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 __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; 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 )); // external-cesium:Cesium var require_Cesium = __commonJS({ "external-cesium:Cesium"(exports, module) { module.exports = Cesium; } }); // node_modules/mersenne-twister/src/mersenne-twister.js var require_mersenne_twister = __commonJS({ "node_modules/mersenne-twister/src/mersenne-twister.js"(exports, module) { var MersenneTwister2 = 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); } }; MersenneTwister2.prototype.init_seed = function(s) { this.mt[0] = s >>> 0; for (this.mti = 1; this.mti < this.N; this.mti++) { var s = this.mt[this.mti - 1] ^ this.mt[this.mti - 1] >>> 30; this.mt[this.mti] = (((s & 4294901760) >>> 16) * 1812433253 << 16) + (s & 65535) * 1812433253 + this.mti; this.mt[this.mti] >>>= 0; } }; MersenneTwister2.prototype.init_by_array = function(init_key, key_length) { var i, j, k; this.init_seed(19650218); i = 1; j = 0; k = this.N > key_length ? this.N : key_length; for (; k; k--) { var s = this.mt[i - 1] ^ this.mt[i - 1] >>> 30; this.mt[i] = (this.mt[i] ^ (((s & 4294901760) >>> 16) * 1664525 << 16) + (s & 65535) * 1664525) + init_key[j] + j; this.mt[i] >>>= 0; i++; j++; if (i >= this.N) { this.mt[0] = this.mt[this.N - 1]; i = 1; } if (j >= key_length) j = 0; } for (k = this.N - 1; k; k--) { var s = this.mt[i - 1] ^ this.mt[i - 1] >>> 30; this.mt[i] = (this.mt[i] ^ (((s & 4294901760) >>> 16) * 1566083941 << 16) + (s & 65535) * 1566083941) - i; this.mt[i] >>>= 0; i++; if (i >= this.N) { this.mt[0] = this.mt[this.N - 1]; i = 1; } } this.mt[0] = 2147483648; }; MersenneTwister2.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; }; MersenneTwister2.prototype.random_int31 = function() { return this.random_int() >>> 1; }; MersenneTwister2.prototype.random_incl = function() { return this.random_int() * (1 / 4294967295); }; MersenneTwister2.prototype.random = function() { return this.random_int() * (1 / 4294967296); }; MersenneTwister2.prototype.random_excl = function() { return (this.random_int() + 0.5) * (1 / 4294967296); }; MersenneTwister2.prototype.random_long = function() { var a = this.random_int() >>> 5, b = this.random_int() >>> 6; return (a * 67108864 + b) * (1 / 9007199254740992); }; module.exports = MersenneTwister2; } }); // node_modules/urijs/src/punycode.js var require_punycode = __commonJS({ "node_modules/urijs/src/punycode.js"(exports, module) { (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, n = initialN, bias = initialBias, basic, j, index, oldi, w, k, digit, t, baseMinusT; basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (j = 0; j < basic; ++j) { if (input.charCodeAt(j) >= 128) { error("not-basic"); } output.push(input.charCodeAt(j)); } for (index = basic > 0 ? basic + 1 : 0; index < inputLength; ) { for (oldi = i, w = 1, k = base; ; k += base) { if (index >= inputLength) { error("invalid-input"); } digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error("overflow"); } i += digit * w; t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (digit < t) { break; } baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error("overflow"); } w *= baseMinusT; } out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); if (floor(i / out) > maxInt - n) { error("overflow"); } n += floor(i / out); i %= out; output.splice(i++, 0, n); } return ucs2encode(output); } function encode(input) { var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], inputLength, handledCPCountPlusOne, baseMinusT, qMinusT; input = ucs2decode(input); inputLength = input.length; n = initialN; delta = 0; bias = initialBias; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 128) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length; if (basicLength) { output.push(delimiter); } while (handledCPCount < inputLength) { for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } } handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error("overflow"); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error("overflow"); } if (currentValue == n) { for (q = delta, k = base; ; k += base) { t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (q < t) { break; } qMinusT = q - t; baseMinusT = base - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(""); } function toUnicode(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); } function toASCII(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? "xn--" + encode(string) : string; }); } punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ "version": "1.3.2", /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see * @memberOf punycode * @type Object */ "ucs2": { "decode": ucs2decode, "encode": ucs2encode }, "decode": decode, "encode": encode, "toASCII": toASCII, "toUnicode": toUnicode }; if (typeof define == "function" && typeof define.amd == "object" && define.amd) { define("punycode", function() { return punycode; }); } else if (freeExports && freeModule) { if (module.exports == freeExports) { freeModule.exports = punycode; } else { for (key in punycode) { punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); } } } else { root.punycode = punycode; } })(exports); } }); // node_modules/urijs/src/IPv6.js var require_IPv6 = __commonJS({ "node_modules/urijs/src/IPv6.js"(exports, module) { (function(root, factory) { "use strict"; if (typeof module === "object" && module.exports) { module.exports = factory(); } else if (typeof define === "function" && define.amd) { define(factory); } else { root.IPv6 = factory(root); } })(exports, function(root) { "use strict"; var _IPv6 = root && root.IPv6; function bestPresentation(address) { var _address = address.toLowerCase(); var segments = _address.split(":"); var length2 = segments.length; var total = 8; if (segments[0] === "" && segments[1] === "" && segments[2] === "") { segments.shift(); segments.shift(); } else if (segments[0] === "" && segments[1] === "") { segments.shift(); } else if (segments[length2 - 1] === "" && segments[length2 - 2] === "") { segments.pop(); } length2 = segments.length; if (segments[length2 - 1].indexOf(".") !== -1) { total = 7; } var pos; for (pos = 0; pos < length2; pos++) { if (segments[pos] === "") { break; } } if (pos < total) { segments.splice(pos, 1, "0000"); while (segments.length < total) { segments.splice(pos, 0, "0000"); } } var _segments; for (var i = 0; i < total; i++) { _segments = segments[i].split(""); for (var j = 0; j < 3; j++) { if (_segments[0] === "0" && _segments.length > 1) { _segments.splice(0, 1); } else { break; } } segments[i] = _segments.join(""); } var best = -1; var _best = 0; var _current = 0; var current = -1; var inzeroes = false; for (i = 0; i < total; i++) { if (inzeroes) { if (segments[i] === "0") { _current += 1; } else { inzeroes = false; if (_current > _best) { best = current; _best = _current; } } } else { if (segments[i] === "0") { inzeroes = true; current = i; _current = 1; } } } if (_current > _best) { best = current; _best = _current; } if (_best > 1) { segments.splice(best, _best, ""); } length2 = segments.length; var result = ""; if (segments[0] === "") { result = ":"; } for (i = 0; i < length2; i++) { result += segments[i]; if (i === length2 - 1) { break; } result += ":"; } if (segments[length2 - 1] === "") { result += ":"; } return result; } function noConflict() { if (root.IPv6 === this) { root.IPv6 = _IPv6; } return this; } return { best: bestPresentation, noConflict }; }); } }); // node_modules/urijs/src/SecondLevelDomains.js var require_SecondLevelDomains = __commonJS({ "node_modules/urijs/src/SecondLevelDomains.js"(exports, module) { (function(root, factory) { "use strict"; if (typeof module === "object" && module.exports) { module.exports = factory(); } else if (typeof define === "function" && define.amd) { define(factory); } else { root.SecondLevelDomains = factory(root); } })(exports, function(root) { "use strict"; var _SecondLevelDomains = root && root.SecondLevelDomains; var SLD = { // list of known Second Level Domains // converted list of SLDs from https://github.com/gavingmiller/second-level-domains // ---- // publicsuffix.org is more current and actually used by a couple of browsers internally. // downside is it also contains domains like "dyndns.org" - which is fine for the security // issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js // ---- list: { "ac": " com gov mil net org ", "ae": " ac co gov mil name net org pro sch ", "af": " com edu gov net org ", "al": " com edu gov mil net org ", "ao": " co ed gv it og pb ", "ar": " com edu gob gov int mil net org tur ", "at": " ac co gv or ", "au": " asn com csiro edu gov id net org ", "ba": " co com edu gov mil net org rs unbi unmo unsa untz unze ", "bb": " biz co com edu gov info net org store tv ", "bh": " biz cc com edu gov info net org ", "bn": " com edu gov net org ", "bo": " com edu gob gov int mil net org tv ", "br": " adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ", "bs": " com edu gov net org ", "bz": " du et om ov rg ", "ca": " ab bc mb nb nf nl ns nt nu on pe qc sk yk ", "ck": " biz co edu gen gov info net org ", "cn": " ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ", "co": " com edu gov mil net nom org ", "cr": " ac c co ed fi go or sa ", "cy": " ac biz com ekloges gov ltd name net org parliament press pro tm ", "do": " art com edu gob gov mil net org sld web ", "dz": " art asso com edu gov net org pol ", "ec": " com edu fin gov info med mil net org pro ", "eg": " com edu eun gov mil name net org sci ", "er": " com edu gov ind mil net org rochest w ", "es": " com edu gob nom org ", "et": " biz com edu gov info name net org ", "fj": " ac biz com info mil name net org pro ", "fk": " ac co gov net nom org ", "fr": " asso com f gouv nom prd presse tm ", "gg": " co net org ", "gh": " com edu gov mil org ", "gn": " ac com gov net org ", "gr": " com edu gov mil net org ", "gt": " com edu gob ind mil net org ", "gu": " com edu gov net org ", "hk": " com edu gov idv net org ", "hu": " 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ", "id": " ac co go mil net or sch web ", "il": " ac co gov idf k12 muni net org ", "in": " ac co edu ernet firm gen gov i ind mil net nic org res ", "iq": " com edu gov i mil net org ", "ir": " ac co dnssec gov i id net org sch ", "it": " edu gov ", "je": " co net org ", "jo": " com edu gov mil name net org sch ", "jp": " ac ad co ed go gr lg ne or ", "ke": " ac co go info me mobi ne or sc ", "kh": " com edu gov mil net org per ", "ki": " biz com de edu gov info mob net org tel ", "km": " asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ", "kn": " edu gov net org ", "kr": " ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ", "kw": " com edu gov net org ", "ky": " com edu gov net org ", "kz": " com edu gov mil net org ", "lb": " com edu gov net org ", "lk": " assn com edu gov grp hotel int ltd net ngo org sch soc web ", "lr": " com edu gov net org ", "lv": " asn com conf edu gov id mil net org ", "ly": " com edu gov id med net org plc sch ", "ma": " ac co gov m net org press ", "mc": " asso tm ", "me": " ac co edu gov its net org priv ", "mg": " com edu gov mil nom org prd tm ", "mk": " com edu gov inf name net org pro ", "ml": " com edu gov net org presse ", "mn": " edu gov org ", "mo": " com edu gov net org ", "mt": " com edu gov net org ", "mv": " aero biz com coop edu gov info int mil museum name net org pro ", "mw": " ac co com coop edu gov int museum net org ", "mx": " com edu gob net org ", "my": " com edu gov mil name net org sch ", "nf": " arts com firm info net other per rec store web ", "ng": " biz com edu gov mil mobi name net org sch ", "ni": " ac co com edu gob mil net nom org ", "np": " com edu gov mil net org ", "nr": " biz com edu gov info net org ", "om": " ac biz co com edu gov med mil museum net org pro sch ", "pe": " com edu gob mil net nom org sld ", "ph": " com edu gov i mil net ngo org ", "pk": " biz com edu fam gob gok gon gop gos gov net org web ", "pl": " art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ", "pr": " ac biz com edu est gov info isla name net org pro prof ", "ps": " com edu gov net org plo sec ", "pw": " belau co ed go ne or ", "ro": " arts com firm info nom nt org rec store tm www ", "rs": " ac co edu gov in org ", "sb": " com edu gov net org ", "sc": " com edu gov net org ", "sh": " co com edu gov net nom org ", "sl": " com edu gov net org ", "st": " co com consulado edu embaixada gov mil net org principe saotome store ", "sv": " com edu gob org red ", "sz": " ac co org ", "tr": " av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ", "tt": " aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ", "tw": " club com ebiz edu game gov idv mil net org ", "mu": " ac co com gov net or org ", "mz": " ac co edu gov org ", "na": " co com ", "nz": " ac co cri geek gen govt health iwi maori mil net org parliament school ", "pa": " abo ac com edu gob ing med net nom org sld ", "pt": " com edu gov int net nome org publ ", "py": " com edu gov mil net org ", "qa": " com edu gov mil net org ", "re": " asso com nom ", "ru": " ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ", "rw": " ac co com edu gouv gov int mil net ", "sa": " com edu gov med net org pub sch ", "sd": " com edu gov info med net org tv ", "se": " a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ", "sg": " com edu gov idn net org per ", "sn": " art com edu gouv org perso univ ", "sy": " com edu gov mil net news org ", "th": " ac co go in mi net or ", "tj": " ac biz co com edu go gov info int mil name net nic org test web ", "tn": " agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ", "tz": " ac co go ne or ", "ua": " biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ", "ug": " ac co go ne or org sc ", "uk": " ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ", "us": " dni fed isa kids nsn ", "uy": " com edu gub mil net org ", "ve": " co com edu gob info mil net org web ", "vi": " co com k12 net org ", "vn": " ac biz com edu gov health info int name net org pro ", "ye": " co com gov ltd me net org plc ", "yu": " ac co edu gov org ", "za": " ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ", "zm": " ac co com edu gov net org sch ", // https://en.wikipedia.org/wiki/CentralNic#Second-level_domains "com": "ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ", "net": "gb jp se uk ", "org": "ae", "de": "com " }, // gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost // in both performance and memory footprint. No initialization required. // http://jsperf.com/uri-js-sld-regex-vs-binary-search/4 // Following methods use lastIndexOf() rather than array.split() in order // to avoid any memory allocations. has: function(domain) { var tldOffset = domain.lastIndexOf("."); if (tldOffset <= 0 || tldOffset >= domain.length - 1) { return false; } var sldOffset = domain.lastIndexOf(".", tldOffset - 1); if (sldOffset <= 0 || sldOffset >= tldOffset - 1) { return false; } var sldList = SLD.list[domain.slice(tldOffset + 1)]; if (!sldList) { return false; } return sldList.indexOf(" " + domain.slice(sldOffset + 1, tldOffset) + " ") >= 0; }, is: function(domain) { var tldOffset = domain.lastIndexOf("."); if (tldOffset <= 0 || tldOffset >= domain.length - 1) { return false; } var sldOffset = domain.lastIndexOf(".", tldOffset - 1); if (sldOffset >= 0) { return false; } var sldList = SLD.list[domain.slice(tldOffset + 1)]; if (!sldList) { return false; } return sldList.indexOf(" " + domain.slice(0, tldOffset) + " ") >= 0; }, get: function(domain) { var tldOffset = domain.lastIndexOf("."); if (tldOffset <= 0 || tldOffset >= domain.length - 1) { return null; } var sldOffset = domain.lastIndexOf(".", tldOffset - 1); if (sldOffset <= 0 || sldOffset >= tldOffset - 1) { return null; } var sldList = SLD.list[domain.slice(tldOffset + 1)]; if (!sldList) { return null; } if (sldList.indexOf(" " + domain.slice(sldOffset + 1, tldOffset) + " ") < 0) { return null; } return domain.slice(sldOffset + 1); }, noConflict: function() { if (root.SecondLevelDomains === this) { root.SecondLevelDomains = _SecondLevelDomains; } return this; } }; return SLD; }); } }); // node_modules/urijs/src/URI.js var require_URI = __commonJS({ "node_modules/urijs/src/URI.js"(exports, module) { (function(root, factory) { "use strict"; if (typeof module === "object" && module.exports) { module.exports = factory(require_punycode(), require_IPv6(), require_SecondLevelDomains()); } else if (typeof define === "function" && define.amd) { define(["./punycode", "./IPv6", "./SecondLevelDomains"], factory); } else { root.URI = factory(root.punycode, root.IPv6, root.SecondLevelDomains, root); } })(exports, function(punycode, IPv6, SLD, root) { "use strict"; var _URI = root && root.URI; function URI(url, base) { var _urlSupplied = arguments.length >= 1; var _baseSupplied = arguments.length >= 2; if (!(this instanceof URI)) { if (_urlSupplied) { if (_baseSupplied) { return new URI(url, base); } return new URI(url); } return new URI(); } if (url === void 0) { if (_urlSupplied) { throw new TypeError("undefined is not a valid argument for URI"); } if (typeof location !== "undefined") { url = location.href + ""; } else { url = ""; } } if (url === null) { if (_urlSupplied) { throw new TypeError("null is not a valid argument for URI"); } } this.href(url); if (base !== void 0) { return this.absoluteTo(base); } return this; } function isInteger(value) { return /^[0-9]+$/.test(value); } URI.version = "1.19.11"; var p = URI.prototype; var hasOwn = Object.prototype.hasOwnProperty; function escapeRegEx(string) { return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, "\\$1"); } function getType(value) { if (value === void 0) { return "Undefined"; } return String(Object.prototype.toString.call(value)).slice(8, -1); } function isArray(obj) { return getType(obj) === "Array"; } function filterArrayValues(data, value) { var lookup = {}; var i, length2; if (getType(value) === "RegExp") { lookup = null; } else if (isArray(value)) { for (i = 0, length2 = value.length; i < length2; i++) { lookup[value[i]] = true; } } else { lookup[value] = true; } for (i = 0, length2 = data.length; i < length2; i++) { var _match = lookup && lookup[data[i]] !== void 0 || !lookup && value.test(data[i]); if (_match) { data.splice(i, 1); length2--; i--; } } return data; } function arrayContains(list, value) { var i, length2; if (isArray(value)) { for (i = 0, length2 = value.length; i < length2; i++) { if (!arrayContains(list, value[i])) { return false; } } return true; } var _type = getType(value); for (i = 0, length2 = list.length; i < length2; i++) { if (_type === "RegExp") { if (typeof list[i] === "string" && list[i].match(value)) { return true; } } else if (list[i] === value) { return true; } } return false; } function arraysEqual(one, two) { if (!isArray(one) || !isArray(two)) { return false; } if (one.length !== two.length) { return false; } one.sort(); two.sort(); for (var i = 0, l = one.length; i < l; i++) { if (one[i] !== two[i]) { return false; } } return true; } function trimSlashes(text) { var trim_expression = /^\/+|\/+$/g; return text.replace(trim_expression, ""); } URI._parts = function() { return { protocol: null, username: null, password: null, hostname: null, urn: null, port: null, path: null, query: null, fragment: null, // state preventInvalidHostname: URI.preventInvalidHostname, duplicateQueryParameters: URI.duplicateQueryParameters, escapeQuerySpace: URI.escapeQuerySpace }; }; URI.preventInvalidHostname = false; URI.duplicateQueryParameters = false; URI.escapeQuerySpace = true; URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i; URI.idn_expression = /[^a-z0-9\._-]/i; URI.punycode_expression = /(xn--)/i; URI.ip4_expression = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; URI.ip6_expression = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/; URI.find_uri_expression = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig; URI.findUri = { // valid "scheme://" or "www." start: /\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi, // everything up to the next whitespace end: /[\s\r\n]|$/, // trim trailing punctuation captured by end RegExp trim: /[`!()\[\]{};:'".,<>?«»“”„‘’]+$/, // balanced parens inclusion (), [], {}, <> parens: /(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g }; URI.leading_whitespace_expression = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/; URI.ascii_tab_whitespace = /[\u0009\u000A\u000D]+/g; URI.defaultPorts = { http: "80", https: "443", ftp: "21", gopher: "70", ws: "80", wss: "443" }; URI.hostProtocols = [ "http", "https" ]; URI.invalid_hostname_characters = /[^a-zA-Z0-9\.\-:_]/; URI.domAttributes = { "a": "href", "blockquote": "cite", "link": "href", "base": "href", "script": "src", "form": "action", "img": "src", "area": "href", "iframe": "src", "embed": "src", "source": "src", "track": "src", "input": "src", // but only if type="image" "audio": "src", "video": "src" }; URI.getDomAttribute = function(node) { if (!node || !node.nodeName) { return void 0; } var nodeName = node.nodeName.toLowerCase(); if (nodeName === "input" && node.type !== "image") { return void 0; } return URI.domAttributes[nodeName]; }; function escapeForDumbFirefox36(value) { return escape(value); } function strictEncodeURIComponent(string) { return encodeURIComponent(string).replace(/[!'()*]/g, escapeForDumbFirefox36).replace(/\*/g, "%2A"); } URI.encode = strictEncodeURIComponent; URI.decode = decodeURIComponent; URI.iso8859 = function() { URI.encode = escape; URI.decode = unescape; }; URI.unicode = function() { URI.encode = strictEncodeURIComponent; URI.decode = decodeURIComponent; }; URI.characters = { pathname: { encode: { // RFC3986 2.1: For consistency, URI producers and normalizers should // use uppercase hexadecimal digits for all percent-encodings. expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig, map: { // -._~!'()* "%24": "$", "%26": "&", "%2B": "+", "%2C": ",", "%3B": ";", "%3D": "=", "%3A": ":", "%40": "@" } }, decode: { expression: /[\/\?#]/g, map: { "/": "%2F", "?": "%3F", "#": "%23" } } }, reserved: { encode: { // RFC3986 2.1: For consistency, URI producers and normalizers should // use uppercase hexadecimal digits for all percent-encodings. expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig, map: { // gen-delims "%3A": ":", "%2F": "/", "%3F": "?", "%23": "#", "%5B": "[", "%5D": "]", "%40": "@", // sub-delims "%21": "!", "%24": "$", "%26": "&", "%27": "'", "%28": "(", "%29": ")", "%2A": "*", "%2B": "+", "%2C": ",", "%3B": ";", "%3D": "=" } } }, urnpath: { // The characters under `encode` are the characters called out by RFC 2141 as being acceptable // for usage in a URN. RFC2141 also calls out "-", ".", and "_" as acceptable characters, but // these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also // note that the colon character is not featured in the encoding map; this is because URI.js // gives the colons in URNs semantic meaning as the delimiters of path segements, and so it // should not appear unencoded in a segment itself. // See also the note above about RFC3986 and capitalalized hex digits. encode: { expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig, map: { "%21": "!", "%24": "$", "%27": "'", "%28": "(", "%29": ")", "%2A": "*", "%2B": "+", "%2C": ",", "%3B": ";", "%3D": "=", "%40": "@" } }, // These characters are the characters called out by RFC2141 as "reserved" characters that // should never appear in a URN, plus the colon character (see note above). decode: { expression: /[\/\?#:]/g, map: { "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" } } } }; URI.encodeQuery = function(string, escapeQuerySpace) { var escaped = URI.encode(string + ""); if (escapeQuerySpace === void 0) { escapeQuerySpace = URI.escapeQuerySpace; } return escapeQuerySpace ? escaped.replace(/%20/g, "+") : escaped; }; URI.decodeQuery = function(string, escapeQuerySpace) { string += ""; if (escapeQuerySpace === void 0) { escapeQuerySpace = URI.escapeQuerySpace; } try { return URI.decode(escapeQuerySpace ? string.replace(/\+/g, "%20") : string); } catch (e) { return string; } }; var _parts = { "encode": "encode", "decode": "decode" }; var _part; var generateAccessor = function(_group, _part2) { return function(string) { try { return URI[_part2](string + "").replace(URI.characters[_group][_part2].expression, function(c) { return URI.characters[_group][_part2].map[c]; }); } catch (e) { return string; } }; }; for (_part in _parts) { URI[_part + "PathSegment"] = generateAccessor("pathname", _parts[_part]); URI[_part + "UrnPathSegment"] = generateAccessor("urnpath", _parts[_part]); } var generateSegmentedPathFunction = function(_sep, _codingFuncName, _innerCodingFuncName) { return function(string) { var actualCodingFunc; if (!_innerCodingFuncName) { actualCodingFunc = URI[_codingFuncName]; } else { actualCodingFunc = function(string2) { return URI[_codingFuncName](URI[_innerCodingFuncName](string2)); }; } var segments = (string + "").split(_sep); for (var i = 0, length2 = segments.length; i < length2; i++) { segments[i] = actualCodingFunc(segments[i]); } return segments.join(_sep); }; }; URI.decodePath = generateSegmentedPathFunction("/", "decodePathSegment"); URI.decodeUrnPath = generateSegmentedPathFunction(":", "decodeUrnPathSegment"); URI.recodePath = generateSegmentedPathFunction("/", "encodePathSegment", "decode"); URI.recodeUrnPath = generateSegmentedPathFunction(":", "encodeUrnPathSegment", "decode"); URI.encodeReserved = generateAccessor("reserved", "encode"); URI.parse = function(string, parts) { var pos; if (!parts) { parts = { preventInvalidHostname: URI.preventInvalidHostname }; } string = string.replace(URI.leading_whitespace_expression, ""); string = string.replace(URI.ascii_tab_whitespace, ""); pos = string.indexOf("#"); if (pos > -1) { parts.fragment = string.substring(pos + 1) || null; string = string.substring(0, pos); } pos = string.indexOf("?"); if (pos > -1) { parts.query = string.substring(pos + 1) || null; string = string.substring(0, pos); } string = string.replace(/^(https?|ftp|wss?)?:+[/\\]*/i, "$1://"); string = string.replace(/^[/\\]{2,}/i, "//"); if (string.substring(0, 2) === "//") { parts.protocol = null; string = string.substring(2); string = URI.parseAuthority(string, parts); } else { pos = string.indexOf(":"); if (pos > -1) { parts.protocol = string.substring(0, pos) || null; if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) { parts.protocol = void 0; } else if (string.substring(pos + 1, pos + 3).replace(/\\/g, "/") === "//") { string = string.substring(pos + 3); string = URI.parseAuthority(string, parts); } else { string = string.substring(pos + 1); parts.urn = true; } } } parts.path = string; return parts; }; URI.parseHost = function(string, parts) { if (!string) { string = ""; } string = string.replace(/\\/g, "/"); var pos = string.indexOf("/"); var bracketPos; var t; if (pos === -1) { pos = string.length; } if (string.charAt(0) === "[") { bracketPos = string.indexOf("]"); parts.hostname = string.substring(1, bracketPos) || null; parts.port = string.substring(bracketPos + 2, pos) || null; if (parts.port === "/") { parts.port = null; } } else { var firstColon = string.indexOf(":"); var firstSlash = string.indexOf("/"); var nextColon = string.indexOf(":", firstColon + 1); if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) { parts.hostname = string.substring(0, pos) || null; parts.port = null; } else { t = string.substring(0, pos).split(":"); parts.hostname = t[0] || null; parts.port = t[1] || null; } } if (parts.hostname && string.substring(pos).charAt(0) !== "/") { pos++; string = "/" + string; } if (parts.preventInvalidHostname) { URI.ensureValidHostname(parts.hostname, parts.protocol); } if (parts.port) { URI.ensureValidPort(parts.port); } return string.substring(pos) || "/"; }; URI.parseAuthority = function(string, parts) { string = URI.parseUserinfo(string, parts); return URI.parseHost(string, parts); }; URI.parseUserinfo = function(string, parts) { var _string = string; var firstBackSlash = string.indexOf("\\"); if (firstBackSlash !== -1) { string = string.replace(/\\/g, "/"); } var firstSlash = string.indexOf("/"); var pos = string.lastIndexOf("@", firstSlash > -1 ? firstSlash : string.length - 1); var t; if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) { t = string.substring(0, pos).split(":"); parts.username = t[0] ? URI.decode(t[0]) : null; t.shift(); parts.password = t[0] ? URI.decode(t.join(":")) : null; string = _string.substring(pos + 1); } else { parts.username = null; parts.password = null; } return string; }; URI.parseQuery = function(string, escapeQuerySpace) { if (!string) { return {}; } string = string.replace(/&+/g, "&").replace(/^\?*&*|&+$/g, ""); if (!string) { return {}; } var items = {}; var splits = string.split("&"); var length2 = splits.length; var v, name, value; for (var i = 0; i < length2; i++) { v = splits[i].split("="); name = URI.decodeQuery(v.shift(), escapeQuerySpace); value = v.length ? URI.decodeQuery(v.join("="), escapeQuerySpace) : null; if (name === "__proto__") { continue; } else if (hasOwn.call(items, name)) { if (typeof items[name] === "string" || items[name] === null) { items[name] = [items[name]]; } items[name].push(value); } else { items[name] = value; } } return items; }; URI.build = function(parts) { var t = ""; var requireAbsolutePath = false; if (parts.protocol) { t += parts.protocol + ":"; } if (!parts.urn && (t || parts.hostname)) { t += "//"; requireAbsolutePath = true; } t += URI.buildAuthority(parts) || ""; if (typeof parts.path === "string") { if (parts.path.charAt(0) !== "/" && requireAbsolutePath) { t += "/"; } t += parts.path; } if (typeof parts.query === "string" && parts.query) { t += "?" + parts.query; } if (typeof parts.fragment === "string" && parts.fragment) { t += "#" + parts.fragment; } return t; }; URI.buildHost = function(parts) { var t = ""; if (!parts.hostname) { return ""; } else if (URI.ip6_expression.test(parts.hostname)) { t += "[" + parts.hostname + "]"; } else { t += parts.hostname; } if (parts.port) { t += ":" + parts.port; } return t; }; URI.buildAuthority = function(parts) { return URI.buildUserinfo(parts) + URI.buildHost(parts); }; URI.buildUserinfo = function(parts) { var t = ""; if (parts.username) { t += URI.encode(parts.username); } if (parts.password) { t += ":" + URI.encode(parts.password); } if (t) { t += "@"; } return t; }; URI.buildQuery = function(data, duplicateQueryParameters, escapeQuerySpace) { var t = ""; var unique, key, i, length2; for (key in data) { if (key === "__proto__") { continue; } else if (hasOwn.call(data, key)) { if (isArray(data[key])) { unique = {}; for (i = 0, length2 = data[key].length; i < length2; i++) { if (data[key][i] !== void 0 && unique[data[key][i] + ""] === void 0) { t += "&" + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace); if (duplicateQueryParameters !== true) { unique[data[key][i] + ""] = true; } } } } else if (data[key] !== void 0) { t += "&" + URI.buildQueryParameter(key, data[key], escapeQuerySpace); } } } return t.substring(1); }; URI.buildQueryParameter = function(name, value, escapeQuerySpace) { return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? "=" + URI.encodeQuery(value, escapeQuerySpace) : ""); }; URI.addQuery = function(data, name, value) { if (typeof name === "object") { for (var key in name) { if (hasOwn.call(name, key)) { URI.addQuery(data, key, name[key]); } } } else if (typeof name === "string") { if (data[name] === void 0) { data[name] = value; return; } else if (typeof data[name] === "string") { data[name] = [data[name]]; } if (!isArray(value)) { value = [value]; } data[name] = (data[name] || []).concat(value); } else { throw new TypeError("URI.addQuery() accepts an object, string as the name parameter"); } }; URI.setQuery = function(data, name, value) { if (typeof name === "object") { for (var key in name) { if (hasOwn.call(name, key)) { URI.setQuery(data, key, name[key]); } } } else if (typeof name === "string") { data[name] = value === void 0 ? null : value; } else { throw new TypeError("URI.setQuery() accepts an object, string as the name parameter"); } }; URI.removeQuery = function(data, name, value) { var i, length2, key; if (isArray(name)) { for (i = 0, length2 = name.length; i < length2; i++) { data[name[i]] = void 0; } } else if (getType(name) === "RegExp") { for (key in data) { if (name.test(key)) { data[key] = void 0; } } } else if (typeof name === "object") { for (key in name) { if (hasOwn.call(name, key)) { URI.removeQuery(data, key, name[key]); } } } else if (typeof name === "string") { if (value !== void 0) { if (getType(value) === "RegExp") { if (!isArray(data[name]) && value.test(data[name])) { data[name] = void 0; } else { data[name] = filterArrayValues(data[name], value); } } else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) { data[name] = void 0; } else if (isArray(data[name])) { data[name] = filterArrayValues(data[name], value); } } else { data[name] = void 0; } } else { throw new TypeError("URI.removeQuery() accepts an object, string, RegExp as the first parameter"); } }; URI.hasQuery = function(data, name, value, withinArray) { switch (getType(name)) { case "String": break; case "RegExp": for (var key in data) { if (hasOwn.call(data, key)) { if (name.test(key) && (value === void 0 || URI.hasQuery(data, key, value))) { return true; } } } return false; case "Object": for (var _key in name) { if (hasOwn.call(name, _key)) { if (!URI.hasQuery(data, _key, name[_key])) { return false; } } } return true; default: throw new TypeError("URI.hasQuery() accepts a string, regular expression or object as the name parameter"); } switch (getType(value)) { case "Undefined": return name in data; case "Boolean": var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]); return value === _booly; case "Function": return !!value(data[name], name, data); case "Array": if (!isArray(data[name])) { return false; } var op = withinArray ? arrayContains : arraysEqual; return op(data[name], value); case "RegExp": if (!isArray(data[name])) { return Boolean(data[name] && data[name].match(value)); } if (!withinArray) { return false; } return arrayContains(data[name], value); case "Number": value = String(value); case "String": if (!isArray(data[name])) { return data[name] === value; } if (!withinArray) { return false; } return arrayContains(data[name], value); default: throw new TypeError("URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter"); } }; URI.joinPaths = function() { var input = []; var segments = []; var nonEmptySegments = 0; for (var i = 0; i < arguments.length; i++) { var url = new URI(arguments[i]); input.push(url); var _segments = url.segment(); for (var s = 0; s < _segments.length; s++) { if (typeof _segments[s] === "string") { segments.push(_segments[s]); } if (_segments[s]) { nonEmptySegments++; } } } if (!segments.length || !nonEmptySegments) { return new URI(""); } var uri = new URI("").segment(segments); if (input[0].path() === "" || input[0].path().slice(0, 1) === "/") { uri.path("/" + uri.path()); } return uri.normalize(); }; URI.commonPath = function(one, two) { var length2 = Math.min(one.length, two.length); var pos; for (pos = 0; pos < length2; pos++) { if (one.charAt(pos) !== two.charAt(pos)) { pos--; break; } } if (pos < 1) { return one.charAt(0) === two.charAt(0) && one.charAt(0) === "/" ? "/" : ""; } if (one.charAt(pos) !== "/" || two.charAt(pos) !== "/") { pos = one.substring(0, pos).lastIndexOf("/"); } return one.substring(0, pos + 1); }; URI.withinString = function(string, callback, options) { options || (options = {}); var _start = options.start || URI.findUri.start; var _end = options.end || URI.findUri.end; var _trim = options.trim || URI.findUri.trim; var _parens = options.parens || URI.findUri.parens; var _attributeOpen = /[a-z0-9-]=["']?$/i; _start.lastIndex = 0; while (true) { var match = _start.exec(string); if (!match) { break; } var start = match.index; if (options.ignoreHtml) { var attributeOpen = string.slice(Math.max(start - 3, 0), start); if (attributeOpen && _attributeOpen.test(attributeOpen)) { continue; } } var end = start + string.slice(start).search(_end); var slice = string.slice(start, end); var parensEnd = -1; while (true) { var parensMatch = _parens.exec(slice); if (!parensMatch) { break; } var parensMatchEnd = parensMatch.index + parensMatch[0].length; parensEnd = Math.max(parensEnd, parensMatchEnd); } if (parensEnd > -1) { slice = slice.slice(0, parensEnd) + slice.slice(parensEnd).replace(_trim, ""); } else { slice = slice.replace(_trim, ""); } if (slice.length <= match[0].length) { continue; } if (options.ignore && options.ignore.test(slice)) { continue; } end = start + slice.length; var result = callback(slice, start, end, string); if (result === void 0) { _start.lastIndex = end; continue; } result = String(result); string = string.slice(0, start) + result + string.slice(end); _start.lastIndex = start + result.length; } _start.lastIndex = 0; return string; }; URI.ensureValidHostname = function(v, protocol) { var hasHostname = !!v; var hasProtocol = !!protocol; var rejectEmptyHostname = false; if (hasProtocol) { rejectEmptyHostname = arrayContains(URI.hostProtocols, protocol); } if (rejectEmptyHostname && !hasHostname) { throw new TypeError("Hostname cannot be empty, if protocol is " + protocol); } else if (v && v.match(URI.invalid_hostname_characters)) { if (!punycode) { throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available'); } if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) { throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_]'); } } }; URI.ensureValidPort = function(v) { if (!v) { return; } var port = Number(v); if (isInteger(port) && port > 0 && port < 65536) { return; } throw new TypeError('Port "' + v + '" is not a valid port'); }; URI.noConflict = function(removeAll) { if (removeAll) { var unconflicted = { URI: this.noConflict() }; if (root.URITemplate && typeof root.URITemplate.noConflict === "function") { unconflicted.URITemplate = root.URITemplate.noConflict(); } if (root.IPv6 && typeof root.IPv6.noConflict === "function") { unconflicted.IPv6 = root.IPv6.noConflict(); } if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === "function") { unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict(); } return unconflicted; } else if (root.URI === this) { root.URI = _URI; } return this; }; p.build = function(deferBuild) { if (deferBuild === true) { this._deferred_build = true; } else if (deferBuild === void 0 || this._deferred_build) { this._string = URI.build(this._parts); this._deferred_build = false; } return this; }; p.clone = function() { return new URI(this); }; p.valueOf = p.toString = function() { return this.build(false)._string; }; function generateSimpleAccessor(_part2) { return function(v, build) { if (v === void 0) { return this._parts[_part2] || ""; } else { this._parts[_part2] = v || null; this.build(!build); return this; } }; } function generatePrefixAccessor(_part2, _key) { return function(v, build) { if (v === void 0) { return this._parts[_part2] || ""; } else { if (v !== null) { v = v + ""; if (v.charAt(0) === _key) { v = v.substring(1); } } this._parts[_part2] = v; this.build(!build); return this; } }; } p.protocol = generateSimpleAccessor("protocol"); p.username = generateSimpleAccessor("username"); p.password = generateSimpleAccessor("password"); p.hostname = generateSimpleAccessor("hostname"); p.port = generateSimpleAccessor("port"); p.query = generatePrefixAccessor("query", "?"); p.fragment = generatePrefixAccessor("fragment", "#"); p.search = function(v, build) { var t = this.query(v, build); return typeof t === "string" && t.length ? "?" + t : t; }; p.hash = function(v, build) { var t = this.fragment(v, build); return typeof t === "string" && t.length ? "#" + t : t; }; p.pathname = function(v, build) { if (v === void 0 || v === true) { var res = this._parts.path || (this._parts.hostname ? "/" : ""); return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res; } else { if (this._parts.urn) { this._parts.path = v ? URI.recodeUrnPath(v) : ""; } else { this._parts.path = v ? URI.recodePath(v) : "/"; } this.build(!build); return this; } }; p.path = p.pathname; p.href = function(href, build) { var key; if (href === void 0) { return this.toString(); } this._string = ""; this._parts = URI._parts(); var _URI2 = href instanceof URI; var _object = typeof href === "object" && (href.hostname || href.path || href.pathname); if (href.nodeName) { var attribute = URI.getDomAttribute(href); href = href[attribute] || ""; _object = false; } if (!_URI2 && _object && href.pathname !== void 0) { href = href.toString(); } if (typeof href === "string" || href instanceof String) { this._parts = URI.parse(String(href), this._parts); } else if (_URI2 || _object) { var src = _URI2 ? href._parts : href; for (key in src) { if (key === "query") { continue; } if (hasOwn.call(this._parts, key)) { this._parts[key] = src[key]; } } if (src.query) { this.query(src.query, false); } } else { throw new TypeError("invalid input"); } this.build(!build); return this; }; p.is = function(what) { var ip = false; var ip4 = false; var ip6 = false; var name = false; var sld = false; var idn = false; var punycode2 = false; var relative = !this._parts.urn; if (this._parts.hostname) { relative = false; ip4 = URI.ip4_expression.test(this._parts.hostname); ip6 = URI.ip6_expression.test(this._parts.hostname); ip = ip4 || ip6; name = !ip; sld = name && SLD && SLD.has(this._parts.hostname); idn = name && URI.idn_expression.test(this._parts.hostname); punycode2 = name && URI.punycode_expression.test(this._parts.hostname); } switch (what.toLowerCase()) { case "relative": return relative; case "absolute": return !relative; case "domain": case "name": return name; case "sld": return sld; case "ip": return ip; case "ip4": case "ipv4": case "inet4": return ip4; case "ip6": case "ipv6": case "inet6": return ip6; case "idn": return idn; case "url": return !this._parts.urn; case "urn": return !!this._parts.urn; case "punycode": return punycode2; } return null; }; var _protocol = p.protocol; var _port = p.port; var _hostname = p.hostname; p.protocol = function(v, build) { if (v) { v = v.replace(/:(\/\/)?$/, ""); if (!v.match(URI.protocol_expression)) { throw new TypeError('Protocol "' + v + `" contains characters other than [A-Z0-9.+-] or doesn't start with [A-Z]`); } } return _protocol.call(this, v, build); }; p.scheme = p.protocol; p.port = function(v, build) { if (this._parts.urn) { return v === void 0 ? "" : this; } if (v !== void 0) { if (v === 0) { v = null; } if (v) { v += ""; if (v.charAt(0) === ":") { v = v.substring(1); } URI.ensureValidPort(v); } } return _port.call(this, v, build); }; p.hostname = function(v, build) { if (this._parts.urn) { return v === void 0 ? "" : this; } if (v !== void 0) { var x = { preventInvalidHostname: this._parts.preventInvalidHostname }; var res = URI.parseHost(v, x); if (res !== "/") { throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); } v = x.hostname; if (this._parts.preventInvalidHostname) { URI.ensureValidHostname(v, this._parts.protocol); } } return _hostname.call(this, v, build); }; p.origin = function(v, build) { if (this._parts.urn) { return v === void 0 ? "" : this; } if (v === void 0) { var protocol = this.protocol(); var authority = this.authority(); if (!authority) { return ""; } return (protocol ? protocol + "://" : "") + this.authority(); } else { var origin = URI(v); this.protocol(origin.protocol()).authority(origin.authority()).build(!build); return this; } }; p.host = function(v, build) { if (this._parts.urn) { return v === void 0 ? "" : this; } if (v === void 0) { return this._parts.hostname ? URI.buildHost(this._parts) : ""; } else { var res = URI.parseHost(v, this._parts); if (res !== "/") { throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); } this.build(!build); return this; } }; p.authority = function(v, build) { if (this._parts.urn) { return v === void 0 ? "" : this; } if (v === void 0) { return this._parts.hostname ? URI.buildAuthority(this._parts) : ""; } else { var res = URI.parseAuthority(v, this._parts); if (res !== "/") { throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); } this.build(!build); return this; } }; p.userinfo = function(v, build) { if (this._parts.urn) { return v === void 0 ? "" : this; } if (v === void 0) { var t = URI.buildUserinfo(this._parts); return t ? t.substring(0, t.length - 1) : t; } else { if (v[v.length - 1] !== "@") { v += "@"; } URI.parseUserinfo(v, this._parts); this.build(!build); return this; } }; p.resource = function(v, build) { var parts; if (v === void 0) { return this.path() + this.search() + this.hash(); } parts = URI.parse(v); this._parts.path = parts.path; this._parts.query = parts.query; this._parts.fragment = parts.fragment; this.build(!build); return this; }; p.subdomain = function(v, build) { if (this._parts.urn) { return v === void 0 ? "" : this; } if (v === void 0) { if (!this._parts.hostname || this.is("IP")) { return ""; } var end = this._parts.hostname.length - this.domain().length - 1; return this._parts.hostname.substring(0, end) || ""; } else { var e = this._parts.hostname.length - this.domain().length; var sub = this._parts.hostname.substring(0, e); var replace = new RegExp("^" + escapeRegEx(sub)); if (v && v.charAt(v.length - 1) !== ".") { v += "."; } if (v.indexOf(":") !== -1) { throw new TypeError("Domains cannot contain colons"); } if (v) { URI.ensureValidHostname(v, this._parts.protocol); } this._parts.hostname = this._parts.hostname.replace(replace, v); this.build(!build); return this; } }; p.domain = function(v, build) { if (this._parts.urn) { return v === void 0 ? "" : this; } if (typeof v === "boolean") { build = v; v = void 0; } if (v === void 0) { if (!this._parts.hostname || this.is("IP")) { return ""; } var t = this._parts.hostname.match(/\./g); if (t && t.length < 2) { return this._parts.hostname; } var end = this._parts.hostname.length - this.tld(build).length - 1; end = this._parts.hostname.lastIndexOf(".", end - 1) + 1; return this._parts.hostname.substring(end) || ""; } else { if (!v) { throw new TypeError("cannot set domain empty"); } if (v.indexOf(":") !== -1) { throw new TypeError("Domains cannot contain colons"); } URI.ensureValidHostname(v, this._parts.protocol); if (!this._parts.hostname || this.is("IP")) { this._parts.hostname = v; } else { var replace = new RegExp(escapeRegEx(this.domain()) + "$"); this._parts.hostname = this._parts.hostname.replace(replace, v); } this.build(!build); return this; } }; p.tld = function(v, build) { if (this._parts.urn) { return v === void 0 ? "" : this; } if (typeof v === "boolean") { build = v; v = void 0; } if (v === void 0) { if (!this._parts.hostname || this.is("IP")) { return ""; } var pos = this._parts.hostname.lastIndexOf("."); var tld = this._parts.hostname.substring(pos + 1); if (build !== true && SLD && SLD.list[tld.toLowerCase()]) { return SLD.get(this._parts.hostname) || tld; } return tld; } else { var replace; if (!v) { throw new TypeError("cannot set TLD empty"); } else if (v.match(/[^a-zA-Z0-9-]/)) { if (SLD && SLD.is(v)) { replace = new RegExp(escapeRegEx(this.tld()) + "$"); this._parts.hostname = this._parts.hostname.replace(replace, v); } else { throw new TypeError('TLD "' + v + '" contains characters other than [A-Z0-9]'); } } else if (!this._parts.hostname || this.is("IP")) { throw new ReferenceError("cannot set TLD on non-domain host"); } else { replace = new RegExp(escapeRegEx(this.tld()) + "$"); this._parts.hostname = this._parts.hostname.replace(replace, v); } this.build(!build); return this; } }; p.directory = function(v, build) { if (this._parts.urn) { return v === void 0 ? "" : this; } if (v === void 0 || v === true) { if (!this._parts.path && !this._parts.hostname) { return ""; } if (this._parts.path === "/") { return "/"; } var end = this._parts.path.length - this.filename().length - 1; var res = this._parts.path.substring(0, end) || (this._parts.hostname ? "/" : ""); return v ? URI.decodePath(res) : res; } else { var e = this._parts.path.length - this.filename().length; var directory = this._parts.path.substring(0, e); var replace = new RegExp("^" + escapeRegEx(directory)); if (!this.is("relative")) { if (!v) { v = "/"; } if (v.charAt(0) !== "/") { v = "/" + v; } } if (v && v.charAt(v.length - 1) !== "/") { v += "/"; } v = URI.recodePath(v); this._parts.path = this._parts.path.replace(replace, v); this.build(!build); return this; } }; p.filename = function(v, build) { if (this._parts.urn) { return v === void 0 ? "" : this; } if (typeof v !== "string") { if (!this._parts.path || this._parts.path === "/") { return ""; } var pos = this._parts.path.lastIndexOf("/"); var res = this._parts.path.substring(pos + 1); return v ? URI.decodePathSegment(res) : res; } else { var mutatedDirectory = false; if (v.charAt(0) === "/") { v = v.substring(1); } if (v.match(/\.?\//)) { mutatedDirectory = true; } var replace = new RegExp(escapeRegEx(this.filename()) + "$"); v = URI.recodePath(v); this._parts.path = this._parts.path.replace(replace, v); if (mutatedDirectory) { this.normalizePath(build); } else { this.build(!build); } return this; } }; p.suffix = function(v, build) { if (this._parts.urn) { return v === void 0 ? "" : this; } if (v === void 0 || v === true) { if (!this._parts.path || this._parts.path === "/") { return ""; } var filename = this.filename(); var pos = filename.lastIndexOf("."); var s, res; if (pos === -1) { return ""; } s = filename.substring(pos + 1); res = /^[a-z0-9%]+$/i.test(s) ? s : ""; return v ? URI.decodePathSegment(res) : res; } else { if (v.charAt(0) === ".") { v = v.substring(1); } var suffix = this.suffix(); var replace; if (!suffix) { if (!v) { return this; } this._parts.path += "." + URI.recodePath(v); } else if (!v) { replace = new RegExp(escapeRegEx("." + suffix) + "$"); } else { replace = new RegExp(escapeRegEx(suffix) + "$"); } if (replace) { v = URI.recodePath(v); this._parts.path = this._parts.path.replace(replace, v); } this.build(!build); return this; } }; p.segment = function(segment, v, build) { var separator = this._parts.urn ? ":" : "/"; var path = this.path(); var absolute = path.substring(0, 1) === "/"; var segments = path.split(separator); if (segment !== void 0 && typeof segment !== "number") { build = v; v = segment; segment = void 0; } if (segment !== void 0 && typeof segment !== "number") { throw new Error('Bad segment "' + segment + '", must be 0-based integer'); } if (absolute) { segments.shift(); } if (segment < 0) { segment = Math.max(segments.length + segment, 0); } if (v === void 0) { return segment === void 0 ? segments : segments[segment]; } else if (segment === null || segments[segment] === void 0) { if (isArray(v)) { segments = []; for (var i = 0, l = v.length; i < l; i++) { if (!v[i].length && (!segments.length || !segments[segments.length - 1].length)) { continue; } if (segments.length && !segments[segments.length - 1].length) { segments.pop(); } segments.push(trimSlashes(v[i])); } } else if (v || typeof v === "string") { v = trimSlashes(v); if (segments[segments.length - 1] === "") { segments[segments.length - 1] = v; } else { segments.push(v); } } } else { if (v) { segments[segment] = trimSlashes(v); } else { segments.splice(segment, 1); } } if (absolute) { segments.unshift(""); } return this.path(segments.join(separator), build); }; p.segmentCoded = function(segment, v, build) { var segments, i, l; if (typeof segment !== "number") { build = v; v = segment; segment = void 0; } if (v === void 0) { segments = this.segment(segment, v, build); if (!isArray(segments)) { segments = segments !== void 0 ? URI.decode(segments) : void 0; } else { for (i = 0, l = segments.length; i < l; i++) { segments[i] = URI.decode(segments[i]); } } return segments; } if (!isArray(v)) { v = typeof v === "string" || v instanceof String ? URI.encode(v) : v; } else { for (i = 0, l = v.length; i < l; i++) { v[i] = URI.encode(v[i]); } } return this.segment(segment, v, build); }; var q = p.query; p.query = function(v, build) { if (v === true) { return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); } else if (typeof v === "function") { var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); var result = v.call(this, data); this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); this.build(!build); return this; } else if (v !== void 0 && typeof v !== "string") { this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); this.build(!build); return this; } else { return q.call(this, v, build); } }; p.setQuery = function(name, value, build) { var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); if (typeof name === "string" || name instanceof String) { data[name] = value !== void 0 ? value : null; } else if (typeof name === "object") { for (var key in name) { if (hasOwn.call(name, key)) { data[key] = name[key]; } } } else { throw new TypeError("URI.addQuery() accepts an object, string as the name parameter"); } this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); if (typeof name !== "string") { build = value; } this.build(!build); return this; }; p.addQuery = function(name, value, build) { var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); URI.addQuery(data, name, value === void 0 ? null : value); this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); if (typeof name !== "string") { build = value; } this.build(!build); return this; }; p.removeQuery = function(name, value, build) { var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); URI.removeQuery(data, name, value); this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); if (typeof name !== "string") { build = value; } this.build(!build); return this; }; p.hasQuery = function(name, value, withinArray) { var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); return URI.hasQuery(data, name, value, withinArray); }; p.setSearch = p.setQuery; p.addSearch = p.addQuery; p.removeSearch = p.removeQuery; p.hasSearch = p.hasQuery; p.normalize = function() { if (this._parts.urn) { return this.normalizeProtocol(false).normalizePath(false).normalizeQuery(false).normalizeFragment(false).build(); } return this.normalizeProtocol(false).normalizeHostname(false).normalizePort(false).normalizePath(false).normalizeQuery(false).normalizeFragment(false).build(); }; p.normalizeProtocol = function(build) { if (typeof this._parts.protocol === "string") { this._parts.protocol = this._parts.protocol.toLowerCase(); this.build(!build); } return this; }; p.normalizeHostname = function(build) { if (this._parts.hostname) { if (this.is("IDN") && punycode) { this._parts.hostname = punycode.toASCII(this._parts.hostname); } else if (this.is("IPv6") && IPv6) { this._parts.hostname = IPv6.best(this._parts.hostname); } this._parts.hostname = this._parts.hostname.toLowerCase(); this.build(!build); } return this; }; p.normalizePort = function(build) { if (typeof this._parts.protocol === "string" && this._parts.port === URI.defaultPorts[this._parts.protocol]) { this._parts.port = null; this.build(!build); } return this; }; p.normalizePath = function(build) { var _path = this._parts.path; if (!_path) { return this; } if (this._parts.urn) { this._parts.path = URI.recodeUrnPath(this._parts.path); this.build(!build); return this; } if (this._parts.path === "/") { return this; } _path = URI.recodePath(_path); var _was_relative; var _leadingParents = ""; var _parent, _pos; if (_path.charAt(0) !== "/") { _was_relative = true; _path = "/" + _path; } if (_path.slice(-3) === "/.." || _path.slice(-2) === "/.") { _path += "/"; } _path = _path.replace(/(\/(\.\/)+)|(\/\.$)/g, "/").replace(/\/{2,}/g, "/"); if (_was_relative) { _leadingParents = _path.substring(1).match(/^(\.\.\/)+/) || ""; if (_leadingParents) { _leadingParents = _leadingParents[0]; } } while (true) { _parent = _path.search(/\/\.\.(\/|$)/); if (_parent === -1) { break; } else if (_parent === 0) { _path = _path.substring(3); continue; } _pos = _path.substring(0, _parent).lastIndexOf("/"); if (_pos === -1) { _pos = _parent; } _path = _path.substring(0, _pos) + _path.substring(_parent + 3); } if (_was_relative && this.is("relative")) { _path = _leadingParents + _path.substring(1); } this._parts.path = _path; this.build(!build); return this; }; p.normalizePathname = p.normalizePath; p.normalizeQuery = function(build) { if (typeof this._parts.query === "string") { if (!this._parts.query.length) { this._parts.query = null; } else { this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace)); } this.build(!build); } return this; }; p.normalizeFragment = function(build) { if (!this._parts.fragment) { this._parts.fragment = null; this.build(!build); } return this; }; p.normalizeSearch = p.normalizeQuery; p.normalizeHash = p.normalizeFragment; p.iso8859 = function() { var e = URI.encode; var d = URI.decode; URI.encode = escape; URI.decode = decodeURIComponent; try { this.normalize(); } finally { URI.encode = e; URI.decode = d; } return this; }; p.unicode = function() { var e = URI.encode; var d = URI.decode; URI.encode = strictEncodeURIComponent; URI.decode = unescape; try { this.normalize(); } finally { URI.encode = e; URI.decode = d; } return this; }; p.readable = function() { var uri = this.clone(); uri.username("").password("").normalize(); var t = ""; if (uri._parts.protocol) { t += uri._parts.protocol + "://"; } if (uri._parts.hostname) { if (uri.is("punycode") && punycode) { t += punycode.toUnicode(uri._parts.hostname); if (uri._parts.port) { t += ":" + uri._parts.port; } } else { t += uri.host(); } } if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== "/") { t += "/"; } t += uri.path(true); if (uri._parts.query) { var q2 = ""; for (var i = 0, qp = uri._parts.query.split("&"), l = qp.length; i < l; i++) { var kv = (qp[i] || "").split("="); q2 += "&" + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace).replace(/&/g, "%26"); if (kv[1] !== void 0) { q2 += "=" + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace).replace(/&/g, "%26"); } } t += "?" + q2.substring(1); } t += URI.decodeQuery(uri.hash(), true); return t; }; p.absoluteTo = function(base) { var resolved = this.clone(); var properties = ["protocol", "username", "password", "hostname", "port"]; var basedir, i, p2; if (this._parts.urn) { throw new Error("URNs do not have any generally defined hierarchical components"); } if (!(base instanceof URI)) { base = new URI(base); } if (resolved._parts.protocol) { return resolved; } else { resolved._parts.protocol = base._parts.protocol; } if (this._parts.hostname) { return resolved; } for (i = 0; p2 = properties[i]; i++) { resolved._parts[p2] = base._parts[p2]; } if (!resolved._parts.path) { resolved._parts.path = base._parts.path; if (!resolved._parts.query) { resolved._parts.query = base._parts.query; } } else { if (resolved._parts.path.substring(-2) === "..") { resolved._parts.path += "/"; } if (resolved.path().charAt(0) !== "/") { basedir = base.directory(); basedir = basedir ? basedir : base.path().indexOf("/") === 0 ? "/" : ""; resolved._parts.path = (basedir ? basedir + "/" : "") + resolved._parts.path; resolved.normalizePath(); } } resolved.build(); return resolved; }; p.relativeTo = function(base) { var relative = this.clone().normalize(); var relativeParts, baseParts, common, relativePath, basePath; if (relative._parts.urn) { throw new Error("URNs do not have any generally defined hierarchical components"); } base = new URI(base).normalize(); relativeParts = relative._parts; baseParts = base._parts; relativePath = relative.path(); basePath = base.path(); if (relativePath.charAt(0) !== "/") { throw new Error("URI is already relative"); } if (basePath.charAt(0) !== "/") { throw new Error("Cannot calculate a URI relative to another relative URI"); } if (relativeParts.protocol === baseParts.protocol) { relativeParts.protocol = null; } if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) { return relative.build(); } if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) { return relative.build(); } if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) { relativeParts.hostname = null; relativeParts.port = null; } else { return relative.build(); } if (relativePath === basePath) { relativeParts.path = ""; return relative.build(); } common = URI.commonPath(relativePath, basePath); if (!common) { return relative.build(); } var parents = baseParts.path.substring(common.length).replace(/[^\/]*$/, "").replace(/.*?\//g, "../"); relativeParts.path = parents + relativeParts.path.substring(common.length) || "./"; return relative.build(); }; p.equals = function(uri) { var one = this.clone(); var two = new URI(uri); var one_map = {}; var two_map = {}; var checked = {}; var one_query, two_query, key; one.normalize(); two.normalize(); if (one.toString() === two.toString()) { return true; } one_query = one.query(); two_query = two.query(); one.query(""); two.query(""); if (one.toString() !== two.toString()) { return false; } if (one_query.length !== two_query.length) { return false; } one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace); two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace); for (key in one_map) { if (hasOwn.call(one_map, key)) { if (!isArray(one_map[key])) { if (one_map[key] !== two_map[key]) { return false; } } else if (!arraysEqual(one_map[key], two_map[key])) { return false; } checked[key] = true; } } for (key in two_map) { if (hasOwn.call(two_map, key)) { if (!checked[key]) { return false; } } } return true; }; p.preventInvalidHostname = function(v) { this._parts.preventInvalidHostname = !!v; return this; }; p.duplicateQueryParameters = function(v) { this._parts.duplicateQueryParameters = !!v; return this; }; p.escapeQuerySpace = function(v) { this._parts.escapeQuerySpace = !!v; return this; }; return URI; }); } }); // packages/engine/Specs/Renderer/AutomaticUniformSpec.js var import__ = __toESM(require_Cesium(), 1); // Specs/createCamera.js var import_engine = __toESM(require_Cesium(), 1); function MockScene(canvas) { canvas = (0, import_engine.defaultValue)(canvas, { clientWidth: 512, clientHeight: 384 }); this.canvas = canvas; this.drawingBufferWidth = canvas.clientWidth * 2; this.drawingBufferHeight = canvas.clientHeight * 2; this.mapProjection = new import_engine.GeographicProjection(); } function createCamera(options) { options = (0, import_engine.defaultValue)(options, import_engine.defaultValue.EMPTY_OBJECT); const scene2 = new MockScene(options.canvas); const camera = new import_engine.Camera(scene2); camera.frustum.near = (0, import_engine.defaultValue)(options.near, 0.01); camera.frustum.far = (0, import_engine.defaultValue)(options.far, 10); const offset = (0, import_engine.defaultValue)(options.offset, new import_engine.Cartesian3(-1, 0, 0)); if ((0, import_engine.defined)(options.target)) { camera.lookAt(options.target, offset); } else if ((0, import_engine.defined)(options.transform)) { camera.lookAtTransform(options.transform, offset); } else { camera.lookAtTransform(import_engine.Matrix4.IDENTITY, offset); } return camera; } var createCamera_default = createCamera; // Specs/createContext.js var import_engine5 = __toESM(require_Cesium(), 1); // Specs/createCanvas.js var import_engine2 = __toESM(require_Cesium(), 1); var canvasCount = 0; function createCanvas(width, height) { width = (0, import_engine2.defaultValue)(width, 1); height = (0, import_engine2.defaultValue)(height, 1); const canvas = document.createElement("canvas"); canvas.id = `canvas${canvasCount++}`; canvas.setAttribute("width", width); canvas.setAttribute("clientWidth", width); canvas.setAttribute("height", height); canvas.setAttribute("clientHeight", height); canvas.innerHTML = "To view this web page, upgrade your browser; it does not support the HTML5 canvas element."; document.body.appendChild(canvas); return canvas; } var createCanvas_default = createCanvas; // Specs/createFrameState.js var import_engine3 = __toESM(require_Cesium(), 1); function createFrameState(context, camera, frameNumber, time2) { const frameState2 = new import_engine3.FrameState( context, new import_engine3.CreditDisplay( document.createElement("div"), void 0, document.createElement("div") ), new import_engine3.JobScheduler() ); const projection = new import_engine3.GeographicProjection(); frameState2.mapProjection = projection; frameState2.frameNumber = (0, import_engine3.defaultValue)(frameNumber, 1); frameState2.time = (0, import_engine3.defaultValue)( time2, import_engine3.JulianDate.fromDate(/* @__PURE__ */ new Date("January 1, 2011 12:00:00 EST")) ); camera = (0, import_engine3.defaultValue)( camera, new import_engine3.Camera({ drawingBufferWidth: 1, drawingBufferHeight: 1, mapProjection: projection }) ); frameState2.camera = camera; frameState2.cullingVolume = camera.frustum.computeCullingVolume( camera.position, camera.direction, camera.up ); frameState2.verticalExaggeration = 1; frameState2.verticalExaggerationRelativeHeight = 0; frameState2.passes.render = true; frameState2.passes.pick = false; frameState2.minimumDisableDepthTestDistance = 0; frameState2.atmosphere = new import_engine3.Atmosphere(); return frameState2; } var createFrameState_default = createFrameState; // Specs/getWebGLStub.js var import_engine4 = __toESM(require_Cesium(), 1); function getWebGLStub(canvas, options) { const stub = (0, import_engine4.clone)(import_engine4.WebGLConstants); stub.canvas = canvas; stub.drawingBufferWidth = Math.max(canvas.width, 1); stub.drawingBufferHeight = Math.max(canvas.height, 1); stub.activeTexture = noop; stub.attachShader = noop; stub.bindAttribLocation = noop; stub.bindBuffer = noop; stub.bindFramebuffer = noop; stub.bindRenderbuffer = noop; stub.bindTexture = noop; stub.blendColor = noop; stub.blendEquation = noop; stub.blendEquationSeparate = noop; stub.blendFunc = noop; stub.blendFuncSeparate = noop; stub.bufferData = noop; stub.bufferSubData = noop; stub.checkFramebufferStatus = checkFramebufferStatusStub; stub.clear = noop; stub.clearColor = noop; stub.clearDepth = noop; stub.clearStencil = noop; stub.colorMask = noop; stub.compileShader = noop; stub.compressedTexImage2D = noop; stub.compressedTexSubImage2D = noop; stub.copyTexImage2D = noop; stub.copyTexSubImage2D = noop; stub.createBuffer = createStub; stub.createFramebuffer = createStub; stub.createProgram = createStub; stub.createRenderbuffer = createStub; stub.createShader = createStub; stub.createTexture = createStub; stub.cullFace = noop; stub.deleteBuffer = noop; stub.deleteFramebuffer = noop; stub.deleteProgram = noop; stub.deleteRenderbuffer = noop; stub.deleteShader = noop; stub.deleteTexture = noop; stub.depthFunc = noop; stub.depthMask = noop; stub.depthRange = noop; stub.detachShader = noop; stub.disable = noop; stub.disableVertexAttribArray = noop; stub.drawArrays = noop; stub.drawElements = noop; stub.enable = noop; stub.enableVertexAttribArray = noop; stub.finish = noop; stub.flush = noop; stub.framebufferRenderbuffer = noop; stub.framebufferTexture2D = noop; stub.frontFace = noop; stub.generateMipmap = noop; stub.getActiveAttrib = getStub; stub.getActiveUniform = getStub; stub.getAttachedShaders = getStubWarning; stub.getAttribLocation = getStub; stub.getBufferParameter = getStubWarning; stub.getContextAttributes = getContextAttributesStub(options); stub.getError = getErrorStub; stub.getExtension = getExtensionStub; stub.getFramebufferAttachmentParameter = getStubWarning; stub.getParameter = getParameterStub(options); stub.getProgramParameter = getProgramParameterStub; stub.getProgramInfoLog = getStub; stub.getRenderbufferParameter = getStubWarning; stub.getShaderParameter = getShaderParameterStub; stub.getShaderInfoLog = getStub; stub.getShaderPrecisionFormat = getShaderPrecisionStub; stub.getShaderSource = getStubWarning; stub.getSupportedExtensions = getStubWarning; stub.getTexParameter = getStubWarning; stub.getUniform = getStub; stub.getUniformLocation = getStub; stub.getVertexAttrib = getStubWarning; stub.getVertexAttribOffset = getStubWarning; stub.hint = noop; stub.isBuffer = getStubWarning; stub.isContextLost = getStubWarning; stub.isEnabled = getStubWarning; stub.isFramebuffer = getStubWarning; stub.isProgram = getStubWarning; stub.isRenderbuffer = getStubWarning; stub.isShader = getStubWarning; stub.isTexture = getStubWarning; stub.lineWidth = noop; stub.linkProgram = noop; stub.pixelStorei = noop; stub.polygonOffset = noop; stub.readPixels = readPixelsStub; stub.renderbufferStorage = noop; stub.sampleCoverage = noop; stub.scissor = noop; stub.shaderSource = noop; stub.stencilFunc = noop; stub.stencilFuncSeparate = noop; stub.stencilMask = noop; stub.stencilMaskSeparate = noop; stub.stencilOp = noop; stub.stencilOpSeparate = noop; stub.texParameterf = noop; stub.texParameteri = noop; stub.texImage2D = noop; stub.texSubImage2D = noop; stub.uniform1f = noop; stub.uniform1fv = noop; stub.uniform1i = noop; stub.uniform1iv = noop; stub.uniform2f = noop; stub.uniform2fv = noop; stub.uniform2i = noop; stub.uniform2iv = noop; stub.uniform3f = noop; stub.uniform3fv = noop; stub.uniform3i = noop; stub.uniform3iv = noop; stub.uniform4f = noop; stub.uniform4fv = noop; stub.uniform4i = noop; stub.uniform4iv = noop; stub.uniformMatrix2fv = noop; stub.uniformMatrix3fv = noop; stub.uniformMatrix4fv = noop; stub.useProgram = noop; stub.validateProgram = noop; stub.vertexAttrib1f = noop; stub.vertexAttrib1fv = noop; stub.vertexAttrib2f = noop; stub.vertexAttrib2fv = noop; stub.vertexAttrib3f = noop; stub.vertexAttrib3fv = noop; stub.vertexAttrib4f = noop; stub.vertexAttrib4fv = noop; stub.vertexAttribPointer = noop; stub.viewport = noop; return stub; } var instancedArraysStub = { drawElementsInstancedANGLE: noop, drawArraysInstancedANGLE: noop, vertexAttribDivisorANGLE: noop }; function noop() { } function createStub() { return {}; } function getStub() { return {}; } function getStubWarning() { throw new import_engine4.DeveloperError( "A stub for this get/is function is not defined. Can it use getStub() or does it need a new one?" ); } function checkFramebufferStatusStub(target) { return import_engine4.WebGLConstants.FRAMEBUFFER_COMPLETE; } function getContextAttributesStub(options) { const contextAttributes = { alpha: (0, import_engine4.defaultValue)(options.alpha, true), depth: (0, import_engine4.defaultValue)(options.depth, true), stencil: (0, import_engine4.defaultValue)(options.stencil, false), antialias: (0, import_engine4.defaultValue)(options.antialias, true), premultipliedAlpha: (0, import_engine4.defaultValue)(options.premultipliedAlpha, true), preserveDrawingBuffer: (0, import_engine4.defaultValue)(options.preserveDrawingBuffer, false), powerPreference: (0, import_engine4.defaultValue)(options.powerPreference, false), failIfMajorPerformanceCaveat: (0, import_engine4.defaultValue)( options.failIfMajorPerformanceCaveat, false ) }; return function() { return contextAttributes; }; } function getErrorStub() { return import_engine4.WebGLConstants.NO_ERROR; } function getExtensionStub(name) { if (name === "ANGLE_instanced_arrays") { return instancedArraysStub; } if (name === "OES_texture_float") { return {}; } return null; } function getParameterStub(options) { const parameterStubValues = {}; parameterStubValues[import_engine4.WebGLConstants.STENCIL_BITS] = options.stencil ? 8 : 0; parameterStubValues[import_engine4.WebGLConstants.MAX_COMBINED_TEXTURE_IMAGE_UNITS] = 32; parameterStubValues[import_engine4.WebGLConstants.MAX_CUBE_MAP_TEXTURE_SIZE] = 16384; parameterStubValues[import_engine4.WebGLConstants.MAX_FRAGMENT_UNIFORM_VECTORS] = 1024; parameterStubValues[import_engine4.WebGLConstants.MAX_TEXTURE_IMAGE_UNITS] = 16; parameterStubValues[import_engine4.WebGLConstants.MAX_RENDERBUFFER_SIZE] = 16384; parameterStubValues[import_engine4.WebGLConstants.MAX_TEXTURE_SIZE] = 16384; parameterStubValues[import_engine4.WebGLConstants.MAX_VARYING_VECTORS] = 30; parameterStubValues[import_engine4.WebGLConstants.MAX_VERTEX_ATTRIBS] = 16; parameterStubValues[import_engine4.WebGLConstants.MAX_VERTEX_TEXTURE_IMAGE_UNITS] = 16; parameterStubValues[import_engine4.WebGLConstants.MAX_VERTEX_UNIFORM_VECTORS] = 4096; parameterStubValues[import_engine4.WebGLConstants.ALIASED_LINE_WIDTH_RANGE] = [1, 1]; parameterStubValues[import_engine4.WebGLConstants.ALIASED_POINT_SIZE_RANGE] = [1, 1024]; parameterStubValues[import_engine4.WebGLConstants.MAX_VIEWPORT_DIMS] = [16384, 16384]; parameterStubValues[import_engine4.WebGLConstants.MAX_TEXTURE_MAX_ANISOTROPY_EXT] = 16; parameterStubValues[import_engine4.WebGLConstants.MAX_DRAW_BUFFERS] = 8; parameterStubValues[import_engine4.WebGLConstants.MAX_COLOR_ATTACHMENTS] = 8; parameterStubValues[import_engine4.WebGLConstants.MAX_SAMPLES] = 8; return function(pname) { const value = parameterStubValues[pname]; if (!(0, import_engine4.defined)(value)) { throw new import_engine4.DeveloperError( `A WebGL parameter stub for ${pname} is not defined. Add it.` ); } return value; }; } function getProgramParameterStub(program, pname) { if (pname === import_engine4.WebGLConstants.LINK_STATUS || pname === import_engine4.WebGLConstants.VALIDATE_STATUS) { return true; } if (pname === import_engine4.WebGLConstants.ACTIVE_UNIFORMS || pname === import_engine4.WebGLConstants.ACTIVE_ATTRIBUTES) { return 0; } throw new import_engine4.DeveloperError( `A WebGL parameter stub for ${pname} is not defined. Add it.` ); } function getShaderParameterStub(shader, pname) { if (pname !== import_engine4.WebGLConstants.COMPILE_STATUS) { throw new import_engine4.DeveloperError( `A WebGL parameter stub for ${pname} is not defined. Add it.` ); } return true; } function getShaderPrecisionStub(shadertype, precisiontype) { if (shadertype !== import_engine4.WebGLConstants.FRAGMENT_SHADER) { throw new import_engine4.DeveloperError( "getShaderPrecision only has a stub for FRAGMENT_SHADER. Update it." ); } if (precisiontype !== import_engine4.WebGLConstants.HIGH_FLOAT && precisiontype !== import_engine4.WebGLConstants.HIGH_INT) { throw new import_engine4.DeveloperError( "getShaderPrecision only has a stub for HIGH_FLOAT and HIGH_INT. Update it." ); } if (precisiontype === import_engine4.WebGLConstants.HIGH_FLOAT) { return { rangeMin: 127, rangeMax: 127, precision: 23 }; } return { rangeMin: 31, rangeMax: 30, precision: 0 }; } function readPixelsStub(x, y, width, height, format, type, pixels) { return [0, 0, 0, 0]; } var getWebGLStub_default = getWebGLStub; // Specs/createContext.js function createContext(options, canvasWidth, canvasHeight) { options = (0, import_engine5.clone)((0, import_engine5.defaultValue)(options, {})); options.webgl = (0, import_engine5.clone)((0, import_engine5.defaultValue)(options.webgl, {})); options.webgl.antialias = (0, import_engine5.defaultValue)(options.webgl.antialias, false); if (!!window.webglStub) { options.getWebGLStub = getWebGLStub_default; } const canvas = createCanvas_default(canvasWidth, canvasHeight); const context = new import_engine5.Context(canvas, options); if (!!window.webglValidation) { context.validateShaderProgram = true; context.validateFramebuffer = true; context.logShaderCompilation = true; context.throwOnWebGLError = true; } const us = context.uniformState; us.update(createFrameState_default(context)); context.destroyForSpecs = function() { document.body.removeChild(context.canvas); return context.destroy(); }; return context; } var createContext_default = createContext; // packages/engine/Specs/Renderer/AutomaticUniformSpec.js describe( "Renderer/AutomaticUniforms", function() { let context; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); function createMockCamera(view, projection, infiniteProjection, position, direction, right, up) { return { viewMatrix: (0, import__.defaultValue)(view, import__.Matrix4.clone(import__.Matrix4.IDENTITY)), inverseViewMatrix: import__.Matrix4.inverseTransformation( (0, import__.defaultValue)(view, import__.Matrix4.clone(import__.Matrix4.IDENTITY)), new import__.Matrix4() ), frustum: { near: 1, far: 1e3, top: 2, bottom: -2, left: -1, right: 1, projectionMatrix: (0, import__.defaultValue)( projection, import__.Matrix4.clone(import__.Matrix4.IDENTITY) ), infiniteProjectionMatrix: (0, import__.defaultValue)( infiniteProjection, import__.Matrix4.clone(import__.Matrix4.IDENTITY) ), computeCullingVolume: function() { return void 0; }, getPixelSize: function() { return new import__.Cartesian2(1, 0.1); } }, position: (0, import__.defaultValue)(position, import__.Cartesian3.clone(import__.Cartesian3.ZERO)), positionWC: (0, import__.defaultValue)(position, import__.Cartesian3.clone(import__.Cartesian3.ZERO)), directionWC: (0, import__.defaultValue)( direction, import__.Cartesian3.clone(import__.Cartesian3.UNIT_Z) ), rightWC: (0, import__.defaultValue)(right, import__.Cartesian3.clone(import__.Cartesian3.UNIT_X)), upWC: (0, import__.defaultValue)(up, import__.Cartesian3.clone(import__.Cartesian3.UNIT_Y)), positionCartographic: new import__.Cartographic(0, 0, 10) }; } it("can declare automatic uniforms", function() { const fs = "void main() { out_FragColor = vec4((czm_viewport.x == 0.0) && (czm_viewport.y == 0.0) && (czm_viewport.z == 1.0) && (czm_viewport.w == 1.0)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_viewport", function() { const fs = "void main() { out_FragColor = vec4((czm_viewport.x == 0.0) && (czm_viewport.y == 0.0) && (czm_viewport.z == 1.0) && (czm_viewport.w == 1.0)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_viewportOrthographic", function() { const fs = "void main() { bool b0 = (czm_viewportOrthographic[0][0] != 0.0) && (czm_viewportOrthographic[1][0] == 0.0) && (czm_viewportOrthographic[2][0] == 0.0) && (czm_viewportOrthographic[3][0] != 0.0); bool b1 = (czm_viewportOrthographic[0][1] == 0.0) && (czm_viewportOrthographic[1][1] != 0.0) && (czm_viewportOrthographic[2][1] == 0.0) && (czm_viewportOrthographic[3][1] != 0.0); bool b2 = (czm_viewportOrthographic[0][2] == 0.0) && (czm_viewportOrthographic[1][2] == 0.0) && (czm_viewportOrthographic[2][2] != 0.0) && (czm_viewportOrthographic[3][2] != 0.0); bool b3 = (czm_viewportOrthographic[0][3] == 0.0) && (czm_viewportOrthographic[1][3] == 0.0) && (czm_viewportOrthographic[2][3] == 0.0) && (czm_viewportOrthographic[3][3] == 1.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_viewportTransformation", function() { const fs = "void main() { bool b0 = (czm_viewportTransformation[0][0] != 0.0) && (czm_viewportTransformation[1][0] == 0.0) && (czm_viewportTransformation[2][0] == 0.0) && (czm_viewportTransformation[3][0] != 0.0); bool b1 = (czm_viewportTransformation[0][1] == 0.0) && (czm_viewportTransformation[1][1] != 0.0) && (czm_viewportTransformation[2][1] == 0.0) && (czm_viewportTransformation[3][1] != 0.0); bool b2 = (czm_viewportTransformation[0][2] == 0.0) && (czm_viewportTransformation[1][2] == 0.0) && (czm_viewportTransformation[2][2] != 0.0) && (czm_viewportTransformation[3][2] != 0.0); bool b3 = (czm_viewportTransformation[0][3] == 0.0) && (czm_viewportTransformation[1][3] == 0.0) && (czm_viewportTransformation[2][3] == 0.0) && (czm_viewportTransformation[3][3] == 1.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_globeDepthTexture", function() { context.uniformState.globeDepthTexture = new import__.Texture({ context, source: { width: 1, height: 1, arrayBufferView: new Uint8Array([255, 255, 255, 255]) } }); const fs = "void main() { out_FragColor = vec4(texture(czm_globeDepthTexture, vec2(0.5, 0.5)).r == 1.0);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_model", function() { const fs = "void main() { bool b0 = (czm_model[0][0] == 1.0) && (czm_model[1][0] == 2.0) && (czm_model[2][0] == 3.0) && (czm_model[3][0] == 4.0); bool b1 = (czm_model[0][1] == 5.0) && (czm_model[1][1] == 6.0) && (czm_model[2][1] == 7.0) && (czm_model[3][1] == 8.0); bool b2 = (czm_model[0][2] == 9.0) && (czm_model[1][2] == 10.0) && (czm_model[2][2] == 11.0) && (czm_model[3][2] == 12.0); bool b3 = (czm_model[0][3] == 13.0) && (czm_model[1][3] == 14.0) && (czm_model[2][3] == 15.0) && (czm_model[3][3] == 16.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; const m = new import__.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); expect({ context, fragmentShader: fs, modelMatrix: m }).contextToRender(); }); it("has czm_inverseModel", function() { const fs = "void main() { bool b0 = (czm_inverseModel[0][0] == 0.0) && (czm_inverseModel[1][0] == 1.0) && (czm_inverseModel[2][0] == 0.0) && (czm_inverseModel[3][0] == -2.0); bool b1 = (czm_inverseModel[0][1] == -1.0) && (czm_inverseModel[1][1] == 0.0) && (czm_inverseModel[2][1] == 0.0) && (czm_inverseModel[3][1] == 1.0); bool b2 = (czm_inverseModel[0][2] == 0.0) && (czm_inverseModel[1][2] == 0.0) && (czm_inverseModel[2][2] == 1.0) && (czm_inverseModel[3][2] == 0.0); bool b3 = (czm_inverseModel[0][3] == 0.0) && (czm_inverseModel[1][3] == 0.0) && (czm_inverseModel[2][3] == 0.0) && (czm_inverseModel[3][3] == 1.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; const m = new import__.Matrix4( 0, -1, 0, 1, 1, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 1 ); expect({ context, fragmentShader: fs, modelMatrix: m }).contextToRender(); }); it("has czm_view", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( new import__.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ) ) ) ); const fs = "void main() { bool b0 = (czm_view[0][0] == 1.0) && (czm_view[1][0] == 2.0) && (czm_view[2][0] == 3.0) && (czm_view[3][0] == 4.0); bool b1 = (czm_view[0][1] == 5.0) && (czm_view[1][1] == 6.0) && (czm_view[2][1] == 7.0) && (czm_view[3][1] == 8.0); bool b2 = (czm_view[0][2] == 9.0) && (czm_view[1][2] == 10.0) && (czm_view[2][2] == 11.0) && (czm_view[3][2] == 12.0); bool b3 = (czm_view[0][3] == 13.0) && (czm_view[1][3] == 14.0) && (czm_view[2][3] == 15.0) && (czm_view[3][3] == 16.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_view3D", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( new import__.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ) ) ) ); const fs = "void main() { bool b0 = (czm_view3D[0][0] == 1.0) && (czm_view3D[1][0] == 2.0) && (czm_view3D[2][0] == 3.0) && (czm_view3D[3][0] == 4.0); bool b1 = (czm_view3D[0][1] == 5.0) && (czm_view3D[1][1] == 6.0) && (czm_view3D[2][1] == 7.0) && (czm_view3D[3][1] == 8.0); bool b2 = (czm_view3D[0][2] == 9.0) && (czm_view3D[1][2] == 10.0) && (czm_view3D[2][2] == 11.0) && (czm_view3D[3][2] == 12.0); bool b3 = (czm_view3D[0][3] == 13.0) && (czm_view3D[1][3] == 14.0) && (czm_view3D[2][3] == 15.0) && (czm_view3D[3][3] == 16.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_viewRotation", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( new import__.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ) ) ) ); const fs = "void main() { bool b0 = (czm_viewRotation[0][0] == 1.0) && (czm_viewRotation[1][0] == 2.0) && (czm_viewRotation[2][0] == 3.0); bool b1 = (czm_viewRotation[0][1] == 5.0) && (czm_viewRotation[1][1] == 6.0) && (czm_viewRotation[2][1] == 7.0); bool b2 = (czm_viewRotation[0][2] == 9.0) && (czm_viewRotation[1][2] == 10.0) && (czm_viewRotation[2][2] == 11.0); out_FragColor = vec4(b0 && b1 && b2); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_viewRotation3D", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( new import__.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ) ) ) ); const fs = "void main() { bool b0 = (czm_viewRotation3D[0][0] == 1.0) && (czm_viewRotation3D[1][0] == 2.0) && (czm_viewRotation3D[2][0] == 3.0); bool b1 = (czm_viewRotation3D[0][1] == 5.0) && (czm_viewRotation3D[1][1] == 6.0) && (czm_viewRotation3D[2][1] == 7.0); bool b2 = (czm_viewRotation3D[0][2] == 9.0) && (czm_viewRotation3D[1][2] == 10.0) && (czm_viewRotation3D[2][2] == 11.0); out_FragColor = vec4(b0 && b1 && b2); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_inverseView", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( new import__.Matrix4( 0, -1, 0, 7, 1, 0, 0, 8, 0, 0, 1, 0, 0, 0, 0, 1 ) ) ) ); const fs = "void main() { out_FragColor = vec4( (czm_inverseView[0][0] == 0.0) && (czm_inverseView[1][0] == 1.0) && (czm_inverseView[2][0] == 0.0) && (czm_inverseView[3][0] == -8.0) && (czm_inverseView[0][1] == -1.0) && (czm_inverseView[1][1] == 0.0) && (czm_inverseView[2][1] == 0.0) && (czm_inverseView[3][1] == 7.0) && (czm_inverseView[0][2] == 0.0) && (czm_inverseView[1][2] == 0.0) && (czm_inverseView[2][2] == 1.0) && (czm_inverseView[3][2] == 0.0) ); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_inverseView3D", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( new import__.Matrix4( 0, -1, 0, 7, 1, 0, 0, 8, 0, 0, 1, 0, 0, 0, 0, 1 ) ) ) ); const fs = "void main() { out_FragColor = vec4( (czm_inverseView3D[0][0] == 0.0) && (czm_inverseView3D[1][0] == 1.0) && (czm_inverseView3D[2][0] == 0.0) && (czm_inverseView3D[3][0] == -8.0) && (czm_inverseView3D[0][1] == -1.0) && (czm_inverseView3D[1][1] == 0.0) && (czm_inverseView3D[2][1] == 0.0) && (czm_inverseView3D[3][1] == 7.0) && (czm_inverseView3D[0][2] == 0.0) && (czm_inverseView3D[1][2] == 0.0) && (czm_inverseView3D[2][2] == 1.0) && (czm_inverseView3D[3][2] == 0.0) ); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_inverseViewRotation", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( new import__.Matrix4( 0, -1, 0, 7, 1, 0, 0, 8, 0, 0, 1, 9, 0, 0, 0, 1 ) ) ) ); const fs = "void main() { out_FragColor = vec4( (czm_inverseViewRotation[0][0] == 0.0) && (czm_inverseViewRotation[1][0] == 1.0) && (czm_inverseViewRotation[2][0] == 0.0) && (czm_inverseViewRotation[0][1] == -1.0) && (czm_inverseViewRotation[1][1] == 0.0) && (czm_inverseViewRotation[2][1] == 0.0) && (czm_inverseViewRotation[0][2] == 0.0) && (czm_inverseViewRotation[1][2] == 0.0) && (czm_inverseViewRotation[2][2] == 1.0) ); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_inverseViewRotation3D", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( new import__.Matrix4( 0, -1, 0, 7, 1, 0, 0, 8, 0, 0, 1, 9, 0, 0, 0, 1 ) ) ) ); const fs = "void main() { out_FragColor = vec4( (czm_inverseViewRotation3D[0][0] == 0.0) && (czm_inverseViewRotation3D[1][0] == 1.0) && (czm_inverseViewRotation3D[2][0] == 0.0) && (czm_inverseViewRotation3D[0][1] == -1.0) && (czm_inverseViewRotation3D[1][1] == 0.0) && (czm_inverseViewRotation3D[2][1] == 0.0) && (czm_inverseViewRotation3D[0][2] == 0.0) && (czm_inverseViewRotation3D[1][2] == 0.0) && (czm_inverseViewRotation3D[2][2] == 1.0) ); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_projection", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( void 0, new import__.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ) ) ) ); const fs = "void main() { bool b0 = (czm_projection[0][0] == 1.0) && (czm_projection[1][0] == 2.0) && (czm_projection[2][0] == 3.0) && (czm_projection[3][0] == 4.0); bool b1 = (czm_projection[0][1] == 5.0) && (czm_projection[1][1] == 6.0) && (czm_projection[2][1] == 7.0) && (czm_projection[3][1] == 8.0); bool b2 = (czm_projection[0][2] == 9.0) && (czm_projection[1][2] == 10.0) && (czm_projection[2][2] == 11.0) && (czm_projection[3][2] == 12.0); bool b3 = (czm_projection[0][3] == 13.0) && (czm_projection[1][3] == 14.0) && (czm_projection[2][3] == 15.0) && (czm_projection[3][3] == 16.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_inverseProjection", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( void 0, new import__.Matrix4( 0, -1, 0, 1, 1, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 1 ) ) ) ); const fs = "void main() { bool b0 = (czm_inverseProjection[0][0] == 0.0) && (czm_inverseProjection[1][0] == 1.0) && (czm_inverseProjection[2][0] == 0.0) && (czm_inverseProjection[3][0] == -2.0); bool b1 = (czm_inverseProjection[0][1] == -1.0) && (czm_inverseProjection[1][1] == 0.0) && (czm_inverseProjection[2][1] == 0.0) && (czm_inverseProjection[3][1] == 1.0); bool b2 = (czm_inverseProjection[0][2] == 0.0) && (czm_inverseProjection[1][2] == 0.0) && (czm_inverseProjection[2][2] == 1.0) && (czm_inverseProjection[3][2] == 0.0); bool b3 = (czm_inverseProjection[0][3] == 0.0) && (czm_inverseProjection[1][3] == 0.0) && (czm_inverseProjection[2][3] == 0.0) && (czm_inverseProjection[3][3] == 1.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_inverseProjection in 2D", function() { const frameState2 = createFrameState_default( context, createMockCamera( void 0, new import__.Matrix4( 0, -1, 0, 1, 1, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 1 ) ) ); frameState2.mode = import__.SceneMode.SCENE2D; const us = context.uniformState; us.update(frameState2); const fs = "void main() { bool b0 = (czm_inverseProjection[0][0] == 0.0) && (czm_inverseProjection[1][0] == 0.0) && (czm_inverseProjection[2][0] == 0.0) && (czm_inverseProjection[3][0] == 0.0); bool b1 = (czm_inverseProjection[0][1] == 0.0) && (czm_inverseProjection[1][1] == 0.0) && (czm_inverseProjection[2][1] == 0.0) && (czm_inverseProjection[3][1] == 0.0); bool b2 = (czm_inverseProjection[0][2] == 0.0) && (czm_inverseProjection[1][2] == 0.0) && (czm_inverseProjection[2][2] == 0.0) && (czm_inverseProjection[3][2] == 0.0); bool b3 = (czm_inverseProjection[0][3] == 0.0) && (czm_inverseProjection[1][3] == 0.0) && (czm_inverseProjection[2][3] == 0.0) && (czm_inverseProjection[3][3] == 0.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_inverseProjection in 3D with orthographic projection", function() { const frameState2 = createFrameState_default( context, createMockCamera( void 0, new import__.Matrix4( 0, -1, 0, 1, 1, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 1 ) ) ); const frustum = new import__.OrthographicFrustum(); frustum.aspectRatio = 1; frustum.width = 1; frameState2.camera.frustum = frustum; const us = context.uniformState; us.update(frameState2); const fs = "void main() { bool b0 = (czm_inverseProjection[0][0] == 0.0) && (czm_inverseProjection[1][0] == 0.0) && (czm_inverseProjection[2][0] == 0.0) && (czm_inverseProjection[3][0] == 0.0); bool b1 = (czm_inverseProjection[0][1] == 0.0) && (czm_inverseProjection[1][1] == 0.0) && (czm_inverseProjection[2][1] == 0.0) && (czm_inverseProjection[3][1] == 0.0); bool b2 = (czm_inverseProjection[0][2] == 0.0) && (czm_inverseProjection[1][2] == 0.0) && (czm_inverseProjection[2][2] == 0.0) && (czm_inverseProjection[3][2] == 0.0); bool b3 = (czm_inverseProjection[0][3] == 0.0) && (czm_inverseProjection[1][3] == 0.0) && (czm_inverseProjection[2][3] == 0.0) && (czm_inverseProjection[3][3] == 0.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_infiniteProjection", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( void 0, void 0, new import__.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ) ) ) ); const fs = "void main() { bool b0 = (czm_infiniteProjection[0][0] == 1.0) && (czm_infiniteProjection[1][0] == 2.0) && (czm_infiniteProjection[2][0] == 3.0) && (czm_infiniteProjection[3][0] == 4.0); bool b1 = (czm_infiniteProjection[0][1] == 5.0) && (czm_infiniteProjection[1][1] == 6.0) && (czm_infiniteProjection[2][1] == 7.0) && (czm_infiniteProjection[3][1] == 8.0); bool b2 = (czm_infiniteProjection[0][2] == 9.0) && (czm_infiniteProjection[1][2] == 10.0) && (czm_infiniteProjection[2][2] == 11.0) && (czm_infiniteProjection[3][2] == 12.0); bool b3 = (czm_infiniteProjection[0][3] == 13.0) && (czm_infiniteProjection[1][3] == 14.0) && (czm_infiniteProjection[2][3] == 15.0) && (czm_infiniteProjection[3][3] == 16.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_modelView", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( new import__.Matrix4( 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1 ) ) ) ); const fs = "void main() { bool b0 = (czm_modelView[0][0] == 2.0) && (czm_modelView[1][0] == 0.0) && (czm_modelView[2][0] == 0.0) && (czm_modelView[3][0] == 1.0); bool b1 = (czm_modelView[0][1] == 0.0) && (czm_modelView[1][1] == 2.0) && (czm_modelView[2][1] == 0.0) && (czm_modelView[3][1] == 1.0); bool b2 = (czm_modelView[0][2] == 0.0) && (czm_modelView[1][2] == 0.0) && (czm_modelView[2][2] == 2.0) && (czm_modelView[3][2] == 1.0); bool b3 = (czm_modelView[0][3] == 0.0) && (czm_modelView[1][3] == 0.0) && (czm_modelView[2][3] == 0.0) && (czm_modelView[3][3] == 1.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; const m = new import__.Matrix4( 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1 ); expect({ context, fragmentShader: fs, modelMatrix: m }).contextToRender(); }); it("has czm_modelView3D", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( new import__.Matrix4( 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1 ) ) ) ); const fs = "void main() { bool b0 = (czm_modelView3D[0][0] == 2.0) && (czm_modelView3D[1][0] == 0.0) && (czm_modelView3D[2][0] == 0.0) && (czm_modelView3D[3][0] == 1.0); bool b1 = (czm_modelView3D[0][1] == 0.0) && (czm_modelView3D[1][1] == 2.0) && (czm_modelView3D[2][1] == 0.0) && (czm_modelView3D[3][1] == 1.0); bool b2 = (czm_modelView3D[0][2] == 0.0) && (czm_modelView3D[1][2] == 0.0) && (czm_modelView3D[2][2] == 2.0) && (czm_modelView3D[3][2] == 1.0); bool b3 = (czm_modelView3D[0][3] == 0.0) && (czm_modelView3D[1][3] == 0.0) && (czm_modelView3D[2][3] == 0.0) && (czm_modelView3D[3][3] == 1.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; const m = new import__.Matrix4( 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1 ); expect({ context, fragmentShader: fs, modelMatrix: m }).contextToRender(); }); it("has czm_modelViewRelativeToEye", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( new import__.Matrix4( 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1 ) ) ) ); const fs = "void main() { bool b0 = (czm_modelViewRelativeToEye[0][0] == 2.0) && (czm_modelViewRelativeToEye[1][0] == 0.0) && (czm_modelViewRelativeToEye[2][0] == 0.0) && (czm_modelViewRelativeToEye[3][0] == 0.0); bool b1 = (czm_modelViewRelativeToEye[0][1] == 0.0) && (czm_modelViewRelativeToEye[1][1] == 2.0) && (czm_modelViewRelativeToEye[2][1] == 0.0) && (czm_modelViewRelativeToEye[3][1] == 0.0); bool b2 = (czm_modelViewRelativeToEye[0][2] == 0.0) && (czm_modelViewRelativeToEye[1][2] == 0.0) && (czm_modelViewRelativeToEye[2][2] == 2.0) && (czm_modelViewRelativeToEye[3][2] == 0.0); bool b3 = (czm_modelViewRelativeToEye[0][3] == 0.0) && (czm_modelViewRelativeToEye[1][3] == 0.0) && (czm_modelViewRelativeToEye[2][3] == 0.0) && (czm_modelViewRelativeToEye[3][3] == 1.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; const m = new import__.Matrix4( 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1 ); expect({ context, fragmentShader: fs, modelMatrix: m }).contextToRender(); }); it("has czm_inverseModelView", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera(import__.Matrix4.clone(import__.Matrix4.IDENTITY)) ) ); const fs = "void main() { bool b0 = (czm_inverseModelView[0][0] == 0.0) && (czm_inverseModelView[1][0] == 1.0) && (czm_inverseModelView[2][0] == 0.0) && (czm_inverseModelView[3][0] == -2.0); bool b1 = (czm_inverseModelView[0][1] == -1.0) && (czm_inverseModelView[1][1] == 0.0) && (czm_inverseModelView[2][1] == 0.0) && (czm_inverseModelView[3][1] == 1.0); bool b2 = (czm_inverseModelView[0][2] == 0.0) && (czm_inverseModelView[1][2] == 0.0) && (czm_inverseModelView[2][2] == 1.0) && (czm_inverseModelView[3][2] == 0.0); bool b3 = (czm_inverseModelView[0][3] == 0.0) && (czm_inverseModelView[1][3] == 0.0) && (czm_inverseModelView[2][3] == 0.0) && (czm_inverseModelView[3][3] == 1.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; const m = new import__.Matrix4( 0, -1, 0, 1, 1, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 1 ); expect({ context, fragmentShader: fs, modelMatrix: m }).contextToRender(); }); it("has czm_inverseModelView3D", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera(import__.Matrix4.clone(import__.Matrix4.IDENTITY)) ) ); const fs = "void main() { bool b0 = (czm_inverseModelView3D[0][0] == 0.0) && (czm_inverseModelView3D[1][0] == 1.0) && (czm_inverseModelView3D[2][0] == 0.0) && (czm_inverseModelView3D[3][0] == -2.0); bool b1 = (czm_inverseModelView3D[0][1] == -1.0) && (czm_inverseModelView3D[1][1] == 0.0) && (czm_inverseModelView3D[2][1] == 0.0) && (czm_inverseModelView3D[3][1] == 1.0); bool b2 = (czm_inverseModelView3D[0][2] == 0.0) && (czm_inverseModelView3D[1][2] == 0.0) && (czm_inverseModelView3D[2][2] == 1.0) && (czm_inverseModelView3D[3][2] == 0.0); bool b3 = (czm_inverseModelView3D[0][3] == 0.0) && (czm_inverseModelView3D[1][3] == 0.0) && (czm_inverseModelView3D[2][3] == 0.0) && (czm_inverseModelView3D[3][3] == 1.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; const m = new import__.Matrix4( 0, -1, 0, 1, 1, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 1 ); expect({ context, fragmentShader: fs, modelMatrix: m }).contextToRender(); }); it("has czm_viewProjection", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( new import__.Matrix4( 1, 0, 0, 0, 0, 1, 0, 8, 0, 0, 1, 0, 0, 0, 0, 1 ), new import__.Matrix4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 9, 0, 0, 0, 1 ) ) ) ); const fs = "void main() { bool b0 = (czm_viewProjection[0][0] == 1.0) && (czm_viewProjection[1][0] == 0.0) && (czm_viewProjection[2][0] == 0.0) && (czm_viewProjection[3][0] == 0.0); bool b1 = (czm_viewProjection[0][1] == 0.0) && (czm_viewProjection[1][1] == 1.0) && (czm_viewProjection[2][1] == 0.0) && (czm_viewProjection[3][1] == 8.0); bool b2 = (czm_viewProjection[0][2] == 0.0) && (czm_viewProjection[1][2] == 0.0) && (czm_viewProjection[2][2] == 1.0) && (czm_viewProjection[3][2] == 9.0); bool b3 = (czm_viewProjection[0][3] == 0.0) && (czm_viewProjection[1][3] == 0.0) && (czm_viewProjection[2][3] == 0.0) && (czm_viewProjection[3][3] == 1.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_inverseViewProjection", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( new import__.Matrix4( 1, 0, 0, 0, 0, 1, 0, 8, 0, 0, 1, 0, 0, 0, 0, 1 ), new import__.Matrix4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 9, 0, 0, 0, 1 ) ) ) ); const fs = "void main() { bool b0 = (czm_inverseViewProjection[0][0] == 1.0) && (czm_inverseViewProjection[1][0] == 0.0) && (czm_inverseViewProjection[2][0] == 0.0) && (czm_inverseViewProjection[3][0] == 0.0); bool b1 = (czm_inverseViewProjection[0][1] == 0.0) && (czm_inverseViewProjection[1][1] == 1.0) && (czm_inverseViewProjection[2][1] == 0.0) && (czm_inverseViewProjection[3][1] == -8.0); bool b2 = (czm_inverseViewProjection[0][2] == 0.0) && (czm_inverseViewProjection[1][2] == 0.0) && (czm_inverseViewProjection[2][2] == 1.0) && (czm_inverseViewProjection[3][2] == -9.0); bool b3 = (czm_inverseViewProjection[0][3] == 0.0) && (czm_inverseViewProjection[1][3] == 0.0) && (czm_inverseViewProjection[2][3] == 0.0) && (czm_inverseViewProjection[3][3] == 1.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_modelViewProjection", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( new import__.Matrix4( 1, 0, 0, 0, 0, 1, 0, 8, 0, 0, 1, 0, 0, 0, 0, 1 ), new import__.Matrix4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 9, 0, 0, 0, 1 ) ) ) ); const fs = "void main() { bool b0 = (czm_modelViewProjection[0][0] == 1.0) && (czm_modelViewProjection[1][0] == 0.0) && (czm_modelViewProjection[2][0] == 0.0) && (czm_modelViewProjection[3][0] == 7.0); bool b1 = (czm_modelViewProjection[0][1] == 0.0) && (czm_modelViewProjection[1][1] == 1.0) && (czm_modelViewProjection[2][1] == 0.0) && (czm_modelViewProjection[3][1] == 8.0); bool b2 = (czm_modelViewProjection[0][2] == 0.0) && (czm_modelViewProjection[1][2] == 0.0) && (czm_modelViewProjection[2][2] == 1.0) && (czm_modelViewProjection[3][2] == 9.0); bool b3 = (czm_modelViewProjection[0][3] == 0.0) && (czm_modelViewProjection[1][3] == 0.0) && (czm_modelViewProjection[2][3] == 0.0) && (czm_modelViewProjection[3][3] == 1.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; const m = new import__.Matrix4( 1, 0, 0, 7, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); expect({ context, fragmentShader: fs, modelMatrix: m }).contextToRender(); }); it("has czm_inverseModelViewProjection", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( new import__.Matrix4( 1, 0, 0, 0, 0, 1, 0, 8, 0, 0, 1, 0, 0, 0, 0, 1 ), new import__.Matrix4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 9, 0, 0, 0, 1 ) ) ) ); const fs = "void main() { bool b0 = (czm_inverseModelViewProjection[0][0] == 1.0) && (czm_inverseModelViewProjection[1][0] == 0.0) && (czm_inverseModelViewProjection[2][0] == 0.0) && (czm_inverseModelViewProjection[3][0] == -7.0); bool b1 = (czm_inverseModelViewProjection[0][1] == 0.0) && (czm_inverseModelViewProjection[1][1] == 1.0) && (czm_inverseModelViewProjection[2][1] == 0.0) && (czm_inverseModelViewProjection[3][1] == -8.0); bool b2 = (czm_inverseModelViewProjection[0][2] == 0.0) && (czm_inverseModelViewProjection[1][2] == 0.0) && (czm_inverseModelViewProjection[2][2] == 1.0) && (czm_inverseModelViewProjection[3][2] == -9.0); bool b3 = (czm_inverseModelViewProjection[0][3] == 0.0) && (czm_inverseModelViewProjection[1][3] == 0.0) && (czm_inverseModelViewProjection[2][3] == 0.0) && (czm_inverseModelViewProjection[3][3] == 1.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; const m = new import__.Matrix4( 1, 0, 0, 7, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); expect({ context, fragmentShader: fs, modelMatrix: m }).contextToRender(); }); it("has czm_modelViewProjectionRelativeToEye", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( new import__.Matrix4( 1, 0, 0, 0, 0, 1, 0, 8, 0, 0, 1, 0, 0, 0, 0, 1 ), new import__.Matrix4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 9, 0, 0, 0, 1 ) ) ) ); const fs = "void main() { bool b0 = (czm_modelViewProjectionRelativeToEye[0][0] == 1.0) && (czm_modelViewProjectionRelativeToEye[1][0] == 0.0) && (czm_modelViewProjectionRelativeToEye[2][0] == 0.0) && (czm_modelViewProjectionRelativeToEye[3][0] == 0.0); bool b1 = (czm_modelViewProjectionRelativeToEye[0][1] == 0.0) && (czm_modelViewProjectionRelativeToEye[1][1] == 1.0) && (czm_modelViewProjectionRelativeToEye[2][1] == 0.0) && (czm_modelViewProjectionRelativeToEye[3][1] == 0.0); bool b2 = (czm_modelViewProjectionRelativeToEye[0][2] == 0.0) && (czm_modelViewProjectionRelativeToEye[1][2] == 0.0) && (czm_modelViewProjectionRelativeToEye[2][2] == 1.0) && (czm_modelViewProjectionRelativeToEye[3][2] == 9.0); bool b3 = (czm_modelViewProjectionRelativeToEye[0][3] == 0.0) && (czm_modelViewProjectionRelativeToEye[1][3] == 0.0) && (czm_modelViewProjectionRelativeToEye[2][3] == 0.0) && (czm_modelViewProjectionRelativeToEye[3][3] == 1.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; const m = new import__.Matrix4( 1, 0, 0, 7, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); expect({ context, fragmentShader: fs, modelMatrix: m }).contextToRender(); }); it("has czm_modelViewInfiniteProjection", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( new import__.Matrix4( 1, 0, 0, 0, 0, 1, 0, 8, 0, 0, 1, 0, 0, 0, 0, 1 ), void 0, new import__.Matrix4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 9, 0, 0, 0, 1 ) ) ) ); const fs = "void main() { bool b0 = (czm_modelViewInfiniteProjection[0][0] == 1.0) && (czm_modelViewInfiniteProjection[1][0] == 0.0) && (czm_modelViewInfiniteProjection[2][0] == 0.0) && (czm_modelViewInfiniteProjection[3][0] == 7.0); bool b1 = (czm_modelViewInfiniteProjection[0][1] == 0.0) && (czm_modelViewInfiniteProjection[1][1] == 1.0) && (czm_modelViewInfiniteProjection[2][1] == 0.0) && (czm_modelViewInfiniteProjection[3][1] == 8.0); bool b2 = (czm_modelViewInfiniteProjection[0][2] == 0.0) && (czm_modelViewInfiniteProjection[1][2] == 0.0) && (czm_modelViewInfiniteProjection[2][2] == 1.0) && (czm_modelViewInfiniteProjection[3][2] == 9.0); bool b3 = (czm_modelViewInfiniteProjection[0][3] == 0.0) && (czm_modelViewInfiniteProjection[1][3] == 0.0) && (czm_modelViewInfiniteProjection[2][3] == 0.0) && (czm_modelViewInfiniteProjection[3][3] == 1.0); out_FragColor = vec4(b0 && b1 && b2 && b3); }"; const m = new import__.Matrix4( 1, 0, 0, 7, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); expect({ context, fragmentShader: fs, modelMatrix: m }).contextToRender(); }); it("has czm_normal", function() { const fs = "void main() { out_FragColor = vec4( (czm_normal[0][0] == 1.0) && (czm_normal[1][0] == 0.0) && (czm_normal[2][0] == 0.0) && (czm_normal[0][1] == 0.0) && (czm_normal[1][1] == 1.0) && (czm_normal[2][1] == 0.0) && (czm_normal[0][2] == 0.0) && (czm_normal[1][2] == 0.0) && (czm_normal[2][2] == 1.0) ); }"; const m = new import__.Matrix4( 1, 0, 0, 7, 0, 1, 0, 8, 0, 0, 1, 9, 0, 0, 0, 1 ); expect({ context, fragmentShader: fs, modelMatrix: m }).contextToRender(); }); it("has czm_inverseNormal", function() { const fs = "void main() { out_FragColor = vec4( (czm_inverseNormal[0][0] == 0.0) && (czm_inverseNormal[1][0] == 1.0) && (czm_inverseNormal[2][0] == 0.0) && (czm_inverseNormal[0][1] == -1.0) && (czm_inverseNormal[1][1] == 0.0) && (czm_inverseNormal[2][1] == 0.0) && (czm_inverseNormal[0][2] == 0.0) && (czm_inverseNormal[1][2] == 0.0) && (czm_inverseNormal[2][2] == 1.0) ); }"; const m = new import__.Matrix4( 0, -1, 0, 7, 1, 0, 0, 8, 0, 0, 1, 9, 0, 0, 0, 1 ); expect({ context, fragmentShader: fs, modelMatrix: m }).contextToRender(); }); it("has czm_normal3D", function() { const fs = "void main() { out_FragColor = vec4( (czm_normal3D[0][0] == 1.0) && (czm_normal3D[1][0] == 0.0) && (czm_normal3D[2][0] == 0.0) && (czm_normal3D[0][1] == 0.0) && (czm_normal3D[1][1] == 1.0) && (czm_normal3D[2][1] == 0.0) && (czm_normal3D[0][2] == 0.0) && (czm_normal3D[1][2] == 0.0) && (czm_normal3D[2][2] == 1.0) ); }"; const m = new import__.Matrix4( 1, 0, 0, 7, 0, 1, 0, 8, 0, 0, 1, 9, 0, 0, 0, 1 ); expect({ context, fragmentShader: fs, modelMatrix: m }).contextToRender(); }); it("has czm_inverseNormal3D", function() { const fs = "void main() { out_FragColor = vec4( (czm_inverseNormal3D[0][0] == 0.0) && (czm_inverseNormal3D[1][0] == 1.0) && (czm_inverseNormal3D[2][0] == 0.0) && (czm_inverseNormal3D[0][1] == -1.0) && (czm_inverseNormal3D[1][1] == 0.0) && (czm_inverseNormal3D[2][1] == 0.0) && (czm_inverseNormal3D[0][2] == 0.0) && (czm_inverseNormal3D[1][2] == 0.0) && (czm_inverseNormal3D[2][2] == 1.0) ); }"; const m = new import__.Matrix4( 0, -1, 0, 7, 1, 0, 0, 8, 0, 0, 1, 9, 0, 0, 0, 1 ); expect({ context, fragmentShader: fs, modelMatrix: m }).contextToRender(); }); it("has czm_encodedCameraPositionMCHigh and czm_encodedCameraPositionMCLow", function() { const us = context.uniformState; us.update( createFrameState_default( context, createMockCamera( void 0, void 0, void 0, new import__.Cartesian3(-1e3, 0, 1e5) ) ) ); const fs = "void main() { bool b = (czm_encodedCameraPositionMCHigh + czm_encodedCameraPositionMCLow == vec3(-1000.0, 0.0, 100000.0)); out_FragColor = vec4(b); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_entireFrustum", function() { const us = context.uniformState; us.update(createFrameState_default(context, createMockCamera())); const fs = "void main() { out_FragColor = vec4((czm_entireFrustum.x == 1.0) && (czm_entireFrustum.y == 1000.0)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_frustumPlanes", function() { const us = context.uniformState; us.update(createFrameState_default(context, createMockCamera())); const fs = "void main() { out_FragColor = vec4(equal(czm_frustumPlanes, vec4(2.0, -2.0, -1.0, 1.0))); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_sunPositionWC", function() { const us = context.uniformState; us.update(createFrameState_default(context, createMockCamera())); const fs = "void main() { out_FragColor = vec4(czm_sunPositionWC != vec3(0.0)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_sunPositionColumbusView", function() { const us = context.uniformState; us.update(createFrameState_default(context, createMockCamera())); const fs = "void main() { out_FragColor = vec4(czm_sunPositionColumbusView != vec3(0.0)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_sunDirectionEC", function() { const us = context.uniformState; us.update(createFrameState_default(context, createMockCamera())); const fs = "void main() { out_FragColor = vec4(czm_sunDirectionEC != vec3(0.0)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_sunDirectionWC", function() { const us = context.uniformState; us.update(createFrameState_default(context, createMockCamera())); const fs = "void main() { out_FragColor = vec4(czm_sunDirectionWC != vec3(0.0)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_moonDirectionEC", function() { const us = context.uniformState; us.update(createFrameState_default(context, createMockCamera())); const fs = "void main() { out_FragColor = vec4(czm_moonDirectionEC != vec3(0.0)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_viewerPositionWC", function() { const us = context.uniformState; us.update(createFrameState_default(context, createMockCamera())); const fs = "void main() { out_FragColor = vec4(czm_viewerPositionWC == vec3(0.0)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_frameNumber", function() { const fs = "void main() { out_FragColor = vec4(czm_frameNumber != 0.0); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_morphTime", function() { const fs = "void main() { out_FragColor = vec4(czm_morphTime == 1.0); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_temeToPseudoFixed", function() { const us = context.uniformState; us.update(createFrameState_default(context, createMockCamera())); const fs = "void main() { out_FragColor = vec4( (czm_temeToPseudoFixed[0][0] != 0.0) && (czm_temeToPseudoFixed[1][0] != 0.0) && (czm_temeToPseudoFixed[2][0] == 0.0) && (czm_temeToPseudoFixed[0][1] != 0.0) && (czm_temeToPseudoFixed[1][1] != 0.0) && (czm_temeToPseudoFixed[2][1] == 0.0) && (czm_temeToPseudoFixed[0][2] == 0.0) && (czm_temeToPseudoFixed[1][2] == 0.0) && (czm_temeToPseudoFixed[2][2] == 1.0) ); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_fogDensity", function() { const frameState2 = createFrameState_default( context, createMockCamera( void 0, void 0, void 0, // Provide position and direction because the default position of (0, 0, 0) // will lead to a divide by zero when updating fog below. new import__.Cartesian3(1, 0, 0), new import__.Cartesian3(0, 1, 0) ) ); const fog = new import__.Fog(); fog.density = 0.1; fog.update(frameState2); const us = context.uniformState; us.update(frameState2); const fs = "void main() { out_FragColor = vec4(czm_fogDensity != 0.0);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_fogMinimumBrightness", function() { const frameState2 = createFrameState_default( context, createMockCamera( void 0, void 0, void 0, // Provide position and direction because the default position of (0, 0, 0) // will lead to a divide by zero when updating fog below new import__.Cartesian3(1, 0, 0), new import__.Cartesian3(0, 1, 0) ) ); const fog = new import__.Fog(); fog.minimumBrightness = 0.25; fog.update(frameState2); const us = context.uniformState; us.update(frameState2); const fs = "void main() { out_FragColor = vec4(czm_fogMinimumBrightness == 0.25);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_atmosphereHsbShift", function() { const frameState2 = createFrameState_default(context, createMockCamera()); const atmosphere = frameState2.atmosphere; atmosphere.hueShift = 1; atmosphere.saturationShift = 2; atmosphere.brightnessShift = 3; const us = context.uniformState; us.update(frameState2); const fs = "void main() { out_FragColor = vec4(czm_atmosphereHsbShift == vec3(1.0, 2.0, 3.0));}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_atmosphereLightIntensity", function() { const frameState2 = createFrameState_default(context, createMockCamera()); const atmosphere = frameState2.atmosphere; atmosphere.lightIntensity = 2; const us = context.uniformState; us.update(frameState2); const fs = "void main() { out_FragColor = vec4(czm_atmosphereLightIntensity == 2.0);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_atmosphereRayleighCoefficient", function() { const frameState2 = createFrameState_default(context, createMockCamera()); const atmosphere = frameState2.atmosphere; atmosphere.rayleighCoefficient = new import__.Cartesian3(1, 2, 3); const us = context.uniformState; us.update(frameState2); const fs = "void main() { out_FragColor = vec4(czm_atmosphereRayleighCoefficient == vec3(1.0, 2.0, 3.0));}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_atmosphereRayleighScaleHeight", function() { const frameState2 = createFrameState_default(context, createMockCamera()); const atmosphere = frameState2.atmosphere; atmosphere.rayleighScaleHeight = 100; const us = context.uniformState; us.update(frameState2); const fs = "void main() { out_FragColor = vec4(czm_atmosphereRayleighScaleHeight == 100.0);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_atmosphereMieCoefficient", function() { const frameState2 = createFrameState_default(context, createMockCamera()); const atmosphere = frameState2.atmosphere; atmosphere.mieCoefficient = new import__.Cartesian3(1, 2, 3); const us = context.uniformState; us.update(frameState2); const fs = "void main() { out_FragColor = vec4(czm_atmosphereMieCoefficient == vec3(1.0, 2.0, 3.0));}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_atmosphereMieScaleHeight", function() { const frameState2 = createFrameState_default(context, createMockCamera()); const atmosphere = frameState2.atmosphere; atmosphere.mieScaleHeight = 100; const us = context.uniformState; us.update(frameState2); const fs = "void main() { out_FragColor = vec4(czm_atmosphereMieScaleHeight == 100.0);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_atmosphereMieAnisotropy", function() { const frameState2 = createFrameState_default(context, createMockCamera()); const atmosphere = frameState2.atmosphere; atmosphere.mieAnisotropy = 100; const us = context.uniformState; us.update(frameState2); const fs = "void main() { out_FragColor = vec4(czm_atmosphereMieAnisotropy == 100.0);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_atmosphereDynamicLighting", function() { const frameState2 = createFrameState_default(context, createMockCamera()); const atmosphere = frameState2.atmosphere; const enumValue = import__.DynamicAtmosphereLightingType.SCENE_LIGHT; atmosphere.dynamicLighting = enumValue; const us = context.uniformState; us.update(frameState2); const fs = `void main() { out_FragColor = vec4(czm_atmosphereDynamicLighting == float(${enumValue}));}`; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_pass and czm_passEnvironment", function() { const us = context.uniformState; us.updatePass(import__.Pass.ENVIRONMENT); const fs = "void main() { out_FragColor = vec4(czm_pass == czm_passEnvironment);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_pass and czm_passCompute", function() { const us = context.uniformState; us.updatePass(import__.Pass.COMPUTE); const fs = "void main() { out_FragColor = vec4(czm_pass == czm_passCompute);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_pass and czm_passGlobe", function() { const us = context.uniformState; us.updatePass(import__.Pass.GLOBE); const fs = "void main() { out_FragColor = vec4(czm_pass == czm_passGlobe);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_pass and czm_passTerrainClassification", function() { const us = context.uniformState; us.updatePass(import__.Pass.TERRAIN_CLASSIFICATION); const fs = "void main() { out_FragColor = vec4(czm_pass == czm_passTerrainClassification);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_pass and czm_passCesium3DTileClassification", function() { const us = context.uniformState; us.updatePass(import__.Pass.CESIUM_3D_TILE_CLASSIFICATION); const fs = "void main() { out_FragColor = vec4(czm_pass == czm_passCesium3DTileClassification);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_pass and czm_passOpaque", function() { const us = context.uniformState; us.updatePass(import__.Pass.OPAQUE); const fs = "void main() { out_FragColor = vec4(czm_pass == czm_passOpaque);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_pass and czm_passTranslucent", function() { const us = context.uniformState; us.updatePass(import__.Pass.TRANSLUCENT); const fs = "void main() { out_FragColor = vec4(czm_pass == czm_passTranslucent);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_pass and czm_passOverlay", function() { const us = context.uniformState; us.updatePass(import__.Pass.OVERLAY); const fs = "void main() { out_FragColor = vec4(czm_pass == czm_passOverlay);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_sceneMode", function() { const fs = "void main() { out_FragColor = vec4(czm_sceneMode == 3.0); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_sceneMode2D", function() { const fs = "void main() { out_FragColor = vec4(czm_sceneMode2D == 2.0); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_sceneModeColumbusView", function() { const fs = "void main() { out_FragColor = vec4(czm_sceneModeColumbusView == 1.0); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_sceneMode3D", function() { const fs = "void main() { out_FragColor = vec4(czm_sceneMode3D == 3.0); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_sceneModeMorphing", function() { const fs = "void main() { out_FragColor = vec4(czm_sceneModeMorphing == 0.0); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_eyeHeight", function() { const frameState2 = createFrameState_default(context, createMockCamera()); context.uniformState.update(frameState2); const fs = "void main() { out_FragColor = vec4(czm_eyeHeight == 10.0); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_eyeHeight2D == 0,0 in Scene3D", function() { const fs = "void main() { out_FragColor = vec4(czm_eyeHeight2D.x == 0.0, czm_eyeHeight2D.y == 0.0, 1.0, 1.0); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_eyeHeight2D in Scene2D", function() { const us = context.uniformState; const camera = createCamera_default(); const frustum = new import__.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; camera.frustum = frustum; const frameState2 = createFrameState_default(context, camera); frameState2.mode = import__.SceneMode.SCENE2D; us.update(frameState2); const fs = "void main() { out_FragColor = vec4(czm_eyeHeight2D.x == 2.0, czm_eyeHeight2D.y == 4.0, 1.0, 1.0); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_splitPosition", function() { const fs = "void main() { out_FragColor = vec4(czm_splitPosition == 0.0); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_backgroundColor", function() { const frameState2 = createFrameState_default(context, createMockCamera()); frameState2.backgroundColor = new import__.Color(0, 0.25, 0.75, 1); context.uniformState.update(frameState2); const fs = "void main() { out_FragColor = vec4(czm_backgroundColor.r == 0.0, czm_backgroundColor.g == 0.25, czm_backgroundColor.b == 0.75, czm_backgroundColor.a == 1.0); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_minimumDisableDepthTestDistance", function() { const frameState2 = createFrameState_default(context, createMockCamera()); context.uniformState.update(frameState2); const fs = "void main() { out_FragColor = vec4(czm_minimumDisableDepthTestDistance == 0.0);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_orthographicIn3D", function() { const frameState2 = createFrameState_default(context, createMockCamera()); context.uniformState.update(frameState2); let fs = "void main() { out_FragColor = vec4(czm_orthographicIn3D == 0.0);}"; expect({ context, fragmentShader: fs }).contextToRender(); const frustum = new import__.OrthographicFrustum(); frustum.aspectRatio = 1; frustum.width = 1; frameState2.camera.frustum = frustum; context.uniformState.update(frameState2); fs = "void main() { out_FragColor = vec4(czm_orthographicIn3D == 1.0);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_gamma", function() { context.uniformState.gamma = 1; const fs = "void main() { out_FragColor = vec4(czm_gamma == 1.0);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_lightDirectionEC", function() { const us = context.uniformState; const frameState2 = createFrameState_default(context, createMockCamera()); frameState2.light = new import__.DirectionalLight({ direction: new import__.Cartesian3(0, 0, 1) }); us.update(frameState2); const fs = "void main() { out_FragColor = vec4(czm_lightDirectionEC != vec3(0.0)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_lightDirectionWC", function() { const us = context.uniformState; const frameState2 = createFrameState_default(context, createMockCamera()); frameState2.light = new import__.DirectionalLight({ direction: new import__.Cartesian3(0, 0, 1) }); us.update(frameState2); const fs = "void main() { out_FragColor = vec4(czm_lightDirectionWC == vec3(0.0, 0.0, -1.0)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_lightColor", function() { const us = context.uniformState; const frameState2 = createFrameState_default(context, createMockCamera()); frameState2.light = new import__.DirectionalLight({ direction: new import__.Cartesian3(0, 0, 1), color: new import__.Color(0.25, 0.5, 1), intensity: 2 }); us.update(frameState2); const fs = "void main() { bool b0 = czm_lightColor.x == 0.25; bool b1 = czm_lightColor.y == 0.5; bool b2 = czm_lightColor.z == 1.0; out_FragColor = vec4(b0 && b1 && b2);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_lightColorHdr", function() { const us = context.uniformState; const frameState2 = createFrameState_default(context, createMockCamera()); frameState2.light = new import__.DirectionalLight({ direction: new import__.Cartesian3(0, 0, 1), color: new import__.Color(0.25, 0.5, 1), intensity: 2 }); us.update(frameState2); const fs = "void main() { bool b0 = czm_lightColorHdr.x == 0.5; bool b1 = czm_lightColorHdr.y == 1.0; bool b2 = czm_lightColorHdr.z == 2.0; out_FragColor = vec4(b0 && b1 && b2);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_eyeEllipsoidNormalEC", function() { const { uniformState } = context; const frameState2 = createFrameState_default(context, createMockCamera()); const ellipsoid = new import__.Ellipsoid(1.1, 1.1, 1); frameState2.mapProjection = new import__.GeographicProjection(ellipsoid); uniformState.update(frameState2); const fragmentShader = `void main() { out_FragColor = vec4(czm_eyeEllipsoidNormalEC != vec3(0.0)); }`; expect({ context, fragmentShader }).contextToRender(); }); it("has czm_eyeEllipsoidCurvature", function() { const { uniformState } = context; const frameState2 = createFrameState_default(context, createMockCamera()); const ellipsoid = new import__.Ellipsoid(1, 1, 1); frameState2.mapProjection = new import__.GeographicProjection(ellipsoid); uniformState.update(frameState2); const fragmentShader = `void main() { out_FragColor = vec4(czm_eyeEllipsoidCurvature == vec2(1.0)); }`; expect({ context, fragmentShader }).contextToRender(); }); it("has czm_modelToEnu", function() { const { uniformState } = context; const frameState2 = createFrameState_default(context, createMockCamera()); const ellipsoid = new import__.Ellipsoid(1, 1, 1); frameState2.mapProjection = new import__.GeographicProjection(ellipsoid); uniformState.update(frameState2); const fragmentShader = `void main() { out_FragColor = vec4(czm_modelToEnu != mat4(0.0)); }`; expect({ context, fragmentShader }).contextToRender(); }); it("has czm_enuToModel", function() { const { uniformState } = context; const frameState2 = createFrameState_default(context, createMockCamera()); const ellipsoid = new import__.Ellipsoid(1, 1, 1); frameState2.mapProjection = new import__.GeographicProjection(ellipsoid); uniformState.update(frameState2); const fragmentShader = `void main() { out_FragColor = vec4(czm_enuToModel != mat4(0.0)); }`; expect({ context, fragmentShader }).contextToRender(); }); it("has czm_ellipsoidRadii", function() { const us = context.uniformState; const frameState2 = createFrameState_default(context, createMockCamera()); const ellipsoid = new import__.Ellipsoid(1, 2, 3); frameState2.mapProjection = new import__.GeographicProjection(ellipsoid); us.update(frameState2); const fs = "void main() { bool b0 = czm_ellipsoidRadii.x == 1.0; bool b1 = czm_ellipsoidRadii.y == 2.0; bool b2 = czm_ellipsoidRadii.z == 3.0; out_FragColor = vec4(b0 && b1 && b2);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_ellipsoidInverseRadii", function() { const us = context.uniformState; const frameState2 = createFrameState_default(context, createMockCamera()); const ellipsoid = new import__.Ellipsoid(1, 1 / 2, 1 / 3); frameState2.mapProjection = new import__.GeographicProjection(ellipsoid); us.update(frameState2); const fs = "float roundNumber(float number) { return floor(number + 0.5); }void main() { bool b0 = roundNumber(czm_ellipsoidInverseRadii.x) == 1.0; bool b1 = roundNumber(czm_ellipsoidInverseRadii.y) == 2.0; bool b2 = roundNumber(czm_ellipsoidInverseRadii.z) == 3.0; out_FragColor = vec4(b0 && b1 && b2);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); }, "WebGL" ); // packages/engine/Specs/Renderer/BufferSpec.js var import__2 = __toESM(require_Cesium(), 1); // packages/engine/Specs/createWebglVersionHelper.js function createWebglVersionHelper(createSpecs) { describe("with WebGL 1", function() { createSpecs({ requestWebgl1: true }); }); describe("with WebGL 2", function() { if (typeof WebGL2RenderingContext !== "undefined") { createSpecs(); } }); } // packages/engine/Specs/Renderer/BufferSpec.js describe( "Renderer/Buffer", function() { createWebglVersionHelper(createBufferSpecs); function createBufferSpecs(contextOptions) { let buffer; let buffer2; let context; beforeAll(function() { context = createContext_default(contextOptions); }); afterAll(function() { context.destroyForSpecs(); }); afterEach(function() { if (buffer && !buffer.isDestroyed()) { buffer = buffer.destroy(); } if (buffer2 && !buffer2.isDestroyed()) { buffer2 = buffer2.destroy(); } }); it(`throws when creating a vertex buffer with no context`, function() { expect(function() { buffer = import__2.Buffer.createVertexBuffer({ sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW }); }).toThrowDeveloperError(); }); it(`throws when creating a vertex buffer with an invalid typed array`, function() { expect(function() { buffer = import__2.Buffer.createVertexBuffer({ context, typedArray: {}, usage: import__2.BufferUsage.STATIC_DRAW }); }).toThrowDeveloperError(); }); it(`throws when creating a vertex buffer with both a typed array and size in bytes`, function() { expect(function() { buffer = import__2.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), sizeInBytes: 16, usage: import__2.BufferUsage.STATIC_DRAW }); }).toThrowDeveloperError(); }); it(`throws when creating a vertex buffer without a typed array or size in bytes`, function() { expect(function() { buffer = import__2.Buffer.createVertexBuffer({ context, usage: import__2.BufferUsage.STATIC_DRAW }); }).toThrowDeveloperError(); }); it(`throws when creating a vertex buffer with invalid usage`, function() { expect(function() { buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 16, usage: 0 }); }).toThrowDeveloperError(); }); it(`throws when creating a vertex buffer with size of zero`, function() { expect(function() { buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 0, usage: import__2.BufferUsage.STATIC_DRAW }); }).toThrowDeveloperError(); }); it(`creates vertex buffer`, function() { buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 16, usage: import__2.BufferUsage.STATIC_DRAW }); expect(buffer.sizeInBytes).toEqual(16); expect(buffer.usage).toEqual(import__2.BufferUsage.STATIC_DRAW); }); it(`copies array to a vertex buffer`, function() { const sizeInBytes = 3 * Float32Array.BYTES_PER_ELEMENT; const vertices = new ArrayBuffer(sizeInBytes); const positions = new Float32Array(vertices); positions[0] = 1; positions[1] = 2; positions[2] = 3; buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes, usage: import__2.BufferUsage.STATIC_DRAW }); buffer.copyFromArrayView(vertices); }); it(`can create a vertex buffer from a typed array`, function() { const typedArray = new Float32Array(3); typedArray[0] = 1; typedArray[1] = 2; typedArray[2] = 3; buffer = import__2.Buffer.createVertexBuffer({ context, typedArray, usage: import__2.BufferUsage.STATIC_DRAW }); expect(buffer.sizeInBytes).toEqual(typedArray.byteLength); expect(buffer.usage).toEqual(import__2.BufferUsage.STATIC_DRAW); }); it(`can create a vertex buffer from a size in bytes`, function() { buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW }); expect(buffer.sizeInBytes).toEqual(4); expect(buffer.usage).toEqual(import__2.BufferUsage.STATIC_DRAW); }); it(`throws when creating an index buffer with no context`, function() { expect(function() { buffer = import__2.Buffer.createIndexBuffer({ sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW, indexDatatype: import__2.IndexDatatype.UNSIGNED_SHORT }); }).toThrowDeveloperError(); }); it(`throws when creating an index buffer with an invalid typed array`, function() { expect(function() { buffer = import__2.Buffer.createIndexBuffer({ context, typedArray: {}, usage: import__2.BufferUsage.STATIC_DRAW, indexDatatype: import__2.IndexDatatype.UNSIGNED_SHORT }); }).toThrowDeveloperError(); }); it(`throws when creating an index buffer with both a typed array and size in bytes`, function() { expect(function() { buffer = import__2.Buffer.createIndexBuffer({ context, typedArray: new Uint16Array([0, 1, 2, 0, 2, 3]), sizeInBytes: 12, usage: import__2.BufferUsage.STATIC_DRAW, indexDatatype: import__2.IndexDatatype.UNSIGNED_SHORT }); }).toThrowDeveloperError(); }); it(`throws when creating an index buffer without a typed array or size in bytes`, function() { expect(function() { buffer = import__2.Buffer.createIndexBuffer({ context, usage: import__2.BufferUsage.STATIC_DRAW, indexDatatype: import__2.IndexDatatype.UNSIGNED_SHORT }); }).toThrowDeveloperError(); }); it(`throws when creating an index buffer with invalid usage`, function() { expect(function() { buffer = import__2.Buffer.createIndexBuffer({ context, sizeInBytes: 16, usage: "invalid", indexDatatype: import__2.IndexDatatype.UNSIGNED_SHORT }); }).toThrowDeveloperError(); }); it(`throws when creating an index buffer with invalid index data type`, function() { expect(function() { buffer = import__2.Buffer.createIndexBuffer({ context, sizeInBytes: 16, usage: import__2.BufferUsage.STATIC_DRAW, indexDatatype: "invalid" }); }).toThrowDeveloperError(); }); it(`throws when creating an index buffer with size of zero`, function() { expect(function() { buffer = import__2.Buffer.createIndexBuffer({ context, sizeInBytes: 0, usage: import__2.BufferUsage.STATIC_DRAW, indexDatatype: import__2.IndexDatatype.UNSIGNED_SHORT }); }).toThrowDeveloperError(); }); it(`creates index buffer`, function() { buffer = import__2.Buffer.createIndexBuffer({ context, sizeInBytes: 6, usage: import__2.BufferUsage.STREAM_DRAW, indexDatatype: import__2.IndexDatatype.UNSIGNED_SHORT }); expect(buffer.sizeInBytes).toEqual(6); expect(buffer.usage).toEqual(import__2.BufferUsage.STREAM_DRAW); expect(buffer.indexDatatype).toEqual(import__2.IndexDatatype.UNSIGNED_SHORT); expect(buffer.bytesPerIndex).toEqual(2); expect(buffer.numberOfIndices).toEqual(3); }); it(`copies array to an index buffer`, function() { const sizeInBytes = 3 * Uint16Array.BYTES_PER_ELEMENT; const elements = new ArrayBuffer(sizeInBytes); const indices = new Uint16Array(elements); indices[0] = 1; indices[1] = 2; indices[2] = 3; buffer = import__2.Buffer.createIndexBuffer({ context, sizeInBytes, usage: import__2.BufferUsage.STATIC_DRAW, indexDatatype: import__2.IndexDatatype.UNSIGNED_SHORT }); buffer.copyFromArrayView(elements); }); it(`can create an index buffer from a typed array`, function() { const typedArray = new Uint16Array(3); typedArray[0] = 1; typedArray[1] = 2; typedArray[2] = 3; buffer = import__2.Buffer.createIndexBuffer({ context, typedArray, usage: import__2.BufferUsage.STATIC_DRAW, indexDatatype: import__2.IndexDatatype.UNSIGNED_SHORT }); expect(buffer.sizeInBytes).toEqual(typedArray.byteLength); expect(buffer.usage).toEqual(import__2.BufferUsage.STATIC_DRAW); expect(buffer.indexDatatype).toEqual(import__2.IndexDatatype.UNSIGNED_SHORT); }); it(`can create an index buffer from a size in bytes`, function() { buffer = import__2.Buffer.createIndexBuffer({ context, sizeInBytes: 6, usage: import__2.BufferUsage.STATIC_DRAW, indexDatatype: import__2.IndexDatatype.UNSIGNED_SHORT }); expect(buffer.sizeInBytes).toEqual(6); expect(buffer.usage).toEqual(import__2.BufferUsage.STATIC_DRAW); expect(buffer.indexDatatype).toEqual(import__2.IndexDatatype.UNSIGNED_SHORT); }); it(`getBufferData throws without WebGL 2`, function() { if (context.webgl2) { return; } buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW }); const array = new Uint8Array(4); expect(function() { buffer.getBufferData(array); }).toThrowDeveloperError(); }); it(`getBufferData throws without arrayView`, function() { if (!context.webgl2) { return; } buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW }); expect(function() { buffer.getBufferData(void 0); }).toThrowDeveloperError(); }); it(`getBufferData throws with invalid sourceOffset`, function() { if (!context.webgl2) { return; } buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW }); const array = new Uint8Array(4); expect(function() { buffer.getBufferData(array, -1); }).toThrowDeveloperError(); expect(function() { buffer.getBufferData(array, 5); }).toThrowDeveloperError(); }); it(`getBufferData throws with invalid destinationOffset`, function() { if (!context.webgl2) { return; } buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW }); const array = new Uint8Array(4); expect(function() { buffer.getBufferData(array, 0, -1); }).toThrowDeveloperError(); expect(function() { buffer.getBufferData(array, 0, 5); }).toThrowDeveloperError(); }); it(`getBufferData throws with invalid length`, function() { if (!context.webgl2) { return; } buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW }); const array = new Uint8Array(4); expect(function() { buffer.getBufferData(array, 2, 0, 4); }).toThrowDeveloperError(); expect(function() { buffer.getBufferData(array, 0, 2, 4); }).toThrowDeveloperError(); }); it(`getBufferData reads from vertex buffer`, function() { if (!context.webgl2) { return; } const typedArray = new Uint8Array(4); typedArray[0] = 1; typedArray[1] = 2; typedArray[2] = 3; typedArray[3] = 4; buffer = import__2.Buffer.createVertexBuffer({ context, typedArray, usage: import__2.BufferUsage.STATIC_DRAW }); const destArray = new Uint8Array(4); buffer.getBufferData(destArray); expect(destArray).toEqual(typedArray); }); it(`getBufferData reads from index buffer`, function() { if (!context.webgl2) { return; } const typedArray = new Uint16Array(3); typedArray[0] = 1; typedArray[1] = 2; typedArray[2] = 3; buffer = import__2.Buffer.createIndexBuffer({ context, typedArray, usage: import__2.BufferUsage.STATIC_DRAW, indexDatatype: import__2.IndexDatatype.UNSIGNED_SHORT }); const destArray = new Uint16Array(3); buffer.getBufferData(destArray); expect(destArray).toEqual(typedArray); }); it(`copyFromBuffer throws without WebGL 2`, function() { if (context.webgl2) { return; } buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW }); buffer2 = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW }); expect(function() { buffer.copyFromBuffer(buffer2, 0, 0, 4); }).toThrowDeveloperError(); }); it(`copyFromBuffer throws without readBuffer`, function() { if (!context.webgl2) { return; } buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW }); expect(function() { buffer.copyFromBuffer(void 0, 0, 0, 4); }).toThrowDeveloperError(); }); it(`copyFromBuffer throws with invalid readOffset`, function() { if (!context.webgl2) { return; } buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW }); buffer2 = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW }); expect(function() { buffer.copyFromBuffer(buffer2, void 0, 0, 4); }).toThrowDeveloperError(); expect(function() { buffer.copyFromBuffer(buffer2, -1, 0, 4); }).toThrowDeveloperError(); expect(function() { buffer.copyFromBuffer(buffer2, 5, 0, 4); }).toThrowDeveloperError(); }); it(`copyFromBuffer throws with invalid writeOffset`, function() { if (!context.webgl2) { return; } buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW }); buffer2 = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW }); expect(function() { buffer.copyFromBuffer(buffer2, 0, void 0, 4); }).toThrowDeveloperError(); expect(function() { buffer.copyFromBuffer(buffer2, 0, -1, 4); }).toThrowDeveloperError(); expect(function() { buffer.copyFromBuffer(buffer2, 0, 5, 4); }).toThrowDeveloperError(); }); it(`copyFromBuffer throws with invalid sizeInBytes`, function() { if (!context.webgl2) { return; } buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW }); buffer2 = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW }); expect(function() { buffer.copyFromBuffer(buffer2, 0, 0, void 0); }).toThrowDeveloperError(); expect(function() { buffer.copyFromBuffer(buffer2, 0, 0, -1); }).toThrowDeveloperError(); expect(function() { buffer.copyFromBuffer(buffer2, 0, 0, 0); }).toThrowDeveloperError(); expect(function() { buffer.copyFromBuffer(buffer2, 0, 0, 5); }).toThrowDeveloperError(); }); it(`copyFromBuffer throws with one index buffer and the other is not an index buffer`, function() { if (!context.webgl2) { return; } const typedArray = new Uint16Array([0, 1, 2, 3, 4]); buffer = import__2.Buffer.createIndexBuffer({ context, typedArray, usage: import__2.BufferUsage.STATIC_DRAW, indexDatatype: import__2.IndexDatatype.UNSIGNED_SHORT }); const typedArray2 = new Float32Array([5, 6, 7, 8, 9]); buffer2 = import__2.Buffer.createVertexBuffer({ context, typedArray: typedArray2, usage: import__2.BufferUsage.STATIC_DRAW }); expect(function() { buffer2.copyFromBuffer(buffer, 0, 0, typedArray.byteLength); }).toThrowDeveloperError(); }); it(`copyFromBuffer throws when readBuffer is the same buffer and copy range overlaps`, function() { if (!context.webgl2) { return; } buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 4, usage: import__2.BufferUsage.STATIC_DRAW }); expect(function() { buffer.copyFromBuffer(buffer, 0, 1, 2); }).toThrowDeveloperError(); expect(function() { buffer.copyFromBuffer(buffer, 1, 0, 2); }).toThrowDeveloperError(); }); it(`copyFromBuffer with vertex buffers`, function() { if (!context.webgl2) { return; } const typedArray = new Float32Array([0, 1, 2, 3, 4]); buffer = import__2.Buffer.createVertexBuffer({ context, typedArray, usage: import__2.BufferUsage.STATIC_DRAW }); const typedArray2 = new Float32Array([5, 6, 7, 8, 9]); buffer2 = import__2.Buffer.createVertexBuffer({ context, typedArray: typedArray2, usage: import__2.BufferUsage.STATIC_DRAW }); const destArray = new Float32Array(5); buffer.getBufferData(destArray); expect(destArray).toEqual(typedArray); buffer2.getBufferData(destArray); expect(destArray).toEqual(typedArray2); buffer2.copyFromBuffer(buffer, 0, 0, typedArray.byteLength); buffer2.getBufferData(destArray); expect(destArray).toEqual(typedArray); }); it(`copyFromBuffer with index buffers`, function() { if (!context.webgl2) { return; } const typedArray = new Uint16Array([0, 1, 2, 3, 4]); buffer = import__2.Buffer.createIndexBuffer({ context, typedArray, usage: import__2.BufferUsage.STATIC_DRAW, indexDatatype: import__2.IndexDatatype.UNSIGNED_SHORT }); const typedArray2 = new Uint16Array([5, 6, 7, 8, 9]); buffer2 = import__2.Buffer.createIndexBuffer({ context, typedArray: typedArray2, usage: import__2.BufferUsage.STATIC_DRAW, indexDatatype: import__2.IndexDatatype.UNSIGNED_SHORT }); const destArray = new Uint16Array(5); buffer.getBufferData(destArray); expect(destArray).toEqual(typedArray); buffer2.getBufferData(destArray); expect(destArray).toEqual(typedArray2); buffer2.copyFromBuffer(buffer, 0, 0, typedArray.byteLength); buffer2.getBufferData(destArray); expect(destArray).toEqual(typedArray); }); it(`destroys`, function() { const b = import__2.Buffer.createIndexBuffer({ context, sizeInBytes: 3, usage: import__2.BufferUsage.STATIC_DRAW, indexDatatype: import__2.IndexDatatype.UNSIGNED_BYTE }); expect(b.isDestroyed()).toEqual(false); b.destroy(); expect(b.isDestroyed()).toEqual(true); }); it(`fails to provide an array view`, function() { buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 3, usage: import__2.BufferUsage.STATIC_DRAW }); expect(function() { buffer.copyFromArrayView(); }).toThrowDeveloperError(); }); it(`fails to copy a large array view`, function() { buffer = import__2.Buffer.createVertexBuffer({ context, sizeInBytes: 3, usage: import__2.BufferUsage.STATIC_DRAW }); const elements = new ArrayBuffer(3); expect(function() { buffer.copyFromArrayView(elements, 1); }).toThrowDeveloperError(); }); it(`fails to destroy`, function() { const b = import__2.Buffer.createIndexBuffer({ context, sizeInBytes: 3, usage: import__2.BufferUsage.STATIC_DRAW, indexDatatype: import__2.IndexDatatype.UNSIGNED_BYTE }); b.destroy(); expect(function() { b.destroy(); }).toThrowDeveloperError(); }); } }, "WebGL" ); // packages/engine/Specs/Renderer/BuiltinFunctionsSpec.js var import__3 = __toESM(require_Cesium(), 1); describe( "Renderer/BuiltinFunctions", function() { let context; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); it("has czm_transpose (2x2)", function() { const fs = "void main() { mat2 m = mat2(1.0, 2.0, 3.0, 4.0); mat2 mt = mat2(1.0, 3.0, 2.0, 4.0); out_FragColor = vec4(czm_transpose(m) == mt); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_transpose (3x3)", function() { const fs = "void main() { mat3 m = mat3(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); mat3 mt = mat3(1.0, 4.0, 7.0, 2.0, 5.0, 8.0, 3.0, 6.0, 9.0); out_FragColor = vec4(czm_transpose(m) == mt); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_transpose (4x4)", function() { const fs = "void main() { mat4 m = mat4(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0); mat4 mt = mat4(1.0, 5.0, 9.0, 13.0, 2.0, 6.0, 10.0, 14.0, 3.0, 7.0, 11.0, 15.0, 4.0, 8.0, 12.0, 16.0); out_FragColor = vec4(czm_transpose(m) == mt); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_eyeToWindowCoordinates", function() { const camera = createCamera_default(); camera.frustum.near = 1; const canvas = context.canvas; const width = canvas.clientWidth; const height = canvas.clientHeight; const vp = new import__3.BoundingRectangle(0, 0, width, height); context.uniformState.viewport = vp; context.uniformState.update(createFrameState_default(context, camera)); const fs = "void main() { float z = czm_projection[3][2] / czm_projection[2][2]; float x = z / czm_projection[0][0]; float y = z / czm_projection[1][1]; vec4 pointEC = vec4(x, y, z, 1.0); vec2 fragCoord = vec2(0.0, 0.0); vec4 actual = czm_eyeToWindowCoordinates(pointEC); vec2 diff = actual.xy - fragCoord; out_FragColor = vec4(all(lessThan(diff, vec2(czm_epsilon6))));}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_windowToEyeCoordinates", function() { const camera = createCamera_default(); camera.frustum.near = 1; const canvas = context.canvas; const width = canvas.clientWidth; const height = canvas.clientHeight; const vp = new import__3.BoundingRectangle(0, 0, width, height); context.uniformState.viewport = vp; context.uniformState.update(createFrameState_default(context, camera)); let fs = "void main() { float z = czm_projection[3][2] / czm_projection[2][2]; float x = z / czm_projection[0][0]; float y = z / czm_projection[1][1]; vec3 pointEC = vec3(x, y, z); vec4 fragCoord = vec4(0.0, 0.0, 0.0, -z); vec4 actual = czm_windowToEyeCoordinates(fragCoord); vec3 diff = actual.xyz - pointEC; out_FragColor = vec4(all(lessThan(diff, vec3(czm_epsilon6))));}"; expect({ context, fragmentShader: fs }).contextToRender(); fs = "void main() { float z = czm_projection[3][2] / czm_projection[2][2]; float x = z / czm_projection[0][0]; float y = z / czm_projection[1][1]; vec3 pointEC = vec3(x, y, z); vec4 actual = czm_windowToEyeCoordinates(vec2(0.0, 0.0), 0.0); vec3 diff = actual.xyz - pointEC; out_FragColor = vec4(all(lessThan(diff, vec3(czm_epsilon6))));}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_planeDistance", function() { let fs = "void main() { vec4 plane = vec4(1.0, 0.0, 0.0, 0.0); vec3 point = vec3(1.0, 0.0, 0.0); float expected = 1.0; float actual = czm_planeDistance(plane, point); out_FragColor = vec4(actual == expected); }"; expect({ context, fragmentShader: fs }).contextToRender(); fs = "void main() { vec4 plane = vec4(1.0, 0.0, 0.0, 0.0); vec3 point = vec3(1.0, 0.0, 0.0); float expected = 1.0; float actual = czm_planeDistance(plane.xyz, plane.w, point); out_FragColor = vec4(actual == expected); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_lineDistance", function() { const fs = "void main() { vec2 point1 = vec2(0.0, 0.0); vec2 point2 = vec2(1.0, 0.0); vec2 point = vec2(0.5, 1.0); float expected = 1.0; float actual = czm_lineDistance(point1, point2, point); out_FragColor = vec4(actual == expected); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_tangentToEyeSpaceMatrix", function() { const fs = "void main() { vec3 tangent = vec3(1.0, 0.0, 0.0); vec3 bitangent = vec3(0.0, 1.0, 0.0); vec3 normal = vec3(0.0, 0.0, 1.0); mat3 expected = mat3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0); mat3 actual = czm_tangentToEyeSpaceMatrix(normal, tangent, bitangent); out_FragColor = vec4(actual == expected); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_translateRelativeToEye", function() { const camera = createCamera_default({ offset: new import__3.Cartesian3(1, 2, 3) }); context.uniformState.update(createFrameState_default(context, camera)); const p = new import__3.Cartesian3(6, 5, 4); const encoded = import__3.EncodedCartesian3.fromCartesian(p); const uniformMap = { u_high: function() { return encoded.high; }, u_low: function() { return encoded.low; } }; const fs = "uniform vec3 u_high;uniform vec3 u_low;void main() { vec4 p = czm_translateRelativeToEye(u_high, u_low); out_FragColor = vec4(p == vec4(5.0, 3.0, 1.0, 1.0)); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("has czm_antialias", function() { const fs = "void main() { vec4 color0 = vec4(1.0, 0.0, 0.0, 1.0); vec4 color1 = vec4(0.0, 1.0, 0.0, 1.0); vec4 result = czm_antialias(color0, color1, color1, 0.5); out_FragColor = vec4(result == color1);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("czm_pointAlongRay: point at ray origin", function() { const fs = "void main() { out_FragColor = vec4(czm_pointAlongRay(czm_ray(vec3(0.0), vec3(1.0, 0.0, 0.0)), 0.0) == vec3(0.0)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("czm_pointAlongRay: point in front of ray origin", function() { const fs = "void main() { out_FragColor = vec4(czm_pointAlongRay(czm_ray(vec3(0.0), vec3(1.0, 0.0, 0.0)), 2.0) == vec3(2.0, 0.0, 0.0)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("czm_pointAlongRay: point behind ray origin", function() { const fs = "void main() { out_FragColor = vec4(czm_pointAlongRay(czm_ray(vec3(0.0), vec3(0.0, 1.0, 0.0)), -2.0) == vec3(0.0, -2.0, 0.0)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_octDecode(vec2)", function() { const fs = "void main() { out_FragColor = vec4(all(lessThanEqual(abs(czm_octDecode(vec2(128.0, 128.0)) - vec3(0.0, 0.0, 1.0)), vec3(0.01)))); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_octDecode(float)", function() { const fs = "void main() { out_FragColor = vec4(all(lessThanEqual(abs(czm_octDecode(32896.0) - vec3(0.0, 0.0, 1.0)), vec3(0.01)))); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_octDecode(vec2, vec3, vec3, vec3)", function() { const fs = "void main() { vec3 a, b, c; czm_octDecode(vec2(8454016.0, 8421631.0), a, b, c); bool decoded = all(lessThanEqual(abs(a - vec3(1.0, 0.0, 0.0)), vec3(0.01))); decoded = decoded && all(lessThanEqual(abs(b - vec3(0.0, 1.0, 0.0)), vec3(0.01))); decoded = decoded && all(lessThanEqual(abs(c - vec3(0.0, 0.0, 1.0)), vec3(0.01))); out_FragColor = vec4(decoded);}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_decompressTextureCoordinates", function() { const fs = "void main() { vec2 coords = czm_decompressTextureCoordinates(8386559.0); vec2 expected = vec2(0.4998779, 0.4998779); out_FragColor = vec4(all(lessThanEqual(abs(coords - expected), vec2(0.00000005)))); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has signNotZero : float", function() { const fs = "void main() { out_FragColor = vec4(czm_signNotZero(0.0) == 1.0, czm_signNotZero(5.0) == 1.0, czm_signNotZero(-5.0) == -1.0, 1.0); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has signNotZero : vec2", function() { const fs = "void main() { out_FragColor = vec4(czm_signNotZero(vec2(0.0, 0.0)) == vec2(1.0, 1.0), czm_signNotZero(vec2(1.0, 1.0)) == vec2(1.0, 1.0), czm_signNotZero(vec2(-1.0, -1.0)) == vec2(-1.0, -1.0), czm_signNotZero(vec2(-1.0, 0.0)) == vec2(-1.0, 1.0)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has signNotZero : vec3", function() { const fs = "void main() { out_FragColor = vec4(czm_signNotZero(vec3(0.0, 0.0, 0.0)) == vec3(1.0, 1.0, 1.0), czm_signNotZero(vec3(1.0, 1.0, 1.0)) == vec3(1.0, 1.0, 1.0), czm_signNotZero(vec3(-1.0, -1.0, -1.0)) == vec3(-1.0, -1.0, -1.0), czm_signNotZero(vec3(-1.0, 0.0, 1.0)) == vec3(-1.0, 1.0, 1.0)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has signNotZero : vec4", function() { const fs = "void main() { out_FragColor = vec4(czm_signNotZero(vec4(0.0, 0.0, 0.0, 0.0)) == vec4(1.0), czm_signNotZero(vec4(1.0, 1.0, 1.0, 1.0)) == vec4(1.0), czm_signNotZero(vec4(-1.0, -1.0, -1.0, -1.0)) == vec4(-1.0), czm_signNotZero(vec4(-1.0, 0.0, 1.0, -10.0)) == vec4(-1.0, 1.0, 1.0, -1.0)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_cosineAndSine in all 4 quadrants", function() { const fs = "bool isBounded(float value, float min, float max) { return ((value < max) && (value > min)); }void main() { out_FragColor = vec4(isBounded(czm_cosineAndSine(czm_piOverFour).x, 0.707106, 0.707107) && isBounded(czm_cosineAndSine(czm_piOverFour).y, 0.707106, 0.707107), isBounded(czm_cosineAndSine(czm_pi - czm_piOverFour).x, -0.707107, -0.707106) && isBounded(czm_cosineAndSine(czm_pi - czm_piOverFour).y, 0.707106, 0.707107), isBounded(czm_cosineAndSine(-czm_piOverFour).x, 0.707106, 0.707107) && isBounded(czm_cosineAndSine(-czm_piOverFour).y, -0.707107, -0.707106), isBounded(czm_cosineAndSine(-czm_pi + czm_piOverFour).x, -0.707107, -0.707106) && isBounded(czm_cosineAndSine(-czm_pi + czm_piOverFour).y, -0.707107, -0.707106)); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("can calculate nearFarScalar", function() { const fs = "vec4 testNearFarScalar = vec4(10.0, 1.0, 20.0, 0.0);void main() { out_FragColor = vec4(czm_nearFarScalar(testNearFarScalar, 5.0 * 5.0) == 1.0, czm_nearFarScalar(testNearFarScalar, 10.0 * 10.0) == 1.0, czm_nearFarScalar(testNearFarScalar, 20.0 * 20.0) == 0.0, czm_nearFarScalar(testNearFarScalar, 50.0 * 50.0) == 0.0); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_cascadeColor", function() { const fs = "void main() { out_FragColor = vec4(all(equal(czm_cascadeColor(vec4(0.5)), vec4(1.0, 0.5, 1.0, 2.0))));}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_approximateSphericalCoordinates", function() { const fs = "void main() { out_FragColor = vec4(all(equal(czm_approximateSphericalCoordinates(vec3(1.0, 0.0, 0.0)), vec2(0.0, 0.0))));}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_transformPlane", function() { const fs = "void main() { mat4 uniformScale2 = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 1.0); out_FragColor = vec4(all(equal(czm_transformPlane(vec4(1.0, 0.0, 0.0, 10.0), uniformScale2), vec4(1.0, 0.0, 0.0, 20.0))));}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_unpackFloat", function() { let packed = import__3.Cartesian4.packFloat(1); packed = import__3.Cartesian4.divideByScalar(packed, 255, packed); const vec4 = `vec4(${packed.x}, ${packed.y}, ${packed.z}, ${packed.w})`; const fs = `${"void main() { out_FragColor = vec4(czm_unpackFloat("}${vec4}));}`; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_branchFreeTernary", function() { let fs = "void main() { out_FragColor = vec4(czm_branchFreeTernary(true, 1.0, 0.0));}"; expect({ context, fragmentShader: fs }).contextToRender(); fs = "void main() { out_FragColor = vec4(czm_branchFreeTernary(true, vec2(1.0), vec2(0.0)), 1.0, 1.0);}"; expect({ context, fragmentShader: fs }).contextToRender(); fs = "void main() { out_FragColor = vec4(czm_branchFreeTernary(true, vec3(1.0), vec3(0.0)), 1.0);}"; expect({ context, fragmentShader: fs }).contextToRender(); fs = "void main() { out_FragColor = czm_branchFreeTernary(true, vec4(1.0), vec4(0.0));}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has czm_fastApproximateAtan", function() { const fsAtan = "void main() { out_FragColor = vec4(czm_fastApproximateAtan(0.0) == 0.0);}"; expect({ context, fragmentShader: fsAtan }).contextToRender(); const fsAtan2 = "void main() { out_FragColor = vec4(czm_fastApproximateAtan(1.0, 0.0) == 0.0);}"; expect({ context, fragmentShader: fsAtan2 }).contextToRender(); }); }, "WebGL" ); // packages/engine/Specs/Renderer/ClearCommandSpec.js var import__4 = __toESM(require_Cesium(), 1); describe("Renderer/ClearCommand", function() { it("constructs with defaults", function() { const c = new import__4.ClearCommand(); expect(c.color).toBeUndefined(); expect(c.depth).toBeUndefined(); expect(c.stencil).toBeUndefined(); expect(c.renderState).toBeUndefined(); expect(c.framebuffer).toBeUndefined(); }); it("constructs with options", function() { const renderState = {}; const framebuffer2 = {}; const c = new import__4.ClearCommand({ color: new import__4.Color(1, 2, 3, 4), depth: 1, stencil: 2, renderState, framebuffer: framebuffer2 }); expect(c.color).toEqual(new import__4.Color(1, 2, 3, 4)); expect(c.depth).toEqual(1); expect(c.stencil).toEqual(2); expect(c.renderState).toBe(renderState); expect(c.framebuffer).toBe(framebuffer2); }); it("ClearCommand.ALL to have defaults", function() { expect(import__4.ClearCommand.ALL.color).toEqual(new import__4.Color(0, 0, 0, 0)); expect(import__4.ClearCommand.ALL.depth).toEqual(1); expect(import__4.ClearCommand.ALL.stencil).toEqual(0); expect(import__4.ClearCommand.ALL.renderState).toBeUndefined(); expect(import__4.ClearCommand.ALL.framebuffer).toBeUndefined(); }); }); // packages/engine/Specs/Renderer/ClearSpec.js var import__5 = __toESM(require_Cesium(), 1); describe( "Renderer/Clear", function() { let context; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); it("default clear", function() { import__5.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); }); it("clears to white", function() { import__5.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); const command = new import__5.ClearCommand({ color: import__5.Color.WHITE }); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); }); it("clears with a color mask", function() { import__5.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); const command = new import__5.ClearCommand({ color: import__5.Color.WHITE, renderState: import__5.RenderState.fromCache({ colorMask: { red: true, green: false, blue: true, alpha: true } }) }); command.execute(context); expect(context).toReadPixels([255, 0, 255, 255]); }); it("clears with scissor test", function() { const command = new import__5.ClearCommand({ color: import__5.Color.WHITE }); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); command.color = import__5.Color.BLACK; command.renderState = import__5.RenderState.fromCache({ scissorTest: { enabled: true, rectangle: new import__5.BoundingRectangle() } }); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); command.renderState = import__5.RenderState.fromCache({ scissorTest: { enabled: true, rectangle: new import__5.BoundingRectangle(0, 0, 1, 1) } }); command.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); }); it("clears a framebuffer color attachment", function() { const colorTexture = new import__5.Texture({ context, width: 1, height: 1 }); let framebuffer2 = new import__5.Framebuffer({ context, colorTextures: [colorTexture] }); const command = new import__5.ClearCommand({ color: new import__5.Color(0, 1, 0, 1), framebuffer: framebuffer2 }); command.execute(context); expect({ context, framebuffer: framebuffer2 }).toReadPixels([0, 255, 0, 255]); framebuffer2 = framebuffer2.destroy(); }); it("fails to read pixels (width)", function() { expect(function() { expect( context.readPixels({ width: -1 }) ).toEqual([0, 0, 0, 0]); }).toThrowDeveloperError(); }); it("fails to read pixels (height)", function() { expect(function() { expect( context.readPixels({ height: -1 }) ).toEqual([0, 0, 0, 0]); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Renderer/ComputeCommandSpec.js var import__6 = __toESM(require_Cesium(), 1); // Specs/createScene.js var import_engine6 = __toESM(require_Cesium(), 1); function createScene(options) { options = (0, import_engine6.defaultValue)(options, {}); const debugWidth = window.debugCanvasWidth; const debugHeight = (0, import_engine6.defaultValue)( window.debugCanvasHeight, window.debugCanvasWidth ); const canvas = (0, import_engine6.defined)(options.canvas) ? options.canvas : createCanvas_default(debugWidth, debugHeight); options.canvas = void 0; options = (0, import_engine6.clone)(options, true); options.canvas = canvas; options.contextOptions = (0, import_engine6.defaultValue)(options.contextOptions, {}); const contextOptions = options.contextOptions; contextOptions.webgl = (0, import_engine6.defaultValue)(contextOptions.webgl, {}); contextOptions.webgl.antialias = (0, import_engine6.defaultValue)( contextOptions.webgl.antialias, false ); contextOptions.webgl.stencil = (0, import_engine6.defaultValue)( contextOptions.webgl.stencil, true ); if (!!window.webglStub) { contextOptions.getWebGLStub = getWebGLStub_default; } const scene2 = new import_engine6.Scene(options); scene2.highDynamicRange = false; if (!!window.webglValidation) { const context = scene2.context; context.validateShaderProgram = true; context.validateFramebuffer = true; context.logShaderCompilation = true; context.throwOnWebGLError = true; } scene2.destroyForSpecs = function() { const canvas2 = this.canvas; this.destroy(); document.body.removeChild(canvas2); }; scene2.renderForSpecs = function(time2) { this.initializeFrame(); this.render(time2); }; scene2.pickForSpecs = function() { this.pick(new import_engine6.Cartesian2(0, 0)); }; scene2.rethrowRenderErrors = (0, import_engine6.defaultValue)(options.rethrowRenderErrors, true); return scene2; } var createScene_default = createScene; // packages/engine/Specs/Renderer/ComputeCommandSpec.js describe( "Renderer/ComputeCommand", function() { let scene2; let context; beforeAll(function() { scene2 = createScene_default(); context = scene2.context; }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.primitives.removeAll(); }); function CommandMockPrimitive(command) { this.update = function(frameState2) { frameState2.commandList.push(command); }; this.destroy = function() { }; this.isDestroyed = function() { return false; }; } it("throws if no shader is provided", function() { const outputTexture = new import__6.Texture({ context, width: 1, height: 1, pixelFormat: import__6.PixelFormat.RGBA }); const computeCommand = new import__6.ComputeCommand({ outputTexture }); scene2.primitives.add(new CommandMockPrimitive(computeCommand)); expect(function() { scene2.renderForSpecs(); }).toThrowDeveloperError(); }); it("throws if no output texture is provided", function() { const computeCommand = new import__6.ComputeCommand({ fragmentShaderSource: "void main() { out_FragColor = vec4(1.0); }" }); scene2.primitives.add(new CommandMockPrimitive(computeCommand)); expect(function() { scene2.renderForSpecs(); }).toThrowDeveloperError(); }); it("renderer resources are preserved or destroyed based on the persists flag", function() { const vertexShader = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fragmentShader = "void main() { out_FragColor = vec4(1.0); }"; const shaderProgram = import__6.ShaderProgram.fromCache({ context, vertexShaderSource: vertexShader, fragmentShaderSource: fragmentShader, attributeLocations: { position: 0 } }); const vertexArray = new import__6.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__6.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__6.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); const outputTexture = new import__6.Texture({ context, width: 1, height: 1, pixelFormat: import__6.PixelFormat.RGBA }); const computeCommand = new import__6.ComputeCommand({ vertexArray, shaderProgram, outputTexture }); computeCommand.persists = true; scene2.primitives.add(new CommandMockPrimitive(computeCommand)); scene2.renderForSpecs(); context.shaderCache.destroyReleasedShaderPrograms(); scene2.primitives.removeAll(); expect(shaderProgram.isDestroyed()).toEqual(false); expect(vertexArray.isDestroyed()).toEqual(false); expect(outputTexture.isDestroyed()).toEqual(false); computeCommand.persists = false; scene2.primitives.add(new CommandMockPrimitive(computeCommand)); scene2.renderForSpecs(); context.shaderCache.destroyReleasedShaderPrograms(); scene2.primitives.removeAll(); expect(shaderProgram.isDestroyed()).toEqual(true); expect(vertexArray.isDestroyed()).toEqual(true); expect(outputTexture.isDestroyed()).toEqual(false); }); it("renders to a texture and draws that texture to the screen", function() { const outputTexture = new import__6.Texture({ context, width: 1, height: 1, pixelFormat: import__6.PixelFormat.RGBA }); const computeCommand = new import__6.ComputeCommand({ fragmentShaderSource: "void main() { out_FragColor = vec4(1.0); }", outputTexture }); const viewportQuad = new import__6.ViewportQuad(); viewportQuad.rectangle = new import__6.BoundingRectangle(0, 0, 1, 1); viewportQuad.material = import__6.Material.fromType(import__6.Material.ImageType); viewportQuad.material.uniforms.image = outputTexture; expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(new CommandMockPrimitive(computeCommand)); scene2.primitives.add(viewportQuad); expect(scene2).notToRender([0, 0, 0, 255]); }); }, "WebGL" ); // packages/engine/Specs/Renderer/ContextSpec.js var import__7 = __toESM(require_Cesium(), 1); describe( "Renderer/Context", function() { let context; const webglStub = !!window.webglStub; beforeAll(function() { context = createContext_default(); spyOn(import__7.Context, "_deprecationWarning"); }); afterAll(function() { context.destroyForSpecs(); }); it("has a unique ID", function() { const c = createContext_default(); expect(c.id).toBeDefined(); expect(c.id).not.toEqual(context.id); c.destroyForSpecs(); }); it("get canvas", function() { expect(context.canvas).not.toBeNull(); }); it("get stencilBits", function() { expect(context.stencilBits).toBeGreaterThanOrEqual(0); }); it("get maximumCombinedTextureImageUnits", function() { expect( import__7.ContextLimits.maximumCombinedTextureImageUnits ).toBeGreaterThanOrEqual(8); }); it("get maximumCubeMapSize", function() { expect(import__7.ContextLimits.maximumCubeMapSize).toBeGreaterThanOrEqual(16); }); it("get maximumFragmentUniformVectors", function() { expect( import__7.ContextLimits.maximumFragmentUniformVectors ).toBeGreaterThanOrEqual(16); }); it("get maximumTextureImageUnits", function() { expect(import__7.ContextLimits.maximumTextureImageUnits).toBeGreaterThanOrEqual(8); }); it("get maximumRenderbufferSize", function() { expect(import__7.ContextLimits.maximumRenderbufferSize).toBeGreaterThanOrEqual(1); }); it("get maximumTextureSize", function() { expect(import__7.ContextLimits.maximumTextureSize).toBeGreaterThanOrEqual(64); }); it("get maximumVaryingVectors", function() { expect(import__7.ContextLimits.maximumVaryingVectors).toBeGreaterThanOrEqual(8); }); it("get maximumVertexAttributes", function() { expect(import__7.ContextLimits.maximumVertexAttributes).toBeGreaterThanOrEqual(8); }); it("get maximumVertexTextureImageUnits", function() { expect( import__7.ContextLimits.maximumVertexTextureImageUnits ).toBeGreaterThanOrEqual(0); }); it("get maximumVertexUniformVectors", function() { expect(import__7.ContextLimits.maximumVertexUniformVectors).toBeGreaterThanOrEqual( 1 ); }); it("get minimumAliasedLineWidth", function() { expect(import__7.ContextLimits.minimumAliasedLineWidth).toBeLessThanOrEqual(1); }); it("get maximumAliasedLineWidth", function() { expect(import__7.ContextLimits.maximumAliasedLineWidth).toBeGreaterThanOrEqual(1); }); it("get minimumAliasedPointSize", function() { expect(import__7.ContextLimits.minimumAliasedPointSize).toBeLessThanOrEqual(1); }); it("get maximumAliasedPointSize", function() { expect(import__7.ContextLimits.maximumAliasedPointSize).toBeGreaterThanOrEqual(1); }); it("get maximumViewportWidth", function() { expect(import__7.ContextLimits.maximumViewportWidth).toBeGreaterThan(0); }); it("get maximumViewportHeight", function() { expect(import__7.ContextLimits.maximumViewportHeight).toBeGreaterThan(0); }); it("gets antialias", function() { const c = createContext_default({ webgl: { antialias: false } }); expect(c.antialias).toEqual(false); c.destroyForSpecs(); }); it("gets the standard derivatives extension", function() { let fs = ""; if (context.standardDerivatives && !context.webgl2) { fs += "#extension GL_OES_standard_derivatives : enable\n"; } fs += "void main()\n{\n"; if (context.standardDerivatives) { fs += " out_FragColor = vec4(dFdx(1.0), dFdy(1.0), 1.0, 1.0);\n"; } else { fs += " out_FragColor = vec4(1.0);\n"; } fs += "}"; const expected = context.standardDerivatives ? [0, 0, 255, 255] : [255, 255, 255, 255]; expect({ context, fragmentShader: fs }).contextToRender(expected); }); it("gets the element index uint extension", function() { if (context.elementIndexUint) { const buffer = import__7.Buffer.createIndexBuffer({ context, sizeInBytes: 6, usage: import__7.BufferUsage.STREAM_DRAW, indexDatatype: import__7.IndexDatatype.UNSIGNED_INT }); expect(buffer).toBeDefined(); buffer.destroy(); } else { expect(function() { import__7.Buffer.createIndexBuffer({ context, sizeInBytes: 6, usage: import__7.BufferUsage.STREAM_DRAW, indexDatatype: import__7.IndexDatatype.UNSIGNED_INT }); }).toThrowDeveloperError(); } }); it("gets the depth texture extension", function() { expect(context.depthTexture).toBeDefined(); }); it("gets the texture float extension", function() { expect(context.floatingPointTexture).toBeDefined(); }); it("gets texture filter anisotropic extension", function() { expect(context.textureFilterAnisotropic).toBeDefined(); }); it("gets texture filter anisotropic extension", function() { expect(context.textureFilterAnisotropic).toBeDefined(); }); it("gets maximum texture filter anisotropy", function() { if (context.textureFilterAnisotropic) { expect( import__7.ContextLimits.maximumTextureFilterAnisotropy ).toBeGreaterThanOrEqual(2); } else { expect(import__7.ContextLimits.maximumTextureFilterAnisotropy).toEqual(1); } }); it("gets vertex array object extension", function() { expect(context.vertexArrayObject).toBeDefined(); }); it("get the fragment depth extension", function() { if (context.fragmentDepth && !context.webgl2) { return; } const fs = "void main()\n{\n out_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n}"; expect({ context, fragmentShader: fs, depth: 0.5 }).contextToRender([255, 0, 0, 255]); let fsFragDepth = "#extension GL_EXT_frag_depth : enable\n"; fsFragDepth += "void main()\n{\n out_FragColor = vec4(0.0, 1.0, 0.0, 1.0);\n"; if (context.fragmentDepth) { fsFragDepth += " gl_FragDepth"; if (!context.webgl2) { fsFragDepth += "EXT"; } fsFragDepth += " = 0.0;\n"; } fsFragDepth += "}\n"; const expected = [0, 255, 0, 255]; expect({ context, fragmentShader: fsFragDepth, depth: 1, clear: false }).contextToRender(expected); }); it("get the draw buffers extension", function() { expect(context.drawBuffers).toBeDefined(); }); it("get the maximum number of draw buffers", function() { if (context.drawBuffers) { expect(import__7.ContextLimits.maximumDrawBuffers).toBeGreaterThanOrEqual(1); } else { expect(import__7.ContextLimits.maximumDrawBuffers).toEqual(1); } }); it("get the maximum number of color attachments", function() { if (context.drawBuffers) { expect(import__7.ContextLimits.maximumColorAttachments).toBeGreaterThanOrEqual(4); } else { expect(import__7.ContextLimits.maximumColorAttachments).toEqual(1); } }); it("can create a pick ID and retrieve an object by pick color", function() { const o = {}; const pickId = context.createPickId(o); expect(pickId).toBeDefined(); expect(context.getObjectByPickColor(pickId.color)).toBe(o); }); it("throws when creating a pick ID without an object", function() { expect(function() { context.createPickId(void 0); }).toThrowDeveloperError(); }); it("returns undefined when retrieving an object by unknown pick color", function() { expect(context.getObjectByPickColor(import__7.Color.WHITE)).toBeUndefined(); }); it("throws when getObjectByPickColor is called without a color", function() { expect(function() { context.getObjectByPickColor(void 0); }).toThrowDeveloperError(); }); it("fails to construct (null canvas)", function() { expect(function() { return new import__7.Context(); }).toThrowDeveloperError(); }); it("isDestroyed", function() { const c = createContext_default(); expect(c.isDestroyed()).toEqual(false); c.destroyForSpecs(); expect(c.isDestroyed()).toEqual(true); }); it("destroying Context destroys objects in cache", function() { const c = createContext_default(); const destroyableObject = jasmine.createSpyObj("destroyableObject", [ "destroy" ]); c.cache.foo = destroyableObject; c.destroyForSpecs(); expect(destroyableObject.destroy).toHaveBeenCalled(); }); it("non-destroyable objects are allowed in the cache", function() { const c = createContext_default(); const nonDestroyableObject = {}; c.cache.foo = nonDestroyableObject; c.destroyForSpecs(); }); it("returns the underling drawingBufferWidth", function() { const c = createContext_default(void 0, 1024, 768); expect(c.drawingBufferWidth).toBe(1024); c.destroyForSpecs(); }); it("returns the underling drawingBufferHeight", function() { const c = createContext_default(void 0, 1024, 768); expect(c.drawingBufferHeight).toBe(768); c.destroyForSpecs(); }); it("requestWebgl1 works", function() { const c1 = createContext_default({ requestWebgl1: true }); expect(c1._webgl2).toBe(false); if (!webglStub) { const c2 = createContext_default({ requestWebgl1: false }); expect(c2._webgl2).toBe(true); } }); }, "WebGL" ); // packages/engine/Specs/Renderer/CubeMapSpec.js var import__8 = __toESM(require_Cesium(), 1); describe( "Renderer/CubeMap", function() { let context; let cubeMap; function expectCubeMapFaces(options) { const cubeMap2 = options.cubeMap; const expectedColors = options.expectedColors; const fs = "uniform samplerCube u_texture;uniform mediump vec3 u_direction;void main() { out_FragColor = czm_textureCube(u_texture, normalize(u_direction)); }"; let faceDirections = options.faceDirections; if (!(0, import__8.defined)(faceDirections)) { faceDirections = [ new import__8.Cartesian3(1, 0, 0), // +X new import__8.Cartesian3(-1, 0, 0), // -X new import__8.Cartesian3(0, 1, 0), // +Y new import__8.Cartesian3(0, -1, 0), // -Y new import__8.Cartesian3(0, 0, 1), // +Z new import__8.Cartesian3(0, 0, -1) // -Z ]; } const uniformMap = { direction: void 0, u_texture: function() { return cubeMap2; }, u_direction: function() { return this.direction; } }; for (let i = 0; i < 6; ++i) { uniformMap.direction = faceDirections[i]; expect({ context, fragmentShader: fs, uniformMap, epsilon: options.epsilon }).contextToRender(expectedColors[i]); } } let greenImage; let blueImage; let blueAlphaImage; let blueOverRedImage; let red16x16Image; let gammaImage; let customColorProfileImage; let supportsImageBitmapOptions; beforeAll(function() { context = createContext_default(); supportsImageBitmapOptions = import__8.Resource.supportsImageBitmapOptions(); const promises = []; promises.push( import__8.Resource.fetchImage("./Data/Images/Green.png").then(function(result) { greenImage = result; }) ); promises.push( import__8.Resource.fetchImage("./Data/Images/Blue.png").then(function(result) { blueImage = result; }) ); promises.push( import__8.Resource.fetchImage("./Data/Images/BlueAlpha.png").then(function(result) { blueAlphaImage = result; }) ); promises.push( import__8.Resource.fetchImage("./Data/Images/BlueOverRed.png").then(function(result) { blueOverRedImage = result; }) ); promises.push( import__8.Resource.fetchImage("./Data/Images/Red16x16.png").then(function(result) { red16x16Image = result; }) ); promises.push( import__8.Resource.fetchImage("./Data/Images/Gamma.png").then(function(result) { gammaImage = result; }) ); promises.push( import__8.Resource.fetchImage("./Data/Images/CustomColorProfile.png").then( function(result) { customColorProfileImage = result; } ) ); return Promise.all(promises); }); afterAll(function() { context.destroyForSpecs(); }); afterEach(function() { cubeMap = cubeMap && cubeMap.destroy(); }); it("gets the pixel format", function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16 }); expect(cubeMap.pixelFormat).toEqual(import__8.PixelFormat.RGBA); expect(cubeMap.positiveX.pixelFormat).toEqual(import__8.PixelFormat.RGBA); expect(cubeMap.negativeX.pixelFormat).toEqual(import__8.PixelFormat.RGBA); expect(cubeMap.positiveY.pixelFormat).toEqual(import__8.PixelFormat.RGBA); expect(cubeMap.negativeY.pixelFormat).toEqual(import__8.PixelFormat.RGBA); expect(cubeMap.positiveZ.pixelFormat).toEqual(import__8.PixelFormat.RGBA); expect(cubeMap.negativeZ.pixelFormat).toEqual(import__8.PixelFormat.RGBA); }); it("gets the pixel datatype", function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16 }); expect(cubeMap.pixelDatatype).toEqual(import__8.PixelDatatype.UNSIGNED_BYTE); expect(cubeMap.positiveX.pixelDatatype).toEqual( import__8.PixelDatatype.UNSIGNED_BYTE ); expect(cubeMap.negativeX.pixelDatatype).toEqual( import__8.PixelDatatype.UNSIGNED_BYTE ); expect(cubeMap.positiveY.pixelDatatype).toEqual( import__8.PixelDatatype.UNSIGNED_BYTE ); expect(cubeMap.negativeY.pixelDatatype).toEqual( import__8.PixelDatatype.UNSIGNED_BYTE ); expect(cubeMap.positiveZ.pixelDatatype).toEqual( import__8.PixelDatatype.UNSIGNED_BYTE ); expect(cubeMap.negativeZ.pixelDatatype).toEqual( import__8.PixelDatatype.UNSIGNED_BYTE ); }); it("sets a sampler", function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16 }); const sampler = new import__8.Sampler({ wrapS: import__8.TextureWrap.REPEAT, wrapT: import__8.TextureWrap.MIRRORED_REPEAT, minificationFilter: import__8.TextureMinificationFilter.NEAREST, magnificationFilter: import__8.TextureMagnificationFilter.NEAREST }); cubeMap.sampler = sampler; const s = cubeMap.sampler; expect(s.wrapS).toEqual(sampler.wrapS); expect(s.wrapT).toEqual(sampler.wrapT); expect(s.minificationFilter).toEqual(sampler.minificationFilter); expect(s.magnificationFilter).toEqual(sampler.magnificationFilter); }); it("gets width and height", function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16 }); expect(cubeMap.width).toEqual(16); expect(cubeMap.height).toEqual(16); }); it("gets size in bytes", function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16 }); expect(cubeMap.sizeInBytes).toEqual(256 * 4 * 6); }); it("gets flip Y", function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16, flipY: true }); expect(cubeMap.flipY).toEqual(true); }); it("draws with a cube map", function() { cubeMap = new import__8.CubeMap({ context, source: { positiveX: blueImage, negativeX: greenImage, positiveY: blueImage, negativeY: greenImage, positiveZ: blueImage, negativeZ: greenImage } }); expectCubeMapFaces({ cubeMap, expectedColors: [ [0, 0, 255, 255], // +X is blue [0, 255, 0, 255], // -X is green [0, 0, 255, 255], // +Y is blue [0, 255, 0, 255], // -Y is green [0, 0, 255, 255], // +Z is blue [0, 255, 0, 255] // -Z is green ] }); }); it("draws with a cube map with premultiplied alpha", function() { cubeMap = new import__8.CubeMap({ context, source: { positiveX: blueAlphaImage, negativeX: blueAlphaImage, positiveY: blueAlphaImage, negativeY: blueAlphaImage, positiveZ: blueAlphaImage, negativeZ: blueAlphaImage }, preMultiplyAlpha: true }); expect(cubeMap.preMultiplyAlpha).toEqual(true); expectCubeMapFaces({ cubeMap, epsilon: 1, expectedColors: [ [0, 0, 127, 255], // +X [0, 0, 127, 255], // -X [0, 0, 127, 255], // +Y [0, 0, 127, 255], // -Y [0, 0, 127, 255], // +Z [0, 0, 127, 255] // -Z ] }); }); it("draws with a cube map while ignoring color profiles", function() { if (!supportsImageBitmapOptions) { return; } cubeMap = new import__8.CubeMap({ context, source: { positiveX: gammaImage, negativeX: customColorProfileImage, positiveY: gammaImage, negativeY: customColorProfileImage, positiveZ: gammaImage, negativeZ: customColorProfileImage }, skipColorSpaceConversion: true }); expectCubeMapFaces({ cubeMap, epsilon: 1, expectedColors: [ [0, 136, 0, 255], // +X [0, 136, 0, 255], // -X [0, 136, 0, 255], // +Y [0, 136, 0, 255], // -Y [0, 136, 0, 255], // +Z [0, 136, 0, 255] // -Z ] }); }); it("draws with a cube map while allowing color profiles", function() { if (!supportsImageBitmapOptions) { return; } cubeMap = new import__8.CubeMap({ context, source: { positiveX: gammaImage, negativeX: customColorProfileImage, positiveY: gammaImage, negativeY: customColorProfileImage, positiveZ: gammaImage, negativeZ: customColorProfileImage }, skipColorSpaceConversion: false }); expectCubeMapFaces({ cubeMap, epsilon: 1, expectedColors: [ [0, 59, 0, 255], // +X [193, 0, 0, 255], // -X [0, 59, 0, 255], // +Y [193, 0, 0, 255], // -Y [0, 59, 0, 255], // +Z [193, 0, 0, 255] // -Z ] }); }); it("draws the context default cube map", function() { expectCubeMapFaces({ cubeMap: context.defaultCubeMap, expectedColors: [ [255, 255, 255, 255], // +X [255, 255, 255, 255], // -X [255, 255, 255, 255], // +Y [255, 255, 255, 255], // -Y [255, 255, 255, 255], // +Z [255, 255, 255, 255] // -Z ] }); }); it("creates a cube map with typed arrays", function() { cubeMap = new import__8.CubeMap({ context, source: { positiveX: { width: 1, height: 1, arrayBufferView: new Uint8Array([0, 255, 255, 255]) }, negativeX: { width: 1, height: 1, arrayBufferView: new Uint8Array([0, 0, 255, 255]) }, positiveY: { width: 1, height: 1, arrayBufferView: new Uint8Array([0, 255, 0, 255]) }, negativeY: { width: 1, height: 1, arrayBufferView: new Uint8Array([255, 0, 0, 255]) }, positiveZ: { width: 1, height: 1, arrayBufferView: new Uint8Array([255, 0, 255, 255]) }, negativeZ: { width: 1, height: 1, arrayBufferView: new Uint8Array([255, 255, 0, 255]) } } }); expectCubeMapFaces({ cubeMap, expectedColors: [ [0, 255, 255, 255], // +X [0, 0, 255, 255], // -X [0, 255, 0, 255], // +Y [255, 0, 0, 255], // -Y [255, 0, 255, 255], // +Z [255, 255, 0, 255] // -Z ] }); }); it("creates a cube map with floating-point textures", function() { if (!context.floatingPointTexture) { return; } const positiveXColor = new import__8.Color(0, 1, 1, 1); const negativeXColor = new import__8.Color(0, 0, 1, 1); const positiveYColor = new import__8.Color(0, 1, 0, 1); const negativeYColor = new import__8.Color(1, 0, 0, 1); const positiveZColor = new import__8.Color(1, 0, 1, 1); const negativeZColor = new import__8.Color(1, 1, 0, 1); cubeMap = new import__8.CubeMap({ context, source: { positiveX: { width: 1, height: 1, arrayBufferView: new Float32Array([ positiveXColor.red, positiveXColor.green, positiveXColor.blue, positiveXColor.alpha ]) }, negativeX: { width: 1, height: 1, arrayBufferView: new Float32Array([ negativeXColor.red, negativeXColor.green, negativeXColor.blue, negativeXColor.alpha ]) }, positiveY: { width: 1, height: 1, arrayBufferView: new Float32Array([ positiveYColor.red, positiveYColor.green, positiveYColor.blue, positiveYColor.alpha ]) }, negativeY: { width: 1, height: 1, arrayBufferView: new Float32Array([ negativeYColor.red, negativeYColor.green, negativeYColor.blue, negativeYColor.alpha ]) }, positiveZ: { width: 1, height: 1, arrayBufferView: new Float32Array([ positiveZColor.red, positiveZColor.green, positiveZColor.blue, positiveZColor.alpha ]) }, negativeZ: { width: 1, height: 1, arrayBufferView: new Float32Array([ negativeZColor.red, negativeZColor.green, negativeZColor.blue, negativeZColor.alpha ]) } }, pixelDatatype: import__8.PixelDatatype.FLOAT }); expectCubeMapFaces({ cubeMap, expectedColors: [ [0, 255, 255, 255], // +X [0, 0, 255, 255], // -X [0, 255, 0, 255], // +Y [255, 0, 0, 255], // -Y [255, 0, 255, 255], // +Z [255, 255, 0, 255] // -Z ] }); }); it("creates a cube map with floating-point textures and linear filtering", function() { if (!context.floatingPointTexture) { return; } const positiveXColor = new import__8.Color(0, 1, 1, 1); const negativeXColor = new import__8.Color(0, 0, 1, 1); const positiveYColor = new import__8.Color(0, 1, 0, 1); const negativeYColor = new import__8.Color(1, 0, 0, 1); const positiveZColor = new import__8.Color(1, 0, 1, 1); const negativeZColor = new import__8.Color(1, 1, 0, 1); cubeMap = new import__8.CubeMap({ context, source: { positiveX: { width: 1, height: 1, arrayBufferView: new Float32Array([ positiveXColor.red, positiveXColor.green, positiveXColor.blue, positiveXColor.alpha ]) }, negativeX: { width: 1, height: 1, arrayBufferView: new Float32Array([ negativeXColor.red, negativeXColor.green, negativeXColor.blue, negativeXColor.alpha ]) }, positiveY: { width: 1, height: 1, arrayBufferView: new Float32Array([ positiveYColor.red, positiveYColor.green, positiveYColor.blue, positiveYColor.alpha ]) }, negativeY: { width: 1, height: 1, arrayBufferView: new Float32Array([ negativeYColor.red, negativeYColor.green, negativeYColor.blue, negativeYColor.alpha ]) }, positiveZ: { width: 1, height: 1, arrayBufferView: new Float32Array([ positiveZColor.red, positiveZColor.green, positiveZColor.blue, positiveZColor.alpha ]) }, negativeZ: { width: 1, height: 1, arrayBufferView: new Float32Array([ negativeZColor.red, negativeZColor.green, negativeZColor.blue, negativeZColor.alpha ]) } }, pixelDatatype: import__8.PixelDatatype.FLOAT, sampler: new import__8.Sampler({ wrapS: import__8.TextureWrap.CLAMP_TO_EDGE, wrapT: import__8.TextureWrap.CLAMP_TO_EDGE, minificationFilter: import__8.TextureMinificationFilter.LINEAR, magnificationFilter: import__8.TextureMagnificationFilter.LINEAR }) }); const fs = "uniform samplerCube u_texture;void main() { out_FragColor = czm_textureCube(u_texture, normalize(vec3(1.0, 1.0, 0.0))); }"; const uniformMap = { u_texture: function() { return cubeMap; } }; if (!context.textureFloatLinear) { expect({ context, fragmentShader: fs, uniformMap, epsilon: 1 }).contextToRender(positiveYColor.toBytes()); } else { import__8.Color.multiplyByScalar(positiveXColor, 1 - 0.5, positiveXColor); import__8.Color.multiplyByScalar(positiveYColor, 0.5, positiveYColor); const color = import__8.Color.add(positiveXColor, positiveYColor, positiveXColor); expect({ context, fragmentShader: fs, uniformMap, epsilon: 1 }).contextToRender(color.toBytes()); } }); it("creates a cube map with half floating-point textures", function() { if (!context.halfFloatingPointTexture) { return; } const positiveXFloats = [12902, 13926, 14541, 15360]; const negativeXFloats = [13926, 12902, 14541, 15360]; const positiveYFloats = [14541, 13926, 12902, 15360]; const negativeYFloats = [12902, 14541, 13926, 15360]; const positiveZFloats = [13926, 14541, 12902, 15360]; const negativeZFloats = [14541, 12902, 13926, 15360]; const positiveXColor = new import__8.Color(0.2, 0.4, 0.6, 1); const negativeXColor = new import__8.Color(0.4, 0.2, 0.6, 1); const positiveYColor = new import__8.Color(0.6, 0.4, 0.2, 1); const negativeYColor = new import__8.Color(0.2, 0.6, 0.4, 1); const positiveZColor = new import__8.Color(0.4, 0.6, 0.2, 1); const negativeZColor = new import__8.Color(0.6, 0.2, 0.4, 1); cubeMap = new import__8.CubeMap({ context, source: { positiveX: { width: 1, height: 1, arrayBufferView: new Uint16Array(positiveXFloats) }, negativeX: { width: 1, height: 1, arrayBufferView: new Uint16Array(negativeXFloats) }, positiveY: { width: 1, height: 1, arrayBufferView: new Uint16Array(positiveYFloats) }, negativeY: { width: 1, height: 1, arrayBufferView: new Uint16Array(negativeYFloats) }, positiveZ: { width: 1, height: 1, arrayBufferView: new Uint16Array(positiveZFloats) }, negativeZ: { width: 1, height: 1, arrayBufferView: new Uint16Array(negativeZFloats) } }, pixelDatatype: import__8.PixelDatatype.HALF_FLOAT }); expectCubeMapFaces({ cubeMap, expectedColors: [ positiveXColor.toBytes(), negativeXColor.toBytes(), positiveYColor.toBytes(), negativeYColor.toBytes(), positiveZColor.toBytes(), negativeZColor.toBytes() ] }); }); it("creates a cube map with half floating-point textures and linear filtering", function() { if (!context.halfFloatingPointTexture) { return; } const positiveXFloats = [12902, 13926, 14541, 15360]; const negativeXFloats = [13926, 12902, 14541, 15360]; const positiveYFloats = [14541, 13926, 12902, 15360]; const negativeYFloats = [12902, 14541, 13926, 15360]; const positiveZFloats = [13926, 14541, 12902, 15360]; const negativeZFloats = [14541, 12902, 13926, 15360]; const positiveXColor = new import__8.Color(0.2, 0.4, 0.6, 1); const positiveYColor = new import__8.Color(0.6, 0.4, 0.2, 1); cubeMap = new import__8.CubeMap({ context, source: { positiveX: { width: 1, height: 1, arrayBufferView: new Uint16Array(positiveXFloats) }, negativeX: { width: 1, height: 1, arrayBufferView: new Uint16Array(negativeXFloats) }, positiveY: { width: 1, height: 1, arrayBufferView: new Uint16Array(positiveYFloats) }, negativeY: { width: 1, height: 1, arrayBufferView: new Uint16Array(negativeYFloats) }, positiveZ: { width: 1, height: 1, arrayBufferView: new Uint16Array(positiveZFloats) }, negativeZ: { width: 1, height: 1, arrayBufferView: new Uint16Array(negativeZFloats) } }, pixelDatatype: import__8.PixelDatatype.HALF_FLOAT, sampler: new import__8.Sampler({ wrapS: import__8.TextureWrap.CLAMP_TO_EDGE, wrapT: import__8.TextureWrap.CLAMP_TO_EDGE, minificationFilter: import__8.TextureMinificationFilter.LINEAR, magnificationFilter: import__8.TextureMagnificationFilter.LINEAR }) }); const fs = "uniform samplerCube u_texture;void main() { out_FragColor = czm_textureCube(u_texture, normalize(vec3(1.0, 1.0, 0.0))); }"; const uniformMap = { u_texture: function() { return cubeMap; } }; if (!context.textureHalfFloatLinear) { expect({ context, fragmentShader: fs, uniformMap, epsilon: 1 }).contextToRender(positiveYColor.toBytes()); } else { import__8.Color.multiplyByScalar(positiveXColor, 1 - 0.5, positiveXColor); import__8.Color.multiplyByScalar(positiveYColor, 0.5, positiveYColor); const color = import__8.Color.add(positiveXColor, positiveYColor, positiveXColor); expect({ context, fragmentShader: fs, uniformMap, epsilon: 1 }).contextToRender(color.toBytes()); } }); it("creates a cube map with typed arrays and images", function() { cubeMap = new import__8.CubeMap({ context, source: { positiveX: blueImage, negativeX: greenImage, positiveY: { width: 1, height: 1, arrayBufferView: new Uint8Array([0, 255, 0, 255]) }, negativeY: { width: 1, height: 1, arrayBufferView: new Uint8Array([255, 0, 0, 255]) }, positiveZ: { width: 1, height: 1, arrayBufferView: new Uint8Array([0, 0, 255, 255]) }, negativeZ: { width: 1, height: 1, arrayBufferView: new Uint8Array([255, 255, 0, 255]) } } }); expectCubeMapFaces({ cubeMap, expectedColors: [ [0, 0, 255, 255], // +X [0, 255, 0, 255], // -X [0, 255, 0, 255], // +Y [255, 0, 0, 255], // -Y [0, 0, 255, 255], // +Z [255, 255, 0, 255] // -Z ] }); }); it("copies to a cube map", function() { cubeMap = new import__8.CubeMap({ context, width: 1, height: 1 }); cubeMap.positiveX.copyFrom({ source: blueImage }); cubeMap.negativeX.copyFrom({ source: greenImage }); cubeMap.positiveY.copyFrom({ source: blueImage }); cubeMap.negativeY.copyFrom({ source: greenImage }); cubeMap.positiveZ.copyFrom({ source: blueImage }); cubeMap.negativeZ.copyFrom({ source: greenImage }); expectCubeMapFaces({ cubeMap, expectedColors: [ [0, 0, 255, 255], // +X [0, 255, 0, 255], // -X [0, 0, 255, 255], // +Y [0, 255, 0, 255], // -Y [0, 0, 255, 255], // +Z [0, 255, 0, 255] // -Z ] }); }); it("copies from a typed array", function() { cubeMap = new import__8.CubeMap({ context, width: 1, height: 1 }); cubeMap.positiveX.copyFrom({ source: { width: 1, height: 1, arrayBufferView: new Uint8Array([0, 255, 255, 255]) } }); cubeMap.negativeX.copyFrom({ source: { width: 1, height: 1, arrayBufferView: new Uint8Array([0, 0, 255, 255]) } }); cubeMap.positiveY.copyFrom({ source: { width: 1, height: 1, arrayBufferView: new Uint8Array([0, 255, 0, 255]) } }); cubeMap.negativeY.copyFrom({ source: { width: 1, height: 1, arrayBufferView: new Uint8Array([255, 0, 0, 255]) } }); cubeMap.positiveZ.copyFrom({ source: { width: 1, height: 1, arrayBufferView: new Uint8Array([255, 0, 255, 255]) } }); cubeMap.negativeZ.copyFrom({ source: { width: 1, height: 1, arrayBufferView: new Uint8Array([255, 255, 0, 255]) } }); expectCubeMapFaces({ cubeMap, expectedColors: [ [0, 255, 255, 255], // +X [0, 0, 255, 255], // -X [0, 255, 0, 255], // +Y [255, 0, 0, 255], // -Y [255, 0, 255, 255], // +Z [255, 255, 0, 255] // -Z ] }); }); it("sub copies images to a cube map", function() { cubeMap = new import__8.CubeMap({ context, width: 2, height: 2 }); cubeMap.positiveX.copyFrom({ source: { width: 1, height: 1, arrayBufferView: new Uint8Array([0, 255, 255, 255]) } }); cubeMap.negativeX.copyFrom({ source: { width: 1, height: 1, arrayBufferView: new Uint8Array([0, 0, 255, 255]) } }); cubeMap.positiveY.copyFrom({ source: { width: 1, height: 1, arrayBufferView: new Uint8Array([0, 255, 0, 255]) } }); cubeMap.negativeY.copyFrom({ source: { width: 1, height: 1, arrayBufferView: new Uint8Array([255, 0, 0, 255]) } }); cubeMap.positiveZ.copyFrom({ source: { width: 1, height: 1, arrayBufferView: new Uint8Array([255, 0, 255, 255]) } }); cubeMap.negativeZ.copyFrom({ source: { width: 1, height: 1, arrayBufferView: new Uint8Array([0, 255, 0, 255]) }, xOffset: 1, yOffset: 0 }); const negativeZDirection = new import__8.Cartesian3(0.25, 0, -1); import__8.Cartesian3.normalize(negativeZDirection, negativeZDirection); expectCubeMapFaces({ cubeMap, expectedColors: [ [0, 64, 64, 255], // +X [0, 0, 64, 255], // -X [0, 64, 0, 255], // +Y [64, 0, 0, 255], // -Y [64, 0, 64, 255], // +Z [0, 32, 0, 255] // -Z ], faceDirections: [ new import__8.Cartesian3(1, 0, 0), // +X new import__8.Cartesian3(-1, 0, 0), // -X new import__8.Cartesian3(0, 1, 0), // +Y new import__8.Cartesian3(0, -1, 0), // -Y new import__8.Cartesian3(0, 0, 1), // +Z negativeZDirection // -Z ] }); }); it("sub copies array buffers to a cube map", function() { cubeMap = new import__8.CubeMap({ context, width: 2, height: 2 }); cubeMap.positiveX.copyFrom({ source: blueImage }); cubeMap.negativeX.copyFrom({ source: greenImage }); cubeMap.positiveY.copyFrom({ source: blueImage }); cubeMap.negativeY.copyFrom({ source: greenImage }); cubeMap.positiveZ.copyFrom({ source: blueImage }); cubeMap.negativeZ.copyFrom({ source: greenImage, xOffset: 1, yOffset: 0 }); const negativeZDirection = new import__8.Cartesian3(0.25, 0, -1); import__8.Cartesian3.normalize(negativeZDirection, negativeZDirection); expectCubeMapFaces({ cubeMap, expectedColors: [ [0, 0, 64, 255], // +X [0, 64, 0, 255], // -X [0, 0, 64, 255], // +Y [0, 64, 0, 255], // -Y [0, 0, 64, 255], // +Z [0, 32, 0, 255] // -Z ], faceDirections: [ new import__8.Cartesian3(1, 0, 0), // +X new import__8.Cartesian3(-1, 0, 0), // -X new import__8.Cartesian3(0, 1, 0), // +Y new import__8.Cartesian3(0, -1, 0), // -Y new import__8.Cartesian3(0, 0, 1), // +Z negativeZDirection // -Z ] }); }); it("copies from the framebuffer", function() { const cxt = createContext_default({ webgl: { alpha: true // Seems to be required for copyFromFramebuffer() } }); cubeMap = new import__8.CubeMap({ context: cxt, width: 1, height: 1 }); cubeMap.positiveX.copyFrom({ source: blueImage }); const fs = "uniform samplerCube u_cubeMap;void main() { out_FragColor = czm_textureCube(u_cubeMap, vec3(1.0, 0.0, 0.0)); }"; const uniformMap = { u_cubeMap: function() { return cubeMap; } }; expect({ context: cxt, fragmentShader: fs, uniformMap }).contextToRender([0, 0, 255, 255]); const clearCommand = new import__8.ClearCommand({ color: new import__8.Color(1, 0, 0, 1) }); clearCommand.execute(cxt); expect(cxt).toReadPixels([255, 0, 0, 255]); cubeMap.positiveX.copyFromFramebuffer(); import__8.ClearCommand.ALL.execute(cxt); expect(cxt).toReadPixels([0, 0, 0, 0]); expect({ context: cxt, fragmentShader: fs, uniformMap }).contextToRender([255, 0, 0, 255]); cxt.destroyForSpecs(); }); it("draws with a cube map and a texture", function() { cubeMap = new import__8.CubeMap({ context, source: { positiveX: greenImage, negativeX: greenImage, positiveY: greenImage, negativeY: greenImage, positiveZ: greenImage, negativeZ: greenImage } }); let texture = new import__8.Texture({ context, source: blueImage }); const fs = "uniform samplerCube u_cubeMap;uniform sampler2D u_texture;void main() { out_FragColor = czm_textureCube(u_cubeMap, vec3(1.0, 0.0, 0.0)) + texture(u_texture, vec2(0.0)); }"; const uniformMap = { u_cubeMap: function() { return cubeMap; }, u_texture: function() { return texture; } }; expect({ context, fragmentShader: fs, uniformMap }).contextToRender([0, 255, 255, 255]); texture = texture.destroy(); }); it("generates mipmaps", function() { cubeMap = new import__8.CubeMap({ context, source: { positiveX: blueImage, negativeX: greenImage, positiveY: blueImage, negativeY: greenImage, positiveZ: blueImage, negativeZ: greenImage } }); cubeMap.generateMipmap(); cubeMap.sampler = new import__8.Sampler({ minificationFilter: import__8.TextureMinificationFilter.NEAREST_MIPMAP_LINEAR }); const fs = "uniform samplerCube u_cubeMap;void main() { out_FragColor = czm_textureCube(u_cubeMap, vec3(1.0, 0.0, 0.0)); }"; const uniformMap = { u_cubeMap: function() { return cubeMap; } }; expect({ context, fragmentShader: fs, uniformMap }).contextToRender([0, 0, 255, 255]); }); it("gets size in bytes for mipmap", function() { cubeMap = new import__8.CubeMap({ context, source: { positiveX: red16x16Image, negativeX: red16x16Image, positiveY: red16x16Image, negativeY: red16x16Image, positiveZ: red16x16Image, negativeZ: red16x16Image } }); cubeMap.generateMipmap(); expect(cubeMap.sizeInBytes).toEqualEpsilon( (16 * 16 + 8 * 8 + 4 * 4 + 2 * 2 + 1) * 4 * 6, 10 ); }); it("destroys", function() { const c = new import__8.CubeMap({ context, width: 16, height: 16 }); expect(c.isDestroyed()).toEqual(false); c.destroy(); expect(c.isDestroyed()).toEqual(true); }); it("fails to create (options)", function() { expect(function() { cubeMap = new import__8.CubeMap(); }).toThrowDeveloperError(); }); it("fails to create (source)", function() { expect(function() { cubeMap = new import__8.CubeMap({ context }); }).toThrowDeveloperError(); }); it("fails to create (width, no height)", function() { expect(function() { cubeMap = new import__8.CubeMap({ context, width: 16 }); }).toThrowDeveloperError(); }); it("fails to create (width != height)", function() { expect(function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 32 }); }).toThrowDeveloperError(); }); it("fails to create (small width)", function() { expect(function() { cubeMap = new import__8.CubeMap({ context, width: 0, height: 0 }); }).toThrowDeveloperError(); }); it("fails to create (large width)", function() { expect(function() { cubeMap = new import__8.CubeMap({ context, width: import__8.ContextLimits.maximumCubeMapSize + 1, height: import__8.ContextLimits.maximumCubeMapSize + 1 }); }).toThrowDeveloperError(); }); it("fails to create (PixelFormat)", function() { expect(function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16, pixelFormat: "invalid PixelFormat" }); }).toThrowDeveloperError(); }); it("throws during creation if pixel format is depth or depth-stencil", function() { expect(function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16, pixelFormat: import__8.PixelFormat.DEPTH_COMPONENT }); }).toThrowDeveloperError(); }); it("throws during creation if pixelDatatype is FLOAT, and OES_texture_float is not supported", function() { if (!context.floatingPointTexture) { expect(function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16, pixelDatatype: import__8.PixelDatatype.FLOAT }); }).toThrowDeveloperError(); } }); it("throws during creation if pixelDatatype is HALF_FLOAT, and OES_texture_half_float is not supported", function() { if (!context.halfFloatingPointTexture) { expect(function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16, pixelDatatype: import__8.PixelDatatype.HALF_FLOAT }); }).toThrowDeveloperError(); } }); it("fails to create (pixelDatatype)", function() { expect(function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16, pixelFormat: import__8.PixelFormat.RGBA, pixelDatatype: "invalid pixelDatatype" }); }).toThrowDeveloperError(); }); it("fails to create (source)", function() { expect(function() { cubeMap = new import__8.CubeMap({ context, source: {} }); }).toThrowDeveloperError(); }); it("fails to create (source width and height)", function() { expect(function() { cubeMap = new import__8.CubeMap({ context, source: { positiveX: greenImage, // 1x1 negativeX: greenImage, // 1x1 positiveY: greenImage, // 1x1 negativeY: greenImage, // 1x1 positiveZ: greenImage, // 1x1 negativeZ: blueOverRedImage // 1x2 } }); }).toThrowDeveloperError(); }); it("fails to copy from no options", function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16 }); expect(function() { cubeMap.positiveX.copyFrom(); }).toThrowDeveloperError(); }); it("fails to copy from no image (source)", function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16 }); expect(function() { cubeMap.positiveX.copyFrom({ xOffset: 0, yOffset: 0 }); }).toThrowDeveloperError(); }); it("fails to copy from an image (xOffset)", function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16 }); const image = new Image(); expect(function() { cubeMap.positiveY.copyFrom({ source: image, xOffset: -1 }); }).toThrowDeveloperError(); }); it("fails to copy from an image (yOffset)", function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16 }); const image = new Image(); expect(function() { cubeMap.positiveZ.copyFrom({ source: image, xOffset: 0, yOffset: -1 }); }).toThrowDeveloperError(); }); it("fails to copy from an image (width)", function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16 }); const image = new Image(); image.width = 16 + 1; expect(function() { cubeMap.negativeX.copyFrom({ source: image }); }).toThrowDeveloperError(); }); it("fails to copy from an image (height)", function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16 }); const image = new Image(); image.height = 16 + 1; expect(function() { cubeMap.negativeY.copyFrom({ source: image }); }).toThrowDeveloperError(); }); it("fails to copy from the framebuffer (invalid data type)", function() { if (context.floatingPointTexture) { cubeMap = new import__8.CubeMap({ context, width: 1, height: 1, pixelDatatype: import__8.PixelDatatype.FLOAT }); expect(function() { cubeMap.positiveX.copyFromFramebuffer(); }).toThrowDeveloperError(); } }); it("fails to copy from the framebuffer (xOffset)", function() { cubeMap = new import__8.CubeMap({ context, width: 1, height: 1 }); expect(function() { cubeMap.positiveX.copyFromFramebuffer(-1); }).toThrowDeveloperError(); }); it("fails to copy from the framebuffer (yOffset)", function() { cubeMap = new import__8.CubeMap({ context, width: 1, height: 1 }); expect(function() { cubeMap.positiveY.copyFromFramebuffer(0, -1); }).toThrowDeveloperError(); }); it("fails to copy from the framebuffer (framebufferXOffset)", function() { cubeMap = new import__8.CubeMap({ context, width: 1, height: 1 }); expect(function() { cubeMap.positiveZ.copyFromFramebuffer(0, 0, -1); }).toThrowDeveloperError(); }); it("fails to copy from the framebuffer (framebufferYOffset)", function() { cubeMap = new import__8.CubeMap({ context, width: 1, height: 1 }); expect(function() { cubeMap.negativeX.copyFromFramebuffer(0, 0, 0, -1); }).toThrowDeveloperError(); }); it("fails to copy from the framebuffer (width)", function() { cubeMap = new import__8.CubeMap({ context, width: 1, height: 1 }); expect(function() { cubeMap.negativeY.copyFromFramebuffer(0, 0, 0, 0, cubeMap.width + 1); }).toThrowDeveloperError(); }); it("fails to copy from the framebuffer (height)", function() { cubeMap = new import__8.CubeMap({ context, width: 1, height: 1 }); expect(function() { cubeMap.negativeZ.copyFromFramebuffer( 0, 0, 0, 0, 0, cubeMap.height + 1 ); }).toThrowDeveloperError(); }); it("fails to copy from the framebuffer (FLOAT", function() { if (!context.floatingPointTexture) { return; } cubeMap = new import__8.CubeMap({ context, width: 1, height: 1, pixelDatatype: import__8.PixelDatatype.FLOAT }); expect(function() { cubeMap.negativeX.copyFromFramebuffer(0, 0, 0, 0, 0, 0); }).toThrowDeveloperError(); }); it("fails to copy from the framebuffer (HALF_FLOAT", function() { if (!context.halfFloatingPointTexture) { return; } cubeMap = new import__8.CubeMap({ context, width: 1, height: 1, pixelDatatype: import__8.PixelDatatype.HALF_FLOAT }); expect(function() { cubeMap.negativeX.copyFromFramebuffer(0, 0, 0, 0, 0, 0); }).toThrowDeveloperError(); }); it("fails to generate mipmaps (width)", function() { cubeMap = new import__8.CubeMap({ context, width: 3, height: 3 }); expect(function() { cubeMap.generateMipmap(); }).toThrowDeveloperError(); }); it("fails to generate mipmaps (hint)", function() { cubeMap = new import__8.CubeMap({ context, width: 16, height: 16 }); expect(function() { cubeMap.generateMipmap("invalid hint"); }).toThrowDeveloperError(); }); it("fails to destroy", function() { const c = new import__8.CubeMap({ context, width: 16, height: 16 }); c.destroy(); expect(function() { c.destroy(); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Renderer/DrawCommandSpec.js var import__9 = __toESM(require_Cesium(), 1); describe("Renderer/DrawCommand", function() { it("constructs", function() { const c = new import__9.DrawCommand(); expect(c.boundingVolume).toBeUndefined(); expect(c.orientedBoundingBox).toBeUndefined(); expect(c.cull).toEqual(true); expect(c.occlude).toEqual(true); expect(c.modelMatrix).toBeUndefined(); expect(c.primitiveType).toEqual(import__9.PrimitiveType.TRIANGLES); expect(c.vertexArray).toBeUndefined(); expect(c.count).toBeUndefined(); expect(c.offset).toEqual(0); expect(c.instanceCount).toEqual(0); expect(c.shaderProgram).toBeUndefined(); expect(c.uniformMap).toBeUndefined(); expect(c.renderState).toBeUndefined(); expect(c.framebuffer).toBeUndefined(); expect(c.pass).toBeUndefined(); expect(c.executeInClosestFrustum).toEqual(false); expect(c.owner).toBeUndefined(); expect(c.debugShowBoundingVolume).toEqual(false); expect(c.debugOverlappingFrustums).toEqual(0); expect(c.castShadows).toEqual(false); expect(c.receiveShadows).toEqual(false); expect(c.pickId).toBeUndefined(); expect(c.pickOnly).toBe(false); }); it("constructs with options", function() { const boundingVolume = {}; const orientedBoundingBox = {}; const modelMatrix = {}; const primitiveType = import__9.PrimitiveType.TRIANGLE_FAN; const vertexArray = {}; const shaderProgram = {}; const uniformMap = {}; const renderState = {}; const framebuffer2 = {}; const pass = import__9.Pass.TRANSLUCENT; const owner = {}; const pickId = {}; const c = new import__9.DrawCommand({ boundingVolume, orientedBoundingBox, cull: false, occlude: false, modelMatrix, primitiveType, vertexArray, count: 3, offset: 3, instanceCount: 2, shaderProgram, uniformMap, renderState, framebuffer: framebuffer2, pass, executeInClosestFrustum: true, owner, debugShowBoundingVolume: true, castShadows: true, receiveShadows: true, pickId, pickOnly: true }); expect(c.boundingVolume).toBe(boundingVolume); expect(c.orientedBoundingBox).toBe(orientedBoundingBox); expect(c.cull).toEqual(false); expect(c.occlude).toEqual(false); expect(c.modelMatrix).toBe(modelMatrix); expect(c.primitiveType).toEqual(primitiveType); expect(c.vertexArray).toBe(vertexArray); expect(c.count).toEqual(3); expect(c.offset).toEqual(3); expect(c.instanceCount).toEqual(2); expect(c.shaderProgram).toBe(shaderProgram); expect(c.uniformMap).toBe(uniformMap); expect(c.renderState).toBe(renderState); expect(c.framebuffer).toBe(framebuffer2); expect(c.pass).toEqual(pass); expect(c.executeInClosestFrustum).toEqual(true); expect(c.owner).toBe(owner); expect(c.debugShowBoundingVolume).toEqual(true); expect(c.debugOverlappingFrustums).toEqual(0); expect(c.castShadows).toEqual(true); expect(c.receiveShadows).toEqual(true); expect(c.pickId).toBe(pickId); expect(c.pickOnly).toEqual(true); }); it("shallow clones", function() { const c = new import__9.DrawCommand({ boundingVolume: {}, orientedBoundingBox: {}, cull: false, occlude: false, modelMatrix: {}, primitiveType: import__9.PrimitiveType.TRIANGLE_FAN, vertexArray: {}, count: 3, offset: 3, instanceCount: 2, shaderProgram: {}, uniformMap: {}, renderState: {}, framebuffer: {}, pass: import__9.Pass.TRANSLUCENT, executeInClosestFrustum: true, owner: {}, debugShowBoundingVolume: true, castShadows: true, receiveShadows: true, pickId: {}, pickOnly: true }); const clone24 = import__9.DrawCommand.shallowClone(c); expect(clone24.boundingVolume).toBe(c.boundingVolume); expect(clone24.orientedBoundingBox).toBe(c.orientedBoundingBox); expect(clone24.cull).toEqual(c.cull); expect(clone24.occlude).toEqual(c.occlude); expect(clone24.modelMatrix).toBe(c.modelMatrix); expect(clone24.primitiveType).toEqual(c.primitiveType); expect(clone24.vertexArray).toBe(c.vertexArray); expect(clone24.count).toEqual(c.count); expect(clone24.offset).toEqual(c.offset); expect(clone24.instanceCount).toEqual(c.instanceCount); expect(clone24.shaderProgram).toBe(c.shaderProgram); expect(clone24.uniformMap).toBe(c.uniformMap); expect(clone24.renderState).toBe(c.renderState); expect(clone24.framebuffer).toBe(c.framebuffer); expect(clone24.pass).toEqual(c.pass); expect(clone24.executeInClosestFrustum).toEqual(c.executeInClosestFrustum); expect(clone24.owner).toBe(c.owner); expect(clone24.debugShowBoundingVolume).toEqual(c.debugShowBoundingVolume); expect(clone24.debugOverlappingFrustums).toEqual(c.debugOverlappingFrustums); expect(clone24.castShadows).toEqual(c.castShadows); expect(clone24.receiveShadows).toEqual(c.receiveShadows); expect(clone24.pickId).toBe(c.pickId); expect(clone24.pickOnly).toBe(c.pickOnly); }); it("shallow clones with result", function() { const c = new import__9.DrawCommand({ boundingVolume: {}, orientedBoundingBox: {}, cull: false, occlude: false, modelMatrix: {}, primitiveType: import__9.PrimitiveType.TRIANGLE_FAN, vertexArray: {}, count: 3, offset: 3, instanceCount: 2, shaderProgram: {}, uniformMap: {}, renderState: {}, framebuffer: {}, pass: import__9.Pass.TRANSLUCENT, executeInClosestFrustum: true, owner: {}, debugShowBoundingVolume: true, castShadows: true, receiveShadows: true, pickId: {}, pickOnly: true }); const result = new import__9.DrawCommand(); const clone24 = import__9.DrawCommand.shallowClone(c, result); expect(result).toBe(clone24); expect(clone24.boundingVolume).toBe(c.boundingVolume); expect(clone24.orientedBoundingBox).toBe(c.orientedBoundingBox); expect(clone24.cull).toEqual(c.cull); expect(clone24.occlude).toEqual(c.occlude); expect(clone24.modelMatrix).toBe(c.modelMatrix); expect(clone24.primitiveType).toEqual(c.primitiveType); expect(clone24.vertexArray).toBe(c.vertexArray); expect(clone24.count).toEqual(c.count); expect(clone24.offset).toEqual(c.offset); expect(clone24.instanceCount).toEqual(c.instanceCount); expect(clone24.shaderProgram).toBe(c.shaderProgram); expect(clone24.uniformMap).toBe(c.uniformMap); expect(clone24.renderState).toBe(c.renderState); expect(clone24.framebuffer).toBe(c.framebuffer); expect(clone24.pass).toEqual(c.pass); expect(clone24.executeInClosestFrustum).toEqual(c.executeInClosestFrustum); expect(clone24.owner).toBe(c.owner); expect(clone24.debugShowBoundingVolume).toEqual(c.debugShowBoundingVolume); expect(clone24.debugOverlappingFrustums).toEqual(c.debugOverlappingFrustums); expect(clone24.castShadows).toEqual(c.castShadows); expect(clone24.receiveShadows).toEqual(c.receiveShadows); expect(clone24.pickId).toBe(c.pickId); expect(clone24.pickOnly).toBe(c.pickOnly); }); it("shallow clone returns undefined", function() { expect(import__9.DrawCommand.shallowClone()).toBeUndefined(); }); }); // packages/engine/Specs/Renderer/DrawSpec.js var import__10 = __toESM(require_Cesium(), 1); describe( "Renderer/Draw", function() { let context; let sp; let va; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); afterEach(function() { sp = sp && sp.destroy(); va = va && va.destroy(); }); it("draws a white point", function() { const fs = "void main() { out_FragColor = vec4(1.0); }"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("draws a white point with an index buffer", function() { const context2 = createContext_default(); const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context: context2, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); const indexBuffer = import__10.Buffer.createIndexBuffer({ context: context2, typedArray: new Uint16Array([0, 0]), usage: import__10.BufferUsage.STATIC_DRAW, indexDatatype: import__10.IndexDatatype.UNSIGNED_SHORT }); va = new import__10.VertexArray({ context: context2, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context: context2, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ], indexBuffer }); import__10.ClearCommand.ALL.execute(context2); expect(context2).toReadPixels([0, 0, 0, 255]); const command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va }); command.execute(context2); expect(context2).toReadPixels([255, 255, 255, 255]); sp = sp.destroy(); va = va.destroy(); context2.destroyForSpecs(); }); it("draws a red point with two vertex buffers", function() { const vs = "in vec4 position;in mediump float intensity;out mediump float fs_intensity;void main() { gl_PointSize = 1.0; gl_Position = position; fs_intensity = intensity;}"; const fs = "in mediump float fs_intensity; void main() { out_FragColor = vec4(fs_intensity, 0.0, 0.0, 1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0, intensity: 1 } }); va = new import__10.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 }, { index: 1, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([1]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 1 } ] }); import__10.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); const command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va }); command.execute(context); expect(context).toReadPixels([255, 0, 0, 255]); }); it("draws a red point with one interleaved vertex buffers", function() { const vs = "in vec4 position;in mediump float intensity;out mediump float fs_intensity;void main() { gl_PointSize = 1.0; gl_Position = position; fs_intensity = intensity;}"; const fs = "in mediump float fs_intensity; void main() { out_FragColor = vec4(fs_intensity, 0.0, 0.0, 1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0, intensity: 1 } }); const stride = 5 * Float32Array.BYTES_PER_ELEMENT; const vertexBuffer = import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1, 1]), usage: import__10.BufferUsage.STATIC_DRAW }); va = new import__10.VertexArray({ context, attributes: [ { index: 0, vertexBuffer, componentsPerAttribute: 4, offsetInBytes: 0, strideInBytes: stride }, { index: 1, vertexBuffer, componentsPerAttribute: 1, offsetInBytes: 4 * Float32Array.BYTES_PER_ELEMENT, strideInBytes: stride } ] }); import__10.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); const command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va }); command.execute(context); expect(context).toReadPixels([255, 0, 0, 255]); }); it("draws with scissor test", function() { const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__10.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); import__10.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); let command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, renderState: import__10.RenderState.fromCache({ scissorTest: { enabled: true, rectangle: new import__10.BoundingRectangle(1, 1, 0, 0) } }) }); command.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, renderState: import__10.RenderState.fromCache({ scissorTest: { enabled: true, rectangle: new import__10.BoundingRectangle(0, 0, 1, 1) } }) }); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); }); it("draws with color mask", function() { const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__10.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); import__10.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); let command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, renderState: import__10.RenderState.fromCache({ colorMask: { red: true, green: false, blue: false, alpha: false } }) }); command.execute(context); expect(context).toReadPixels([255, 0, 0, 255]); command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, renderState: import__10.RenderState.fromCache({ colorMask: { red: false, green: false, blue: true, alpha: false } }) }); command.execute(context); expect(context).toReadPixels([255, 0, 255, 255]); }); it("draws with additive blending", function() { const cxt = createContext_default({ webgl: { alpha: true } }); const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(0.5); }"; const sp2 = import__10.ShaderProgram.fromCache({ context: cxt, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); const va2 = new import__10.VertexArray({ context: cxt, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context: cxt, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); import__10.ClearCommand.ALL.execute(cxt); expect(cxt).toReadPixels([0, 0, 0, 0]); const command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp2, vertexArray: va2, renderState: import__10.RenderState.fromCache({ blending: { enabled: true, equationRgb: import__10.WebGLConstants.FUNC_ADD, // Optional, default equationAlpha: import__10.WebGLConstants.FUNC_ADD, // Optional, default functionSourceRgb: import__10.WebGLConstants.ONE, // Optional, default functionSourceAlpha: import__10.WebGLConstants.ONE, // Optional, default functionDestinationRgb: import__10.WebGLConstants.ONE, functionDestinationAlpha: import__10.WebGLConstants.ONE } }) }); command.execute(cxt); expect({ context: cxt, epsilon: 1 }).toReadPixels([127, 127, 127, 127]); command.execute(cxt); expect({ context: cxt, epsilon: 1 }).toReadPixels([254, 254, 254, 254]); sp2.destroy(); va2.destroy(); cxt.destroyForSpecs(); }); it("draws with alpha blending", function() { const cxt = createContext_default({ webgl: { alpha: true } }); const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0, 1.0, 1.0, 0.5); }"; const sp2 = import__10.ShaderProgram.fromCache({ context: cxt, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); const va2 = new import__10.VertexArray({ context: cxt, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context: cxt, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); import__10.ClearCommand.ALL.execute(cxt); expect(cxt).toReadPixels([0, 0, 0, 0]); const command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp2, vertexArray: va2, renderState: import__10.RenderState.fromCache({ blending: { enabled: true, equationRgb: import__10.WebGLConstants.FUNC_ADD, equationAlpha: import__10.WebGLConstants.FUNC_SUBTRACT, // does not actually matter functionSourceRgb: import__10.WebGLConstants.SRC_ALPHA, functionSourceAlpha: import__10.WebGLConstants.ONE, // Don't blend alpha functionDestinationRgb: import__10.WebGLConstants.ONE_MINUS_SRC_ALPHA, functionDestinationAlpha: import__10.WebGLConstants.ZERO } }) }); command.execute(cxt); expect({ context: cxt, epsilon: 1 }).toReadPixels([127, 127, 127, 127]); command.execute(cxt); expect({ context: cxt, epsilon: 2 }).toReadPixels([191, 191, 191, 127]); sp2.destroy(); va2.destroy(); cxt.destroyForSpecs(); }); it("draws with blend color", function() { const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0, 1.0, 1.0, 1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__10.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); import__10.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); const command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, renderState: import__10.RenderState.fromCache({ blending: { enabled: true, color: { red: 0.5, green: 0.5, blue: 0.5, alpha: 0.5 }, equationRgb: import__10.WebGLConstants.FUNC_SUBTRACT, equationAlpha: import__10.WebGLConstants.FUNC_SUBTRACT, functionSourceRgb: import__10.WebGLConstants.CONSTANT_COLOR, functionSourceAlpha: import__10.WebGLConstants.ONE, functionDestinationRgb: import__10.WebGLConstants.ZERO, functionDestinationAlpha: import__10.WebGLConstants.ZERO } }) }); command.execute(context); expect({ context, epsilon: 1 }).toReadPixels([128, 128, 128, 255]); }); it("draws with culling", function() { const vs = "in vec4 position; void main() { gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__10.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([ -1e3, -1e3, 0, 1, 1e3, -1e3, 0, 1, -1e3, 1e3, 0, 1, 1e3, 1e3, 0, 1 ]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); import__10.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); let command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.TRIANGLE_STRIP, shaderProgram: sp, vertexArray: va, renderState: import__10.RenderState.fromCache({ cull: { enabled: true, face: import__10.WebGLConstants.FRONT } }) }); command.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.TRIANGLE_STRIP, shaderProgram: sp, vertexArray: va, renderState: import__10.RenderState.fromCache({ cull: { enabled: true, face: import__10.WebGLConstants.BACK } }) }); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); }); it("draws with front face winding order", function() { const vs = "in vec4 position; void main() { gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__10.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([ -1e3, -1e3, 0, 1, 1e3, -1e3, 0, 1, -1e3, 1e3, 0, 1, 1e3, 1e3, 0, 1 ]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); import__10.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); let command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.TRIANGLE_STRIP, shaderProgram: sp, vertexArray: va, renderState: import__10.RenderState.fromCache({ frontFace: import__10.WindingOrder.CLOCKWISE, cull: { enabled: true, face: import__10.WebGLConstants.BACK } }) }); command.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.TRIANGLE_STRIP, shaderProgram: sp, vertexArray: va, renderState: import__10.RenderState.fromCache({ frontFace: import__10.WindingOrder.COUNTER_CLOCKWISE, cull: { enabled: true, face: import__10.WebGLConstants.BACK } }) }); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); }); it("draws with the depth test", function() { const vs = "in vec4 position; void main() { gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__10.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([ -1e3, -1e3, 0, 1, 1e3, -1e3, 0, 1, -1e3, 1e3, 0, 1, 1e3, 1e3, 0, 1 ]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); const command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.TRIANGLE_STRIP, shaderProgram: sp, vertexArray: va, renderState: import__10.RenderState.fromCache({ depthTest: { enabled: true, func: import__10.WebGLConstants.LEQUAL } }) }); const clearCommand = new import__10.ClearCommand({ color: new import__10.Color(0, 0, 0, 0), depth: 1 }); clearCommand.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); clearCommand.color = new import__10.Color(0, 0, 0, 0); clearCommand.depth = 0; clearCommand.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); command.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); }); it("draws with depth range", function() { const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(gl_DepthRange.near, gl_DepthRange.far, 0.0, 1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__10.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); import__10.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); const command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, renderState: import__10.RenderState.fromCache({ depthRange: { near: 0.25, far: 0.75 } }) }); command.execute(context); expect(context).toReadPixels([64, 191, 0, 255]); }); it("draws with line width", function() { const vs = "in vec4 position; void main() { gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__10.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([ -1e3, -1e3, 0, 1, 1e3, 1e3, 0, 1 ]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); import__10.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); const command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.LINES, shaderProgram: sp, vertexArray: va, renderState: import__10.RenderState.fromCache({ lineWidth: import__10.ContextLimits.maximumAliasedLineWidth // May only be 1. }) }); command.execute(context); expect(context).notToReadPixels([0, 0, 0, 255]); }); it("draws with polygon offset", function() { const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__10.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); import__10.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); const command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, renderState: import__10.RenderState.fromCache({ polygonOffset: { enabled: true, factor: 1, units: 1 } }) }); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); }); it("draws with sample coverage", function() { if (!context.antialias) { return; } const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__10.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); import__10.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); let command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, renderState: import__10.RenderState.fromCache({ sampleCoverage: { enabled: true, value: 0, invert: false } }) }); command.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, renderState: import__10.RenderState.fromCache({ sampleCoverage: { enabled: false } }) }); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); }); it("draws with stencil test (front)", function() { if (context.stencilBits === 0) { return; } const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__10.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([ -1e3, -1e3, 0, 1, 1e3, -1e3, 0, 1, -1e3, 1e3, 0, 1, 1e3, 1e3, 0, 1 ]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); const rs = import__10.RenderState.fromCache({ stencilTest: { enabled: true, frontFunction: import__10.WebGLConstants.EQUAL, reference: 1, mask: 1 } }); import__10.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); let command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.TRIANGLE_STRIP, shaderProgram: sp, vertexArray: va, renderState: rs }); command.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.TRIANGLE_STRIP, shaderProgram: sp, vertexArray: va, renderState: import__10.RenderState.fromCache({ colorMask: { red: false, green: false, blue: false, alpha: false }, stencilTest: { enabled: true, frontOperation: { zPass: import__10.WebGLConstants.INCR } } }) }); command.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.TRIANGLE_STRIP, shaderProgram: sp, vertexArray: va, renderState: rs }); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); }); it("draws with stencil test (back)", function() { if (context.stencilBits === 0) { return; } const vs = "in vec4 position; void main() { gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__10.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([ -1e3, -1e3, 0, 1, 1e3, -1e3, 0, 1, -1e3, 1e3, 0, 1, 1e3, 1e3, 0, 1 ]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); const rs = import__10.RenderState.fromCache({ frontFace: import__10.WindingOrder.CLOCKWISE, stencilTest: { enabled: true, backFunction: import__10.WebGLConstants.NOTEQUAL, reference: 0 } }); import__10.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); let command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.TRIANGLE_STRIP, shaderProgram: sp, vertexArray: va, renderState: rs }); command.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.TRIANGLE_STRIP, shaderProgram: sp, vertexArray: va, renderState: import__10.RenderState.fromCache({ frontFace: import__10.WindingOrder.CLOCKWISE, colorMask: { red: false, green: false, blue: false, alpha: false }, stencilTest: { enabled: true, backOperation: { zPass: import__10.WebGLConstants.INVERT } } }) }); command.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.TRIANGLE_STRIP, shaderProgram: sp, vertexArray: va, renderState: rs }); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); }); it("draws with an offset and count", function() { const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__10.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, -1, 0, 0, 0, 1]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); import__10.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); let command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, offset: 0, count: 1, shaderProgram: sp, vertexArray: va }); command.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, offset: 1, count: 1, shaderProgram: sp, vertexArray: va }); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); }); it("draws two instances of a point with different per-instance colors", function() { const vs = "in vec4 position;in vec4 color;out vec4 v_color;void main() { gl_PointSize = 1.0; gl_Position = position; v_color = color;}"; const fs = "in vec4 v_color; void main() { out_FragColor = v_color; }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0, color: 1 } }); va = new import__10.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 }, { index: 1, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Uint8Array([255, 0, 0, 255, 0, 255, 0, 255]), usage: import__10.BufferUsage.STATIC_DRAW }), componentDatatype: import__10.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 4, normalize: true, instanceDivisor: 1 } ] }); import__10.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); const command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, instanceCount: 2, renderState: import__10.RenderState.fromCache({ blending: import__10.BlendingState.ADDITIVE_BLEND }) }); command.execute(context); expect(context).toReadPixels([255, 255, 0, 255]); }); it("fails to draw (missing command)", function() { expect(function() { context.draw(); }).toThrowDeveloperError(); }); it("fails to draw (missing shaderProgram)", function() { expect(function() { context.draw({ primitiveType: import__10.PrimitiveType.POINTS }); }).toThrowDeveloperError(); }); it("fails to draw (missing primitiveType)", function() { const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs }); expect(function() { context.draw({ shaderProgram: sp }); }).toThrowDeveloperError(); }); it("fails to draw (primitiveType)", function() { const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs }); expect(function() { context.draw({ primitiveType: "invalid value", shaderProgram: sp }); }).toThrowDeveloperError(); }); it("fails to draw (missing vertexArray)", function() { const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs }); expect(function() { context.draw({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp }); }).toThrowDeveloperError(); }); it("fails to draw (negative offset)", function() { const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs }); expect(function() { context.draw({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: new import__10.VertexArray({ context }), offset: -1, count: 1 }); }).toThrowDeveloperError(); }); it("throws if instanceCount is less than one", function() { const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__10.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); const command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, instanceCount: -1 }); expect(function() { command.execute(context); }).toThrowDeveloperError(); }); describe("WebGL1", function() { let webgl1Context; beforeAll(() => { webgl1Context = createContext_default({ requestWebgl1: true }); }); afterAll(() => { webgl1Context.destroyForSpecs(); }); it("throws when instanceCount is greater than one and instancing is disabled", function() { const webgl1Context2 = createContext_default({ requestWebgl1: true }); const instancedArrays = webgl1Context2._instancedArrays; webgl1Context2._instancedArrays = void 0; const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__10.ShaderProgram.fromCache({ context: webgl1Context2, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__10.VertexArray({ context: webgl1Context2, attributes: [ { index: 0, vertexBuffer: import__10.Buffer.createVertexBuffer({ context: webgl1Context2, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__10.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); const command = new import__10.DrawCommand({ primitiveType: import__10.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, instanceCount: 2 }); expect(function() { command.execute(webgl1Context2); }).toThrowDeveloperError(); context._instancedArrays = instancedArrays; }); }); }, "WebGL" ); // packages/engine/Specs/Renderer/FramebufferManagerSpec.js var import__11 = __toESM(require_Cesium(), 1); describe( "Renderer/FramebufferManager", function() { let context; let fbm; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); afterEach(function() { if ((0, import__11.defined)(fbm)) { fbm.destroy(); } }); it("throws when constructor has no enabled attachments", function() { expect(function() { fbm = new import__11.FramebufferManager({ color: false }); }).toThrowDeveloperError(); }); it("throws when constructor enables depth and depth-stencil attachments", function() { expect(function() { fbm = new import__11.FramebufferManager({ depth: true, depthStencil: true }); }).toThrowDeveloperError(); }); it("throws if update is called without width or height", function() { fbm = new import__11.FramebufferManager(); expect(function() { fbm.update(context); }).toThrowDeveloperError(); expect(function() { fbm.update(context, 1); }).toThrowDeveloperError(); expect(function() { fbm.update(context, void 0, 1); }).toThrowDeveloperError(); }); it("throws if getting color texture at an invalid index", function() { fbm = new import__11.FramebufferManager({ colorAttachmentsLength: 2, createColorAttachments: false }); expect(function() { fbm.getColorTexture(2); }).toThrowDeveloperError(); }); it("throws if setting color texture when createColorAttachments is true", function() { fbm = new import__11.FramebufferManager(); expect(function() { fbm.setColorTexture(); }).toThrowDeveloperError(); }); it("throws if setting color texture at an invalid index", function() { fbm = new import__11.FramebufferManager({ colorAttachmentsLength: 2, createColorAttachments: false }); expect(function() { fbm.setColorTexture({}, 2); }).toThrowDeveloperError(); }); it("sets color textures", function() { fbm = new import__11.FramebufferManager({ colorAttachmentsLength: 2, createColorAttachments: false }); const texture0 = new import__11.Texture({ context, width: 1, height: 1, pixelFormat: import__11.PixelFormat.RGB }); const texture1 = new import__11.Texture({ context, width: 1, height: 1, pixelFormat: import__11.PixelFormat.RGBA }); fbm.setColorTexture(texture0, 0); fbm.setColorTexture(texture1, 1); expect(fbm._colorTextures.length).toEqual(2); expect(fbm.getColorTexture(0)).toEqual(texture0); expect(fbm.getColorTexture(1)).toEqual(texture1); texture0.destroy(); texture1.destroy(); }); it("throws if setting depth attachments when createDepthAttachments is true", function() { fbm = new import__11.FramebufferManager(); expect(function() { fbm.setDepthTexture(); }).toThrowDeveloperError(); expect(function() { fbm.setDepthRenderbuffer(); }).toThrowDeveloperError(); }); it("sets depth attachments", function() { fbm = new import__11.FramebufferManager({ createDepthAttachments: false }); const texture = new import__11.Texture({ context, width: 1, height: 1 }); fbm.setDepthTexture(texture); expect(fbm.getDepthTexture()).toBeDefined(); expect(fbm.getDepthTexture()).toEqual(texture); texture.destroy(); const renderbuffer = new import__11.Renderbuffer({ context, width: 1, height: 1 }); fbm.setDepthRenderbuffer(renderbuffer); expect(fbm.getDepthRenderbuffer()).toBeDefined(); expect(fbm.getDepthRenderbuffer()).toEqual(renderbuffer); renderbuffer.destroy(); }); it("throws if setting depth-stencil attachments when createDepthStencilAttachments is true", function() { fbm = new import__11.FramebufferManager(); expect(function() { fbm.setDepthStencilTexture(); }).toThrowDeveloperError(); expect(function() { fbm.setDepthStencilRenderbuffer(); }).toThrowDeveloperError(); }); it("sets depth-stencil attachments", function() { fbm = new import__11.FramebufferManager({ createDepthAttachments: false }); const texture = new import__11.Texture({ context, width: 1, height: 1 }); fbm.setDepthStencilTexture(texture); expect(fbm.getDepthStencilTexture()).toBeDefined(); expect(fbm.getDepthStencilTexture()).toEqual(texture); texture.destroy(); const renderbuffer = new import__11.Renderbuffer({ context, width: 1, height: 1 }); fbm.setDepthStencilRenderbuffer(renderbuffer); expect(fbm.getDepthStencilRenderbuffer()).toBeDefined(); expect(fbm.getDepthStencilRenderbuffer()).toEqual(renderbuffer); renderbuffer.destroy(); }); it("creates framebuffer", function() { fbm = new import__11.FramebufferManager(); expect(fbm.framebuffer).toBeUndefined(); fbm.update(context, 1, 1); const framebuffer2 = fbm.framebuffer; expect(framebuffer2).toBeDefined(); expect(framebuffer2.numberOfColorAttachments).toEqual(1); }); it("destroyFramebuffer destroys framebuffer", function() { fbm = new import__11.FramebufferManager(); fbm.update(context, 1, 1); expect(fbm.framebuffer.isDestroyed()).toEqual(false); spyOn(import__11.Framebuffer.prototype, "destroy").and.callThrough(); fbm.destroyFramebuffer(); expect(fbm.framebuffer).toBeUndefined(); expect(import__11.Framebuffer.prototype.destroy).toHaveBeenCalled(); }); it("creates single color attachment", function() { fbm = new import__11.FramebufferManager(); fbm.update(context, 1, 1); const texture = fbm.getColorTexture(); expect(texture).toBeDefined(); expect(texture.width).toEqual(1); expect(texture.height).toEqual(1); expect(texture.pixelFormat).toEqual(import__11.PixelFormat.RGBA); expect(texture.pixelDatatype).toEqual(import__11.PixelDatatype.UNSIGNED_BYTE); }); it("creates multiple color attachments", function() { if (!context.drawBuffers) { return; } const length2 = 2; fbm = new import__11.FramebufferManager({ colorAttachmentsLength: length2 }); fbm.update(context, 1, 1); for (let i = 0; i < length2; ++i) { const texture = fbm.getColorTexture(i); expect(texture).toBeDefined(); expect(texture.width).toEqual(1); expect(texture.height).toEqual(1); expect(texture.pixelFormat).toEqual(import__11.PixelFormat.RGBA); expect(texture.pixelDatatype).toEqual(import__11.PixelDatatype.UNSIGNED_BYTE); } }); it("creates depth attachments", function() { fbm = new import__11.FramebufferManager({ color: false, depth: true, supportsDepthTexture: true }); fbm.update(context, 1, 1); if (context.depthTexture) { const texture = fbm.getDepthTexture(); expect(texture).toBeDefined(); expect(texture.width).toEqual(1); expect(texture.height).toEqual(1); expect(texture.pixelFormat).toEqual(import__11.PixelFormat.DEPTH_COMPONENT); expect(texture.pixelDatatype).toEqual(import__11.PixelDatatype.UNSIGNED_INT); } else { const renderbuffer = fbm.getDepthRenderbuffer(); expect(renderbuffer).toBeDefined(); expect(renderbuffer.width).toEqual(1); expect(renderbuffer.height).toEqual(1); expect(renderbuffer.format).toEqual( import__11.RenderbufferFormat.DEPTH_COMPONENT16 ); } }); it("creates depth-stencil attachments", function() { fbm = new import__11.FramebufferManager({ color: false, depthStencil: true, supportsDepthTexture: true }); fbm.update(context, 1, 1); if (context.depthTexture) { const texture = fbm.getDepthStencilTexture(); expect(texture).toBeDefined(); expect(texture.width).toEqual(1); expect(texture.height).toEqual(1); expect(texture.pixelFormat).toEqual(import__11.PixelFormat.DEPTH_STENCIL); expect(texture.pixelDatatype).toEqual(import__11.PixelDatatype.UNSIGNED_INT_24_8); } else { const renderbuffer = fbm.getDepthStencilRenderbuffer(); expect(renderbuffer).toBeDefined(); expect(renderbuffer.width).toEqual(1); expect(renderbuffer.height).toEqual(1); expect(renderbuffer.format).toEqual(import__11.RenderbufferFormat.DEPTH_STENCIL); } }); it("creates renderbuffer depth attachments if supportsDepthTexture is false", function() { fbm = new import__11.FramebufferManager({ depth: true }); fbm.update(context, 1, 1); expect(fbm.getDepthTexture()).toBeUndefined(); expect(fbm.getDepthRenderbuffer()).toBeDefined(); }); it("creates renderbuffer depth attachments if supportsDepthTexture is true but context.depthTexture is false", function() { fbm = new import__11.FramebufferManager({ depth: true, supportsDepthTexture: true }); const depthTexture = context._depthTexture; context._depthTexture = false; const webgl2 = context._webgl2; context._webgl2 = false; fbm.update(context, 1, 1); expect(fbm.getDepthTexture()).toBeUndefined(); expect(fbm.getDepthRenderbuffer()).toBeDefined(); context._depthTexture = depthTexture; context._webgl2 = webgl2; }); it("doesn't create multisample resources if msaa is unsupported", function() { fbm = new import__11.FramebufferManager({ depth: true, supportsDepthTexture: true }); const webgl2 = context._webgl2; context._webgl2 = false; fbm.update(context, 1, 1, 4); expect(fbm._multisampleFramebuffer).toBeUndefined(); context._webgl2 = webgl2; }); it("destroys attachments and framebuffer", function() { if (!context.drawBuffers) { return; } fbm = new import__11.FramebufferManager({ colorAttachmentsLength: 2, depth: true }); fbm.update(context, 1, 1); expect(fbm.framebuffer).toBeDefined(); expect(fbm.getColorTexture(0)).toBeDefined(); expect(fbm.getColorTexture(1)).toBeDefined(); expect(fbm.getDepthRenderbuffer()).toBeDefined(); spyOn(import__11.Framebuffer.prototype, "destroy").and.callThrough(); spyOn(import__11.Renderbuffer.prototype, "destroy").and.callThrough(); spyOn(import__11.Texture.prototype, "destroy").and.callThrough(); fbm.destroy(); expect(import__11.Framebuffer.prototype.destroy.calls.count()).toEqual(1); expect(fbm.framebuffer).toBeUndefined(); expect(import__11.Renderbuffer.prototype.destroy.calls.count()).toEqual(1); expect(fbm.getDepthRenderbuffer()).toBeUndefined(); expect(import__11.Texture.prototype.destroy.calls.count()).toEqual(2); expect(fbm.getColorTexture(0)).toBeUndefined(); expect(fbm.getColorTexture(1)).toBeUndefined(); }); it("does not destroy attachments that are not created by FramebufferManager", function() { fbm = new import__11.FramebufferManager({ createColorAttachments: false, createDepthAttachments: false }); const colorTexture = new import__11.Texture({ context, width: 1, height: 1, pixelFormat: import__11.PixelFormat.RGBA }); fbm.setColorTexture(colorTexture, 0); const depthRenderbuffer = new import__11.Renderbuffer({ context, width: 1, height: 1 }); fbm.setDepthRenderbuffer(depthRenderbuffer); fbm.update(context, 1, 1); fbm.destroy(); expect(fbm.framebuffer).toBeUndefined(); expect(fbm.getColorTexture()).toBeDefined(); expect(fbm.getDepthRenderbuffer()).toBeDefined(); colorTexture.destroy(); depthRenderbuffer.destroy(); }); it("does not destroy resources if texture dimensions haven't changed", function() { fbm = new import__11.FramebufferManager(); spyOn(import__11.FramebufferManager.prototype, "destroy").and.callThrough(); fbm.update(context, 1, 1); fbm.update(context, 1, 1); expect(import__11.FramebufferManager.prototype.destroy.calls.count()).toEqual(1); }); it("destroys resources after texture dimensions change", function() { fbm = new import__11.FramebufferManager(); spyOn(import__11.FramebufferManager.prototype, "destroy").and.callThrough(); fbm.update(context, 1, 1); fbm.update(context, 2, 1); expect(import__11.FramebufferManager.prototype.destroy.calls.count()).toEqual(2); }); it("destroys resources after numSamples changes", function() { if (!context.webgl2) { return; } fbm = new import__11.FramebufferManager(); spyOn(import__11.FramebufferManager.prototype, "destroy").and.callThrough(); fbm.update(context, 1, 1); fbm.update(context, 1, 1, 2); expect(import__11.FramebufferManager.prototype.destroy.calls.count()).toEqual(2); }); it("destroys resources after pixel datatype changes", function() { fbm = new import__11.FramebufferManager({ pixelDatatype: import__11.PixelDatatype.UNSIGNED_INT }); spyOn(import__11.FramebufferManager.prototype, "destroy").and.callThrough(); fbm.update(context, 1, 1); fbm.update(context, 1, 1, 1, import__11.PixelDatatype.UNSIGNED_BYTE); expect(import__11.FramebufferManager.prototype.destroy.calls.count()).toEqual(2); }); it("destroys resources after pixel format changes", function() { fbm = new import__11.FramebufferManager({ pixelFormat: import__11.PixelFormat.RGB }); spyOn(import__11.FramebufferManager.prototype, "destroy").and.callThrough(); fbm.update(context, 1, 1); fbm.update(context, 1, 1, 1, void 0, import__11.PixelFormat.RGBA); expect(import__11.FramebufferManager.prototype.destroy.calls.count()).toEqual(2); }); it("destroys resources after new attachment is set", function() { fbm = new import__11.FramebufferManager({ createColorAttachments: false }); const texture = new import__11.Texture({ context, width: 1, height: 1 }); spyOn(import__11.FramebufferManager.prototype, "destroy").and.callThrough(); fbm.setColorTexture(texture, 0); fbm.update(context, 1, 1); fbm.setColorTexture(texture, 0); fbm.update(context, 1, 1); expect(import__11.FramebufferManager.prototype.destroy.calls.count()).toEqual(1); }); it("executes clear command", function() { import__11.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); fbm = new import__11.FramebufferManager(); fbm.update(context, 1, 1); const clearCommand = new import__11.ClearCommand({ color: new import__11.Color(1, 0, 0, 1) }); fbm.clear(context, clearCommand); const fs = "uniform sampler2D u_texture; void main() { out_FragColor = texture(u_texture, vec2(0.0)); }"; const uniformMap = { u_texture: function() { return fbm.getColorTexture(); } }; expect({ context, fragmentShader: fs, uniformMap }).contextToRender([255, 0, 0, 255]); }); it("preserves clear command framebuffer after clear()", function() { import__11.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); fbm = new import__11.FramebufferManager(); fbm.update(context, 1, 1); const fb = new import__11.Framebuffer({ context }); const clearCommand = new import__11.ClearCommand({ color: new import__11.Color(1, 0, 0, 1), framebuffer: fb }); fbm.clear(context, clearCommand); expect(clearCommand.framebuffer).toBe(fb); const fs = "uniform sampler2D u_texture; void main() { out_FragColor = texture(u_texture, vec2(0.0)); }"; const uniformMap = { u_texture: function() { return fbm.getColorTexture(); } }; expect({ context, fragmentShader: fs, uniformMap }).contextToRender([255, 0, 0, 255]); fb.destroy(); }); it("returns framebuffer status", function() { fbm = new import__11.FramebufferManager(); fbm.update(context, 1, 1); expect(fbm.status).toEqual(fbm.framebuffer.status); }); }, "WebGL" ); // packages/engine/Specs/Renderer/FramebufferSpec.js var import__12 = __toESM(require_Cesium(), 1); describe( "Renderer/Framebuffer", function() { let context; let sp; let va; let framebuffer2; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); afterEach(function() { sp = sp && sp.destroy(); va = va && va.destroy(); framebuffer2 = framebuffer2 && framebuffer2.destroy(); }); it("has a color texture attachment", function() { framebuffer2 = new import__12.Framebuffer({ context, colorTextures: [ new import__12.Texture({ context, width: 1, height: 1 }) ] }); expect(framebuffer2.getColorTexture(0)).toBeDefined(); }); it("has a color renderbuffer attachment", function() { framebuffer2 = new import__12.Framebuffer({ context, colorRenderbuffers: [ new import__12.Renderbuffer({ context, format: import__12.RenderbufferFormat.RGBA4 }) ] }); expect(framebuffer2.getColorRenderbuffer(0)).toBeDefined(); }); it("has a depth texture attachment", function() { if (context.depthTexture) { framebuffer2 = new import__12.Framebuffer({ context, depthTexture: new import__12.Texture({ context, width: 1, height: 1, pixelFormat: import__12.PixelFormat.DEPTH_COMPONENT, pixelDatatype: import__12.PixelDatatype.UNSIGNED_SHORT }) }); expect(framebuffer2.depthTexture).toBeDefined(); } }); it("has a depth renderbuffer attachment", function() { framebuffer2 = new import__12.Framebuffer({ context, depthRenderbuffer: new import__12.Renderbuffer({ context, format: import__12.RenderbufferFormat.DEPTH_COMPONENT16 }) }); expect(framebuffer2.depthRenderbuffer).toBeDefined(); }); it("has a stencil renderbuffer attachment", function() { framebuffer2 = new import__12.Framebuffer({ context, stencilRenderbuffer: new import__12.Renderbuffer({ context, format: import__12.RenderbufferFormat.STENCIL_INDEX8 }) }); expect(framebuffer2.stencilRenderbuffer).toBeDefined(); }); it("has a depth-stencil texture attachment", function() { if (context.depthTexture) { framebuffer2 = new import__12.Framebuffer({ context, depthStencilTexture: new import__12.Texture({ context, width: 1, height: 1, pixelFormat: import__12.PixelFormat.DEPTH_STENCIL, pixelDatatype: import__12.PixelDatatype.UNSIGNED_INT_24_8 }) }); expect(framebuffer2.depthStencilTexture).toBeDefined(); } }); it("has a depth-stencil renderbuffer attachment", function() { framebuffer2 = new import__12.Framebuffer({ context, depthStencilRenderbuffer: new import__12.Renderbuffer({ context, format: import__12.RenderbufferFormat.DEPTH_STENCIL }) }); expect(framebuffer2.depthStencilRenderbuffer).toBeDefined(); }); it("has a depth attachment", function() { framebuffer2 = new import__12.Framebuffer({ context }); expect(framebuffer2.hasDepthAttachment).toEqual(false); framebuffer2.destroy(); framebuffer2 = new import__12.Framebuffer({ context, depthRenderbuffer: new import__12.Renderbuffer({ context, format: import__12.RenderbufferFormat.DEPTH_COMPONENT16 }) }); expect(framebuffer2.hasDepthAttachment).toEqual(true); }); it("clears a color attachment", function() { import__12.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); const colorTexture = new import__12.Texture({ context, width: 1, height: 1 }); framebuffer2 = new import__12.Framebuffer({ context, colorTextures: [colorTexture] }); const clearCommand = new import__12.ClearCommand({ color: new import__12.Color(0, 1, 0, 1), framebuffer: framebuffer2 }); clearCommand.execute(context); const fs = "uniform sampler2D u_texture; void main() { out_FragColor = texture(u_texture, vec2(0.0)); }"; const uniformMap = { u_texture: function() { return colorTexture; } }; expect({ context, fragmentShader: fs, uniformMap }).contextToRender([0, 255, 0, 255]); }); it("clears a cube map face color attachment", function() { let cubeMap = new import__12.CubeMap({ context, width: 1, height: 1 }); import__12.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); framebuffer2 = new import__12.Framebuffer({ context, colorTextures: [cubeMap.positiveX], destroyAttachments: false }); const clearCommand = new import__12.ClearCommand({ color: new import__12.Color(0, 1, 0, 1), framebuffer: framebuffer2 }); clearCommand.execute(context); const fs = "uniform samplerCube u_cubeMap; void main() { out_FragColor = czm_textureCube(u_cubeMap, vec3(1.0, 0.0, 0.0)); }"; const uniformMap = { u_cubeMap: function() { return cubeMap; } }; expect({ context, fragmentShader: fs, uniformMap }).contextToRender([0, 255, 0, 255]); cubeMap = cubeMap.destroy(); }); function renderColorTexture(framebuffer3, color, expectedColor) { const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "uniform vec4 color; void main() { out_FragColor = color; }"; sp = import__12.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__12.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__12.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__12.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); const uniformMap = { color: function() { return color; } }; const command = new import__12.DrawCommand({ primitiveType: import__12.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, uniformMap, framebuffer: framebuffer3 }); command.execute(context); expect({ context, framebuffer: framebuffer3 }).toReadPixels(expectedColor); } it("draws to a color attachment", function() { framebuffer2 = new import__12.Framebuffer({ context, colorTextures: [ new import__12.Texture({ context, width: 1, height: 1 }) ] }); renderColorTexture(framebuffer2, new import__12.Color(0, 1, 0, 1), [ 0, 255, 0, 255 ]); }); it("draws to a floating-point color attachment", function() { if (!context.colorBufferFloat) { return; } framebuffer2 = new import__12.Framebuffer({ context, colorTextures: [ new import__12.Texture({ context, width: 1, height: 1, pixelDatatype: import__12.PixelDatatype.FLOAT }) ] }); renderColorTexture(framebuffer2, new import__12.Color(0.5, 1.5, 2, 1), [ 0.5, 1.5, 2, 1 ]); }); it("draws to a half floating-point color attachment", function() { if (!context.colorBufferHalfFloat) { return; } framebuffer2 = new import__12.Framebuffer({ context, colorTextures: [ new import__12.Texture({ context, width: 1, height: 1, pixelDatatype: import__12.PixelDatatype.HALF_FLOAT }) ] }); renderColorTexture(framebuffer2, new import__12.Color(0.5, 1.5, 2, 1), [ 14336, 15872, 16384, 15360 ]); }); function renderDepthAttachment(framebuffer3, texture) { import__12.ClearCommand.ALL.execute(context); const framebufferClear = new import__12.ClearCommand({ depth: 1, framebuffer: framebuffer3 }); framebufferClear.execute(context); const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(0.0, 1.0, 0.0, 1.0); }"; sp = import__12.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__12.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__12.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__12.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); let command = new import__12.DrawCommand({ primitiveType: import__12.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, framebuffer: framebuffer3, renderState: import__12.RenderState.fromCache({ depthTest: { enabled: true } }) }); command.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); const vs2 = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs2 = "uniform sampler2D u_texture; void main() { out_FragColor = texture(u_texture, vec2(0.0)).rrrr; }"; let sp2 = import__12.ShaderProgram.fromCache({ context, vertexShaderSource: vs2, fragmentShaderSource: fs2, attributeLocations: { position: 0 } }); const uniformMap = { u_texture: function() { return texture; } }; command = new import__12.DrawCommand({ primitiveType: import__12.PrimitiveType.POINTS, shaderProgram: sp2, vertexArray: va, uniformMap }); command.execute(context); sp2 = sp2.destroy(); return context.readPixels(); } it("draws to a depth texture attachment", function() { if (context.depthTexture) { framebuffer2 = new import__12.Framebuffer({ context, colorTextures: [ new import__12.Texture({ context, width: 1, height: 1 }) ], depthTexture: new import__12.Texture({ context, width: 1, height: 1, pixelFormat: import__12.PixelFormat.DEPTH_COMPONENT, pixelDatatype: import__12.PixelDatatype.UNSIGNED_SHORT }) }); if (framebuffer2.status === import__12.WebGLConstants.FRAMEBUFFER_COMPLETE) { expect( renderDepthAttachment(framebuffer2, framebuffer2.depthTexture) ).toEqualEpsilon([128, 128, 128, 255], 1); } } }); it("draws to a depth-stencil texture attachment", function() { if (context.depthTexture) { framebuffer2 = new import__12.Framebuffer({ context, colorTextures: [ new import__12.Texture({ context, width: 1, height: 1 }) ], depthStencilTexture: new import__12.Texture({ context, width: 1, height: 1, pixelFormat: import__12.PixelFormat.DEPTH_STENCIL, pixelDatatype: import__12.PixelDatatype.UNSIGNED_INT_24_8 }) }); if (framebuffer2.status === import__12.WebGLConstants.FRAMEBUFFER_COMPLETE) { expect( renderDepthAttachment(framebuffer2, framebuffer2.depthStencilTexture) ).toEqualEpsilon([128, 128, 128, 255], 1); } } }); it("draws with a depth attachment", function() { framebuffer2 = new import__12.Framebuffer({ context, colorTextures: [ new import__12.Texture({ context, width: 1, height: 1 }) ], depthRenderbuffer: new import__12.Renderbuffer({ context, format: import__12.RenderbufferFormat.DEPTH_COMPONENT16, width: 1, height: 1 }) }); const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0, 1.0, 1.0, 1.0); }"; sp = import__12.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__12.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__12.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__12.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); const clearCommand = new import__12.ClearCommand({ color: new import__12.Color(0, 0, 0, 0), depth: 1, framebuffer: framebuffer2 }); clearCommand.execute(context); expect({ context, framebuffer: framebuffer2 }).toReadPixels([0, 0, 0, 0]); let command = new import__12.DrawCommand({ primitiveType: import__12.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, framebuffer: framebuffer2, renderState: import__12.RenderState.fromCache({ depthTest: { enabled: true, func: import__12.WebGLConstants.NEVER } }) }); command.execute(context); expect({ context, framebuffer: framebuffer2 }).toReadPixels([0, 0, 0, 0]); command = new import__12.DrawCommand({ primitiveType: import__12.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, framebuffer: framebuffer2, renderState: import__12.RenderState.fromCache({ depthTest: { enabled: true, func: import__12.WebGLConstants.ALWAYS } }) }); command.execute(context); expect({ context, framebuffer: framebuffer2 }).toReadPixels([255, 255, 255, 255]); }); it("draws with multiple render targets", function() { if (!context.drawBuffers) { return; } const source = new Uint8Array(4); const colorTexture0 = new import__12.Texture({ context, source: { arrayBufferView: source, width: 1, height: 1 } }); const colorTexture1 = new import__12.Texture({ context, source: { arrayBufferView: source, width: 1, height: 1 } }); framebuffer2 = new import__12.Framebuffer({ context, colorTextures: [colorTexture0, colorTexture1] }); import__12.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "layout (location = 0) out vec4 out_FragData_0;\n layout (location = 1) out vec4 out_FragData_1; \n void main() { out_FragData_0 = vec4(1.0, 0.0, 0.0, 1.0); out_FragData_1 = vec4(0.0, 1.0, 0.0, 1.0); }"; sp = import__12.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__12.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__12.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__12.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); let command = new import__12.DrawCommand({ primitiveType: import__12.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, framebuffer: framebuffer2 }); command.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); const vs2 = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs2 = "uniform sampler2D u_texture0; uniform sampler2D u_texture1; void main() { out_FragColor = texture(u_texture0, vec2(0.0)) + texture(u_texture1, vec2(0.0)); }"; let sp2 = import__12.ShaderProgram.fromCache({ context, vertexShaderSource: vs2, fragmentShaderSource: fs2, attributeLocations: { position: 0 } }); const uniformMap = { u_texture0: function() { return colorTexture0; }, u_texture1: function() { return colorTexture1; } }; command = new import__12.DrawCommand({ primitiveType: import__12.PrimitiveType.POINTS, shaderProgram: sp2, vertexArray: va, uniformMap }); command.execute(context); expect(context).toReadPixels([255, 255, 0, 255]); const clearCommand = new import__12.ClearCommand({ color: new import__12.Color(0, 0, 0, 0), framebuffer: framebuffer2 }); clearCommand.execute(context); command = new import__12.DrawCommand({ primitiveType: import__12.PrimitiveType.POINTS, shaderProgram: sp2, vertexArray: va }); command.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); sp2 = sp2.destroy(); }); it("gets the status of a complete framebuffer", function() { framebuffer2 = new import__12.Framebuffer({ context, colorTextures: [ new import__12.Texture({ context, width: 1, height: 1 }) ], depthRenderbuffer: new import__12.Renderbuffer({ context, format: import__12.RenderbufferFormat.DEPTH_COMPONENT16, width: 1, height: 1 }) }); expect(framebuffer2.status).toEqual(import__12.WebGLConstants.FRAMEBUFFER_COMPLETE); }); it("gets the status of a incomplete framebuffer", function() { if (!!window.webglStub) { return; } framebuffer2 = new import__12.Framebuffer({ context, colorTextures: [ new import__12.Texture({ context, width: 1, height: 1 }) ], depthRenderbuffer: new import__12.Renderbuffer({ context, format: import__12.RenderbufferFormat.RGBA4, width: 2, height: 2 }) }); expect(framebuffer2.status).not.toEqual( import__12.WebGLConstants.FRAMEBUFFER_COMPLETE ); }); it("destroys", function() { const f = new import__12.Framebuffer({ context }); expect(f.isDestroyed()).toEqual(false); f.destroy(); expect(f.isDestroyed()).toEqual(true); }); it("throws when created with color texture and color renderbuffer attachments", function() { expect(function() { framebuffer2 = new import__12.Framebuffer({ context, colorTextures: "not undefined", colorRenderbuffers: "not undefined" }); }).toThrowDeveloperError(); }); it("throws when created with depth texture and depth renderbuffer attachments", function() { expect(function() { framebuffer2 = new import__12.Framebuffer({ context, depthTexture: "not undefined", depthRenderbuffer: "not undefined" }); }).toThrowDeveloperError(); }); it("throws when created with depth-stencil texture and depth-stencil renderbuffer attachments", function() { expect(function() { framebuffer2 = new import__12.Framebuffer({ context, depthStencilTexture: "not undefined", depthStencilRenderbuffer: "not undefined" }); }).toThrowDeveloperError(); }); it("throws when created with depth and depth-stencil attachments", function() { expect(function() { framebuffer2 = new import__12.Framebuffer({ context, depthRenderbuffer: "not undefined", depthStencilRenderbuffer: "not undefined" }); }).toThrowDeveloperError(); }); it("throws when created with stencil and depth-stencil attachments", function() { expect(function() { framebuffer2 = new import__12.Framebuffer({ context, stencilRenderbuffer: "not undefined", depthStencilRenderbuffer: "not undefined" }); }).toThrowDeveloperError(); }); it("throws when created with depth and stencil attachments", function() { expect(function() { framebuffer2 = new import__12.Framebuffer({ context, depthRenderbuffer: "not undefined", stencilRenderbuffer: "not undefined" }); }).toThrowDeveloperError(); }); it("throws when created with a color texture with a non-color pixel format", function() { if (context.depthTexture) { expect(function() { framebuffer2 = new import__12.Framebuffer({ context, colorTextures: [ new import__12.Texture({ context, width: 1, height: 1, pixelFormat: import__12.PixelFormat.DEPTH_COMPONENT, pixelDatatype: import__12.PixelDatatype.UNSIGNED_SHORT }) ] }); }).toThrowDeveloperError(); } }); it("throws when created with a depth texture without a DEPTH_COMPONENT pixel format", function() { expect(function() { framebuffer2 = new import__12.Framebuffer({ context, depthTexture: new import__12.Texture({ context, width: 1, height: 1 }) }); }).toThrowDeveloperError(); }); it("throws when created with a depth-stencil texture without a DEPTH_STENCIL pixel format", function() { expect(function() { framebuffer2 = new import__12.Framebuffer({ context, depthStencilTexture: new import__12.Texture({ context, width: 1, height: 1 }) }); }).toThrowDeveloperError(); }); it("throws when the depth test is enabled without an appropriate attachment", function() { framebuffer2 = new import__12.Framebuffer({ context, colorTextures: [ new import__12.Texture({ context, width: 1, height: 1 }) ] }); const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0, 1.0, 1.0, 1.0); }"; sp = import__12.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__12.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__12.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__12.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); expect(function() { const command = new import__12.DrawCommand({ primitiveType: import__12.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, framebuffer: framebuffer2, renderState: import__12.RenderState.fromCache({ depthTest: { enabled: true } }) }); command.execute(context); }).toThrowDeveloperError(); }); it("throws when the number of color texture exceeds the number color attachments supported", function() { expect(function() { return new import__12.Framebuffer({ context, colorTextures: new Array(import__12.ContextLimits.maximumColorAttachments + 1) }); }).toThrowDeveloperError(); }); it("throws when the number of color renderbuffers exceeds the number color attachments supported", function() { expect(function() { return new import__12.Framebuffer({ context, colorRenderbuffers: new Array( import__12.ContextLimits.maximumColorAttachments + 1 ) }); }).toThrowDeveloperError(); }); it("throws when the index to getColorTexture is out of bounds", function() { framebuffer2 = new import__12.Framebuffer({ context }); expect(function() { framebuffer2.getColorTexture(); }).toThrowDeveloperError(); expect(function() { framebuffer2.getColorTexture(-1); }).toThrowDeveloperError(); expect(function() { framebuffer2.getColorTexture(import__12.ContextLimits.maximumColorAttachments + 1); }).toThrowDeveloperError(); }); it("throws when the index to getColorRenderbuffer is out of bounds", function() { framebuffer2 = new import__12.Framebuffer({ context }); expect(function() { framebuffer2.getColorRenderbuffer(); }).toThrowDeveloperError(); expect(function() { framebuffer2.getColorRenderbuffer(-1); }).toThrowDeveloperError(); expect(function() { framebuffer2.getColorRenderbuffer( import__12.ContextLimits.maximumColorAttachments + 1 ); }).toThrowDeveloperError(); }); it("throws when a color attachment has a floating-point datatype but the EXT_color_buffer_float extension is not supported", function() { if (context.colorBufferFloat) { return; } expect(function() { return new import__12.Framebuffer({ context, colorTextures: [ new import__12.Texture({ context, width: 1, height: 1, pixelDatatype: import__12.PixelDatatype.FLOAT }) ] }); }).toThrowDeveloperError(); }); it("throws when a color attachment has a half floating-point datatype but the EXT_color_buffer_half_float extension is not supported", function() { if (context.colorBufferHalfFloat) { return; } expect(function() { return new import__12.Framebuffer({ context, colorTextures: [ new import__12.Texture({ context, width: 1, height: 1, pixelDatatype: import__12.PixelDatatype.HALF_FLOAT }) ] }); }).toThrowDeveloperError(); }); it("fails to destroy", function() { const f = new import__12.Framebuffer({ context }); f.destroy(); expect(function() { f.destroy(); }).toThrowDeveloperError(); }); it("throws when there is no context", function() { expect(function() { return new import__12.Framebuffer(); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Renderer/MultisampleFramebufferSpec.js var import__13 = __toESM(require_Cesium(), 1); describe( "Renderer/MultisampleFramebuffer", function() { let context; let sp; let va; let framebuffer2; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); afterEach(function() { sp = sp && sp.destroy(); va = va && va.destroy(); framebuffer2 = framebuffer2 && framebuffer2.destroy(); }); it("throws when missing a color attachment", function() { expect(function() { framebuffer2 = new import__13.MultisampleFramebuffer({ context, width: 1, height: 1, colorTextures: [] }); }).toThrowDeveloperError(); expect(function() { framebuffer2 = new import__13.MultisampleFramebuffer({ context, width: 1, height: 1, colorRenderbuffers: [] }); }).toThrowDeveloperError(); }); it("throws when missing a depth-stencil attachment", function() { expect(function() { framebuffer2 = new import__13.MultisampleFramebuffer({ context, width: 1, height: 1, depthStencilTexture: [] }); }).toThrowDeveloperError(); expect(function() { framebuffer2 = new import__13.MultisampleFramebuffer({ context, width: 1, height: 1, depthStencilRenderbuffer: [] }); }).toThrowDeveloperError(); }); it("creates read and draw framebuffers", function() { if (!context.depthTexture) { return; } framebuffer2 = new import__13.MultisampleFramebuffer({ context, width: 1, height: 1, colorTextures: [ new import__13.Texture({ context, width: 1, height: 1 }) ], colorRenderbuffers: [ new import__13.Renderbuffer({ context, format: import__13.RenderbufferFormat.RGBA8 }) ], depthStencilTexture: new import__13.Texture({ context, width: 1, height: 1, pixelFormat: import__13.PixelFormat.DEPTH_STENCIL, pixelDatatype: import__13.PixelDatatype.UNSIGNED_INT_24_8 }), depthStencilRenderbuffer: new import__13.Renderbuffer({ context, format: import__13.RenderbufferFormat.DEPTH_STENCIL }) }); const readFB = framebuffer2.getRenderFramebuffer(); const drawFB = framebuffer2.getColorFramebuffer(); expect(readFB).toBeDefined(); expect(readFB.getColorRenderbuffer(0)).toBeDefined(); expect(readFB.depthStencilRenderbuffer).toBeDefined(); expect(drawFB).toBeDefined(); expect(drawFB.getColorTexture(0)).toBeDefined(); expect(drawFB.depthStencilTexture).toBeDefined(); }); function renderColor(framebuffer3, color) { const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "uniform vec4 color; void main() { out_FragColor = color; }"; sp = import__13.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__13.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__13.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__13.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); const uniformMap = { color: function() { return color; } }; const command = new import__13.DrawCommand({ primitiveType: import__13.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, uniformMap, framebuffer: framebuffer3 }); command.execute(context); } it("blits color attachments", function() { if (!context.webgl2) { return; } framebuffer2 = new import__13.MultisampleFramebuffer({ context, width: 1, height: 1, colorTextures: [ new import__13.Texture({ context, width: 1, height: 1 }) ], colorRenderbuffers: [ new import__13.Renderbuffer({ context, format: import__13.RenderbufferFormat.RGBA8, numSamples: 2 }) ] }); const renderFB = framebuffer2.getRenderFramebuffer(); renderColor(renderFB, new import__13.Color(0, 1, 0, 1)); framebuffer2.blitFramebuffers(context); const colorFB = framebuffer2.getColorFramebuffer(); expect({ context, framebuffer: colorFB }).toReadPixels([0, 255, 0, 255]); }); function renderAndBlitDepthAttachment(framebuffer3) { const renderFB = framebuffer3.getRenderFramebuffer(); const colorFB = framebuffer3.getColorFramebuffer(); import__13.ClearCommand.ALL.execute(context); const framebufferClear = new import__13.ClearCommand({ depth: 1, framebuffer: renderFB }); framebufferClear.execute(context); const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(0.0, 1.0, 0.0, 1.0); }"; sp = import__13.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); va = new import__13.VertexArray({ context, attributes: [ { index: 0, vertexBuffer: import__13.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__13.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); let command = new import__13.DrawCommand({ primitiveType: import__13.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, framebuffer: renderFB, renderState: import__13.RenderState.fromCache({ depthTest: { enabled: true } }) }); command.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); framebuffer3.blitFramebuffers(context); const vs2 = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs2 = "uniform sampler2D u_texture; void main() { out_FragColor = texture(u_texture, vec2(0.0)).rrrr; }"; let sp2 = import__13.ShaderProgram.fromCache({ context, vertexShaderSource: vs2, fragmentShaderSource: fs2, attributeLocations: { position: 0 } }); const uniformMap = { u_texture: function() { return colorFB.depthStencilTexture; } }; command = new import__13.DrawCommand({ primitiveType: import__13.PrimitiveType.POINTS, shaderProgram: sp2, vertexArray: va, uniformMap }); command.execute(context); sp2 = sp2.destroy(); return context.readPixels(); } it("blits depth-stencil attachments", function() { if (!context.webgl2 || !context.depthTexture) { return; } framebuffer2 = new import__13.MultisampleFramebuffer({ context, width: 1, height: 1, colorTextures: [ new import__13.Texture({ context, width: 1, height: 1 }) ], colorRenderbuffers: [ new import__13.Renderbuffer({ context, format: import__13.RenderbufferFormat.RGBA8, numSamples: 2 }) ], depthStencilTexture: new import__13.Texture({ context, width: 1, height: 1, pixelFormat: import__13.PixelFormat.DEPTH_STENCIL, pixelDatatype: import__13.PixelDatatype.UNSIGNED_INT_24_8 }), depthStencilRenderbuffer: new import__13.Renderbuffer({ context, width: 1, height: 1, format: import__13.RenderbufferFormat.DEPTH24_STENCIL8, numSamples: 2 }) }); expect(renderAndBlitDepthAttachment(framebuffer2)).toEqualEpsilon( [128, 128, 128, 255], 1 ); }); it("destroys", function() { const f = new import__13.MultisampleFramebuffer({ context, width: 1, height: 1 }); expect(f.isDestroyed()).toEqual(false); f.destroy(); expect(f.isDestroyed()).toEqual(true); }); it("fails to destroy", function() { const f = new import__13.MultisampleFramebuffer({ context, width: 1, height: 1 }); f.destroy(); expect(function() { f.destroy(); }).toThrowDeveloperError(); }); it("throws when there is no context", function() { expect(function() { return new import__13.MultisampleFramebuffer(); }).toThrowDeveloperError(); }); it("throws when there is no width or height", function() { expect(function() { return new import__13.MultisampleFramebuffer({ context, height: 1 }); }).toThrowDeveloperError(); expect(function() { return new import__13.MultisampleFramebuffer({ context, width: 1 }); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Renderer/PassStateSpec.js var import__14 = __toESM(require_Cesium(), 1); describe("Renderer/PassState", function() { it("creates a pass state", function() { const context = {}; const passState = new import__14.PassState(context); expect(passState.context).toBe(context); expect(passState.framebuffer).not.toBeDefined(); expect(passState.blendingEnabled).not.toBeDefined(); expect(passState.scissorTest).not.toBeDefined(); }); }); // packages/engine/Specs/Renderer/RenderStateSpec.js var import__15 = __toESM(require_Cesium(), 1); describe( "Renderer/RenderState", function() { let context; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); it("creates with defaults", function() { const defaultRS = { frontFace: import__15.WindingOrder.COUNTER_CLOCKWISE, cull: { enabled: false, face: import__15.WebGLConstants.BACK }, lineWidth: 1, polygonOffset: { enabled: false, factor: 0, units: 0 }, scissorTest: { enabled: false, rectangle: { x: 0, y: 0, width: 0, height: 0 } }, depthRange: { near: 0, far: 1 }, depthTest: { enabled: false, func: import__15.WebGLConstants.LESS }, colorMask: { red: true, green: true, blue: true, alpha: true }, depthMask: true, stencilMask: ~0, blending: { enabled: false, color: { red: 0, green: 0, blue: 0, alpha: 0 }, equationRgb: import__15.WebGLConstants.FUNC_ADD, equationAlpha: import__15.WebGLConstants.FUNC_ADD, functionSourceRgb: import__15.WebGLConstants.ONE, functionSourceAlpha: import__15.WebGLConstants.ONE, functionDestinationRgb: import__15.WebGLConstants.ZERO, functionDestinationAlpha: import__15.WebGLConstants.ZERO }, stencilTest: { enabled: false, frontFunction: import__15.WebGLConstants.ALWAYS, backFunction: import__15.WebGLConstants.ALWAYS, reference: 0, mask: ~0, frontOperation: { fail: import__15.WebGLConstants.KEEP, zFail: import__15.WebGLConstants.KEEP, zPass: import__15.WebGLConstants.KEEP }, backOperation: { fail: import__15.WebGLConstants.KEEP, zFail: import__15.WebGLConstants.KEEP, zPass: import__15.WebGLConstants.KEEP } }, sampleCoverage: { enabled: false, value: 1, invert: false } }; const rs = import__15.RenderState.fromCache(); expect(rs.frontFace).toEqual(defaultRS.frontFace); expect(rs.cull.enabled).toEqual(defaultRS.cull.enabled); expect(rs.cull.face).toEqual(defaultRS.cull.face); expect(rs.cull.lineWidth).toEqual(defaultRS.cull.lineWidth); expect(rs.polygonOffset.enabled).toEqual(defaultRS.polygonOffset.enabled); expect(rs.polygonOffset.factor).toEqual(defaultRS.polygonOffset.factor); expect(rs.polygonOffset.units).toEqual(defaultRS.polygonOffset.units); expect(rs.scissorTest.enabled).toEqual(defaultRS.scissorTest.enabled); expect(rs.scissorTest.rectangle.x).toEqual( defaultRS.scissorTest.rectangle.x ); expect(rs.scissorTest.rectangle.y).toEqual( defaultRS.scissorTest.rectangle.y ); expect(rs.scissorTest.rectangle.width).toEqual( defaultRS.scissorTest.rectangle.width ); expect(rs.scissorTest.rectangle.height).toEqual( defaultRS.scissorTest.rectangle.height ); expect(rs.depthRange.near).toEqual(defaultRS.depthRange.near); expect(rs.depthRange.far).toEqual(defaultRS.depthRange.far); expect(rs.depthTest.enabled).toEqual(defaultRS.depthTest.enabled); expect(rs.depthTest.func).toEqual(defaultRS.depthTest.func); expect(rs.colorMask.red).toEqual(defaultRS.colorMask.red); expect(rs.colorMask.green).toEqual(defaultRS.colorMask.green); expect(rs.colorMask.blue).toEqual(defaultRS.colorMask.blue); expect(rs.colorMask.alpha).toEqual(defaultRS.colorMask.alpha); expect(rs.depthMask).toEqual(defaultRS.depthMask); expect(rs.stencilMask).toEqual(defaultRS.stencilMask); expect(rs.blending.enabled).toEqual(defaultRS.blending.enabled); expect(rs.blending.color.red).toEqual(defaultRS.blending.color.red); expect(rs.blending.color.green).toEqual(defaultRS.blending.color.green); expect(rs.blending.color.blue).toEqual(defaultRS.blending.color.blue); expect(rs.blending.color.alpha).toEqual(defaultRS.blending.color.alpha); expect(rs.blending.equationRgb).toEqual(defaultRS.blending.equationRgb); expect(rs.blending.equationAlpha).toEqual( defaultRS.blending.equationAlpha ); expect(rs.blending.functionSourceRgb).toEqual( defaultRS.blending.functionSourceRgb ); expect(rs.blending.functionSourceAlpha).toEqual( defaultRS.blending.functionSourceAlpha ); expect(rs.blending.functionDestinationRgb).toEqual( defaultRS.blending.functionDestinationRgb ); expect(rs.blending.functionDestinationAlpha).toEqual( defaultRS.blending.functionDestinationAlpha ); expect(rs.stencilTest.enabled).toEqual(defaultRS.stencilTest.enabled); expect(rs.stencilTest.frontFunction).toEqual( defaultRS.stencilTest.frontFunction ); expect(rs.stencilTest.backFunction).toEqual( defaultRS.stencilTest.backFunction ); expect(rs.stencilTest.reference).toEqual(defaultRS.stencilTest.reference); expect(rs.stencilTest.mask).toEqual(defaultRS.stencilTest.mask); expect(rs.stencilTest.frontOperation.fail).toEqual( defaultRS.stencilTest.frontOperation.fail ); expect(rs.stencilTest.frontOperation.zFail).toEqual( defaultRS.stencilTest.frontOperation.zFail ); expect(rs.stencilTest.frontOperation.zPass).toEqual( defaultRS.stencilTest.frontOperation.zPass ); expect(rs.stencilTest.backOperation.fail).toEqual( defaultRS.stencilTest.backOperation.fail ); expect(rs.stencilTest.backOperation.zFail).toEqual( defaultRS.stencilTest.backOperation.zFail ); expect(rs.stencilTest.backOperation.zPass).toEqual( defaultRS.stencilTest.backOperation.zPass ); expect(rs.sampleCoverage.enabled).toEqual( defaultRS.sampleCoverage.enabled ); expect(rs.sampleCoverage.value).toEqual(defaultRS.sampleCoverage.value); expect(rs.sampleCoverage.invert).toEqual(defaultRS.sampleCoverage.invert); }); it("creates with all render states", function() { const r = { frontFace: import__15.WindingOrder.CLOCKWISE, cull: { enabled: true, face: import__15.WebGLConstants.FRONT }, lineWidth: import__15.ContextLimits.maximumAliasedLineWidth, polygonOffset: { enabled: false, factor: 1, units: 1 }, scissorTest: { enabled: true, rectangle: { x: 1, y: 1, width: 2, height: 2 } }, depthRange: { near: 0.25, far: 0.75 }, depthTest: { enabled: true, func: import__15.WebGLConstants.GREATER }, colorMask: { red: false, green: false, blue: false, alpha: false }, depthMask: false, stencilMask: 0, blending: { enabled: true, color: { red: 1, green: 1, blue: 1, alpha: 1 }, equationRgb: import__15.WebGLConstants.FUNC_SUBTRACT, equationAlpha: import__15.WebGLConstants.FUNC_SUBTRACT, functionSourceRgb: import__15.WebGLConstants.ZERO, functionSourceAlpha: import__15.WebGLConstants.ZERO, functionDestinationRgb: import__15.WebGLConstants.ONE, functionDestinationAlpha: import__15.WebGLConstants.ONE }, stencilTest: { enabled: true, frontFunction: import__15.WebGLConstants.NEVER, backFunction: import__15.WebGLConstants.NEVER, reference: 1, mask: 0, frontOperation: { fail: import__15.WebGLConstants.REPLACE, zFail: import__15.WebGLConstants.REPLACE, zPass: import__15.WebGLConstants.REPLACE }, backOperation: { fail: import__15.WebGLConstants.REPLACE, zFail: import__15.WebGLConstants.REPLACE, zPass: import__15.WebGLConstants.REPLACE } }, sampleCoverage: { enabled: true, value: 0.5, invert: true } }; const rs = import__15.RenderState.fromCache(r); expect(rs.frontFace).toEqual(r.frontFace); expect(rs.cull.enabled).toEqual(r.cull.enabled); expect(rs.cull.face).toEqual(r.cull.face); expect(rs.cull.lineWidth).toEqual(r.cull.lineWidth); expect(rs.polygonOffset.enabled).toEqual(r.polygonOffset.enabled); expect(rs.polygonOffset.factor).toEqual(r.polygonOffset.factor); expect(rs.polygonOffset.units).toEqual(r.polygonOffset.units); expect(rs.scissorTest.enabled).toEqual(r.scissorTest.enabled); expect(rs.scissorTest.rectangle.x).toEqual(r.scissorTest.rectangle.x); expect(rs.scissorTest.rectangle.y).toEqual(r.scissorTest.rectangle.y); expect(rs.scissorTest.rectangle.width).toEqual( r.scissorTest.rectangle.width ); expect(rs.scissorTest.rectangle.height).toEqual( r.scissorTest.rectangle.height ); expect(rs.depthRange.near).toEqual(r.depthRange.near); expect(rs.depthRange.far).toEqual(r.depthRange.far); expect(rs.depthTest.enabled).toEqual(r.depthTest.enabled); expect(rs.depthTest.func).toEqual(r.depthTest.func); expect(rs.colorMask.red).toEqual(r.colorMask.red); expect(rs.colorMask.green).toEqual(r.colorMask.green); expect(rs.colorMask.blue).toEqual(r.colorMask.blue); expect(rs.colorMask.alpha).toEqual(r.colorMask.alpha); expect(rs.depthMask).toEqual(r.depthMask); expect(rs.stencilMask).toEqual(r.stencilMask); expect(rs.blending.enabled).toEqual(r.blending.enabled); expect(rs.blending.color.red).toEqual(r.blending.color.red); expect(rs.blending.color.green).toEqual(r.blending.color.green); expect(rs.blending.color.blue).toEqual(r.blending.color.blue); expect(rs.blending.color.alpha).toEqual(r.blending.color.alpha); expect(rs.blending.equationRgb).toEqual(r.blending.equationRgb); expect(rs.blending.equationAlpha).toEqual(r.blending.equationAlpha); expect(rs.blending.functionSourceRgb).toEqual( r.blending.functionSourceRgb ); expect(rs.blending.functionSourceAlpha).toEqual( r.blending.functionSourceAlpha ); expect(rs.blending.functionDestinationRgb).toEqual( r.blending.functionDestinationRgb ); expect(rs.blending.functionDestinationAlpha).toEqual( r.blending.functionDestinationAlpha ); expect(rs.stencilTest.enabled).toEqual(r.stencilTest.enabled); expect(rs.stencilTest.frontFunction).toEqual(r.stencilTest.frontFunction); expect(rs.stencilTest.backFunction).toEqual(r.stencilTest.backFunction); expect(rs.stencilTest.reference).toEqual(r.stencilTest.reference); expect(rs.stencilTest.mask).toEqual(r.stencilTest.mask); expect(rs.stencilTest.frontOperation.fail).toEqual( r.stencilTest.frontOperation.fail ); expect(rs.stencilTest.frontOperation.zFail).toEqual( r.stencilTest.frontOperation.zFail ); expect(rs.stencilTest.frontOperation.zPass).toEqual( r.stencilTest.frontOperation.zPass ); expect(rs.stencilTest.backOperation.fail).toEqual( r.stencilTest.backOperation.fail ); expect(rs.stencilTest.backOperation.zFail).toEqual( r.stencilTest.backOperation.zFail ); expect(rs.stencilTest.backOperation.zPass).toEqual( r.stencilTest.backOperation.zPass ); expect(rs.sampleCoverage.enabled).toEqual(r.sampleCoverage.enabled); expect(rs.sampleCoverage.value).toEqual(r.sampleCoverage.value); expect(rs.sampleCoverage.invert).toEqual(r.sampleCoverage.invert); }); it("creates with some render states", function() { const r = { frontFace: import__15.WindingOrder.CLOCKWISE, depthRange: { near: 0.25, far: 0.75 } }; const rs = import__15.RenderState.fromCache(r); expect(rs.frontFace).toEqual(r.frontFace); expect(rs.depthRange.near).toEqual(r.depthRange.near); expect(rs.depthRange.far).toEqual(r.depthRange.far); const defaultRS = import__15.RenderState.fromCache(); expect(rs.cull.enabled).toEqual(defaultRS.cull.enabled); expect(rs.cull.face).toEqual(defaultRS.cull.face); expect(rs.cull.lineWidth).toEqual(defaultRS.cull.lineWidth); expect(rs.polygonOffset.enabled).toEqual(defaultRS.polygonOffset.enabled); expect(rs.polygonOffset.factor).toEqual(defaultRS.polygonOffset.factor); expect(rs.polygonOffset.units).toEqual(defaultRS.polygonOffset.units); expect(rs.scissorTest.enabled).toEqual(defaultRS.scissorTest.enabled); expect(rs.scissorTest.rectangle.x).toEqual( defaultRS.scissorTest.rectangle.x ); expect(rs.scissorTest.rectangle.y).toEqual( defaultRS.scissorTest.rectangle.y ); expect(rs.scissorTest.rectangle.width).toEqual( defaultRS.scissorTest.rectangle.width ); expect(rs.scissorTest.rectangle.height).toEqual( defaultRS.scissorTest.rectangle.height ); expect(rs.depthTest.enabled).toEqual(defaultRS.depthTest.enabled); expect(rs.depthTest.func).toEqual(defaultRS.depthTest.func); expect(rs.colorMask.red).toEqual(defaultRS.colorMask.red); expect(rs.colorMask.green).toEqual(defaultRS.colorMask.green); expect(rs.colorMask.blue).toEqual(defaultRS.colorMask.blue); expect(rs.colorMask.alpha).toEqual(defaultRS.colorMask.alpha); expect(rs.depthMask).toEqual(defaultRS.depthMask); expect(rs.stencilMask).toEqual(defaultRS.stencilMask); expect(rs.blending.enabled).toEqual(defaultRS.blending.enabled); expect(rs.blending.color.red).toEqual(defaultRS.blending.color.red); expect(rs.blending.color.green).toEqual(defaultRS.blending.color.green); expect(rs.blending.color.blue).toEqual(defaultRS.blending.color.blue); expect(rs.blending.color.alpha).toEqual(defaultRS.blending.color.alpha); expect(rs.blending.equationRgb).toEqual(defaultRS.blending.equationRgb); expect(rs.blending.equationAlpha).toEqual( defaultRS.blending.equationAlpha ); expect(rs.blending.functionSourceRgb).toEqual( defaultRS.blending.functionSourceRgb ); expect(rs.blending.functionSourceAlpha).toEqual( defaultRS.blending.functionSourceAlpha ); expect(rs.blending.functionDestinationRgb).toEqual( defaultRS.blending.functionDestinationRgb ); expect(rs.blending.functionDestinationAlpha).toEqual( defaultRS.blending.functionDestinationAlpha ); expect(rs.stencilTest.enabled).toEqual(defaultRS.stencilTest.enabled); expect(rs.stencilTest.frontFunction).toEqual( defaultRS.stencilTest.frontFunction ); expect(rs.stencilTest.backFunction).toEqual( defaultRS.stencilTest.backFunction ); expect(rs.stencilTest.reference).toEqual(defaultRS.stencilTest.reference); expect(rs.stencilTest.mask).toEqual(defaultRS.stencilTest.mask); expect(rs.stencilTest.frontOperation.fail).toEqual( defaultRS.stencilTest.frontOperation.fail ); expect(rs.stencilTest.frontOperation.zFail).toEqual( defaultRS.stencilTest.frontOperation.zFail ); expect(rs.stencilTest.frontOperation.zPass).toEqual( defaultRS.stencilTest.frontOperation.zPass ); expect(rs.stencilTest.backOperation.fail).toEqual( defaultRS.stencilTest.backOperation.fail ); expect(rs.stencilTest.backOperation.zFail).toEqual( defaultRS.stencilTest.backOperation.zFail ); expect(rs.stencilTest.backOperation.zPass).toEqual( defaultRS.stencilTest.backOperation.zPass ); expect(rs.sampleCoverage.enabled).toEqual( defaultRS.sampleCoverage.enabled ); expect(rs.sampleCoverage.value).toEqual(defaultRS.sampleCoverage.value); expect(rs.sampleCoverage.invert).toEqual(defaultRS.sampleCoverage.invert); }); it("caches render states", function() { const rs = import__15.RenderState.fromCache(); const rs2 = import__15.RenderState.fromCache(); const rs3 = import__15.RenderState.fromCache({ depthTest: { enabled: false, func: import__15.WebGLConstants.LESS } }); const rs4 = import__15.RenderState.fromCache({ depthTest: { enabled: true, func: import__15.WebGLConstants.NEVER } }); expect(rs2).toBe(rs); expect(rs3).toBe(rs); expect(rs4).not.toBe(rs); }); it("removes from render cache", function() { import__15.RenderState.clearCache(); const cache = import__15.RenderState.getCache(); const rs = import__15.RenderState.fromCache(); const undefinedKey = JSON.stringify(void 0); const fullKey = JSON.stringify(new import__15.RenderState()); expect(cache[fullKey].referenceCount).toEqual(1); expect(cache[undefinedKey].referenceCount).toEqual(1); const rs2 = import__15.RenderState.fromCache(); expect(cache[fullKey].referenceCount).toEqual(1); expect(cache[undefinedKey].referenceCount).toEqual(2); const param = { depthTest: { enabled: false, func: import__15.WebGLConstants.LESS } }; const rs3 = import__15.RenderState.fromCache(param); const paramKey = JSON.stringify(param); expect(rs2).toBe(rs); expect(rs3).toBe(rs); expect(cache[fullKey].referenceCount).toEqual(2); expect(cache[undefinedKey].referenceCount).toEqual(2); expect(cache[paramKey].referenceCount).toEqual(1); import__15.RenderState.removeFromCache(param); expect(cache[fullKey].referenceCount).toEqual(1); expect(cache[undefinedKey].referenceCount).toEqual(2); expect(cache[paramKey]).not.toBeDefined(); import__15.RenderState.removeFromCache(); import__15.RenderState.removeFromCache(); expect(cache[undefinedKey]).not.toBeDefined(); expect(cache[fullKey]).not.toBeDefined(); }); it("freezes render states", function() { const rs = import__15.RenderState.fromCache(); expect(Object.isFrozen(rs)).toBe(!window.specsUsingRelease); }); it("fails to create (frontFace)", function() { expect(function() { import__15.RenderState.fromCache({ frontFace: "invalid value" }); }).toThrowDeveloperError(); }); it("fails to create (cull.face)", function() { expect(function() { import__15.RenderState.fromCache({ cull: { face: "invalid value" } }); }).toThrowDeveloperError(); }); it("fails to create (small lineWidth)", function() { expect(function() { import__15.RenderState.fromCache({ lineWidth: import__15.ContextLimits.minimumAliasedLineWidth - 1 }); }).toThrowDeveloperError(); }); it("fails to create (large lineWidth)", function() { expect(function() { import__15.RenderState.fromCache({ lineWidth: import__15.ContextLimits.maximumAliasedLineWidth + 1 }); }).toThrowDeveloperError(); }); it("fails to create (negative scissorTest.rectangle.width)", function() { expect(function() { import__15.RenderState.fromCache({ scissorTest: { rectangle: { x: 0, y: 0, width: -1, height: 0 } } }); }).toThrowDeveloperError(); }); it("fails to create (negative scissorTest.rectangle.height)", function() { expect(function() { import__15.RenderState.fromCache({ scissorTest: { rectangle: { x: 0, y: 0, width: 0, height: -1 } } }); }).toThrowDeveloperError(); }); it("fails to create (near > far)", function() { expect(function() { import__15.RenderState.fromCache({ depthRange: { near: 0.75, far: 0.25 } }); }).toThrowDeveloperError(); }); it("fails to create (near < 0)", function() { expect(function() { import__15.RenderState.fromCache({ depthRange: { near: -1 } }); }).toThrowDeveloperError(); }); it("fails to create (far > 1)", function() { expect(function() { import__15.RenderState.fromCache({ depthRange: { far: 2 } }); }).toThrowDeveloperError(); }); it("fails to create (depthTest.func)", function() { expect(function() { import__15.RenderState.fromCache({ depthTest: { func: "invalid value" } }); }).toThrowDeveloperError(); }); it("fails to create (blending.color < 0)", function() { expect(function() { import__15.RenderState.fromCache({ blending: { color: { red: -1, green: 0, blue: 0, alpha: 0 } } }); }).toThrowDeveloperError(); }); it("fails to create (blending.color > 1)", function() { expect(function() { import__15.RenderState.fromCache({ blending: { color: { red: 0, green: 0, blue: 0, alpha: 2 } } }); }).toThrowDeveloperError(); }); it("fails to create (blend.equationRgb)", function() { expect(function() { import__15.RenderState.fromCache({ blending: { equationRgb: "invalid value" } }); }).toThrowDeveloperError(); }); it("fails to create (blend.equationAlpha)", function() { expect(function() { import__15.RenderState.fromCache({ blending: { equationAlpha: "invalid value" } }); }).toThrowDeveloperError(); }); it("fails to create (blend.functionSourceRgb)", function() { expect(function() { import__15.RenderState.fromCache({ blending: { functionSourceRgb: "invalid value" } }); }).toThrowDeveloperError(); }); it("fails to create (blend.functionSourceAlpha)", function() { expect(function() { import__15.RenderState.fromCache({ blending: { functionSourceAlpha: "invalid value" } }); }).toThrowDeveloperError(); }); it("fails to create (blend.functionDestinationRgb)", function() { expect(function() { import__15.RenderState.fromCache({ blending: { functionDestinationRgb: "invalid value" } }); }).toThrowDeveloperError(); }); it("fails to create (blend.functionDestinationAlpha)", function() { expect(function() { import__15.RenderState.fromCache({ blending: { functionDestinationAlpha: "invalid value" } }); }).toThrowDeveloperError(); }); it("fails to create (stencilTest.frontFunction)", function() { expect(function() { import__15.RenderState.fromCache({ stencilTest: { frontFunction: "invalid value" } }); }).toThrowDeveloperError(); }); it("fails to create (stencilTest.backFunction)", function() { expect(function() { import__15.RenderState.fromCache({ stencilTest: { backFunction: "invalid value" } }); }).toThrowDeveloperError(); }); it("fails to create (stencilTest.frontOperation.fail)", function() { expect(function() { import__15.RenderState.fromCache({ stencilTest: { frontOperation: { fail: "invalid value" } } }); }).toThrowDeveloperError(); }); it("fails to create (stencilTest.frontOperation.zFail)", function() { expect(function() { import__15.RenderState.fromCache({ stencilTest: { frontOperation: { zFail: "invalid value" } } }); }).toThrowDeveloperError(); }); it("fails to create (stencilTest.frontOperation.zPass)", function() { expect(function() { import__15.RenderState.fromCache({ stencilTest: { frontOperation: { zPass: "invalid value" } } }); }).toThrowDeveloperError(); }); it("fails to create (stencilTest.backOperation.fail)", function() { expect(function() { import__15.RenderState.fromCache({ stencilTest: { backOperation: { fail: "invalid value" } } }); }).toThrowDeveloperError(); }); it("fails to create (stencilTest.backOperation.zFail)", function() { expect(function() { import__15.RenderState.fromCache({ stencilTest: { backOperation: { zFail: "invalid value" } } }); }).toThrowDeveloperError(); }); it("fails to create (stencilTest.backOperation.zPass)", function() { expect(function() { import__15.RenderState.fromCache({ stencilTest: { backOperation: { zPass: "invalid value" } } }); }).toThrowDeveloperError(); }); it("fails to get state without renderState", function() { expect(function() { import__15.RenderState.getState(void 0); }).toThrowDeveloperError(); }); it("clones", function() { const r = { frontFace: import__15.WindingOrder.CLOCKWISE, cull: { enabled: true, face: import__15.WebGLConstants.FRONT }, lineWidth: import__15.ContextLimits.maximumAliasedLineWidth, polygonOffset: { enabled: false, factor: 1, units: 1 }, scissorTest: { enabled: true, rectangle: { x: 1, y: 1, width: 2, height: 2 } }, depthRange: { near: 0.25, far: 0.75 }, depthTest: { enabled: true, func: import__15.WebGLConstants.GREATER }, colorMask: { red: false, green: false, blue: false, alpha: false }, depthMask: false, stencilMask: 0, blending: { enabled: true, color: { red: 1, green: 1, blue: 1, alpha: 1 }, equationRgb: import__15.WebGLConstants.FUNC_SUBTRACT, equationAlpha: import__15.WebGLConstants.FUNC_SUBTRACT, functionSourceRgb: import__15.WebGLConstants.ZERO, functionSourceAlpha: import__15.WebGLConstants.ZERO, functionDestinationRgb: import__15.WebGLConstants.ONE, functionDestinationAlpha: import__15.WebGLConstants.ONE }, stencilTest: { enabled: true, frontFunction: import__15.WebGLConstants.NEVER, backFunction: import__15.WebGLConstants.NEVER, reference: 1, mask: 0, frontOperation: { fail: import__15.WebGLConstants.REPLACE, zFail: import__15.WebGLConstants.REPLACE, zPass: import__15.WebGLConstants.REPLACE }, backOperation: { fail: import__15.WebGLConstants.REPLACE, zFail: import__15.WebGLConstants.REPLACE, zPass: import__15.WebGLConstants.REPLACE } }, sampleCoverage: { enabled: true, value: 0.5, invert: true } }; const rs = import__15.RenderState.fromCache(import__15.RenderState.getState(r)); expect(rs.frontFace).toEqual(r.frontFace); expect(rs.cull.enabled).toEqual(r.cull.enabled); expect(rs.cull.face).toEqual(r.cull.face); expect(rs.cull.lineWidth).toEqual(r.cull.lineWidth); expect(rs.polygonOffset.enabled).toEqual(r.polygonOffset.enabled); expect(rs.polygonOffset.factor).toEqual(r.polygonOffset.factor); expect(rs.polygonOffset.units).toEqual(r.polygonOffset.units); expect(rs.scissorTest.enabled).toEqual(r.scissorTest.enabled); expect(rs.scissorTest.rectangle.x).toEqual(r.scissorTest.rectangle.x); expect(rs.scissorTest.rectangle.y).toEqual(r.scissorTest.rectangle.y); expect(rs.scissorTest.rectangle.width).toEqual( r.scissorTest.rectangle.width ); expect(rs.scissorTest.rectangle.height).toEqual( r.scissorTest.rectangle.height ); expect(rs.depthRange.near).toEqual(r.depthRange.near); expect(rs.depthRange.far).toEqual(r.depthRange.far); expect(rs.depthTest.enabled).toEqual(r.depthTest.enabled); expect(rs.depthTest.func).toEqual(r.depthTest.func); expect(rs.colorMask.red).toEqual(r.colorMask.red); expect(rs.colorMask.green).toEqual(r.colorMask.green); expect(rs.colorMask.blue).toEqual(r.colorMask.blue); expect(rs.colorMask.alpha).toEqual(r.colorMask.alpha); expect(rs.depthMask).toEqual(r.depthMask); expect(rs.stencilMask).toEqual(r.stencilMask); expect(rs.blending.enabled).toEqual(r.blending.enabled); expect(rs.blending.color.red).toEqual(r.blending.color.red); expect(rs.blending.color.green).toEqual(r.blending.color.green); expect(rs.blending.color.blue).toEqual(r.blending.color.blue); expect(rs.blending.color.alpha).toEqual(r.blending.color.alpha); expect(rs.blending.equationRgb).toEqual(r.blending.equationRgb); expect(rs.blending.equationAlpha).toEqual(r.blending.equationAlpha); expect(rs.blending.functionSourceRgb).toEqual( r.blending.functionSourceRgb ); expect(rs.blending.functionSourceAlpha).toEqual( r.blending.functionSourceAlpha ); expect(rs.blending.functionDestinationRgb).toEqual( r.blending.functionDestinationRgb ); expect(rs.blending.functionDestinationAlpha).toEqual( r.blending.functionDestinationAlpha ); expect(rs.stencilTest.enabled).toEqual(r.stencilTest.enabled); expect(rs.stencilTest.frontFunction).toEqual(r.stencilTest.frontFunction); expect(rs.stencilTest.backFunction).toEqual(r.stencilTest.backFunction); expect(rs.stencilTest.reference).toEqual(r.stencilTest.reference); expect(rs.stencilTest.mask).toEqual(r.stencilTest.mask); expect(rs.stencilTest.frontOperation.fail).toEqual( r.stencilTest.frontOperation.fail ); expect(rs.stencilTest.frontOperation.zFail).toEqual( r.stencilTest.frontOperation.zFail ); expect(rs.stencilTest.frontOperation.zPass).toEqual( r.stencilTest.frontOperation.zPass ); expect(rs.stencilTest.backOperation.fail).toEqual( r.stencilTest.backOperation.fail ); expect(rs.stencilTest.backOperation.zFail).toEqual( r.stencilTest.backOperation.zFail ); expect(rs.stencilTest.backOperation.zPass).toEqual( r.stencilTest.backOperation.zPass ); expect(rs.sampleCoverage.enabled).toEqual(r.sampleCoverage.enabled); expect(rs.sampleCoverage.value).toEqual(r.sampleCoverage.value); expect(rs.sampleCoverage.invert).toEqual(r.sampleCoverage.invert); }); }, "WebGL" ); // packages/engine/Specs/Renderer/RenderbufferSpec.js var import__16 = __toESM(require_Cesium(), 1); describe( "Renderer/Renderbuffer", function() { let context; let renderbuffer; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); afterEach(function() { renderbuffer = renderbuffer && renderbuffer.destroy(); }); it("creates", function() { renderbuffer = new import__16.Renderbuffer({ context, format: import__16.RenderbufferFormat.DEPTH_COMPONENT16, width: 64, height: 32 }); expect(renderbuffer.format).toEqual(import__16.RenderbufferFormat.DEPTH_COMPONENT16); expect(renderbuffer.width).toEqual(64); expect(renderbuffer.height).toEqual(32); }); it("creates with defaults", function() { renderbuffer = new import__16.Renderbuffer({ context }); expect(renderbuffer.format).toEqual(import__16.RenderbufferFormat.RGBA4); expect(renderbuffer.width).toEqual(context.canvas.clientWidth); expect(renderbuffer.height).toEqual(context.canvas.clientHeight); }); it("destroys", function() { const r = new import__16.Renderbuffer({ context }); expect(r.isDestroyed()).toEqual(false); r.destroy(); expect(r.isDestroyed()).toEqual(true); }); it("throws when created with invalid format", function() { expect(function() { renderbuffer = new import__16.Renderbuffer({ context, format: "invalid format" }); }).toThrowDeveloperError(); }); it("throws when created with small width", function() { expect(function() { renderbuffer = new import__16.Renderbuffer({ context, width: 0 }); }).toThrowDeveloperError(); }); it("throws when created with large width", function() { expect(function() { renderbuffer = new import__16.Renderbuffer({ context, width: import__16.ContextLimits.maximumRenderbufferSize + 1 }); }).toThrowDeveloperError(); }); it("throws when created with small height", function() { expect(function() { renderbuffer = new import__16.Renderbuffer({ context, height: 0 }); }).toThrowDeveloperError(); }); it("throws when created with large height", function() { expect(function() { renderbuffer = new import__16.Renderbuffer({ context, height: import__16.ContextLimits.maximumRenderbufferSize + 1 }); }).toThrowDeveloperError(); }); it("throws when fails to destroy", function() { const r = new import__16.Renderbuffer({ context }); r.destroy(); expect(function() { r.destroy(); }).toThrowDeveloperError(); }); it("throws when there is no context", function() { expect(function() { return new import__16.Renderbuffer(); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Renderer/SamplerSpec.js var import__17 = __toESM(require_Cesium(), 1); describe( "Renderer/Sampler", function() { let context; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); it("has expected default values", function() { const sampler = new import__17.Sampler(); expect(sampler.wrapS).toEqual(import__17.TextureWrap.CLAMP_TO_EDGE); expect(sampler.wrapT).toEqual(import__17.TextureWrap.CLAMP_TO_EDGE); expect(sampler.minificationFilter).toEqual( import__17.TextureMinificationFilter.LINEAR ); expect(sampler.magnificationFilter).toEqual( import__17.TextureMinificationFilter.LINEAR ); expect(sampler.maximumAnisotropy).toEqual(1); }); it("throws when creating a sampler with invalid wrapS", function() { expect(function() { return new import__17.Sampler({ wrapS: "invalid wrap" }); }).toThrowDeveloperError(); }); it("throws when creating a sampler with invalid wrapT", function() { expect(function() { return new import__17.Sampler({ wrapT: "invalid wrap" }); }).toThrowDeveloperError(); }); it("throws when creating a sampler with invalid minificationFilter", function() { expect(function() { return new import__17.Sampler({ minificationFilter: "invalid filter" }); }).toThrowDeveloperError(); }); it("throws when creating a sampler with invalid magnificationFilter", function() { expect(function() { return new import__17.Sampler({ magnificationFilter: "invalid filter" }); }).toThrowDeveloperError(); }); it("throws when creating a sampler with invalid maximumAnisotropy", function() { expect(function() { return new import__17.Sampler({ maximumAnisotropy: 0 }); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Renderer/ShaderBuilderSpec.js var import__18 = __toESM(require_Cesium(), 1); describe( "Renderer/ShaderBuilder", function() { let context; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); function checkVertexShader(shaderProgram, expectedDefines, expectedSources) { expectedSources = [expectedSources.join("\n")]; const expectedText = new import__18.ShaderSource({ defines: expectedDefines, sources: expectedSources }).createCombinedVertexShader(context); expect(shaderProgram._vertexShaderText).toEqual(expectedText); } function checkFragmentShader(shaderProgram, expectedDefines, expectedSources) { expectedSources = [expectedSources.join("\n")]; const expectedText = new import__18.ShaderSource({ defines: expectedDefines, sources: expectedSources }).createCombinedFragmentShader(context); expect(shaderProgram._fragmentShaderText).toEqual(expectedText); } it("creates an empty shader by default", function() { const shaderBuilder = new import__18.ShaderBuilder(); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkVertexShader(shaderProgram, [], []); checkFragmentShader(shaderProgram, [], []); }); it("addDefine throws for undefined identifier", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addDefine(void 0); }).toThrowDeveloperError(); }); it("addDefine throws for invalid identifier", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addDefine(42); }).toThrowDeveloperError(); }); it("addDefine defines macros without values", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addDefine("USE_SHADOWS"); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkVertexShader(shaderProgram, ["USE_SHADOWS"], []); checkFragmentShader(shaderProgram, ["USE_SHADOWS"], []); }); it("addDefine defines macros with values", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addDefine("PI", 3.1415); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkVertexShader(shaderProgram, ["PI 3.1415"], []); checkFragmentShader(shaderProgram, ["PI 3.1415"], []); }); it("addDefine puts the define in the destination shader(s)", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addDefine("POINT_SIZE", 2, import__18.ShaderDestination.VERTEX); shaderBuilder.addDefine("PI", 3.1415, import__18.ShaderDestination.FRAGMENT); shaderBuilder.addDefine( "USE_FRAGMENT_SHADING", 1, import__18.ShaderDestination.BOTH ); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkVertexShader( shaderProgram, ["POINT_SIZE 2", "USE_FRAGMENT_SHADING 1"], [] ); checkFragmentShader( shaderProgram, ["PI 3.1415", "USE_FRAGMENT_SHADING 1"], [] ); }); it("addDefine defaults to both shaders", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addDefine("PI", 3.1415); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkVertexShader(shaderProgram, ["PI 3.1415"], []); checkFragmentShader(shaderProgram, ["PI 3.1415"], []); }); it("addStruct throws for undefined structId", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addStruct( void 0, "TestStruct", import__18.ShaderDestination.FRAGMENT ); }).toThrowDeveloperError(); }); it("addStruct throws for invalid structId", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addStruct( {}, "TestStruct", import__18.ShaderDestination.FRAGMENT ); }).toThrowDeveloperError(); }); it("addStruct throws for undefined structName", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addStruct( "testStruct", void 0, import__18.ShaderDestination.FRAGMENT ); }).toThrowDeveloperError(); }); it("addStruct throws for invalid structId", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addStruct( "testStruct", {}, import__18.ShaderDestination.FRAGMENT ); }).toThrowDeveloperError(); }); it("addStruct throws for undefined destination", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addStruct("testStruct", "TestStruct", void 0); }).toThrowDeveloperError(); }); it("addStruct throws for invalid structId", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addStruct("testStruct", "TestStruct", "vertex"); }).toThrowDeveloperError(); }); it("addStruct adds a struct to the shader", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addStruct( "structVS", "TestStruct", import__18.ShaderDestination.VERTEX ); shaderBuilder.addStruct( "structFS", "TestStruct", import__18.ShaderDestination.FRAGMENT ); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkVertexShader( shaderProgram, [], ["struct TestStruct", "{", " float _empty;", "};"] ); checkFragmentShader( shaderProgram, [], ["struct TestStruct", "{", " float _empty;", "};"] ); }); it("addStructField throws for undefined structId", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addStruct( "structVS", "TestStruct", import__18.ShaderDestination.VERTEX ); expect(function() { return shaderBuilder.addStructField(void 0, "vec3", "positionMC"); }).toThrowDeveloperError(); }); it("addStructField throws for invalid structId", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addStruct( "structVS", "TestStruct", import__18.ShaderDestination.VERTEX ); expect(function() { return shaderBuilder.addStructField(-1, "vec3", "positionMC"); }).toThrowDeveloperError(); }); it("addStructField throws for undefined type", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addStruct( "structVS", "TestStruct", import__18.ShaderDestination.VERTEX ); expect(function() { return shaderBuilder.addStructField( "structVS", void 0, "positionMC" ); }).toThrowDeveloperError(); }); it("addStructField throws for invalid type", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addStruct( "structVS", "TestStruct", import__18.ShaderDestination.VERTEX ); expect(function() { return shaderBuilder.addStructField("structVS", -1, "positionMC"); }).toThrowDeveloperError(); }); it("addStructField throws for undefined identifier", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addStruct( "structVS", "TestStruct", import__18.ShaderDestination.VERTEX ); expect(function() { return shaderBuilder.addStructField("structVS", "vec3", void 0); }).toThrowDeveloperError(); }); it("addStructField throws for invalid identifier", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addStruct( "structVS", "TestStruct", import__18.ShaderDestination.VERTEX ); expect(function() { return shaderBuilder.addStructField("structVS", "vec3", -1); }).toThrowDeveloperError(); }); it("addStructField adds a struct field to the shader", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addStruct( "structVS", "TestStruct", import__18.ShaderDestination.VERTEX ); shaderBuilder.addStruct( "structFS", "TestStruct", import__18.ShaderDestination.FRAGMENT ); shaderBuilder.addStructField("structVS", "vec3", "positionMC"); shaderBuilder.addStructField("structFS", "vec3", "positionMC"); shaderBuilder.addStructField("structFS", "float", "temperature"); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkVertexShader( shaderProgram, [], ["struct TestStruct", "{", " vec3 positionMC;", "};"] ); checkFragmentShader( shaderProgram, [], [ "struct TestStruct", "{", " vec3 positionMC;", " float temperature;", "};" ] ); }); const signature = "float circleMask(float radius)"; it("addFunction throws for undefined functionName", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addFunction( void 0, signature, import__18.ShaderDestination.FRAGMENT ); }).toThrowDeveloperError(); }); it("addFunction throws for invalid functionName", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addFunction( {}, signature, import__18.ShaderDestination.FRAGMENT ); }).toThrowDeveloperError(); }); it("addFunction throws for undefined signature", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addFunction( "testFunction", void 0, import__18.ShaderDestination.FRAGMENT ); }).toThrowDeveloperError(); }); it("addFunction throws for invalid signature", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addFunction( "testFunction", -1, import__18.ShaderDestination.FRAGMENT ); }).toThrowDeveloperError(); }); it("addFunction throws for undefined destination", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addFunction("testFunction", signature, void 0); }).toThrowDeveloperError(); }); it("addFunction throws for invalid structId", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addFunction("testFunction", signature, "fragment"); }).toThrowDeveloperError(); }); it("addFunction adds a struct to the shader", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addFunction( "testFunctionVS", signature, import__18.ShaderDestination.VERTEX ); shaderBuilder.addFunction( "testFunctionFS", signature, import__18.ShaderDestination.FRAGMENT ); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkVertexShader(shaderProgram, [], [signature, "{", "}"]); checkFragmentShader(shaderProgram, [], [signature, "{", "}"]); }); it("addFunctionLines throws for undefined functionName", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addFunction( "testFunctionVS", signature, import__18.ShaderDestination.VERTEX ); expect(function() { return shaderBuilder.addFunctionLines(void 0, "return 1.0;"); }).toThrowDeveloperError(); }); it("addFunctionLines throws for invalid functionName", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addFunction( "testFunctionVS", signature, import__18.ShaderDestination.VERTEX ); expect(function() { return shaderBuilder.addFunctionLines(-1, "return 1.0;"); }).toThrowDeveloperError(); }); it("addFunctionLines throws for undefined lines", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addFunction( "testFunctionVS", signature, import__18.ShaderDestination.VERTEX ); expect(function() { return shaderBuilder.addFunctionLines("testFunctionVS", void 0); }).toThrowDeveloperError(); }); it("addFunctionLines throws for invalid lines", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addFunction( "testFunctionVS", signature, import__18.ShaderDestination.VERTEX ); expect(function() { return shaderBuilder.addFunctionLines("testFunctionVS", -1); }).toThrowDeveloperError(); }); it("addFunctionLines adds lines to the body of a function", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addFunction( "testFunctionVS", signature, import__18.ShaderDestination.VERTEX ); shaderBuilder.addFunction( "testFunctionFS", signature, import__18.ShaderDestination.FRAGMENT ); shaderBuilder.addFunctionLines("testFunctionVS", [ "v_color = vec3(0.0);", "return 1.0;" ]); shaderBuilder.addFunctionLines("testFunctionFS", [ "return 1.0 - step(0.3, radius);" ]); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkVertexShader( shaderProgram, [], [signature, "{", " v_color = vec3(0.0);", " return 1.0;", "}"] ); checkFragmentShader( shaderProgram, [], [signature, "{", " return 1.0 - step(0.3, radius);", "}"] ); }); it("addFunctionLines adds a single line to the body of the function", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addFunction( "testFunctionVS", signature, import__18.ShaderDestination.VERTEX ); shaderBuilder.addFunction( "testFunctionFS", signature, import__18.ShaderDestination.FRAGMENT ); shaderBuilder.addFunctionLines("testFunctionVS", "return 1.0;"); shaderBuilder.addFunctionLines("testFunctionFS", "return 2.0;"); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkVertexShader( shaderProgram, [], [signature, "{", " return 1.0;", "}"] ); checkFragmentShader( shaderProgram, [], [signature, "{", " return 2.0;", "}"] ); }); it("addUniform throws for undefined type", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addUniform(void 0, "u_time"); }).toThrowDeveloperError(); }); it("addUniform throws for invalid type", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addUniform(10, "u_time"); }).toThrowDeveloperError(); }); it("addUniform throws for undefined identifier", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addUniform("vec3"); }).toThrowDeveloperError(); }); it("addUniform throws for invalid identifier", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addUniform("vec3", 0); }).toThrowDeveloperError(); }); it("addUniform puts the uniform in the destination shader(s)", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addUniform( "vec3", "u_gridDimensions", import__18.ShaderDestination.VERTEX ); shaderBuilder.addUniform( "vec2", "u_mousePosition", import__18.ShaderDestination.FRAGMENT ); shaderBuilder.addUniform("float", "u_time", import__18.ShaderDestination.BOTH); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkVertexShader( shaderProgram, [], ["uniform vec3 u_gridDimensions;", "uniform float u_time;"] ); checkFragmentShader( shaderProgram, [], ["uniform vec2 u_mousePosition;", "uniform float u_time;"] ); }); it("addUniform defaults to both shaders", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addUniform("float", "u_time"); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkVertexShader(shaderProgram, [], ["uniform float u_time;"]); checkFragmentShader(shaderProgram, [], ["uniform float u_time;"]); }); it("setPositionAttribute throws for undefined type", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.setPositionAttribute(void 0, "a_position"); }).toThrowDeveloperError(); }); it("setPositionAttribute throws for invalid type", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.setPositionAttribute(0, "a_position"); }).toThrowDeveloperError(); }); it("setPositionAttribute throws for undefined identifier", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.setPositionAttribute("vec3", void 0); }).toThrowDeveloperError(); }); it("setPositionAttribute throws for invalid identifier", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.setPositionAttribute("vec3", 0); }).toThrowDeveloperError(); }); it("setPositionAttribute creates a position attribute in location 0", function() { const shaderBuilder = new import__18.ShaderBuilder(); const normalLocation = shaderBuilder.addAttribute("vec3", "a_normal"); const positionLocation = shaderBuilder.setPositionAttribute( "vec3", "a_position" ); expect(positionLocation).toBe(0); expect(normalLocation).toBe(1); const shaderProgram = shaderBuilder.buildShaderProgram(context); const expectedAttributes = ["in vec3 a_position;", "in vec3 a_normal;"]; checkVertexShader(shaderProgram, [], expectedAttributes); checkFragmentShader(shaderProgram, [], []); const expectedLocations = { a_position: 0, a_normal: 1 }; expect(shaderBuilder.attributeLocations).toEqual(expectedLocations); expect(shaderProgram._attributeLocations).toEqual(expectedLocations); }); it("setPositionAttribute throws if called twice", function() { const shaderBuilder = new import__18.ShaderBuilder(); const positionLocation = shaderBuilder.setPositionAttribute( "vec3", "a_position" ); expect(positionLocation).toBe(0); expect(function() { return shaderBuilder.setPositionAttribute("vec3", "a_position2"); }).toThrowDeveloperError(); }); it("addAttribute throws for undefined type", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addAttribute(void 0, "a_position"); }).toThrowDeveloperError(); }); it("addAttribute throws for invalid type", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addAttribute(0, "a_position"); }).toThrowDeveloperError(); }); it("addAttribute throws for undefined identifier", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addAttribute("vec2", void 0); }).toThrowDeveloperError(); }); it("addAttribute throws for invalid identifier", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addAttribute("vec2", 0); }).toThrowDeveloperError(); }); it("addAttribute creates an attribute in the vertex shader", function() { const shaderBuilder = new import__18.ShaderBuilder(); const colorLocation = shaderBuilder.addAttribute("vec4", "a_color"); const normalLocation = shaderBuilder.addAttribute("vec3", "a_normal"); expect(colorLocation).toBe(1); expect(normalLocation).toBe(2); const shaderProgram = shaderBuilder.buildShaderProgram(context); const expectedAttributes = ["in vec4 a_color;", "in vec3 a_normal;"]; checkVertexShader(shaderProgram, [], expectedAttributes); checkFragmentShader(shaderProgram, [], []); const expectedLocations = { a_color: 1, a_normal: 2 }; expect(shaderBuilder.attributeLocations).toEqual(expectedLocations); expect(shaderProgram._attributeLocations).toEqual(expectedLocations); }); it("addAttribute handles matrix attribute locations correctly", function() { const shaderBuilder = new import__18.ShaderBuilder(); const matrixLocation = shaderBuilder.addAttribute("mat3", "a_warpMatrix"); const colorLocation = shaderBuilder.addAttribute("vec3", "a_color"); expect(matrixLocation).toBe(1); expect(colorLocation).toBe(4); const shaderProgram = shaderBuilder.buildShaderProgram(context); const expectedAttributes = ["in mat3 a_warpMatrix;", "in vec3 a_color;"]; checkVertexShader(shaderProgram, [], expectedAttributes); checkFragmentShader(shaderProgram, [], []); const expectedLocations = { a_warpMatrix: 1, a_color: 4 }; expect(shaderBuilder.attributeLocations).toEqual(expectedLocations); expect(shaderProgram._attributeLocations).toEqual(expectedLocations); }); it("addVarying throws for undefined type", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addVarying(void 0, "v_uv"); }).toThrowDeveloperError(); }); it("addVarying throws for invalid type", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addVarying(0, "v_uv"); }).toThrowDeveloperError(); }); it("addVarying throws for undefined identifier", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addVarying("vec2", void 0); }).toThrowDeveloperError(); }); it("addVarying throws for invalid identifier", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addVarying("vec2", 0); }).toThrowDeveloperError(); }); it("addVarying adds varyings to both shaders", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addVarying("vec2", "v_uv"); const expectedVaryings = ["vec2 v_uv;"]; const expectedVertexVaryings = expectedVaryings.map( (varying) => `out ${varying}` ); const expectedFragmentVaryings = expectedVaryings.map( (varying) => `in ${varying}` ); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkVertexShader(shaderProgram, [], expectedVertexVaryings); checkFragmentShader(shaderProgram, [], expectedFragmentVaryings); }); it("addVertexLines throws for undefined lines", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addVertexLines(void 0); }).toThrowDeveloperError(); }); it("addVertexLines throws for invalid lines", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addVertexLines(-1); }).toThrowDeveloperError(); }); it("addVertexLines appends lines to the vertex shader", function() { const shaderBuilder = new import__18.ShaderBuilder(); const vertexLines = [ "void main()", "{", " gl_Position = vec4(0.0, 0.0, 0.0, 1.0);", "}" ]; shaderBuilder.addVertexLines(vertexLines); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkVertexShader(shaderProgram, [], vertexLines); }); it("addVertexLines appends a single line to the shader", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addVertexLines("float sum;"); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkVertexShader(shaderProgram, [], ["float sum;"]); }); it("addFragmentLines throws for undefined lines", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addFragmentLines(void 0); }).toThrowDeveloperError(); }); it("addFragmentLines throws for invalid lines", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.addFragmentLines(-1); }).toThrowDeveloperError(); }); it("addFragmentLines appends lines to the fragment shader", function() { const shaderBuilder = new import__18.ShaderBuilder(); const fragmentLines = [ "void main()", "{", " out_FragColor = vec4(1.0, 0.5, 0.0, 1.0);", "}" ]; shaderBuilder.addFragmentLines(fragmentLines); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkFragmentShader(shaderProgram, [], fragmentLines); }); it("addFragmentLines appends a single line to the fragment shader", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.addFragmentLines("float sum;"); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkFragmentShader(shaderProgram, [], ["float sum;"]); }); it("buildShaderProgram throws for undefined context", function() { const shaderBuilder = new import__18.ShaderBuilder(); expect(function() { return shaderBuilder.buildShaderProgram(void 0); }).toThrowDeveloperError(); }); it("buildShaderProgram creates a shaderProgram", function() { const shaderBuilder = new import__18.ShaderBuilder(); shaderBuilder.setPositionAttribute("vec3", "a_position"); shaderBuilder.addAttribute("vec3", "a_uv"); shaderBuilder.addVarying("vec2", "v_uv"); shaderBuilder.addDefine("BLUE_TINT", 0.5, import__18.ShaderDestination.FRAGMENT); const vertexLines = [ "void main()", "{", " v_uv = a_uv", " gl_Position = vec4(a_position, 1.0);", "}" ]; shaderBuilder.addVertexLines(vertexLines); const fragmentLines = [ "void main()", "{", " out_FragColor = vec4(v_uv, BLUE_TINT, 1.0);", "}" ]; shaderBuilder.addFragmentLines(fragmentLines); const expectedAttributes = ["in vec3 a_position;", "in vec3 a_uv;"]; const expectedVaryings = ["vec2 v_uv;"]; const expectedVertexVaryings = expectedVaryings.map( (varying) => `out ${varying}` ); const expectedFragmentVaryings = expectedVaryings.map( (varying) => `in ${varying}` ); const shaderProgram = shaderBuilder.buildShaderProgram(context); checkVertexShader( shaderProgram, [], expectedAttributes.concat(expectedVertexVaryings, vertexLines) ); checkFragmentShader( shaderProgram, ["BLUE_TINT 0.5"], expectedFragmentVaryings.concat(fragmentLines) ); }); }, "WebGL" ); // packages/engine/Specs/Renderer/ShaderCacheSpec.js var import__19 = __toESM(require_Cesium(), 1); describe( "Renderer/ShaderCache", function() { let context; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); it("adds and removes", function() { const vs = "in vec4 position; void main() { gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; const cache = new import__19.ShaderCache(context); const sp = cache.getShaderProgram({ vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); expect(sp._cachedShader.count).toEqual(1); expect(cache.numberOfShaders).toEqual(1); cache.releaseShaderProgram(sp); expect(sp.isDestroyed()).toEqual(false); expect(cache.numberOfShaders).toEqual(1); cache.destroyReleasedShaderPrograms(); expect(sp.isDestroyed()).toEqual(true); expect(cache.numberOfShaders).toEqual(0); cache.destroy(); }); it("adds and removes 2", function() { const vs = "in vec4 position; void main() { gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; const cache = new import__19.ShaderCache(context); const sp = cache.getShaderProgram({ vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); expect(sp._cachedShader.count).toEqual(1); sp.destroy(); expect(sp.isDestroyed()).toEqual(false); cache.destroyReleasedShaderPrograms(); expect(sp.isDestroyed()).toEqual(true); cache.destroy(); }); it("has a cache hit", function() { const vs = "in vec4 position; void main() { gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; spyOn( import__19.ShaderSource.prototype, "createCombinedVertexShader" ).and.callThrough(); spyOn( import__19.ShaderSource.prototype, "createCombinedFragmentShader" ).and.callThrough(); const cache = new import__19.ShaderCache(context); const sp = cache.getShaderProgram({ vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); const sp2 = cache.getShaderProgram({ vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); expect(sp).toBe(sp2); expect(sp._cachedShader.count).toEqual(2); expect(cache.numberOfShaders).toEqual(1); expect( import__19.ShaderSource.prototype.createCombinedVertexShader ).toHaveBeenCalledTimes(1); expect( import__19.ShaderSource.prototype.createCombinedFragmentShader ).toHaveBeenCalledTimes(1); sp.destroy(); sp2.destroy(); cache.destroyReleasedShaderPrograms(); expect(sp.isDestroyed()).toEqual(true); expect(cache.numberOfShaders).toEqual(0); cache.destroy(); }); it("cache handles unordered attributeLocations dictionary", function() { const vs = "in vec4 position; void main() { gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; const attributeLocations = { position: 0, normal: 1, color: 2 }; const attributeLocationsReordered = { color: 2, position: 0, normal: 1 }; spyOn( import__19.ShaderSource.prototype, "createCombinedVertexShader" ).and.callThrough(); spyOn( import__19.ShaderSource.prototype, "createCombinedFragmentShader" ).and.callThrough(); const cache = new import__19.ShaderCache(context); const sp = cache.getShaderProgram({ vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations }); const sp2 = cache.getShaderProgram({ vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: attributeLocationsReordered }); expect(sp).toBe(sp2); expect(sp._cachedShader.count).toEqual(2); expect(cache.numberOfShaders).toEqual(1); expect( import__19.ShaderSource.prototype.createCombinedVertexShader ).toHaveBeenCalledTimes(1); expect( import__19.ShaderSource.prototype.createCombinedFragmentShader ).toHaveBeenCalledTimes(1); sp.destroy(); sp2.destroy(); cache.destroyReleasedShaderPrograms(); expect(sp.isDestroyed()).toEqual(true); expect(cache.numberOfShaders).toEqual(0); cache.destroy(); }); it("replaces a shader program", function() { const vs = "in vec4 position; void main() { gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; const fs2 = "void main() { out_FragColor = vec4(0.5); }"; const attributeLocations = { position: 0 }; const cache = new import__19.ShaderCache(context); const sp = cache.replaceShaderProgram({ vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations }); const sp2 = cache.replaceShaderProgram({ shaderProgram: sp, vertexShaderSource: vs, fragmentShaderSource: fs2, attributeLocations }); expect(sp._cachedShader.count).toEqual(0); expect(sp2._cachedShader.count).toEqual(1); cache.destroy(); }); it("avoids thrashing", function() { const vs = "in vec4 position; void main() { gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; const cache = new import__19.ShaderCache(context); const sp = cache.getShaderProgram({ vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); sp.destroy(); const sp2 = cache.getShaderProgram({ vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); cache.destroyReleasedShaderPrograms(); expect(sp.isDestroyed()).toEqual(false); expect(sp2.isDestroyed()).toEqual(false); sp2.destroy(); cache.destroyReleasedShaderPrograms(); expect(sp.isDestroyed()).toEqual(true); expect(sp2.isDestroyed()).toEqual(true); cache.destroy(); }); it("create derived shader program", function() { const vs = "in vec4 position; void main() { gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; const cache = new import__19.ShaderCache(context); const sp = cache.getShaderProgram({ vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); const keyword = "derived"; let spDerived = cache.getDerivedShaderProgram(sp, keyword); expect(spDerived).not.toBeDefined(); const fsDerived = "void main() { out_FragColor = vec4(vec3(1.0), 0.5); }"; spDerived = cache.createDerivedShaderProgram(sp, keyword, { vertexShaderSource: vs, fragmentShaderSource: fsDerived, attributeLocations: { position: 0 } }); expect(spDerived).toBeDefined(); cache.destroy(); }); it("replaces derived shader program", function() { const vs = "in vec4 position; void main() { gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; const cache = new import__19.ShaderCache(context); const sp = cache.getShaderProgram({ vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); const derivedKeywords = sp._cachedShader.derivedKeywords; const keyword = "derived"; const fsDerived = "void main() { out_FragColor = vec4(vec3(1.0), 0.5); }"; const spDerived = cache.replaceDerivedShaderProgram(sp, keyword, { vertexShaderSource: vs, fragmentShaderSource: fsDerived, attributeLocations: { position: 0 } }); expect(spDerived).toBeDefined(); expect(derivedKeywords.length).toBe(1); const fsDerived2 = "void main() { out_FragColor = vec4(vec3(0.5), 0.5); }"; const spDerived2 = cache.replaceDerivedShaderProgram(sp, keyword, { vertexShaderSource: vs, fragmentShaderSource: fsDerived2, attributeLocations: { position: 0 } }); expect(spDerived.isDestroyed()).toBe(true); expect(spDerived2.isDestroyed()).toBe(false); expect(derivedKeywords.length).toBe(1); cache.destroy(); }); it("destroying a shader program destroys its derived shaders", function() { const vs = "in vec4 position; void main() { gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; const cache = new import__19.ShaderCache(context); const sp = cache.getShaderProgram({ vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); const keyword = "derived"; const fsDerived = "void main() { out_FragColor = vec4(vec3(1.0), 0.5); }"; const spDerived = cache.createDerivedShaderProgram(sp, keyword, { vertexShaderSource: vs, fragmentShaderSource: fsDerived, attributeLocations: { position: 0 } }); expect(spDerived).toBeDefined(); sp.destroy(); cache.destroyReleasedShaderPrograms(); expect(sp.isDestroyed()).toEqual(true); expect(spDerived.isDestroyed()).toEqual(true); cache.destroy(); }); it("is destroyed", function() { const vs = "in vec4 position; void main() { gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; const cache = new import__19.ShaderCache(context); const sp = cache.getShaderProgram({ vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); cache.destroy(); expect(sp.isDestroyed()).toEqual(true); expect(cache.isDestroyed()).toEqual(true); }); it("is not destroyed", function() { const cache = new import__19.ShaderCache(context); expect(cache.isDestroyed()).toEqual(false); }); }, "WebGL" ); // packages/engine/Specs/Renderer/ShaderDestinationSpec.js var import__20 = __toESM(require_Cesium(), 1); describe("Renderer/ShaderDestination", function() { it("includesVertexShader throws for undefined destination", function() { expect(function() { return import__20.ShaderDestination.includesVertexShader(void 0); }).toThrowDeveloperError(); }); it("includesVertexShader works", function() { expect( import__20.ShaderDestination.includesVertexShader(import__20.ShaderDestination.VERTEX) ).toBe(true); expect( import__20.ShaderDestination.includesVertexShader(import__20.ShaderDestination.FRAGMENT) ).toBe(false); expect(import__20.ShaderDestination.includesVertexShader(import__20.ShaderDestination.BOTH)).toBe( true ); }); it("includesFragmentShader throws for undefined destination", function() { expect(function() { return import__20.ShaderDestination.includesFragmentShader(void 0); }).toThrowDeveloperError(); }); it("includesFragmentShader works", function() { expect( import__20.ShaderDestination.includesFragmentShader(import__20.ShaderDestination.VERTEX) ).toBe(false); expect( import__20.ShaderDestination.includesFragmentShader(import__20.ShaderDestination.FRAGMENT) ).toBe(true); expect( import__20.ShaderDestination.includesFragmentShader(import__20.ShaderDestination.BOTH) ).toBe(true); }); }); // packages/engine/Specs/Renderer/ShaderFunctionSpec.js var import__21 = __toESM(require_Cesium(), 1); describe("Renderer/ShaderFunction", function() { const signature = "vec3 testFunction(vec3 position)"; it("constructs", function() { const func = new import__21.ShaderFunction(signature); expect(func.signature).toEqual(signature); expect(func.body).toEqual([]); }); it("addLines throws without lines", function() { const func = new import__21.ShaderFunction("TestFunction"); expect(function() { return func.addLines(); }).toThrowDeveloperError(); }); it("addLines throws for invalid lines", function() { const func = new import__21.ShaderFunction("TestFunction"); expect(function() { return func.addLines(100); }).toThrowDeveloperError(); }); it("addLines adds lines to the function body", function() { const func = new import__21.ShaderFunction("TestFunction"); func.addLines(["v_color = a_color;", "return vec3(0.0, 0.0, 1.0);"]); expect(func.body).toEqual([ " v_color = a_color;", " return vec3(0.0, 0.0, 1.0);" ]); }); it("addLines accepts a single string", function() { const func = new import__21.ShaderFunction("TestFunction"); func.addLines("v_color = a_color;"); expect(func.body).toEqual([" v_color = a_color;"]); }); it("generateGlslLines generates a function", function() { const func = new import__21.ShaderFunction(signature); func.addLines(["v_color = a_color;", "return vec3(0.0, 0.0, 1.0);"]); expect(func.generateGlslLines()).toEqual([ signature, "{", " v_color = a_color;", " return vec3(0.0, 0.0, 1.0);", "}" ]); }); }); // packages/engine/Specs/Renderer/ShaderProgramSpec.js var import__22 = __toESM(require_Cesium(), 1); describe( "Renderer/ShaderProgram", function() { const webglStub = !!window.webglStub; let context; let sp; const injectedTestFunctions = { czm_circularDependency1: "void czm_circularDependency1() { czm_circularDependency2(); }", czm_circularDependency2: "void czm_circularDependency2() { czm_circularDependency1(); }", czm_testFunction3: "void czm_testFunction3(vec4 color) { czm_testFunction2(color); }", czm_testFunction2: "void czm_testFunction2(vec4 color) { czm_testFunction1(color); }", czm_testFunction1: "void czm_testFunction1(vec4 color) { out_FragColor = color; }", czm_testDiamondDependency1: "vec4 czm_testDiamondDependency1(vec4 color) { return czm_testAddAlpha(color); }", czm_testDiamondDependency2: "vec4 czm_testDiamondDependency2(vec4 color) { return czm_testAddAlpha(color); }", czm_testAddAlpha: "vec4 czm_testAddAlpha(vec4 color) { color.a = clamp(color.a + 0.1, 0.0, 1.0); return color; }", czm_testAddRed: "vec4 czm_testAddRed(vec4 color) { color.r = clamp(color.r + 0.1, 0.0, 1.0); return color; }", czm_testAddGreen: "vec4 czm_testAddGreen(vec4 color) { color.g = clamp(color.g + 0.1, 0.0, 1.0); return color; }", czm_testAddRedGreenAlpha: "vec4 czm_testAddRedGreenAlpha(vec4 color) { color = czm_testAddRed(color); color = czm_testAddGreen(color); color = czm_testAddAlpha(color); return color; }", czm_testFunction4: "void czm_testFunction4(vec4 color) { color = czm_testAddAlpha(color); color = czm_testAddRedGreenAlpha(color); czm_testFunction3(color); }", czm_testFunctionWithComment: "/**\n czm_circularDependency1() \n*/\nvoid czm_testFunctionWithComment(vec4 color) { czm_testFunction1(color); }" }; beforeAll(function() { context = createContext_default(); for (const functionName in injectedTestFunctions) { if (injectedTestFunctions.hasOwnProperty(functionName)) { import__22.ShaderSource._czmBuiltinsAndUniforms[functionName] = injectedTestFunctions[functionName]; } } }); afterAll(function() { context.destroyForSpecs(); for (const functionName in injectedTestFunctions) { if (injectedTestFunctions.hasOwnProperty(functionName)) { delete import__22.ShaderSource._czmBuiltinsAndUniforms[functionName]; } } }); afterEach(function() { sp = sp && sp.destroy(); }); it("has vertex and fragment shader source", function() { const vs = "void main() { gl_Position = vec4(1.0); }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__22.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs }); const expectedVSText = new import__22.ShaderSource({ sources: [vs] }).createCombinedVertexShader(context); expect(sp._vertexShaderText).toEqual(expectedVSText); const expectedFSText = new import__22.ShaderSource({ sources: [fs] }).createCombinedFragmentShader(context); expect(sp._fragmentShaderText).toEqual(expectedFSText); }); it("has a position vertex attribute", function() { const vs = "in vec4 position; void main() { gl_Position = position; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__22.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs }); if (webglStub) { return; } expect(sp.numberOfVertexAttributes).toEqual(1); expect(sp.vertexAttributes.position.name).toEqual("position"); }); it("sets attribute indices", function() { const vs = "in vec4 position;in vec3 normal;in float heat;void main() { gl_Position = position + vec4(normal, 0.0) + vec4(heat); }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; const attributes = { position: 3, normal: 2, heat: 1 }; sp = import__22.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: attributes }); if (webglStub) { return; } expect(sp.numberOfVertexAttributes).toEqual(3); expect(sp.vertexAttributes.position.name).toEqual("position"); expect(sp.vertexAttributes.position.index).toEqual(attributes.position); expect(sp.vertexAttributes.normal.name).toEqual("normal"); expect(sp.vertexAttributes.normal.index).toEqual(attributes.normal); expect(sp.vertexAttributes.heat.name).toEqual("heat"); expect(sp.vertexAttributes.heat.index).toEqual(attributes.heat); }); it("has an automatic uniform", function() { const vs = "uniform vec4 u_vec4; void main() { gl_Position = u_vec4; }"; const fs = "void main() { out_FragColor = vec4((czm_viewport.x == 0.0) && (czm_viewport.y == 0.0) && (czm_viewport.z == 1.0) && (czm_viewport.w == 1.0)); }"; sp = import__22.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs }); if (webglStub) { return; } expect(sp.allUniforms.u_vec4.name).toEqual("u_vec4"); expect(sp.allUniforms.czm_viewport.name).toEqual("czm_viewport"); }); it("has uniforms of every datatype", function() { const d = context; const vs = "uniform float u_float;uniform vec2 u_vec2;uniform vec3 u_vec3;uniform vec4 u_vec4;uniform int u_int;uniform ivec2 u_ivec2;uniform ivec3 u_ivec3;uniform ivec4 u_ivec4;uniform bool u_bool;uniform bvec2 u_bvec2;uniform bvec3 u_bvec3;uniform bvec4 u_bvec4;uniform mat2 u_mat2;uniform mat3 u_mat3;uniform mat4 u_mat4;void main() { gl_Position = vec4(u_float) * vec4((u_mat2 * u_vec2), 0.0, 0.0) * vec4((u_mat3 * u_vec3), 0.0) * (u_mat4 * u_vec4) * vec4(u_int) * vec4(u_ivec2, 0.0, 0.0) * vec4(u_ivec3, 0.0) * vec4(u_ivec4) * vec4(u_bool) * vec4(u_bvec2, 0.0, 0.0) * vec4(u_bvec3, 0.0) * vec4(u_bvec4); }"; const fs = "uniform sampler2D u_sampler2D;uniform samplerCube u_samplerCube;void main() { out_FragColor = texture(u_sampler2D, vec2(0.0)) + czm_textureCube(u_samplerCube, vec3(1.0)); }"; sp = import__22.ShaderProgram.fromCache({ context: d, vertexShaderSource: vs, fragmentShaderSource: fs }); if (webglStub) { return; } expect(sp.allUniforms.u_float.name).toEqual("u_float"); expect(sp.allUniforms.u_vec2.name).toEqual("u_vec2"); expect(sp.allUniforms.u_vec3.name).toEqual("u_vec3"); expect(sp.allUniforms.u_vec4.name).toEqual("u_vec4"); expect(sp.allUniforms.u_int.name).toEqual("u_int"); expect(sp.allUniforms.u_ivec2.name).toEqual("u_ivec2"); expect(sp.allUniforms.u_ivec3.name).toEqual("u_ivec3"); expect(sp.allUniforms.u_ivec4.name).toEqual("u_ivec4"); expect(sp.allUniforms.u_bool.name).toEqual("u_bool"); expect(sp.allUniforms.u_bvec2.name).toEqual("u_bvec2"); expect(sp.allUniforms.u_bvec3.name).toEqual("u_bvec3"); expect(sp.allUniforms.u_bvec4.name).toEqual("u_bvec4"); expect(sp.allUniforms.u_mat2.name).toEqual("u_mat2"); expect(sp.allUniforms.u_mat3.name).toEqual("u_mat3"); expect(sp.allUniforms.u_mat4.name).toEqual("u_mat4"); expect(sp.allUniforms.u_sampler2D.name).toEqual("u_sampler2D"); expect(sp.allUniforms.u_samplerCube.name).toEqual("u_samplerCube"); }); it("has a struct uniform", function() { const vs = "uniform struct { float f; vec4 v; } u_struct; void main() { gl_Position = u_struct.f * u_struct.v; }"; const fs = "void main() { out_FragColor = vec4(1.0); }"; sp = import__22.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs }); if (webglStub) { return; } expect(sp.allUniforms["u_struct.f"].name).toEqual("u_struct.f"); expect(sp.allUniforms["u_struct.v"].name).toEqual("u_struct.v"); }); it("has uniform arrays of every datatype", function() { const d = context; const vs = "uniform float u_float[2];uniform vec2 u_vec2[2];uniform vec3 u_vec3[2];uniform vec4 u_vec4[2];uniform int u_int[2];uniform ivec2 u_ivec2[2];uniform ivec3 u_ivec3[2];uniform ivec4 u_ivec4[2];uniform bool u_bool[2];uniform bvec2 u_bvec2[2];uniform bvec3 u_bvec3[2];uniform bvec4 u_bvec4[2];uniform mat2 u_mat2[2];uniform mat3 u_mat3[2];uniform mat4 u_mat4[2];void main() { gl_Position = vec4(u_float[0]) * vec4(u_float[1]) * vec4((u_mat2[0] * u_vec2[0]), 0.0, 0.0) * vec4((u_mat2[1] * u_vec2[1]), 0.0, 0.0) * vec4((u_mat3[0] * u_vec3[0]), 0.0) * vec4((u_mat3[1] * u_vec3[1]), 0.0) * (u_mat4[0] * u_vec4[0]) * (u_mat4[1] * u_vec4[1]) * vec4(u_int[0]) * vec4(u_int[1]) * vec4(u_ivec2[0], 0.0, 0.0) * vec4(u_ivec2[1], 0.0, 0.0) * vec4(u_ivec3[0], 0.0) * vec4(u_ivec3[1], 0.0) * vec4(u_ivec4[0]) * vec4(u_ivec4[1]) * vec4(u_bool[0]) * vec4(u_bool[1]) * vec4(u_bvec2[0], 0.0, 0.0) * vec4(u_bvec2[1], 0.0, 0.0) * vec4(u_bvec3[0], 0.0) * vec4(u_bvec3[1], 0.0) * vec4(u_bvec4[0]) * vec4(u_bvec4[1]); }"; const fs = "uniform sampler2D u_sampler2D[2];uniform samplerCube u_samplerCube[2];void main() { out_FragColor = texture(u_sampler2D[0], vec2(0.0)) + texture(u_sampler2D[1], vec2(0.0)) + czm_textureCube(u_samplerCube[0], vec3(1.0)) + czm_textureCube(u_samplerCube[1], vec3(1.0)); }"; sp = import__22.ShaderProgram.fromCache({ context: d, vertexShaderSource: vs, fragmentShaderSource: fs }); if (webglStub) { return; } expect(sp.allUniforms.u_float.name).toEqual("u_float"); expect(sp.allUniforms.u_vec2.name).toEqual("u_vec2"); expect(sp.allUniforms.u_vec3.name).toEqual("u_vec3"); expect(sp.allUniforms.u_vec4.name).toEqual("u_vec4"); expect(sp.allUniforms.u_int.name).toEqual("u_int"); expect(sp.allUniforms.u_ivec2.name).toEqual("u_ivec2"); expect(sp.allUniforms.u_ivec3.name).toEqual("u_ivec3"); expect(sp.allUniforms.u_ivec4.name).toEqual("u_ivec4"); expect(sp.allUniforms.u_bool.name).toEqual("u_bool"); expect(sp.allUniforms.u_bvec2.name).toEqual("u_bvec2"); expect(sp.allUniforms.u_bvec3.name).toEqual("u_bvec3"); expect(sp.allUniforms.u_bvec4.name).toEqual("u_bvec4"); expect(sp.allUniforms.u_mat2.name).toEqual("u_mat2"); expect(sp.allUniforms.u_mat3.name).toEqual("u_mat3"); expect(sp.allUniforms.u_mat4.name).toEqual("u_mat4"); expect(sp.allUniforms.u_sampler2D.name).toEqual("u_sampler2D"); expect(sp.allUniforms.u_samplerCube.name).toEqual("u_samplerCube"); expect(sp.allUniforms.u_float.value.length).toEqual(2); expect(sp.allUniforms.u_vec2.value.length).toEqual(2); expect(sp.allUniforms.u_vec3.value.length).toEqual(2); expect(sp.allUniforms.u_vec4.value.length).toEqual(2); expect(sp.allUniforms.u_int.value.length).toEqual(2); expect(sp.allUniforms.u_ivec2.value.length).toEqual(2); expect(sp.allUniforms.u_ivec3.value.length).toEqual(2); expect(sp.allUniforms.u_ivec4.value.length).toEqual(2); expect(sp.allUniforms.u_bool.value.length).toEqual(2); expect(sp.allUniforms.u_bvec2.value.length).toEqual(2); expect(sp.allUniforms.u_bvec3.value.length).toEqual(2); expect(sp.allUniforms.u_bvec4.value.length).toEqual(2); expect(sp.allUniforms.u_mat2.value.length).toEqual(2); expect(sp.allUniforms.u_mat3.value.length).toEqual(2); expect(sp.allUniforms.u_mat4.value.length).toEqual(2); expect(sp.allUniforms.u_sampler2D.value.length).toEqual(2); expect(sp.allUniforms.u_samplerCube.value.length).toEqual(2); }); it("has predefined constants", function() { const fs = "void main() { float f = ((czm_pi > 0.0) && \n (czm_oneOverPi > 0.0) && \n (czm_piOverTwo > 0.0) && \n (czm_piOverThree > 0.0) && \n (czm_piOverFour > 0.0) && \n (czm_piOverSix > 0.0) && \n (czm_threePiOver2 > 0.0) && \n (czm_twoPi > 0.0) && \n (czm_oneOverTwoPi > 0.0) && \n (czm_radiansPerDegree > 0.0) && \n (czm_degreesPerRadian > 0.0)) ? 1.0 : 0.0; \n out_FragColor = vec4(f); \n}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("has built-in constant, structs, and functions", function() { const fs = "void main() { \n czm_materialInput materialInput; \n czm_material material = czm_getDefaultMaterial(materialInput); \n material.diffuse = vec3(1.0, 1.0, 1.0); \n material.alpha = 1.0; \n material.diffuse = czm_hue(material.diffuse, czm_twoPi); \n out_FragColor = vec4(material.diffuse, material.alpha); \n}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("creates duplicate uniforms if precision of uniforms in vertex and fragment shader do not match", function() { const highpFloatSupported = import__22.ContextLimits.highpFloatSupported; import__22.ContextLimits._highpFloatSupported = false; const vs = "in vec4 position; uniform float u_value; out float v_value; void main() { gl_PointSize = 1.0; v_value = u_value * czm_viewport.z; gl_Position = position; }"; const fs = "uniform float u_value; in float v_value; void main() { out_FragColor = vec4(u_value * v_value * czm_viewport.z); }"; const uniformMap = { u_value: function() { return 1; } }; sp = import__22.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs }); if (!webglStub) { expect(sp.allUniforms.u_value).toBeDefined(); expect(sp.allUniforms.czm_mediump_u_value).toBeDefined(); } expect({ context, vertexShader: vs, fragmentShader: fs, uniformMap }).notContextToRender([0, 0, 0, 0]); import__22.ContextLimits._highpFloatSupported = highpFloatSupported; }); it("1 level function dependency", function() { const fs = "void main() { \n czm_testFunction1(vec4(1.0)); \n}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("2 level function dependency", function() { const fs = "void main() { \n czm_testFunction2(vec4(1.0)); \n}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("3 level function dependency", function() { const fs = "void main() { \n czm_testFunction3(vec4(1.0)); \n}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("diamond dependency", function() { const fs = "layout (location = 0) out vec4 out_FragColor;\nvoid main() { \n vec4 color = vec4(1.0, 1.0, 1.0, 0.8); \n color = czm_testDiamondDependency1(color); \n color = czm_testDiamondDependency2(color); \n out_FragColor = color; \n}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("diamond plus 3 level function dependency", function() { const fs = "void main() { \n vec4 color = vec4(1.0, 1.0, 1.0, 0.8); \n color = czm_testDiamondDependency1(color); \n color = czm_testDiamondDependency2(color); \n czm_testFunction3(color); \n}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("big mess of function dependencies", function() { const fs = "void main() { \n vec4 color = vec4(0.9, 0.9, 1.0, 0.6); \n color = czm_testDiamondDependency1(color); \n color = czm_testDiamondDependency2(color); \n czm_testFunction4(color); \n}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("doc comment with reference to another function", function() { const fs = "void main() { \n vec4 color = vec4(1.0, 1.0, 1.0, 1.0); \n czm_testFunctionWithComment(color); \n}"; expect({ context, fragmentShader: fs }).contextToRender(); }); it("compiles with #version at the top", function() { const vs = "#version 100 \nin vec4 position; void main() { gl_Position = position; }"; const fs = "#version 100 \nlayout (location = 0) out vec4 out_FragColor;\nvoid main() { out_FragColor = vec4(1.0); }"; sp = import__22.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs }); }); it("compiles with #version after whitespace and comments", function() { const vs = "// comment before version directive. \n#version 100 \nin vec4 position; void main() { gl_Position = position; }"; const fs = "\n#version 100 \nlayout (location = 0) out vec4 out_FragColor;\nvoid main() { out_FragColor = vec4(1.0); }"; sp = import__22.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs }); }); it("fails vertex shader compile", function() { if (webglStub) { return; } const vs = "does not compile."; const fs = "layout (location = 0) out vec4 out_FragColor;\nvoid main() { out_FragColor = vec4(1.0); }"; sp = import__22.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs }); expect(function() { sp._bind(); }).toThrowError(import__22.RuntimeError); }); it("fails fragment shader compile", function() { if (webglStub) { return; } const vs = "void main() { gl_Position = vec4(0.0); }"; const fs = "does not compile."; sp = import__22.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs }); expect(function() { sp._bind(); }).toThrowError(import__22.RuntimeError); }); it("fails to link", function() { if (webglStub) { return; } const vs = "void nomain() { }"; const fs = "void nomain() { }"; sp = import__22.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs }); expect(function() { sp._bind(); }).toThrowError(import__22.RuntimeError); }); it("fails with built-in function circular dependency", function() { const vs = "void main() { gl_Position = vec4(0.0); }"; const fs = "layout (location = 0) out vec4 out_FragColor;\nvoid main() { czm_circularDependency1(); out_FragColor = vec4(1.0); }"; expect(function() { sp = import__22.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs }); sp._bind(); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Renderer/ShaderSourceSpec.js var import__23 = __toESM(require_Cesium(), 1); describe("Renderer/ShaderSource", function() { const mockContext = { webgl2: true }; const fragColorDeclarationRegex = /layout\s*\(location\s*=\s*0\)\s*out\s+vec4\s+out_FragColor;/g; it("combines #defines", function() { const source = new import__23.ShaderSource({ defines: ["A", "B", ""] }); const shaderText = source.createCombinedVertexShader(mockContext); expect(shaderText).toContain("#define A"); expect(shaderText).toContain("#define B"); expect(shaderText.match(/#define/g).length).toEqual(2); }); it("combines sources", function() { const source = new import__23.ShaderSource({ sources: ["void func() {}", "void main() {}"] }); const shaderText = source.createCombinedVertexShader(mockContext); expect(shaderText).toContain("#line 0\nvoid func() {}"); expect(shaderText).toContain("#line 0\nvoid main() {}"); }); it("combines #defines and sources", function() { const source = new import__23.ShaderSource({ defines: ["A", "B", ""], sources: ["void func() {}", "void main() {}"] }); const shaderText = source.createCombinedVertexShader(mockContext); expect(shaderText).toContain("#define A"); expect(shaderText).toContain("#define B"); expect(shaderText.match(/#define/g).length).toEqual(2); expect(shaderText).toContain("#line 0\nvoid func() {}"); expect(shaderText).toContain("#line 0\nvoid main() {}"); }); it("creates a pick shader with a uniform", function() { const source = new import__23.ShaderSource({ sources: ["void main() { out_FragColor = vec4(1.0); }"], pickColorQualifier: "uniform" }); const shaderText = source.createCombinedVertexShader(mockContext); expect(shaderText).toContain("uniform vec4 czm_pickColor;"); expect(shaderText).toContain("out_FragColor = czm_pickColor;"); }); it("creates a pick shader with a varying", function() { const source = new import__23.ShaderSource({ sources: ["void main() { out_FragColor = vec4(1.0); }"], pickColorQualifier: "in" }); const shaderText = source.createCombinedVertexShader(mockContext); expect(shaderText).toContain("in vec4 czm_pickColor;"); expect(shaderText).toContain("out_FragColor = czm_pickColor;"); }); it("throws with invalid qualifier", function() { expect(function() { return new import__23.ShaderSource({ pickColorQualifier: "const" }); }).toThrowDeveloperError(); }); it("combines #version to shader", function() { const source = new import__23.ShaderSource({ sources: ["#version 300 es\nvoid main() {out_FragColor = vec4(1.0); }"] }); const shaderText = source.createCombinedVertexShader(mockContext); expect(shaderText).toStartWith("#version 300 es\n"); }); it("clones", function() { const source = new import__23.ShaderSource({ defines: ["A"], sources: ["void main() { out_FragColor = vec4(1.0); }"], pickColorQualifier: "in", includeBuiltIns: false }); const clone24 = source.clone(); expect(clone24.defines).toBeDefined(); expect(clone24.defines.length).toEqual(1); expect(clone24.defines[0]).toEqual(source.defines[0]); expect(clone24.sources).toBeDefined(); expect(clone24.sources.length).toEqual(1); expect(clone24.sources[0]).toEqual(source.sources[0]); expect(clone24.pickColorQualifier).toEqual(source.pickColorQualifier); expect(clone24.includeBuiltIns).toEqual(source.includeBuiltIns); }); it("creates cache key for empty shader", function() { const source = new import__23.ShaderSource(); expect(source.getCacheKey()).toBe(":undefined:true:"); }); it("creates cache key", function() { const source = new import__23.ShaderSource({ defines: ["A", "B", "C"], sources: ["void main() { out_FragColor = vec4(1.0); }"], pickColorQualifier: "in", includeBuiltIns: false }); expect(source.getCacheKey()).toBe( "A,B,C:in:false:void main() { out_FragColor = vec4(1.0); }" ); }); it("uses sorted list of defines in cache key", function() { const defines1 = ["A", "B", "C"]; const defines2 = ["B", "C", "A"]; const source1 = new import__23.ShaderSource({ defines: defines1 }); const source2 = new import__23.ShaderSource({ defines: defines2 }); const key1 = source1.getCacheKey(); expect(key1).toBe(source2.getCacheKey()); expect(key1).toBe("A,B,C:undefined:true:"); }); it("cache key includes all sources", function() { const source = new import__23.ShaderSource({ sources: [ "vec4 getColor() { return vec4(1.0, 0.0, 0.0, 1.0); }", "void main() { out_FragColor = getColor(); }" ] }); expect(source.getCacheKey()).toBe( ":undefined:true:vec4 getColor() { return vec4(1.0, 0.0, 0.0, 1.0); }\nvoid main() { out_FragColor = getColor(); }" ); }); it("adds layout declaration for out_FragColor if it does not already exist", function() { const source = new import__23.ShaderSource({ defines: ["A"], sources: ["void main() { out_FragColor = vec4(1.0); }"], pickColorQualifier: "in", includeBuiltIns: false }); const shaderText = source.createCombinedFragmentShader(mockContext); const fragColorDeclarations = shaderText.match(fragColorDeclarationRegex) || []; expect(fragColorDeclarations.length).toEqual(1); }); it("does not layout declaration for out_FragColor if it already exists", function() { const source = new import__23.ShaderSource({ defines: ["A"], sources: [ "layout (location = 0) out vec4 out_FragColor; void main() { out_FragColor = vec4(1.0); }" ], pickColorQualifier: "in", includeBuiltIns: false }); const shaderText = source.createCombinedFragmentShader(mockContext); const fragColorDeclarations = shaderText.match(fragColorDeclarationRegex) || []; expect(fragColorDeclarations.length).toEqual(1); }); }); // packages/engine/Specs/Renderer/ShaderStructSpec.js var import__24 = __toESM(require_Cesium(), 1); describe("Renderer/ShaderStruct", function() { it("constructs", function() { const struct = new import__24.ShaderStruct("TestStruct"); expect(struct.name).toEqual("TestStruct"); expect(struct.fields).toEqual([]); }); it("addField adds fields", function() { const struct = new import__24.ShaderStruct("TestStruct"); struct.addField("vec3", "positionMC"); struct.addField("float", "weights[4]"); struct.addField("OtherStruct", "complex"); expect(struct.fields).toEqual([ " vec3 positionMC;", " float weights[4];", " OtherStruct complex;" ]); }); it("generateGlslLines generates a struct definition", function() { const struct = new import__24.ShaderStruct("TestStruct"); struct.addField("vec3", "positionMC"); struct.addField("float", "weights[4]"); struct.addField("OtherStruct", "complex"); expect(struct.generateGlslLines()).toEqual([ "struct TestStruct", "{", " vec3 positionMC;", " float weights[4];", " OtherStruct complex;", "};" ]); }); it("generateGlslLines pads an empty struct definition", function() { const struct = new import__24.ShaderStruct("Nothing"); expect(struct.generateGlslLines()).toEqual([ "struct Nothing", "{", " float _empty;", "};" ]); }); }); // packages/engine/Specs/Renderer/TextureCacheSpec.js var import__25 = __toESM(require_Cesium(), 1); describe( "Renderer/TextureCache", function() { let context; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); it("adds and removes", function() { const cache = new import__25.TextureCache(); const keyword = "texture"; const texture = new import__25.Texture({ context, width: 1, height: 1 }); cache.addTexture(keyword, texture); expect(cache._textures[keyword].count).toEqual(1); expect(cache.numberOfTextures).toEqual(1); texture.destroy(); expect(texture.isDestroyed()).toEqual(false); expect(cache.numberOfTextures).toEqual(1); cache.destroyReleasedTextures(); expect(texture.isDestroyed()).toEqual(true); expect(cache.numberOfTextures).toEqual(0); cache.destroy(); }); it("has a cache hit", function() { const cache = new import__25.TextureCache(context); const keyword = "texture"; const texture = new import__25.Texture({ context, width: 1, height: 1 }); cache.addTexture(keyword, texture); const texture2 = cache.getTexture(keyword); expect(texture2).toBeDefined(); expect(texture).toBe(texture2); expect(cache._textures[keyword].count).toEqual(2); expect(cache.numberOfTextures).toEqual(1); texture.destroy(); texture2.destroy(); cache.destroyReleasedTextures(); expect(texture.isDestroyed()).toEqual(true); expect(cache.numberOfTextures).toEqual(0); cache.destroy(); }); it("avoids thrashing", function() { const cache = new import__25.TextureCache(); const keyword = "texture"; const texture = new import__25.Texture({ context, width: 1, height: 1 }); cache.addTexture(keyword, texture); texture.destroy(); const texture2 = cache.getTexture(keyword); cache.destroyReleasedTextures(); expect(texture.isDestroyed()).toEqual(false); expect(texture2.isDestroyed()).toEqual(false); texture2.destroy(); cache.destroyReleasedTextures(); expect(texture.isDestroyed()).toEqual(true); expect(texture2.isDestroyed()).toEqual(true); cache.destroy(); }); it("is destroyed", function() { const cache = new import__25.TextureCache(); const keyword = "texture"; const texture = new import__25.Texture({ context, width: 1, height: 1 }); cache.addTexture(keyword, texture); cache.destroy(); expect(texture.isDestroyed()).toEqual(true); expect(cache.isDestroyed()).toEqual(true); }); it("is not destroyed", function() { const cache = new import__25.TextureCache(); expect(cache.isDestroyed()).toEqual(false); }); }, "WebGL" ); // packages/engine/Specs/Renderer/TextureSpec.js var import__26 = __toESM(require_Cesium(), 1); describe( "Renderer/Texture", function() { let context; let greenImage; let blueImage; let blueAlphaImage; let blueOverRedImage; let blueOverRedFlippedImage; let red16x16Image; let greenKTX2Image; let greenBasisKTX2Image; const fs = "uniform sampler2D u_texture;void main() { out_FragColor = texture(u_texture, vec2(0.0)); }"; const fsLuminanceAlpha = "uniform sampler2D u_texture;void main() { out_FragColor = vec4(texture(u_texture, vec2(0.0)).ra, 0.0, 1.0); }"; let texture; const uniformMap = { u_texture: function() { return texture; } }; beforeAll(function() { context = createContext_default(); const promises = []; promises.push( import__26.Resource.fetchImage("./Data/Images/Green.png").then(function(image) { greenImage = image; }) ); promises.push( import__26.Resource.fetchImage("./Data/Images/Blue.png").then(function(image) { blueImage = image; }) ); promises.push( import__26.Resource.fetchImage("./Data/Images/BlueAlpha.png").then(function(image) { blueAlphaImage = image; }) ); promises.push( import__26.Resource.fetchImage("./Data/Images/BlueOverRed.png").then(function(image) { blueOverRedImage = image; }) ); promises.push( import__26.Resource.fetchImage({ url: "./Data/Images/BlueOverRed.png", preferImageBitmap: true }).then(function(image) { blueOverRedFlippedImage = image; }) ); promises.push( import__26.Resource.fetchImage("./Data/Images/Red16x16.png").then(function(image) { red16x16Image = image; }) ); const resource = import__26.Resource.createIfNeeded("./Data/Images/Green4x4.ktx2"); const loadPromise = resource.fetchArrayBuffer(); promises.push( loadPromise.then(function(buffer) { const promise = import__26.KTX2Transcoder.transcode(buffer, {}); return promise.then(function(result) { greenKTX2Image = result; }); }) ); if (context.supportsBasis) { promises.push( (0, import__26.loadKTX2)("./Data/Images/Green4x4_ETC1S.ktx2").then(function(image) { greenBasisKTX2Image = image; }) ); } return Promise.all(promises); }); afterAll(function() { context.destroyForSpecs(); }); afterEach(function() { texture = texture && texture.destroy(); }); it("has expected default values for pixel format and datatype", function() { texture = new import__26.Texture({ context, source: blueImage }); expect(texture.id).toBeDefined(); expect(texture.pixelFormat).toEqual(import__26.PixelFormat.RGBA); expect(texture.pixelDatatype).toEqual(import__26.PixelDatatype.UNSIGNED_BYTE); }); it("can create a texture from the framebuffer", function() { const command = new import__26.ClearCommand({ color: import__26.Color.RED }); command.execute(context); texture = import__26.Texture.fromFramebuffer({ context }); const expectedWidth = context.canvas.clientWidth; const expectedHeight = context.canvas.clientHeight; expect(texture.width).toEqual(expectedWidth); expect(texture.height).toEqual(expectedHeight); expect(texture.sizeInBytes).toEqual( expectedWidth * expectedHeight * import__26.PixelFormat.componentsLength(texture.pixelFormat) ); command.color = import__26.Color.WHITE; command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); expect({ context, fragmentShader: fs, uniformMap }).contextToRender([255, 0, 0, 255]); }); it("can copy from the framebuffer", function() { texture = new import__26.Texture({ context, source: blueImage, pixelFormat: import__26.PixelFormat.RGB }); expect({ context, fragmentShader: fs, uniformMap }).contextToRender([0, 0, 255, 255]); const command = new import__26.ClearCommand({ color: import__26.Color.RED }); command.execute(context); expect(context).toReadPixels(import__26.Color.RED.toBytes()); texture.copyFromFramebuffer(); const expectedWidth = context.canvas.clientWidth; const expectedHeight = context.canvas.clientHeight; expect(texture.width).toEqual(expectedWidth); expect(texture.height).toEqual(expectedHeight); expect(texture.sizeInBytes).toEqual( expectedWidth * expectedHeight * import__26.PixelFormat.componentsLength(texture.pixelFormat) ); command.color = import__26.Color.WHITE; command.execute(context); expect(context).toReadPixels(import__26.Color.WHITE.toBytes()); expect({ context, fragmentShader: fs, uniformMap }).contextToRender([255, 0, 0, 255]); }); it("draws the expected texture color", function() { texture = new import__26.Texture({ context, source: blueImage, pixelFormat: import__26.PixelFormat.RGBA }); expect({ context, fragmentShader: fs, uniformMap }).contextToRender([0, 0, 255, 255]); }); it("cannot flip texture when using ImageBitmap", function() { const topColor = new import__26.Color(0, 0, 1, 1); let bottomColor = new import__26.Color(1, 0, 0, 1); return import__26.Resource.supportsImageBitmapOptions().then(function(supportsImageBitmapOptions) { if (supportsImageBitmapOptions) { bottomColor = topColor; } texture = new import__26.Texture({ context, source: blueOverRedFlippedImage, pixelFormat: import__26.PixelFormat.RGBA, flipY: false }); expect({ context, fragmentShader: fs, uniformMap }).contextToRender(topColor.toBytes()); texture = new import__26.Texture({ context, source: blueOverRedFlippedImage, pixelFormat: import__26.PixelFormat.RGBA, flipY: true }); expect({ context, fragmentShader: fs, uniformMap }).contextToRender(bottomColor.toBytes()); }); }); it("draws the expected floating-point texture color", function() { if (!context.floatingPointTexture) { return; } const color = new import__26.Color(0.2, 0.4, 0.6, 1); const floats = new Float32Array([ color.red, color.green, color.blue, color.alpha ]); texture = new import__26.Texture({ context, pixelFormat: import__26.PixelFormat.RGBA, pixelDatatype: import__26.PixelDatatype.FLOAT, source: { width: 1, height: 1, arrayBufferView: floats } }); expect(texture.sizeInBytes).toEqual(16); expect({ context, fragmentShader: fs, uniformMap }).contextToRender(color.toBytes()); }); it("draws the expected floating-point texture color with linear filtering", function() { if (!context.floatingPointTexture) { return; } const color0 = new import__26.Color(0.2, 0.4, 0.6, 1); const color1 = new import__26.Color(0.1, 0.3, 0.5, 1); const floats = new Float32Array([ color0.red, color0.green, color0.blue, color0.alpha, color1.red, color1.green, color1.blue, color1.alpha ]); texture = new import__26.Texture({ context, pixelFormat: import__26.PixelFormat.RGBA, pixelDatatype: import__26.PixelDatatype.FLOAT, source: { width: 2, height: 1, arrayBufferView: floats }, sampler: new import__26.Sampler({ wrapS: import__26.TextureWrap.CLAMP_TO_EDGE, wrapT: import__26.TextureWrap.CLAMP_TO_EDGE, minificationFilter: import__26.TextureMinificationFilter.LINEAR, magnificationFilter: import__26.TextureMagnificationFilter.LINEAR }) }); expect(texture.sizeInBytes).toEqual(32); const fs2 = "uniform sampler2D u_texture;void main() { out_FragColor = texture(u_texture, vec2(0.5, 0.0)); }"; if (!context.textureFloatLinear) { expect({ context, fragmentShader: fs2, uniformMap, epsilon: 1 }).contextToRender(color1.toBytes()); } else { import__26.Color.multiplyByScalar(color0, 1 - 0.5, color0); import__26.Color.multiplyByScalar(color1, 0.5, color1); import__26.Color.add(color0, color1, color1); expect({ context, fragmentShader: fs2, uniformMap }).contextToRender(color1.toBytes()); } }); it("draws the expected half floating-point texture color", function() { if (!context.halfFloatingPointTexture) { return; } const color = new import__26.Color(0.2, 0.4, 0.6, 1); const floats = new Uint16Array([12902, 13926, 14541, 15360]); texture = new import__26.Texture({ context, pixelFormat: import__26.PixelFormat.RGBA, pixelDatatype: import__26.PixelDatatype.HALF_FLOAT, source: { width: 1, height: 1, arrayBufferView: floats }, flipY: false }); expect(texture.sizeInBytes).toEqual(8); expect({ context, fragmentShader: fs, uniformMap }).contextToRender(color.toBytes()); }); it("draws the expected half floating-point texture color with linear filtering", function() { if (!context.halfFloatingPointTexture) { return; } const color0 = new import__26.Color(0.2, 0.4, 0.6, 1); const color1 = new import__26.Color(0.1, 0.3, 0.5, 1); const floats = new Uint16Array([ 12902, 13926, 14541, 15360, 11878, 13517, 14336, 15360 ]); texture = new import__26.Texture({ context, pixelFormat: import__26.PixelFormat.RGBA, pixelDatatype: import__26.PixelDatatype.HALF_FLOAT, source: { width: 2, height: 1, arrayBufferView: floats }, flipY: false }); expect(texture.sizeInBytes).toEqual(16); const fs2 = "uniform sampler2D u_texture;void main() { out_FragColor = texture(u_texture, vec2(0.5, 0.0)); }"; if (!context.textureHalfFloatLinear) { expect({ context, fragmentShader: fs2, uniformMap, epsilon: 1 }).contextToRender(color1.toBytes()); } else { import__26.Color.multiplyByScalar(color0, 1 - 0.5, color0); import__26.Color.multiplyByScalar(color1, 0.5, color1); import__26.Color.add(color0, color1, color1); expect({ context, fragmentShader: fs2, uniformMap }).contextToRender(color1.toBytes()); } }); it("draws the expected Basis compressed texture color", function() { if (!context.supportsBasis) { return; } texture = new import__26.Texture({ context, pixelFormat: greenBasisKTX2Image.internalFormat, source: { width: greenBasisKTX2Image.width, height: greenBasisKTX2Image.height, arrayBufferView: greenBasisKTX2Image.bufferView } }); expect(texture.sizeInBytes).toBe(8); expect({ context, fragmentShader: fs, uniformMap }).contextToRenderAndCall(function(color) { return expect(color).toEqualEpsilon([2, 255, 2, 255], 2); }); }); it("draws the expected KTX2 uncompressed texture color", function() { texture = new import__26.Texture({ context, pixelFormat: greenKTX2Image.internalFormat, source: { width: greenKTX2Image.width, height: greenKTX2Image.height, arrayBufferView: greenKTX2Image.bufferView } }); expect(texture.sizeInBytes).toBe(48); expect({ context, fragmentShader: fs, uniformMap }).contextToRenderAndCall(function(color) { return expect(color).toEqualEpsilon([0, 255, 24, 255], 2); }); }); it("renders with premultiplied alpha", function() { const cxt = createContext_default({ webgl: { alpha: true } }); const texture2 = new import__26.Texture({ context: cxt, source: blueAlphaImage, pixelFormat: import__26.PixelFormat.RGBA, preMultiplyAlpha: true }); const uniformMap2 = { u_texture: function() { return texture2; } }; expect(texture2.preMultiplyAlpha).toEqual(true); expect({ context: cxt, fragmentShader: fs, uniformMap: uniformMap2, epsilon: 1 }).contextToRender([0, 0, 127, 127]); texture2.destroy(); cxt.destroyForSpecs(); }); it("draws textured blue and red points", function() { texture = new import__26.Texture({ context, source: blueOverRedImage, pixelFormat: import__26.PixelFormat.RGBA }); let fragmentShaderSource = ""; fragmentShaderSource += "uniform sampler2D u_texture;"; fragmentShaderSource += "uniform mediump vec2 u_txCoords;"; fragmentShaderSource += "void main() { out_FragColor = texture(u_texture, u_txCoords); }"; let txCoords; const um = { u_texture: function() { return texture; }, u_txCoords: function() { return txCoords; } }; txCoords = new import__26.Cartesian2(0.5, 0.75); expect({ context, fragmentShader: fragmentShaderSource, uniformMap: um }).contextToRender([0, 0, 255, 255]); txCoords = new import__26.Cartesian2(0.5, 0.25); expect({ context, fragmentShader: fragmentShaderSource, uniformMap: um }).contextToRender([255, 0, 0, 255]); }); it("draws the expected luminance texture color", function() { const color = new import__26.Color(0.6, 0.6, 0.6, 1); const arrayBufferView = new Uint8Array([153]); texture = new import__26.Texture({ context, pixelFormat: import__26.PixelFormat.LUMINANCE, pixelDatatype: import__26.PixelDatatype.UNSIGNED_BYTE, source: { width: 1, height: 1, arrayBufferView }, flipY: false }); expect({ context, fragmentShader: fs, uniformMap }).contextToRender(color.toBytes()); }); it("draws the expected luminance alpha texture color", function() { const color = new import__26.Color(0.6, 0.8, 0, 1); const arrayBufferView = new Uint8Array([153, 204]); texture = new import__26.Texture({ context, pixelFormat: import__26.PixelFormat.LUMINANCE_ALPHA, pixelDatatype: import__26.PixelDatatype.UNSIGNED_BYTE, source: { width: 1, height: 1, arrayBufferView }, flipY: false }); expect({ context, fragmentShader: fsLuminanceAlpha, uniformMap }).contextToRender(color.toBytes()); }); it("can be created from a typed array", function() { const bytes = new Uint8Array([0, 255, 0, 255]); texture = new import__26.Texture({ context, pixelFormat: import__26.PixelFormat.RGBA, pixelDatatype: import__26.PixelDatatype.UNSIGNED_BYTE, source: { width: 1, height: 1, arrayBufferView: bytes } }); expect(texture.width).toEqual(1); expect(texture.height).toEqual(1); expect(texture.sizeInBytes).toEqual(4); expect({ context, fragmentShader: fs, uniformMap }).contextToRender([0, 255, 0, 255]); }); it("can copy from a typed array", function() { texture = new import__26.Texture({ context, pixelFormat: import__26.PixelFormat.RGBA, pixelDatatype: import__26.PixelDatatype.UNSIGNED_BYTE, width: 1, height: 1 }); const bytes = new Uint8Array(import__26.Color.NAVY.toBytes()); texture.copyFrom({ source: { width: 1, height: 1, arrayBufferView: bytes } }); expect(texture.width).toEqual(1); expect(texture.height).toEqual(1); expect(texture.sizeInBytes).toEqual(4); expect({ context, fragmentShader: fs, uniformMap }).contextToRender(import__26.Color.NAVY.toBytes()); }); it("can copy from a DOM element", function() { texture = new import__26.Texture({ context, pixelFormat: import__26.PixelFormat.RGB, pixelDatatype: import__26.PixelDatatype.UNSIGNED_BYTE, width: blueImage.width, height: blueImage.height }); texture.copyFrom({ source: blueImage }); expect({ context, fragmentShader: fs, uniformMap, epsilon: 1 }).contextToRender([0, 0, 255, 255]); }); it("can replace a subset of a texture", function() { texture = new import__26.Texture({ context, source: blueOverRedImage, pixelFormat: import__26.PixelFormat.RGBA }); let fragmentShaderSource = ""; fragmentShaderSource += "uniform sampler2D u_texture;"; fragmentShaderSource += "uniform mediump vec2 u_txCoords;"; fragmentShaderSource += "void main() { out_FragColor = texture(u_texture, u_txCoords); }"; let txCoords; const um = { u_texture: function() { return texture; }, u_txCoords: function() { return txCoords; } }; txCoords = new import__26.Cartesian2(0.5, 0.75); expect({ context, fragmentShader: fragmentShaderSource, uniformMap: um }).contextToRender([0, 0, 255, 255]); txCoords = new import__26.Cartesian2(0.5, 0.25); expect({ context, fragmentShader: fragmentShaderSource, uniformMap: um }).contextToRender([255, 0, 0, 255]); texture.copyFrom({ source: greenImage, xOffset: 0, yOffset: 1 }); txCoords = new import__26.Cartesian2(0.5, 0.75); expect({ context, fragmentShader: fragmentShaderSource, uniformMap: um }).contextToRender(import__26.Color.LIME.toBytes()); txCoords = new import__26.Cartesian2(0.5, 0.25); expect({ context, fragmentShader: fragmentShaderSource, uniformMap: um }).contextToRender([255, 0, 0, 255]); }); it("can generate mipmaps", function() { texture = new import__26.Texture({ context, source: red16x16Image, pixelFormat: import__26.PixelFormat.RGBA, sampler: new import__26.Sampler({ minificationFilter: import__26.TextureMinificationFilter.NEAREST_MIPMAP_LINEAR }) }); texture.generateMipmap(); expect(texture.sizeInBytes).toEqualEpsilon( (16 * 16 + 8 * 8 + 4 * 4 + 2 * 2 + 1) * 4, 1 ); expect({ context, fragmentShader: fs, uniformMap }).contextToRender([255, 0, 0, 255]); }); it("can set a sampler property", function() { texture = new import__26.Texture({ context, source: blueImage, pixelFormat: import__26.PixelFormat.RGBA }); const sampler = new import__26.Sampler({ wrapS: import__26.TextureWrap.REPEAT, wrapT: import__26.TextureWrap.MIRRORED_REPEAT, minificationFilter: import__26.TextureMinificationFilter.NEAREST, magnificationFilter: import__26.TextureMagnificationFilter.NEAREST, maximumAnisotropy: 2 }); texture.sampler = sampler; const s = texture.sampler; expect(s.wrapS).toEqual(sampler.wrapS); expect(s.wrapT).toEqual(sampler.wrapT); expect(s.minificationFilter).toEqual(sampler.minificationFilter); expect(s.magnificationFilter).toEqual(sampler.magnificationFilter); expect(s.maximumAnisotropy).toEqual(2); }); it("can set sampler at construction", function() { texture = new import__26.Texture({ context, source: blueImage, pixelFormat: import__26.PixelFormat.RGBA, sampler: new import__26.Sampler({ wrapS: import__26.TextureWrap.REPEAT, wrapT: import__26.TextureWrap.MIRRORED_REPEAT, minificationFilter: import__26.TextureMinificationFilter.NEAREST, magnificationFilter: import__26.TextureMagnificationFilter.NEAREST, maximumAnisotropy: 2 }) }); const s = texture.sampler; expect(s.wrapS).toEqual(import__26.TextureWrap.REPEAT); expect(s.wrapT).toEqual(import__26.TextureWrap.MIRRORED_REPEAT); expect(s.minificationFilter).toEqual(import__26.TextureMinificationFilter.NEAREST); expect(s.magnificationFilter).toEqual(import__26.TextureMagnificationFilter.NEAREST); expect(s.maximumAnisotropy).toEqual(2); }); it("can get width and height", function() { texture = new import__26.Texture({ context, source: blueOverRedImage, pixelFormat: import__26.PixelFormat.RGBA }); expect(texture.width).toEqual(1); expect(texture.height).toEqual(2); }); it("can get whether Y is flipped", function() { texture = new import__26.Texture({ context, source: blueOverRedImage, pixelFormat: import__26.PixelFormat.RGBA, flipY: true }); expect(texture.flipY).toEqual(true); }); it("can get the dimensions of a texture", function() { texture = new import__26.Texture({ context, width: 64, height: 16 }); expect(texture.dimensions).toEqual(new import__26.Cartesian2(64, 16)); }); function expectTextureByteSize(width, height, pixelFormat, pixelDatatype, expectedSize) { texture = new import__26.Texture({ context, width, height, pixelFormat, pixelDatatype }); expect(texture.sizeInBytes).toBe(expectedSize); texture = texture && texture.destroy(); } it("can get the size in bytes of a texture", function() { if (context.depthTexture) { expectTextureByteSize( 16, 16, import__26.PixelFormat.DEPTH_COMPONENT, import__26.PixelDatatype.UNSIGNED_SHORT, 256 * 2 ); expectTextureByteSize( 16, 16, import__26.PixelFormat.DEPTH_COMPONENT, import__26.PixelDatatype.UNSIGNED_INT, 256 * 4 ); expectTextureByteSize( 16, 16, import__26.PixelFormat.DEPTH_STENCIL, import__26.PixelDatatype.UNSIGNED_INT_24_8, 256 * 4 ); } expectTextureByteSize( 16, 16, import__26.PixelFormat.ALPHA, import__26.PixelDatatype.UNSIGNED_BYTE, 256 ); expectTextureByteSize( 16, 16, import__26.PixelFormat.RGB, import__26.PixelDatatype.UNSIGNED_BYTE, 256 * 3 ); expectTextureByteSize( 16, 16, import__26.PixelFormat.RGBA, import__26.PixelDatatype.UNSIGNED_BYTE, 256 * 4 ); expectTextureByteSize( 16, 16, import__26.PixelFormat.LUMINANCE, import__26.PixelDatatype.UNSIGNED_BYTE, 256 ); expectTextureByteSize( 16, 16, import__26.PixelFormat.LUMINANCE_ALPHA, import__26.PixelDatatype.UNSIGNED_BYTE, 256 * 2 ); }); it("can be destroyed", function() { const t = new import__26.Texture({ context, source: blueImage, pixelFormat: import__26.PixelFormat.RGBA }); expect(t.isDestroyed()).toEqual(false); t.destroy(); expect(t.isDestroyed()).toEqual(true); }); it("throws when creating a texture without a options", function() { expect(function() { texture = new import__26.Texture(); }).toThrowDeveloperError(); }); it("throws when creating a texture without a source", function() { expect(function() { texture = new import__26.Texture({ context }); }).toThrowDeveloperError(); }); it("throws when creating a texture with width and no height", function() { expect(function() { texture = new import__26.Texture({ context, width: 16 }); }).toThrowDeveloperError(); }); it("throws when creating a texture with height and no width", function() { expect(function() { texture = new import__26.Texture({ context, height: 16 }); }).toThrowDeveloperError(); }); it("throws when creating a texture with zero width", function() { expect(function() { texture = new import__26.Texture({ context, width: 0, height: 16 }); }).toThrowDeveloperError(); }); it("throws when creating a texture with width larger than the maximum texture size", function() { expect(function() { texture = new import__26.Texture({ context, width: import__26.ContextLimits.maximumTextureSize + 1, height: 16 }); }).toThrowDeveloperError(); }); it("throws when creating a texture with zero height", function() { expect(function() { texture = new import__26.Texture({ context, width: 16, height: 0 }); }).toThrowDeveloperError(); }); it("throws when creating a texture with height larger than the maximum texture size", function() { expect(function() { texture = new import__26.Texture({ context, width: 16, height: import__26.ContextLimits.maximumTextureSize + 1 }); }).toThrowDeveloperError(); }); it("throws when creating a texture with an invalid pixel format", function() { expect(function() { texture = new import__26.Texture({ context, source: blueImage, pixelFormat: "invalid PixelFormat" }); }).toThrowDeveloperError(); }); it("throws when creating a texture with an invalid pixel datatype", function() { expect(function() { texture = new import__26.Texture({ context, source: blueImage, pixelFormat: import__26.PixelFormat.RGBA, pixelDatatype: "invalid pixelDatatype" }); }).toThrowDeveloperError(); }); it("throws when creating if pixelFormat is DEPTH_COMPONENT and pixelDatatype is not UNSIGNED_SHORT or UNSIGNED_INT", function() { expect(function() { texture = new import__26.Texture({ context, pixelFormat: import__26.PixelFormat.DEPTH_COMPONENT, pixelDatatype: import__26.PixelDatatype.UNSIGNED_BYTE }); }).toThrowDeveloperError(); }); it("throws when creating if pixelFormat is DEPTH_STENCIL and pixelDatatype is not UNSIGNED_INT_24_8", function() { expect(function() { texture = new import__26.Texture({ context, pixelFormat: import__26.PixelFormat.DEPTH_STENCIL, pixelDatatype: import__26.PixelDatatype.UNSIGNED_BYTE }); }).toThrowDeveloperError(); }); it("throws when creating if pixelFormat is DEPTH_COMPONENT or DEPTH_STENCIL, and source is provided", function() { expect(function() { texture = new import__26.Texture({ context, source: blueImage, pixelFormat: import__26.PixelFormat.DEPTH_COMPONENT, pixelDatatype: import__26.PixelDatatype.UNSIGNED_SHORT }); }).toThrowDeveloperError(); }); it("throws when creating if pixelFormat is DEPTH_COMPONENT or DEPTH_STENCIL, and WEBGL_depth_texture is not supported", function() { if (!context.depthTexture) { expect(function() { texture = new import__26.Texture({ context, width: 1, height: 1, pixelFormat: import__26.PixelFormat.DEPTH_COMPONENT, pixelDatatype: import__26.PixelDatatype.UNSIGNED_SHORT }); }).toThrowDeveloperError(); } }); it("throws when creating if pixelDatatype is FLOAT, and OES_texture_float is not supported", function() { if (!context.floatingPointTexture) { expect(function() { texture = new import__26.Texture({ context, width: 1, height: 1, pixelFormat: import__26.PixelFormat.RGBA, pixelDatatype: import__26.PixelDatatype.FLOAT }); }).toThrowDeveloperError(); } }); it("throws when creating if pixelDatatype = HALF_FLOAT, and OES_texture_half_float is not supported", function() { if (!context.halfFloatingPointTexture) { expect(function() { texture = new import__26.Texture({ context, width: 1, height: 1, pixelFormat: import__26.PixelDatatype.RGBA, pixelDatatype: import__26.PixelDatatype.HALF_FLOAT }); }).toThrowDeveloperError(); } }); it("throws when creating compressed texture and the array buffer source is undefined", function() { expect(function() { texture = new import__26.Texture({ context, width: 4, height: 4, pixelFormat: import__26.PixelFormat.RGBA_DXT3 }); }).toThrowDeveloperError(); }); it("throws when creating from the framebuffer with an invalid pixel format", function() { expect(function() { texture = import__26.Texture.fromFramebuffer({ context, pixelFormat: "invalid PixelFormat" }); }).toThrowDeveloperError(); }); it("throws when creating from the framebuffer if PixelFormat is DEPTH_COMPONENT or DEPTH_STENCIL", function() { expect(function() { texture = import__26.Texture.fromFramebuffer({ context, pixelFormat: import__26.PixelFormat.DEPTH_COMPONENT }); }).toThrowDeveloperError(); }); it("throws when creating from the framebuffer with a negative framebufferXOffset", function() { expect(function() { texture = import__26.Texture.fromFramebuffer({ context, pixelFormat: import__26.PixelFormat.RGB, framebufferXOffset: -1 }); }).toThrowDeveloperError(); }); it("throws when creating from the framebuffer with a negative framebufferYOffset", function() { expect(function() { texture = import__26.Texture.fromFramebuffer({ context, pixelFormat: import__26.PixelFormat.RGB, framebufferXOffset: 0, framebufferYOffset: -1 }); }).toThrowDeveloperError(); }); it("throws when creating from the framebuffer with a width greater than the canvas clientWidth", function() { expect(function() { texture = import__26.Texture.fromFramebuffer({ context, pixelFormat: import__26.PixelFormat.RGB, framebufferXOffset: 0, framebufferYOffset: 0, width: context.canvas.clientWidth + 1 }); }).toThrowDeveloperError(); }); it("throws when creating from the framebuffer with a height greater than the canvas clientHeight", function() { expect(function() { texture = import__26.Texture.fromFramebuffer({ context, pixelFormat: import__26.PixelFormat.RGB, framebufferXOffset: 0, framebufferYOffset: 0, width: 1, height: context.canvas.clientHeight + 1 }); }).toThrowDeveloperError(); }); it("throws when copying to a texture from the framebuffer with a DEPTH_COMPONENT or DEPTH_STENCIL pixel format", function() { if (context.depthTexture) { texture = new import__26.Texture({ context, width: 1, height: 1, pixelFormat: import__26.PixelFormat.DEPTH_COMPONENT, pixelDatatype: import__26.PixelDatatype.UNSIGNED_SHORT }); expect(function() { texture.copyFromFramebuffer(); }).toThrowDeveloperError(); } }); it("throws when copying to a texture from the framebuffer with a compressed pixel format", function() { if (context.supportsBasis) { texture = new import__26.Texture({ context, width: greenBasisKTX2Image.width, height: greenBasisKTX2Image.height, pixelFormat: greenBasisKTX2Image.internalFormat, source: { arrayBufferView: greenBasisKTX2Image.bufferView } }); expect(function() { texture.copyFromFramebuffer(); }).toThrowDeveloperError(); } }); it("throws when copying to a texture from the framebuffer with a FLOAT pixel data type", function() { if (context.floatingPointTexture) { texture = new import__26.Texture({ context, width: 1, height: 1, pixelFormat: import__26.PixelFormat.RGBA, pixelDatatype: import__26.PixelDatatype.FLOAT }); expect(function() { texture.copyFromFramebuffer(); }).toThrowDeveloperError(); } }); it("throws when copying to a texture from the framebuffer with a HALF_FLOAT pixel data type", function() { if (context.halfFloatingPointTexture) { texture = new import__26.Texture({ context, width: 1, height: 1, pixelFormat: import__26.PixelFormat.RGBA, pixelDatatype: import__26.PixelDatatype.HALF_FLOAT }); expect(function() { texture.copyFromFramebuffer(); }).toThrowDeveloperError(); } }); it("throws when copying from the framebuffer with a negative xOffset", function() { texture = new import__26.Texture({ context, source: blueImage }); expect(function() { texture.copyFromFramebuffer(-1); }).toThrowDeveloperError(); }); it("throws when copying from the framebuffer with a negative yOffset", function() { texture = new import__26.Texture({ context, source: blueImage }); expect(function() { texture.copyFromFramebuffer(0, -1); }).toThrowDeveloperError(); }); it("throws when copying from the framebuffer with a negative framebufferXOffset", function() { texture = new import__26.Texture({ context, source: blueImage }); expect(function() { texture.copyFromFramebuffer(0, 0, -1); }).toThrowDeveloperError(); }); it("throws when copying from the framebuffer with a negative framebufferYOffset", function() { texture = new import__26.Texture({ context, source: blueImage }); expect(function() { texture.copyFromFramebuffer(0, 0, 0, -1); }).toThrowDeveloperError(); }); it("throws when copying from the framebuffer with a larger width", function() { texture = new import__26.Texture({ context, source: blueImage }); expect(function() { texture.copyFromFramebuffer(0, 0, 0, 0, texture.width + 1); }).toThrowDeveloperError(); }); it("throws when copying from the framebuffer with a larger height", function() { texture = new import__26.Texture({ context, source: blueImage }); expect(function() { texture.copyFromFramebuffer(0, 0, 0, 0, 0, texture.height + 1); }).toThrowDeveloperError(); }); it("throws when copying to a texture with a DEPTH_COMPONENT or DEPTH_STENCIL pixel format", function() { if (context.depthTexture) { texture = new import__26.Texture({ context, width: 1, height: 1, pixelFormat: import__26.PixelFormat.DEPTH_COMPONENT, pixelDatatype: import__26.PixelDatatype.UNSIGNED_SHORT }); expect(function() { texture.copyFrom({ source: { arrayBufferView: new Uint16Array([0]), width: 1, height: 1 } }); }).toThrowDeveloperError(); } }); it("throws when copyFrom is not given any options", function() { texture = new import__26.Texture({ context, source: blueImage }); expect(function() { texture.copyFrom(); }).toThrowDeveloperError(); }); it("throws when copyFrom is not given a source", function() { texture = new import__26.Texture({ context, source: blueImage }); expect(function() { texture.copyFrom({ xOffset: 0, yOffset: 2 }); }).toThrowDeveloperError(); }); it("throws when copyFrom is given a negative xOffset", function() { texture = new import__26.Texture({ context, source: blueImage }); expect(function() { texture.copyFrom({ source: blueImage, xOffset: -1 }); }).toThrowDeveloperError(); }); it("throws when copyFrom is given a negative yOffset", function() { texture = new import__26.Texture({ context, source: blueImage }); expect(function() { texture.copyFrom({ source: blueImage, xOffset: 0, yOffset: -1 }); }).toThrowDeveloperError(); }); it("throws when copyFrom is given a source with larger width", function() { texture = new import__26.Texture({ context, source: blueImage }); const image = new Image(); image.width = blueImage.width + 1; expect(function() { texture.copyFrom({ source: image }); }).toThrowDeveloperError(); }); it("throws when copyFrom is given a source with larger height", function() { texture = new import__26.Texture({ context, source: blueImage }); const image = new Image(); image.height = blueImage.height + 1; expect(function() { texture.copyFrom({ source: image }); }).toThrowDeveloperError(); }); it("throws when copyFrom is given a source with a compressed pixel format", function() { if (context.supportsBasis) { texture = new import__26.Texture({ context, width: greenBasisKTX2Image.width, height: greenBasisKTX2Image.height, pixelFormat: greenBasisKTX2Image.internalFormat, source: { arrayBufferView: greenBasisKTX2Image.bufferView } }); const image = new Image(); expect(function() { texture.copyFrom({ source: image }); }).toThrowDeveloperError(); } }); it("throws when generating mipmaps with a DEPTH_COMPONENT or DEPTH_STENCIL pixel format", function() { if (context.depthTexture) { texture = new import__26.Texture({ context, width: 1, height: 1, pixelFormat: import__26.PixelFormat.DEPTH_COMPONENT, pixelDatatype: import__26.PixelDatatype.UNSIGNED_SHORT }); expect(function() { texture.generateMipmap(); }).toThrowDeveloperError(); } }); it("throws when generating mipmaps with a compressed pixel format", function() { if (context.supportsBasis) { texture = new import__26.Texture({ context, width: greenBasisKTX2Image.width, height: greenBasisKTX2Image.height, pixelFormat: greenBasisKTX2Image.internalFormat, source: { arrayBufferView: greenBasisKTX2Image.bufferView } }); expect(function() { texture.generateMipmap(); }).toThrowDeveloperError(); } }); describe("WebGL1", function() { let webgl1Context; beforeAll(() => { webgl1Context = createContext_default({ requestWebgl1: true }); }); afterAll(() => { webgl1Context.destroyForSpecs(); }); it("throws when generating mipmaps with a non-power of two width", function() { texture = new import__26.Texture({ context: webgl1Context, width: 3, height: 2 }); expect(function() { texture.generateMipmap(); }).toThrowDeveloperError(); }); it("throws when generating mipmaps with a non-power of two height", function() { texture = new import__26.Texture({ context: webgl1Context, width: 2, height: 3 }); expect(function() { texture.generateMipmap(); }).toThrowDeveloperError(); }); }); it("throws when generating mipmaps with an invalid hint", function() { texture = new import__26.Texture({ context, source: blueImage }); expect(function() { texture.generateMipmap("invalid hint"); }).toThrowDeveloperError(); }); it("throws when destroy is called after destroying", function() { const t = new import__26.Texture({ context, source: blueImage, pixelFormat: import__26.PixelFormat.RGBA }); t.destroy(); expect(function() { t.destroy(); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Renderer/UniformSpec.js var import__27 = __toESM(require_Cesium(), 1); describe( "Renderer/Uniform", function() { let context; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); it("sets float uniform", function() { const uniformMap = { u: function() { return 1; } }; const fs = "uniform float u;void main() { out_FragColor = vec4(u == 1.0); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets vec2 uniform", function() { const uniformMap = { u: function() { return new import__27.Cartesian2(0.25, 0.5); } }; const fs = "uniform vec2 u;void main() { out_FragColor = vec4(u == vec2(0.25, 0.5)); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets vec3 uniform (Cartesian3)", function() { const uniformMap = { u: function() { return new import__27.Cartesian3(0.25, 0.5, 0.75); } }; const fs = "uniform vec3 u;void main() { out_FragColor = vec4(u == vec3(0.25, 0.5, 0.75)); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets vec3 uniform (Color)", function() { const uniformMap = { u: function() { return new import__27.Color(0.25, 0.5, 0.75); } }; const fs = "uniform vec3 u;void main() { out_FragColor = vec4(u == vec3(0.25, 0.5, 0.75)); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets vec4 uniform (Cartesian4)", function() { const uniformMap = { u: function() { return new import__27.Cartesian4(0.25, 0.5, 0.75, 1); } }; const fs = "uniform vec4 u;void main() { out_FragColor = vec4(u == vec4(0.25, 0.5, 0.75, 1.0)); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets vec4 uniform (Color)", function() { const uniformMap = { u: function() { return new import__27.Color(0.25, 0.5, 0.75, 1); } }; const fs = "uniform vec4 u;void main() { out_FragColor = vec4(u == vec4(0.25, 0.5, 0.75, 1.0)); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets int uniform", function() { const uniformMap = { u: function() { return 1; } }; const fs = "uniform int u;void main() { out_FragColor = vec4(u == 1); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets ivec2 uniform", function() { const uniformMap = { u: function() { return new import__27.Cartesian2(1, 2); } }; const fs = "uniform ivec2 u;void main() { out_FragColor = vec4(u == ivec2(1, 2)); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets ivec3 uniform", function() { const uniformMap = { u: function() { return new import__27.Cartesian3(1, 2, 3); } }; const fs = "uniform ivec3 u;void main() { out_FragColor = vec4(u == ivec3(1, 2, 3)); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets ivec4 uniform", function() { const uniformMap = { u: function() { return new import__27.Cartesian4(1, 2, 3, 4); } }; const fs = "uniform ivec4 u;void main() { out_FragColor = vec4(u == ivec4(1, 2, 3, 4)); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets bool uniform", function() { const uniformMap = { u: function() { return true; } }; const fs = "uniform bool u;void main() { out_FragColor = vec4(u); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets bvec2 uniform", function() { const uniformMap = { u: function() { return new import__27.Cartesian2(true, false); } }; const fs = "uniform bvec2 u;void main() { out_FragColor = vec4(u == bvec2(true, false)); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets bvec3 uniform", function() { const uniformMap = { u: function() { return new import__27.Cartesian3(true, false, true); } }; const fs = "uniform bvec3 u;void main() { out_FragColor = vec4(u == bvec3(true, false, true)); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets bvec4 uniform", function() { const uniformMap = { u: function() { return new import__27.Cartesian4(true, false, true, false); } }; const fs = "uniform bvec4 u;void main() { out_FragColor = vec4(u == bvec4(true, false, true, false)); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets mat2 uniform", function() { const uniformMap = { u: function() { return new import__27.Matrix2(1, 2, 3, 4); } }; const fs = "uniform mat2 u;void main() { out_FragColor = vec4( (u[0].x == 1.0) && (u[1].x == 2.0) && (u[0].y == 3.0) && (u[1].y == 4.0) ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets mat3 uniform", function() { const uniformMap = { u: function() { return new import__27.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); } }; const fs = "uniform mat3 u;void main() { out_FragColor = vec4( (u[0].x == 1.0) && (u[1].x == 2.0) && (u[2].x == 3.0) && (u[0].y == 4.0) && (u[1].y == 5.0) && (u[2].y == 6.0) && (u[0].z == 7.0) && (u[1].z == 8.0) && (u[2].z == 9.0) ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets mat4 uniform", function() { const uniformMap = { u: function() { return new import__27.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); } }; const fs = "uniform mat4 u;void main() { out_FragColor = vec4( (u[0].x == 1.0) && (u[1].x == 2.0) && (u[2].x == 3.0) && (u[3].x == 4.0) && (u[0].y == 5.0) && (u[1].y == 6.0) && (u[2].y == 7.0) && (u[3].y == 8.0) && (u[0].z == 9.0) && (u[1].z == 10.0) && (u[2].z == 11.0) && (u[3].z == 12.0) && (u[0].w == 13.0) && (u[1].w == 14.0) && (u[2].w == 15.0) && (u[3].w == 16.0) ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets a struct uniform", function() { const uniformMap = { "u.f": function() { return 2.5; }, "u.v": function() { return new import__27.Cartesian4(0.25, 0.5, 0.75, 1); } }; const fs = "uniform struct { float f; vec4 v; } u;void main() { out_FragColor = vec4((u.f == 2.5)); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets float uniform array", function() { const uniformMap = { u: function() { return new Float32Array([0.25, 0.5]); }, u2: function() { return [1.25, 1.5]; } }; const fs = "uniform float u[2];uniform float u2[2];void main() { out_FragColor = vec4( (u[0] == 0.25) && (u[1] == 0.5) && (u2[0] == 1.25) && (u2[1] == 1.5) ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets vec2 uniform array", function() { const uniformMap = { u: function() { return [new import__27.Cartesian2(0.25, 0.5), new import__27.Cartesian2(1.25, 1.5)]; } }; const fs = "uniform vec2 u[2];void main() { out_FragColor = vec4( (u[0] == vec2(0.25, 0.5)) && (u[1] == vec2(1.25, 1.5)) ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets vec3 uniform array", function() { const uniformMap = { u: function() { return [ new import__27.Cartesian3(0.25, 0.5, 0.75), new import__27.Cartesian3(1.25, 1.5, 1.75) ]; } }; const fs = "uniform vec3 u[2];void main() { out_FragColor = vec4( (u[0] == vec3(0.25, 0.5, 0.75)) && (u[1] == vec3(1.25, 1.5, 1.75)) ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets vec4 uniform array", function() { const uniformMap = { u: function() { return [ new import__27.Cartesian4(0.25, 0.5, 0.75, 1), new import__27.Cartesian4(1.25, 1.5, 1.75, 2) ]; } }; const fs = "uniform vec4 u[2];void main() { out_FragColor = vec4( (u[0] == vec4(0.25, 0.5, 0.75, 1.0)) && (u[1] == vec4(1.25, 1.5, 1.75, 2.0)) ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets int uniform array", function() { const uniformMap = { u: function() { return new Int32Array([1, 2]); }, u2: function() { return [3, 4]; } }; const fs = "uniform int u[2];uniform int u2[2];void main() { out_FragColor = vec4( (u[0] == 1) && (u[1] == 2) && (u2[0] == 3) && (u2[1] == 4) ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets ivec2 uniform array", function() { const uniformMap = { u: function() { return [new import__27.Cartesian2(1, 2), new import__27.Cartesian2(3, 4)]; } }; const fs = "uniform ivec2 u[2];void main() { out_FragColor = vec4( (u[0] == ivec2(1, 2)) && (u[1] == ivec2(3, 4)) ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets ivec3 uniform array", function() { const uniformMap = { u: function() { return [new import__27.Cartesian3(1, 2, 3), new import__27.Cartesian3(4, 5, 6)]; } }; const fs = "uniform ivec3 u[2];void main() { out_FragColor = vec4( (u[0] == ivec3(1, 2, 3)) && (u[1] == ivec3(4, 5, 6)) ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets ivec4 uniform array", function() { const uniformMap = { u: function() { return [new import__27.Cartesian4(1, 2, 3, 4), new import__27.Cartesian4(5, 6, 7, 8)]; } }; const fs = "uniform ivec4 u[2];void main() { out_FragColor = vec4( (u[0] == ivec4(1, 2, 3, 4)) && (u[1] == ivec4(5, 6, 7, 8)) ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets bool uniform array", function() { const uniformMap = { u: function() { return new Int32Array([1, 0]); }, u2: function() { return [0, 1]; } }; const fs = "uniform bool u[2];uniform bool u2[2];void main() { out_FragColor = vec4( u[0] && !u[1] && !u2[0] && u2[1] ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets bvec2 uniform array", function() { const uniformMap = { u: function() { return [new import__27.Cartesian2(true, false), new import__27.Cartesian2(false, true)]; } }; const fs = "uniform bvec2 u[2];void main() { out_FragColor = vec4( (u[0] == bvec2(true, false)) && (u[1] == bvec2(false, true)) ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets bvec3 uniform array", function() { const uniformMap = { u: function() { return [ new import__27.Cartesian3(true, false, true), new import__27.Cartesian3(false, true, false) ]; } }; const fs = "uniform bvec3 u[2];void main() { out_FragColor = vec4( (u[0] == bvec3(true, false, true)) && (u[1] == bvec3(false, true, false)) ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets bvec4 uniform array", function() { const uniformMap = { u: function() { return [ new import__27.Cartesian4(true, false, true, false), new import__27.Cartesian4(false, true, false, true) ]; } }; const fs = "uniform bvec4 u[2];void main() { out_FragColor = vec4( (u[0] == bvec4(true, false, true, false)) && (u[1] == bvec4(false, true, false, true)) ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets mat2 uniform array", function() { const uniformMap = { u: function() { return [ new import__27.Matrix2(1, 2, 3, 4), new import__27.Matrix2(5, 6, 7, 8) ]; } }; const fs = "uniform mat2 u[2];void main() { out_FragColor = vec4( ((u[0])[0].x == 1.0) && ((u[0])[1].x == 2.0) && ((u[0])[0].y == 3.0) && ((u[0])[1].y == 4.0) && ((u[1])[0].x == 5.0) && ((u[1])[1].x == 6.0) && ((u[1])[0].y == 7.0) && ((u[1])[1].y == 8.0) ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets mat3 uniform array", function() { const uniformMap = { u: function() { return [ new import__27.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9), new import__27.Matrix3(11, 12, 13, 14, 15, 16, 17, 18, 19) ]; } }; const fs = "uniform mat3 u[2];void main() { out_FragColor = vec4( ((u[0])[0].x == 1.0) && ((u[0])[1].x == 2.0) && ((u[0])[2].x == 3.0) && ((u[0])[0].y == 4.0) && ((u[0])[1].y == 5.0) && ((u[0])[2].y == 6.0) && ((u[0])[0].z == 7.0) && ((u[0])[1].z == 8.0) && ((u[0])[2].z == 9.0) && ((u[1])[0].x == 11.0) && ((u[1])[1].x == 12.0) && ((u[1])[2].x == 13.0) && ((u[1])[0].y == 14.0) && ((u[1])[1].y == 15.0) && ((u[1])[2].y == 16.0) && ((u[1])[0].z == 17.0) && ((u[1])[1].z == 18.0) && ((u[1])[2].z == 19.0) ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); it("sets mat4 uniform array", function() { const uniformMap = { u: function() { return [ new import__27.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ), new import__27.Matrix4( 11, 12, 13, 14, 15, 16, 17, 18, 19, 110, 111, 112, 113, 114, 115, 116 ) ]; } }; const fs = "uniform mat4 u[2];void main() { out_FragColor = vec4( ((u[0])[0].x == 1.0) && ((u[0])[1].x == 2.0) && ((u[0])[2].x == 3.0) && ((u[0])[3].x == 4.0) && ((u[0])[0].y == 5.0) && ((u[0])[1].y == 6.0) && ((u[0])[2].y == 7.0) && ((u[0])[3].y == 8.0) && ((u[0])[0].z == 9.0) && ((u[0])[1].z == 10.0) && ((u[0])[2].z == 11.0) && ((u[0])[3].z == 12.0) && ((u[0])[0].w == 13.0) && ((u[0])[1].w == 14.0) && ((u[0])[2].w == 15.0) && ((u[0])[3].w == 16.0) && ((u[1])[0].x == 11.0) && ((u[1])[1].x == 12.0) && ((u[1])[2].x == 13.0) && ((u[1])[3].x == 14.0) && ((u[1])[0].y == 15.0) && ((u[1])[1].y == 16.0) && ((u[1])[2].y == 17.0) && ((u[1])[3].y == 18.0) && ((u[1])[0].z == 19.0) && ((u[1])[1].z == 110.0) && ((u[1])[2].z == 111.0) && ((u[1])[3].z == 112.0) && ((u[1])[0].w == 113.0) && ((u[1])[1].w == 114.0) && ((u[1])[2].w == 115.0) && ((u[1])[3].w == 116.0) ); }"; expect({ context, fragmentShader: fs, uniformMap }).contextToRender(); }); }, "WebGL" ); // packages/engine/Specs/Renderer/VertexArrayFacadeSpec.js var import__28 = __toESM(require_Cesium(), 1); describe( "Renderer/VertexArrayFacade", function() { let context; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); it("creates a vertex array with static floats", function() { const positionIndex = 0; const vaf = new import__28.VertexArrayFacade( context, [ { index: positionIndex, componentsPerAttribute: 3, componentDatatype: import__28.ComponentDatatype.FLOAT, usage: import__28.BufferUsage.STATIC_DRAW } ], 1 ); const writer = vaf.writers[positionIndex]; expect(writer).toBeDefined(); writer(0, 1, 2, 3); vaf.commit(); expect(vaf.va[0].va.getAttribute(0).vertexBuffer).toBeDefined(); expect(vaf.va[0].va.getAttribute(0).vertexBuffer.sizeInBytes).toEqual( 1 * 3 * 4 ); expect(vaf.va[0].va.getAttribute(0).vertexBuffer.usage).toEqual( import__28.BufferUsage.STATIC_DRAW ); expect(vaf.va[0].va.getAttribute(0).componentsPerAttribute).toEqual(3); expect(vaf.va[0].va.getAttribute(0).componentDatatype).toEqual( import__28.ComponentDatatype.FLOAT ); expect(vaf.va[0].va.getAttribute(0).offsetInBytes).toEqual(0); expect(vaf.va[0].va.getAttribute(0).strideInBytes).toEqual(3 * 4); }); it("resizes a vertex array with static floats", function() { const positionIndex = 0; const vaf = new import__28.VertexArrayFacade( context, [ { index: positionIndex, componentsPerAttribute: 3, componentDatatype: import__28.ComponentDatatype.FLOAT, usage: import__28.BufferUsage.STATIC_DRAW } ], 1 ); const writer = vaf.writers[positionIndex]; expect(writer).toBeDefined(); writer(0, 1, 2, 3); vaf.resize(2); writer(1, 1, 2, 3); vaf.commit(); expect(vaf.va[0].va.getAttribute(0).vertexBuffer).toBeDefined(); expect(vaf.va[0].va.getAttribute(0).vertexBuffer.sizeInBytes).toEqual( 2 * 3 * 4 ); expect(vaf.va[0].va.getAttribute(0).vertexBuffer.usage).toEqual( import__28.BufferUsage.STATIC_DRAW ); expect(vaf.va[0].va.getAttribute(0).componentsPerAttribute).toEqual(3); expect(vaf.va[0].va.getAttribute(0).componentDatatype).toEqual( import__28.ComponentDatatype.FLOAT ); expect(vaf.va[0].va.getAttribute(0).offsetInBytes).toEqual(0); expect(vaf.va[0].va.getAttribute(0).strideInBytes).toEqual(3 * 4); }); it("creates a vertex array with static floats and unsigned bytes", function() { const positionIndex = 0; const colorIndex = 2; const vaf = new import__28.VertexArrayFacade( context, [ { index: positionIndex, componentsPerAttribute: 3, componentDatatype: import__28.ComponentDatatype.FLOAT, usage: import__28.BufferUsage.STATIC_DRAW }, { index: colorIndex, componentsPerAttribute: 4, componentDatatype: import__28.ComponentDatatype.UNSIGNED_BYTE, usage: import__28.BufferUsage.STATIC_DRAW } ], 1 ); const positionWriter = vaf.writers[positionIndex]; const colorWriter = vaf.writers[colorIndex]; expect(positionWriter).toBeDefined(); expect(colorWriter).toBeDefined(); positionWriter(0, 1, 2, 3); colorWriter(0, 0, 255, 0, 255); vaf.commit(); expect(vaf.va[0].va.getAttribute(0).vertexBuffer).toBeDefined(); expect(vaf.va[0].va.getAttribute(0).vertexBuffer.sizeInBytes).toEqual( 1 * (3 * 4 + 4 * 1) ); expect(vaf.va[0].va.getAttribute(0).vertexBuffer.usage).toEqual( import__28.BufferUsage.STATIC_DRAW ); expect(vaf.va[0].va.getAttribute(0).componentsPerAttribute).toEqual(3); expect(vaf.va[0].va.getAttribute(0).componentDatatype).toEqual( import__28.ComponentDatatype.FLOAT ); expect(vaf.va[0].va.getAttribute(0).offsetInBytes).toEqual(0); expect(vaf.va[0].va.getAttribute(0).strideInBytes).toEqual(3 * 4 + 4 * 1); expect(vaf.va[0].va.getAttribute(1).vertexBuffer).toEqual( vaf.va[0].va.getAttribute(0).vertexBuffer ); expect(vaf.va[0].va.getAttribute(1).componentsPerAttribute).toEqual(4); expect(vaf.va[0].va.getAttribute(1).componentDatatype).toEqual( import__28.ComponentDatatype.UNSIGNED_BYTE ); expect(vaf.va[0].va.getAttribute(1).offsetInBytes).toEqual(3 * 4); expect(vaf.va[0].va.getAttribute(1).strideInBytes).toEqual( vaf.va[0].va.getAttribute(0).strideInBytes ); }); it("creates a vertex array with static and dynamic attributes", function() { const positionIndex = 0; const txCoordIndex = 2; const vaf = new import__28.VertexArrayFacade( context, [ { index: positionIndex, componentsPerAttribute: 3, componentDatatype: import__28.ComponentDatatype.FLOAT, usage: import__28.BufferUsage.STATIC_DRAW }, { index: txCoordIndex, componentsPerAttribute: 2, componentDatatype: import__28.ComponentDatatype.UNSIGNED_SHORT, usage: import__28.BufferUsage.DYNAMIC_DRAW, normalize: true } ], 1 ); const positionWriter = vaf.writers[positionIndex]; const txCoordWriter = vaf.writers[txCoordIndex]; expect(positionWriter).toBeDefined(); expect(txCoordWriter).toBeDefined(); positionWriter(0, 1, 2, 3); txCoordWriter(0, 32 * 1024, 64 * 1024); vaf.commit(); expect(vaf.va[0].va.getAttribute(0).vertexBuffer).toBeDefined(); expect(vaf.va[0].va.getAttribute(0).vertexBuffer.sizeInBytes).toEqual( 1 * (3 * 4) ); expect(vaf.va[0].va.getAttribute(0).vertexBuffer.usage).toEqual( import__28.BufferUsage.STATIC_DRAW ); expect(vaf.va[0].va.getAttribute(0).componentsPerAttribute).toEqual(3); expect(vaf.va[0].va.getAttribute(0).componentDatatype).toEqual( import__28.ComponentDatatype.FLOAT ); expect(vaf.va[0].va.getAttribute(0).offsetInBytes).toEqual(0); expect(vaf.va[0].va.getAttribute(0).strideInBytes).toEqual(3 * 4); expect(vaf.va[0].va.getAttribute(1).vertexBuffer).toBeDefined(); expect(vaf.va[0].va.getAttribute(1).vertexBuffer.sizeInBytes).toEqual( 1 * (2 * 2) ); expect(vaf.va[0].va.getAttribute(1).vertexBuffer.usage).toEqual( import__28.BufferUsage.DYNAMIC_DRAW ); expect(vaf.va[0].va.getAttribute(1).componentsPerAttribute).toEqual(2); expect(vaf.va[0].va.getAttribute(1).componentDatatype).toEqual( import__28.ComponentDatatype.UNSIGNED_SHORT ); expect(vaf.va[0].va.getAttribute(1).offsetInBytes).toEqual(0); expect(vaf.va[0].va.getAttribute(1).strideInBytes).toEqual(2 * 2); }); it("sub-commits", function() { const positionIndex = 0; const temperatureIndex = 2; const vaf = new import__28.VertexArrayFacade( context, [ { index: positionIndex, componentsPerAttribute: 3, componentDatatype: import__28.ComponentDatatype.FLOAT, usage: import__28.BufferUsage.STATIC_DRAW }, { index: temperatureIndex, componentsPerAttribute: 1, componentDatatype: import__28.ComponentDatatype.FLOAT, usage: import__28.BufferUsage.STREAM_DRAW } ], 2 ); const positionWriter = vaf.writers[positionIndex]; const temperatureWriter = vaf.writers[temperatureIndex]; expect(positionWriter).toBeDefined(); expect(temperatureWriter).toBeDefined(); positionWriter(0, 1, 2, 3); temperatureWriter(0, 98.6); positionWriter(1, 7, 8, 9); temperatureWriter(1, 32); vaf.commit(); positionWriter(0, 10, 20, 30); temperatureWriter(0, 37); positionWriter(1, 70, 80, 90); temperatureWriter(1, 0); vaf.commit(); temperatureWriter(1, 212); vaf.subCommit(1, 1); vaf.endSubCommits(); expect(vaf.va[0].va.getAttribute(1).vertexBuffer).toBeDefined(); expect(vaf.va[0].va.getAttribute(1).vertexBuffer.sizeInBytes).toEqual( 2 * (3 * 4) ); expect(vaf.va[0].va.getAttribute(1).vertexBuffer.usage).toEqual( import__28.BufferUsage.STATIC_DRAW ); expect(vaf.va[0].va.getAttribute(1).componentsPerAttribute).toEqual(3); expect(vaf.va[0].va.getAttribute(1).componentDatatype).toEqual( import__28.ComponentDatatype.FLOAT ); expect(vaf.va[0].va.getAttribute(1).offsetInBytes).toEqual(0); expect(vaf.va[0].va.getAttribute(1).strideInBytes).toEqual(3 * 4); expect(vaf.va[0].va.getAttribute(0).vertexBuffer).toBeDefined(); expect(vaf.va[0].va.getAttribute(0).vertexBuffer.sizeInBytes).toEqual( 2 * 4 ); expect(vaf.va[0].va.getAttribute(0).vertexBuffer.usage).toEqual( import__28.BufferUsage.STREAM_DRAW ); expect(vaf.va[0].va.getAttribute(0).componentsPerAttribute).toEqual(1); expect(vaf.va[0].va.getAttribute(0).componentDatatype).toEqual( import__28.ComponentDatatype.FLOAT ); expect(vaf.va[0].va.getAttribute(0).offsetInBytes).toEqual(0); expect(vaf.va[0].va.getAttribute(0).strideInBytes).toEqual(1 * 4); }); it("destroys previous vertex buffers when number of vertices grows", function() { const positionIndex = 0; const vaf = new import__28.VertexArrayFacade( context, [ { index: positionIndex, componentsPerAttribute: 3, componentDatatype: import__28.ComponentDatatype.FLOAT, usage: import__28.BufferUsage.STATIC_DRAW } ], 1 ); const writer = vaf.writers[positionIndex]; expect(writer).toBeDefined(); writer(0, 1, 2, 3); vaf.commit(); const vbBeforeResize = vaf.va[0].va.getAttribute(0).vertexBuffer; vaf.resize(2); writer(1, 1, 2, 3); vaf.commit(); expect(vbBeforeResize.isDestroyed()).toBe(true); expect(vaf.va[0].va.getAttribute(0).vertexBuffer).not.toBe( vbBeforeResize ); }); it("is not initially destroyed", function() { const positionIndex = 0; const vaf = new import__28.VertexArrayFacade( context, [ { index: positionIndex, componentsPerAttribute: 3, componentDatatype: import__28.ComponentDatatype.FLOAT, usage: import__28.BufferUsage.STATIC_DRAW } ], 1 ); expect(vaf.isDestroyed()).toBe(false); }); it("throws when constructed without a context", function() { expect(function() { return new import__28.VertexArrayFacade(void 0, void 0, void 0); }).toThrowDeveloperError(); }); it("throws when constructed undefined attributes", function() { expect(function() { return new import__28.VertexArrayFacade(context, void 0, void 0); }).toThrowDeveloperError(); }); it("throws when constructed without attributes", function() { expect(function() { return new import__28.VertexArrayFacade(context, []); }).toThrowDeveloperError(); }); it("throws when constructed with attributes without componentsPerAttribute", function() { expect(function() { return new import__28.VertexArrayFacade(context, [{}]); }).toThrowDeveloperError(); }); it("throws when constructed with attributes with an invalid componentDatatype", function() { expect(function() { return new import__28.VertexArrayFacade(context, [ { componentsPerAttribute: 1, componentDatatype: "invalid component datatype" } ]); }).toThrowDeveloperError(); }); it("throws when constructed with attributes with an invalid usage", function() { expect(function() { return new import__28.VertexArrayFacade(context, [ { componentsPerAttribute: 1, usage: "invalid component usage" } ]); }).toThrowDeveloperError(); }); it("throws when constructed with attributes with duplicate indices", function() { expect(function() { return new import__28.VertexArrayFacade(context, [ { index: 0, componentsPerAttribute: 1 }, { index: 0, componentsPerAttribute: 1 } ]); }).toThrowDeveloperError(); }); it("subCommit throws when passed an invalid offsetInVertices", function() { const positionIndex = 0; const vaf = new import__28.VertexArrayFacade( context, [ { index: positionIndex, componentsPerAttribute: 3, componentDatatype: import__28.ComponentDatatype.FLOAT, usage: import__28.BufferUsage.STATIC_DRAW } ], 10 ); expect(function() { vaf.subCommit(-1, 1); }).toThrowDeveloperError(); expect(function() { vaf.subCommit(10, 1); }).toThrowDeveloperError(); expect(function() { vaf.subCommit(1, 10); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Renderer/VertexArrayFactorySpec.js var import__29 = __toESM(require_Cesium(), 1); describe( "Renderer/VertexArrayFactory", function() { let context; let va; let sp; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); afterEach(function() { va = va && va.destroy(); sp = sp && sp.destroy(); }); it("throws when there is no context", function() { expect(function() { return import__29.VertexArray.fromGeometry(); }).toThrowDeveloperError(); }); it("creates with no optional arguments", function() { va = import__29.VertexArray.fromGeometry({ context }); expect(va.numberOfAttributes).toEqual(0); expect(va.indexBuffer).not.toBeDefined(); }); it("creates with no geometry", function() { va = import__29.VertexArray.fromGeometry({ context, interleave: true }); expect(va.numberOfAttributes).toEqual(0); expect(va.indexBuffer).not.toBeDefined(); }); it("creates a single-attribute vertex (non-interleaved)", function() { const geometry = new import__29.Geometry({ attributes: { position: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0, 1, 1, 1] }) }, primitiveType: import__29.PrimitiveType.POINTS }); const va2 = import__29.VertexArray.fromGeometry({ context, geometry, attributeLocations: import__29.GeometryPipeline.createAttributeLocations(geometry) }); expect(va2.numberOfAttributes).toEqual(1); expect(va2.indexBuffer).not.toBeDefined(); const position = geometry.attributes.position; expect(va2.getAttribute(0).index).toEqual(0); expect(va2.getAttribute(0).componentDatatype).toEqual( position.componentDatatype ); expect(va2.getAttribute(0).componentsPerAttribute).toEqual( position.componentsPerAttribute ); expect(va2.getAttribute(0).offsetInBytes).toEqual(0); expect(va2.getAttribute(0).strideInBytes).toEqual(0); expect(va2.getAttribute(0).vertexBuffer.usage).toEqual( import__29.BufferUsage.DYNAMIC_DRAW ); }); it("creates a single-attribute vertex (interleaved)", function() { const geometry = new import__29.Geometry({ attributes: { position: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0, 1, 1, 1] }) }, primitiveType: import__29.PrimitiveType.POINTS }); const va2 = import__29.VertexArray.fromGeometry({ context, geometry, attributeLocations: import__29.GeometryPipeline.createAttributeLocations(geometry), interleave: true, bufferUsage: import__29.BufferUsage.STATIC_DRAW }); expect(va2.numberOfAttributes).toEqual(1); expect(va2.indexBuffer).not.toBeDefined(); const position = geometry.attributes.position; expect(va2.getAttribute(0).index).toEqual(0); expect(va2.getAttribute(0).componentDatatype).toEqual( position.componentDatatype ); expect(va2.getAttribute(0).componentsPerAttribute).toEqual( position.componentsPerAttribute ); expect(va2.getAttribute(0).offsetInBytes).toEqual(0); expect(va2.getAttribute(0).strideInBytes).toEqual( import__29.ComponentDatatype.getSizeInBytes(position.componentDatatype) * position.componentsPerAttribute ); expect(va2.getAttribute(0).vertexBuffer.usage).toEqual( import__29.BufferUsage.STATIC_DRAW ); }); it("creates a homogeneous multiple-attribute vertex (non-interleaved)", function() { const geometry = new import__29.Geometry({ attributes: { customPosition: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0, 2, 2, 2] }), customNormal: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [1, 1, 1, 3, 3, 3] }) }, primitiveType: import__29.PrimitiveType.POINTS }); const va2 = import__29.VertexArray.fromGeometry({ context, geometry, attributeLocations: import__29.GeometryPipeline.createAttributeLocations(geometry) }); expect(va2.numberOfAttributes).toEqual(2); expect(va2.indexBuffer).not.toBeDefined(); const position = geometry.attributes.customPosition; expect(va2.getAttribute(0).index).toEqual(0); expect(va2.getAttribute(0).componentDatatype).toEqual( position.componentDatatype ); expect(va2.getAttribute(0).componentsPerAttribute).toEqual( position.componentsPerAttribute ); expect(va2.getAttribute(0).offsetInBytes).toEqual(0); expect(va2.getAttribute(0).strideInBytes).toEqual(0); const normal = geometry.attributes.customNormal; expect(va2.getAttribute(1).index).toEqual(1); expect(va2.getAttribute(1).componentDatatype).toEqual( normal.componentDatatype ); expect(va2.getAttribute(1).componentsPerAttribute).toEqual( normal.componentsPerAttribute ); expect(va2.getAttribute(1).offsetInBytes).toEqual(0); expect(va2.getAttribute(1).strideInBytes).toEqual(0); expect(va2.getAttribute(0).vertexBuffer).not.toBe( va2.getAttribute(1).vertexBuffer ); }); it("creates a homogeneous multiple-attribute vertex (interleaved)", function() { const geometry = new import__29.Geometry({ attributes: { customPosition: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0, 2, 2, 2] }), customNormal: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [1, 1, 1, 3, 3, 3] }) }, primitiveType: import__29.PrimitiveType.POINTS }); const va2 = import__29.VertexArray.fromGeometry({ context, geometry, attributeLocations: import__29.GeometryPipeline.createAttributeLocations(geometry), interleave: true }); expect(va2.numberOfAttributes).toEqual(2); expect(va2.indexBuffer).not.toBeDefined(); const position = geometry.attributes.customPosition; const normal = geometry.attributes.customNormal; const expectedStride = import__29.ComponentDatatype.getSizeInBytes(position.componentDatatype) * position.componentsPerAttribute + import__29.ComponentDatatype.getSizeInBytes(normal.componentDatatype) * normal.componentsPerAttribute; expect(va2.getAttribute(0).index).toEqual(0); expect(va2.getAttribute(0).componentDatatype).toEqual( position.componentDatatype ); expect(va2.getAttribute(0).componentsPerAttribute).toEqual( position.componentsPerAttribute ); expect(va2.getAttribute(0).offsetInBytes).toEqual(0); expect(va2.getAttribute(0).strideInBytes).toEqual(expectedStride); expect(va2.getAttribute(1).index).toEqual(1); expect(va2.getAttribute(1).componentDatatype).toEqual( normal.componentDatatype ); expect(va2.getAttribute(1).componentsPerAttribute).toEqual( normal.componentsPerAttribute ); expect(va2.getAttribute(1).offsetInBytes).toEqual( import__29.ComponentDatatype.getSizeInBytes(position.componentDatatype) * position.componentsPerAttribute ); expect(va2.getAttribute(1).strideInBytes).toEqual(expectedStride); expect(va2.getAttribute(0).vertexBuffer).toBe( va2.getAttribute(1).vertexBuffer ); }); it("creates a heterogeneous multiple-attribute vertex (interleaved)", function() { const geometry = new import__29.Geometry({ attributes: { position: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0, 2, 2, 2] }), colors: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 4, values: [1, 1, 1, 1, 2, 2, 2, 2] }) }, primitiveType: import__29.PrimitiveType.POINTS }); const va2 = import__29.VertexArray.fromGeometry({ context, geometry, attributeLocations: import__29.GeometryPipeline.createAttributeLocations(geometry), interleave: true }); expect(va2.numberOfAttributes).toEqual(2); expect(va2.indexBuffer).not.toBeDefined(); const position = geometry.attributes.position; const colors = geometry.attributes.colors; const expectedStride = import__29.ComponentDatatype.getSizeInBytes(position.componentDatatype) * position.componentsPerAttribute + import__29.ComponentDatatype.getSizeInBytes(colors.componentDatatype) * colors.componentsPerAttribute; expect(va2.getAttribute(0).index).toEqual(0); expect(va2.getAttribute(0).componentDatatype).toEqual( position.componentDatatype ); expect(va2.getAttribute(0).componentsPerAttribute).toEqual( position.componentsPerAttribute ); expect(va2.getAttribute(0).offsetInBytes).toEqual(0); expect(va2.getAttribute(0).strideInBytes).toEqual(expectedStride); expect(va2.getAttribute(1).index).toEqual(1); expect(va2.getAttribute(1).componentDatatype).toEqual( colors.componentDatatype ); expect(va2.getAttribute(1).componentsPerAttribute).toEqual( colors.componentsPerAttribute ); expect(va2.getAttribute(1).offsetInBytes).toEqual( import__29.ComponentDatatype.getSizeInBytes(position.componentDatatype) * position.componentsPerAttribute ); expect(va2.getAttribute(1).strideInBytes).toEqual(expectedStride); expect(va2.getAttribute(0).vertexBuffer).toBe( va2.getAttribute(1).vertexBuffer ); }); it("sorts interleaved attributes from large to small components", function() { const geometry = new import__29.Geometry({ attributes: { bytes: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.BYTE, componentsPerAttribute: 1, values: [0] }), shorts: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.SHORT, componentsPerAttribute: 1, values: [1] }), floats: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.FLOAT, componentsPerAttribute: 1, values: [2] }) }, primitiveType: import__29.PrimitiveType.POINTS }); const attributeLocations = import__29.GeometryPipeline.createAttributeLocations( geometry ); const va2 = import__29.VertexArray.fromGeometry({ context, geometry, attributeLocations, interleave: true }); expect(va2.numberOfAttributes).toEqual(3); const vertexBuffer = va2.getAttribute(0).vertexBuffer; expect(vertexBuffer).toBe(va2.getAttribute(1).vertexBuffer); expect(vertexBuffer).toBe(va2.getAttribute(2).vertexBuffer); expect(vertexBuffer.sizeInBytes).toEqual(8); const vs = "in float bytes; in float shorts; in float floats; out vec4 fsColor; void main() { gl_PointSize = 1.0; gl_Position = vec4(0.0, 0.0, 0.0, 1.0); fsColor = vec4((bytes == 0.0) && (shorts == 1.0) && (floats == 2.0)); }"; const fs = "in vec4 fsColor; void main() { out_FragColor = fsColor; }"; sp = import__29.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations }); import__29.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); const command = new import__29.DrawCommand({ primitiveType: import__29.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va2 }); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); }); it("sorts interleaved attributes from large to small components (2)", function() { const geometry = new import__29.Geometry({ attributes: { color: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 4, normalize: true, values: [255, 0, 0, 255, 0, 255, 0, 255] }), position: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0, 0, 0, 0] }) }, primitiveType: import__29.PrimitiveType.POINTS }); const attributeLocations = import__29.GeometryPipeline.createAttributeLocations( geometry ); const va2 = import__29.VertexArray.fromGeometry({ context, geometry, attributeLocations, interleave: true }); expect(va2.getAttribute(0).vertexBuffer.sizeInBytes).toEqual(32); const vs = "in vec3 position; in vec4 color; out vec4 fsColor; void main() { gl_PointSize = 1.0; gl_Position = vec4(position, 1.0); fsColor = color; }"; const fs = "in vec4 fsColor; void main() { out_FragColor = fsColor; }"; sp = import__29.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations }); import__29.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); let command = new import__29.DrawCommand({ primitiveType: import__29.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va2, offset: 0, count: 1 }); command.execute(context); expect(context).toReadPixels([255, 0, 0, 255]); command = new import__29.DrawCommand({ primitiveType: import__29.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va2, offset: 1, count: 1 }); command.execute(context); expect(context).toReadPixels([0, 255, 0, 255]); }); it("sorts interleaved attributes from large to small components (3)", function() { const geometry = new import__29.Geometry({ attributes: { unsignedByteAttribute: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 2, values: [1, 2] }), unsignedShortAttribute: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.UNSIGNED_SHORT, componentsPerAttribute: 1, values: [3] }), byteAttribute: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.BYTE, componentsPerAttribute: 1, values: [4] }), shortAttribute: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.SHORT, componentsPerAttribute: 1, values: [5] }) }, primitiveType: import__29.PrimitiveType.POINTS }); const attributeLocations = import__29.GeometryPipeline.createAttributeLocations( geometry ); const va2 = import__29.VertexArray.fromGeometry({ context, geometry, attributeLocations, interleave: true }); expect(va2.numberOfAttributes).toEqual(4); expect(va2.getAttribute(0).vertexBuffer.sizeInBytes).toEqual(8); const vs = "in vec2 unsignedByteAttribute; in float unsignedShortAttribute; in float byteAttribute; in float shortAttribute; out vec4 fsColor; void main() { gl_PointSize = 1.0; gl_Position = vec4(0.0, 0.0, 0.0, 1.0); fsColor = vec4((unsignedByteAttribute.x == 1.0) && (unsignedByteAttribute.y == 2.0) && (unsignedShortAttribute == 3.0) && (byteAttribute == 4.0) && (shortAttribute == 5.0)); }"; const fs = "in vec4 fsColor; void main() { out_FragColor = fsColor; }"; sp = import__29.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations }); import__29.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); const command = new import__29.DrawCommand({ primitiveType: import__29.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va2 }); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); }); it("creates a custom interleaved vertex", function() { const geometry = new import__29.Geometry({ attributes: { position: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0, 0, 0, 0] }), color: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 3, normalize: true, values: [255, 0, 0, 0, 255, 0] }), normal: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [1, 0, 0, 0, 1, 0] }), temperature: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.UNSIGNED_SHORT, componentsPerAttribute: 1, values: [75, 100] }) }, primitiveType: import__29.PrimitiveType.POINTS }); const attributeLocations = import__29.GeometryPipeline.createAttributeLocations( geometry ); const va2 = import__29.VertexArray.fromGeometry({ context, geometry, attributeLocations, interleave: true }); expect(va2.getAttribute(0).vertexBuffer.sizeInBytes).toEqual(2 * 32); const vs = "in vec3 position; in vec3 color; in vec3 normal; in float temperature; out vec4 fsColor; void main() { gl_PointSize = 1.0; gl_Position = vec4(position, 1.0); if ((normal == vec3(1.0, 0.0, 0.0)) && (temperature == 75.0)) { fsColor = vec4(color, 1.0); } else { fsColor = vec4(1.0); }}"; const fs = "in vec4 fsColor; void main() { out_FragColor = fsColor; }"; sp = import__29.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations }); import__29.ClearCommand.ALL.execute(context); expect(context).toReadPixels([0, 0, 0, 255]); let command = new import__29.DrawCommand({ primitiveType: import__29.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va2, offset: 0, count: 1 }); command.execute(context); expect(context).toReadPixels([255, 0, 0, 255]); const vs2 = "in vec3 position; in vec3 color; in vec3 normal; in float temperature; out vec4 fsColor; void main() { gl_PointSize = 1.0; gl_Position = vec4(position, 1.0); if ((normal == vec3(0.0, 1.0, 0.0)) && (temperature == 100.0)) { fsColor = vec4(color, 1.0); } else { fsColor = vec4(1.0); }}"; sp = sp.destroy(); sp = import__29.ShaderProgram.fromCache({ context, vertexShaderSource: vs2, fragmentShaderSource: fs, attributeLocations }); command = new import__29.DrawCommand({ primitiveType: import__29.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va2, offset: 1, count: 1 }); command.execute(context); expect(context).toReadPixels([0, 255, 0, 255]); }); it("creates an index buffer", function() { const geometry = new import__29.Geometry({ attributes: {}, indices: [0], primitiveType: import__29.PrimitiveType.POINTS }); const va2 = import__29.VertexArray.fromGeometry({ context, geometry }); expect(va2.numberOfAttributes).toEqual(0); expect(va2.indexBuffer).toBeDefined(); expect(va2.indexBuffer.usage).toEqual(import__29.BufferUsage.DYNAMIC_DRAW); expect(va2.indexBuffer.indexDatatype).toEqual( import__29.IndexDatatype.UNSIGNED_SHORT ); expect(va2.indexBuffer.numberOfIndices).toEqual(geometry.indices.length); }); it("throws with different number of interleaved attributes", function() { const geometry = new import__29.Geometry({ attributes: { position: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.FLOAT, componentsPerAttribute: 1, values: [0] }), normal: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.FLOAT, componentsPerAttribute: 1, values: [1, 2] }) }, primitiveType: import__29.PrimitiveType.POINTS }); expect(function() { return import__29.VertexArray.fromGeometry({ context, geometry, interleave: true }); }).toThrowError(import__29.RuntimeError); }); it("throws with duplicate indices", function() { const geometry = new import__29.Geometry({ attributes: { position: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.FLOAT, componentsPerAttribute: 1, values: [0] }), normal: new import__29.GeometryAttribute({ componentDatatype: import__29.ComponentDatatype.FLOAT, componentsPerAttribute: 1, values: [1] }) }, primitiveType: import__29.PrimitiveType.POINTS }); expect(function() { return import__29.VertexArray.fromGeometry({ context, geometry, attributeLocations: { position: 0, normal: 0 } }); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Renderer/VertexArraySpec.js var import__30 = __toESM(require_Cesium(), 1); describe( "Renderer/VertexArray", function() { let context; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); it("binds", function() { const positionBuffer = import__30.Buffer.createVertexBuffer({ context, sizeInBytes: 3, usage: import__30.BufferUsage.STATIC_DRAW }); const attributes = [ { index: 0, enabled: true, vertexBuffer: positionBuffer, componentsPerAttribute: 3, componentDatatype: import__30.ComponentDatatype.FLOAT, normalize: false, offsetInBytes: 0, strideInBytes: 0, instanceDivisor: 0 // tightly packed } ]; let va = new import__30.VertexArray({ context, attributes }); va._bind(); va._unBind(); va = va.destroy(); }); it("binds with default values", function() { const positionBuffer = import__30.Buffer.createVertexBuffer({ context, sizeInBytes: 3, usage: import__30.BufferUsage.STATIC_DRAW }); const attributes = [ { vertexBuffer: positionBuffer, componentsPerAttribute: 3 } ]; let va = new import__30.VertexArray({ context, attributes }); expect(va.numberOfAttributes).toEqual(1); expect(va.getAttribute(0).index).toEqual(0); expect(va.getAttribute(0).enabled).toEqual(true); expect(va.getAttribute(0).vertexBuffer).toEqual(positionBuffer); expect(va.getAttribute(0).componentsPerAttribute).toEqual(3); expect(va.getAttribute(0).componentDatatype).toEqual( import__30.ComponentDatatype.FLOAT ); expect(va.getAttribute(0).normalize).toEqual(false); expect(va.getAttribute(0).offsetInBytes).toEqual(0); expect(va.getAttribute(0).strideInBytes).toEqual(0); expect(va.getAttribute(0).instanceDivisor).toEqual(0); va._bind(); va._unBind(); va = va.destroy(); }); it("binds with multiple buffers", function() { const attributeSize = 3 * Float32Array.BYTES_PER_ELEMENT; const positionBuffer = import__30.Buffer.createVertexBuffer({ context, sizeInBytes: attributeSize, usage: import__30.BufferUsage.STATIC_DRAW }); const normalBuffer = import__30.Buffer.createVertexBuffer({ context, sizeInBytes: attributeSize, usage: import__30.BufferUsage.STATIC_DRAW }); const attributes = [ { index: 0, vertexBuffer: positionBuffer, componentsPerAttribute: 3, componentDatatype: import__30.ComponentDatatype.FLOAT }, { index: 1, vertexBuffer: normalBuffer, componentsPerAttribute: 3, componentDatatype: import__30.ComponentDatatype.FLOAT } ]; let va = new import__30.VertexArray({ context, attributes }); expect(va.numberOfAttributes).toEqual(2); va._bind(); va._unBind(); va = va.destroy(); }); it("binds with interleaved buffer", function() { const attributeSize = 3 * Float32Array.BYTES_PER_ELEMENT; const buffer = import__30.Buffer.createVertexBuffer({ context, sizeInBytes: attributeSize, usage: import__30.BufferUsage.STATIC_DRAW }); const attributes = [ { vertexBuffer: buffer, componentsPerAttribute: 3, componentDatatype: import__30.ComponentDatatype.FLOAT, offsetInBytes: 0, strideInBytes: 2 * attributeSize }, { vertexBuffer: buffer, componentsPerAttribute: 3, componentDatatype: import__30.ComponentDatatype.FLOAT, normalize: true, offsetInBytes: attributeSize, strideInBytes: 2 * attributeSize } ]; let va = new import__30.VertexArray({ context, attributes }); expect(va.numberOfAttributes).toEqual(2); va._bind(); va._unBind(); va = va.destroy(); }); it("adds attributes", function() { const positionBuffer = import__30.Buffer.createVertexBuffer({ context, sizeInBytes: 3, usage: import__30.BufferUsage.STATIC_DRAW }); let va = new import__30.VertexArray({ context, attributes: [ { vertexBuffer: positionBuffer, componentsPerAttribute: 3 } ] }); expect(va.numberOfAttributes).toEqual(1); expect(va.getAttribute(0).index).toEqual(0); expect(va.getAttribute(0).enabled).toEqual(true); expect(va.getAttribute(0).vertexBuffer).toEqual(positionBuffer); expect(va.getAttribute(0).componentsPerAttribute).toEqual(3); expect(va.getAttribute(0).componentDatatype).toEqual( import__30.ComponentDatatype.FLOAT ); expect(va.getAttribute(0).normalize).toEqual(false); expect(va.getAttribute(0).offsetInBytes).toEqual(0); expect(va.getAttribute(0).strideInBytes).toEqual(0); expect(va.getAttribute(0).instanceDivisor).toEqual(0); va = va.destroy(); }); it("modifies attributes", function() { const buffer = import__30.Buffer.createVertexBuffer({ context, sizeInBytes: 6, usage: import__30.BufferUsage.STATIC_DRAW }); const attributes = [ { vertexBuffer: buffer, componentsPerAttribute: 3 } ]; let va = new import__30.VertexArray({ context, attributes }); expect(va.numberOfAttributes).toEqual(1); expect(va.getAttribute(0).enabled).toEqual(true); va.getAttribute(0).enabled = false; expect(va.getAttribute(0).enabled).toEqual(false); va._bind(); va._unBind(); va = va.destroy(); }); it("renders with a one-component constant value", function() { const vs = "in float firefoxWorkaround;in float attr;out vec4 v_color;void main() { v_color = vec4(attr == 0.5) + vec4(firefoxWorkaround); gl_PointSize = 1.0; gl_Position = vec4(0.0, 0.0, 0.0, 1.0);}"; const fs = "in vec4 v_color;void main() { out_FragColor = v_color; }"; let sp = import__30.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { firefoxWorkaround: 0, attr: 1 } }); let va = new import__30.VertexArray({ context, attributes: [ { vertexBuffer: import__30.Buffer.createVertexBuffer({ context, sizeInBytes: Float32Array.BYTES_PER_ELEMENT, usage: import__30.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 1 }, { value: [0.5] } ] }); const command = new import__30.DrawCommand({ primitiveType: import__30.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, count: 1 }); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); sp = sp.destroy(); va = va.destroy(); }); it("renders with a two-component constant value", function() { const vs = "in float firefoxWorkaround;in vec2 attr;out vec4 v_color;void main() { v_color = vec4(attr == vec2(0.25, 0.75)) + vec4(firefoxWorkaround); gl_PointSize = 1.0; gl_Position = vec4(0.0, 0.0, 0.0, 1.0);}"; const fs = "in vec4 v_color;void main() { out_FragColor = v_color; }"; let sp = import__30.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { firefoxWorkaround: 0, attr: 1 } }); let va = new import__30.VertexArray({ context, attributes: [ { vertexBuffer: import__30.Buffer.createVertexBuffer({ context, sizeInBytes: Float32Array.BYTES_PER_ELEMENT, usage: import__30.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 1 }, { value: [0.25, 0.75] } ] }); const command = new import__30.DrawCommand({ primitiveType: import__30.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, count: 1 }); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); sp = sp.destroy(); va = va.destroy(); }); it("renders with a three-component constant value", function() { const vs = "in float firefoxWorkaround;in vec3 attr;out vec4 v_color;void main() { v_color = vec4(attr == vec3(0.25, 0.5, 0.75)) + vec4(firefoxWorkaround); gl_PointSize = 1.0; gl_Position = vec4(0.0, 0.0, 0.0, 1.0);}"; const fs = "in vec4 v_color;void main() { out_FragColor = v_color; }"; let sp = import__30.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { firefoxWorkaround: 0, attr: 1 } }); let va = new import__30.VertexArray({ context, attributes: [ { vertexBuffer: import__30.Buffer.createVertexBuffer({ context, sizeInBytes: Float32Array.BYTES_PER_ELEMENT, usage: import__30.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 1 }, { value: [0.25, 0.5, 0.75] } ] }); const command = new import__30.DrawCommand({ primitiveType: import__30.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, count: 1 }); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); sp = sp.destroy(); va = va.destroy(); }); it("renders with a four-component constant value", function() { const vs = "in float firefoxWorkaround;in vec4 attr;out vec4 v_color;void main() { v_color = vec4(attr == vec4(0.2, 0.4, 0.6, 0.8)) + vec4(firefoxWorkaround); gl_PointSize = 1.0; gl_Position = vec4(0.0, 0.0, 0.0, 1.0);}"; const fs = "in vec4 v_color;void main() { out_FragColor = v_color; }"; let sp = import__30.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { firefoxWorkaround: 0, attr: 1 } }); let va = new import__30.VertexArray({ context, attributes: [ { vertexBuffer: import__30.Buffer.createVertexBuffer({ context, sizeInBytes: Float32Array.BYTES_PER_ELEMENT, usage: import__30.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 1 }, { value: [0.2, 0.4, 0.6, 0.8] } ] }); const command = new import__30.DrawCommand({ primitiveType: import__30.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, count: 1 }); command.execute(context); expect(context).toReadPixels([255, 255, 255, 255]); sp = sp.destroy(); va = va.destroy(); }); it("renders two vertex arrays with constant values", function() { const vs = "in float firefoxWorkaround;in vec4 attr;out vec4 v_color;void main() { v_color = attr + vec4(firefoxWorkaround); gl_PointSize = 1.0; gl_Position = vec4(0.0, 0.0, 0.0, 1.0);}"; const fs = "in vec4 v_color;void main() { out_FragColor = v_color; }"; let sp = import__30.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { firefoxWorkaround: 0, attr: 1 } }); const vertexBuffer = import__30.Buffer.createVertexBuffer({ context, sizeInBytes: Float32Array.BYTES_PER_ELEMENT, usage: import__30.BufferUsage.STATIC_DRAW }); let vaRed = new import__30.VertexArray({ context, attributes: [ { vertexBuffer, componentsPerAttribute: 1 }, { value: [1, 0, 0, 1] } ] }); let vaGreen = new import__30.VertexArray({ context, attributes: [ { vertexBuffer, componentsPerAttribute: 1 }, { value: [0, 1, 0, 1] } ] }); const commandRed = new import__30.DrawCommand({ primitiveType: import__30.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: vaRed, count: 1 }); const commandGreen = new import__30.DrawCommand({ primitiveType: import__30.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: vaGreen, count: 1 }); commandRed.execute(context); expect(context).toReadPixels([255, 0, 0, 255]); commandGreen.execute(context); expect(context).toReadPixels([0, 255, 0, 255]); sp = sp.destroy(); vaRed = vaRed.destroy(); vaGreen = vaGreen.destroy(); }); it("destroys", function() { const va = new import__30.VertexArray({ context, attributes: [ { vertexBuffer: import__30.Buffer.createVertexBuffer({ context, sizeInBytes: new Float32Array([0, 0, 0, 1]).byteLength, usage: import__30.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); expect(va.isDestroyed()).toEqual(false); va.destroy(); expect(va.isDestroyed()).toEqual(true); }); it("fails to create (missing vertexBuffer and value)", function() { const attributes = [ { componentsPerAttribute: 3 } ]; expect(function() { return new import__30.VertexArray({ context, attributes }); }).toThrowDeveloperError(); }); it("fails to create (provides both vertexBuffer and value)", function() { const buffer = import__30.Buffer.createVertexBuffer({ context, sizeInBytes: 3, usage: import__30.BufferUsage.STATIC_DRAW }); const attributes = [ { vertexBuffer: buffer, value: [1, 2, 3], componentsPerAttribute: 3 } ]; expect(function() { return new import__30.VertexArray({ context, attributes }); }).toThrowDeveloperError(); }); it("fails to create with duplicate indices", function() { const buffer = import__30.Buffer.createVertexBuffer({ context, sizeInBytes: 1, usage: import__30.BufferUsage.STATIC_DRAW }); const attributes = [ { index: 1, vertexBuffer: buffer, componentsPerAttribute: 1 }, { index: 1, vertexBuffer: buffer, componentsPerAttribute: 1 } ]; expect(function() { return new import__30.VertexArray({ context, attributes }); }).toThrowDeveloperError(); }); it("fails to create (componentsPerAttribute missing)", function() { const buffer = import__30.Buffer.createVertexBuffer({ context, sizeInBytes: 3, usage: import__30.BufferUsage.STATIC_DRAW }); const attributes = [ { vertexBuffer: buffer } ]; expect(function() { return new import__30.VertexArray({ context, attributes }); }).toThrowDeveloperError(); }); it("fails to create (componentsPerAttribute < 1)", function() { const attributes = [ { componentsPerAttribute: 0 } ]; expect(function() { return new import__30.VertexArray({ context, attributes }); }).toThrowDeveloperError(); }); it("fails to create (componentsPerAttribute > 4)", function() { const attributes = [ { componentsPerAttribute: 5 } ]; expect(function() { return new import__30.VertexArray({ context, attributes }); }).toThrowDeveloperError(); }); it("fails to create (value.length < 1)", function() { const attributes = [ { value: [] } ]; expect(function() { return new import__30.VertexArray({ context, attributes }); }).toThrowDeveloperError(); }); it("fails to create (value.length > 4)", function() { const attributes = [ { value: [1, 2, 3, 4, 5] } ]; expect(function() { return new import__30.VertexArray({ context, attributes }); }).toThrowDeveloperError(); }); it("fails to create (componentDatatype)", function() { const buffer = import__30.Buffer.createVertexBuffer({ context, sizeInBytes: 3, usage: import__30.BufferUsage.STATIC_DRAW }); const attributes = [ { vertexBuffer: buffer, componentsPerAttribute: 3, componentDatatype: "invalid component datatype" } ]; expect(function() { return new import__30.VertexArray({ context, attributes }); }).toThrowDeveloperError(); }); it("fails to create (strideInBytes)", function() { const buffer = import__30.Buffer.createVertexBuffer({ context, sizeInBytes: 3, usage: import__30.BufferUsage.STATIC_DRAW }); const attributes = [ { vertexBuffer: buffer, componentsPerAttribute: 3, strideInBytes: 256 } ]; expect(function() { return new import__30.VertexArray({ context, attributes }); }).toThrowDeveloperError(); }); it("fails to get attribute", function() { const attributes = [ { value: [0, 0, 0], componentsPerAttribute: 3 } ]; const va = new import__30.VertexArray({ context, attributes }); expect(function() { return va.getAttribute(); }).toThrowDeveloperError(); }); it("fails to destroy", function() { const attributes = [ { value: [0, 0, 0], componentsPerAttribute: 3 } ]; const va = new import__30.VertexArray({ context, attributes }); va.destroy(); expect(function() { va.destroy(); }).toThrowDeveloperError(); }); it("throws when there is no context", function() { expect(function() { return new import__30.VertexArray(); }).toThrowDeveloperError(); }); it("throws if instanceDivisor is less than zero", function() { const buffer = import__30.Buffer.createVertexBuffer({ context, sizeInBytes: 3, usage: import__30.BufferUsage.STATIC_DRAW }); const attributes = [ { vertexBuffer: buffer, componentsPerAttribute: 3, instanceDivisor: -1 } ]; expect(function() { return new import__30.VertexArray({ context, attributes }); }).toThrowDeveloperError(); }); it("throws if vertex attribute zero is instanced", function() { const buffer = import__30.Buffer.createVertexBuffer({ context, sizeInBytes: 3, usage: import__30.BufferUsage.STATIC_DRAW }); const attributes = [ { index: 0, vertexBuffer: buffer, componentsPerAttribute: 3, instanceDivisor: 1 }, { index: 1, vertexBuffer: buffer, componentsPerAttribute: 3 } ]; expect(function() { return new import__30.VertexArray({ context, attributes }); }).toThrowDeveloperError(); }); it("throws if an attribute has an instanceDivisor and is not backed by a buffer", function() { const buffer = import__30.Buffer.createVertexBuffer({ context, sizeInBytes: 3, usage: import__30.BufferUsage.STATIC_DRAW }); const attributes = [ { index: 0, vertexBuffer: buffer, componentsPerAttribute: 3 }, { index: 1, value: [0, 0, 1], componentsPerAttribute: 3, instanceDivisor: 1 } ]; expect(function() { return new import__30.VertexArray({ context, attributes }); }).toThrowDeveloperError(); }); it("throws when instanceDivisor is greater than zero and instancing is disabled", function() { const contextWithoutInstancing = createContext_default({ requestWebgl1: true }); contextWithoutInstancing._instancedArrays = void 0; const buffer = import__30.Buffer.createVertexBuffer({ context: contextWithoutInstancing, sizeInBytes: 3, usage: import__30.BufferUsage.STATIC_DRAW }); const attributes = [ { index: 0, vertexBuffer: buffer, componentsPerAttribute: 3 }, { index: 1, vertexBuffer: buffer, componentsPerAttribute: 3, instanceDivisor: 1 } ]; expect(function() { return new import__30.VertexArray({ context: contextWithoutInstancing, attributes }); }).toThrowDeveloperError(); contextWithoutInstancing.destroyForSpecs(); }); }, "WebGL" ); // packages/engine/Specs/Renderer/demodernizeShaderSpec.js var import__31 = __toESM(require_Cesium(), 1); describe("Renderer/demodernizeShader", () => { it("replaces version", () => { const input = `#version 300 es void main() {} `; const output = (0, import__31.demodernizeShader)(input, false); const expectedVersion = "#version 100"; expect(output.startsWith(expectedVersion)).toEqual(true); }); it("replaces out_FragData with gl_FragData", () => { const input = `#version 300 es layout (location = 0) vec4 out_FragData_0; layout (location = 1) vec4 out_FragData_1; layout (location = 10) vec4 out_FragData_10; layout (location = 11) vec4 out_FragData_11; void main() { out_FragData_0 = vec4(0.0); out_FragData_1 = vec4(1.0); out_FragData_10 = vec4(0.0, 0.0, 0.0, 0.0); out_FragData_11 = vec4(1.0, 2.0, 3.0, 4.0); } `; const output = (0, import__31.demodernizeShader)(input, true); const expectedVersion = "#version 100"; expect(output.startsWith(expectedVersion)).toEqual(true); expect(output).not.toContain("layout (location = 0) vec4 out_FragData_0"); expect(output).not.toContain("layout (location = 1) vec4 out_FragData_1"); expect(output).not.toContain("layout (location = 10) vec4 out_FragData_10"); expect(output).not.toContain("layout (location = 11) vec4 out_FragData_11"); expect(output).toContain("gl_FragData[0] = vec4(0.0);"); expect(output).toContain("gl_FragData[1] = vec4(1.0);"); expect(output).toContain("gl_FragData[10] = vec4(0.0, 0.0, 0.0, 0.0);"); expect(output).toContain("gl_FragData[11] = vec4(1.0, 2.0, 3.0, 4.0);"); }); it("replaces out_FragColor with gl_FragColor", () => { const input = `#version 300 es layout (location = 0) vec4 out_FragColor; void main() { out_FragColor = vec4(1.0); out_FragColor[0] = 0.0; out_FragColor[2] = 2.0; } `; const output = (0, import__31.demodernizeShader)(input, true); const expectedVersion = "#version 100"; expect(output.startsWith(expectedVersion)).toEqual(true); expect(output).not.toContain("layout (location = 0) vec4 out_FragColor"); expect(output).toContain("gl_FragColor = vec4(1.0);"); expect(output).toContain("gl_FragColor[0] = 0.0;"); expect(output).toContain("gl_FragColor[2] = 2.0;"); }); it("replaces texture with texture2D", () => { const input = `#version 300 es uniform sampler2D u_texture; void main() { vec4 tex = texture(u_texture, vec2(0.0)); } `; const output = (0, import__31.demodernizeShader)(input, false); const expectedVersion = "#version 100"; expect(output.startsWith(expectedVersion)).toEqual(true); expect(output).toContain("vec4 tex = texture2D(u_texture, vec2(0.0));"); }); it("replaces in with attribute in vertex shader", () => { const input = `#version 300 es in float a_float; in vec3 a_vec3; in mat2 a_mat2; void main() {} `; const output = (0, import__31.demodernizeShader)(input, false); const expectedVersion = "#version 100"; expect(output.startsWith(expectedVersion)).toEqual(true); expect(output).toContain("attribute float a_float;"); expect(output).toContain("attribute vec3 a_vec3;"); expect(output).toContain("attribute mat2 a_mat2;"); }); it("replaces in with varying in fragment shader", () => { const input = `#version 300 es in float a_float; in vec3 a_vec3; in mat2 a_mat2; void main() {} `; const output = (0, import__31.demodernizeShader)(input, true); const expectedVersion = "#version 100"; expect(output.startsWith(expectedVersion)).toEqual(true); expect(output).toContain("varying float a_float;"); expect(output).toContain("varying vec3 a_vec3;"); expect(output).toContain("varying mat2 a_mat2;"); }); it("replaces out with varying in vertex shader", () => { const input = `#version 300 es out float a_float; out vec3 a_vec3; out mat2 a_mat2; void main() {} `; const output = (0, import__31.demodernizeShader)(input, false); const expectedVersion = "#version 100"; expect(output.startsWith(expectedVersion)).toEqual(true); expect(output).toContain("varying float a_float;"); expect(output).toContain("varying vec3 a_vec3;"); expect(output).toContain("varying mat2 a_mat2;"); }); it("replaces gl_FragDepth with gl_FragDepthEXT", () => { const input = `#version 300 es void main() { gl_FragDepth = vec4(1.0); gl_FragDepth += vec4(2.0); } `; const output = (0, import__31.demodernizeShader)(input, true); const expectedVersion = "#version 100"; expect(output.startsWith(expectedVersion)).toEqual(true); expect(output).toContain("#extension GL_EXT_frag_depth : enable"); expect(output).toContain("gl_FragDepthEXT = vec4(1.0);"); expect(output).toContain("gl_FragDepthEXT += vec4(2.0);"); }); }); // packages/engine/Specs/Renderer/freezeRenderStateSpec.js var import__32 = __toESM(require_Cesium(), 1); describe("Renderer/freezeRenderState", function() { it("works as expected", function() { const fresh = { a: 1, b: { c: "c" }, _applyFunctions: [function() { }] }; const frozen = (0, import__32.freezeRenderState)(fresh); expect(Object.isFrozen(frozen)).toBe(true); expect(Object.isFrozen(frozen.a)).toBe(true); expect(Object.isFrozen(frozen.b)).toBe(true); expect(Object.isFrozen(frozen.c)).toBe(true); expect(Object.isFrozen(frozen._applyFunctions)).toBe(false); }); }); // packages/engine/Specs/Renderer/loadCubeMapSpec.js var import__33 = __toESM(require_Cesium(), 1); describe( "Renderer/loadCubeMap", function() { let context; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); it("loads a cube map", function() { return (0, import__33.loadCubeMap)(context, { positiveX: "./Data/Images/Green.png", negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Green.png", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Green.png", negativeZ: "./Data/Images/Blue.png" }).then(function(cm) { expect(cm.width).toEqual(1); expect(cm.height).toEqual(1); const vs = "in vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }"; const fs = "uniform samplerCube u_texture;uniform mediump vec3 u_direction;void main() { out_FragColor = czm_textureCube(u_texture, normalize(u_direction)); }"; const sp = import__33.ShaderProgram.fromCache({ context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations: { position: 0 } }); const uniformMap = { direction: void 0, u_texture: function() { return cm; }, u_direction: function() { return this.direction; } }; const va = new import__33.VertexArray({ context, attributes: [ { vertexBuffer: import__33.Buffer.createVertexBuffer({ context, typedArray: new Float32Array([0, 0, 0, 1]), usage: import__33.BufferUsage.STATIC_DRAW }), componentsPerAttribute: 4 } ] }); const command = new import__33.DrawCommand({ primitiveType: import__33.PrimitiveType.POINTS, shaderProgram: sp, vertexArray: va, uniformMap }); uniformMap.direction = new import__33.Cartesian3(1, 0, 0); command.execute(context); expect(context).toReadPixels([0, 255, 0, 255]); uniformMap.direction = new import__33.Cartesian3(-1, 0, 0); command.execute(context); expect(context).toReadPixels([0, 0, 255, 255]); uniformMap.direction = new import__33.Cartesian3(0, 1, 0); command.execute(context); expect(context).toReadPixels([0, 255, 0, 255]); uniformMap.direction = new import__33.Cartesian3(0, -1, 0); command.execute(context); expect(context).toReadPixels([0, 0, 255, 255]); uniformMap.direction = new import__33.Cartesian3(0, 0, 1); command.execute(context); expect(context).toReadPixels([0, 255, 0, 255]); uniformMap.direction = new import__33.Cartesian3(0, 0, -1); command.execute(context); expect(context).toReadPixels([0, 0, 255, 255]); sp.destroy(); va.destroy(); cm.destroy(); }); }); it("calls error function when positiveX does not exist", function() { return (0, import__33.loadCubeMap)(context, { positiveX: "not.found", negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" }).then(function(cubeMap) { fail("should not be called"); }).catch(function() { }); }); it("calls error function when negativeX does not exist", function() { return (0, import__33.loadCubeMap)(context, { positiveX: "./Data/Images/Blue.png", negativeX: "not.found", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" }).then(function(cubeMap) { fail("should not be called"); }).catch(function() { }); }); it("calls error function when positiveY does not exist", function() { return (0, import__33.loadCubeMap)(context, { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", positiveY: "not.found", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" }).then(function(cubeMap) { fail("should not be called"); }).catch(function() { }); }); it("calls error function when negativeY does not exist", function() { return (0, import__33.loadCubeMap)(context, { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: "not.found", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" }).then(function(cubeMap) { fail("should not be called"); }).catch(function() { }); }); it("calls error function when positiveZ does not exist", function() { return (0, import__33.loadCubeMap)(context, { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: "not.found", negativeZ: "./Data/Images/Blue.png" }).then(function(cubeMap) { fail("should not be called"); }).catch(function() { }); }); it("calls error function when negativeZ does not exist", function() { return (0, import__33.loadCubeMap)(context, { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "not.found" }).then(function(cubeMap) { fail("should not be called"); }).catch(function() { }); }); it("throws without a context", function() { expect(function() { (0, import__33.loadCubeMap)(void 0); }).toThrowDeveloperError(); }); it("throws without urls", function() { expect(function() { (0, import__33.loadCubeMap)(context); }).toThrowDeveloperError(); }); it("throws without positiveX", function() { expect(function() { (0, import__33.loadCubeMap)(context, { negativeX: "any.image", positiveY: "any.image", negativeY: "any.image", positiveZ: "any.image", negativeZ: "any.image" }); }).toThrowDeveloperError(); }); it("throws without negativeX", function() { expect(function() { (0, import__33.loadCubeMap)(context, { positiveX: "any.image", positiveY: "any.image", negativeY: "any.image", positiveZ: "any.image", negativeZ: "any.image" }); }).toThrowDeveloperError(); }); it("throws without positiveY", function() { expect(function() { (0, import__33.loadCubeMap)(context, { positiveX: "any.image", negativeX: "any.image", negativeY: "any.image", positiveZ: "any.image", negativeZ: "any.image" }); }).toThrowDeveloperError(); }); it("throws without negativeY", function() { expect(function() { (0, import__33.loadCubeMap)(context, { positiveX: "any.image", negativeX: "any.image", positiveY: "any.image", positiveZ: "any.image", negativeZ: "any.image" }); }).toThrowDeveloperError(); }); it("throws without positiveZ", function() { expect(function() { (0, import__33.loadCubeMap)(context, { positiveX: "any.image", negativeX: "any.image", positiveY: "any.image", negativeY: "any.image", negativeZ: "any.image" }); }).toThrowDeveloperError(); }); it("throws without negativeZ", function() { expect(function() { (0, import__33.loadCubeMap)(context, { positiveX: "any.image", negativeX: "any.image", positiveY: "any.image", negativeY: "any.image", positiveZ: "any.image" }); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/DataSources/BillboardGraphicsSpec.js var import__34 = __toESM(require_Cesium(), 1); describe("DataSources/BillboardGraphics", function() { it("creates expected instance from raw assignment and construction", function() { const options = { image: "0", rotation: 1, alignedAxis: import__34.Cartesian3.UNIT_Z, color: import__34.Color.RED, heightReference: import__34.HeightReference.CLAMP_TO_GROUND, horizontalOrigin: import__34.HorizontalOrigin.LEFT, verticalOrigin: import__34.VerticalOrigin.BOTTOM, eyeOffset: new import__34.Cartesian3(5, 6, 7), pixelOffset: new import__34.Cartesian2(8, 9), scale: 10, show: true, width: 11, height: 12, scaleByDistance: new import__34.NearFarScalar(13, 14, 15, 16), translucencyByDistance: new import__34.NearFarScalar(17, 18, 19, 20), pixelOffsetScaleByDistance: new import__34.NearFarScalar(21, 22, 23, 24), sizeInMeters: true, distanceDisplayCondition: new import__34.DistanceDisplayCondition(10, 100), disableDepthTestDistance: 10 }; const billboard = new import__34.BillboardGraphics(options); expect(billboard.image).toBeInstanceOf(import__34.ConstantProperty); expect(billboard.rotation).toBeInstanceOf(import__34.ConstantProperty); expect(billboard.alignedAxis).toBeInstanceOf(import__34.ConstantProperty); expect(billboard.color).toBeInstanceOf(import__34.ConstantProperty); expect(billboard.heightReference).toBeInstanceOf(import__34.ConstantProperty); expect(billboard.horizontalOrigin).toBeInstanceOf(import__34.ConstantProperty); expect(billboard.verticalOrigin).toBeInstanceOf(import__34.ConstantProperty); expect(billboard.eyeOffset).toBeInstanceOf(import__34.ConstantProperty); expect(billboard.scale).toBeInstanceOf(import__34.ConstantProperty); expect(billboard.show).toBeInstanceOf(import__34.ConstantProperty); expect(billboard.width).toBeInstanceOf(import__34.ConstantProperty); expect(billboard.height).toBeInstanceOf(import__34.ConstantProperty); expect(billboard.scaleByDistance).toBeInstanceOf(import__34.ConstantProperty); expect(billboard.translucencyByDistance).toBeInstanceOf(import__34.ConstantProperty); expect(billboard.pixelOffsetScaleByDistance).toBeInstanceOf( import__34.ConstantProperty ); expect(billboard.sizeInMeters).toBeInstanceOf(import__34.ConstantProperty); expect(billboard.distanceDisplayCondition).toBeInstanceOf(import__34.ConstantProperty); expect(billboard.disableDepthTestDistance).toBeInstanceOf(import__34.ConstantProperty); expect(billboard.image.getValue()).toEqual(options.image); expect(billboard.rotation.getValue()).toEqual(options.rotation); expect(billboard.alignedAxis.getValue()).toEqual(options.alignedAxis); expect(billboard.color.getValue()).toEqual(options.color); expect(billboard.heightReference.getValue()).toEqual( options.heightReference ); expect(billboard.horizontalOrigin.getValue()).toEqual( options.horizontalOrigin ); expect(billboard.verticalOrigin.getValue()).toEqual(options.verticalOrigin); expect(billboard.eyeOffset.getValue()).toEqual(options.eyeOffset); expect(billboard.scale.getValue()).toEqual(options.scale); expect(billboard.show.getValue()).toEqual(options.show); expect(billboard.width.getValue()).toEqual(options.width); expect(billboard.height.getValue()).toEqual(options.height); expect(billboard.scaleByDistance.getValue()).toEqual( options.scaleByDistance ); expect(billboard.translucencyByDistance.getValue()).toEqual( options.translucencyByDistance ); expect(billboard.pixelOffsetScaleByDistance.getValue()).toEqual( options.pixelOffsetScaleByDistance ); expect(billboard.sizeInMeters.getValue()).toEqual(options.sizeInMeters); expect(billboard.distanceDisplayCondition.getValue()).toEqual( options.distanceDisplayCondition ); expect(billboard.disableDepthTestDistance.getValue()).toEqual( options.disableDepthTestDistance ); }); it("merge assigns unassigned properties", function() { const source = new import__34.BillboardGraphics(); source.image = new import__34.ConstantProperty(""); source.imageSubRegion = new import__34.ConstantProperty(); source.rotation = new import__34.ConstantProperty(5); source.alignedAxis = new import__34.ConstantProperty(new import__34.Cartesian3()); source.color = new import__34.ConstantProperty(import__34.Color.BLACK); source.heightReference = new import__34.ConstantProperty( import__34.HeightReference.CLAMP_TO_GROUND ); source.horizontalOrigin = new import__34.ConstantProperty(import__34.HorizontalOrigin.LEFT); source.verticalOrigin = new import__34.ConstantProperty(import__34.VerticalOrigin.BOTTOM); source.eyeOffset = new import__34.ConstantProperty(import__34.Cartesian3.UNIT_Y); source.pixelOffset = new import__34.ConstantProperty(import__34.Cartesian2.UNIT_X); source.scale = new import__34.ConstantProperty(1); source.show = new import__34.ConstantProperty(false); source.width = new import__34.ConstantProperty(24); source.height = new import__34.ConstantProperty(36); source.scaleByDistance = new import__34.ConstantProperty(new import__34.NearFarScalar()); source.translucencyByDistance = new import__34.ConstantProperty(new import__34.NearFarScalar()); source.pixelOffsetScaleByDistance = new import__34.ConstantProperty( new import__34.NearFarScalar(1, 0, 3e9, 0) ); source.sizeInMeters = new import__34.ConstantProperty(true); source.distanceDisplayCondition = new import__34.ConstantProperty( new import__34.DistanceDisplayCondition(10, 100) ); source.disableDepthTestDistance = 10; const target = new import__34.BillboardGraphics(); target.merge(source); expect(target.image).toBe(source.image); expect(target.imageSubRegion).toBe(source.imageSubRegion); expect(target.rotation).toBe(source.rotation); expect(target.alignedAxis).toBe(source.alignedAxis); expect(target.color).toBe(source.color); expect(target.heightReference).toBe(source.heightReference); expect(target.horizontalOrigin).toBe(source.horizontalOrigin); expect(target.verticalOrigin).toBe(source.verticalOrigin); expect(target.eyeOffset).toBe(source.eyeOffset); expect(target.pixelOffset).toBe(source.pixelOffset); expect(target.scale).toBe(source.scale); expect(target.show).toBe(source.show); expect(target.width).toBe(source.width); expect(target.height).toBe(source.height); expect(target.scaleByDistance).toBe(source.scaleByDistance); expect(target.translucencyByDistance).toBe(source.translucencyByDistance); expect(target.pixelOffsetScaleByDistance).toBe( source.pixelOffsetScaleByDistance ); expect(target.sizeInMeters).toBe(source.sizeInMeters); expect(target.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(target.disableDepthTestDistance).toBe( source.disableDepthTestDistance ); }); it("merge does not assign assigned properties", function() { const source = new import__34.BillboardGraphics(); source.image = new import__34.ConstantProperty(""); source.imageSubRegion = new import__34.ConstantProperty(); source.rotation = new import__34.ConstantProperty(5); source.alignedAxis = new import__34.ConstantProperty(new import__34.Cartesian3()); source.color = new import__34.ConstantProperty(import__34.Color.BLACK); source.heightReference = new import__34.ConstantProperty( import__34.HeightReference.CLAMP_TO_GROUND ); source.horizontalOrigin = new import__34.ConstantProperty(import__34.HorizontalOrigin.LEFT); source.verticalOrigin = new import__34.ConstantProperty(import__34.VerticalOrigin.BOTTOM); source.eyeOffset = new import__34.ConstantProperty(import__34.Cartesian3.UNIT_Y); source.pixelOffset = new import__34.ConstantProperty(import__34.Cartesian2.UNIT_X); source.scale = new import__34.ConstantProperty(1); source.show = new import__34.ConstantProperty(false); source.width = new import__34.ConstantProperty(24); source.height = new import__34.ConstantProperty(36); source.scaleByDistance = new import__34.ConstantProperty(new import__34.NearFarScalar()); source.translucencyByDistance = new import__34.ConstantProperty(new import__34.NearFarScalar()); source.pixelOffsetScaleByDistance = new import__34.ConstantProperty( new import__34.NearFarScalar(1, 0, 3e9, 0) ); source.sizeInMeters = new import__34.ConstantProperty(true); source.distanceDisplayCondition = new import__34.ConstantProperty( new import__34.DistanceDisplayCondition(10, 100) ); source.disableDepthTestDistance = new import__34.ConstantProperty(10); const image = new import__34.ConstantProperty(""); const imageSubRegion = new import__34.ConstantProperty(); const rotation = new import__34.ConstantProperty(5); const alignedAxis = new import__34.ConstantProperty(new import__34.Cartesian3()); const color = new import__34.ConstantProperty(import__34.Color.BLACK); const heightReference = new import__34.ConstantProperty( import__34.HeightReference.CLAMP_TO_GROUND ); const horizontalOrigin = new import__34.ConstantProperty(import__34.HorizontalOrigin.LEFT); const verticalOrigin = new import__34.ConstantProperty(import__34.VerticalOrigin.BOTTOM); const eyeOffset = new import__34.ConstantProperty(import__34.Cartesian3.UNIT_Y); const pixelOffset = new import__34.ConstantProperty(import__34.Cartesian2.UNIT_X); const scale = new import__34.ConstantProperty(1); const show = new import__34.ConstantProperty(false); const width = new import__34.ConstantProperty(2); const height = new import__34.ConstantProperty(3); const scaleByDistance = new import__34.ConstantProperty(new import__34.NearFarScalar()); const translucencyByDistance = new import__34.ConstantProperty(new import__34.NearFarScalar()); const pixelOffsetScaleByDistance = new import__34.ConstantProperty( new import__34.NearFarScalar() ); const sizeInMeters = new import__34.ConstantProperty(true); const distanceDisplayCondition = new import__34.ConstantProperty( new import__34.DistanceDisplayCondition() ); const disableDepthTestDistance = new import__34.ConstantProperty(10); const target = new import__34.BillboardGraphics(); target.image = image; target.imageSubRegion = imageSubRegion; target.rotation = rotation; target.alignedAxis = alignedAxis; target.color = color; target.heightReference = heightReference; target.horizontalOrigin = horizontalOrigin; target.verticalOrigin = verticalOrigin; target.eyeOffset = eyeOffset; target.pixelOffset = pixelOffset; target.scale = scale; target.show = show; target.width = width; target.height = height; target.scaleByDistance = scaleByDistance; target.translucencyByDistance = translucencyByDistance; target.pixelOffsetScaleByDistance = pixelOffsetScaleByDistance; target.sizeInMeters = sizeInMeters; target.distanceDisplayCondition = distanceDisplayCondition; target.disableDepthTestDistance = disableDepthTestDistance; target.merge(source); expect(target.image).toBe(image); expect(target.imageSubRegion).toBe(imageSubRegion); expect(target.rotation).toBe(rotation); expect(target.alignedAxis).toBe(alignedAxis); expect(target.color).toBe(color); expect(target.heightReference).toBe(heightReference); expect(target.horizontalOrigin).toBe(horizontalOrigin); expect(target.verticalOrigin).toBe(verticalOrigin); expect(target.eyeOffset).toBe(eyeOffset); expect(target.pixelOffset).toBe(pixelOffset); expect(target.scale).toBe(scale); expect(target.show).toBe(show); expect(target.width).toBe(width); expect(target.height).toBe(height); expect(target.scaleByDistance).toBe(scaleByDistance); expect(target.translucencyByDistance).toBe(translucencyByDistance); expect(target.pixelOffsetScaleByDistance).toBe(pixelOffsetScaleByDistance); expect(target.sizeInMeters).toBe(sizeInMeters); expect(target.distanceDisplayCondition).toBe(distanceDisplayCondition); expect(target.disableDepthTestDistance).toBe(disableDepthTestDistance); }); it("clone works", function() { const source = new import__34.BillboardGraphics(); source.image = new import__34.ConstantProperty(""); source.imageSubRegion = new import__34.ConstantProperty(); source.rotation = new import__34.ConstantProperty(5); source.alignedAxis = new import__34.ConstantProperty(new import__34.Cartesian3()); source.color = new import__34.ConstantProperty(import__34.Color.BLACK); source.heightReference = new import__34.ConstantProperty( import__34.HeightReference.CLAMP_TO_GROUND ); source.horizontalOrigin = new import__34.ConstantProperty(import__34.HorizontalOrigin.LEFT); source.verticalOrigin = new import__34.ConstantProperty(import__34.VerticalOrigin.BOTTOM); source.eyeOffset = new import__34.ConstantProperty(import__34.Cartesian3.UNIT_Y); source.pixelOffset = new import__34.ConstantProperty(import__34.Cartesian2.UNIT_X); source.scale = new import__34.ConstantProperty(1); source.show = new import__34.ConstantProperty(false); source.width = new import__34.ConstantProperty(24); source.height = new import__34.ConstantProperty(36); source.scaleByDistance = new import__34.ConstantProperty(new import__34.NearFarScalar()); source.translucencyByDistance = new import__34.ConstantProperty(new import__34.NearFarScalar()); source.pixelOffsetScaleByDistance = new import__34.ConstantProperty( new import__34.NearFarScalar(1, 0, 3e9, 0) ); source.sizeInMeters = new import__34.ConstantProperty(true); source.distanceDisplayCondition = new import__34.ConstantProperty( new import__34.DistanceDisplayCondition(10, 100) ); source.disableDepthTestDistance = new import__34.ConstantProperty(10); const result = source.clone(); expect(result.image).toBe(source.image); expect(result.imageSubRegion).toBe(source.imageSubRegion); expect(result.rotation).toBe(source.rotation); expect(result.alignedAxis).toBe(source.alignedAxis); expect(result.color).toBe(source.color); expect(result.heightReference).toBe(source.heightReference); expect(result.horizontalOrigin).toBe(source.horizontalOrigin); expect(result.verticalOrigin).toBe(source.verticalOrigin); expect(result.eyeOffset).toBe(source.eyeOffset); expect(result.pixelOffset).toBe(source.pixelOffset); expect(result.scale).toBe(source.scale); expect(result.show).toBe(source.show); expect(result.width).toBe(source.width); expect(result.height).toBe(source.height); expect(result.scaleByDistance).toBe(source.scaleByDistance); expect(result.translucencyByDistance).toBe(source.translucencyByDistance); expect(result.pixelOffsetScaleByDistance).toBe( source.pixelOffsetScaleByDistance ); expect(result.sizeInMeters).toBe(source.sizeInMeters); expect(result.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(result.disableDepthTestDistance).toBe( source.disableDepthTestDistance ); }); it("merge throws if source undefined", function() { const target = new import__34.BillboardGraphics(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/BillboardVisualizerSpec.js var import__35 = __toESM(require_Cesium(), 1); // Specs/createGlobe.js var import_engine7 = __toESM(require_Cesium(), 1); function createGlobe(ellipsoid) { ellipsoid = (0, import_engine7.defaultValue)(ellipsoid, import_engine7.Ellipsoid.WGS84); const globe2 = { _callback: void 0, _removedCallback: false, ellipsoid, beginFrame: function() { }, endFrame: function() { }, update: function() { }, render: function() { }, getHeight: function() { return 0; }, _surface: {}, imageryLayersUpdatedEvent: new import_engine7.Event(), _terrainProvider: void 0, terrainProviderChanged: new import_engine7.Event(), tileLoadProgressEvent: new import_engine7.Event(), destroy: function() { }, isDestroyed: function() { return false; } }; globe2._surface.updateHeight = function(position, callback) { globe2._callback = callback; return function() { globe2._removedCallback = true; globe2._callback = void 0; }; }; globe2.terrainProviderChanged = new import_engine7.Event(); Object.defineProperties(globe2, { terrainProvider: { get: function() { return this._terrainProvider; }, set: function(value) { this._terrainProvider = value; this.terrainProviderChanged.raiseEvent(value); } } }); return globe2; } var createGlobe_default = createGlobe; // Specs/pollToPromise.js var import_engine8 = __toESM(require_Cesium(), 1); function pollToPromise(f, options) { options = (0, import_engine8.defaultValue)(options, import_engine8.defaultValue.EMPTY_OBJECT); const pollInterval = (0, import_engine8.defaultValue)(options.pollInterval, 1); const timeout = (0, import_engine8.defaultValue)(options.timeout, 5e3); return new Promise(function(resolve, reject) { const startTimestamp = (0, import_engine8.getTimestamp)(); const endTimestamp = startTimestamp + timeout; function poller() { let result = false; try { result = f(); } catch (e) { reject(e); return; } if (result) { resolve(); } else if ((0, import_engine8.getTimestamp)() > endTimestamp) { reject( new Error(`Timeout - function did not complete within ${timeout}ms`) ); } else { setTimeout(poller, pollInterval); } } poller(); }); } var pollToPromise_default = pollToPromise; // packages/engine/Specs/DataSources/BillboardVisualizerSpec.js describe( "DataSources/BillboardVisualizer", function() { let scene2; let entityCluster; let visualizer; beforeAll(function() { scene2 = createScene_default(); scene2.globe = createGlobe_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { entityCluster = new import__35.EntityCluster(); entityCluster._initialize(scene2); }); afterEach(function() { if ((0, import__35.defined)(visualizer)) { visualizer = visualizer.destroy(); } entityCluster.destroy(); }); it("constructor throws if no entityCluster is passed.", function() { expect(function() { return new import__35.BillboardVisualizer(); }).toThrowDeveloperError(); }); it("update throws if no time specified.", function() { const entityCollection = new import__35.EntityCollection(); visualizer = new import__35.BillboardVisualizer(entityCluster, entityCollection); expect(function() { visualizer.update(); }).toThrowDeveloperError(); }); it("isDestroy returns false until destroyed.", function() { const entityCollection = new import__35.EntityCollection(); visualizer = new import__35.BillboardVisualizer(entityCluster, entityCollection); expect(visualizer.isDestroyed()).toEqual(false); visualizer.destroy(); expect(visualizer.isDestroyed()).toEqual(true); visualizer = void 0; }); it("removes the listener from the entity collection when destroyed", function() { const entityCollection = new import__35.EntityCollection(); const visualizer2 = new import__35.BillboardVisualizer( entityCluster, entityCollection ); expect(entityCollection.collectionChanged.numberOfListeners).toEqual(1); visualizer2.destroy(); expect(entityCollection.collectionChanged.numberOfListeners).toEqual(0); }); it("object with no billboard does not create a billboard.", function() { const entityCollection = new import__35.EntityCollection(); visualizer = new import__35.BillboardVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__35.ConstantProperty( new import__35.Cartesian3(1234, 5678, 9101112) ); visualizer.update(import__35.JulianDate.now()); expect(entityCluster._billboardCollection).not.toBeDefined(); }); it("object with no position does not create a billboard.", function() { const entityCollection = new import__35.EntityCollection(); visualizer = new import__35.BillboardVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); const billboard = testObject.billboard = new import__35.BillboardGraphics(); billboard.show = new import__35.ConstantProperty(true); billboard.image = new import__35.ConstantProperty("Data/Images/Blue.png"); visualizer.update(import__35.JulianDate.now()); expect(entityCluster._billboardCollection).not.toBeDefined(); }); it("object with no image does not create a billboard.", function() { const entityCollection = new import__35.EntityCollection(); visualizer = new import__35.BillboardVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__35.ConstantProperty( new import__35.Cartesian3(1234, 5678, 9101112) ); const billboard = testObject.billboard = new import__35.BillboardGraphics(); billboard.show = new import__35.ConstantProperty(true); visualizer.update(import__35.JulianDate.now()); expect(entityCluster._billboardCollection).not.toBeDefined(); }); it("A BillboardGraphics causes a Billboard to be created and updated.", function() { const entityCollection = new import__35.EntityCollection(); visualizer = new import__35.BillboardVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); const time2 = import__35.JulianDate.now(); const billboard = testObject.billboard = new import__35.BillboardGraphics(); testObject.position = new import__35.ConstantProperty( new import__35.Cartesian3(1234, 5678, 9101112) ); billboard.show = new import__35.ConstantProperty(true); billboard.color = new import__35.ConstantProperty(new import__35.Color(0.5, 0.5, 0.5, 0.5)); billboard.image = new import__35.ConstantProperty("Data/Images/Blue.png"); billboard.imageSubRegion = new import__35.ConstantProperty( new import__35.BoundingRectangle(0, 0, 1, 1) ); billboard.eyeOffset = new import__35.ConstantProperty(new import__35.Cartesian3(1, 2, 3)); billboard.scale = new import__35.ConstantProperty(12.5); billboard.rotation = new import__35.ConstantProperty(1.5); billboard.alignedAxis = new import__35.ConstantProperty(import__35.Cartesian3.UNIT_Z); billboard.heightReference = new import__35.ConstantProperty( import__35.HeightReference.CLAMP_TO_GROUND ); billboard.horizontalOrigin = new import__35.ConstantProperty(import__35.HorizontalOrigin.RIGHT); billboard.verticalOrigin = new import__35.ConstantProperty(import__35.VerticalOrigin.TOP); billboard.pixelOffset = new import__35.ConstantProperty(new import__35.Cartesian2(3, 2)); billboard.width = new import__35.ConstantProperty(15); billboard.height = new import__35.ConstantProperty(5); billboard.scaleByDistance = new import__35.ConstantProperty(new import__35.NearFarScalar()); billboard.translucencyByDistance = new import__35.ConstantProperty( new import__35.NearFarScalar() ); billboard.pixelOffsetScaleByDistance = new import__35.ConstantProperty( new import__35.NearFarScalar(1, 0, 3e9, 0) ); billboard.sizeInMeters = new import__35.ConstantProperty(true); billboard.distanceDisplayCondition = new import__35.ConstantProperty( new import__35.DistanceDisplayCondition(10, 100) ); billboard.disableDepthTestDistance = new import__35.ConstantProperty(10); visualizer.update(time2); const billboardCollection = entityCluster._billboardCollection; expect(billboardCollection.length).toEqual(1); const bb = billboardCollection.get(0); return pollToPromise_default(function() { visualizer.update(time2); return bb.show; }).then(function() { expect(bb.position).toEqual(testObject.position.getValue(time2)); expect(bb.color).toEqual(testObject.billboard.color.getValue(time2)); expect(bb.eyeOffset).toEqual( testObject.billboard.eyeOffset.getValue(time2) ); expect(bb.scale).toEqual(testObject.billboard.scale.getValue(time2)); expect(bb.rotation).toEqual( testObject.billboard.rotation.getValue(time2) ); expect(bb.alignedAxis).toEqual( testObject.billboard.alignedAxis.getValue(time2) ); expect(bb.heightReference).toEqual( testObject.billboard.heightReference.getValue(time2) ); expect(bb.horizontalOrigin).toEqual( testObject.billboard.horizontalOrigin.getValue(time2) ); expect(bb.verticalOrigin).toEqual( testObject.billboard.verticalOrigin.getValue(time2) ); expect(bb.width).toEqual(testObject.billboard.width.getValue(time2)); expect(bb.height).toEqual(testObject.billboard.height.getValue(time2)); expect(bb.scaleByDistance).toEqual( testObject.billboard.scaleByDistance.getValue(time2) ); expect(bb.translucencyByDistance).toEqual( testObject.billboard.translucencyByDistance.getValue(time2) ); expect(bb.pixelOffsetScaleByDistance).toEqual( testObject.billboard.pixelOffsetScaleByDistance.getValue(time2) ); expect(bb.sizeInMeters).toEqual( testObject.billboard.sizeInMeters.getValue(time2) ); expect(bb.distanceDisplayCondition).toEqual( testObject.billboard.distanceDisplayCondition.getValue(time2) ); expect(bb.disableDepthTestDistance).toEqual( testObject.billboard.disableDepthTestDistance.getValue(time2) ); expect(bb._imageSubRegion).toEqual( testObject.billboard.imageSubRegion.getValue(time2) ); billboard.show = new import__35.ConstantProperty(false); return pollToPromise_default(function() { visualizer.update(time2); return !bb.show; }); }); }); it("Display billboard after toggling show", function() { const entityCollection = new import__35.EntityCollection(); visualizer = new import__35.BillboardVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); const time2 = import__35.JulianDate.now(); const billboard = testObject.billboard = new import__35.BillboardGraphics(); testObject.position = new import__35.ConstantProperty( new import__35.Cartesian3(1234, 5678, 9101112) ); billboard.show = new import__35.ConstantProperty(true); billboard.color = new import__35.ConstantProperty(new import__35.Color(0.5, 0.5, 0.5, 0.5)); billboard.image = new import__35.ConstantProperty("Data/Images/Blue.png"); billboard.imageSubRegion = new import__35.ConstantProperty( new import__35.BoundingRectangle(0, 0, 1, 1) ); billboard.eyeOffset = new import__35.ConstantProperty(new import__35.Cartesian3(1, 2, 3)); billboard.scale = new import__35.ConstantProperty(12.5); billboard.rotation = new import__35.ConstantProperty(1.5); billboard.alignedAxis = new import__35.ConstantProperty(import__35.Cartesian3.UNIT_Z); billboard.heightReference = new import__35.ConstantProperty( import__35.HeightReference.CLAMP_TO_GROUND ); billboard.horizontalOrigin = new import__35.ConstantProperty(import__35.HorizontalOrigin.RIGHT); billboard.verticalOrigin = new import__35.ConstantProperty(import__35.VerticalOrigin.TOP); billboard.pixelOffset = new import__35.ConstantProperty(new import__35.Cartesian2(3, 2)); billboard.width = new import__35.ConstantProperty(15); billboard.height = new import__35.ConstantProperty(5); billboard.scaleByDistance = new import__35.ConstantProperty(new import__35.NearFarScalar()); billboard.translucencyByDistance = new import__35.ConstantProperty( new import__35.NearFarScalar() ); billboard.pixelOffsetScaleByDistance = new import__35.ConstantProperty( new import__35.NearFarScalar(1, 0, 3e9, 0) ); billboard.sizeInMeters = new import__35.ConstantProperty(true); billboard.distanceDisplayCondition = new import__35.ConstantProperty( new import__35.DistanceDisplayCondition(10, 100) ); billboard.disableDepthTestDistance = new import__35.ConstantProperty(10); visualizer.update(time2); const billboardCollection = entityCluster._billboardCollection; expect(billboardCollection.length).toEqual(1); const bb = billboardCollection.get(0); return pollToPromise_default(function() { visualizer.update(time2); return bb.show; }).then(function() { billboard.show = new import__35.ConstantProperty(false); return pollToPromise_default(function() { visualizer.update(time2); return !bb.show; }).then(function() { billboard.show = new import__35.ConstantProperty(true); return pollToPromise_default(function() { visualizer.update(time2); return bb.show; }).then(function() { expect(bb.position).toEqual(testObject.position.getValue(time2)); expect(bb.color).toEqual(testObject.billboard.color.getValue(time2)); expect(bb.eyeOffset).toEqual( testObject.billboard.eyeOffset.getValue(time2) ); expect(bb.scale).toEqual(testObject.billboard.scale.getValue(time2)); expect(bb.rotation).toEqual( testObject.billboard.rotation.getValue(time2) ); expect(bb.alignedAxis).toEqual( testObject.billboard.alignedAxis.getValue(time2) ); expect(bb.heightReference).toEqual( testObject.billboard.heightReference.getValue(time2) ); expect(bb.horizontalOrigin).toEqual( testObject.billboard.horizontalOrigin.getValue(time2) ); expect(bb.verticalOrigin).toEqual( testObject.billboard.verticalOrigin.getValue(time2) ); expect(bb.width).toEqual(testObject.billboard.width.getValue(time2)); expect(bb.height).toEqual( testObject.billboard.height.getValue(time2) ); expect(bb.scaleByDistance).toEqual( testObject.billboard.scaleByDistance.getValue(time2) ); expect(bb.translucencyByDistance).toEqual( testObject.billboard.translucencyByDistance.getValue(time2) ); expect(bb.pixelOffsetScaleByDistance).toEqual( testObject.billboard.pixelOffsetScaleByDistance.getValue(time2) ); expect(bb.sizeInMeters).toEqual( testObject.billboard.sizeInMeters.getValue(time2) ); expect(bb.distanceDisplayCondition).toEqual( testObject.billboard.distanceDisplayCondition.getValue(time2) ); expect(bb.disableDepthTestDistance).toEqual( testObject.billboard.disableDepthTestDistance.getValue(time2) ); expect(bb.image).toBeDefined(); expect(bb._imageSubRegion).toEqual( testObject.billboard.imageSubRegion.getValue(time2) ); }); }); }); }); it("Reuses primitives when hiding one and showing another", function() { const time2 = import__35.JulianDate.now(); const entityCollection = new import__35.EntityCollection(); visualizer = new import__35.BillboardVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__35.ConstantProperty( new import__35.Cartesian3(1234, 5678, 9101112) ); testObject.billboard = new import__35.BillboardGraphics(); testObject.billboard.image = new import__35.ConstantProperty("Data/Images/Blue.png"); testObject.billboard.show = new import__35.ConstantProperty(true); visualizer.update(time2); const billboardCollection = entityCluster._billboardCollection; expect(billboardCollection.length).toEqual(1); testObject.billboard.show = new import__35.ConstantProperty(false); visualizer.update(time2); expect(billboardCollection.length).toEqual(1); const testObject2 = entityCollection.getOrCreateEntity("test2"); testObject2.position = new import__35.ConstantProperty( new import__35.Cartesian3(1234, 5678, 9101112) ); testObject2.billboard = new import__35.BillboardGraphics(); testObject2.billboard.image = new import__35.ConstantProperty( "Data/Images/Blue.png" ); testObject2.billboard.show = new import__35.ConstantProperty(true); visualizer.update(time2); expect(billboardCollection.length).toEqual(1); }); it("clear hides billboards.", function() { const entityCollection = new import__35.EntityCollection(); visualizer = new import__35.BillboardVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); const time2 = import__35.JulianDate.now(); const billboard = testObject.billboard = new import__35.BillboardGraphics(); testObject.position = new import__35.ConstantProperty( new import__35.Cartesian3(1234, 5678, 9101112) ); billboard.show = new import__35.ConstantProperty(true); billboard.image = new import__35.ConstantProperty("Data/Images/Blue.png"); visualizer.update(time2); const billboardCollection = entityCluster._billboardCollection; expect(billboardCollection.length).toEqual(1); const bb = billboardCollection.get(0); return pollToPromise_default(function() { visualizer.update(time2); return bb.show; }).then(function() { entityCollection.removeAll(); expect(bb.show).toEqual(false); expect(bb.id).toBeUndefined(); }); }); it("Visualizer sets entity property.", function() { const entityCollection = new import__35.EntityCollection(); visualizer = new import__35.BillboardVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); const time2 = import__35.JulianDate.now(); const billboard = testObject.billboard = new import__35.BillboardGraphics(); testObject.position = new import__35.ConstantProperty( new import__35.Cartesian3(1234, 5678, 9101112) ); billboard.show = new import__35.ConstantProperty(true); billboard.image = new import__35.ConstantProperty("Data/Images/Blue.png"); visualizer.update(time2); const billboardCollection = entityCluster._billboardCollection; expect(billboardCollection.length).toEqual(1); const bb = billboardCollection.get(0); expect(bb.id).toEqual(testObject); }); it("Computes bounding sphere.", function() { const entityCollection = new import__35.EntityCollection(); visualizer = new import__35.BillboardVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); const time2 = import__35.JulianDate.now(); const billboard = testObject.billboard = new import__35.BillboardGraphics(); testObject.position = new import__35.ConstantProperty( new import__35.Cartesian3(1234, 5678, 9101112) ); billboard.show = new import__35.ConstantProperty(true); billboard.image = new import__35.ConstantProperty("Data/Images/Blue.png"); visualizer.update(time2); const result = new import__35.BoundingSphere(); const state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__35.BoundingSphereState.DONE); expect(result.center).toEqual(testObject.position.getValue()); expect(result.radius).toEqual(0); }); it("Fails bounding sphere for entity without billboard.", function() { const entityCollection = new import__35.EntityCollection(); const testObject = entityCollection.getOrCreateEntity("test"); visualizer = new import__35.BillboardVisualizer(entityCluster, entityCollection); visualizer.update(import__35.JulianDate.now()); const result = new import__35.BoundingSphere(); const state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__35.BoundingSphereState.FAILED); }); it("Compute bounding sphere throws without entity.", function() { const entityCollection = new import__35.EntityCollection(); visualizer = new import__35.BillboardVisualizer(entityCluster, entityCollection); const result = new import__35.BoundingSphere(); expect(function() { visualizer.getBoundingSphere(void 0, result); }).toThrowDeveloperError(); }); it("Compute bounding sphere throws without result.", function() { const entityCollection = new import__35.EntityCollection(); const testObject = entityCollection.getOrCreateEntity("test"); visualizer = new import__35.BillboardVisualizer(entityCluster, entityCollection); expect(function() { visualizer.getBoundingSphere(testObject, void 0); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/DataSources/BoxGeometryUpdaterSpec.js var import__36 = __toESM(require_Cesium(), 1); // Specs/createDynamicGeometryUpdaterSpecs.js var import_engine10 = __toESM(require_Cesium(), 1); // Specs/createDynamicProperty.js var import_engine9 = __toESM(require_Cesium(), 1); function createDynamicProperty(value) { const property = new import_engine9.ConstantProperty(value); Object.defineProperties(property, { isConstant: { value: false } }); return property; } var createDynamicProperty_default = createDynamicProperty; // Specs/createDynamicGeometryUpdaterSpecs.js function createDynamicGeometryUpdaterSpecs(Updater, geometryPropertyName, createDynamicEntity, getScene) { const time2 = import_engine10.JulianDate.now(); it("dynamic updater sets properties", function() { if (Updater === import_engine10.EllipsoidGeometryUpdater) { return; } const entity = createDynamicEntity(); const geometry = entity[geometryPropertyName]; geometry.show = createDynamicProperty_default(true); geometry.outline = createDynamicProperty_default(true); geometry.fill = createDynamicProperty_default(true); const updater = new Updater(entity, getScene()); const primitives = new import_engine10.PrimitiveCollection(); const groundPrimitives = new import_engine10.PrimitiveCollection(); const dynamicUpdater = updater.createDynamicUpdater( primitives, groundPrimitives ); expect(primitives.length).toBe(0); expect(groundPrimitives.length).toBe(0); dynamicUpdater.update(import_engine10.JulianDate.now()); expect(primitives.length).toBe(2); expect(groundPrimitives.length).toBe(0); expect(dynamicUpdater.isDestroyed()).toBe(false); expect(dynamicUpdater._options.id).toBe(entity); entity.show = false; updater._onEntityPropertyChanged(entity, "show"); dynamicUpdater.update(import_engine10.JulianDate.now()); expect(primitives.length).toBe(0); entity.show = true; updater._onEntityPropertyChanged(entity, "show"); geometry.show.setValue(false); updater._onEntityPropertyChanged(entity, "box"); dynamicUpdater.update(import_engine10.JulianDate.now()); expect(primitives.length).toBe(0); geometry.show.setValue(true); geometry.fill.setValue(false); updater._onEntityPropertyChanged(entity, "box"); dynamicUpdater.update(import_engine10.JulianDate.now()); expect(primitives.length).toBe(1); geometry.fill.setValue(true); geometry.outline.setValue(false); updater._onEntityPropertyChanged(entity, "box"); dynamicUpdater.update(import_engine10.JulianDate.now()); expect(primitives.length).toBe(1); dynamicUpdater.destroy(); expect(primitives.length).toBe(0); updater.destroy(); }); it("Computes dynamic geometry bounding sphere for fill.", function() { const scene2 = getScene(); const entity = createDynamicEntity(); const geometry = entity[geometryPropertyName]; const updater = new Updater(entity, scene2); geometry.fill = true; geometry.outline = false; updater._onEntityPropertyChanged(entity, updater._geometryPropertyName); const dynamicUpdater = updater.createDynamicUpdater( scene2.primitives, scene2.groundPrimitives ); dynamicUpdater.update(time2); let state2; const result = new import_engine10.BoundingSphere(); return pollToPromise_default(function() { scene2.initializeFrame(); scene2.render(); state2 = dynamicUpdater.getBoundingSphere(result); return state2 !== import_engine10.BoundingSphereState.PENDING; }).then(function() { const primitive = scene2.primitives.get(0); expect(state2).toBe(import_engine10.BoundingSphereState.DONE); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(result).toEqualEpsilon( attributes.boundingSphere, import_engine10.Math.EPSILON6 ); updater.destroy(); scene2.primitives.removeAll(); }); }); it("Computes dynamic geometry bounding sphere for outline.", function() { const scene2 = getScene(); const entity = createDynamicEntity(); const geometry = entity[geometryPropertyName]; const updater = new Updater(entity, scene2); geometry.fill = false; geometry.outline = true; updater._onEntityPropertyChanged(entity, updater._geometryPropertyName); const dynamicUpdater = updater.createDynamicUpdater( scene2.primitives, scene2.groundPrimitives ); dynamicUpdater.update(time2); let state2; const result = new import_engine10.BoundingSphere(); return pollToPromise_default(function() { scene2.initializeFrame(); scene2.render(); state2 = dynamicUpdater.getBoundingSphere(result); return state2 !== import_engine10.BoundingSphereState.PENDING; }).then(function() { const primitive = scene2.primitives.get(0); expect(state2).toBe(import_engine10.BoundingSphereState.DONE); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(result).toEqualEpsilon( attributes.boundingSphere, import_engine10.Math.EPSILON6 ); updater.destroy(); scene2.primitives.removeAll(); }); }); it("Compute dynamic geometry bounding sphere throws without result.", function() { const scene2 = getScene(); const entity = createDynamicEntity(); const updater = new Updater(entity, scene2); const dynamicUpdater = updater.createDynamicUpdater( scene2.primitives, scene2.groundPrimitives ); expect(function() { dynamicUpdater.getBoundingSphere(void 0); }).toThrowDeveloperError(); updater.destroy(); scene2.primitives.removeAll(); }); } var createDynamicGeometryUpdaterSpecs_default = createDynamicGeometryUpdaterSpecs; // Specs/createGeometryUpdaterSpecs.js var import_engine11 = __toESM(require_Cesium(), 1); function createGeometryUpdaterSpecs(Updater, geometryPropertyName, createEntity, getScene) { const time2 = import_engine11.JulianDate.now(); it("Constructor sets expected defaults", function() { const entity = createEntity(); const updater = new Updater(entity, getScene()); expect(updater.isDestroyed()).toBe(false); expect(updater.entity).toBe(entity); expect(updater.isClosed).toBe(updater._getIsClosed(updater._options)); expect(updater.fillEnabled).toBe(true); expect(updater.fillMaterialProperty).toBeInstanceOf(import_engine11.ColorMaterialProperty); expect(updater.outlineEnabled).toBe(false); expect(updater.hasConstantFill).toBe(true); expect(updater.hasConstantOutline).toBe(true); expect(updater.outlineColorProperty).toBe(void 0); expect(updater.outlineWidth).toBe(1); expect(updater.shadowsProperty.getValue()).toBe(import_engine11.ShadowMode.DISABLED); expect(updater.distanceDisplayConditionProperty.getValue()).toEqual( new import_engine11.DistanceDisplayCondition() ); expect(updater.isDynamic).toBe(false); expect(updater.onTerrain).toBe(false); expect(updater.isOutlineVisible(time2)).toBe(false); expect(updater.isFilled(time2)).toBe(true); updater.destroy(); expect(updater.isDestroyed()).toBe(true); }); it("No geometry created when entity geometry property is undefined ", function() { const entity = new import_engine11.Entity(); const updater = new Updater(entity, getScene()); expect(updater.fillEnabled).toBe(false); expect(updater.outlineEnabled).toBe(false); expect(updater.isDynamic).toBe(false); }); it("No geometry available when not filled or outline.", function() { const entity = createEntity(); entity[geometryPropertyName].fill = new import_engine11.ConstantProperty(false); entity[geometryPropertyName].outline = new import_engine11.ConstantProperty(false); const updater = new Updater(entity, getScene()); expect(updater.fillEnabled).toBe(false); expect(updater.outlineEnabled).toBe(false); expect(updater.isDynamic).toBe(false); }); it("Values correct when using default graphics", function() { const entity = createEntity(); const updater = new Updater(entity, getScene()); expect(updater.isClosed).toBe(updater._getIsClosed(updater._options)); expect(updater.fillEnabled).toBe(true); expect(updater.fillMaterialProperty).toEqual( new import_engine11.ColorMaterialProperty(import_engine11.Color.WHITE) ); expect(updater.outlineEnabled).toBe(false); expect(updater.hasConstantFill).toBe(true); expect(updater.hasConstantOutline).toBe(true); expect(updater.outlineColorProperty).toBe(void 0); expect(updater.outlineWidth).toBe(1); expect(updater.shadowsProperty).toEqual( new import_engine11.ConstantProperty(import_engine11.ShadowMode.DISABLED) ); expect(updater.distanceDisplayConditionProperty).toEqual( new import_engine11.ConstantProperty(new import_engine11.DistanceDisplayCondition()) ); expect(updater.isDynamic).toBe(false); }); it("material is correctly exposed.", function() { const entity = createEntity(); entity[geometryPropertyName].material = new import_engine11.GridMaterialProperty( import_engine11.Color.BLUE ); const updater = new Updater(entity, getScene()); expect(updater.fillMaterialProperty).toBe( entity[geometryPropertyName].material ); }); it("A time-varying outlineWidth causes geometry to be dynamic", function() { const entity = createEntity(); entity[geometryPropertyName].outlineWidth = new import_engine11.SampledProperty(Number); entity[geometryPropertyName].outlineWidth.addSample(time2, 1); const updater = new Updater(entity, getScene()); expect(updater.isDynamic).toBe(true); }); it("Correctly exposes outlineWidth", function() { const entity = createEntity(); entity[geometryPropertyName].outlineWidth = new import_engine11.ConstantProperty(8); const updater = new Updater(entity, getScene()); expect(updater.outlineWidth).toBe(8); }); it("Attributes have expected values at creation time", function() { const time1 = new import_engine11.JulianDate(0, 0); const time22 = new import_engine11.JulianDate(10, 0); const time3 = new import_engine11.JulianDate(20, 0); const fill = new import_engine11.TimeIntervalCollectionProperty(); fill.intervals.addInterval( new import_engine11.TimeInterval({ start: time1, stop: time22, data: false }) ); fill.intervals.addInterval( new import_engine11.TimeInterval({ start: time22, stop: time3, isStartIncluded: false, data: true }) ); const colorMaterial = new import_engine11.ColorMaterialProperty(); colorMaterial.color = new import_engine11.SampledProperty(import_engine11.Color); colorMaterial.color.addSample(time2, import_engine11.Color.YELLOW); colorMaterial.color.addSample(time22, import_engine11.Color.BLUE); colorMaterial.color.addSample(time3, import_engine11.Color.RED); const outline = new import_engine11.TimeIntervalCollectionProperty(); outline.intervals.addInterval( new import_engine11.TimeInterval({ start: time1, stop: time22, data: false }) ); outline.intervals.addInterval( new import_engine11.TimeInterval({ start: time22, stop: time3, isStartIncluded: false, data: true }) ); const outlineColor = new import_engine11.SampledProperty(import_engine11.Color); outlineColor.addSample(time2, import_engine11.Color.BLUE); outlineColor.addSample(time22, import_engine11.Color.RED); outlineColor.addSample(time3, import_engine11.Color.YELLOW); const entity = createEntity(); entity[geometryPropertyName].fill = fill; entity[geometryPropertyName].material = colorMaterial; entity[geometryPropertyName].outline = outline; entity[geometryPropertyName].outlineColor = outlineColor; const updater = new Updater(entity, getScene()); let instance = updater.createFillGeometryInstance(time22); let attributes = instance.attributes; expect(attributes.color.value).toEqual( import_engine11.ColorGeometryInstanceAttribute.toValue( colorMaterial.color.getValue(time22) ) ); expect(attributes.show.value).toEqual( import_engine11.ShowGeometryInstanceAttribute.toValue(fill.getValue(time22)) ); instance = updater.createOutlineGeometryInstance(time22); attributes = instance.attributes; expect(attributes.color.value).toEqual( import_engine11.ColorGeometryInstanceAttribute.toValue(outlineColor.getValue(time22)) ); expect(attributes.show.value).toEqual( import_engine11.ShowGeometryInstanceAttribute.toValue(outline.getValue(time22)) ); }); it("createFillGeometryInstance obeys Entity.show is false.", function() { const entity = createEntity(); entity.show = false; entity[geometryPropertyName].fill = true; const updater = new Updater(entity, getScene()); const instance = updater.createFillGeometryInstance(new import_engine11.JulianDate()); const attributes = instance.attributes; expect(attributes.show.value).toEqual( import_engine11.ShowGeometryInstanceAttribute.toValue(false) ); }); it("createOutlineGeometryInstance obeys Entity.show is false.", function() { const entity = createEntity(); entity.show = false; entity[geometryPropertyName].outline = true; const updater = new Updater(entity, getScene()); const instance = updater.createFillGeometryInstance(new import_engine11.JulianDate()); const attributes = instance.attributes; expect(attributes.show.value).toEqual( import_engine11.ShowGeometryInstanceAttribute.toValue(false) ); }); it("createFillGeometryInstance throws if object is not filled", function() { if (Updater === import_engine11.EllipsoidGeometryUpdater) { return; } const entity = new import_engine11.Entity(); const updater = new Updater(entity, getScene()); expect(function() { return updater.createFillGeometryInstance(time2); }).toThrowDeveloperError(); }); it("createFillGeometryInstance throws if no time provided", function() { const entity = createEntity(); const updater = new Updater(entity, getScene()); expect(function() { return updater.createFillGeometryInstance(void 0); }).toThrowDeveloperError(); }); it("createOutlineGeometryInstance throws if object is not outlined", function() { if (Updater === import_engine11.EllipsoidGeometryUpdater) { return; } const entity = new import_engine11.Entity(); const updater = new Updater(entity, getScene()); expect(function() { return updater.createOutlineGeometryInstance(time2); }).toThrowDeveloperError(); }); it("createOutlineGeometryInstance throws if no time provided", function() { const entity = createEntity(); entity[geometryPropertyName].outline = new import_engine11.ConstantProperty(true); const updater = new Updater(entity, getScene()); expect(function() { return updater.createOutlineGeometryInstance(void 0); }).toThrowDeveloperError(); }); function validateGeometryInstanceAttributes(options) { const entity = createEntity(); const geometryProperty = entity[geometryPropertyName]; geometryProperty.show = true; geometryProperty.fill = true; geometryProperty.material = options.material; geometryProperty.outline = true; geometryProperty.outlineColor = new import_engine11.ConstantProperty(options.outlineColor); geometryProperty.distanceDisplayCondition = options.distanceDisplayCondition; const updater = new Updater(entity, getScene()); let instance; let attributes; instance = updater.createFillGeometryInstance(time2); attributes = instance.attributes; if (options.material instanceof import_engine11.ColorMaterialProperty) { expect(attributes.color.value).toEqual( import_engine11.ColorGeometryInstanceAttribute.toValue( options.material.color.getValue(time2) ) ); } else { expect(attributes.color).toBeUndefined(); } expect(attributes.show.value).toEqual( import_engine11.ShowGeometryInstanceAttribute.toValue(true) ); if (options.distanceDisplayCondition) { expect(attributes.distanceDisplayCondition.value).toEqual( import_engine11.DistanceDisplayConditionGeometryInstanceAttribute.toValue( options.distanceDisplayCondition ) ); } instance = updater.createOutlineGeometryInstance(time2); attributes = instance.attributes; expect(attributes.color.value).toEqual( import_engine11.ColorGeometryInstanceAttribute.toValue(options.outlineColor) ); expect(attributes.show.value).toEqual( import_engine11.ShowGeometryInstanceAttribute.toValue(true) ); if (options.distanceDisplayCondition) { expect(attributes.distanceDisplayCondition.value).toEqual( import_engine11.DistanceDisplayConditionGeometryInstanceAttribute.toValue( options.distanceDisplayCondition ) ); } } it("Creates expected per-color geometry", function() { validateGeometryInstanceAttributes({ material: new import_engine11.ColorMaterialProperty(import_engine11.Color.RED), outlineColor: import_engine11.Color.BLUE }); }); it("Creates expected per-material geometry", function() { validateGeometryInstanceAttributes({ material: new import_engine11.GridMaterialProperty(), outlineColor: import_engine11.Color.GREEN }); }); it("Creates expected distance display condition geometry", function() { validateGeometryInstanceAttributes({ material: new import_engine11.ColorMaterialProperty(import_engine11.Color.BLUE), outlineColor: import_engine11.Color.RED, distanceDisplayCondition: new import_engine11.DistanceDisplayCondition(10, 100) }); }); it("Attributes have expected values at creation time", function() { const time1 = new import_engine11.JulianDate(0, 0); const time22 = new import_engine11.JulianDate(10, 0); const time3 = new import_engine11.JulianDate(20, 0); const fill = new import_engine11.TimeIntervalCollectionProperty(); fill.intervals.addInterval( new import_engine11.TimeInterval({ start: time1, stop: time22, data: false }) ); fill.intervals.addInterval( new import_engine11.TimeInterval({ start: time22, stop: time3, isStartIncluded: false, data: true }) ); const colorMaterial = new import_engine11.ColorMaterialProperty(); colorMaterial.color = new import_engine11.SampledProperty(import_engine11.Color); colorMaterial.color.addSample(time2, import_engine11.Color.YELLOW); colorMaterial.color.addSample(time22, import_engine11.Color.BLUE); colorMaterial.color.addSample(time3, import_engine11.Color.RED); const outline = new import_engine11.TimeIntervalCollectionProperty(); outline.intervals.addInterval( new import_engine11.TimeInterval({ start: time1, stop: time22, data: false }) ); outline.intervals.addInterval( new import_engine11.TimeInterval({ start: time22, stop: time3, isStartIncluded: false, data: true }) ); const outlineColor = new import_engine11.SampledProperty(import_engine11.Color); outlineColor.addSample(time2, import_engine11.Color.BLUE); outlineColor.addSample(time22, import_engine11.Color.RED); outlineColor.addSample(time3, import_engine11.Color.YELLOW); const entity = createEntity(); const geoemtry = entity[geometryPropertyName]; geoemtry.fill = fill; geoemtry.material = colorMaterial; geoemtry.outline = outline; geoemtry.outlineColor = outlineColor; const updater = new Updater(entity, getScene()); let instance = updater.createFillGeometryInstance(time22); let attributes = instance.attributes; expect(attributes.color.value).toEqual( import_engine11.ColorGeometryInstanceAttribute.toValue( colorMaterial.color.getValue(time22) ) ); expect(attributes.show.value).toEqual( import_engine11.ShowGeometryInstanceAttribute.toValue(fill.getValue(time22)) ); instance = updater.createOutlineGeometryInstance(time22); attributes = instance.attributes; expect(attributes.color.value).toEqual( import_engine11.ColorGeometryInstanceAttribute.toValue(outlineColor.getValue(time22)) ); expect(attributes.show.value).toEqual( import_engine11.ShowGeometryInstanceAttribute.toValue(outline.getValue(time22)) ); }); it("Works with dynamic color with missing interval", function() { const time1 = new import_engine11.JulianDate(0, 0); const time22 = new import_engine11.JulianDate(10, 0); const missingTime = new import_engine11.JulianDate(15, 0); const time3 = new import_engine11.JulianDate(20, 0); const time4 = new import_engine11.JulianDate(30, 0); const colorMaterial = new import_engine11.ColorMaterialProperty(); const color = new import_engine11.TimeIntervalCollectionProperty(); color.intervals.addInterval( new import_engine11.TimeInterval({ start: time1, stop: time22, data: import_engine11.Color.BLUE }) ); color.intervals.addInterval( new import_engine11.TimeInterval({ start: time3, stop: time4, isStartIncluded: false, data: import_engine11.Color.YELLOW }) ); colorMaterial.color = color; const outlineColor = new import_engine11.TimeIntervalCollectionProperty(); outlineColor.intervals.addInterval( new import_engine11.TimeInterval({ start: time1, stop: time22, data: import_engine11.Color.RED }) ); outlineColor.intervals.addInterval( new import_engine11.TimeInterval({ start: time3, stop: time4, isStartIncluded: false, data: import_engine11.Color.GREEN }) ); const entity = createEntity(); const geometry = entity[geometryPropertyName]; geometry.fill = true; geometry.outline = true; geometry.material = colorMaterial; geometry.outlineColor = outlineColor; const updater = new Updater(entity, getScene()); let instance = updater.createFillGeometryInstance(missingTime); let attributes = instance.attributes; expect(attributes.color.value).toEqual( import_engine11.ColorGeometryInstanceAttribute.toValue(import_engine11.Color.WHITE) ); instance = updater.createOutlineGeometryInstance(missingTime); attributes = instance.attributes; expect(attributes.color.value).toEqual( import_engine11.ColorGeometryInstanceAttribute.toValue(import_engine11.Color.BLACK) ); }); } var createGeometryUpdaterSpecs_default = createGeometryUpdaterSpecs; // packages/engine/Specs/DataSources/BoxGeometryUpdaterSpec.js describe( "DataSources/BoxGeometryUpdater", function() { let scene2; let time2; beforeAll(function() { scene2 = createScene_default(); time2 = import__36.JulianDate.now(); }); afterAll(function() { scene2.destroyForSpecs(); }); function createBasicBox() { const box = new import__36.BoxGraphics(); box.dimensions = new import__36.ConstantProperty(new import__36.Cartesian3(1, 2, 3)); const entity = new import__36.Entity(); entity.position = new import__36.ConstantPositionProperty( import__36.Cartesian3.fromDegrees(0, 0, 0) ); entity.box = box; return entity; } function createDynamicBox() { const entity = createBasicBox(); entity.box.dimensions = createDynamicProperty_default(new import__36.Cartesian3(1, 2, 3)); return entity; } it("A time-varying dimensions causes geometry to be dynamic", function() { const entity = createBasicBox(); const updater = new import__36.BoxGeometryUpdater(entity, scene2); entity.box.dimensions = createDynamicProperty_default(); updater._onEntityPropertyChanged(entity, "box"); expect(updater.isDynamic).toBe(true); }); it("Creates geometry with expected properties", function() { const entity = createBasicBox(); const dimensions = new import__36.Cartesian3(1, 2, 3); const box = entity.box; box.outline = true; box.dimensions = dimensions; const updater = new import__36.BoxGeometryUpdater(entity, scene2); let instance; let geometry; instance = updater.createFillGeometryInstance(time2); geometry = instance.geometry; expect(geometry._maximum).toEqual( import__36.Cartesian3.multiplyByScalar(dimensions, 0.5, new import__36.Cartesian3()) ); expect(geometry._offsetAttribute).toBeUndefined(); instance = updater.createOutlineGeometryInstance(time2); geometry = instance.geometry; expect(geometry._max).toEqual( import__36.Cartesian3.multiplyByScalar(dimensions, 0.5, new import__36.Cartesian3()) ); expect(geometry._offsetAttribute).toBeUndefined(); }); it("Creates geometry with expected offsetAttribute", function() { const entity = createBasicBox(); const graphics = entity.box; graphics.outline = true; graphics.outlineColor = import__36.Color.BLACK; graphics.height = new import__36.ConstantProperty(20); graphics.extrudedHeight = new import__36.ConstantProperty(0); const updater = new import__36.BoxGeometryUpdater(entity, getScene()); let instance; updater._onEntityPropertyChanged(entity, "box"); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); graphics.heightReference = new import__36.ConstantProperty(import__36.HeightReference.NONE); updater._onEntityPropertyChanged(entity, "box"); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); graphics.heightReference = new import__36.ConstantProperty( import__36.HeightReference.CLAMP_TO_GROUND ); updater._onEntityPropertyChanged(entity, "box"); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import__36.GeometryOffsetAttribute.ALL ); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import__36.GeometryOffsetAttribute.ALL ); graphics.heightReference = new import__36.ConstantProperty( import__36.HeightReference.RELATIVE_TO_GROUND ); updater._onEntityPropertyChanged(entity, "box"); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import__36.GeometryOffsetAttribute.ALL ); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import__36.GeometryOffsetAttribute.ALL ); }); it("dynamic updater sets properties", function() { const entity = createDynamicBox(); const updater = new import__36.BoxGeometryUpdater(entity, scene2); const dynamicUpdater = updater.createDynamicUpdater( new import__36.PrimitiveCollection(), new import__36.PrimitiveCollection() ); dynamicUpdater.update(import__36.JulianDate.now()); expect(dynamicUpdater._options.dimensions).toEqual( entity.box.dimensions.getValue() ); expect(dynamicUpdater._options.offsetAttribute).toBeUndefined(); }); it("geometryChanged event is raised when expected", function() { const entity = createBasicBox(); const updater = new import__36.BoxGeometryUpdater(entity, scene2); const listener = jasmine.createSpy("listener"); updater.geometryChanged.addEventListener(listener); entity.box.dimensions = new import__36.ConstantProperty(); updater._onEntityPropertyChanged(entity, "box"); expect(listener.calls.count()).toEqual(1); entity.availability = new import__36.TimeIntervalCollection(); updater._onEntityPropertyChanged(entity, "availability"); expect(listener.calls.count()).toEqual(2); entity.box.dimensions = void 0; updater._onEntityPropertyChanged(entity, "box"); expect(listener.calls.count()).toEqual(3); entity.box.height = void 0; updater._onEntityPropertyChanged(entity, "box"); entity.viewFrom = new import__36.ConstantProperty(import__36.Cartesian3.UNIT_X); updater._onEntityPropertyChanged(entity, "viewFrom"); expect(listener.calls.count()).toEqual(3); }); it("computes center", function() { const entity = createBasicBox(); const updater = new import__36.BoxGeometryUpdater(entity, scene2); expect(updater._computeCenter(time2)).toEqual( entity.position.getValue(time2) ); }); function getScene() { return scene2; } createGeometryUpdaterSpecs_default( import__36.BoxGeometryUpdater, "box", createBasicBox, getScene ); createDynamicGeometryUpdaterSpecs_default( import__36.BoxGeometryUpdater, "box", createDynamicBox, getScene ); }, "WebGL" ); // packages/engine/Specs/DataSources/BoxGraphicsSpec.js var import__37 = __toESM(require_Cesium(), 1); // Specs/testDefinitionChanged.js var import_engine12 = __toESM(require_Cesium(), 1); function testDefinitionChanged(property, name, value1, value2) { const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); const oldValue = property[name]; property[name] = new import_engine12.ConstantProperty(value1); expect(listener).toHaveBeenCalledWith( property, name, property[name], oldValue ); listener.calls.reset(); property[name].setValue(value2); expect(listener).toHaveBeenCalledWith( property, name, property[name], property[name] ); listener.calls.reset(); property[name] = property[name]; expect(listener.calls.count()).toEqual(0); } var testDefinitionChanged_default = testDefinitionChanged; // Specs/testMaterialDefinitionChanged.js var import_engine13 = __toESM(require_Cesium(), 1); function testMaterialDefinitionChanged(property, name, value1, value2) { const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); const oldValue = property[name]; property[name] = new import_engine13.ColorMaterialProperty(value1); expect(listener).toHaveBeenCalledWith( property, name, property[name], oldValue ); listener.calls.reset(); property[name].color.setValue(value2); expect(listener).toHaveBeenCalledWith( property, name, property[name], property[name] ); listener.calls.reset(); property[name] = property[name]; expect(listener.calls.count()).toEqual(0); } var testMaterialDefinitionChanged_default = testMaterialDefinitionChanged; // packages/engine/Specs/DataSources/BoxGraphicsSpec.js describe("DataSources/BoxGraphics", function() { it("creates expected instance from raw assignment and construction", function() { const options = { material: import__37.Color.BLUE, show: true, fill: false, outline: false, outlineColor: import__37.Color.RED, outlineWidth: 1, dimensions: new import__37.Cartesian3(2, 3, 4), shadows: import__37.ShadowMode.DISABLED, distanceDisplayCondition: new import__37.DistanceDisplayCondition(10, 100) }; const box = new import__37.BoxGraphics(options); expect(box.material).toBeInstanceOf(import__37.ColorMaterialProperty); expect(box.show).toBeInstanceOf(import__37.ConstantProperty); expect(box.fill).toBeInstanceOf(import__37.ConstantProperty); expect(box.outline).toBeInstanceOf(import__37.ConstantProperty); expect(box.outlineColor).toBeInstanceOf(import__37.ConstantProperty); expect(box.outlineWidth).toBeInstanceOf(import__37.ConstantProperty); expect(box.dimensions).toBeInstanceOf(import__37.ConstantProperty); expect(box.shadows).toBeInstanceOf(import__37.ConstantProperty); expect(box.distanceDisplayCondition).toBeInstanceOf(import__37.ConstantProperty); expect(box.material.color.getValue()).toEqual(options.material); expect(box.show.getValue()).toEqual(options.show); expect(box.fill.getValue()).toEqual(options.fill); expect(box.outline.getValue()).toEqual(options.outline); expect(box.outlineColor.getValue()).toEqual(options.outlineColor); expect(box.outlineWidth.getValue()).toEqual(options.outlineWidth); expect(box.dimensions.getValue()).toEqual(options.dimensions); expect(box.shadows.getValue()).toEqual(options.shadows); expect(box.distanceDisplayCondition.getValue()).toEqual( options.distanceDisplayCondition ); }); it("merge assigns unassigned properties", function() { const source = new import__37.BoxGraphics(); source.material = new import__37.ColorMaterialProperty(); source.show = new import__37.ConstantProperty(); source.fill = new import__37.ConstantProperty(); source.outline = new import__37.ConstantProperty(); source.outlineColor = new import__37.ConstantProperty(); source.outlineWidth = new import__37.ConstantProperty(); source.dimensions = new import__37.ConstantProperty(); source.shadows = new import__37.ConstantProperty(import__37.ShadowMode.ENABLED); source.distanceDisplayCondition = new import__37.ConstantProperty( new import__37.DistanceDisplayCondition(10, 100) ); const target = new import__37.BoxGraphics(); target.merge(source); expect(target.material).toBe(source.material); expect(target.show).toBe(source.show); expect(target.fill).toBe(source.fill); expect(target.outline).toBe(source.outline); expect(target.outlineColor).toBe(source.outlineColor); expect(target.outlineWidth).toBe(source.outlineWidth); expect(target.dimensions).toBe(source.dimensions); expect(target.shadows).toBe(source.shadows); expect(target.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); }); it("merge does not assign assigned properties", function() { const source = new import__37.BoxGraphics(); const material = new import__37.ColorMaterialProperty(); const show = new import__37.ConstantProperty(); const fill = new import__37.ConstantProperty(); const outline = new import__37.ConstantProperty(); const outlineColor = new import__37.ConstantProperty(); const outlineWidth = new import__37.ConstantProperty(); const dimensions = new import__37.ConstantProperty(); const shadows = new import__37.ConstantProperty(); const distanceDisplayCondition = new import__37.ConstantProperty(); const target = new import__37.BoxGraphics(); target.material = material; target.show = show; target.fill = fill; target.outline = outline; target.outlineColor = outlineColor; target.outlineWidth = outlineWidth; target.dimensions = dimensions; target.shadows = shadows; target.distanceDisplayCondition = distanceDisplayCondition; target.merge(source); expect(target.material).toBe(material); expect(target.show).toBe(show); expect(target.fill).toBe(fill); expect(target.outline).toBe(outline); expect(target.outlineColor).toBe(outlineColor); expect(target.outlineWidth).toBe(outlineWidth); expect(target.dimensions).toBe(dimensions); expect(target.shadows).toBe(shadows); expect(target.distanceDisplayCondition).toBe(distanceDisplayCondition); }); it("clone works", function() { const source = new import__37.BoxGraphics(); source.material = new import__37.ColorMaterialProperty(); source.show = new import__37.ConstantProperty(); source.fill = new import__37.ConstantProperty(); source.outline = new import__37.ConstantProperty(); source.outlineColor = new import__37.ConstantProperty(); source.outlineWidth = new import__37.ConstantProperty(); source.dimensions = new import__37.ConstantProperty(); source.shadows = new import__37.ConstantProperty(); source.distanceDisplayCondition = new import__37.ConstantProperty(); const result = source.clone(); expect(result.material).toBe(source.material); expect(result.show).toBe(source.show); expect(result.fill).toBe(source.fill); expect(result.outline).toBe(source.outline); expect(result.outlineColor).toBe(source.outlineColor); expect(result.outlineWidth).toBe(source.outlineWidth); expect(result.dimensions).toBe(source.dimensions); expect(result.shadows).toBe(source.shadows); expect(result.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); }); it("merge throws if source undefined", function() { const target = new import__37.BoxGraphics(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__37.BoxGraphics(); testMaterialDefinitionChanged_default(property, "material", import__37.Color.RED, import__37.Color.BLUE); testDefinitionChanged_default(property, "show", true, false); testDefinitionChanged_default(property, "fill", false, true); testDefinitionChanged_default(property, "outline", true, false); testDefinitionChanged_default(property, "outlineColor", import__37.Color.RED, import__37.Color.BLUE); testDefinitionChanged_default(property, "outlineWidth", 2, 3); testDefinitionChanged_default( property, "dimensions", new import__37.Cartesian3(0, 0, 0), new import__37.Cartesian3(1, 1, 1) ); testDefinitionChanged_default( property, "shadows", import__37.ShadowMode.ENABLED, import__37.ShadowMode.DISABLED ); testDefinitionChanged_default( property, "distanceDisplayCondition", new import__37.DistanceDisplayCondition(), new import__37.DistanceDisplayCondition(10, 100) ); }); }); // packages/engine/Specs/DataSources/CallbackPropertySpec.js var import__38 = __toESM(require_Cesium(), 1); describe("DataSources/CallbackProperty", function() { const time2 = import__38.JulianDate.now(); it("callback received proper parameters", function() { const result = {}; const callback = jasmine.createSpy("callback"); const property = new import__38.CallbackProperty(callback, true); property.getValue(time2, result); expect(callback).toHaveBeenCalledWith(time2, result); }); it("getValue returns callback result", function() { const result = {}; const callback = function(time3, result2) { return result2; }; const property = new import__38.CallbackProperty(callback, true); expect(property.getValue(time2, result)).toBe(result); }); it("isConstant returns correct value", function() { const property = new import__38.CallbackProperty(function() { }, true); expect(property.isConstant).toBe(true); property.setCallback(function() { }, false); expect(property.isConstant).toBe(false); }); it("setCallback raises definitionChanged event", function() { const property = new import__38.CallbackProperty(function() { }, true); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.setCallback(function() { }, false); expect(listener).toHaveBeenCalledWith(property); }); it("constructor throws with undefined isConstant", function() { expect(function() { return new import__38.CallbackProperty(function() { }, void 0); }).toThrowDeveloperError(); }); it("constructor throws with undefined callback", function() { expect(function() { return new import__38.CallbackProperty(void 0, true); }).toThrowDeveloperError(); }); it("equals works", function() { const callback = function() { }; const left = new import__38.CallbackProperty(callback, true); const right = new import__38.CallbackProperty(callback, true); expect(left.equals(right)).toEqual(true); right.setCallback(callback, false); expect(left.equals(right)).toEqual(false); right.setCallback(function() { return void 0; }, true); expect(left.equals(right)).toEqual(false); }); }); // packages/engine/Specs/DataSources/Cesium3DTilesetGraphicsSpec.js var import__39 = __toESM(require_Cesium(), 1); describe("DataSources/Cesium3DTilesetGraphics", function() { it("creates expected instance from raw assignment and construction", function() { const options = { uri: "0", show: false, maximumScreenSpaceError: 2 }; const model = new import__39.Cesium3DTilesetGraphics(options); expect(model.uri).toBeInstanceOf(import__39.ConstantProperty); expect(model.show).toBeInstanceOf(import__39.ConstantProperty); expect(model.maximumScreenSpaceError).toBeInstanceOf(import__39.ConstantProperty); expect(model.uri.getValue()).toEqual(options.uri); expect(model.show.getValue()).toEqual(options.show); expect(model.maximumScreenSpaceError.getValue()).toEqual( options.maximumScreenSpaceError ); }); it("merge assigns unassigned properties", function() { const source = new import__39.Cesium3DTilesetGraphics(); source.uri = new import__39.ConstantProperty(""); source.show = new import__39.ConstantProperty(true); source.maximumScreenSpaceError = new import__39.ConstantProperty(2); const target = new import__39.Cesium3DTilesetGraphics(); target.merge(source); expect(target.uri).toBe(source.uri); expect(target.show).toBe(source.show); expect(target.maximumScreenSpaceError).toBe(source.maximumScreenSpaceError); }); it("merge does not assign assigned properties", function() { const source = new import__39.Cesium3DTilesetGraphics(); source.uri = new import__39.ConstantProperty(""); source.show = new import__39.ConstantProperty(true); source.maximumScreenSpaceError = new import__39.ConstantProperty(2); const uri = new import__39.ConstantProperty(""); const show = new import__39.ConstantProperty(true); const maximumScreenSpaceError = new import__39.ConstantProperty(2); const target = new import__39.Cesium3DTilesetGraphics(); target.uri = uri; target.show = show; target.maximumScreenSpaceError = maximumScreenSpaceError; target.merge(source); expect(target.uri).toBe(uri); expect(target.show).toBe(show); expect(target.maximumScreenSpaceError).toBe(maximumScreenSpaceError); }); it("clone works", function() { const source = new import__39.Cesium3DTilesetGraphics(); source.uri = new import__39.ConstantProperty(""); source.show = new import__39.ConstantProperty(true); source.maximumScreenSpaceError = new import__39.ConstantProperty(2); const result = source.clone(); expect(result.uri).toBe(source.uri); expect(result.show).toBe(source.show); expect(result.maximumScreenSpaceError).toBe(source.maximumScreenSpaceError); }); it("clone works with result parameter", function() { const source = new import__39.Cesium3DTilesetGraphics(); source.uri = new import__39.ConstantProperty(""); source.show = new import__39.ConstantProperty(true); source.maximumScreenSpaceError = new import__39.ConstantProperty(2); const existingResult = new import__39.Cesium3DTilesetGraphics(); const result = source.clone(existingResult); expect(result).toBe(existingResult); expect(result.uri).toBe(source.uri); expect(result.show).toBe(source.show); expect(result.maximumScreenSpaceError).toBe(source.maximumScreenSpaceError); }); it("merge throws if source undefined", function() { const target = new import__39.Cesium3DTilesetGraphics(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/Cesium3DTilesetVisualizerSpec.js var import__40 = __toESM(require_Cesium(), 1); describe( "DataSources/Cesium3DTilesetVisualizer", function() { const tilesetUrl = "./Data/Cesium3DTiles/Batched/BatchedColors/tileset.json"; let scene2; let visualizer; beforeAll(function() { scene2 = createScene_default(); scene2.globe = new import__40.Globe(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { if ((0, import__40.defined)(visualizer)) { visualizer = visualizer.destroy(); } }); it("constructor throws if no scene is passed.", function() { expect(function() { return new import__40.Cesium3DTilesetVisualizer(); }).toThrowDeveloperError(); }); it("update throws if no time specified.", function() { const entityCollection = new import__40.EntityCollection(); visualizer = new import__40.Cesium3DTilesetVisualizer(scene2, entityCollection); expect(function() { visualizer.update(); }).toThrowDeveloperError(); }); it("isDestroy returns false until destroyed.", function() { const entityCollection = new import__40.EntityCollection(); visualizer = new import__40.Cesium3DTilesetVisualizer(scene2, entityCollection); expect(visualizer.isDestroyed()).toEqual(false); visualizer.destroy(); expect(visualizer.isDestroyed()).toEqual(true); visualizer = void 0; }); it("removes the listener from the entity collection when destroyed", function() { const entityCollection = new import__40.EntityCollection(); visualizer = new import__40.Cesium3DTilesetVisualizer(scene2, entityCollection); expect(entityCollection.collectionChanged.numberOfListeners).toEqual(1); visualizer.destroy(); expect(entityCollection.collectionChanged.numberOfListeners).toEqual(0); visualizer = void 0; }); it("object with no tileset does not create one.", function() { const entityCollection = new import__40.EntityCollection(); visualizer = new import__40.Cesium3DTilesetVisualizer(scene2, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__40.ConstantProperty( new import__40.Cartesian3(1234, 5678, 9101112) ); visualizer.update(import__40.JulianDate.now()); expect(scene2.primitives.length).toEqual(0); }); it("object with no position does not set modelMatrix.", async function() { const entityCollection = new import__40.EntityCollection(); visualizer = new import__40.Cesium3DTilesetVisualizer(scene2, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); const tileset = testObject.tileset = new import__40.Cesium3DTilesetGraphics(); tileset.uri = new import__40.ConstantProperty(tilesetUrl); visualizer.update(import__40.JulianDate.now()); await pollToPromise_default(function() { return (0, import__40.defined)(scene2.primitives.get(0)); }); const tilesetPrimitive = scene2.primitives.get(0); expect(tilesetPrimitive.modelMatrix).toEqual(import__40.Matrix4.IDENTITY); }); it("A Cesium3DTilesetGraphics causes a primitive to be created and updated.", async function() { const time2 = import__40.JulianDate.now(); const entityCollection = new import__40.EntityCollection(); visualizer = new import__40.Cesium3DTilesetVisualizer(scene2, entityCollection); const tileset = new import__40.Cesium3DTilesetGraphics(); tileset.show = new import__40.ConstantProperty(true); tileset.maximumScreenSpaceError = new import__40.ConstantProperty(24); tileset.uri = new import__40.ConstantProperty(tilesetUrl); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__40.ConstantPositionProperty( import__40.Cartesian3.fromDegrees(1, 2, 3) ); testObject.tileset = tileset; visualizer.update(time2); await pollToPromise_default(function() { return (0, import__40.defined)(scene2.primitives.get(0)); }); expect(scene2.primitives.length).toEqual(1); expect(scene2.primitives.get(0)).toBeInstanceOf(import__40.Cesium3DTileset); const primitive = scene2.primitives.get(0); visualizer.update(time2); expect(primitive.show).toEqual(true); expect(primitive.maximumScreenSpaceError).toEqual(24); }); it("A Cesium3DTilesetGraphics with a Resource causes a primitive to be created.", async function() { const time2 = import__40.JulianDate.now(); const entityCollection = new import__40.EntityCollection(); visualizer = new import__40.Cesium3DTilesetVisualizer(scene2, entityCollection); const tileset = new import__40.Cesium3DTilesetGraphics(); tileset.show = new import__40.ConstantProperty(true); tileset.uri = new import__40.ConstantProperty( new import__40.Resource({ url: tilesetUrl }) ); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__40.ConstantPositionProperty( import__40.Cartesian3.fromDegrees(1, 2, 3) ); testObject.tileset = tileset; visualizer.update(time2); await pollToPromise_default(function() { return (0, import__40.defined)(scene2.primitives.get(0)); }); expect(scene2.primitives.length).toEqual(1); expect(scene2.primitives.get(0)).toBeInstanceOf(import__40.Cesium3DTileset); }); it("removing removes primitives.", async function() { const entityCollection = new import__40.EntityCollection(); visualizer = new import__40.Cesium3DTilesetVisualizer(scene2, entityCollection); const tileset = new import__40.Cesium3DTilesetGraphics(); tileset.uri = new import__40.ConstantProperty(tilesetUrl); const time2 = import__40.JulianDate.now(); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__40.ConstantProperty( new import__40.Cartesian3(5678, 1234, 1101112) ); testObject.tileset = tileset; visualizer.update(time2); await pollToPromise_default(function() { return (0, import__40.defined)(scene2.primitives.get(0)); }); expect(scene2.primitives.length).toEqual(1); visualizer.update(time2); entityCollection.removeAll(); visualizer.update(time2); expect(scene2.primitives.length).toEqual(0); }); it("Visualizer sets id property.", async function() { const entityCollection = new import__40.EntityCollection(); visualizer = new import__40.Cesium3DTilesetVisualizer(scene2, entityCollection); const time2 = import__40.JulianDate.now(); const testObject = entityCollection.getOrCreateEntity("test"); const tileset = new import__40.Cesium3DTilesetGraphics(); testObject.tileset = tileset; testObject.position = new import__40.ConstantProperty( new import__40.Cartesian3(5678, 1234, 1101112) ); tileset.uri = new import__40.ConstantProperty(tilesetUrl); visualizer.update(time2); await pollToPromise_default(function() { return (0, import__40.defined)(scene2.primitives.get(0)); }); const tilesetPrimitive = scene2.primitives.get(0); expect(tilesetPrimitive.id).toEqual(testObject); }); it("Visualizer does not create tileset primitive when show is false.", async function() { const time2 = import__40.JulianDate.now(); const entityCollection = new import__40.EntityCollection(); visualizer = new import__40.Cesium3DTilesetVisualizer(scene2, entityCollection); const tileset = new import__40.Cesium3DTilesetGraphics(); tileset.show = new import__40.ConstantProperty(false); tileset.uri = new import__40.ConstantProperty( new import__40.Resource({ url: tilesetUrl }) ); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__40.ConstantPositionProperty( import__40.Cartesian3.fromDegrees(1, 2, 3) ); testObject.tileset = tileset; spyOn(import__40.Cesium3DTileset, "fromUrl").and.callThrough(); visualizer.update(time2); expect(import__40.Cesium3DTileset.fromUrl).not.toHaveBeenCalled(); tileset.show = new import__40.ConstantProperty(true); visualizer.update(time2); expect(import__40.Cesium3DTileset.fromUrl).toHaveBeenCalled(); await pollToPromise_default(function() { return (0, import__40.defined)(scene2.primitives.get(0)); }); expect(scene2.primitives.length).toEqual(1); expect(scene2.primitives.get(0)).toBeInstanceOf(import__40.Cesium3DTileset); expect(scene2.primitives.get(0).show).toEqual(true); }); it("Visualizer does not create tileset primitive when show is false.", async function() { const time2 = import__40.JulianDate.now(); const entityCollection = new import__40.EntityCollection(); visualizer = new import__40.Cesium3DTilesetVisualizer(scene2, entityCollection); const tileset = new import__40.Cesium3DTilesetGraphics(); tileset.show = new import__40.ConstantProperty(true); tileset.uri = new import__40.ConstantProperty( new import__40.Resource({ url: tilesetUrl }) ); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__40.ConstantPositionProperty( import__40.Cartesian3.fromDegrees(1, 2, 3) ); testObject.tileset = tileset; spyOn(import__40.Cesium3DTileset, "fromUrl"); visualizer.update(time2); tileset.show = new import__40.ConstantProperty(false); expect(() => visualizer.update(time2)).not.toThrow(); }); it("Visualizer sets show property.", async function() { const entityCollection = new import__40.EntityCollection(); visualizer = new import__40.Cesium3DTilesetVisualizer(scene2, entityCollection); const time2 = import__40.JulianDate.now(); const testObject = entityCollection.getOrCreateEntity("test"); const tileset = new import__40.Cesium3DTilesetGraphics(); testObject.tileset = tileset; testObject.position = new import__40.ConstantProperty( new import__40.Cartesian3(5678, 1234, 1101112) ); tileset.uri = new import__40.ConstantProperty(tilesetUrl); visualizer.update(time2); await pollToPromise_default(function() { return (0, import__40.defined)(scene2.primitives.get(0)); }); const tilesetPrimitive = scene2.primitives.get(0); expect(tilesetPrimitive.show).toEqual(true); tileset.show = new import__40.ConstantProperty(false); visualizer.update(time2); expect(tilesetPrimitive.show).toEqual(false); }); it("Computes bounding sphere.", async function() { const entityCollection = new import__40.EntityCollection(); visualizer = new import__40.Cesium3DTilesetVisualizer(scene2, entityCollection); const time2 = import__40.JulianDate.now(); const testObject = entityCollection.getOrCreateEntity("test"); const tileset = new import__40.Cesium3DTilesetGraphics(); testObject.tileset = tileset; testObject.position = new import__40.ConstantProperty( new import__40.Cartesian3(5678, 1234, 1101112) ); tileset.uri = new import__40.ConstantProperty(tilesetUrl); visualizer.update(time2); const result = new import__40.BoundingSphere(); let state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__40.BoundingSphereState.PENDING); await pollToPromise_default(function() { state2 = visualizer.getBoundingSphere(testObject, result); return state2 !== import__40.BoundingSphereState.PENDING; }); const tilesetPrimitive = scene2.primitives.get(0); expect(state2).toBe(import__40.BoundingSphereState.DONE); expect(result).toEqual(tilesetPrimitive.boundingSphere); }); it("Fails bounding sphere for entity without tileset.", function() { const entityCollection = new import__40.EntityCollection(); const testObject = entityCollection.getOrCreateEntity("test"); visualizer = new import__40.Cesium3DTilesetVisualizer(scene2, entityCollection); visualizer.update(import__40.JulianDate.now()); const result = new import__40.BoundingSphere(); const state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__40.BoundingSphereState.FAILED); }); it("Fails bounding sphere when tileset fails to load.", async function() { const entityCollection = new import__40.EntityCollection(); visualizer = new import__40.Cesium3DTilesetVisualizer(scene2, entityCollection); const time2 = import__40.JulianDate.now(); const testObject = entityCollection.getOrCreateEntity("test"); const tileset = new import__40.Cesium3DTilesetGraphics(); testObject.tileset = tileset; testObject.position = new import__40.ConstantProperty( new import__40.Cartesian3(5678, 1234, 1101112) ); tileset.uri = new import__40.ConstantProperty("/path/to/incorrect/file"); visualizer.update(time2); const result = new import__40.BoundingSphere(); let state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__40.BoundingSphereState.PENDING); await pollToPromise_default(function() { state2 = visualizer.getBoundingSphere(testObject, result); return state2 !== import__40.BoundingSphereState.PENDING; }); state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__40.BoundingSphereState.FAILED); }); it("Compute bounding sphere throws without entity.", function() { const entityCollection = new import__40.EntityCollection(); visualizer = new import__40.Cesium3DTilesetVisualizer(scene2, entityCollection); const result = new import__40.BoundingSphere(); expect(function() { visualizer.getBoundingSphere(void 0, result); }).toThrowDeveloperError(); }); it("Compute bounding sphere throws without result.", function() { const entityCollection = new import__40.EntityCollection(); const testObject = entityCollection.getOrCreateEntity("test"); visualizer = new import__40.Cesium3DTilesetVisualizer(scene2, entityCollection); expect(function() { visualizer.getBoundingSphere(testObject, void 0); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/DataSources/CheckerboardMaterialPropertySpec.js var import__41 = __toESM(require_Cesium(), 1); describe("DataSources/CheckerboardMaterialProperty", function() { it("constructor provides the expected defaults", function() { const property = new import__41.CheckerboardMaterialProperty(); expect(property.getType()).toEqual("Checkerboard"); expect(property.isConstant).toBe(true); expect(property.evenColor).toBeUndefined(); expect(property.oddColor).toBeUndefined(); expect(property.repeat).toBeUndefined(); const result = property.getValue(); expect(result.lightColor).toEqual(import__41.Color.WHITE); expect(result.darkColor).toEqual(import__41.Color.BLACK); expect(result.repeat).toEqual(new import__41.Cartesian2(2, 2)); }); it("constructor sets options and allows raw assignment", function() { const options = { evenColor: import__41.Color.RED, oddColor: import__41.Color.BLUE, repeat: new import__41.Cartesian2(1, 2) }; const property = new import__41.CheckerboardMaterialProperty(options); expect(property.evenColor).toBeInstanceOf(import__41.ConstantProperty); expect(property.oddColor).toBeInstanceOf(import__41.ConstantProperty); expect(property.repeat).toBeInstanceOf(import__41.ConstantProperty); expect(property.evenColor.getValue()).toEqual(options.evenColor); expect(property.oddColor.getValue()).toEqual(options.oddColor); expect(property.repeat.getValue()).toEqual(options.repeat); }); it("works with constant values", function() { const property = new import__41.CheckerboardMaterialProperty(); property.evenColor = new import__41.ConstantProperty(import__41.Color.RED); property.oddColor = new import__41.ConstantProperty(import__41.Color.BLUE); property.repeat = new import__41.ConstantProperty(new import__41.Cartesian2(5, 5)); const result = property.getValue(import__41.JulianDate.now()); expect(result.lightColor).toEqual(import__41.Color.RED); expect(result.darkColor).toEqual(import__41.Color.BLUE); expect(result.repeat).toEqual(new import__41.Cartesian2(5, 5)); }); it("works with dynamic values", function() { const property = new import__41.CheckerboardMaterialProperty(); property.evenColor = new import__41.TimeIntervalCollectionProperty(); property.oddColor = new import__41.TimeIntervalCollectionProperty(); property.repeat = new import__41.TimeIntervalCollectionProperty(); const start = new import__41.JulianDate(1, 0); const stop = new import__41.JulianDate(2, 0); property.evenColor.intervals.addInterval( new import__41.TimeInterval({ start, stop, data: import__41.Color.RED }) ); property.oddColor.intervals.addInterval( new import__41.TimeInterval({ start, stop, data: import__41.Color.BLUE }) ); property.repeat.intervals.addInterval( new import__41.TimeInterval({ start, stop, data: new import__41.Cartesian2(5, 5) }) ); expect(property.isConstant).toBe(false); const result = property.getValue(start); expect(result.lightColor).toEqual(import__41.Color.RED); expect(result.darkColor).toEqual(import__41.Color.BLUE); expect(result.repeat).toEqual(new import__41.Cartesian2(5, 5)); }); it("works with a result parameter", function() { const property = new import__41.CheckerboardMaterialProperty(); property.evenColor = new import__41.ConstantProperty(import__41.Color.RED); property.oddColor = new import__41.ConstantProperty(import__41.Color.BLUE); property.repeat = new import__41.ConstantProperty(new import__41.Cartesian2(5, 5)); const result = { lightColor: import__41.Color.YELLOW.clone(), darkColor: import__41.Color.YELLOW.clone(), repeat: new import__41.Cartesian2(1, 1) }; const returnedResult = property.getValue(import__41.JulianDate.now(), result); expect(returnedResult).toBe(result); expect(result.lightColor).toEqual(import__41.Color.RED); expect(result.darkColor).toEqual(import__41.Color.BLUE); expect(result.repeat).toEqual(new import__41.Cartesian2(5, 5)); }); it("equals works", function() { const left = new import__41.CheckerboardMaterialProperty(); left.evenColor = new import__41.ConstantProperty(import__41.Color.RED); left.oddColor = new import__41.ConstantProperty(import__41.Color.BLUE); left.repeat = new import__41.ConstantProperty(new import__41.Cartesian2(5, 5)); const right = new import__41.CheckerboardMaterialProperty(); right.evenColor = new import__41.ConstantProperty(import__41.Color.RED); right.oddColor = new import__41.ConstantProperty(import__41.Color.BLUE); right.repeat = new import__41.ConstantProperty(new import__41.Cartesian2(5, 5)); expect(left.equals(right)).toEqual(true); right.evenColor = new import__41.ConstantProperty(import__41.Color.BLACK); expect(left.equals(right)).toEqual(false); right.evenColor = new import__41.ConstantProperty(import__41.Color.RED); right.oddColor = new import__41.ConstantProperty(import__41.Color.BLACK); expect(left.equals(right)).toEqual(false); right.oddColor = new import__41.ConstantProperty(import__41.Color.BLUE); right.repeat = new import__41.ConstantProperty(new import__41.Cartesian2(5, 6)); expect(left.equals(right)).toEqual(false); right.repeat = new import__41.ConstantProperty(new import__41.Cartesian2(5, 5)); expect(left.equals(right)).toEqual(true); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__41.CheckerboardMaterialProperty(); testDefinitionChanged_default(property, "evenColor", import__41.Color.RED, import__41.Color.BLUE); testDefinitionChanged_default(property, "oddColor", import__41.Color.RED, import__41.Color.BLUE); testDefinitionChanged_default( property, "repeat", new import__41.Cartesian2(5, 5), new import__41.Cartesian2(7, 7) ); }); }); // packages/engine/Specs/DataSources/ColorMaterialPropertySpec.js var import__42 = __toESM(require_Cesium(), 1); describe("DataSources/ColorMaterialProperty", function() { it("constructor provides the expected defaults", function() { let property = new import__42.ColorMaterialProperty(); expect(property.color).toBeUndefined(); expect(property.getType()).toEqual("Color"); expect(property.isConstant).toBe(true); const result = property.getValue(); expect(result.color).toEqual(import__42.Color.WHITE); const colorProperty = new import__42.ConstantProperty(import__42.Color.BLUE); property = new import__42.ColorMaterialProperty(colorProperty); expect(property.color).toBe(colorProperty); property = new import__42.ColorMaterialProperty(import__42.Color.BLUE); expect(property.color).toBeInstanceOf(import__42.ConstantProperty); expect(property.color.getValue()).toEqual(import__42.Color.BLUE); }); it("works with constant values", function() { const property = new import__42.ColorMaterialProperty(); property.color = new import__42.ConstantProperty(import__42.Color.RED); const result = property.getValue(import__42.JulianDate.now()); expect(result.color).toEqual(import__42.Color.RED); }); it("works with dynamic values", function() { const property = new import__42.ColorMaterialProperty(); property.color = new import__42.TimeIntervalCollectionProperty(); const start = new import__42.JulianDate(1, 0); const stop = new import__42.JulianDate(2, 0); property.color.intervals.addInterval( new import__42.TimeInterval({ start, stop, data: import__42.Color.BLUE }) ); expect(property.isConstant).toBe(false); const result = property.getValue(start); expect(result.color).toEqual(import__42.Color.BLUE); }); it("works with a result parameter", function() { const property = new import__42.ColorMaterialProperty(); property.color = new import__42.ConstantProperty(import__42.Color.RED); const result = { color: import__42.Color.BLUE.clone() }; const returnedResult = property.getValue(import__42.JulianDate.now(), result); expect(returnedResult).toBe(result); expect(result.color).toEqual(import__42.Color.RED); }); it("equals works", function() { const left = new import__42.ColorMaterialProperty(); left.color = new import__42.ConstantProperty(import__42.Color.WHITE); const right = new import__42.ColorMaterialProperty(); right.color = new import__42.ConstantProperty(import__42.Color.WHITE); expect(left.equals(right)).toEqual(true); right.color = new import__42.ConstantProperty(import__42.Color.BLACK); expect(left.equals(right)).toEqual(false); }); it("raises definitionChanged when a color property is assigned or modified", function() { const property = new import__42.ColorMaterialProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); const oldValue = property.color; property.color = new import__42.ConstantProperty(import__42.Color.WHITE); expect(listener).toHaveBeenCalledWith( property, "color", property.color, oldValue ); listener.calls.reset(); property.color.setValue(import__42.Color.BLACK); expect(listener).toHaveBeenCalledWith( property, "color", property.color, property.color ); listener.calls.reset(); property.color = property.color; expect(listener.calls.count()).toEqual(0); }); }); // packages/engine/Specs/DataSources/CompositeEntityCollectionSpec.js var import__43 = __toESM(require_Cesium(), 1); describe("DataSources/CompositeEntityCollection", function() { function CollectionListener() { this.timesCalled = 0; this.added = []; this.removed = []; } CollectionListener.prototype.onCollectionChanged = function(collection, added, removed) { this.timesCalled++; this.added = added.slice(0); this.removed = removed.slice(0); }; it("constructor has expected defaults", function() { const composite = new import__43.CompositeEntityCollection(); expect(composite.collectionChanged).toBeDefined(); expect(composite.getCollectionsLength()).toEqual(0); expect(composite.values.length).toEqual(0); }); it("constructor with owner", function() { const composite = new import__43.CompositeEntityCollection(); const child = new import__43.CompositeEntityCollection(void 0, composite); expect(child.owner).toEqual(composite); }); it("addCollection/removeCollection works", function() { const entityCollection = new import__43.EntityCollection(); entityCollection.add(new import__43.Entity()); const entityCollection2 = new import__43.EntityCollection(); entityCollection2.add(new import__43.Entity()); const composite = new import__43.CompositeEntityCollection(); composite.addCollection(entityCollection); expect(composite.getCollectionsLength()).toEqual(1); expect(composite.values.length).toEqual(1); composite.addCollection(entityCollection2); expect(composite.getCollectionsLength()).toEqual(2); expect(composite.values.length).toEqual(2); expect(composite.removeCollection(entityCollection)).toEqual(true); expect(composite.values.length).toEqual(1); expect(composite.removeCollection(entityCollection2)).toEqual(true); expect(composite.values.length).toEqual(0); expect(composite.getCollectionsLength()).toEqual(0); expect(composite.removeCollection(entityCollection)).toEqual(false); }); it("addCollection works with index", function() { const entityCollection = new import__43.EntityCollection(); const entityCollection2 = new import__43.EntityCollection(); const entityCollection3 = new import__43.EntityCollection(); const composite = new import__43.CompositeEntityCollection(); composite.addCollection(entityCollection); composite.addCollection(entityCollection3); composite.addCollection(entityCollection2, 1); expect(composite.getCollection(0)).toBe(entityCollection); expect(composite.getCollection(1)).toBe(entityCollection2); expect(composite.getCollection(2)).toBe(entityCollection3); }); it("contains returns true if in collection", function() { const entityCollection = new import__43.EntityCollection(); const composite = new import__43.CompositeEntityCollection(); composite.addCollection(entityCollection); const entity = entityCollection.getOrCreateEntity("asd"); expect(entityCollection.contains(entity)).toBe(true); }); it("contains returns false if not in collection", function() { const entityCollection = new import__43.CompositeEntityCollection(); expect(entityCollection.contains(new import__43.Entity())).toBe(false); }); it("contains throws with undefined Entity", function() { const entityCollection = new import__43.CompositeEntityCollection(); expect(function() { entityCollection.contains(void 0); }).toThrowDeveloperError(); }); it("containsCollection works", function() { const entityCollection = new import__43.EntityCollection(); const composite = new import__43.CompositeEntityCollection(); expect(composite.containsCollection(entityCollection)).toEqual(false); composite.addCollection(entityCollection); expect(composite.containsCollection(entityCollection)).toEqual(true); }); it("indexOfCollection works", function() { const entityCollection = new import__43.EntityCollection(); const entityCollection2 = new import__43.EntityCollection(); const composite = new import__43.CompositeEntityCollection(); expect(composite.indexOfCollection(entityCollection)).toEqual(-1); composite.addCollection(entityCollection); composite.addCollection(entityCollection2); expect(composite.indexOfCollection(entityCollection)).toEqual(0); expect(composite.indexOfCollection(entityCollection2)).toEqual(1); composite.removeCollection(entityCollection); expect(composite.indexOfCollection(entityCollection2)).toEqual(0); }); it("getCollection works", function() { const entityCollection = new import__43.EntityCollection(); const entityCollection2 = new import__43.EntityCollection(); const composite = new import__43.CompositeEntityCollection(); composite.addCollection(entityCollection); composite.addCollection(entityCollection2); expect(composite.getCollection(0)).toBe(entityCollection); expect(composite.getCollection(1)).toBe(entityCollection2); expect(composite.getCollection(2)).toBeUndefined(); }); it("raise/lower collection works", function() { const entityCollection = new import__43.EntityCollection(); const entityCollection2 = new import__43.EntityCollection(); const entityCollection3 = new import__43.EntityCollection(); const composite = new import__43.CompositeEntityCollection(); composite.addCollection(entityCollection); composite.addCollection(entityCollection2); composite.addCollection(entityCollection3); expect(composite.indexOfCollection(entityCollection2)).toEqual(1); composite.raiseCollection(entityCollection2); expect(composite.indexOfCollection(entityCollection2)).toEqual(2); composite.lowerCollection(entityCollection2); composite.lowerCollection(entityCollection2); expect(composite.indexOfCollection(entityCollection2)).toEqual(0); composite.lowerCollection(entityCollection2); expect(composite.indexOfCollection(entityCollection2)).toEqual(0); composite.raiseCollectionToTop(entityCollection2); expect(composite.indexOfCollection(entityCollection2)).toEqual(2); composite.raiseCollectionToTop(entityCollection2); expect(composite.indexOfCollection(entityCollection2)).toEqual(2); composite.lowerCollectionToBottom(entityCollection2); expect(composite.indexOfCollection(entityCollection2)).toEqual(0); composite.lowerCollectionToBottom(entityCollection2); expect(composite.indexOfCollection(entityCollection2)).toEqual(0); }); it("add/remove works", function() { const entity = new import__43.Entity(); const entity2 = new import__43.Entity(); const entityCollection = new import__43.EntityCollection(); const composite = new import__43.CompositeEntityCollection([entityCollection]); entityCollection.add(entity); expect(composite.values.length).toEqual(1); entityCollection.add(entity2); expect(composite.values.length).toEqual(2); entityCollection.remove(entity2); expect(composite.values.length).toEqual(1); entityCollection.remove(entity); expect(composite.values.length).toEqual(0); }); it("add/remove raises expected events", function() { const entity = new import__43.Entity(); const entity2 = new import__43.Entity(); const entityCollection = new import__43.EntityCollection(); const composite = new import__43.CompositeEntityCollection([entityCollection]); const listener = new CollectionListener(); composite.collectionChanged.addEventListener( listener.onCollectionChanged, listener ); entityCollection.add(entity); expect(listener.timesCalled).toEqual(1); expect(listener.added.length).toEqual(1); expect(listener.added[0].id).toBe(entity.id); expect(listener.removed.length).toEqual(0); entityCollection.add(entity2); expect(listener.timesCalled).toEqual(2); expect(listener.added.length).toEqual(1); expect(listener.added[0].id).toBe(entity2.id); expect(listener.removed.length).toEqual(0); entityCollection.remove(entity2); expect(listener.timesCalled).toEqual(3); expect(listener.added.length).toEqual(0); expect(listener.removed.length).toEqual(1); expect(listener.removed[0].id).toBe(entity2.id); entityCollection.remove(entity); expect(listener.timesCalled).toEqual(4); expect(listener.added.length).toEqual(0); expect(listener.removed.length).toEqual(1); expect(listener.removed[0].id).toBe(entity.id); composite.collectionChanged.removeEventListener( listener.onCollectionChanged, listener ); }); it("suspended add/remove raises expected events", function() { const entity = new import__43.Entity(); const entity2 = new import__43.Entity(); const entity3 = new import__43.Entity(); const entityCollection = new import__43.EntityCollection(); const composite = new import__43.CompositeEntityCollection([entityCollection]); const listener = new CollectionListener(); composite.collectionChanged.addEventListener( listener.onCollectionChanged, listener ); composite.suspendEvents(); composite.suspendEvents(); entityCollection.add(entity); entityCollection.add(entity2); entityCollection.add(entity3); entityCollection.remove(entity2); expect(listener.timesCalled).toEqual(0); composite.resumeEvents(); expect(listener.timesCalled).toEqual(0); composite.resumeEvents(); expect(listener.timesCalled).toEqual(1); expect(listener.added.length).toEqual(2); expect(listener.added[0].id).toBe(entity.id); expect(listener.added[1].id).toBe(entity3.id); expect(listener.removed.length).toEqual(0); composite.suspendEvents(); entityCollection.remove(entity); entityCollection.remove(entity3); entityCollection.add(entity); entityCollection.add(entity3); composite.resumeEvents(); expect(listener.timesCalled).toEqual(1); composite.collectionChanged.removeEventListener( listener.onCollectionChanged, listener ); }); it("removeAllCollections works", function() { const entity = new import__43.Entity(); const entity2 = new import__43.Entity(); const entityCollection = new import__43.EntityCollection(); const composite = new import__43.CompositeEntityCollection([entityCollection]); entityCollection.add(entity); entityCollection.add(entity2); composite.removeAllCollections(); expect(composite.values.length).toEqual(0); }); it("removeAllCollections raises expected events", function() { const entity = new import__43.Entity(); const entity2 = new import__43.Entity(); const entityCollection = new import__43.EntityCollection(); const listener = new CollectionListener(); const composite = new import__43.CompositeEntityCollection([entityCollection]); entityCollection.add(entity); entityCollection.add(entity2); composite.collectionChanged.addEventListener( listener.onCollectionChanged, listener ); composite.removeAllCollections(); expect(listener.timesCalled).toEqual(1); expect(listener.removed.length).toEqual(2); expect(listener.removed[0].id).toBe(entity.id); expect(listener.removed[1].id).toBe(entity2.id); expect(listener.added.length).toEqual(0); composite.removeAllCollections(); expect(listener.timesCalled).toEqual(1); composite.collectionChanged.removeEventListener( listener.onCollectionChanged, listener ); }); it("suspended removeAllCollections raises expected events", function() { const entity = new import__43.Entity(); const entity2 = new import__43.Entity(); const entityCollection = new import__43.EntityCollection(); const listener = new CollectionListener(); const composite = new import__43.CompositeEntityCollection([entityCollection]); entityCollection.add(entity); entityCollection.add(entity2); composite.collectionChanged.addEventListener( listener.onCollectionChanged, listener ); composite.suspendEvents(); composite.removeAllCollections(); composite.resumeEvents(); expect(listener.timesCalled).toEqual(1); expect(listener.removed.length).toEqual(2); expect(listener.removed[0].id).toBe(entity.id); expect(listener.removed[1].id).toBe(entity2.id); expect(listener.added.length).toEqual(0); expect(composite.getCollectionsLength()).toEqual(0); composite.suspendEvents(); composite.addCollection(entityCollection); entityCollection.removeAll(); composite.resumeEvents(); expect(listener.timesCalled).toEqual(1); composite.collectionChanged.removeEventListener( listener.onCollectionChanged, listener ); }); it("getById works", function() { const entity = new import__43.Entity(); const entity2 = new import__43.Entity(); const entityCollection = new import__43.EntityCollection(); entityCollection.add(entity); entityCollection.add(entity2); const composite = new import__43.CompositeEntityCollection(); composite.addCollection(entityCollection); expect(composite.getById(entity.id).id).toEqual(entity.id); expect(composite.getById(entity2.id).id).toEqual(entity2.id); }); it("getById returns undefined for non-existent object", function() { const composite = new import__43.CompositeEntityCollection(); expect(composite.getById("123")).toBeUndefined(); }); it("computeAvailability returns infinite with no data.", function() { const entityCollection = new import__43.EntityCollection(); const composite = new import__43.CompositeEntityCollection(); composite.addCollection(entityCollection); const availability = composite.computeAvailability(); expect(availability.start).toEqual(import__43.Iso8601.MINIMUM_VALUE); expect(availability.stop).toEqual(import__43.Iso8601.MAXIMUM_VALUE); }); it("computeAvailability returns intersection of collections.", function() { const entityCollection = new import__43.EntityCollection(); const entity = entityCollection.getOrCreateEntity("1"); const entity2 = entityCollection.getOrCreateEntity("2"); const entity3 = entityCollection.getOrCreateEntity("3"); entity.availability = new import__43.TimeIntervalCollection(); entity.availability.addInterval( import__43.TimeInterval.fromIso8601({ iso8601: "2012-08-01/2012-08-02" }) ); entity2.availability = new import__43.TimeIntervalCollection(); entity2.availability.addInterval( import__43.TimeInterval.fromIso8601({ iso8601: "2012-08-05/2012-08-06" }) ); entity3.availability = void 0; const composite = new import__43.CompositeEntityCollection(); composite.addCollection(entityCollection); const availability = composite.computeAvailability(); expect(availability.start).toEqual(import__43.JulianDate.fromIso8601("2012-08-01")); expect(availability.stop).toEqual(import__43.JulianDate.fromIso8601("2012-08-06")); }); it("computeAvailability works if only start or stop time is infinite.", function() { const entityCollection = new import__43.EntityCollection(); const entity = entityCollection.getOrCreateEntity("1"); const entity2 = entityCollection.getOrCreateEntity("2"); const entity3 = entityCollection.getOrCreateEntity("3"); entity.availability = new import__43.TimeIntervalCollection(); entity.availability.addInterval( import__43.TimeInterval.fromIso8601({ iso8601: "2012-08-01/9999-12-31T24:00:00Z" }) ); entity2.availability = new import__43.TimeIntervalCollection(); entity2.availability.addInterval( import__43.TimeInterval.fromIso8601({ iso8601: "0000-01-01T00:00:00Z/2012-08-06" }) ); entity3.availability = void 0; const composite = new import__43.CompositeEntityCollection(); composite.addCollection(entityCollection); const availability = composite.computeAvailability(); expect(availability.start).toEqual(import__43.JulianDate.fromIso8601("2012-08-01")); expect(availability.stop).toEqual(import__43.JulianDate.fromIso8601("2012-08-06")); }); it("coarse property compositing works", function() { const composite = new import__43.CompositeEntityCollection(); const collection1 = new import__43.EntityCollection(); const collection2 = new import__43.EntityCollection(); const collection3 = new import__43.EntityCollection(); composite.addCollection(collection3); composite.addCollection(collection2); composite.addCollection(collection1); const entity2 = new import__43.Entity(); collection2.add(entity2); entity2.position = new import__43.CompositePositionProperty(); entity2.orientation = new import__43.CompositeProperty(); const compositeObject = composite.getById(entity2.id); expect(compositeObject).toBeDefined(); expect(composite.values.length).toEqual(1); expect(compositeObject.position).toBe(entity2.position); expect(compositeObject.orientation).toBe(entity2.orientation); const entity3 = new import__43.Entity({ id: entity2.id }); collection3.add(entity3); entity3.position = new import__43.CompositePositionProperty(); entity3.viewFrom = new import__43.CompositeProperty(); expect(composite.values.length).toEqual(1); expect(compositeObject.position).toBe(entity2.position); expect(compositeObject.orientation).toBe(entity2.orientation); expect(compositeObject.viewFrom).toBe(entity3.viewFrom); const entity1 = new import__43.Entity({ id: entity2.id }); collection1.add(entity1); entity1.position = new import__43.CompositePositionProperty(); expect(composite.values.length).toEqual(1); expect(compositeObject.position).toBe(entity1.position); expect(compositeObject.orientation).toBe(entity2.orientation); expect(compositeObject.viewFrom).toBe(entity3.viewFrom); }); it("sub-property compositing works", function() { const id = "test"; const collection1 = new import__43.EntityCollection(); const entity1 = new import__43.Entity({ id }); entity1.billboard = new import__43.BillboardGraphics(); collection1.add(entity1); const collection2 = new import__43.EntityCollection(); const entity2 = new import__43.Entity({ id }); entity2.billboard = new import__43.BillboardGraphics(); collection2.add(entity2); const collection3 = new import__43.EntityCollection(); const entity3 = new import__43.Entity({ id }); entity3.billboard = new import__43.BillboardGraphics(); collection3.add(entity3); const composite = new import__43.CompositeEntityCollection(); composite.addCollection(collection3); composite.addCollection(collection2); composite.addCollection(collection1); const compositeObject = composite.getById(id); entity2.billboard.show = new import__43.CompositeProperty(); expect(compositeObject.billboard.show).toBe(entity2.billboard.show); entity3.billboard.show = new import__43.CompositeProperty(); expect(compositeObject.billboard.show).toBe(entity2.billboard.show); entity1.billboard.show = new import__43.CompositeProperty(); expect(compositeObject.billboard.show).toBe(entity1.billboard.show); entity2.billboard.show = void 0; expect(compositeObject.billboard.show).toBe(entity1.billboard.show); entity1.billboard.show = void 0; expect(compositeObject.billboard.show).toBe(entity3.billboard.show); entity3.billboard.show = void 0; expect(compositeObject.billboard.show).toBeUndefined(); }); it("per-entity availability works", function() { const id = "test"; const collection1 = new import__43.EntityCollection(); const availability1 = new import__43.TimeIntervalCollection(); availability1.addInterval( import__43.TimeInterval.fromIso8601({ iso8601: "2019-01-01/2019-01-04" }) ); const entity1 = new import__43.Entity({ id, availability: availability1 }); collection1.add(entity1); const collection2 = new import__43.EntityCollection(); const availability2 = new import__43.TimeIntervalCollection(); availability2.addInterval( import__43.TimeInterval.fromIso8601({ iso8601: "2019-01-02/2019-01-05" }) ); const entity2 = new import__43.Entity({ id, availability: availability2 }); collection2.add(entity2); const collection3 = new import__43.EntityCollection(); const availability3 = new import__43.TimeIntervalCollection(); availability3.addInterval( import__43.TimeInterval.fromIso8601({ iso8601: "2019-01-03/2019-01-06" }) ); const entity3 = new import__43.Entity({ id, availability: availability3 }); collection3.add(entity3); const composite = new import__43.CompositeEntityCollection(); composite.addCollection(collection3); composite.addCollection(collection2); composite.addCollection(collection1); const compositeObject = composite.getById(id); expect(compositeObject.availability.start).toEqual( import__43.JulianDate.fromIso8601("2019-01-01") ); composite.removeCollection(collection1); expect(compositeObject.availability.start).toEqual( import__43.JulianDate.fromIso8601("2019-01-02") ); composite.removeCollection(collection2); expect(compositeObject.availability.start).toEqual( import__43.JulianDate.fromIso8601("2019-01-03") ); }); it("works when collection being composited suspends updates", function() { const collection = new import__43.EntityCollection(); const composite = new import__43.CompositeEntityCollection([collection]); collection.suspendEvents(); collection.getOrCreateEntity("id1"); collection.getOrCreateEntity("id2"); expect(composite.getById("id1")).toBeUndefined(); expect(composite.getById("id2")).toBeUndefined(); collection.resumeEvents(); expect(composite.getById("id1")).toBeDefined(); expect(composite.getById("id2")).toBeDefined(); }); it("custom entity properties are properly registed on new composited entity.", function() { const oldValue = "tubelcane"; const newValue = "fizzbuzz"; const propertyName = "customProperty"; const collection = new import__43.EntityCollection(); const e1 = collection.getOrCreateEntity("id1"); e1.addProperty(propertyName); e1[propertyName] = oldValue; const composite = new import__43.CompositeEntityCollection([collection]); const e1Composite = composite.getById("id1"); expect(e1Composite[propertyName]).toEqual(e1[propertyName]); const listener = jasmine.createSpy("listener"); e1Composite.definitionChanged.addEventListener(listener); e1[propertyName] = newValue; expect(listener).toHaveBeenCalledWith( e1Composite, propertyName, newValue, oldValue ); }); it("custom entity properties are properly registed on existing composited entity.", function() { const oldValue = "tubelcane"; const newValue = "fizzbuzz"; const propertyName = "customProperty"; const collection = new import__43.EntityCollection(); const e1 = collection.getOrCreateEntity("id1"); const composite = new import__43.CompositeEntityCollection([collection]); e1.addProperty(propertyName); e1[propertyName] = oldValue; const e1Composite = composite.getById("id1"); expect(e1Composite[propertyName]).toEqual(e1[propertyName]); const listener = jasmine.createSpy("listener"); e1Composite.definitionChanged.addEventListener(listener); e1[propertyName] = newValue; expect(listener).toHaveBeenCalledWith( e1Composite, propertyName, newValue, oldValue ); }); it("can use the same entity collection in multiple composites", function() { const id = "test"; const collection1 = new import__43.EntityCollection(); const entity1 = new import__43.Entity({ id }); entity1.billboard = new import__43.BillboardGraphics(); entity1.billboard.show = new import__43.ConstantProperty(true); collection1.add(entity1); const collection2 = new import__43.EntityCollection(); const entity2 = new import__43.Entity({ id }); entity2.billboard = new import__43.BillboardGraphics(); entity2.billboard.show = new import__43.ConstantProperty(false); collection2.add(entity2); const composite1 = new import__43.CompositeEntityCollection(); composite1.addCollection(collection2); composite1.addCollection(collection1); const composite2 = new import__43.CompositeEntityCollection(); composite2.addCollection(collection1); composite2.addCollection(collection2); expect( composite1.getById(id).billboard.show.getValue(import__43.JulianDate.now()) ).toEqual(true); expect( composite2.getById(id).billboard.show.getValue(import__43.JulianDate.now()) ).toEqual(false); entity2.billboard.show = new import__43.ConstantProperty(true); expect( composite2.getById(id).billboard.show.getValue(import__43.JulianDate.now()) ).toEqual(true); expect(composite1.getById(id).billboard.show).toBe(entity1.billboard.show); expect(composite2.getById(id).billboard.show).toBe(entity2.billboard.show); entity1.position = new import__43.CompositePositionProperty(); expect(composite1.getById(id).position).toBe(entity1.position); expect(composite2.getById(id).position).toBe(entity1.position); entity2.position = new import__43.CompositePositionProperty(); expect(composite1.getById(id).position).toBe(entity1.position); expect(composite2.getById(id).position).toBe(entity2.position); }); it("has entity with link to entity collection", function() { const id = "test"; const collection = new import__43.EntityCollection(); const entity = new import__43.Entity({ id }); collection.add(entity); const composite = new import__43.CompositeEntityCollection(); composite.addCollection(collection); const compositeEntity = composite.getCollection(0).values[0]; expect(compositeEntity.entityCollection).toEqual(collection); }); it("suspend events suspends recompositing", function() { const id = "test"; const collection1 = new import__43.EntityCollection(); const entity1 = new import__43.Entity({ id }); collection1.add(entity1); const collection2 = new import__43.EntityCollection(); const entity2 = new import__43.Entity({ id }); collection2.add(entity2); const composite = new import__43.CompositeEntityCollection(); composite.addCollection(collection2); composite.suspendEvents(); composite.addCollection(collection1); const compositeObject = composite.getById(id); entity1.billboard = new import__43.BillboardGraphics(); entity1.billboard.show = new import__43.ConstantProperty(false); expect(compositeObject.billboard).toBeUndefined(); composite.resumeEvents(); expect(compositeObject.billboard.show).toBe(entity1.billboard.show); }); it("prevents names from colliding between property events and object events", function() { const id = "test"; const collection1 = new import__43.EntityCollection(); const entity1 = new import__43.Entity({ id }); collection1.add(entity1); const collection2 = new import__43.EntityCollection(); const entity2 = new import__43.Entity({ id }); collection2.add(entity2); const composite = new import__43.CompositeEntityCollection(); composite.addCollection(collection2); composite.addCollection(collection1); const compositeObject = composite.getById(id); entity1.billboard = new import__43.BillboardGraphics(); entity1.billboard.show = new import__43.ConstantProperty(false); expect(compositeObject.billboard.show).toBe(entity1.billboard.show); const newObject = new import__43.Entity({ id: `${id}billboard` }); collection1.add(newObject); entity1.billboard = new import__43.BillboardGraphics(); entity1.billboard.show = new import__43.ConstantProperty(false); newObject.position = new import__43.CompositePositionProperty(); expect(composite.getById(newObject.id).position).toBe(newObject.position); }); it("addCollection throws with undefined collection", function() { const composite = new import__43.CompositeEntityCollection(); expect(function() { composite.addCollection(void 0); }).toThrowDeveloperError(); }); it("addCollection throws if negative index", function() { const collection = new import__43.EntityCollection(); const composite = new import__43.CompositeEntityCollection(); expect(function() { composite.addCollection(collection, -1); }).toThrowDeveloperError(); }); it("addCollection throws if index greater than length", function() { const collection = new import__43.EntityCollection(); const composite = new import__43.CompositeEntityCollection(); expect(function() { composite.addCollection(collection, 1); }).toThrowDeveloperError(); }); it("getCollection throws with undefined index", function() { const composite = new import__43.CompositeEntityCollection(); expect(function() { composite.getCollection(void 0); }).toThrowDeveloperError(); }); it("raiseCollection throws if collection not in composite", function() { const composite = new import__43.CompositeEntityCollection(); const collection = new import__43.EntityCollection(); expect(function() { composite.raiseCollection(collection); }).toThrowDeveloperError(); }); it("raiseCollectionToTop throws if collection not in composite", function() { const composite = new import__43.CompositeEntityCollection(); const collection = new import__43.EntityCollection(); expect(function() { composite.raiseCollectionToTop(collection); }).toThrowDeveloperError(); }); it("lowerCollection throws if collection not in composite", function() { const composite = new import__43.CompositeEntityCollection(); const collection = new import__43.EntityCollection(); expect(function() { composite.lowerCollection(collection); }).toThrowDeveloperError(); }); it("lowerCollectionToBottom throws if collection not in composite", function() { const composite = new import__43.CompositeEntityCollection(); const collection = new import__43.EntityCollection(); expect(function() { composite.lowerCollectionToBottom(collection); }).toThrowDeveloperError(); }); it("raiseCollection throws if collection not defined", function() { const composite = new import__43.CompositeEntityCollection(); expect(function() { composite.raiseCollection(void 0); }).toThrowDeveloperError(); }); it("raiseCollectionToTop throws if collection not defined", function() { const composite = new import__43.CompositeEntityCollection(); expect(function() { composite.raiseCollectionToTop(void 0); }).toThrowDeveloperError(); }); it("lowerCollection throws if collection not defined", function() { const composite = new import__43.CompositeEntityCollection(); expect(function() { composite.lowerCollection(void 0); }).toThrowDeveloperError(); }); it("lowerCollectionToBottom throws if collection not defined", function() { const composite = new import__43.CompositeEntityCollection(); expect(function() { composite.lowerCollectionToBottom(void 0); }).toThrowDeveloperError(); }); it("resumeEvents throws if no matching suspendEvents", function() { const composite = new import__43.CompositeEntityCollection(); expect(function() { composite.resumeEvents(); }).toThrowDeveloperError(); }); it("getById throws if no id specified", function() { const composite = new import__43.CompositeEntityCollection(); expect(function() { composite.getById(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/CompositeMaterialPropertySpec.js var import__44 = __toESM(require_Cesium(), 1); describe("DataSources/CompositeMaterialProperty", function() { it("default constructor has expected values", function() { const property = new import__44.CompositeMaterialProperty(); expect(property.intervals).toBeInstanceOf(import__44.TimeIntervalCollection); expect(property.isConstant).toBe(true); expect(property.getType(import__44.JulianDate.now())).toBeUndefined(); expect(property.getValue(import__44.JulianDate.now())).toBeUndefined(); }); it("works without a result parameter", function() { const interval1 = new import__44.TimeInterval({ start: new import__44.JulianDate(10, 0), stop: new import__44.JulianDate(12, 0), data: new import__44.ColorMaterialProperty() }); const interval2 = new import__44.TimeInterval({ start: new import__44.JulianDate(12, 0), stop: new import__44.JulianDate(14, 0), isStartIncluded: false, data: new import__44.GridMaterialProperty() }); const property = new import__44.CompositeMaterialProperty(); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); expect(property.isConstant).toBe(false); const result1 = property.getValue(interval1.start); expect(property.getType(interval1.start)).toEqual("Color"); expect(result1).not.toBe(interval1.data.getValue(interval1.start)); expect(result1).toEqual(interval1.data.getValue(interval1.start)); const result2 = property.getValue(interval2.stop); expect(property.getType(interval2.stop)).toEqual("Grid"); expect(result2).not.toBe(interval2.data.getValue(interval2.stop)); expect(result2).toEqual(interval2.data.getValue(interval2.stop)); }); it("works with a result parameter", function() { const interval1 = new import__44.TimeInterval({ start: new import__44.JulianDate(10, 0), stop: new import__44.JulianDate(12, 0), data: new import__44.ColorMaterialProperty() }); const interval2 = new import__44.TimeInterval({ start: new import__44.JulianDate(12, 0), stop: new import__44.JulianDate(14, 0), isStartIncluded: false, data: new import__44.GridMaterialProperty() }); const property = new import__44.CompositeMaterialProperty(); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); expect(property.isConstant).toBe(false); const expected = {}; const result1 = property.getValue(interval1.start, expected); expect(result1).toBe(expected); expect(result1).toEqual(interval1.data.getValue(interval1.start)); const result2 = property.getValue(interval2.stop, expected); expect(result2).toBe(expected); expect(result2).toEqual(interval2.data.getValue(interval2.stop)); }); it("equals works", function() { const interval1 = new import__44.TimeInterval({ start: new import__44.JulianDate(10, 0), stop: new import__44.JulianDate(12, 0), data: new import__44.ColorMaterialProperty() }); const interval2 = new import__44.TimeInterval({ start: new import__44.JulianDate(12, 0), stop: new import__44.JulianDate(14, 0), isStartIncluded: false, data: new import__44.GridMaterialProperty() }); const left = new import__44.CompositeMaterialProperty(); left.intervals.addInterval(interval1); left.intervals.addInterval(interval2); const right = new import__44.CompositeMaterialProperty(); right.intervals.addInterval(interval1); expect(left.equals(right)).toEqual(false); right.intervals.addInterval(interval2); expect(left.equals(right)).toEqual(true); }); it("raises definitionChanged event in all cases", function() { const interval1 = new import__44.TimeInterval({ start: new import__44.JulianDate(10, 0), stop: new import__44.JulianDate(12, 0), data: new import__44.ColorMaterialProperty(import__44.Color.RED) }); const interval2 = new import__44.TimeInterval({ start: new import__44.JulianDate(12, 0), stop: new import__44.JulianDate(14, 0), isStartIncluded: false, data: new import__44.ColorMaterialProperty(import__44.Color.YELLOW) }); const property = new import__44.CompositeMaterialProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.intervals.addInterval(interval1); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.intervals.addInterval(interval2); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.intervals.removeInterval(interval2); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); interval1.data.color.setValue(import__44.Color.BLUE); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.intervals.removeAll(); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); }); it("does not raise definitionChanged for an overwritten interval", function() { const interval1 = new import__44.TimeInterval({ start: new import__44.JulianDate(11, 0), stop: new import__44.JulianDate(13, 0), data: new import__44.ColorMaterialProperty(import__44.Color.RED) }); const interval2 = new import__44.TimeInterval({ start: new import__44.JulianDate(10, 0), stop: new import__44.JulianDate(14, 0), isStartIncluded: false, data: new import__44.ColorMaterialProperty(import__44.Color.YELLOW) }); const property = new import__44.CompositeMaterialProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); expect(listener.calls.count()).toBe(2); interval1.data.color.setValue(import__44.Color.BLUE); expect(listener.calls.count()).toBe(2); }); it("getValue throws with no time parameter", function() { const property = new import__44.CompositeMaterialProperty(); expect(function() { property.getValue(void 0); }).toThrowDeveloperError(); }); it("getType throws with no time parameter", function() { const property = new import__44.CompositeMaterialProperty(); expect(function() { property.getType(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/CompositePositionPropertySpec.js var import__45 = __toESM(require_Cesium(), 1); describe("DataSources/CompositePositionProperty", function() { it("default constructor has expected values", function() { const property = new import__45.CompositePositionProperty(); expect(property.intervals).toBeInstanceOf(import__45.TimeIntervalCollection); expect(property.getValue(import__45.JulianDate.now())).toBeUndefined(); expect(property.referenceFrame).toBe(import__45.ReferenceFrame.FIXED); expect(property.isConstant).toBe(true); }); it("constructor sets expected values", function() { const property = new import__45.CompositePositionProperty(import__45.ReferenceFrame.INERTIAL); expect(property.referenceFrame).toBe(import__45.ReferenceFrame.INERTIAL); }); it("can modify reference frame", function() { const property = new import__45.CompositePositionProperty(); expect(property.referenceFrame).toBe(import__45.ReferenceFrame.FIXED); property.referenceFrame = import__45.ReferenceFrame.INERTIAL; expect(property.referenceFrame).toBe(import__45.ReferenceFrame.INERTIAL); }); it("works without a result parameter", function() { const interval1 = new import__45.TimeInterval({ start: new import__45.JulianDate(10, 0), stop: new import__45.JulianDate(12, 0), data: new import__45.ConstantPositionProperty(new import__45.Cartesian3(1, 2, 3)) }); const interval2 = new import__45.TimeInterval({ start: new import__45.JulianDate(12, 0), stop: new import__45.JulianDate(14, 0), isStartIncluded: false, data: new import__45.ConstantPositionProperty(new import__45.Cartesian3(4, 5, 6)) }); const property = new import__45.CompositePositionProperty(); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); expect(property.isConstant).toBe(false); const result1 = property.getValue(interval1.start); expect(result1).not.toBe(interval1.data.getValue(interval1.start)); expect(result1).toEqual(interval1.data.getValue(interval1.start)); const result2 = property.getValue(interval2.stop); expect(result2).not.toBe(interval2.data.getValue(interval2.stop)); expect(result2).toEqual(interval2.data.getValue(interval2.stop)); }); it("getValue works with a result parameter", function() { const interval1 = new import__45.TimeInterval({ start: new import__45.JulianDate(10, 0), stop: new import__45.JulianDate(12, 0), data: new import__45.ConstantPositionProperty(new import__45.Cartesian3(1, 2, 3)) }); const interval2 = new import__45.TimeInterval({ start: new import__45.JulianDate(12, 0), stop: new import__45.JulianDate(14, 0), isStartIncluded: false, data: new import__45.ConstantPositionProperty(new import__45.Cartesian3(4, 5, 6)) }); const property = new import__45.CompositePositionProperty(); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); expect(property.isConstant).toBe(false); const expected = new import__45.Cartesian3(); const result1 = property.getValue(interval1.start, expected); expect(result1).toBe(expected); expect(result1).toEqual(interval1.data.getValue(interval1.start)); const result2 = property.getValue(interval2.stop, expected); expect(result2).toBe(expected); expect(result2).toEqual(interval2.data.getValue(interval2.stop)); }); it("getValue works without a result parameter", function() { const interval1 = new import__45.TimeInterval({ start: new import__45.JulianDate(10, 0), stop: new import__45.JulianDate(12, 0), data: new import__45.ConstantPositionProperty(new import__45.Cartesian3(1, 2, 3)) }); const interval2 = new import__45.TimeInterval({ start: new import__45.JulianDate(12, 0), stop: new import__45.JulianDate(14, 0), isStartIncluded: false, data: new import__45.ConstantPositionProperty(new import__45.Cartesian3(4, 5, 6)) }); const property = new import__45.CompositePositionProperty(); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); const result1 = property.getValue(interval1.start); expect(result1).toEqual(interval1.data.getValue(interval1.start)); const result2 = property.getValue(interval2.stop); expect(result2).toEqual(interval2.data.getValue(interval2.stop)); }); it("getValue returns in fixed frame", function() { const interval1 = new import__45.TimeInterval({ start: new import__45.JulianDate(10, 0), stop: new import__45.JulianDate(12, 0), data: new import__45.ConstantPositionProperty( new import__45.Cartesian3(1, 2, 3), import__45.ReferenceFrame.INERTIAL ) }); const interval2 = new import__45.TimeInterval({ start: new import__45.JulianDate(12, 0), stop: new import__45.JulianDate(14, 0), isStartIncluded: false, data: new import__45.ConstantPositionProperty( new import__45.Cartesian3(4, 5, 6), import__45.ReferenceFrame.FIXED ) }); const property = new import__45.CompositePositionProperty(); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); const valueInertial = new import__45.Cartesian3(1, 2, 3); const valueFixed = import__45.PositionProperty.convertToReferenceFrame( interval1.start, valueInertial, import__45.ReferenceFrame.INERTIAL, import__45.ReferenceFrame.FIXED ); const result1 = property.getValue(interval1.start); expect(result1).toEqual(valueFixed); const result2 = property.getValue(interval2.stop); expect(result2).toEqual(interval2.data.getValue(interval2.stop)); }); it("getValueInReferenceFrame works with a result parameter", function() { const interval1 = new import__45.TimeInterval({ start: new import__45.JulianDate(10, 0), stop: new import__45.JulianDate(12, 0), data: new import__45.ConstantPositionProperty( new import__45.Cartesian3(1, 2, 3), import__45.ReferenceFrame.INERTIAL ) }); const interval2 = new import__45.TimeInterval({ start: new import__45.JulianDate(12, 0), stop: new import__45.JulianDate(14, 0), isStartIncluded: false, data: new import__45.ConstantPositionProperty( new import__45.Cartesian3(4, 5, 6), import__45.ReferenceFrame.FIXED ) }); const property = new import__45.CompositePositionProperty(); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); const expected = new import__45.Cartesian3(); const result1 = property.getValueInReferenceFrame( interval1.start, import__45.ReferenceFrame.INERTIAL, expected ); expect(result1).toBe(expected); expect(result1).toEqual( interval1.data.getValueInReferenceFrame( interval1.start, import__45.ReferenceFrame.INERTIAL ) ); const result2 = property.getValueInReferenceFrame( interval2.stop, import__45.ReferenceFrame.FIXED, expected ); expect(result2).toBe(expected); expect(result2).toEqual( interval2.data.getValueInReferenceFrame( interval2.stop, import__45.ReferenceFrame.FIXED ) ); }); it("getValueInReferenceFrame works without a result parameter", function() { const interval1 = new import__45.TimeInterval({ start: new import__45.JulianDate(10, 0), stop: new import__45.JulianDate(12, 0), data: new import__45.ConstantPositionProperty( new import__45.Cartesian3(1, 2, 3), import__45.ReferenceFrame.INERTIAL ) }); const interval2 = new import__45.TimeInterval({ start: new import__45.JulianDate(12, 0), stop: new import__45.JulianDate(14, 0), isStartIncluded: false, data: new import__45.ConstantPositionProperty( new import__45.Cartesian3(4, 5, 6), import__45.ReferenceFrame.FIXED ) }); const property = new import__45.CompositePositionProperty(); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); const result1 = property.getValueInReferenceFrame( interval1.start, import__45.ReferenceFrame.INERTIAL ); expect(result1).toEqual( interval1.data.getValueInReferenceFrame( interval1.start, import__45.ReferenceFrame.INERTIAL ) ); const result2 = property.getValueInReferenceFrame( interval2.stop, import__45.ReferenceFrame.FIXED ); expect(result2).toEqual( interval2.data.getValueInReferenceFrame( interval2.stop, import__45.ReferenceFrame.FIXED ) ); }); it("equals works", function() { const interval1 = new import__45.TimeInterval({ start: new import__45.JulianDate(10, 0), stop: new import__45.JulianDate(12, 0), data: new import__45.ConstantPositionProperty(new import__45.Cartesian3(1, 2, 3)) }); const interval2 = new import__45.TimeInterval({ start: new import__45.JulianDate(12, 0), stop: new import__45.JulianDate(14, 0), isStartIncluded: false, data: new import__45.ConstantPositionProperty(new import__45.Cartesian3(4, 5, 6)) }); const left = new import__45.CompositePositionProperty(); left.intervals.addInterval(interval1); left.intervals.addInterval(interval2); const right = new import__45.CompositePositionProperty(); right.intervals.addInterval(interval1); expect(left.equals(right)).toEqual(false); right.intervals.addInterval(interval2); expect(left.equals(right)).toEqual(true); right.referenceFrame = import__45.ReferenceFrame.INERTIAL; expect(left.equals(right)).toEqual(false); }); it("getValue throws with no time parameter", function() { const property = new import__45.CompositePositionProperty(); expect(function() { property.getValue(void 0); }).toThrowDeveloperError(); }); it("getValueInReferenceFrame throws with no referenceFrame parameter", function() { const property = new import__45.CompositePositionProperty(); const time2 = import__45.JulianDate.now(); expect(function() { property.getValueInReferenceFrame(time2, void 0); }).toThrowDeveloperError(); }); it("raises definitionChanged event in all cases", function() { const interval1 = new import__45.TimeInterval({ start: new import__45.JulianDate(10, 0), stop: new import__45.JulianDate(12, 0), data: new import__45.ConstantPositionProperty(new import__45.Cartesian3(1, 2, 3)) }); const interval2 = new import__45.TimeInterval({ start: new import__45.JulianDate(12, 0), stop: new import__45.JulianDate(14, 0), isStartIncluded: false, data: new import__45.ConstantPositionProperty(new import__45.Cartesian3(4, 5, 6)) }); const property = new import__45.CompositePositionProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.intervals.addInterval(interval1); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.intervals.addInterval(interval2); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.intervals.removeInterval(interval2); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); interval1.data.setValue(new import__45.Cartesian3()); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.intervals.removeAll(); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); }); it("does not raise definitionChanged for an overwritten interval", function() { const interval1 = new import__45.TimeInterval({ start: new import__45.JulianDate(11, 0), stop: new import__45.JulianDate(13, 0), data: new import__45.ConstantPositionProperty(new import__45.Cartesian3(1, 2, 3)) }); const interval2 = new import__45.TimeInterval({ start: new import__45.JulianDate(10, 0), stop: new import__45.JulianDate(14, 0), isStartIncluded: false, data: new import__45.ConstantPositionProperty(new import__45.Cartesian3(4, 5, 6)) }); const property = new import__45.CompositePositionProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); expect(listener.calls.count()).toBe(2); interval1.data.setValue(new import__45.Cartesian3()); expect(listener.calls.count()).toBe(2); }); }); // packages/engine/Specs/DataSources/CompositePropertySpec.js var import__46 = __toESM(require_Cesium(), 1); describe("DataSources/CompositeProperty", function() { it("default constructor has expected values", function() { const property = new import__46.CompositeProperty(); expect(property.intervals).toBeInstanceOf(import__46.TimeIntervalCollection); expect(property.getValue(import__46.JulianDate.now())).toBeUndefined(); expect(property.isConstant).toBe(true); }); it("works without a result parameter", function() { const interval1 = new import__46.TimeInterval({ start: new import__46.JulianDate(10, 0), stop: new import__46.JulianDate(12, 0), data: new import__46.ConstantProperty(new import__46.Cartesian3(1, 2, 3)) }); const interval2 = new import__46.TimeInterval({ start: new import__46.JulianDate(12, 0), stop: new import__46.JulianDate(14, 0), isStartIncluded: false, data: new import__46.ConstantProperty(new import__46.Cartesian3(4, 5, 6)) }); const property = new import__46.CompositeProperty(); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); expect(property.isConstant).toBe(false); const result1 = property.getValue(interval1.start); expect(result1).not.toBe(interval1.data.getValue(interval1.start)); expect(result1).toEqual(interval1.data.getValue(interval1.start)); const result2 = property.getValue(interval2.stop); expect(result2).not.toBe(interval2.data.getValue(interval2.stop)); expect(result2).toEqual(interval2.data.getValue(interval2.stop)); }); it("works with a result parameter", function() { const interval1 = new import__46.TimeInterval({ start: new import__46.JulianDate(10, 0), stop: new import__46.JulianDate(12, 0), data: new import__46.ConstantProperty(new import__46.Cartesian3(1, 2, 3)) }); const interval2 = new import__46.TimeInterval({ start: new import__46.JulianDate(12, 0), stop: new import__46.JulianDate(14, 0), isStartIncluded: false, data: new import__46.ConstantProperty(new import__46.Cartesian3(4, 5, 6)) }); const property = new import__46.CompositeProperty(); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); expect(property.isConstant).toBe(false); const expected = new import__46.Cartesian3(); const result1 = property.getValue(interval1.start, expected); expect(result1).toBe(expected); expect(result1).toEqual(interval1.data.getValue(interval1.start)); const result2 = property.getValue(interval2.stop, expected); expect(result2).toBe(expected); expect(result2).toEqual(interval2.data.getValue(interval2.stop)); }); it("equals works", function() { const interval1 = new import__46.TimeInterval({ start: new import__46.JulianDate(10, 0), stop: new import__46.JulianDate(12, 0), data: new import__46.ConstantProperty(new import__46.Cartesian3(1, 2, 3)) }); const interval2 = new import__46.TimeInterval({ start: new import__46.JulianDate(12, 0), stop: new import__46.JulianDate(14, 0), isStartIncluded: false, data: new import__46.ConstantProperty(new import__46.Cartesian3(4, 5, 6)) }); const left = new import__46.CompositeProperty(); left.intervals.addInterval(interval1); left.intervals.addInterval(interval2); const right = new import__46.CompositeProperty(); right.intervals.addInterval(interval1); expect(left.equals(right)).toEqual(false); right.intervals.addInterval(interval2); expect(left.equals(right)).toEqual(true); }); it("raises definitionChanged event in all cases", function() { const interval1 = new import__46.TimeInterval({ start: new import__46.JulianDate(10, 0), stop: new import__46.JulianDate(12, 0), data: new import__46.ConstantProperty(new import__46.Cartesian3(1, 2, 3)) }); const interval2 = new import__46.TimeInterval({ start: new import__46.JulianDate(12, 0), stop: new import__46.JulianDate(14, 0), isStartIncluded: false, data: new import__46.ConstantProperty(new import__46.Cartesian3(4, 5, 6)) }); const property = new import__46.CompositeProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.intervals.addInterval(interval1); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.intervals.addInterval(interval2); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.intervals.removeInterval(interval2); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); interval1.data.setValue(new import__46.Cartesian3()); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.intervals.removeAll(); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); }); it("does not raise definitionChanged for an overwritten interval", function() { const interval1 = new import__46.TimeInterval({ start: new import__46.JulianDate(11, 0), stop: new import__46.JulianDate(13, 0), data: new import__46.ConstantProperty(new import__46.Cartesian3(1, 2, 3)) }); const interval2 = new import__46.TimeInterval({ start: new import__46.JulianDate(10), stop: new import__46.JulianDate(14, 0), isStartIncluded: false, data: new import__46.ConstantProperty(new import__46.Cartesian3(4, 5, 6)) }); const property = new import__46.CompositeProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); expect(listener.calls.count()).toBe(2); interval1.data.setValue(new import__46.Cartesian3()); expect(listener.calls.count()).toBe(2); }); it("getValue throws with no time parameter", function() { const property = new import__46.CompositeProperty(); expect(function() { property.getValue(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/ConstantPositionPropertySpec.js var import__47 = __toESM(require_Cesium(), 1); describe("DataSources/ConstantPositionProperty", function() { const time2 = import__47.JulianDate.now(); it("Constructor sets expected defaults", function() { let property = new import__47.ConstantPositionProperty(); expect(property.referenceFrame).toBe(import__47.ReferenceFrame.FIXED); property = new import__47.ConstantPositionProperty( new import__47.Cartesian3(1, 2, 3), import__47.ReferenceFrame.INERTIAL ); expect(property.referenceFrame).toBe(import__47.ReferenceFrame.INERTIAL); }); it("getValue works without a result parameter", function() { const value = new import__47.Cartesian3(1, 2, 3); const property = new import__47.ConstantPositionProperty(value); const result = property.getValue(time2); expect(result).not.toBe(value); expect(result).toEqual(value); }); it("getValue works with a result parameter", function() { const value = new import__47.Cartesian3(1, 2, 3); const property = new import__47.ConstantPositionProperty(value); const expected = new import__47.Cartesian3(); const result = property.getValue(time2, expected); expect(result).toBe(expected); expect(expected).toEqual(value); }); it("getValue returns in fixed frame", function() { const valueInertial = new import__47.Cartesian3(1, 2, 3); const valueFixed = import__47.PositionProperty.convertToReferenceFrame( time2, valueInertial, import__47.ReferenceFrame.INERTIAL, import__47.ReferenceFrame.FIXED ); const property = new import__47.ConstantPositionProperty( valueInertial, import__47.ReferenceFrame.INERTIAL ); const result = property.getValue(time2); expect(result).toEqual(valueFixed); }); it("getValue works with undefined fixed value", function() { const property = new import__47.ConstantPositionProperty(void 0); expect(property.getValue(time2)).toBeUndefined(); }); it("getValue work swith undefined inertial value", function() { const property = new import__47.ConstantPositionProperty( void 0, import__47.ReferenceFrame.INERTIAL ); expect(property.getValue(time2)).toBeUndefined(); }); it("getValueInReferenceFrame works without a result parameter", function() { const value = new import__47.Cartesian3(1, 2, 3); const property = new import__47.ConstantPositionProperty(value); const result = property.getValueInReferenceFrame( time2, import__47.ReferenceFrame.INERTIAL ); expect(result).not.toBe(value); expect(result).toEqual( import__47.PositionProperty.convertToReferenceFrame( time2, value, import__47.ReferenceFrame.FIXED, import__47.ReferenceFrame.INERTIAL ) ); }); it("getValueInReferenceFrame works with a result parameter", function() { const value = new import__47.Cartesian3(1, 2, 3); const property = new import__47.ConstantPositionProperty( value, import__47.ReferenceFrame.INERTIAL ); const expected = new import__47.Cartesian3(); const result = property.getValueInReferenceFrame( time2, import__47.ReferenceFrame.FIXED, expected ); expect(result).toBe(expected); expect(expected).toEqual( import__47.PositionProperty.convertToReferenceFrame( time2, value, import__47.ReferenceFrame.INERTIAL, import__47.ReferenceFrame.FIXED ) ); }); it("setValue raises definitionChanged event", function() { const property = new import__47.ConstantPositionProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.setValue(new import__47.Cartesian3(1, 2, 3)); expect(listener).toHaveBeenCalledWith(property); }); it("setValue does not raise definitionChanged event with equal data", function() { const property = new import__47.ConstantPositionProperty(new import__47.Cartesian3(0, 0, 0)); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.setValue(new import__47.Cartesian3(0, 0, 0)); expect(listener.calls.count()).toBe(0); }); it("setValue raises definitionChanged when referenceFrame changes", function() { const property = new import__47.ConstantPositionProperty( new import__47.Cartesian3(0, 0, 0), import__47.ReferenceFrame.FIXED ); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.setValue(new import__47.Cartesian3(0, 0, 0), import__47.ReferenceFrame.INERTIAL); expect(listener).toHaveBeenCalledWith(property); }); it("equals works", function() { const left = new import__47.ConstantPositionProperty( new import__47.Cartesian3(1, 2, 3), import__47.ReferenceFrame.INERTIAL ); let right = new import__47.ConstantPositionProperty( new import__47.Cartesian3(1, 2, 3), import__47.ReferenceFrame.INERTIAL ); expect(left.equals(right)).toEqual(true); right = new import__47.ConstantPositionProperty( new import__47.Cartesian3(1, 2, 3), import__47.ReferenceFrame.FIXED ); expect(left.equals(right)).toEqual(false); right = new import__47.ConstantPositionProperty( new import__47.Cartesian3(1, 2, 4), import__47.ReferenceFrame.INERTIAL ); expect(left.equals(right)).toEqual(false); }); it("getValue throws without time parameter", function() { const property = new import__47.ConstantPositionProperty(new import__47.Cartesian3(1, 2, 3)); expect(function() { property.getValue(void 0); }).toThrowDeveloperError(); }); it("getValueInReferenceFrame throws with no referenceFrame parameter", function() { const property = new import__47.ConstantPositionProperty(new import__47.Cartesian3(1, 2, 3)); expect(function() { property.getValueInReferenceFrame(time2, void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/ConstantPropertySpec.js var import__48 = __toESM(require_Cesium(), 1); describe("DataSources/ConstantProperty", function() { const time2 = import__48.JulianDate.now(); it("works with basic types", function() { const expected = 5; const property = new import__48.ConstantProperty(expected); expect(property.getValue(time2)).toBe(expected); expect(property.valueOf()).toBe(expected); expect(property.toString()).toBe(expected.toString()); expect(0 + property).toBe(expected); expect(`0${property}`).toBe(`0${expected}`); }); it("works with objects", function() { const value = new import__48.Cartesian3(1, 2, 3); const property = new import__48.ConstantProperty(value); const result = property.getValue(time2); expect(result).not.toBe(value); expect(result).toEqual(value); expect(property.valueOf()).toEqual(value); expect(property.toString()).toEqual(value.toString()); }); it("works with objects without clone", function() { const value = {}; const property = new import__48.ConstantProperty(value); const result = property.getValue(time2); expect(result).toBe(value); expect(result).toEqual(value); expect(property.valueOf()).toEqual(value); expect(property.toString()).toEqual(value.toString()); }); it("setValue raises definitionChanged event", function() { const property = new import__48.ConstantProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.setValue(5); expect(listener).toHaveBeenCalledWith(property); }); it("setValue does not raise definitionChanged event with equal data", function() { const property = new import__48.ConstantProperty(new import__48.Cartesian3(0, 0, 0)); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.setValue(new import__48.Cartesian3(0, 0, 0)); expect(listener.calls.count()).toBe(0); }); it("works with objects with result parameter", function() { const value = new import__48.Cartesian3(1, 2, 3); const property = new import__48.ConstantProperty(value); const expected = new import__48.Cartesian3(); const result = property.getValue(time2, expected); expect(result).toBe(expected); expect(expected).toEqual(value); }); it("works with undefined value", function() { const property = new import__48.ConstantProperty(void 0); expect(property.getValue()).toBeUndefined(); expect(property.valueOf()).toBeUndefined(); expect(0 + property).toBeNaN(); expect(`0${property}`).toBe("0undefined"); }); it('equals works for object types with "equals" function', function() { const left = new import__48.ConstantProperty(new import__48.Cartesian3(1, 2, 3)); let right = new import__48.ConstantProperty(new import__48.Cartesian3(1, 2, 3)); expect(left.equals(right)).toEqual(true); right = new import__48.ConstantProperty(new import__48.Cartesian3(1, 2, 4)); expect(left.equals(right)).toEqual(false); }); it('equals works for object types without "equals" function', function() { const value = {}; const left = new import__48.ConstantProperty(value); let right = new import__48.ConstantProperty(value); expect(left.equals(right)).toEqual(true); right = new import__48.ConstantProperty({}); expect(left.equals(right)).toEqual(false); }); it("equals works for simple types", function() { const left = new import__48.ConstantProperty(1); let right = new import__48.ConstantProperty(1); expect(left.equals(right)).toEqual(true); right = new import__48.ConstantProperty(2); expect(left.equals(right)).toEqual(false); }); }); // packages/engine/Specs/DataSources/CorridorGeometryUpdaterSpec.js var import__49 = __toESM(require_Cesium(), 1); var import__50 = __toESM(require_Cesium(), 1); // Specs/createGeometryUpdaterGroundGeometrySpecs.js var import_engine14 = __toESM(require_Cesium(), 1); function createGeometryUpdaterGroundGeometrySpecs(Updater, geometryPropertyName, createEntity, createDynamicEntity, getScene) { const time2 = import_engine14.JulianDate.now(); it("has default zIndex of zero", function() { const entity = createEntity(); const updater = new Updater(entity, getScene()); expect(updater.zIndex.getValue()).toBe(0); }); it("uses zIndex value", function() { const entity = createEntity(); entity[geometryPropertyName].zIndex = 22; const updater = new Updater(entity, getScene()); expect(updater.zIndex.getValue()).toBe(22); }); it("A time-varying color does not cause ground geometry to be dynamic", function() { const entity = createEntity(); const color = new import_engine14.SampledProperty(import_engine14.Color); color.addSample(time2, import_engine14.Color.WHITE); entity[geometryPropertyName].material = new import_engine14.ColorMaterialProperty(color); const updater = new Updater(entity, getScene()); expect(updater.isDynamic).toBe(false); }); it("Checks that an entity without height and extrudedHeight is on terrain", function() { const entity = createEntity(); const geometry = entity[geometryPropertyName]; geometry.height = void 0; geometry.outline = new import_engine14.ConstantProperty(true); const updater = new Updater(entity, getScene()); if (import_engine14.GroundPrimitive.isSupported(getScene())) { expect(updater.onTerrain).toBe(true); expect(updater.outlineEnabled).toBe(false); } else { expect(updater.onTerrain).toBe(false); expect(updater.outlineEnabled).toBe(true); } }); it("Checks that an entity with height isn't on terrain", function() { const entity = createEntity(); entity[geometryPropertyName].height = new import_engine14.ConstantProperty(1); const updater = new Updater(entity, getScene()); expect(updater.onTerrain).toBe(false); }); it("Checks that an entity with extrudedHeight isn't on terrain", function() { const entity = createEntity(); const geometry = entity[geometryPropertyName]; geometry.height = void 0; geometry.extrudedHeight = new import_engine14.ConstantProperty(1); const updater = new Updater(entity, getScene()); expect(updater.onTerrain).toBe(false); }); it("fill is true sets onTerrain to true", function() { const entity = createEntity(); entity[geometryPropertyName].fill = true; const updater = new Updater(entity, getScene()); if (import_engine14.GroundPrimitive.isSupported(getScene())) { expect(updater.onTerrain).toBe(true); } else { expect(updater.onTerrain).toBe(false); } }); it("fill is false sets onTerrain to false", function() { const entity = createEntity(); entity[geometryPropertyName].fill = false; const updater = new Updater(entity, getScene()); expect(updater.onTerrain).toBe(false); }); it("a defined height sets onTerrain to false", function() { const entity = createEntity(); const geometry = entity[geometryPropertyName]; geometry.fill = true; geometry.height = 0; const updater = new Updater(entity, getScene()); expect(updater.onTerrain).toBe(false); }); it("a defined extrudedHeight sets onTerrain to false", function() { const entity = createEntity(); const geometry = entity[geometryPropertyName]; geometry.fill = true; geometry.extrudedHeight = 12; const updater = new Updater(entity, getScene()); expect(updater.onTerrain).toBe(false); }); it("Creates geometry with no offsetAttribute when geometry is on terrain", function() { const entity = createEntity(); const updater = new Updater(entity, getScene()); const instance = updater.createFillGeometryInstance(time2); const geometry = instance.geometry; expect(geometry._offsetAttribute).toBeUndefined(); }); it("Creates geometry with expected offsetAttribute based on height and extrudedHeight", function() { const entity = createEntity(); const graphics = entity[geometryPropertyName]; graphics.outline = true; graphics.outlineColor = import_engine14.Color.BLACK; graphics.height = new import_engine14.ConstantProperty(20); graphics.extrudedHeight = new import_engine14.ConstantProperty(0); const updater = new Updater(entity, getScene()); let instance; updater._onEntityPropertyChanged(entity, geometryPropertyName); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); graphics.heightReference = new import_engine14.ConstantProperty(import_engine14.HeightReference.NONE); graphics.extrudedHeightReference = new import_engine14.ConstantProperty( import_engine14.HeightReference.NONE ); updater._onEntityPropertyChanged(entity, geometryPropertyName); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); graphics.heightReference = new import_engine14.ConstantProperty(import_engine14.HeightReference.NONE); graphics.extrudedHeightReference = new import_engine14.ConstantProperty( import_engine14.HeightReference.CLAMP_TO_GROUND ); updater._onEntityPropertyChanged(entity, geometryPropertyName); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); graphics.heightReference = new import_engine14.ConstantProperty(import_engine14.HeightReference.NONE); graphics.extrudedHeightReference = new import_engine14.ConstantProperty( import_engine14.HeightReference.RELATIVE_TO_GROUND ); updater._onEntityPropertyChanged(entity, geometryPropertyName); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import_engine14.GeometryOffsetAttribute.TOP ); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import_engine14.GeometryOffsetAttribute.TOP ); graphics.heightReference = new import_engine14.ConstantProperty( import_engine14.HeightReference.CLAMP_TO_GROUND ); graphics.extrudedHeightReference = new import_engine14.ConstantProperty( import_engine14.HeightReference.NONE ); updater._onEntityPropertyChanged(entity, geometryPropertyName); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import_engine14.GeometryOffsetAttribute.TOP ); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import_engine14.GeometryOffsetAttribute.TOP ); graphics.heightReference = new import_engine14.ConstantProperty( import_engine14.HeightReference.CLAMP_TO_GROUND ); graphics.extrudedHeightReference = new import_engine14.ConstantProperty( import_engine14.HeightReference.CLAMP_TO_GROUND ); updater._onEntityPropertyChanged(entity, geometryPropertyName); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import_engine14.GeometryOffsetAttribute.TOP ); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import_engine14.GeometryOffsetAttribute.TOP ); graphics.heightReference = new import_engine14.ConstantProperty( import_engine14.HeightReference.CLAMP_TO_GROUND ); graphics.extrudedHeightReference = new import_engine14.ConstantProperty( import_engine14.HeightReference.RELATIVE_TO_GROUND ); updater._onEntityPropertyChanged(entity, geometryPropertyName); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import_engine14.GeometryOffsetAttribute.ALL ); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import_engine14.GeometryOffsetAttribute.ALL ); graphics.heightReference = new import_engine14.ConstantProperty( import_engine14.HeightReference.RELATIVE_TO_GROUND ); graphics.extrudedHeightReference = new import_engine14.ConstantProperty( import_engine14.HeightReference.NONE ); updater._onEntityPropertyChanged(entity, geometryPropertyName); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import_engine14.GeometryOffsetAttribute.TOP ); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import_engine14.GeometryOffsetAttribute.TOP ); graphics.heightReference = new import_engine14.ConstantProperty( import_engine14.HeightReference.RELATIVE_TO_GROUND ); graphics.extrudedHeightReference = new import_engine14.ConstantProperty( import_engine14.HeightReference.CLAMP_TO_GROUND ); updater._onEntityPropertyChanged(entity, geometryPropertyName); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import_engine14.GeometryOffsetAttribute.TOP ); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import_engine14.GeometryOffsetAttribute.TOP ); graphics.heightReference = new import_engine14.ConstantProperty( import_engine14.HeightReference.RELATIVE_TO_GROUND ); graphics.extrudedHeightReference = new import_engine14.ConstantProperty( import_engine14.HeightReference.RELATIVE_TO_GROUND ); updater._onEntityPropertyChanged(entity, geometryPropertyName); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import_engine14.GeometryOffsetAttribute.ALL ); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import_engine14.GeometryOffsetAttribute.ALL ); graphics.height = void 0; graphics.extrudedHeight = void 0; updater._onEntityPropertyChanged(entity, geometryPropertyName); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); }); it("color material sets onTerrain to true", function() { const entity = createEntity(); const geometry = entity[geometryPropertyName]; geometry.fill = true; geometry.material = new import_engine14.ColorMaterialProperty(import_engine14.Color.WHITE); const updater = new Updater(entity, getScene()); if (import_engine14.GroundPrimitive.isSupported(getScene())) { expect(updater.onTerrain).toBe(true); } else { expect(updater.onTerrain).toBe(false); } }); it("dynamic updater on terrain", function() { const entity = createDynamicEntity(); const updater = new Updater(entity, getScene()); const primitives = new import_engine14.PrimitiveCollection(); const groundPrimitives = new import_engine14.PrimitiveCollection(); const dynamicUpdater = updater.createDynamicUpdater( primitives, groundPrimitives ); expect(dynamicUpdater.isDestroyed()).toBe(false); expect(primitives.length).toBe(0); expect(groundPrimitives.length).toBe(0); dynamicUpdater.update(time2); if (import_engine14.GroundPrimitive.isSupported(getScene())) { expect(primitives.length).toBe(0); expect(groundPrimitives.length).toBe(1); } else { expect(primitives.length).toBe(2); expect(groundPrimitives.length).toBe(0); } dynamicUpdater.destroy(); updater.destroy(); }); it("dynamic updater on terrain propagates classification type", function() { const entity = createDynamicEntity(); entity[geometryPropertyName].classificationType = import_engine14.ClassificationType.BOTH; const updater = new Updater(entity, getScene()); const primitives = new import_engine14.PrimitiveCollection(); const groundPrimitives = new import_engine14.PrimitiveCollection(); const dynamicUpdater = updater.createDynamicUpdater( primitives, groundPrimitives ); dynamicUpdater.update(time2); if (import_engine14.GroundPrimitive.isSupported(getScene())) { expect(groundPrimitives.get(0).classificationType).toEqual( import_engine14.ClassificationType.BOTH ); } dynamicUpdater.destroy(); updater.destroy(); }); } var createGeometryUpdaterGroundGeometrySpecs_default = createGeometryUpdaterGroundGeometrySpecs; // packages/engine/Specs/DataSources/CorridorGeometryUpdaterSpec.js describe( "DataSources/CorridorGeometryUpdater", function() { let scene2; let time2; beforeAll(function() { scene2 = createScene_default(); time2 = import__49.JulianDate.now(); return import__49.ApproximateTerrainHeights.initialize(); }); afterAll(function() { scene2.destroyForSpecs(); import__49.ApproximateTerrainHeights._initPromise = void 0; import__49.ApproximateTerrainHeights._terrainHeights = void 0; }); function createBasicCorridor() { const corridor = new import__49.CorridorGraphics(); corridor.positions = new import__49.ConstantProperty( import__49.Cartesian3.fromDegreesArray([0, 0, 1, 0, 1, 1, 0, 1]) ); corridor.width = new import__49.ConstantProperty(1); corridor.height = new import__49.ConstantProperty(0); const entity = new import__49.Entity(); entity.corridor = corridor; return entity; } function createDynamicCorridor() { const entity = createBasicCorridor(); entity.corridor.positions = createDynamicProperty_default( import__49.Cartesian3.fromDegreesArray([0, 0, 1, 0, 1, 1, 0, 1]) ); return entity; } function createBasicCorridorWithoutHeight() { const corridor = new import__49.CorridorGraphics(); corridor.positions = new import__49.ConstantProperty( import__49.Cartesian3.fromDegreesArray([0, 0, 1, 0, 1, 1, 0, 1]) ); corridor.width = new import__49.ConstantProperty(1); const entity = new import__49.Entity(); entity.corridor = corridor; return entity; } function createDynamicCorridorWithoutHeight() { const entity = createBasicCorridorWithoutHeight(); entity.corridor.positions = createDynamicProperty_default( import__49.Cartesian3.fromDegreesArray([0, 0, 1, 0, 1, 1, 0, 1]) ); return entity; } it("A time-varying positions causes geometry to be dynamic", function() { const entity = createBasicCorridor(); const updater = new import__49.CorridorGeometryUpdater(entity, scene2); const point1 = new import__49.SampledPositionProperty(); point1.addSample(time2, new import__49.Cartesian3()); const point2 = new import__49.SampledPositionProperty(); point2.addSample(time2, new import__49.Cartesian3()); const point3 = new import__49.SampledPositionProperty(); point3.addSample(time2, new import__49.Cartesian3()); entity.corridor.positions = new import__49.PropertyArray(); entity.corridor.positions.setValue([point1, point2, point3]); updater._onEntityPropertyChanged(entity, "corridor"); expect(updater.isDynamic).toBe(true); }); it("A time-varying height causes geometry to be dynamic", function() { const entity = createBasicCorridor(); const updater = new import__49.CorridorGeometryUpdater(entity, scene2); entity.corridor.height = new import__49.SampledProperty(Number); entity.corridor.height.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "corridor"); expect(updater.isDynamic).toBe(true); }); it("A time-varying extrudedHeight causes geometry to be dynamic", function() { const entity = createBasicCorridor(); const updater = new import__49.CorridorGeometryUpdater(entity, scene2); entity.corridor.extrudedHeight = new import__49.SampledProperty(Number); entity.corridor.extrudedHeight.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "corridor"); expect(updater.isDynamic).toBe(true); }); it("A time-varying granularity causes geometry to be dynamic", function() { const entity = createBasicCorridor(); const updater = new import__49.CorridorGeometryUpdater(entity, scene2); entity.corridor.granularity = new import__49.SampledProperty(Number); entity.corridor.granularity.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "corridor"); expect(updater.isDynamic).toBe(true); }); it("A time-varying width causes geometry to be dynamic", function() { const entity = createBasicCorridor(); const updater = new import__49.CorridorGeometryUpdater(entity, scene2); entity.corridor.width = new import__49.SampledProperty(Number); entity.corridor.width.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "corridor"); expect(updater.isDynamic).toBe(true); }); it("A time-varying cornerType causes geometry to be dynamic", function() { const entity = createBasicCorridor(); const updater = new import__49.CorridorGeometryUpdater(entity, scene2); entity.corridor.cornerType = new import__49.TimeIntervalCollectionProperty(); entity.corridor.cornerType.intervals.addInterval( new import__49.TimeInterval({ start: import__49.JulianDate.now(), stop: import__49.JulianDate.now(), data: import__49.CornerType.ROUNDED }) ); updater._onEntityPropertyChanged(entity, "corridor"); expect(updater.isDynamic).toBe(true); }); it("Creates geometry with expected properties", function() { const options = { height: 431, extrudedHeight: 123, granularity: 0.97, width: 12, cornerType: import__49.CornerType.MITERED }; const entity = createBasicCorridor(); const corridor = entity.corridor; corridor.outline = true; corridor.cornerType = new import__49.ConstantProperty(options.cornerType); corridor.width = new import__49.ConstantProperty(options.width); corridor.height = new import__49.ConstantProperty(options.height); corridor.extrudedHeight = new import__49.ConstantProperty(options.extrudedHeight); corridor.granularity = new import__49.ConstantProperty(options.granularity); const updater = new import__49.CorridorGeometryUpdater(entity, scene2); let instance; let geometry; instance = updater.createFillGeometryInstance(time2); geometry = instance.geometry; expect(geometry._width).toEqual(options.width); expect(geometry._height).toEqual(options.height); expect(geometry._granularity).toEqual(options.granularity); expect(geometry._extrudedHeight).toEqual(options.extrudedHeight); expect(geometry._cornerType).toEqual(options.cornerType); expect(geometry._offsetAttribute).toBeUndefined(); instance = updater.createOutlineGeometryInstance(time2); geometry = instance.geometry; expect(geometry._width).toEqual(options.width); expect(geometry._height).toEqual(options.height); expect(geometry._granularity).toEqual(options.granularity); expect(geometry._extrudedHeight).toEqual(options.extrudedHeight); expect(geometry._cornerType).toEqual(options.cornerType); expect(geometry._offsetAttribute).toBeUndefined(); }); it("dynamic updater sets properties", function() { const corridor = new import__49.CorridorGraphics(); corridor.positions = createDynamicProperty_default( import__49.Cartesian3.fromDegreesArray([0, 0, 1, 0, 1, 1, 0, 1]) ); corridor.show = createDynamicProperty_default(true); corridor.height = createDynamicProperty_default(3); corridor.extrudedHeight = createDynamicProperty_default(2); corridor.outline = createDynamicProperty_default(true); corridor.fill = createDynamicProperty_default(true); corridor.width = createDynamicProperty_default(6); corridor.granularity = createDynamicProperty_default(2); corridor.cornerType = createDynamicProperty_default(import__49.CornerType.MITERED); const entity = new import__49.Entity(); entity.corridor = corridor; const updater = new import__49.CorridorGeometryUpdater(entity, scene2); const dynamicUpdater = updater.createDynamicUpdater( new import__49.PrimitiveCollection(), new import__49.PrimitiveCollection() ); dynamicUpdater.update(time2); const options = dynamicUpdater._options; expect(options.positions).toEqual(corridor.positions.getValue()); expect(options.height).toEqual(corridor.height.getValue()); expect(options.extrudedHeight).toEqual( corridor.extrudedHeight.getValue() ); expect(options.width).toEqual(corridor.width.getValue()); expect(options.granularity).toEqual(corridor.granularity.getValue()); expect(options.cornerType).toEqual(corridor.cornerType.getValue()); expect(options.offsetAttribute).toBeUndefined(); }); it("geometryChanged event is raised when expected", function() { const entity = createBasicCorridor(); const updater = new import__49.CorridorGeometryUpdater(entity, scene2); const listener = jasmine.createSpy("listener"); updater.geometryChanged.addEventListener(listener); entity.corridor.positions = new import__49.ConstantProperty([]); updater._onEntityPropertyChanged(entity, "corridor"); expect(listener.calls.count()).toEqual(1); entity.corridor.height = new import__49.ConstantProperty(82); updater._onEntityPropertyChanged(entity, "corridor"); expect(listener.calls.count()).toEqual(2); entity.availability = new import__49.TimeIntervalCollection(); updater._onEntityPropertyChanged(entity, "availability"); expect(listener.calls.count()).toEqual(3); entity.corridor.positions = void 0; updater._onEntityPropertyChanged(entity, "corridor"); expect(listener.calls.count()).toEqual(4); entity.corridor.height = void 0; updater._onEntityPropertyChanged(entity, "corridor"); entity.viewFrom = new import__49.ConstantProperty(import__49.Cartesian3.UNIT_X); updater._onEntityPropertyChanged(entity, "viewFrom"); expect(listener.calls.count()).toEqual(4); }); it("computes center", function() { const entity = createBasicCorridor(); const updater = new import__49.CorridorGeometryUpdater(entity, scene2); expect(updater._computeCenter(time2)).toEqualEpsilon( import__49.Cartesian3.fromDegrees(1, 1), import__50.Math.EPSILON10 ); }); function getScene() { return scene2; } createGeometryUpdaterSpecs_default( import__49.CorridorGeometryUpdater, "corridor", createBasicCorridor, getScene ); createDynamicGeometryUpdaterSpecs_default( import__49.CorridorGeometryUpdater, "corridor", createDynamicCorridor, getScene ); createGeometryUpdaterGroundGeometrySpecs_default( import__49.CorridorGeometryUpdater, "corridor", createBasicCorridorWithoutHeight, createDynamicCorridorWithoutHeight, getScene ); }, "WebGL" ); // packages/engine/Specs/DataSources/CorridorGraphicsSpec.js var import__51 = __toESM(require_Cesium(), 1); describe("DataSources/CorridorGraphics", function() { it("creates expected instance from raw assignment and construction", function() { const options = { material: import__51.Color.BLUE, positions: [], show: true, height: 1, extrudedHeight: 2, granularity: 3, width: 4, fill: false, outline: false, outlineColor: import__51.Color.RED, outlineWidth: 5, cornerType: import__51.CornerType.BEVELED, shadows: import__51.ShadowMode.DISABLED, distanceDisplayCondition: new import__51.DistanceDisplayCondition(10, 100), classificationType: import__51.ClassificationType.TERRAIN, zIndex: 3 }; const corridor = new import__51.CorridorGraphics(options); expect(corridor.material).toBeInstanceOf(import__51.ColorMaterialProperty); expect(corridor.positions).toBeInstanceOf(import__51.ConstantProperty); expect(corridor.show).toBeInstanceOf(import__51.ConstantProperty); expect(corridor.height).toBeInstanceOf(import__51.ConstantProperty); expect(corridor.extrudedHeight).toBeInstanceOf(import__51.ConstantProperty); expect(corridor.granularity).toBeInstanceOf(import__51.ConstantProperty); expect(corridor.width).toBeInstanceOf(import__51.ConstantProperty); expect(corridor.fill).toBeInstanceOf(import__51.ConstantProperty); expect(corridor.outline).toBeInstanceOf(import__51.ConstantProperty); expect(corridor.outlineColor).toBeInstanceOf(import__51.ConstantProperty); expect(corridor.outlineWidth).toBeInstanceOf(import__51.ConstantProperty); expect(corridor.cornerType).toBeInstanceOf(import__51.ConstantProperty); expect(corridor.shadows).toBeInstanceOf(import__51.ConstantProperty); expect(corridor.distanceDisplayCondition).toBeInstanceOf(import__51.ConstantProperty); expect(corridor.classificationType).toBeInstanceOf(import__51.ConstantProperty); expect(corridor.zIndex).toBeInstanceOf(import__51.ConstantProperty); expect(corridor.material.color.getValue()).toEqual(options.material); expect(corridor.positions.getValue()).toEqual(options.positions); expect(corridor.show.getValue()).toEqual(options.show); expect(corridor.height.getValue()).toEqual(options.height); expect(corridor.extrudedHeight.getValue()).toEqual(options.extrudedHeight); expect(corridor.granularity.getValue()).toEqual(options.granularity); expect(corridor.width.getValue()).toEqual(options.width); expect(corridor.fill.getValue()).toEqual(options.fill); expect(corridor.outline.getValue()).toEqual(options.outline); expect(corridor.outlineColor.getValue()).toEqual(options.outlineColor); expect(corridor.outlineWidth.getValue()).toEqual(options.outlineWidth); expect(corridor.cornerType.getValue()).toEqual(options.cornerType); expect(corridor.shadows.getValue()).toEqual(options.shadows); expect(corridor.distanceDisplayCondition.getValue()).toEqual( options.distanceDisplayCondition ); expect(corridor.classificationType.getValue()).toEqual( options.classificationType ); expect(corridor.zIndex.getValue()).toEqual(options.zIndex); }); it("merge assigns unassigned properties", function() { const source = new import__51.CorridorGraphics(); source.material = new import__51.ColorMaterialProperty(); source.positions = new import__51.ConstantProperty(); source.show = new import__51.ConstantProperty(); source.height = new import__51.ConstantProperty(); source.extrudedHeight = new import__51.ConstantProperty(); source.granularity = new import__51.ConstantProperty(); source.width = new import__51.ConstantProperty(); source.fill = new import__51.ConstantProperty(); source.outline = new import__51.ConstantProperty(); source.outlineColor = new import__51.ConstantProperty(); source.outlineWidth = new import__51.ConstantProperty(); source.cornerType = new import__51.ConstantProperty(); source.shadows = new import__51.ConstantProperty(import__51.ShadowMode.ENABLED); source.distanceDisplayCondition = new import__51.ConstantProperty( new import__51.DistanceDisplayCondition(10, 100) ); source.classificationType = new import__51.ConstantProperty( import__51.ClassificationType.TERRAIN ); source.zIndex = new import__51.ConstantProperty(3); const target = new import__51.CorridorGraphics(); target.merge(source); expect(target.material).toBe(source.material); expect(target.positions).toBe(source.positions); expect(target.show).toBe(source.show); expect(target.height).toBe(source.height); expect(target.extrudedHeight).toBe(source.extrudedHeight); expect(target.granularity).toBe(source.granularity); expect(target.width).toBe(source.width); expect(target.fill).toBe(source.fill); expect(target.outline).toBe(source.outline); expect(target.outlineColor).toBe(source.outlineColor); expect(target.outlineWidth).toBe(source.outlineWidth); expect(target.cornerType).toBe(source.cornerType); expect(target.shadows).toBe(source.shadows); expect(target.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(target.classificationType).toBe(source.classificationType); expect(target.zIndex).toBe(source.zIndex); }); it("merge does not assign assigned properties", function() { const source = new import__51.CorridorGraphics(); const material = new import__51.ColorMaterialProperty(); const positions = new import__51.ConstantProperty(); const show = new import__51.ConstantProperty(); const height = new import__51.ConstantProperty(); const extrudedHeight = new import__51.ConstantProperty(); const granularity = new import__51.ConstantProperty(); const width = new import__51.ConstantProperty(); const fill = new import__51.ConstantProperty(); const outline = new import__51.ConstantProperty(); const outlineColor = new import__51.ConstantProperty(); const outlineWidth = new import__51.ConstantProperty(); const cornerType = new import__51.ConstantProperty(); const shadows = new import__51.ConstantProperty(); const distanceDisplayCondition = new import__51.ConstantProperty(); const classificationType = new import__51.ConstantProperty(); const zIndex = new import__51.ConstantProperty(); const target = new import__51.CorridorGraphics(); target.material = material; target.positions = positions; target.show = show; target.height = height; target.extrudedHeight = extrudedHeight; target.granularity = granularity; target.width = width; target.fill = fill; target.outline = outline; target.outlineColor = outlineColor; target.outlineWidth = outlineWidth; target.cornerType = cornerType; target.shadows = shadows; target.distanceDisplayCondition = distanceDisplayCondition; target.classificationType = classificationType; target.zIndex = zIndex; target.merge(source); expect(target.material).toBe(material); expect(target.positions).toBe(positions); expect(target.show).toBe(show); expect(target.height).toBe(height); expect(target.extrudedHeight).toBe(extrudedHeight); expect(target.granularity).toBe(granularity); expect(target.width).toBe(width); expect(target.fill).toBe(fill); expect(target.outline).toBe(outline); expect(target.outlineColor).toBe(outlineColor); expect(target.outlineWidth).toBe(outlineWidth); expect(target.cornerType).toBe(cornerType); expect(target.shadows).toBe(shadows); expect(target.distanceDisplayCondition).toBe(distanceDisplayCondition); expect(target.classificationType).toBe(classificationType); expect(target.zIndex).toBe(zIndex); }); it("clone works", function() { const source = new import__51.CorridorGraphics(); source.material = new import__51.ColorMaterialProperty(); source.positions = new import__51.ConstantProperty(); source.show = new import__51.ConstantProperty(); source.height = new import__51.ConstantProperty(); source.extrudedHeight = new import__51.ConstantProperty(); source.granularity = new import__51.ConstantProperty(); source.width = new import__51.ConstantProperty(); source.fill = new import__51.ConstantProperty(); source.outline = new import__51.ConstantProperty(); source.outlineColor = new import__51.ConstantProperty(); source.outlineWidth = new import__51.ConstantProperty(); source.cornerType = new import__51.ConstantProperty(); source.shadows = new import__51.ConstantProperty(); source.distanceDisplayCondition = new import__51.ConstantProperty(); source.classificationType = new import__51.ConstantProperty(); source.zIndex = new import__51.ConstantProperty(); const result = source.clone(); expect(result.material).toBe(source.material); expect(result.positions).toBe(source.positions); expect(result.show).toBe(source.show); expect(result.height).toBe(source.height); expect(result.extrudedHeight).toBe(source.extrudedHeight); expect(result.granularity).toBe(source.granularity); expect(result.width).toBe(source.width); expect(result.fill).toBe(source.fill); expect(result.outline).toBe(source.outline); expect(result.outlineColor).toBe(source.outlineColor); expect(result.outlineWidth).toBe(source.outlineWidth); expect(result.cornerType).toBe(source.cornerType); expect(result.shadows).toBe(source.shadows); expect(result.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(result.classificationType).toBe(source.classificationType); expect(result.zIndex).toBe(source.zIndex); }); it("merge throws if source undefined", function() { const target = new import__51.CorridorGraphics(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__51.CorridorGraphics(); testMaterialDefinitionChanged_default(property, "material", import__51.Color.RED, import__51.Color.BLUE); testDefinitionChanged_default(property, "positions", [], []); testDefinitionChanged_default(property, "show", true, false); testDefinitionChanged_default(property, "height", 3, 4); testDefinitionChanged_default(property, "extrudedHeight", 4, 3); testDefinitionChanged_default(property, "granularity", 1, 2); testDefinitionChanged_default(property, "width", 5, 6); testDefinitionChanged_default(property, "fill", false, true); testDefinitionChanged_default(property, "outline", true, false); testDefinitionChanged_default(property, "outlineColor", import__51.Color.RED, import__51.Color.BLUE); testDefinitionChanged_default(property, "outlineWidth", 2, 3); testDefinitionChanged_default( property, "cornerType", import__51.CornerType.BEVELED, import__51.CornerType.MITERED ); testDefinitionChanged_default( property, "shadows", import__51.ShadowMode.ENABLED, import__51.ShadowMode.DISABLED ); testDefinitionChanged_default( property, "distanceDisplayCondition", new import__51.DistanceDisplayCondition(), new import__51.DistanceDisplayCondition(10, 100) ); testDefinitionChanged_default( property, "classificationType", import__51.ClassificationType.TERRAIN, import__51.ClassificationType.BOTH ); testDefinitionChanged_default(property, "zIndex", 3, 0); }); }); // packages/engine/Specs/DataSources/CustomDataSourceSpec.js var import__52 = __toESM(require_Cesium(), 1); describe("DataSources/CustomDataSource", function() { it("constructor has expected defaults", function() { const dataSource = new import__52.CustomDataSource(); expect(dataSource.name).toBeUndefined(); expect(dataSource.clock).toBeUndefined(); expect(dataSource.entities).toBeInstanceOf(import__52.EntityCollection); expect(dataSource.isLoading).toBe(false); expect(dataSource.changedEvent).toBeInstanceOf(import__52.Event); expect(dataSource.errorEvent).toBeInstanceOf(import__52.Event); expect(dataSource.loadingEvent).toBeInstanceOf(import__52.Event); expect(dataSource.show).toBe(true); }); it("show sets underlying entity collection show.", function() { const dataSource = new import__52.CustomDataSource(); dataSource.show = false; expect(dataSource.show).toBe(false); expect(dataSource.show).toEqual(dataSource.entities.show); dataSource.show = true; expect(dataSource.show).toBe(true); expect(dataSource.show).toEqual(dataSource.entities.show); }); it("setting name raises changed event", function() { const dataSource = new import__52.CustomDataSource(); const spy = jasmine.createSpy("changedEvent"); dataSource.changedEvent.addEventListener(spy); const newName = "chester"; dataSource.name = newName; expect(dataSource.name).toEqual(newName); expect(spy.calls.count()).toEqual(1); expect(spy).toHaveBeenCalledWith(dataSource); }); it("setting clock raises changed event", function() { const dataSource = new import__52.CustomDataSource(); const spy = jasmine.createSpy("changedEvent"); dataSource.changedEvent.addEventListener(spy); const newClock = new import__52.DataSourceClock(); dataSource.clock = newClock; expect(dataSource.clock).toBe(newClock); expect(spy.calls.count()).toEqual(1); expect(spy).toHaveBeenCalledWith(dataSource); }); it("setting isLoading raises loading event", function() { const dataSource = new import__52.CustomDataSource(); const spy = jasmine.createSpy("loadingEvent"); dataSource.loadingEvent.addEventListener(spy); dataSource.isLoading = true; expect(spy.calls.count()).toEqual(1); expect(spy).toHaveBeenCalledWith(dataSource, true); dataSource.isLoading = false; expect(spy.calls.count()).toEqual(2); expect(spy).toHaveBeenCalledWith(dataSource, false); }); it("has entity collection with link to data source", function() { const dataSource = new import__52.CustomDataSource(); const entityCollection = dataSource.entities; expect(entityCollection.owner).toEqual(dataSource); }); }); // packages/engine/Specs/DataSources/CylinderGeometryUpdaterSpec.js var import__53 = __toESM(require_Cesium(), 1); describe( "DataSources/CylinderGeometryUpdater", function() { let scene2; let time2; beforeAll(function() { scene2 = createScene_default(); time2 = import__53.JulianDate.now(); }); afterAll(function() { scene2.destroyForSpecs(); }); function createBasicCylinder() { const cylinder = new import__53.CylinderGraphics(); cylinder.length = new import__53.ConstantProperty(1e3); cylinder.topRadius = new import__53.ConstantProperty(1e3); cylinder.bottomRadius = new import__53.ConstantProperty(1e3); const entity = new import__53.Entity(); entity.position = new import__53.ConstantPositionProperty( import__53.Cartesian3.fromDegrees(0, 0, 0) ); entity.cylinder = cylinder; return entity; } function createDynamicCylinder() { const entity = createBasicCylinder(); entity.cylinder.topRadius = createDynamicProperty_default(4); return entity; } it("No geometry available when topRadius is undefined", function() { const entity = createBasicCylinder(); const updater = new import__53.CylinderGeometryUpdater(entity, scene2); entity.cylinder.topRadius = void 0; updater._onEntityPropertyChanged(entity, "cylinder"); expect(updater.fillEnabled).toBe(false); expect(updater.outlineEnabled).toBe(false); expect(updater.isDynamic).toBe(false); }); it("No geometry available when bottomRadius is undefined", function() { const entity = createBasicCylinder(); const updater = new import__53.CylinderGeometryUpdater(entity, scene2); entity.cylinder.bottomRadius = void 0; updater._onEntityPropertyChanged(entity, "cylinder"); expect(updater.fillEnabled).toBe(false); expect(updater.outlineEnabled).toBe(false); expect(updater.isDynamic).toBe(false); }); it("A time-varying position causes geometry to be dynamic", function() { const entity = createBasicCylinder(); const updater = new import__53.CylinderGeometryUpdater(entity, scene2); entity.position = new import__53.SampledPositionProperty(); entity.position.addSample(time2, import__53.Cartesian3.ZERO); updater._onEntityPropertyChanged(entity, "position"); expect(updater.isDynamic).toBe(true); }); it("A time-varying bottomRadius causes geometry to be dynamic", function() { const entity = createBasicCylinder(); const updater = new import__53.CylinderGeometryUpdater(entity, scene2); entity.cylinder.bottomRadius = new import__53.SampledProperty(Number); entity.cylinder.bottomRadius.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "cylinder"); expect(updater.isDynamic).toBe(true); }); it("A time-varying topRadius causes geometry to be dynamic", function() { const entity = createBasicCylinder(); const updater = new import__53.CylinderGeometryUpdater(entity, scene2); entity.cylinder.topRadius = new import__53.SampledProperty(Number); entity.cylinder.topRadius.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "cylinder"); expect(updater.isDynamic).toBe(true); }); it("A time-varying length causes geometry to be dynamic", function() { const entity = createBasicCylinder(); const updater = new import__53.CylinderGeometryUpdater(entity, scene2); entity.cylinder.length = new import__53.SampledProperty(Number); entity.cylinder.length.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "cylinder"); expect(updater.isDynamic).toBe(true); }); it("A time-varying numberOfVerticalLines causes geometry to be dynamic", function() { const entity = createBasicCylinder(); const updater = new import__53.CylinderGeometryUpdater(entity, scene2); entity.cylinder.numberOfVerticalLines = new import__53.SampledProperty(Number); entity.cylinder.numberOfVerticalLines.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "cylinder"); expect(updater.isDynamic).toBe(true); }); it("Creates geometry with expected properties", function() { const options = { length: 1, topRadius: 3, bottomRadius: 2, numberOfVerticalLines: 15 }; const entity = new import__53.Entity(); entity.position = new import__53.ConstantPositionProperty(new import__53.Cartesian3(4, 5, 6)); entity.orientation = new import__53.ConstantProperty(import__53.Quaternion.IDENTITY); const cylinder = new import__53.CylinderGraphics(); cylinder.outline = true; cylinder.numberOfVerticalLines = new import__53.ConstantProperty( options.numberOfVerticalLines ); cylinder.length = new import__53.ConstantProperty(options.length); cylinder.topRadius = new import__53.ConstantProperty(options.topRadius); cylinder.bottomRadius = new import__53.ConstantProperty(options.bottomRadius); entity.cylinder = cylinder; const updater = new import__53.CylinderGeometryUpdater(entity, scene2); let instance; let geometry; instance = updater.createFillGeometryInstance(time2); geometry = instance.geometry; expect(geometry._topRadius).toEqual(options.topRadius); expect(geometry._bottomRadius).toEqual(options.bottomRadius); expect(geometry._length).toEqual(options.length); expect(geometry._offsetAttribute).toBeUndefined(); instance = updater.createOutlineGeometryInstance(time2); geometry = instance.geometry; expect(geometry._topRadius).toEqual(options.topRadius); expect(geometry._bottomRadius).toEqual(options.bottomRadius); expect(geometry._length).toEqual(options.length); expect(geometry._numberOfVerticalLines).toEqual( options.numberOfVerticalLines ); expect(geometry._offsetAttribute).toBeUndefined(); }); it("Creates geometry with expected offsetAttribute", function() { const entity = createBasicCylinder(); const graphics = entity.cylinder; graphics.outline = true; graphics.outlineColor = import__53.Color.BLACK; graphics.height = new import__53.ConstantProperty(20); graphics.extrudedHeight = new import__53.ConstantProperty(0); const updater = new import__53.CylinderGeometryUpdater(entity, getScene()); let instance; updater._onEntityPropertyChanged(entity, "cylinder"); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); graphics.heightReference = new import__53.ConstantProperty(import__53.HeightReference.NONE); updater._onEntityPropertyChanged(entity, "cylinder"); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); graphics.heightReference = new import__53.ConstantProperty( import__53.HeightReference.CLAMP_TO_GROUND ); updater._onEntityPropertyChanged(entity, "cylinder"); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import__53.GeometryOffsetAttribute.ALL ); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import__53.GeometryOffsetAttribute.ALL ); graphics.heightReference = new import__53.ConstantProperty( import__53.HeightReference.RELATIVE_TO_GROUND ); updater._onEntityPropertyChanged(entity, "cylinder"); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import__53.GeometryOffsetAttribute.ALL ); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import__53.GeometryOffsetAttribute.ALL ); }); it("dynamic updater sets properties", function() { const cylinder = new import__53.CylinderGraphics(); cylinder.topRadius = createDynamicProperty_default(2); cylinder.bottomRadius = createDynamicProperty_default(1); cylinder.length = createDynamicProperty_default(3); const entity = new import__53.Entity(); entity.position = createDynamicProperty_default(import__53.Cartesian3.UNIT_Z); entity.orientation = createDynamicProperty_default(import__53.Quaternion.IDENTITY); entity.cylinder = cylinder; const updater = new import__53.CylinderGeometryUpdater(entity, scene2); const dynamicUpdater = updater.createDynamicUpdater( new import__53.PrimitiveCollection(), new import__53.PrimitiveCollection() ); dynamicUpdater.update(import__53.JulianDate.now()); const options = dynamicUpdater._options; expect(options.topRadius).toEqual(cylinder.topRadius.getValue()); expect(options.bottomRadius).toEqual(cylinder.bottomRadius.getValue()); expect(options.length).toEqual(cylinder.length.getValue()); expect(options.offsetAttribute).toBeUndefined(); }); it("geometryChanged event is raised when expected", function() { const entity = createBasicCylinder(); const updater = new import__53.CylinderGeometryUpdater(entity, scene2); const listener = jasmine.createSpy("listener"); updater.geometryChanged.addEventListener(listener); entity.position = new import__53.ConstantPositionProperty(import__53.Cartesian3.UNIT_Z); updater._onEntityPropertyChanged(entity, "position"); expect(listener.calls.count()).toEqual(1); entity.cylinder.topRadius = new import__53.ConstantProperty(82); updater._onEntityPropertyChanged(entity, "cylinder"); expect(listener.calls.count()).toEqual(2); entity.availability = new import__53.TimeIntervalCollection(); updater._onEntityPropertyChanged(entity, "availability"); expect(listener.calls.count()).toEqual(3); entity.cylinder.topRadius = void 0; updater._onEntityPropertyChanged(entity, "cylinder"); expect(listener.calls.count()).toEqual(4); entity.cylinder.bottomRadius = void 0; updater._onEntityPropertyChanged(entity, "cylinder"); entity.viewFrom = new import__53.ConstantProperty(import__53.Cartesian3.UNIT_X); updater._onEntityPropertyChanged(entity, "viewFrom"); expect(listener.calls.count()).toEqual(4); entity.cylinder.topRadius = new import__53.SampledProperty(Number); entity.cylinder.bottomRadius = new import__53.SampledProperty(Number); updater._onEntityPropertyChanged(entity, "cylinder"); expect(listener.calls.count()).toEqual(5); }); it("computes center", function() { const entity = createBasicCylinder(); const updater = new import__53.CylinderGeometryUpdater(entity, scene2); expect(updater._computeCenter(time2)).toEqual( entity.position.getValue(time2) ); }); function getScene() { return scene2; } createGeometryUpdaterSpecs_default( import__53.CylinderGeometryUpdater, "cylinder", createBasicCylinder, getScene ); createDynamicGeometryUpdaterSpecs_default( import__53.CylinderGeometryUpdater, "cylinder", createDynamicCylinder, getScene ); }, "WebGL" ); // packages/engine/Specs/DataSources/CylinderGraphicsSpec.js var import__54 = __toESM(require_Cesium(), 1); describe("DataSources/CylinderGraphics", function() { it("creates expected instance from raw assignment and construction", function() { const options = { material: import__54.Color.BLUE, show: true, length: 1, topRadius: 2, bottomRadius: 3, numberOfVerticalLines: 4, slices: 5, fill: false, outline: false, outlineColor: import__54.Color.RED, outlineWidth: 6, shadows: import__54.ShadowMode.DISABLED, distanceDisplayCondition: new import__54.DistanceDisplayCondition(10, 100) }; const cylinder = new import__54.CylinderGraphics(options); expect(cylinder.material).toBeInstanceOf(import__54.ColorMaterialProperty); expect(cylinder.show).toBeInstanceOf(import__54.ConstantProperty); expect(cylinder.length).toBeInstanceOf(import__54.ConstantProperty); expect(cylinder.topRadius).toBeInstanceOf(import__54.ConstantProperty); expect(cylinder.bottomRadius).toBeInstanceOf(import__54.ConstantProperty); expect(cylinder.numberOfVerticalLines).toBeInstanceOf(import__54.ConstantProperty); expect(cylinder.slices).toBeInstanceOf(import__54.ConstantProperty); expect(cylinder.fill).toBeInstanceOf(import__54.ConstantProperty); expect(cylinder.outline).toBeInstanceOf(import__54.ConstantProperty); expect(cylinder.outlineColor).toBeInstanceOf(import__54.ConstantProperty); expect(cylinder.outlineWidth).toBeInstanceOf(import__54.ConstantProperty); expect(cylinder.shadows).toBeInstanceOf(import__54.ConstantProperty); expect(cylinder.distanceDisplayCondition).toBeInstanceOf(import__54.ConstantProperty); expect(cylinder.material.color.getValue()).toEqual(options.material); expect(cylinder.show.getValue()).toEqual(options.show); expect(cylinder.length.getValue()).toEqual(options.length); expect(cylinder.topRadius.getValue()).toEqual(options.topRadius); expect(cylinder.bottomRadius.getValue()).toEqual(options.bottomRadius); expect(cylinder.numberOfVerticalLines.getValue()).toEqual( options.numberOfVerticalLines ); expect(cylinder.slices.getValue()).toEqual(options.slices); expect(cylinder.fill.getValue()).toEqual(options.fill); expect(cylinder.outline.getValue()).toEqual(options.outline); expect(cylinder.outlineColor.getValue()).toEqual(options.outlineColor); expect(cylinder.outlineWidth.getValue()).toEqual(options.outlineWidth); expect(cylinder.shadows.getValue()).toEqual(options.shadows); expect(cylinder.distanceDisplayCondition.getValue()).toEqual( options.distanceDisplayCondition ); }); it("merge assigns unassigned properties", function() { const source = new import__54.CylinderGraphics(); source.material = new import__54.ColorMaterialProperty(); source.length = new import__54.ConstantProperty(); source.topRadius = new import__54.ConstantProperty(); source.bottomRadius = new import__54.ConstantProperty(); source.numberOfVerticalLines = new import__54.ConstantProperty(); source.slices = new import__54.ConstantProperty(); source.fill = new import__54.ConstantProperty(); source.outline = new import__54.ConstantProperty(); source.outlineColor = new import__54.ConstantProperty(); source.outlineWidth = new import__54.ConstantProperty(); source.shadows = new import__54.ConstantProperty(import__54.ShadowMode.ENABLED); source.distanceDisplayCondition = new import__54.ConstantProperty(); const target = new import__54.CylinderGraphics(); target.merge(source); expect(target.material).toBe(source.material); expect(target.length).toBe(source.length); expect(target.topRadius).toBe(source.topRadius); expect(target.bottomRadius).toBe(source.bottomRadius); expect(target.numberOfVerticalLines).toBe(source.numberOfVerticalLines); expect(target.slices).toBe(source.slices); expect(target.fill).toBe(source.fill); expect(target.outline).toBe(source.outline); expect(target.outlineColor).toBe(source.outlineColor); expect(target.outlineWidth).toBe(source.outlineWidth); expect(target.shadows).toBe(source.shadows); expect(target.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); }); it("merge does not assign assigned properties", function() { const source = new import__54.CylinderGraphics(); const material = new import__54.ColorMaterialProperty(); const topRadius = new import__54.ConstantProperty(); const length2 = new import__54.ConstantProperty(); const bottomRadius = new import__54.ConstantProperty(); const numberOfVerticalLines = new import__54.ConstantProperty(); const slices = new import__54.ConstantProperty(); const fill = new import__54.ConstantProperty(); const outline = new import__54.ConstantProperty(); const outlineColor = new import__54.ConstantProperty(); const outlineWidth = new import__54.ConstantProperty(); const shadows = new import__54.ConstantProperty(); const distanceDisplayCondition = new import__54.ConstantProperty(); const target = new import__54.CylinderGraphics(); target.material = material; target.length = length2; target.topRadius = topRadius; target.bottomRadius = bottomRadius; target.numberOfVerticalLines = numberOfVerticalLines; target.slices = slices; target.fill = fill; target.outline = outline; target.outlineColor = outlineColor; target.outlineWidth = outlineWidth; target.shadows = shadows; target.distanceDisplayCondition = distanceDisplayCondition; target.merge(source); expect(target.material).toBe(material); expect(target.length).toBe(length2); expect(target.topRadius).toBe(topRadius); expect(target.bottomRadius).toBe(bottomRadius); expect(target.numberOfVerticalLines).toBe(numberOfVerticalLines); expect(target.slices).toBe(slices); expect(target.fill).toBe(fill); expect(target.outline).toBe(outline); expect(target.outlineColor).toBe(outlineColor); expect(target.outlineWidth).toBe(outlineWidth); expect(target.shadows).toBe(shadows); expect(target.distanceDisplayCondition).toBe(distanceDisplayCondition); }); it("clone works", function() { const source = new import__54.CylinderGraphics(); source.material = new import__54.ColorMaterialProperty(); source.length = new import__54.ConstantProperty(); source.topRadius = new import__54.ConstantProperty(); source.bottomRadius = new import__54.ConstantProperty(); source.numberOfVerticalLines = new import__54.ConstantProperty(); source.slices = new import__54.ConstantProperty(); source.fill = new import__54.ConstantProperty(); source.outline = new import__54.ConstantProperty(); source.outlineColor = new import__54.ConstantProperty(); source.outlineWidth = new import__54.ConstantProperty(); source.shadows = new import__54.ConstantProperty(); source.distanceDisplayCondition = new import__54.ConstantProperty(); const result = source.clone(); expect(result.material).toBe(source.material); expect(result.length).toBe(source.length); expect(result.topRadius).toBe(source.topRadius); expect(result.bottomRadius).toBe(source.bottomRadius); expect(result.numberOfVerticalLines).toBe(source.numberOfVerticalLines); expect(result.slices).toBe(source.slices); expect(result.fill).toBe(source.fill); expect(result.outline).toBe(source.outline); expect(result.outlineColor).toBe(source.outlineColor); expect(result.outlineWidth).toBe(source.outlineWidth); expect(result.shadows).toBe(source.shadows); expect(result.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); }); it("merge throws if source undefined", function() { const target = new import__54.CylinderGraphics(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__54.CylinderGraphics(); testMaterialDefinitionChanged_default(property, "material", import__54.Color.RED, import__54.Color.BLUE); testDefinitionChanged_default(property, "length", 2, 3); testDefinitionChanged_default(property, "topRadius", 3, 4); testDefinitionChanged_default(property, "bottomRadius", 5, 6); testDefinitionChanged_default(property, "numberOfVerticalLines", 16, 32); testDefinitionChanged_default(property, "slices", 16, 24); testDefinitionChanged_default(property, "fill", false, true); testDefinitionChanged_default(property, "outline", true, false); testDefinitionChanged_default(property, "outlineColor", import__54.Color.RED, import__54.Color.BLUE); testDefinitionChanged_default(property, "outlineWidth", 2, 3); testDefinitionChanged_default( property, "shadows", import__54.ShadowMode.ENABLED, import__54.ShadowMode.DISABLED ); testDefinitionChanged_default( property, "distanceDisplayCondition", new import__54.DistanceDisplayCondition(), new import__54.DistanceDisplayCondition(10, 100) ); }); }); // packages/engine/Specs/DataSources/CzmlDataSourceSpec.js var import__55 = __toESM(require_Cesium(), 1); describe("DataSources/CzmlDataSource", function() { function makeDocument(packet) { const documentPacket = { id: "document", version: "1.0" }; return [documentPacket, packet]; } const staticCzml = { id: "test", billboard: { show: true } }; const czmlDelete = { id: "test", delete: true }; const dynamicCzml = { id: "test", availability: "2000-01-01/2001-01-01", billboard: { show: true } }; const clockCzml = { id: "document", version: "1.0", clock: { interval: "2012-03-15T10:00:00Z/2012-03-16T10:00:00Z", currentTime: "2012-03-15T10:00:00Z", multiplier: 60, range: "LOOP_STOP", step: "SYSTEM_CLOCK_MULTIPLIER" } }; const clockCzml2 = { id: "document", version: "1.0", clock: { interval: "2013-03-15T10:00:00Z/2013-03-16T10:00:00Z", currentTime: "2013-03-15T10:00:00Z", multiplier: 30, range: "UNBOUNDED", step: "TICK_DEPENDENT" } }; const parsedClock = { interval: import__55.TimeInterval.fromIso8601({ iso8601: clockCzml.clock.interval }), currentTime: import__55.JulianDate.fromIso8601(clockCzml.clock.currentTime), multiplier: clockCzml.clock.multiplier, range: import__55.ClockRange[clockCzml.clock.range], step: import__55.ClockStep[clockCzml.clock.step] }; const parsedClock2 = { interval: import__55.TimeInterval.fromIso8601({ iso8601: clockCzml2.clock.interval }), currentTime: import__55.JulianDate.fromIso8601(clockCzml2.clock.currentTime), multiplier: clockCzml2.clock.multiplier, range: import__55.ClockRange[clockCzml2.clock.range], step: import__55.ClockStep[clockCzml2.clock.step] }; const nameCzml = { id: "document", version: "1.0", name: "czmlName" }; let simple; const simpleUrl = "Data/CZML/simple.czml"; let vehicle; const vehicleUrl = "Data/CZML/Vehicle.czml"; beforeAll(function() { return Promise.all([ import__55.Resource.fetchJson(simpleUrl).then(function(result) { simple = result; }), import__55.Resource.fetchJson(vehicleUrl).then(function(result) { vehicle = result; }) ]); }); function arraySubset(array, startIndex, count) { startIndex = startIndex === void 0 ? 0 : startIndex; return array.slice(startIndex, startIndex + count); } function cartesianFromArrayDegrees(array, startIndex, ellipsoid) { return import__55.Cartesian3.fromDegrees.apply( null, [].concat(arraySubset(array, startIndex, 3), ellipsoid) ); } function cartesianFromArrayRadians(array, startIndex, ellipsoid) { return import__55.Cartesian3.fromRadians.apply( null, [].concat(arraySubset(array, startIndex, 3), ellipsoid) ); } it("default constructor has expected values", function() { const dataSource = new import__55.CzmlDataSource(); expect(dataSource.changedEvent).toBeInstanceOf(import__55.Event); expect(dataSource.errorEvent).toBeInstanceOf(import__55.Event); expect(dataSource.name).toBeUndefined(); expect(dataSource.clock).toBeUndefined(); expect(dataSource.entities).toBeInstanceOf(import__55.EntityCollection); expect(dataSource.entities.values.length).toEqual(0); expect(dataSource.show).toEqual(true); expect(dataSource.credit).toBeUndefined(); }); it("show sets underlying entity collection show.", function() { const dataSource = new import__55.CzmlDataSource(); dataSource.show = false; expect(dataSource.show).toEqual(false); expect(dataSource.show).toEqual(dataSource.entities.show); dataSource.show = true; expect(dataSource.show).toEqual(true); expect(dataSource.show).toEqual(dataSource.entities.show); }); it("name returns CZML defined name", function() { return import__55.CzmlDataSource.load(nameCzml).then(function(dataSource) { expect(dataSource.name).toEqual(nameCzml.name); }); }); it("name uses source name if CZML name is undefined", function() { return import__55.CzmlDataSource.load(clockCzml, { sourceUri: "Gallery/simple.czml?asd=true" }).then(function(dataSource) { expect(dataSource.name).toEqual("simple.czml"); }); }); it("credit gets set from options", function() { return import__55.CzmlDataSource.load(nameCzml, { credit: "This is my credit" }).then(function(dataSource) { expect(dataSource.credit).toBeInstanceOf(import__55.Credit); }); }); it("does not overwrite existing name if CZML name is undefined", function() { const name = "myName"; const dataSource = new import__55.CzmlDataSource(name); return dataSource.load(clockCzml, { sourceUri: "Gallery/simple.czml" }).then(function(dataSource2) { expect(dataSource2.name).toEqual(name); }); }); it("clock returns undefined for static CZML", function() { return import__55.CzmlDataSource.load(makeDocument(staticCzml)).then(function(dataSource) { expect(dataSource.clock).toBeUndefined(); }); }); it("clock returns CZML defined clock", function() { return import__55.CzmlDataSource.load(clockCzml).then(function(dataSource) { const clock = dataSource.clock; expect(clock).toBeDefined(); expect(clock.startTime).toEqual(parsedClock.interval.start); expect(clock.stopTime).toEqual(parsedClock.interval.stop); expect(clock.currentTime).toEqual(parsedClock.currentTime); expect(clock.clockRange).toEqual(parsedClock.range); expect(clock.clockStep).toEqual(parsedClock.step); expect(clock.multiplier).toEqual(parsedClock.multiplier); return dataSource.process(clockCzml2); }).then(function(dataSource) { const clock = dataSource.clock; expect(clock).toBeDefined(); expect(clock.startTime).toEqual(parsedClock2.interval.start); expect(clock.stopTime).toEqual(parsedClock2.interval.stop); expect(clock.currentTime).toEqual(parsedClock2.currentTime); expect(clock.clockRange).toEqual(parsedClock2.range); expect(clock.clockStep).toEqual(parsedClock2.step); expect(clock.multiplier).toEqual(parsedClock2.multiplier); }); }); it("clock returns data interval if no clock defined", function() { const interval = import__55.TimeInterval.fromIso8601({ iso8601: dynamicCzml.availability }); return import__55.CzmlDataSource.load(makeDocument(dynamicCzml)).then(function(dataSource) { const clock = dataSource.clock; expect(clock).toBeDefined(); expect(clock.startTime).toEqual(interval.start); expect(clock.stopTime).toEqual(interval.stop); expect(clock.currentTime).toEqual(interval.start); expect(clock.clockRange).toEqual(import__55.ClockRange.LOOP_STOP); expect(clock.clockStep).toEqual(import__55.ClockStep.SYSTEM_CLOCK_MULTIPLIER); expect(clock.multiplier).toEqual( import__55.JulianDate.secondsDifference(interval.stop, interval.start) / 120 ); }); }); it("process loads expected data", function() { const dataSource = new import__55.CzmlDataSource(); return dataSource.process(simple).then(function(dataSource2) { expect(dataSource2.entities.values.length).toEqual(10); }); }); it("process loads expected data from Resource", function() { const dataSource = new import__55.CzmlDataSource(); return dataSource.process( new import__55.Resource({ url: simpleUrl }) ).then(function(dataSource2) { expect(dataSource2.entities.values.length).toEqual(10); }); }); it("process loads data on top of existing", function() { const dataSource = new import__55.CzmlDataSource(); return dataSource.process(simple).then(function(dataSource2) { expect(dataSource2.entities.values.length).toEqual(10); return dataSource2.process(vehicle, vehicleUrl); }).then(function(dataSource2) { expect(dataSource2.entities.values.length).toEqual(11); }); }); it("load replaces data", function() { const dataSource = new import__55.CzmlDataSource(); return dataSource.process(simple).then(function(dataSource2) { expect(dataSource2.entities.values.length).toEqual(10); return dataSource2.load(vehicle, vehicleUrl); }).then(function(dataSource2) { expect(dataSource2.entities.values.length).toEqual(1); }); }); it("process throws with undefined CZML", function() { const dataSource = new import__55.CzmlDataSource(); expect(function() { dataSource.process(void 0); }).toThrowDeveloperError(); }); it("load throws with undefined CZML", function() { const dataSource = new import__55.CzmlDataSource(); expect(function() { dataSource.load(void 0); }).toThrowDeveloperError(); }); it("raises changed event when loading CZML", function() { const dataSource = new import__55.CzmlDataSource(); const spy = jasmine.createSpy("changedEvent"); dataSource.changedEvent.addEventListener(spy); return dataSource.load(clockCzml).then(function(dataSource2) { expect(spy).toHaveBeenCalledWith(dataSource2); }); }); it("raises changed event when name changes in CZML", function() { const dataSource = new import__55.CzmlDataSource(); const spy = jasmine.createSpy("changedEvent"); const originalCzml = { id: "document", version: "1.0", name: "czmlName" }; return dataSource.load(originalCzml).then(function(dataSource2) { dataSource2.changedEvent.addEventListener(spy); const newCzml = { id: "document", name: "newCzmlName" }; return dataSource2.process(newCzml); }).then(function(dataSource2) { expect(spy).toHaveBeenCalledWith(dataSource2); }); }); it("does not raise changed event when name does not change in CZML", function() { const dataSource = new import__55.CzmlDataSource(); const spy = jasmine.createSpy("changedEvent"); return dataSource.load(nameCzml).then(function(dataSource2) { dataSource2.changedEvent.addEventListener(spy); return dataSource2.load(nameCzml); }).then(function(dataSource2) { expect(spy).not.toHaveBeenCalled(); }); }); it("raises changed event when clock changes in CZML", function() { const dataSource = new import__55.CzmlDataSource(); const spy = jasmine.createSpy("changedEvent"); const originalCzml = { id: "document", version: "1.0", clock: { interval: "2012-03-15T10:00:00Z/2012-03-16T10:00:00Z", currentTime: "2012-03-15T10:00:00Z", multiplier: 60, range: "LOOP_STOP", step: "SYSTEM_CLOCK_MULTIPLIER" } }; return dataSource.load(originalCzml).then(function(dataSource2) { dataSource2.changedEvent.addEventListener(spy); const newCzml = { id: "document", version: "1.0", clock: { interval: "2013-03-15T10:00:00Z/2013-03-16T10:00:00Z", currentTime: "2012-03-15T10:00:00Z", multiplier: 60, range: "LOOP_STOP", step: "SYSTEM_CLOCK_MULTIPLIER" } }; return dataSource2.load(newCzml); }).then(function(dataSource2) { expect(spy).toHaveBeenCalledWith(dataSource2); }); }); it("does not raise changed event when clock does not change in CZML", function() { const dataSource = new import__55.CzmlDataSource(); const spy = jasmine.createSpy("changedEvent"); return dataSource.load(clockCzml).then(function(dataSource2) { dataSource2.changedEvent.addEventListener(spy); return dataSource2.load(clockCzml); }).then(function(dataSource2) { expect(spy).not.toHaveBeenCalled(); }); }); it("raises error when an error occurs in load", function() { const dataSource = new import__55.CzmlDataSource(); const spy = jasmine.createSpy("errorEvent"); dataSource.errorEvent.addEventListener(spy); return dataSource.load("Data/Images/Blue.png").then(function() { fail("should not be called"); }).catch(function() { expect(spy).toHaveBeenCalledWith(dataSource, jasmine.any(Error)); }); }); it("raises error when an error occurs in process", function() { const dataSource = new import__55.CzmlDataSource(); const spy = jasmine.createSpy("errorEvent"); dataSource.errorEvent.addEventListener(spy); return dataSource.process("Data/Images/Blue.png").then(function() { fail("should not be called"); }).catch(function() { expect(spy).toHaveBeenCalledWith(dataSource, jasmine.any(Error)); }); }); it("can load constant data for billboard", function() { const sourceUri = "http://someImage.invalid/"; const packet = { billboard: { image: "image.png", scale: 1, rotation: 1.3, heightReference: "CLAMP_TO_GROUND", horizontalOrigin: "CENTER", verticalOrigin: "CENTER", color: { rgbaf: [1, 1, 1, 1] }, eyeOffset: { cartesian: [3, 4, 5] }, pixelOffset: { cartesian2: [1, 2] }, alignedAxis: { unitCartesian: [1, 0, 0] }, show: true, sizeInMeters: false, width: 10, height: 11, scaleByDistance: { nearFarScalar: [1, 2, 1e4, 3] }, translucencyByDistance: { nearFarScalar: [1, 1, 1e4, 0] }, pixelOffsetScaleByDistance: { nearFarScalar: [1, 20, 1e4, 30] }, imageSubRegion: { boundingRectangle: [20, 30, 10, 11] } } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet), { sourceUri }).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.billboard).toBeDefined(); expect(entity.billboard.image.getValue(time2).url).toEqual( sourceUri + packet.billboard.image ); expect(entity.billboard.rotation.getValue(time2)).toEqual( packet.billboard.rotation ); expect(entity.billboard.scale.getValue(time2)).toEqual( packet.billboard.scale ); expect(entity.billboard.heightReference.getValue(time2)).toEqual( import__55.HeightReference[packet.billboard.heightReference] ); expect(entity.billboard.horizontalOrigin.getValue(time2)).toEqual( import__55.HorizontalOrigin[packet.billboard.horizontalOrigin] ); expect(entity.billboard.verticalOrigin.getValue(time2)).toEqual( import__55.VerticalOrigin[packet.billboard.verticalOrigin] ); expect(entity.billboard.color.getValue(time2)).toEqual( import__55.Color.unpack(packet.billboard.color.rgbaf) ); expect(entity.billboard.eyeOffset.getValue(time2)).toEqual( import__55.Cartesian3.unpack(packet.billboard.eyeOffset.cartesian) ); expect(entity.billboard.pixelOffset.getValue(time2)).toEqual( import__55.Cartesian2.unpack(packet.billboard.pixelOffset.cartesian2) ); expect(entity.billboard.alignedAxis.getValue(time2)).toEqual( import__55.Cartesian3.unpack(packet.billboard.alignedAxis.unitCartesian) ); expect(entity.billboard.show.getValue(time2)).toEqual( packet.billboard.show ); expect(entity.billboard.sizeInMeters.getValue(time2)).toEqual( packet.billboard.sizeInMeters ); expect(entity.billboard.width.getValue(time2)).toEqual( packet.billboard.width ); expect(entity.billboard.height.getValue(time2)).toEqual( packet.billboard.height ); expect(entity.billboard.scaleByDistance.getValue(time2)).toEqual( import__55.NearFarScalar.unpack(packet.billboard.scaleByDistance.nearFarScalar) ); expect(entity.billboard.translucencyByDistance.getValue(time2)).toEqual( import__55.NearFarScalar.unpack( packet.billboard.translucencyByDistance.nearFarScalar ) ); expect( entity.billboard.pixelOffsetScaleByDistance.getValue(time2) ).toEqual( import__55.NearFarScalar.unpack( packet.billboard.pixelOffsetScaleByDistance.nearFarScalar ) ); expect(entity.billboard.imageSubRegion.getValue(time2)).toEqual( import__55.BoundingRectangle.unpack( packet.billboard.imageSubRegion.boundingRectangle ) ); }); }); it("can handle aligned axis expressed as a cartesian", function() { const packet = { billboard: { alignedAxis: { cartesian: [1, 0, 0] } } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.billboard).toBeDefined(); expect(entity.billboard.alignedAxis.getValue(time2)).toEqual( import__55.Cartesian3.unpack(packet.billboard.alignedAxis.cartesian) ); }); }); it("can handle aligned axis expressed as a velocity reference", function() { const packet = { position: { epoch: "2016-06-17T12:00:00Z", cartesian: [0, 1, 2, 3, 60, 61, 122, 183] }, billboard: { alignedAxis: { velocityReference: "#position" } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; const property = entity.billboard.alignedAxis; const expectedVelocity = new import__55.Cartesian3(1, 2, 3); const expectedVelocityDirection = import__55.Cartesian3.normalize( expectedVelocity, new import__55.Cartesian3() ); expect( property.getValue(import__55.JulianDate.fromIso8601("2016-06-17T12:00:00Z")) ).toEqualEpsilon(expectedVelocityDirection, import__55.Math.EPSILON15); expect( property.getValue(import__55.JulianDate.fromIso8601("2016-06-17T12:00:30Z")) ).toEqualEpsilon(expectedVelocityDirection, import__55.Math.EPSILON15); }); }); it("can handle aligned axis expressed as a velocity reference within an interval", function() { const packet = { position: { epoch: "2016-06-17T12:00:00Z", cartesian: [0, 1, 2, 3, 60, 61, 122, 183] }, billboard: { alignedAxis: [ { interval: "2016-06-17T12:00:00Z/2016-06-17T12:00:30Z", unitCartesian: [0, 1, 0] }, { interval: "2016-06-17T12:00:30Z/2016-06-17T12:01:00Z", velocityReference: "#position" } ] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; const property = entity.billboard.alignedAxis; const expected = new import__55.Cartesian3(0, 1, 0); expect( property.getValue(import__55.JulianDate.fromIso8601("2016-06-17T12:00:00Z")) ).toEqual(expected); expect( property.getValue(import__55.JulianDate.fromIso8601("2016-06-17T12:00:29Z")) ).toEqual(expected); const expectedVelocity = new import__55.Cartesian3(1, 2, 3); const expectedVelocityDirection = import__55.Cartesian3.normalize( expectedVelocity, new import__55.Cartesian3() ); expect( property.getValue(import__55.JulianDate.fromIso8601("2016-06-17T12:00:30Z")) ).toEqualEpsilon(expectedVelocityDirection, import__55.Math.EPSILON15); expect( property.getValue(import__55.JulianDate.fromIso8601("2016-06-17T12:01:00Z")) ).toEqualEpsilon(expectedVelocityDirection, import__55.Math.EPSILON12); }); }); it("can handle image intervals both of type uri and image", function() { const source = "http://some.url.invalid/"; const packet = { billboard: { image: [ { interval: "2013-01-01T00:00:00Z/2013-01-01T01:00:00Z", uri: "image.png" }, { interval: "2013-01-01T01:00:00Z/2013-01-01T02:00:00Z", uri: "image2.png" } ] } }; return import__55.CzmlDataSource.load(makeDocument(packet), { sourceUri: source }).then(function(dataSource) { const entity = dataSource.entities.values[0]; const imageProperty = entity.billboard.image; expect( imageProperty.getValue(import__55.JulianDate.fromIso8601("2013-01-01T00:00:00Z")).url ).toEqual(`${source}image.png`); expect( imageProperty.getValue(import__55.JulianDate.fromIso8601("2013-01-01T01:00:00Z")).url ).toEqual(`${source}image2.png`); }); }); it("can load interval data for billboard", function() { const packet = { billboard: { interval: "2000-01-01/2001-01-01", image: "http://someImage.invalid/image", scale: 1, horizontalOrigin: "CENTER", verticalOrigin: "CENTER", color: { rgbaf: [1, 1, 1, 1] }, eyeOffset: { cartesian: [3, 4, 5] }, pixelOffset: { cartesian2: [1, 2] }, show: true } }; const validTime = import__55.TimeInterval.fromIso8601({ iso8601: packet.billboard.interval }).start; const invalidTime = import__55.JulianDate.addSeconds(validTime, -1, new import__55.JulianDate()); return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.billboard).toBeDefined(); expect(entity.billboard.image.getValue(validTime).url).toEqual( packet.billboard.image ); expect(entity.billboard.scale.getValue(validTime)).toEqual( packet.billboard.scale ); expect(entity.billboard.horizontalOrigin.getValue(validTime)).toEqual( import__55.HorizontalOrigin[packet.billboard.horizontalOrigin] ); expect(entity.billboard.verticalOrigin.getValue(validTime)).toEqual( import__55.VerticalOrigin[packet.billboard.verticalOrigin] ); expect(entity.billboard.color.getValue(validTime)).toEqual( import__55.Color.unpack(packet.billboard.color.rgbaf) ); expect(entity.billboard.eyeOffset.getValue(validTime)).toEqual( import__55.Cartesian3.unpack(packet.billboard.eyeOffset.cartesian) ); expect(entity.billboard.pixelOffset.getValue(validTime)).toEqual( import__55.Cartesian2.unpack(packet.billboard.pixelOffset.cartesian2) ); expect(entity.billboard.show.getValue(validTime)).toEqual( packet.billboard.show ); expect(entity.billboard).toBeDefined(); expect(entity.billboard.image.getValue(invalidTime)).toBeUndefined(); expect(entity.billboard.scale.getValue(invalidTime)).toBeUndefined(); expect( entity.billboard.horizontalOrigin.getValue(invalidTime) ).toBeUndefined(); expect( entity.billboard.verticalOrigin.getValue(invalidTime) ).toBeUndefined(); expect(entity.billboard.color.getValue(invalidTime)).toBeUndefined(); expect(entity.billboard.eyeOffset.getValue(invalidTime)).toBeUndefined(); expect( entity.billboard.pixelOffset.getValue(invalidTime) ).toBeUndefined(); expect(entity.billboard.show.getValue(invalidTime)).toBeUndefined(); }); }); it("can load interval data with further constrained intervals in subproperties", function() { const packet = { billboard: { interval: "2010-01-01T00:00:00Z/2010-01-02T01:00:00Z", scaleByDistance: [ { interval: "2009-01-01T00:00:00Z/2010-01-01T00:30:00Z", nearFarScalar: [1, 2, 1e4, 3] }, { interval: "2010-01-01T00:30:00Z/2011-01-01T00:00:00Z", nearFarScalar: [2, 3, 2e4, 4] } ] }, ellipsoid: { interval: "2010-01-01T00:00:00Z/2010-01-02T01:00:00Z", material: [ { interval: "2009-01-01T00:00:00Z/2010-01-01T00:30:00Z", solidColor: { color: { rgbaf: [0.1, 0.2, 0.3, 0.4] } } }, { interval: "2010-01-01T00:30:00Z/2011-01-01T00:00:00Z", solidColor: { color: { rgbaf: [0.5, 0.4, 0.3, 0.2] } } } ] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.billboard).toBeDefined(); expect(entity.ellipsoid).toBeDefined(); let time2 = import__55.JulianDate.fromIso8601("2009-01-01T00:00:00Z"); expect(entity.billboard.scaleByDistance.getValue(time2)).toBeUndefined(); expect(entity.ellipsoid.material.getValue(time2)).toBeUndefined(); time2 = import__55.JulianDate.fromIso8601("2010-01-01T00:05:00Z"); expect(entity.billboard.scaleByDistance.getValue(time2)).toEqual( import__55.NearFarScalar.unpack(packet.billboard.scaleByDistance[0].nearFarScalar) ); expect(entity.ellipsoid.material.getValue(time2).color).toEqual( import__55.Color.unpack(packet.ellipsoid.material[0].solidColor.color.rgbaf) ); time2 = import__55.JulianDate.fromIso8601("2010-01-01T00:35:00Z"); expect(entity.billboard.scaleByDistance.getValue(time2)).toEqual( import__55.NearFarScalar.unpack(packet.billboard.scaleByDistance[1].nearFarScalar) ); expect(entity.ellipsoid.material.getValue(time2).color).toEqual( import__55.Color.unpack(packet.ellipsoid.material[1].solidColor.color.rgbaf) ); time2 = import__55.JulianDate.fromIso8601("2010-01-03T00:00:00Z"); expect(entity.billboard.scaleByDistance.getValue(time2)).toBeUndefined(); expect(entity.ellipsoid.material.getValue(time2)).toBeUndefined(); }); }); it("can constrain a constant property by sending an interval in a subsequent packet", function() { const constantPacket = { id: "a", billboard: { scale: 1 } }; const intervalPacket = { id: "a", billboard: { scale: { interval: "2010-01-01T00:00:00Z/2010-01-02T01:00:00Z", number: 2 } } }; return import__55.CzmlDataSource.load(makeDocument(constantPacket)).then(function(dataSource) { return dataSource.process(intervalPacket); }).then(function(dataSource) { const entity = dataSource.entities.getById("a"); expect(entity.billboard).toBeDefined(); expect(entity.billboard.scale).toBeInstanceOf(import__55.CompositeProperty); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2009-01-01T00:00:00Z") ) ).toEqual(constantPacket.billboard.scale); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2010-01-01T00:00:00Z") ) ).toEqual(intervalPacket.billboard.scale.number); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2011-01-01T00:00:00Z") ) ).toEqual(constantPacket.billboard.scale); }); }); it("can constrain a constant position property by sending an interval in a subsequent packet", function() { const constantPacket = { id: "a", position: { cartographicDegrees: [34, 117, 0] } }; const intervalPacket = { id: "a", position: { interval: "2010-01-01T00:00:00Z/2010-01-02T01:00:00Z", cartographicDegrees: [40, 100, 0] } }; return import__55.CzmlDataSource.load(makeDocument(constantPacket)).then(function(dataSource) { return dataSource.process(intervalPacket); }).then(function(dataSource) { const entity = dataSource.entities.getById("a"); expect(entity.position).toBeDefined(); expect(entity.position).toBeInstanceOf(import__55.CompositePositionProperty); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2009-01-01T00:00:00Z") ) ).toEqual( cartesianFromArrayDegrees(constantPacket.position.cartographicDegrees) ); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2010-01-01T00:00:00Z") ) ).toEqual( cartesianFromArrayDegrees(intervalPacket.position.cartographicDegrees) ); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2011-01-01T00:00:00Z") ) ).toEqual( cartesianFromArrayDegrees(constantPacket.position.cartographicDegrees) ); }); }); it("can convert a sampled property to a composite by sending intervals in a subsequent packet", function() { const sampledPacket = { id: "a", billboard: { scale: { number: [ "2010-01-01T00:00:00Z", 1, "2010-01-01T01:00:00Z", 2, "2010-01-01T02:00:00Z", 3 ] } } }; const intervalPacket = { id: "a", billboard: { scale: [ { interval: "2010-01-01T00:20:00Z/2010-01-01T00:22:00Z", number: ["2010-01-01T00:20:00Z", 10, "2010-01-01T00:22:00Z", 20] } ] } }; return import__55.CzmlDataSource.load(makeDocument(sampledPacket)).then(function(dataSource) { return dataSource.process(intervalPacket); }).then(function(dataSource) { const entity = dataSource.entities.getById("a"); expect(entity.billboard).toBeDefined(); expect(entity.billboard.scale).toBeInstanceOf(import__55.CompositeProperty); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2010-01-01T00:00:00Z") ) ).toEqual(1); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2010-01-01T00:20:00Z") ) ).toEqual(10); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2010-01-01T00:21:00Z") ) ).toEqual(15); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2010-01-01T00:22:00Z") ) ).toEqual(20); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2010-01-01T01:00:00Z") ) ).toEqual(2); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2010-01-01T02:00:00Z") ) ).toEqual(3); }); }); it("can convert a sampled position property to a composite by sending intervals in a subsequent packet", function() { const sampledPacket = { id: "a", position: { cartographicDegrees: [ "2010-01-01T00:00:00Z", 34, 117, 1e4, "2010-01-01T01:00:00Z", 34, 117, 2e4 ] } }; const intervalPacket = { id: "a", position: [ { interval: "2010-01-01T00:20:00Z/2010-01-01T00:22:00Z", cartographicDegrees: [ "2010-01-01T00:20:00Z", 40, 100, 1e4, "2010-01-01T00:22:00Z", 40, 100, 2e4 ] } ] }; return import__55.CzmlDataSource.load(makeDocument(sampledPacket)).then(function(dataSource) { return dataSource.process(intervalPacket); }).then(function(dataSource) { const entity = dataSource.entities.getById("a"); expect(entity.position).toBeDefined(); expect(entity.position).toBeInstanceOf(import__55.CompositePositionProperty); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2010-01-01T00:00:00Z") ) ).toEqual(import__55.Cartesian3.fromDegrees(34, 117, 1e4)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2010-01-01T00:20:00Z") ) ).toEqual(import__55.Cartesian3.fromDegrees(40, 100, 1e4)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2010-01-01T00:21:00Z") ) ).toEqualEpsilon( import__55.Cartesian3.fromDegrees(40, 100, 15e3), import__55.Math.EPSILON10 ); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2010-01-01T00:22:00Z") ) ).toEqual(import__55.Cartesian3.fromDegrees(40, 100, 2e4)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2010-01-01T01:00:00Z") ) ).toEqual(import__55.Cartesian3.fromDegrees(34, 117, 2e4)); }); }); it("can handle sampled billboard pixelOffset.", function() { const epoch = import__55.JulianDate.now(); const packet = { billboard: { pixelOffset: { epoch: import__55.JulianDate.toIso8601(epoch), cartesian2: [0, 1, 2, 1, 3, 4] } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.billboard).toBeDefined(); const date1 = epoch; const date2 = import__55.JulianDate.addSeconds(epoch, 0.5, new import__55.JulianDate()); const date3 = import__55.JulianDate.addSeconds(epoch, 1, new import__55.JulianDate()); expect(entity.billboard.pixelOffset.getValue(date1)).toEqual( new import__55.Cartesian2(1, 2) ); expect(entity.billboard.pixelOffset.getValue(date2)).toEqual( new import__55.Cartesian2(2, 3) ); expect(entity.billboard.pixelOffset.getValue(date3)).toEqual( new import__55.Cartesian2(3, 4) ); }); }); it("can handle interval billboard scaleByDistance", function() { const packet = { billboard: { scaleByDistance: [ { interval: "2013-01-01T00:00:00Z/2013-01-01T01:00:00Z", nearFarScalar: [1, 2, 1e4, 3] }, { interval: "2013-01-01T01:00:00Z/2013-01-01T02:00:00Z", nearFarScalar: [2, 3, 2e4, 4] } ] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.billboard).toBeDefined(); expect( entity.billboard.scaleByDistance.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:00:00Z") ) ).toEqual( import__55.NearFarScalar.unpack(packet.billboard.scaleByDistance[0].nearFarScalar) ); expect( entity.billboard.scaleByDistance.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:00:00Z") ) ).toEqual( import__55.NearFarScalar.unpack(packet.billboard.scaleByDistance[1].nearFarScalar) ); }); }); it("can handle sampled billboard scaleByDistance", function() { const epoch = import__55.JulianDate.now(); const packet = { billboard: { scaleByDistance: { epoch: import__55.JulianDate.toIso8601(epoch), nearFarScalar: [0, 1, 2, 1e4, 3, 2, 2, 3, 2e4, 4] } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.billboard).toBeDefined(); const date1 = epoch; const date2 = import__55.JulianDate.addSeconds(epoch, 1, new import__55.JulianDate()); const date3 = import__55.JulianDate.addSeconds(epoch, 2, new import__55.JulianDate()); expect(entity.billboard.scaleByDistance.getValue(date1)).toEqual( new import__55.NearFarScalar(1, 2, 1e4, 3) ); expect(entity.billboard.scaleByDistance.getValue(date2)).toEqual( new import__55.NearFarScalar(1.5, 2.5, 15e3, 3.5) ); expect(entity.billboard.scaleByDistance.getValue(date3)).toEqual( new import__55.NearFarScalar(2, 3, 2e4, 4) ); }); }); it("can handle sampled billboard color rgba.", function() { const epoch = import__55.JulianDate.now(); const packet = { billboard: { color: { epoch: import__55.JulianDate.toIso8601(epoch), rgba: [0, 200, 202, 204, 206, 2, 0, 0, 0, 0] } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.billboard).toBeDefined(); const date1 = epoch; const date2 = import__55.JulianDate.addSeconds(epoch, 1, new import__55.JulianDate()); const date3 = import__55.JulianDate.addSeconds(epoch, 2, new import__55.JulianDate()); expect(entity.billboard.color.getValue(date1)).toEqual( import__55.Color.fromBytes(200, 202, 204, 206) ); expect(entity.billboard.color.getValue(date2)).toEqual( import__55.Color.fromBytes(100, 101, 102, 103) ); expect(entity.billboard.color.getValue(date3)).toEqual( import__55.Color.fromBytes(0, 0, 0, 0) ); }); }); it("can handle clock data.", function() { const documentPacket = { id: "document", version: "1.0", clock: { interval: "2012-03-15T10:00:00Z/2012-03-16T10:00:00Z", currentTime: "2012-03-15T10:00:00Z", multiplier: 60, range: "LOOP_STOP", step: "SYSTEM_CLOCK_MULTIPLIER" } }; const interval = import__55.TimeInterval.fromIso8601({ iso8601: documentPacket.clock.interval }); return import__55.CzmlDataSource.load(documentPacket).then(function(dataSource) { const clock = dataSource.clock; expect(clock).toBeDefined(); expect(clock.startTime).toEqual(interval.start); expect(clock.stopTime).toEqual(interval.stop); expect(clock.currentTime).toEqual( import__55.JulianDate.fromIso8601(documentPacket.clock.currentTime) ); expect(clock.clockRange).toEqual(import__55.ClockRange[documentPacket.clock.range]); expect(clock.clockStep).toEqual(import__55.ClockStep[documentPacket.clock.step]); expect(clock.multiplier).toEqual(documentPacket.clock.multiplier); }); }); it("can handle position specified as constant cartographicsDegrees", function() { const packet = { position: { cartographicDegrees: [34, 117, 1e4] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; const resultCartesian = entity.position.getValue(import__55.JulianDate.now()); expect(resultCartesian).toEqual( cartesianFromArrayDegrees(packet.position.cartographicDegrees) ); }); }); it("can handle position specified as constant cartographicsDegrees with non-standard ellipsoid", function() { const WGS84 = import__55.Ellipsoid.WGS84.clone(); import__55.Ellipsoid.WGS84 = new import__55.Ellipsoid(1737400, 1737400, 1737400); const packet = { position: { cartographicDegrees: [34, 117, 1e4] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; const resultCartesian = entity.position.getValue(import__55.JulianDate.now()); expect(resultCartesian).toEqual( cartesianFromArrayDegrees( packet.position.cartographicDegrees, 0, import__55.Ellipsoid.WGS84 ) ); import__55.Ellipsoid.WGS84 = WGS84; }); }); it("can handle position specified as sampled cartographicsDegrees", function() { const epoch = import__55.JulianDate.now(); const packet = { position: { epoch: import__55.JulianDate.toIso8601(epoch), cartographicDegrees: [0, 34, 117, 1e4, 1, 34, 117, 2e4] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; let resultCartesian = entity.position.getValue(epoch); expect(resultCartesian).toEqual( cartesianFromArrayDegrees(packet.position.cartographicDegrees, 1) ); resultCartesian = entity.position.getValue( import__55.JulianDate.addSeconds(epoch, 1, new import__55.JulianDate()) ); expect(resultCartesian).toEqual( cartesianFromArrayDegrees(packet.position.cartographicDegrees, 5) ); }); }); it("can handle position specified as sampled cartographicDegrees without epoch", function() { const lastDate = import__55.JulianDate.now(); const firstDate = new import__55.JulianDate(lastDate.dayNumber - 1, 0); const packet = { position: { cartographicDegrees: [ import__55.JulianDate.toIso8601(firstDate), 34, 117, 1e4, import__55.JulianDate.toIso8601(lastDate), 34, 117, 2e4 ] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; let resultCartesian = entity.position.getValue(firstDate); expect(resultCartesian).toEqual( cartesianFromArrayDegrees(packet.position.cartographicDegrees, 1) ); resultCartesian = entity.position.getValue(lastDate); expect(resultCartesian).toEqual( cartesianFromArrayDegrees(packet.position.cartographicDegrees, 5) ); }); }); it("can handle position specified as constant cartographicRadians", function() { const packet = { position: { cartographicRadians: [1, 2, 1e4] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; const resultCartesian = entity.position.getValue(import__55.JulianDate.now()); expect(resultCartesian).toEqual( cartesianFromArrayRadians(packet.position.cartographicRadians) ); }); }); it("can handle position specified as constant cartographicRadians with non-standard ellipsoid", function() { const WGS84 = import__55.Ellipsoid.WGS84.clone(); import__55.Ellipsoid.WGS84 = new import__55.Ellipsoid(1737400, 1737400, 1737400); const packet = { position: { cartographicRadians: [1, 2, 1e4] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; const resultCartesian = entity.position.getValue(import__55.JulianDate.now()); expect(resultCartesian).toEqual( cartesianFromArrayRadians( packet.position.cartographicRadians, 0, import__55.Ellipsoid.WGS84 ) ); import__55.Ellipsoid.WGS84 = WGS84; }); }); it("can handle position specified as sampled cartographicRadians", function() { const epoch = import__55.JulianDate.now(); const packet = { position: { epoch: import__55.JulianDate.toIso8601(epoch), cartographicRadians: [0, 2, 0.3, 1e4, 1, 0.2, 0.5, 2e4] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; let resultCartesian = entity.position.getValue(epoch); expect(resultCartesian).toEqual( cartesianFromArrayRadians(packet.position.cartographicRadians, 1) ); resultCartesian = entity.position.getValue( import__55.JulianDate.addSeconds(epoch, 1, new import__55.JulianDate()) ); expect(resultCartesian).toEqual( cartesianFromArrayRadians(packet.position.cartographicRadians, 5) ); }); }); it("can set position reference frame", function() { const epoch = import__55.JulianDate.now(); const dataSource = new import__55.CzmlDataSource(); let packet = { position: { referenceFrame: "INERTIAL", epoch: import__55.JulianDate.toIso8601(epoch), cartesian: [1, 2, 3] } }; return dataSource.load(makeDocument(packet)).then(function(dataSource2) { const entity = dataSource2.entities.values[0]; expect(entity.position.referenceFrame).toEqual(import__55.ReferenceFrame.INERTIAL); packet = { position: { referenceFrame: "FIXED", epoch: import__55.JulianDate.toIso8601(epoch), cartesian: [1, 2, 3] } }; return dataSource2.load(makeDocument(packet)); }).then(function(dataSource2) { const entity = dataSource2.entities.values[0]; expect(entity.position.referenceFrame).toEqual(import__55.ReferenceFrame.FIXED); }); }); it("uses FIXED as default position reference frame if not specified in CZML", function() { const epoch = import__55.JulianDate.now(); const packet = { position: { epoch: import__55.JulianDate.toIso8601(epoch), cartesian: [1, 2, 3] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.position.referenceFrame).toEqual(import__55.ReferenceFrame.FIXED); }); }); it("does not reset value to FIXED when omitting reference frame on subsequent packet", function() { const epoch = import__55.JulianDate.now(); const dataSource = new import__55.CzmlDataSource(); let packet = { position: { referenceFrame: "INERTIAL", epoch: import__55.JulianDate.toIso8601(epoch), cartesian: [1, 2, 3] } }; return dataSource.process(makeDocument(packet)).then(function(dataSource2) { const entity = dataSource2.entities.values[0]; expect(entity.position.referenceFrame).toEqual(import__55.ReferenceFrame.INERTIAL); packet = { position: { epoch: import__55.JulianDate.toIso8601(epoch), cartesian: [1, 2, 3] } }; return dataSource2.process(packet); }).then(function(dataSource2) { const entity = dataSource2.entities.values[0]; expect(entity.position.referenceFrame).toEqual(import__55.ReferenceFrame.INERTIAL); }); }); it("can load a number specified as sampled values without epoch.", function() { const firstDate = import__55.Iso8601.MINIMUM_VALUE; const midDate = import__55.JulianDate.addDays(firstDate, 1, new import__55.JulianDate()); const lastDate = import__55.JulianDate.addDays(firstDate, 2, new import__55.JulianDate()); const packet = { ellipse: { semiMajorAxis: { number: [ import__55.JulianDate.toIso8601(firstDate), 0, import__55.JulianDate.toIso8601(lastDate), 10 ] } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.ellipse).toBeDefined(); expect(entity.ellipse.semiMajorAxis.getValue(firstDate)).toEqual(0); expect(entity.ellipse.semiMajorAxis.getValue(midDate)).toEqual(5); expect(entity.ellipse.semiMajorAxis.getValue(lastDate)).toEqual(10); }); }); it("can load a direction specified as constant unitSpherical", function() { const packet = { billboard: { alignedAxis: { unitSpherical: [1, 2] } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; const resultCartesian = entity.billboard.alignedAxis.getValue( import__55.JulianDate.now() ); expect(resultCartesian).toEqual( import__55.Cartesian3.fromSpherical(new import__55.Spherical(1, 2)) ); }); }); it("can load a direction specified as sampled unitSpherical", function() { const epoch = import__55.JulianDate.now(); const packet = { billboard: { alignedAxis: { epoch: import__55.JulianDate.toIso8601(epoch), unitSpherical: [0, 1, 2, 1, -1, -2] } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; let resultCartesian = entity.billboard.alignedAxis.getValue(epoch); expect(resultCartesian).toEqual( import__55.Cartesian3.fromSpherical(new import__55.Spherical(1, 2)) ); resultCartesian = entity.billboard.alignedAxis.getValue( import__55.JulianDate.addSeconds(epoch, 1, new import__55.JulianDate()) ); expect(resultCartesian).toEqual( import__55.Cartesian3.fromSpherical(new import__55.Spherical(-1, -2)) ); }); }); it("can load a direction specified as constant spherical", function() { const packet = { billboard: { alignedAxis: { spherical: [1, 2, 30] } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; const resultCartesian = entity.billboard.alignedAxis.getValue( import__55.JulianDate.now() ); const expected = import__55.Cartesian3.fromSpherical(new import__55.Spherical(1, 2, 30)); import__55.Cartesian3.normalize(expected, expected); expect(resultCartesian).toEqual(expected); }); }); it("can load a direction specified as sampled spherical", function() { const epoch = import__55.JulianDate.now(); const packet = { billboard: { alignedAxis: { epoch: import__55.JulianDate.toIso8601(epoch), spherical: [0, 1, 2, 30, 1, -1, -2, 40] } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; let resultCartesian = entity.billboard.alignedAxis.getValue(epoch); let expected = import__55.Cartesian3.fromSpherical(new import__55.Spherical(1, 2, 30)); import__55.Cartesian3.normalize(expected, expected); expect(resultCartesian).toEqual(expected); resultCartesian = entity.billboard.alignedAxis.getValue( import__55.JulianDate.addSeconds(epoch, 1, new import__55.JulianDate()) ); expected = import__55.Cartesian3.fromSpherical(new import__55.Spherical(-1, -2, 40)); import__55.Cartesian3.normalize(expected, expected); expect(resultCartesian).toEqual(expected); }); }); it("can load constant data for ellipse", function() { const packet = { ellipse: { semiMajorAxis: 10, semiMinorAxis: 20, rotation: 1, outline: true, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 6, shadows: "ENABLED", zIndex: 8, classificationType: "TERRAIN" } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.ellipse).toBeDefined(); expect(entity.ellipse.semiMajorAxis.getValue(time2)).toEqual( packet.ellipse.semiMajorAxis ); expect(entity.ellipse.semiMinorAxis.getValue(time2)).toEqual( packet.ellipse.semiMinorAxis ); expect(entity.ellipse.rotation.getValue(time2)).toEqual( packet.ellipse.rotation ); expect(entity.ellipse.outline.getValue(time2)).toEqual( packet.ellipse.outline ); expect(entity.ellipse.outlineColor.getValue(time2)).toEqual( import__55.Color.unpack(packet.ellipse.outlineColor.rgbaf) ); expect(entity.ellipse.outlineWidth.getValue(time2)).toEqual( packet.ellipse.outlineWidth ); expect(entity.ellipse.shadows.getValue(time2)).toEqual( import__55.ShadowMode[packet.ellipse.shadows] ); expect(entity.ellipse.zIndex.getValue(time2)).toEqual( packet.ellipse.zIndex ); expect(entity.ellipse.classificationType.getValue(time2)).toEqual( import__55.ClassificationType[packet.ellipse.classificationType] ); }); }); it("can load interval data for ellipse", function() { const packet = { ellipse: { interval: "2000-01-01/2001-01-01", semiMajorAxis: 10, semiMinorAxis: 20, rotation: 1, shadows: "ENABLED" } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; const validTime = import__55.TimeInterval.fromIso8601({ iso8601: packet.ellipse.interval }).start; const invalidTime = import__55.JulianDate.addSeconds( validTime, -1, new import__55.JulianDate() ); expect(entity.ellipse).toBeDefined(); expect(entity.ellipse.semiMajorAxis.getValue(validTime)).toEqual( packet.ellipse.semiMajorAxis ); expect(entity.ellipse.semiMinorAxis.getValue(validTime)).toEqual( packet.ellipse.semiMinorAxis ); expect(entity.ellipse.rotation.getValue(validTime)).toEqual( packet.ellipse.rotation ); expect(entity.ellipse.shadows.getValue(validTime)).toEqual( import__55.ShadowMode[packet.ellipse.shadows] ); expect( entity.ellipse.semiMajorAxis.getValue(invalidTime) ).toBeUndefined(); expect( entity.ellipse.semiMinorAxis.getValue(invalidTime) ).toBeUndefined(); expect(entity.ellipse.rotation.getValue(invalidTime)).toBeUndefined(); expect(entity.ellipse.shadows.getValue(invalidTime)).toBeUndefined(); }); }); it("can load constant data for ellipsoid", function() { const packet = { ellipsoid: { radii: { cartesian: [1, 2, 3] }, show: true, material: { solidColor: { color: { rgbaf: [0.1, 0.1, 0.1, 0.1] } } }, outline: true, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 6, stackPartitions: 25, slicePartitions: 26, subdivisions: 27, shadows: "ENABLED" } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.ellipsoid).toBeDefined(); expect(entity.ellipsoid.radii.getValue(time2)).toEqual( import__55.Cartesian3.unpack(packet.ellipsoid.radii.cartesian) ); expect(entity.ellipsoid.show.getValue(time2)).toEqual( packet.ellipsoid.show ); expect(entity.ellipsoid.material.getValue(time2).color).toEqual( import__55.Color.unpack(packet.ellipsoid.material.solidColor.color.rgbaf) ); expect(entity.ellipsoid.outline.getValue(time2)).toEqual( packet.ellipsoid.outline ); expect(entity.ellipsoid.outlineColor.getValue(time2)).toEqual( import__55.Color.unpack(packet.ellipsoid.outlineColor.rgbaf) ); expect(entity.ellipsoid.outlineWidth.getValue(time2)).toEqual( packet.ellipsoid.outlineWidth ); expect(entity.ellipsoid.stackPartitions.getValue(time2)).toEqual( packet.ellipsoid.stackPartitions ); expect(entity.ellipsoid.slicePartitions.getValue(time2)).toEqual( packet.ellipsoid.slicePartitions ); expect(entity.ellipsoid.subdivisions.getValue(time2)).toEqual( packet.ellipsoid.subdivisions ); expect(entity.ellipsoid.shadows.getValue(time2)).toEqual( import__55.ShadowMode[packet.ellipsoid.shadows] ); }); }); it("can load interval data for ellipsoid", function() { const packet = { ellipsoid: { interval: "2000-01-01/2001-01-01", radii: { cartesian: [1, 2, 3] }, show: true, material: { solidColor: { color: { rgbaf: [0.1, 0.1, 0.1, 0.1] } } }, shadows: "ENABLED" } }; const validTime = import__55.TimeInterval.fromIso8601({ iso8601: packet.ellipsoid.interval }).start; const invalidTime = import__55.JulianDate.addSeconds(validTime, -1, new import__55.JulianDate()); return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.ellipsoid).toBeDefined(); expect(entity.ellipsoid.radii.getValue(validTime)).toEqual( import__55.Cartesian3.unpack(packet.ellipsoid.radii.cartesian) ); expect(entity.ellipsoid.show.getValue(validTime)).toEqual( packet.ellipsoid.show ); expect(entity.ellipsoid.material.getValue(validTime).color).toEqual( import__55.Color.unpack(packet.ellipsoid.material.solidColor.color.rgbaf) ); expect(entity.ellipsoid.shadows.getValue(validTime)).toEqual( import__55.ShadowMode[packet.ellipsoid.shadows] ); expect(entity.ellipsoid.radii.getValue(invalidTime)).toBeUndefined(); expect(entity.ellipsoid.show.getValue(invalidTime)).toBeUndefined(); expect(entity.ellipsoid.material.getValue(invalidTime)).toBeUndefined(); expect(entity.ellipsoid.shadows.getValue(invalidTime)).toBeUndefined(); }); }); it("can load constant data for label", function() { const packet = { label: { text: "TestFacility", font: '10pt "Open Sans"', style: "FILL", fillColor: { rgbaf: [0.1, 0.1, 0.1, 0.1] }, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 3.14, horizontalOrigin: "LEFT", verticalOrigin: "CENTER", eyeOffset: { cartesian: [1, 2, 3] }, pixelOffset: { cartesian2: [4, 5] }, scale: 1, show: true, translucencyByDistance: { nearFarScalar: [1, 1, 1e4, 0] }, pixelOffsetScaleByDistance: { nearFarScalar: [1, 20, 1e4, 30] } } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.label).toBeDefined(); expect(entity.label.text.getValue(time2)).toEqual(packet.label.text); expect(entity.label.font.getValue(time2)).toEqual(packet.label.font); expect(entity.label.style.getValue(time2)).toEqual( import__55.LabelStyle[packet.label.style] ); expect(entity.label.fillColor.getValue(time2)).toEqual( import__55.Color.unpack(packet.label.fillColor.rgbaf) ); expect(entity.label.outlineColor.getValue(time2)).toEqual( import__55.Color.unpack(packet.label.outlineColor.rgbaf) ); expect(entity.label.outlineWidth.getValue(time2)).toEqual( packet.label.outlineWidth ); expect(entity.label.horizontalOrigin.getValue(time2)).toEqual( import__55.HorizontalOrigin[packet.label.horizontalOrigin] ); expect(entity.label.verticalOrigin.getValue(time2)).toEqual( import__55.VerticalOrigin[packet.label.verticalOrigin] ); expect(entity.label.eyeOffset.getValue(time2)).toEqual( import__55.Cartesian3.unpack(packet.label.eyeOffset.cartesian) ); expect(entity.label.pixelOffset.getValue(time2)).toEqual( import__55.Cartesian2.unpack(packet.label.pixelOffset.cartesian2) ); expect(entity.label.scale.getValue(time2)).toEqual(packet.label.scale); expect(entity.label.show.getValue(time2)).toEqual(packet.label.show); expect(entity.label.translucencyByDistance.getValue(time2)).toEqual( import__55.NearFarScalar.unpack(packet.label.translucencyByDistance.nearFarScalar) ); expect(entity.label.pixelOffsetScaleByDistance.getValue(time2)).toEqual( import__55.NearFarScalar.unpack( packet.label.pixelOffsetScaleByDistance.nearFarScalar ) ); }); }); it("can load interval data for label", function() { const packet = { label: { interval: "2000-01-01/2001-01-01", text: "TestFacility", font: '10pt "Open Sans"', style: "FILL", fillColor: { rgbaf: [0.1, 0.1, 0.1, 0.1] }, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 2.78, horizontalOrigin: "LEFT", verticalOrigin: "CENTER", eyeOffset: { cartesian: [1, 2, 3] }, pixelOffset: { cartesian2: [4, 5] }, scale: 1, show: true } }; const validTime = import__55.TimeInterval.fromIso8601({ iso8601: packet.label.interval }).start; const invalidTime = import__55.JulianDate.addSeconds(validTime, -1, new import__55.JulianDate()); return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.label).toBeDefined(); expect(entity.label.text.getValue(validTime)).toEqual(packet.label.text); expect(entity.label.font.getValue(validTime)).toEqual(packet.label.font); expect(entity.label.style.getValue(validTime)).toEqual( import__55.LabelStyle[packet.label.style] ); expect(entity.label.fillColor.getValue(validTime)).toEqual( import__55.Color.unpack(packet.label.fillColor.rgbaf) ); expect(entity.label.outlineColor.getValue(validTime)).toEqual( import__55.Color.unpack(packet.label.outlineColor.rgbaf) ); expect(entity.label.outlineWidth.getValue(validTime)).toEqual( packet.label.outlineWidth ); expect(entity.label.horizontalOrigin.getValue(validTime)).toEqual( import__55.HorizontalOrigin[packet.label.horizontalOrigin] ); expect(entity.label.verticalOrigin.getValue(validTime)).toEqual( import__55.VerticalOrigin[packet.label.verticalOrigin] ); expect(entity.label.eyeOffset.getValue(validTime)).toEqual( import__55.Cartesian3.unpack(packet.label.eyeOffset.cartesian) ); expect(entity.label.pixelOffset.getValue(validTime)).toEqual( import__55.Cartesian2.unpack(packet.label.pixelOffset.cartesian2) ); expect(entity.label.scale.getValue(validTime)).toEqual( packet.label.scale ); expect(entity.label.show.getValue(validTime)).toEqual(packet.label.show); expect(entity.label.text.getValue(invalidTime)).toBeUndefined(); expect(entity.label.font.getValue(invalidTime)).toBeUndefined(); expect(entity.label.style.getValue(invalidTime)).toBeUndefined(); expect(entity.label.fillColor.getValue(invalidTime)).toBeUndefined(); expect(entity.label.outlineColor.getValue(invalidTime)).toBeUndefined(); expect(entity.label.outlineWidth.getValue(invalidTime)).toBeUndefined(); expect( entity.label.horizontalOrigin.getValue(invalidTime) ).toBeUndefined(); expect(entity.label.verticalOrigin.getValue(invalidTime)).toBeUndefined(); expect(entity.label.eyeOffset.getValue(invalidTime)).toBeUndefined(); expect(entity.label.pixelOffset.getValue(invalidTime)).toBeUndefined(); expect(entity.label.scale.getValue(invalidTime)).toBeUndefined(); expect(entity.label.show.getValue(invalidTime)).toBeUndefined(); }); }); it("can handle sampled label pixelOffset.", function() { const epoch = import__55.JulianDate.now(); const packet = { label: { pixelOffset: { epoch: import__55.JulianDate.toIso8601(epoch), cartesian2: [0, 1, 2, 1, 3, 4] } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.label).toBeDefined(); const date1 = epoch; const date2 = import__55.JulianDate.addSeconds(epoch, 1, new import__55.JulianDate()); expect(entity.label.pixelOffset.getValue(date1)).toEqual( new import__55.Cartesian2(1, 2) ); expect(entity.label.pixelOffset.getValue(date2)).toEqual( new import__55.Cartesian2(3, 4) ); }); }); it("can load position", function() { const packet = { position: { cartesian: [1, 2, 3] } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.position.getValue(time2)).toEqual( import__55.Cartesian3.unpack(packet.position.cartesian) ); }); }); it("can load orientation", function() { const packet = { orientation: { unitQuaternion: [0, 0, 0, 1] } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.orientation.getValue(time2)).toEqual( import__55.Quaternion.unpack(packet.orientation.unitQuaternion) ); }); }); it("normalizes constant orientation on load", function() { const packet = { orientation: { unitQuaternion: [0, 0, 0.7071067, 0.7071067] } }; const expected = import__55.Quaternion.unpack(packet.orientation.unitQuaternion); import__55.Quaternion.normalize(expected, expected); const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.orientation.getValue(time2)).toEqual(expected); }); }); it("normalizes sampled orientation on load", function() { const time1 = "2000-01-01T00:00:00Z"; const time2 = "2000-01-01T00:00:01Z"; const packet = { orientation: { unitQuaternion: [ time1, 0, 0, 0.7071067, 0.7071067, time2, 0.7071067, 0.7071067, 0, 0 ] } }; const expected1 = import__55.Quaternion.unpack(packet.orientation.unitQuaternion, 1); import__55.Quaternion.normalize(expected1, expected1); const expected2 = import__55.Quaternion.unpack(packet.orientation.unitQuaternion, 6); import__55.Quaternion.normalize(expected2, expected2); return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect( entity.orientation.getValue(import__55.JulianDate.fromIso8601(time1)) ).toEqual(expected1); expect( entity.orientation.getValue(import__55.JulianDate.fromIso8601(time2)) ).toEqual(expected2); }); }); it("can handle orientation expressed as a velocity reference", function() { const packet = { position: { epoch: "2016-06-17T12:00:00Z", cartesian: [0, 1, 2, 3, 60, 61, 122, 183] }, orientation: { velocityReference: "#position" } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; const property = entity.orientation; const expectedVelocity = new import__55.Cartesian3(1, 2, 3); const expectedVelocityDirection = import__55.Cartesian3.normalize( expectedVelocity, new import__55.Cartesian3() ); const expectedPosition = new import__55.Cartesian3(1, 2, 3); const expectedRotation = import__55.Transforms.rotationMatrixFromPositionVelocity( expectedPosition, expectedVelocityDirection ); const expectedOrientation = import__55.Quaternion.fromRotationMatrix( expectedRotation ); expect( property.getValue(import__55.JulianDate.fromIso8601("2016-06-17T12:00:00Z")) ).toEqualEpsilon(expectedOrientation, import__55.Math.EPSILON15); expect( property.getValue(import__55.JulianDate.fromIso8601("2016-06-17T12:00:30Z")) ).toEqualEpsilon(expectedOrientation, import__55.Math.EPSILON15); }); }); it("can load positions expressed as cartesians", function() { const packet = { polyline: { positions: { cartesian: [1, 2, 3, 5, 6, 7] } } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polyline.positions.getValue(time2)).toEqual( import__55.Cartesian3.unpackArray(packet.polyline.positions.cartesian) ); }); }); it("can load positions expressed as cartographicRadians", function() { const packet = { polyline: { positions: { cartographicRadians: [1, 2, 4, 5, 6, 7] } } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polyline.positions.getValue(time2)).toEqual( import__55.Cartesian3.fromRadiansArrayHeights( packet.polyline.positions.cartographicRadians ) ); }); }); it("can load positions expressed as cartographicDegrees", function() { const packet = { polyline: { positions: { cartographicDegrees: [1, 2, 3, 5, 6, 7] } } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polyline.positions.getValue(time2)).toEqual( import__55.Cartesian3.fromDegreesArrayHeights( packet.polyline.positions.cartographicDegrees ) ); }); }); it("can load viewFrom", function() { const packet = { viewFrom: { cartesian: [1, 2, 3] } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.viewFrom.getValue(time2)).toEqual( import__55.Cartesian3.unpack(packet.viewFrom.cartesian) ); }); }); it("can load description", function() { const packet = { description: "this is a description" }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.description.getValue(time2)).toEqual(packet.description); }); }); it("can load constant custom properties", function() { const testObject = { foo: 4, bar: { name: "bar" } }; const testArray = [2, 4, 16, "test"]; const packet = { properties: { constant_name: "ABC", constant_height: 8, constant_object: { value: testObject }, constant_array: { value: testArray } } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.properties.constant_name.getValue(time2)).toEqual( packet.properties.constant_name ); expect(entity.properties.constant_height.getValue(time2)).toEqual( packet.properties.constant_height ); expect(entity.properties.constant_object.getValue(time2)).toEqual( testObject ); expect(entity.properties.constant_array.getValue(time2)).toEqual( testArray ); }); }); it("can load custom properties which are constant with specified type", function() { const testObject = { foo: 4, bar: { name: "bar" } }; const testArray = [2, 4, 16, "test"]; const packet = { properties: { constant_name: { string: "ABC" }, constant_height: { number: 8 }, constant_object: { object: testObject }, constant_array: { array: testArray } } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.properties.constant_name.getValue(time2)).toEqual( packet.properties.constant_name.string ); expect(entity.properties.constant_height.getValue(time2)).toEqual( packet.properties.constant_height.number ); expect(entity.properties.constant_object.getValue(time2)).toEqual( testObject ); expect(entity.properties.constant_array.getValue(time2)).toEqual( testArray ); }); }); it("can load custom properties with one interval", function() { const packet = { properties: { changing_name: { interval: "2012/2014", value: "ABC" } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect( entity.properties.changing_name.getValue(import__55.JulianDate.fromIso8601("2013")) ).toEqual(packet.properties.changing_name.value); expect( entity.properties.changing_name.getValue(import__55.JulianDate.fromIso8601("2015")) ).toBeUndefined(); }); }); it("can load custom properties with one interval with specified type", function() { const packet = { properties: { changing_name: { interval: "2012/2014", string: "ABC" } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect( entity.properties.changing_name.getValue(import__55.JulianDate.fromIso8601("2013")) ).toEqual(packet.properties.changing_name.string); expect( entity.properties.changing_name.getValue(import__55.JulianDate.fromIso8601("2015")) ).toBeUndefined(); }); }); it("can load custom properties with multiple intervals", function() { const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const packet = { properties: { changing_array: [ { interval: "2012/2013", value: array1 }, { interval: "2013/2014", value: array2 } ] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect( entity.properties.changing_array.getValue( import__55.JulianDate.fromIso8601("2012-06-01") ) ).toEqual(array1); expect( entity.properties.changing_array.getValue( import__55.JulianDate.fromIso8601("2013-06-01") ) ).toEqual(array2); }); }); it("can load boolean custom properties with multiple intervals", function() { const packet = { id: "MyID", properties: { custom_boolean: [ { interval: "2012-04-02T12:00:00Z/2012-04-02T12:00:01Z", boolean: true }, { interval: "2012-04-02T12:00:01Z/2012-04-02T12:00:02Z", boolean: false }, { interval: "2012-04-02T12:00:02Z/2012-04-02T12:01:00Z", boolean: true } ] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.getById("MyID"); expect(entity).toBeDefined(); expect(entity.properties).toBeDefined(); expect(entity.properties.custom_boolean).toBeDefined(); expect( entity.properties.custom_boolean.getValue( import__55.JulianDate.fromIso8601("2012-04-02T12:00:00Z") ) ).toEqual(true); expect( entity.properties.custom_boolean.getValue( import__55.JulianDate.fromIso8601("2012-04-02T12:00:01Z") ) ).toEqual(false); expect( entity.properties.custom_boolean.getValue( import__55.JulianDate.fromIso8601("2012-04-02T12:00:02Z") ) ).toEqual(true); }); }); it("can load custom properties with multiple intervals with specified type", function() { const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const packet = { properties: { changing_array: [ { interval: "2012/2013", array: array1 }, { interval: "2013/2014", array: array2 } ] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect( entity.properties.changing_array.getValue( import__55.JulianDate.fromIso8601("2012-06-01") ) ).toEqual(array1); expect( entity.properties.changing_array.getValue( import__55.JulianDate.fromIso8601("2013-06-01") ) ).toEqual(array2); }); }); it("can load sampled custom properties", function() { const packet = { id: "MyID", properties: { custom_cartesian: { epoch: "2012-04-02T12:00:00Z", cartesian: [0, 1, 2, 3, 60, 4, 5, 6, 120, 7, 8, 9] } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.getById("MyID"); expect(entity).toBeDefined(); expect(entity.properties).toBeDefined(); expect(entity.properties.custom_cartesian).toBeDefined(); expect( entity.properties.custom_cartesian.getValue( import__55.JulianDate.fromIso8601("2012-04-02T12:00:00Z") ) ).toBeInstanceOf(import__55.Cartesian3); expect( entity.properties.custom_cartesian.getValue( import__55.JulianDate.fromIso8601("2012-04-02T12:00:00Z") ) ).toEqual(new import__55.Cartesian3(1, 2, 3)); expect( entity.properties.custom_cartesian.getValue( import__55.JulianDate.fromIso8601("2012-04-02T12:00:30Z") ) ).toEqual(new import__55.Cartesian3((1 + 4) / 2, (2 + 5) / 2, (3 + 6) / 2)); expect( entity.properties.custom_cartesian.getValue( import__55.JulianDate.fromIso8601("2012-04-02T12:01:00Z") ) ).toEqual(new import__55.Cartesian3(4, 5, 6)); expect( entity.properties.custom_cartesian.getValue( import__55.JulianDate.fromIso8601("2012-04-02T12:02:00Z") ) ).toEqual(new import__55.Cartesian3(7, 8, 9)); }); }); it("can load various types of custom properties", function() { const interval1 = "2012/2013"; const interval2 = "2013/2014"; const packet = { id: "MyID", properties: { custom_array_constant: { array: [1, 2, 3] }, custom_array_interval: [ { interval: interval1, array: [1, 2, 3] }, { interval: interval2, array: [4, 5, 6] } ], custom_boolean_constant: { boolean: true }, custom_boolean_interval: [ { interval: interval1, boolean: true }, { interval: interval2, boolean: false } ], custom_boundingRectangle_constant: { boundingRectangle: [20, 30, 10, 11] }, custom_boundingRectangle_interval: [ { interval: interval1, boundingRectangle: [20, 30, 10, 11] }, { interval: interval2, boundingRectangle: [21, 31, 11, 12] } ], custom_boundingRectangle_sampled: { epoch: "2012-06-01", boundingRectangle: [0, 20, 30, 10, 11, 60, 21, 31, 11, 12] }, custom_cartesian2_constant: { cartesian2: [20, 30] }, custom_cartesian2_interval: [ { interval: interval1, cartesian2: [20, 30] }, { interval: interval2, cartesian2: [21, 31] } ], custom_cartesian2_sampled: { epoch: "2012-06-01", cartesian2: [0, 20, 30, 60, 21, 31] }, custom_cartesian_constant: { cartesian: [10, 11, 12] }, custom_cartesian_interval: [ { interval: interval1, cartesian: [10, 11, 12] }, { interval: interval2, cartesian: [13, 14, 15] } ], custom_cartesian_sampled: { epoch: "2012-06-01", cartesian: [0, 10, 11, 12, 60, 13, 14, 15] }, custom_color_constant: { rgbaf: [0.1, 0.2, 0.3, 0.4] }, custom_color_interval: [ { interval: interval1, rgbaf: [0.1, 0.2, 0.3, 0.4] }, { interval: interval2, rgbaf: [0.5, 0.6, 0.7, 0.8] } ], custom_color_sampled: { epoch: "2012-06-01", rgbaf: [0, 0.1, 0.2, 0.3, 0.4, 60, 0.5, 0.6, 0.7, 0.8] }, custom_date_constant: { date: "2014-06-01" }, custom_date_interval: [ { interval: interval1, date: "2014-06-01" }, { interval: interval2, date: "2015-06-01" } ] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.getById("MyID"); expect(entity).toBeDefined(); expect(entity.properties).toBeDefined(); const time1 = import__55.JulianDate.fromIso8601("2012-06-01"); const time2 = import__55.JulianDate.fromIso8601("2013-06-01"); expect(entity.properties.custom_array_constant).toBeDefined(); expect( entity.properties.custom_array_constant.getValue(time1) ).toBeInstanceOf(Array); expect(entity.properties.custom_array_constant.getValue(time1)).toEqual( packet.properties.custom_array_constant.array ); expect(entity.properties.custom_array_interval).toBeDefined(); expect( entity.properties.custom_array_interval.getValue(time1) ).toBeInstanceOf(Array); expect(entity.properties.custom_array_interval.getValue(time1)).toEqual( packet.properties.custom_array_interval[0].array ); expect(entity.properties.custom_array_interval.getValue(time2)).toEqual( packet.properties.custom_array_interval[1].array ); expect(entity.properties.custom_boolean_constant).toBeDefined(); expect(entity.properties.custom_boolean_constant.getValue(time1)).toEqual( packet.properties.custom_boolean_constant.boolean ); expect(entity.properties.custom_boolean_interval).toBeDefined(); expect(entity.properties.custom_boolean_interval.getValue(time1)).toEqual( packet.properties.custom_boolean_interval[0].boolean ); expect(entity.properties.custom_boolean_interval.getValue(time2)).toEqual( packet.properties.custom_boolean_interval[1].boolean ); expect(entity.properties.custom_boundingRectangle_constant).toBeDefined(); expect( entity.properties.custom_boundingRectangle_constant.getValue(time1) ).toBeInstanceOf(import__55.BoundingRectangle); expect( entity.properties.custom_boundingRectangle_constant.getValue(time1) ).toEqual( import__55.BoundingRectangle.unpack( packet.properties.custom_boundingRectangle_constant.boundingRectangle ) ); expect(entity.properties.custom_boundingRectangle_interval).toBeDefined(); expect( entity.properties.custom_boundingRectangle_interval.getValue(time1) ).toBeInstanceOf(import__55.BoundingRectangle); expect( entity.properties.custom_boundingRectangle_interval.getValue(time1) ).toEqual( import__55.BoundingRectangle.unpack( packet.properties.custom_boundingRectangle_interval[0].boundingRectangle ) ); expect( entity.properties.custom_boundingRectangle_interval.getValue(time2) ).toEqual( import__55.BoundingRectangle.unpack( packet.properties.custom_boundingRectangle_interval[1].boundingRectangle ) ); expect(entity.properties.custom_boundingRectangle_sampled).toBeDefined(); expect( entity.properties.custom_boundingRectangle_sampled.getValue(time1) ).toBeInstanceOf(import__55.BoundingRectangle); expect( entity.properties.custom_boundingRectangle_sampled.getValue(time1) ).toEqual( import__55.BoundingRectangle.unpack( packet.properties.custom_boundingRectangle_sampled.boundingRectangle, 0 + 1 ) ); expect( entity.properties.custom_boundingRectangle_sampled.getValue( import__55.JulianDate.addSeconds(time1, 60, new import__55.JulianDate()) ) ).toEqual( import__55.BoundingRectangle.unpack( packet.properties.custom_boundingRectangle_sampled.boundingRectangle, 4 + 2 ) ); expect(entity.properties.custom_cartesian2_constant).toBeDefined(); expect( entity.properties.custom_cartesian2_constant.getValue(time1) ).toBeInstanceOf(import__55.Cartesian2); expect( entity.properties.custom_cartesian2_constant.getValue(time1) ).toEqual( import__55.Cartesian2.unpack( packet.properties.custom_cartesian2_constant.cartesian2 ) ); expect(entity.properties.custom_cartesian2_interval).toBeDefined(); expect( entity.properties.custom_cartesian2_interval.getValue(time1) ).toBeInstanceOf(import__55.Cartesian2); expect( entity.properties.custom_cartesian2_interval.getValue(time1) ).toEqual( import__55.Cartesian2.unpack( packet.properties.custom_cartesian2_interval[0].cartesian2 ) ); expect( entity.properties.custom_cartesian2_interval.getValue(time2) ).toEqual( import__55.Cartesian2.unpack( packet.properties.custom_cartesian2_interval[1].cartesian2 ) ); expect(entity.properties.custom_cartesian2_sampled).toBeDefined(); expect( entity.properties.custom_cartesian2_sampled.getValue(time1) ).toBeInstanceOf(import__55.Cartesian2); expect( entity.properties.custom_cartesian2_sampled.getValue(time1) ).toEqual( import__55.Cartesian2.unpack( packet.properties.custom_cartesian2_sampled.cartesian2, 0 + 1 ) ); expect( entity.properties.custom_cartesian2_sampled.getValue( import__55.JulianDate.addSeconds(time1, 60, new import__55.JulianDate()) ) ).toEqual( import__55.Cartesian2.unpack( packet.properties.custom_cartesian2_sampled.cartesian2, 2 + 2 ) ); expect(entity.properties.custom_cartesian_constant).toBeDefined(); expect( entity.properties.custom_cartesian_constant.getValue(time1) ).toBeInstanceOf(import__55.Cartesian3); expect( entity.properties.custom_cartesian_constant.getValue(time1) ).toEqual( import__55.Cartesian3.unpack(packet.properties.custom_cartesian_constant.cartesian) ); expect(entity.properties.custom_cartesian_interval).toBeDefined(); expect( entity.properties.custom_cartesian_interval.getValue(time1) ).toBeInstanceOf(import__55.Cartesian3); expect( entity.properties.custom_cartesian_interval.getValue(time1) ).toEqual( import__55.Cartesian3.unpack( packet.properties.custom_cartesian_interval[0].cartesian ) ); expect( entity.properties.custom_cartesian_interval.getValue(time2) ).toEqual( import__55.Cartesian3.unpack( packet.properties.custom_cartesian_interval[1].cartesian ) ); expect(entity.properties.custom_cartesian_sampled).toBeDefined(); expect( entity.properties.custom_cartesian_sampled.getValue(time1) ).toBeInstanceOf(import__55.Cartesian3); expect( entity.properties.custom_cartesian_sampled.getValue(time1) ).toEqual( import__55.Cartesian3.unpack( packet.properties.custom_cartesian_sampled.cartesian, 0 + 1 ) ); expect( entity.properties.custom_cartesian_sampled.getValue( import__55.JulianDate.addSeconds(time1, 60, new import__55.JulianDate()) ) ).toEqual( import__55.Cartesian3.unpack( packet.properties.custom_cartesian_sampled.cartesian, 3 + 2 ) ); expect(entity.properties.custom_color_constant).toBeDefined(); expect( entity.properties.custom_color_constant.getValue(time1) ).toBeInstanceOf(import__55.Color); expect(entity.properties.custom_color_constant.getValue(time1)).toEqual( import__55.Color.unpack(packet.properties.custom_color_constant.rgbaf) ); expect(entity.properties.custom_color_interval).toBeDefined(); expect( entity.properties.custom_color_interval.getValue(time1) ).toBeInstanceOf(import__55.Color); expect(entity.properties.custom_color_interval.getValue(time1)).toEqual( import__55.Color.unpack(packet.properties.custom_color_interval[0].rgbaf) ); expect(entity.properties.custom_color_interval.getValue(time2)).toEqual( import__55.Color.unpack(packet.properties.custom_color_interval[1].rgbaf) ); expect(entity.properties.custom_color_sampled).toBeDefined(); expect( entity.properties.custom_color_sampled.getValue(time1) ).toBeInstanceOf(import__55.Color); expect(entity.properties.custom_color_sampled.getValue(time1)).toEqual( import__55.Color.unpack(packet.properties.custom_color_sampled.rgbaf, 0 + 1) ); expect( entity.properties.custom_color_sampled.getValue( import__55.JulianDate.addSeconds(time1, 60, new import__55.JulianDate()) ) ).toEqual( import__55.Color.unpack(packet.properties.custom_color_sampled.rgbaf, 4 + 2) ); expect(entity.properties.custom_date_constant).toBeDefined(); expect( entity.properties.custom_date_constant.getValue(time1) ).toBeInstanceOf(import__55.JulianDate); expect(entity.properties.custom_date_constant.getValue(time1)).toEqual( import__55.JulianDate.fromIso8601(packet.properties.custom_date_constant.date) ); expect(entity.properties.custom_date_interval).toBeDefined(); expect( entity.properties.custom_date_interval.getValue(time1) ).toBeInstanceOf(import__55.JulianDate); expect(entity.properties.custom_date_interval.getValue(time1)).toEqual( import__55.JulianDate.fromIso8601(packet.properties.custom_date_interval[0].date) ); expect(entity.properties.custom_date_interval.getValue(time2)).toEqual( import__55.JulianDate.fromIso8601(packet.properties.custom_date_interval[1].date) ); }); }); it("can delete an entire property", function() { function createDataSource() { return import__55.CzmlDataSource.load([ { id: "document", version: "1.0" }, { id: "test-constant", billboard: { scale: 1 } }, { id: "test-interval", billboard: { scale: [ { interval: "2012-03-15T10:00:00Z/2012-03-16T10:00:00Z", number: 1 } ] } }, { id: "test-sampled", billboard: { scale: { number: ["2012-03-15T10:00:00Z", 1] } } } ]); } const deletePackets = [ { id: "test-constant", billboard: { scale: { delete: true } } }, { id: "test-interval", billboard: { scale: { delete: true } } }, { id: "test-sampled", billboard: { scale: { delete: true } } } ]; const deleteMaxIntervalPackets = [ { id: "test-constant", billboard: { scale: { interval: import__55.TimeInterval.toIso8601(import__55.Iso8601.MAXIMUM_INTERVAL), delete: true } } }, { id: "test-interval", billboard: { scale: { interval: import__55.TimeInterval.toIso8601(import__55.Iso8601.MAXIMUM_INTERVAL), delete: true } } }, { id: "test-sampled", billboard: { scale: { interval: import__55.TimeInterval.toIso8601(import__55.Iso8601.MAXIMUM_INTERVAL), delete: true } } } ]; function expectPropertiesToBeDefined(dataSource) { let entity = dataSource.entities.getById("test-constant"); expect(entity.billboard.scale).toBeInstanceOf(import__55.ConstantProperty); entity = dataSource.entities.getById("test-interval"); expect(entity.billboard.scale).toBeInstanceOf( import__55.TimeIntervalCollectionProperty ); entity = dataSource.entities.getById("test-sampled"); expect(entity.billboard.scale).toBeInstanceOf(import__55.SampledProperty); return dataSource; } function expectPropertiesToBeUndefined(dataSource) { let entity = dataSource.entities.getById("test-constant"); expect(entity.billboard.scale).toBeUndefined(); entity = dataSource.entities.getById("test-interval"); expect(entity.billboard.scale).toBeUndefined(); entity = dataSource.entities.getById("test-sampled"); expect(entity.billboard.scale).toBeUndefined(); return dataSource; } return createDataSource().then(expectPropertiesToBeDefined).then(function(dataSource) { return dataSource.process(deletePackets); }).then(expectPropertiesToBeUndefined).then(function(dataSource) { return dataSource.process(deletePackets); }).then(expectPropertiesToBeUndefined).then(createDataSource).then(function(dataSource) { return dataSource.process(deleteMaxIntervalPackets); }).then(expectPropertiesToBeUndefined).then(function(dataSource) { return dataSource.process(deleteMaxIntervalPackets); }).then(expectPropertiesToBeUndefined); }); it("can delete a custom property", function() { function createDataSource() { return import__55.CzmlDataSource.load([ { id: "document", version: "1.0" }, { id: "test", properties: { custom: { number: ["2012-03-15T10:00:00Z", 1] } } } ]); } const deletePackets = [ { id: "test", properties: { custom: { delete: true } } } ]; function expectPropertiesToBeDefined(dataSource) { const entity = dataSource.entities.getById("test"); expect(entity.properties.custom).toBeInstanceOf(import__55.SampledProperty); return dataSource; } function expectPropertiesToBeUndefined(dataSource) { const entity = dataSource.entities.getById("test"); expect(entity.properties.custom).toBeUndefined(); return dataSource; } return createDataSource().then(expectPropertiesToBeDefined).then(function(dataSource) { return dataSource.process(deletePackets); }).then(expectPropertiesToBeUndefined).then(function(dataSource) { return dataSource.process(deletePackets); }).then(expectPropertiesToBeUndefined); }); it("can delete an entire position property", function() { function createDataSource() { return import__55.CzmlDataSource.load([ { id: "document", version: "1.0" }, { id: "test-constant", position: { cartographicDegrees: [34, 117, 1e4] } }, { id: "test-interval", position: [ { interval: "2012-03-15T10:00:00Z/2012-03-16T10:00:00Z", cartographicDegrees: [34, 117, 1e4] } ] }, { id: "test-sampled", position: { cartographicDegrees: ["2012-03-15T10:00:00Z", 34, 117, 1e4] } } ]); } const deletePackets = [ { id: "test-constant", position: { delete: true } }, { id: "test-interval", position: { delete: true } }, { id: "test-sampled", position: { delete: true } } ]; const deleteMaxIntervalPackets = [ { id: "test-constant", position: { interval: import__55.TimeInterval.toIso8601(import__55.Iso8601.MAXIMUM_INTERVAL), delete: true } }, { id: "test-interval", position: { interval: import__55.TimeInterval.toIso8601(import__55.Iso8601.MAXIMUM_INTERVAL), delete: true } }, { id: "test-sampled", position: { interval: import__55.TimeInterval.toIso8601(import__55.Iso8601.MAXIMUM_INTERVAL), delete: true } } ]; function expectPropertiesToBeDefined(dataSource) { let entity = dataSource.entities.getById("test-constant"); expect(entity.position).toBeInstanceOf(import__55.ConstantPositionProperty); entity = dataSource.entities.getById("test-interval"); expect(entity.position).toBeInstanceOf( import__55.TimeIntervalCollectionPositionProperty ); entity = dataSource.entities.getById("test-sampled"); expect(entity.position).toBeInstanceOf(import__55.SampledPositionProperty); return dataSource; } function expectPropertiesToBeUndefined(dataSource) { let entity = dataSource.entities.getById("test-constant"); expect(entity.position).toBeUndefined(); entity = dataSource.entities.getById("test-interval"); expect(entity.position).toBeUndefined(); entity = dataSource.entities.getById("test-sampled"); expect(entity.position).toBeUndefined(); return dataSource; } return createDataSource().then(expectPropertiesToBeDefined).then(function(dataSource) { return dataSource.process(deletePackets); }).then(expectPropertiesToBeUndefined).then(function(dataSource) { return dataSource.process(deletePackets); }).then(expectPropertiesToBeUndefined).then(createDataSource).then(function(dataSource) { return dataSource.process(deleteMaxIntervalPackets); }).then(expectPropertiesToBeUndefined).then(function(dataSource) { return dataSource.process(deleteMaxIntervalPackets); }).then(expectPropertiesToBeUndefined); }); it("can delete samples from a sampled property", function() { const packet = { id: "id", billboard: { scale: { number: [ "2012-03-15T10:00:00Z", 1, "2012-03-15T11:00:00Z", 5, "2012-03-15T12:00:00Z", 3 ] } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.getById("id"); expect(entity.billboard.scale).toBeInstanceOf(import__55.SampledProperty); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2012-03-15T10:00:00Z") ) ).toEqual(1); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2012-03-15T11:00:00Z") ) ).toEqual(5); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2012-03-15T12:00:00Z") ) ).toEqual(3); return dataSource; }).then(function(dataSource) { const deletePacket = { id: "id", billboard: { scale: { interval: "2012-03-15T11:00:00Z/2012-03-15T11:00:00Z", delete: true } } }; return dataSource.process(deletePacket); }).then(function(dataSource) { const entity = dataSource.entities.getById("id"); expect(entity.billboard.scale).toBeInstanceOf(import__55.SampledProperty); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2012-03-15T10:00:00Z") ) ).toEqual(1); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2012-03-15T11:00:00Z") ) ).toEqual(2); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2012-03-15T12:00:00Z") ) ).toEqual(3); }); }); it("can delete samples from a sampled custom property", function() { const packet = { id: "id", properties: { custom: { number: [ "2012-03-15T10:00:00Z", 1, "2012-03-15T11:00:00Z", 5, "2012-03-15T12:00:00Z", 3 ] } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.getById("id"); expect(entity.properties.custom).toBeInstanceOf(import__55.SampledProperty); expect( entity.properties.custom.getValue( import__55.JulianDate.fromIso8601("2012-03-15T10:00:00Z") ) ).toEqual(1); expect( entity.properties.custom.getValue( import__55.JulianDate.fromIso8601("2012-03-15T11:00:00Z") ) ).toEqual(5); expect( entity.properties.custom.getValue( import__55.JulianDate.fromIso8601("2012-03-15T12:00:00Z") ) ).toEqual(3); return dataSource; }).then(function(dataSource) { const deletePacket = { id: "id", properties: { custom: { interval: "2012-03-15T11:00:00Z/2012-03-15T11:00:00Z", delete: true } } }; return dataSource.process(deletePacket); }).then(function(dataSource) { const entity = dataSource.entities.getById("id"); expect(entity.properties.custom).toBeInstanceOf(import__55.SampledProperty); expect( entity.properties.custom.getValue( import__55.JulianDate.fromIso8601("2012-03-15T10:00:00Z") ) ).toEqual(1); expect( entity.properties.custom.getValue( import__55.JulianDate.fromIso8601("2012-03-15T11:00:00Z") ) ).toEqual(2); expect( entity.properties.custom.getValue( import__55.JulianDate.fromIso8601("2012-03-15T12:00:00Z") ) ).toEqual(3); }); }); it("can delete samples from a sampled position property", function() { const packet = { id: "id", position: { epoch: "2016-06-17T12:00:00Z", cartesian: [0, 1, 2, 3, 60, 61, 122, 183, 120, 3, 4, 5] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.getById("id"); expect(entity.position).toBeInstanceOf(import__55.SampledPositionProperty); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2016-06-17T12:00:00Z") ) ).toEqual(new import__55.Cartesian3(1, 2, 3)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2016-06-17T12:01:00Z") ) ).toEqual(new import__55.Cartesian3(61, 122, 183)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2016-06-17T12:02:00Z") ) ).toEqual(new import__55.Cartesian3(3, 4, 5)); return dataSource; }).then(function(dataSource) { const deletePacket = { id: "id", position: { interval: "2016-06-17T12:00:45Z/2016-06-17T12:01:10Z", delete: true } }; return dataSource.process(deletePacket); }).then(function(dataSource) { const entity = dataSource.entities.getById("id"); expect(entity.position).toBeInstanceOf(import__55.SampledPositionProperty); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2016-06-17T12:00:00Z") ) ).toEqual(new import__55.Cartesian3(1, 2, 3)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2016-06-17T12:01:00Z") ) ).toEqual(new import__55.Cartesian3(2, 3, 4)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2016-06-17T12:02:00Z") ) ).toEqual(new import__55.Cartesian3(3, 4, 5)); }); }); it("can delete interval from an interval property", function() { const packet = { id: "id", billboard: { scale: [ { interval: "2013-01-01T00:00:00Z/2013-01-01T01:00:00Z", number: 2 }, { interval: "2013-01-01T01:00:00Z/2013-01-01T02:00:00Z", number: 6 } ] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.getById("id"); expect(entity.billboard.scale).toBeInstanceOf( import__55.TimeIntervalCollectionProperty ); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:30:00Z") ) ).toEqual(2); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:30:00Z") ) ).toEqual(6); return dataSource; }).then(function(dataSource) { const deletePacket = { id: "id", billboard: { scale: { interval: "2013-01-01T00:30:00Z/2013-01-01T01:30:00Z", delete: true } } }; return dataSource.process(deletePacket); }).then(function(dataSource) { const entity = dataSource.entities.getById("id"); expect(entity.billboard.scale).toBeInstanceOf( import__55.TimeIntervalCollectionProperty ); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:30:00Z") ) ).toBeUndefined(); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:30:00Z") ) ).toBeUndefined(); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:29:00Z") ) ).toEqual(2); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:31:00Z") ) ).toEqual(6); }); }); it("can delete interval from an interval position property", function() { const packet = { id: "id", position: [ { interval: "2013-01-01T00:00:00Z/2013-01-01T01:00:00Z", cartesian: [1, 2, 3] }, { interval: "2013-01-01T01:00:00Z/2013-01-01T02:00:00Z", cartesian: [4, 5, 6] } ] }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.getById("id"); expect(entity.position).toBeInstanceOf( import__55.TimeIntervalCollectionPositionProperty ); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:30:00Z") ) ).toEqual(new import__55.Cartesian3(1, 2, 3)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:30:00Z") ) ).toEqual(new import__55.Cartesian3(4, 5, 6)); return dataSource; }).then(function(dataSource) { const deletePacket = { id: "id", position: { interval: "2013-01-01T00:30:00Z/2013-01-01T01:30:00Z", delete: true } }; return dataSource.process(deletePacket); }).then(function(dataSource) { const entity = dataSource.entities.getById("id"); expect(entity.position).toBeInstanceOf( import__55.TimeIntervalCollectionPositionProperty ); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:30:00Z") ) ).toBeUndefined(); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:30:00Z") ) ).toBeUndefined(); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:29:00Z") ) ).toEqual(new import__55.Cartesian3(1, 2, 3)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:31:00Z") ) ).toEqual(new import__55.Cartesian3(4, 5, 6)); }); }); it("can delete samples from a composite property", function() { const packet = { id: "id", billboard: { scale: [ { interval: "2013-01-01T00:00:00Z/2013-01-01T01:00:00Z", epoch: "2013-01-01T00:00:00Z", number: [0, 1, 30, 6, 60, 3] }, { interval: "2013-01-01T00:02:00Z/2013-01-01T01:00:00Z", number: 33 }, { interval: "2013-01-01T01:00:00Z/2013-01-01T02:00:00Z", number: [ "2013-01-01T01:00:00Z", 9, "2013-01-01T01:00:30Z", 19, "2013-01-01T01:01:00Z", 11 ] } ] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.getById("id"); expect(entity.billboard.scale).toBeInstanceOf(import__55.CompositeProperty); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:00:00Z") ) ).toEqual(1); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:00:30Z") ) ).toEqual(6); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:01:00Z") ) ).toEqual(3); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:02:00Z") ) ).toEqual(33); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:00:00Z") ) ).toEqual(9); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:00:30Z") ) ).toEqual(19); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:01:00Z") ) ).toEqual(11); return dataSource; }).then(function(dataSource) { const deletePacket = { id: "id", billboard: { scale: { interval: "2013-01-01T00:01:00Z/2013-01-01T01:00:00Z", delete: true } } }; return dataSource.process(deletePacket); }).then(function(dataSource) { const entity = dataSource.entities.getById("id"); expect(entity.billboard.scale).toBeInstanceOf(import__55.CompositeProperty); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:00:00Z") ) ).toEqual(1); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:00:30Z") ) ).toEqual(6); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:01:00Z") ) ).toBeUndefined(); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:02:00Z") ) ).toBeUndefined(); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:00:00Z") ) ).toBeUndefined(); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:00:30Z") ) ).toEqual(19); expect( entity.billboard.scale.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:01:00Z") ) ).toEqual(11); }); }); it("can delete samples from a composite position property", function() { const packet = { id: "id", position: [ { interval: "2013-01-01T00:00:00Z/2013-01-01T01:00:00Z", epoch: "2013-01-01T00:00:00Z", cartesian: [0, 1, 2, 3, 30, 6, 7, 8, 60, 3, 4, 5] }, { interval: "2013-01-01T00:02:00Z/2013-01-01T01:00:00Z", cartesian: [15, 16, 17] }, { interval: "2013-01-01T01:00:00Z/2013-01-01T02:00:00Z", cartesian: [ "2013-01-01T01:00:00Z", 9, 15, 10, "2013-01-01T01:00:30Z", 19, 16, 11, "2013-01-01T01:01:00Z", 11, 17, 12 ] } ] }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.getById("id"); expect(entity.position).toBeInstanceOf(import__55.CompositePositionProperty); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:00:00Z") ) ).toEqual(new import__55.Cartesian3(1, 2, 3)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:00:30Z") ) ).toEqual(new import__55.Cartesian3(6, 7, 8)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:01:00Z") ) ).toEqual(new import__55.Cartesian3(3, 4, 5)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:02:00Z") ) ).toEqual(new import__55.Cartesian3(15, 16, 17)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:00:00Z") ) ).toEqual(new import__55.Cartesian3(9, 15, 10)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:00:30Z") ) ).toEqual(new import__55.Cartesian3(19, 16, 11)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:01:00Z") ) ).toEqual(new import__55.Cartesian3(11, 17, 12)); return dataSource; }).then(function(dataSource) { const deletePacket = { id: "id", position: { interval: "2013-01-01T00:01:00Z/2013-01-01T01:00:00Z", delete: true } }; return dataSource.process(deletePacket); }).then(function(dataSource) { const entity = dataSource.entities.getById("id"); expect(entity.position).toBeInstanceOf(import__55.CompositePositionProperty); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:00:00Z") ) ).toEqual(new import__55.Cartesian3(1, 2, 3)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:00:30Z") ) ).toEqual(new import__55.Cartesian3(6, 7, 8)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:01:00Z") ) ).toBeUndefined(); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:02:00Z") ) ).toBeUndefined(); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:00:00Z") ) ).toBeUndefined(); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:00:30Z") ) ).toEqual(new import__55.Cartesian3(19, 16, 11)); expect( entity.position.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:01:00Z") ) ).toEqual(new import__55.Cartesian3(11, 17, 12)); }); }); it("can load custom properties in a way that allows CompositeEntityCollection to work", function() { const testObject1 = { foo: 4, bar: { name: "bar" } }; const testArray1 = [2, 4, 16, "test"]; const packet1 = { id: "test", properties: { constant_name: "ABC", constant_height: 8, constant_object: { value: testObject1 }, constant_array: { value: testArray1 } } }; const dataSource1 = new import__55.CzmlDataSource(); const dataSource2 = new import__55.CzmlDataSource(); const time2 = import__55.Iso8601.MINIMUM_VALUE; const packet2 = { id: "test", properties: { constant_name: "DEF" } }; const testObject3 = { some: "value" }; const testArray3 = ["not", "the", "same", 4]; const packet3 = { id: "test", properties: { constant_height: 9, constant_object: { value: testObject3 }, constant_array: { value: testArray3 } } }; let entity, composite; return dataSource1.load(makeDocument(packet1)).then(function() { composite = new import__55.CompositeEntityCollection([ dataSource1.entities, dataSource2.entities ]); entity = composite.values[0]; expect(entity.properties.constant_name.getValue(time2)).toEqual( packet1.properties.constant_name ); expect(entity.properties.constant_height.getValue(time2)).toEqual( packet1.properties.constant_height ); expect(entity.properties.constant_object.getValue(time2)).toEqual( testObject1 ); expect(entity.properties.constant_array.getValue(time2)).toEqual( testArray1 ); return dataSource2.load(makeDocument(packet2)); }).then(function() { entity = composite.values[0]; expect(entity.properties.constant_name.getValue(time2)).toEqual( packet2.properties.constant_name ); expect(entity.properties.constant_height.getValue(time2)).toEqual( packet1.properties.constant_height ); expect(entity.properties.constant_object.getValue(time2)).toEqual( testObject1 ); expect(entity.properties.constant_array.getValue(time2)).toEqual( testArray1 ); return dataSource2.process(packet3); }).then(function() { entity = composite.values[0]; expect(entity.properties.constant_name.getValue(time2)).toEqual( packet2.properties.constant_name ); expect(entity.properties.constant_height.getValue(time2)).toEqual( packet3.properties.constant_height ); expect(entity.properties.constant_object.getValue(time2)).toEqual( testObject3 ); expect(entity.properties.constant_array.getValue(time2)).toEqual( testArray3 ); }); }); it("can load and modify availability from a single interval", function() { const packet1 = { id: "testObject", availability: "2000-01-01/2001-01-01" }; const packet2 = { id: "testObject", availability: "2000-02-02/2001-02-02" }; const dataSource = new import__55.CzmlDataSource(); return dataSource.process(makeDocument(packet1)).then(function(dataSource2) { const entity = dataSource2.entities.values[0]; const interval = import__55.TimeInterval.fromIso8601({ iso8601: packet1.availability }); expect(entity.availability.length).toEqual(1); expect(entity.availability.get(0)).toEqual(interval); return dataSource2.process(packet2); }).then(function(dataSource2) { const entity = dataSource2.entities.values[0]; const interval = import__55.TimeInterval.fromIso8601({ iso8601: packet2.availability }); expect(entity.availability.length).toEqual(1); expect(entity.availability.get(0)).toEqual(interval); }); }); it("can load and modify availability from multiple intervals", function() { const packet1 = { id: "testObject", availability: ["2000-01-01/2001-01-01", "2002-01-01/2003-01-01"] }; const packet2 = { id: "testObject", availability: ["2003-01-01/2004-01-01", "2005-01-01/2006-01-01"] }; const dataSource = new import__55.CzmlDataSource(); return dataSource.process(makeDocument(packet1)).then(function(dataSource2) { const entity = dataSource2.entities.values[0]; const interval1 = import__55.TimeInterval.fromIso8601({ iso8601: packet1.availability[0] }); const interval2 = import__55.TimeInterval.fromIso8601({ iso8601: packet1.availability[1] }); expect(entity.availability.length).toEqual(2); expect(entity.availability.get(0)).toEqual(interval1); expect(entity.availability.get(1)).toEqual(interval2); return dataSource2.process(packet2); }).then(function(dataSource2) { const entity = dataSource2.entities.values[0]; const interval1 = import__55.TimeInterval.fromIso8601({ iso8601: packet2.availability[0] }); const interval2 = import__55.TimeInterval.fromIso8601({ iso8601: packet2.availability[1] }); expect(entity.availability.length).toEqual(2); expect(entity.availability.get(0)).toEqual(interval1); expect(entity.availability.get(1)).toEqual(interval2); }); }); it("can load constant data for path", function() { const packet = { path: { material: { polylineOutline: { color: { rgbaf: [0.1, 0.1, 0.1, 0.1] }, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 1 } }, width: 1, resolution: 23, leadTime: 2, trailTime: 3, show: true } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.path).toBeDefined(); expect(entity.path.material.color.getValue(time2)).toEqual( import__55.Color.unpack(packet.path.material.polylineOutline.color.rgbaf) ); expect(entity.path.material.outlineColor.getValue(time2)).toEqual( import__55.Color.unpack(packet.path.material.polylineOutline.outlineColor.rgbaf) ); expect(entity.path.material.outlineWidth.getValue(time2)).toEqual( packet.path.material.polylineOutline.outlineWidth ); expect(entity.path.width.getValue(time2)).toEqual(packet.path.width); expect(entity.path.resolution.getValue(time2)).toEqual( packet.path.resolution ); expect(entity.path.leadTime.getValue(time2)).toEqual(packet.path.leadTime); expect(entity.path.trailTime.getValue(time2)).toEqual( packet.path.trailTime ); expect(entity.path.show.getValue(time2)).toEqual(packet.path.show); }); }); it("can load interval data for path", function() { const packet = { path: { interval: "2000-01-01/2001-01-01", material: { polylineOutline: { color: { rgbaf: [0.1, 0.1, 0.1, 0.1] }, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 1 } }, width: 1, resolution: 23, leadTime: 2, trailTime: 3, show: true } }; const validTime = import__55.TimeInterval.fromIso8601({ iso8601: packet.path.interval }).start; const invalidTime = import__55.JulianDate.addSeconds(validTime, -1, new import__55.JulianDate()); return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.path).toBeDefined(); expect(entity.path.width.getValue(validTime)).toEqual(packet.path.width); expect(entity.path.resolution.getValue(validTime)).toEqual( packet.path.resolution ); expect(entity.path.leadTime.getValue(validTime)).toEqual( packet.path.leadTime ); expect(entity.path.trailTime.getValue(validTime)).toEqual( packet.path.trailTime ); expect(entity.path.show.getValue(validTime)).toEqual(packet.path.show); expect(entity.path.material.getValue(validTime).color).toEqual( import__55.Color.unpack(packet.path.material.polylineOutline.color.rgbaf) ); expect(entity.path.material.getValue(validTime).outlineColor).toEqual( import__55.Color.unpack(packet.path.material.polylineOutline.outlineColor.rgbaf) ); expect(entity.path.material.getValue(validTime).outlineWidth).toEqual( packet.path.material.polylineOutline.outlineWidth ); expect(entity.path.material.getValue(invalidTime)).toBeUndefined(); expect(entity.path.width.getValue(invalidTime)).toBeUndefined(); expect(entity.path.leadTime.getValue(invalidTime)).toBeUndefined(); expect(entity.path.trailTime.getValue(invalidTime)).toBeUndefined(); expect(entity.path.show.getValue(invalidTime)).toBeUndefined(); }); }); it("can load constant data for point", function() { const packet = { point: { color: { rgbaf: [0.1, 0.1, 0.1, 0.1] }, pixelSize: 1, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 1, show: true, scaleByDistance: { nearFarScalar: [1, 2, 1e4, 3] }, translucencyByDistance: { nearFarScalar: [1, 1, 1e4, 0] }, heightReference: "CLAMP_TO_GROUND" } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.point).toBeDefined(); expect(entity.point.color.getValue(time2)).toEqual( import__55.Color.unpack(packet.point.color.rgbaf) ); expect(entity.point.pixelSize.getValue(time2)).toEqual( packet.point.pixelSize ); expect(entity.point.outlineColor.getValue(time2)).toEqual( import__55.Color.unpack(packet.point.outlineColor.rgbaf) ); expect(entity.point.outlineWidth.getValue(time2)).toEqual( packet.point.outlineWidth ); expect(entity.point.show.getValue(time2)).toEqual(packet.point.show); expect(entity.point.scaleByDistance.getValue(time2)).toEqual( import__55.NearFarScalar.unpack(packet.point.scaleByDistance.nearFarScalar) ); expect(entity.point.translucencyByDistance.getValue(time2)).toEqual( import__55.NearFarScalar.unpack(packet.point.translucencyByDistance.nearFarScalar) ); expect(entity.point.heightReference.getValue(time2)).toEqual( import__55.HeightReference[packet.point.heightReference] ); }); }); it("can load interval data for point", function() { const packet = { point: { interval: "2000-01-01/2001-01-01", color: { rgbaf: [0.1, 0.1, 0.1, 0.1] }, pixelSize: 1, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 1, show: true } }; const validTime = import__55.TimeInterval.fromIso8601({ iso8601: packet.point.interval }).start; const invalidTime = import__55.JulianDate.addSeconds(validTime, -1, new import__55.JulianDate()); return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.point).toBeDefined(); expect(entity.point.color.getValue(validTime)).toEqual( import__55.Color.unpack(packet.point.color.rgbaf) ); expect(entity.point.pixelSize.getValue(validTime)).toEqual( packet.point.pixelSize ); expect(entity.point.outlineColor.getValue(validTime)).toEqual( import__55.Color.unpack(packet.point.outlineColor.rgbaf) ); expect(entity.point.outlineWidth.getValue(validTime)).toEqual( packet.point.outlineWidth ); expect(entity.point.show.getValue(validTime)).toEqual(packet.point.show); expect(entity.point.color.getValue(invalidTime)).toBeUndefined(); expect(entity.point.pixelSize.getValue(invalidTime)).toBeUndefined(); expect(entity.point.outlineColor.getValue(invalidTime)).toBeUndefined(); expect(entity.point.outlineWidth.getValue(invalidTime)).toBeUndefined(); expect(entity.point.show.getValue(invalidTime)).toBeUndefined(); }); }); it("can load constant data for polygon", function() { const packet = { polygon: { material: { solidColor: { color: { rgbaf: [0.1, 0.1, 0.1, 0.1] } } }, height: 1, extrudedHeight: 2, granularity: 3, stRotation: 4, show: true, outline: true, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 6, closeTop: false, closeBottom: false, shadows: "ENABLED", zIndex: 3, classificationType: "TERRAIN" } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon).toBeDefined(); expect(entity.polygon.material.getValue(time2).color).toEqual( import__55.Color.unpack(packet.polygon.material.solidColor.color.rgbaf) ); expect(entity.polygon.show.getValue(time2)).toEqual(packet.polygon.show); expect(entity.polygon.height.getValue(time2)).toEqual( packet.polygon.height ); expect(entity.polygon.extrudedHeight.getValue(time2)).toEqual( packet.polygon.extrudedHeight ); expect(entity.polygon.granularity.getValue(time2)).toEqual( packet.polygon.granularity ); expect(entity.polygon.stRotation.getValue(time2)).toEqual( packet.polygon.stRotation ); expect(entity.polygon.outline.getValue(time2)).toEqual( packet.polygon.outline ); expect(entity.polygon.outlineColor.getValue(time2)).toEqual( import__55.Color.unpack(packet.polygon.outlineColor.rgbaf) ); expect(entity.polygon.outlineWidth.getValue(time2)).toEqual( packet.polygon.outlineWidth ); expect(entity.polygon.closeTop.getValue(time2)).toEqual( packet.polygon.closeTop ); expect(entity.polygon.closeBottom.getValue(time2)).toEqual( packet.polygon.closeBottom ); expect(entity.polygon.shadows.getValue(time2)).toEqual( import__55.ShadowMode[packet.polygon.shadows] ); expect(entity.polygon.zIndex.getValue(time2)).toEqual( packet.polygon.zIndex ); expect(entity.polygon.classificationType.getValue(time2)).toEqual( import__55.ClassificationType[packet.polygon.classificationType] ); }); }); it("can load interval data for polygon", function() { const packet = { polygon: { interval: "2000-01-01/2001-01-01", material: { solidColor: { color: { rgbaf: [0.1, 0.1, 0.1, 0.1] } } }, show: true, shadows: "ENABLED" } }; const validTime = import__55.TimeInterval.fromIso8601({ iso8601: packet.polygon.interval }).start; const invalidTime = import__55.JulianDate.addSeconds(validTime, -1, new import__55.JulianDate()); return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon).toBeDefined(); expect(entity.polygon.material.getValue(validTime).color).toEqual( import__55.Color.unpack(packet.polygon.material.solidColor.color.rgbaf) ); expect(entity.polygon.show.getValue(validTime)).toEqual( packet.polygon.show ); expect(entity.polygon.shadows.getValue(validTime)).toEqual( import__55.ShadowMode[packet.polygon.shadows] ); expect(entity.polygon.material.getValue(invalidTime)).toBeUndefined(); expect(entity.polygon.show.getValue(invalidTime)).toBeUndefined(); expect(entity.polygon.shadows.getValue(invalidTime)).toBeUndefined(); }); }); it("can load constant polygon positions", function() { const packet = { polygon: { positions: { cartographicDegrees: [-50, 20, 0, -50, 40, 0, -40, 40, 0, -40, 20, 0] } } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon).toBeDefined(); expect(entity.polygon.hierarchy).toBeDefined(); expect(entity.polygon.hierarchy.isConstant).toEqual(true); let hierarchy = entity.polygon.hierarchy.getValue(time2); expect(hierarchy).toBeInstanceOf(import__55.PolygonHierarchy); expect(hierarchy.positions).toEqual( import__55.Cartesian3.fromDegreesArrayHeights( packet.polygon.positions.cartographicDegrees ) ); hierarchy = entity.polygon.hierarchy.getValue( time2, new import__55.PolygonHierarchy() ); expect(hierarchy).toBeInstanceOf(import__55.PolygonHierarchy); expect(hierarchy.positions).toEqual( import__55.Cartesian3.fromDegreesArrayHeights( packet.polygon.positions.cartographicDegrees ) ); }); }); function unpackPolygonHoleFromCartographicDegrees(holePositions) { return new import__55.PolygonHierarchy( import__55.Cartesian3.fromDegreesArrayHeights(holePositions) ); } it("can load constant polygon positions with holes", function() { const packet = { polygon: { positions: { cartographicDegrees: [-50, 20, 0, -50, 40, 0, -40, 40, 0, -40, 20, 0] }, holes: { cartographicDegrees: [ [-48.2, 39, 0, -44.5, 37, 0, -48.9, 33.1, 0, -49, 36.6, 0], [-45.2, 21, 0, -43.5, 27, 0, -41.6, 21.1, 0] ] } } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon).toBeDefined(); expect(entity.polygon.hierarchy).toBeDefined(); expect(entity.polygon.hierarchy.isConstant).toEqual(true); const hierarchy = entity.polygon.hierarchy.getValue(time2); expect(hierarchy).toBeInstanceOf(import__55.PolygonHierarchy); expect(hierarchy.positions).toEqual( import__55.Cartesian3.fromDegreesArrayHeights( packet.polygon.positions.cartographicDegrees ) ); expect(hierarchy.holes).toEqual( packet.polygon.holes.cartographicDegrees.map( unpackPolygonHoleFromCartographicDegrees ) ); }); }); it("can load interval polygon positions", function() { const packet = { polygon: { positions: [ { interval: "2012-08-04T16:00:00Z/2012-08-04T16:20:00Z", cartographicDegrees: [ -50, 20, 0, -50, 40, 0, -40, 40, 0, -40, 20, 0 ] }, { interval: "2012-08-04T16:20:00Z/2012-08-04T16:40:00Z", cartographicDegrees: [-35, 50, 0, -35, 10, 0, -45, 30, 0] } ] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon).toBeDefined(); expect(entity.polygon.hierarchy).toBeDefined(); expect(entity.polygon.hierarchy.isConstant).toEqual(false); let hierarchy = entity.polygon.hierarchy.getValue( import__55.JulianDate.fromIso8601("2012-08-04T16:10:00Z") ); expect(hierarchy).toBeInstanceOf(import__55.PolygonHierarchy); expect(hierarchy.positions).toEqual( import__55.Cartesian3.fromDegreesArrayHeights( packet.polygon.positions[0].cartographicDegrees ) ); hierarchy = entity.polygon.hierarchy.getValue( import__55.JulianDate.fromIso8601("2012-08-04T16:20:00Z") ); expect(hierarchy).toBeInstanceOf(import__55.PolygonHierarchy); expect(hierarchy.positions).toEqual( import__55.Cartesian3.fromDegreesArrayHeights( packet.polygon.positions[1].cartographicDegrees ) ); }); }); it("can load interval polygon positions with holes expressed as degrees", function() { const packet = { polygon: { positions: [ { interval: "2012-08-04T16:00:00Z/2012-08-04T16:20:00Z", cartographicDegrees: [ -50, 20, 0, -50, 40, 0, -40, 40, 0, -40, 20, 0 ] }, { interval: "2012-08-04T16:20:00Z/2012-08-04T16:40:00Z", cartographicDegrees: [-35, 50, 0, -35, 10, 0, -45, 30, 0] } ], holes: [ { interval: "2012-08-04T16:00:00Z/2012-08-04T16:20:00Z", cartographicDegrees: [ [-48.2, 39, 0, -44.5, 37, 0, -48.9, 33.1, 0, -49, 36.6, 0], [-45.2, 21, 0, -43.5, 27, 0, -41.6, 21.1, 0] ] }, { interval: "2012-08-04T16:20:00Z/2012-08-04T16:40:00Z", cartographicDegrees: [[-40, 34, 0, -37, 26, 0, -41.2, 31, 0]] } ] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon).toBeDefined(); expect(entity.polygon.hierarchy).toBeDefined(); expect(entity.polygon.hierarchy.isConstant).toEqual(false); let hierarchy = entity.polygon.hierarchy.getValue( import__55.JulianDate.fromIso8601("2012-08-04T16:10:00Z") ); expect(hierarchy).toBeInstanceOf(import__55.PolygonHierarchy); expect(hierarchy.positions).toEqual( import__55.Cartesian3.fromDegreesArrayHeights( packet.polygon.positions[0].cartographicDegrees ) ); expect(hierarchy.holes).toEqual( packet.polygon.holes[0].cartographicDegrees.map( unpackPolygonHoleFromCartographicDegrees ) ); hierarchy = entity.polygon.hierarchy.getValue( import__55.JulianDate.fromIso8601("2012-08-04T16:20:00Z") ); expect(hierarchy).toBeInstanceOf(import__55.PolygonHierarchy); expect(hierarchy.positions).toEqual( import__55.Cartesian3.fromDegreesArrayHeights( packet.polygon.positions[1].cartographicDegrees ) ); expect(hierarchy.holes).toEqual( packet.polygon.holes[1].cartographicDegrees.map( unpackPolygonHoleFromCartographicDegrees ) ); }); }); function unpackPolygonHoleFromCartographicRadians(holePositions) { return new import__55.PolygonHierarchy( import__55.Cartesian3.fromRadiansArrayHeights(holePositions) ); } it("can load interval polygon positions with holes expressed as radians", function() { const packet = { polygon: { positions: [ { interval: "2012-08-04T16:00:00Z/2012-08-04T16:20:00Z", cartographicRadians: [ -0.8726646259971648, 0.3490658503988659, 0, -0.8726646259971648, 0.6981317007977318, 0, -0.6981317007977318, 0.6981317007977318, 0, -0.6981317007977318, 0.3490658503988659, 0 ] } ], holes: [ { interval: "2012-08-04T16:00:00Z/2012-08-04T16:20:00Z", cartographicRadians: [ [ -0.8412486994612669, 0.6806784082777885, 0, -0.7766715171374766, 0.6457718232379019, 0, -0.8534660042252271, 0.5777039824101231, 0, -0.8552113334772214, 0.6387905062299246, 0 ] ] } ] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon).toBeDefined(); expect(entity.polygon.hierarchy).toBeDefined(); expect(entity.polygon.hierarchy.isConstant).toEqual(false); const hierarchy = entity.polygon.hierarchy.getValue( import__55.JulianDate.fromIso8601("2012-08-04T16:10:00Z") ); expect(hierarchy).toBeInstanceOf(import__55.PolygonHierarchy); expect(hierarchy.positions).toEqual( import__55.Cartesian3.fromRadiansArrayHeights( packet.polygon.positions[0].cartographicRadians ) ); expect(hierarchy.holes).toEqual( packet.polygon.holes[0].cartographicRadians.map( unpackPolygonHoleFromCartographicRadians ) ); }); }); function unpackPolygonHoleFromCartesian(holePositions) { return new import__55.PolygonHierarchy(import__55.Cartesian3.unpackArray(holePositions)); } it("can load interval polygon positions with holes expressed as cartesian", function() { const packet = { polygon: { positions: [ { interval: "2012-08-04T16:00:00Z/2012-08-04T16:20:00Z", cartesian: [-35, 50, 0, -35, 10, 0, -45, 30, 0] } ], holes: [ { interval: "2012-08-04T16:00:00Z/2012-08-04T16:20:00Z", cartesian: [[-40, 34, 0, -37, 26, 0, -41.2, 31, 0]] } ] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon).toBeDefined(); expect(entity.polygon.hierarchy).toBeDefined(); expect(entity.polygon.hierarchy.isConstant).toEqual(false); const hierarchy = entity.polygon.hierarchy.getValue( import__55.JulianDate.fromIso8601("2012-08-04T16:10:00Z") ); expect(hierarchy).toBeInstanceOf(import__55.PolygonHierarchy); expect(hierarchy.positions).toEqual( import__55.Cartesian3.unpackArray(packet.polygon.positions[0].cartesian) ); expect(hierarchy.holes).toEqual( packet.polygon.holes[0].cartesian.map(unpackPolygonHoleFromCartesian) ); }); }); it("can load reference polygon positions with holes", function() { const packets = [ { id: "document", version: "1.0" }, { id: "target1", position: { cartesian: [1, 2, 3] } }, { id: "target2", position: { cartesian: [4, 5, 6] } }, { id: "target3", position: { cartesian: [7, 8, 9] } }, { id: "target4", position: { cartesian: [1.5, 2.5, 3.5] } }, { id: "target5", position: { cartesian: [1.5, 2.6, 3.5] } }, { id: "target6", position: { cartesian: [1.6, 2.5, 3.5] } }, { id: "polygon", polygon: { positions: { references: [ "target1#position", "target2#position", "target3#position" ] }, holes: { references: [ ["target4#position", "target5#position", "target6#position"] ] } } } ]; return import__55.CzmlDataSource.load(packets).then(function(dataSource) { const entity = dataSource.entities.getById("polygon"); expect(entity.polygon).toBeDefined(); expect(entity.polygon.hierarchy).toBeDefined(); expect(entity.polygon.hierarchy.isConstant).toEqual(true); const time2 = import__55.JulianDate.fromIso8601("2012-08-04T16:10:00Z"); const hierarchy = entity.polygon.hierarchy.getValue(time2); expect(hierarchy).toBeInstanceOf(import__55.PolygonHierarchy); expect(hierarchy.positions).toEqual([ dataSource.entities.getById("target1").position.getValue(time2), dataSource.entities.getById("target2").position.getValue(time2), dataSource.entities.getById("target3").position.getValue(time2) ]); expect(hierarchy.holes).toEqual([ new import__55.PolygonHierarchy([ dataSource.entities.getById("target4").position.getValue(time2), dataSource.entities.getById("target5").position.getValue(time2), dataSource.entities.getById("target6").position.getValue(time2) ]) ]); }); }); it("reports correct value of isConstant for polygon hierarchy", function() { const document2 = [ { id: "document", version: "1.0" }, { id: "constantPositionsTimeVaryingHoles", polygon: { positions: { cartographicDegrees: [ -50, 20, 0, -50, 40, 0, -40, 40, 0, -40, 20, 0 ] }, holes: [ { interval: "2012-08-04T16:00:00Z/2012-08-04T16:20:00Z", cartographicDegrees: [ [-45.2, 21, 0, -43.5, 27, 0, -41.6, 21.1, 0] ] }, { interval: "2012-08-04T16:20:00Z/2012-08-04T16:40:00Z", cartographicDegrees: [[-40, 34, 0, -37, 26, 0, -41.2, 31, 0]] } ] } }, { id: "timeVaryingPositionsConstantHoles", polygon: { positions: [ { interval: "2012-08-04T16:00:00Z/2012-08-04T16:20:00Z", cartographicDegrees: [ -50, 20, 0, -50, 40, 0, -40, 40, 0, -40, 20, 0 ] }, { interval: "2012-08-04T16:20:00Z/2012-08-04T16:40:00Z", cartographicDegrees: [-35, 50, 0, -35, 10, 0, -45, 30, 0] } ], holes: { cartographicDegrees: [[-45.2, 21, 0, -43.5, 27, 0, -41.6, 21.1, 0]] } } } ]; return import__55.CzmlDataSource.load(document2).then(function(dataSource) { let entity = dataSource.entities.getById( "constantPositionsTimeVaryingHoles" ); expect(entity.polygon).toBeDefined(); expect(entity.polygon.hierarchy).toBeDefined(); expect(entity.polygon.hierarchy.isConstant).toEqual(false); entity = dataSource.entities.getById("timeVaryingPositionsConstantHoles"); expect(entity.polygon).toBeDefined(); expect(entity.polygon.hierarchy).toBeDefined(); expect(entity.polygon.hierarchy.isConstant).toEqual(false); }); }); it("can load constant data for polyline", function() { const packet = { polyline: { material: { polylineOutline: { color: { rgbaf: [0.1, 0.1, 0.1, 0.1] }, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 1 } }, width: 1, show: true, shadows: "ENABLED", classificationType: "CESIUM_3D_TILE" } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polyline).toBeDefined(); expect(entity.polyline.material.color.getValue(time2)).toEqual( import__55.Color.unpack(packet.polyline.material.polylineOutline.color.rgbaf) ); expect(entity.polyline.material.outlineColor.getValue(time2)).toEqual( import__55.Color.unpack( packet.polyline.material.polylineOutline.outlineColor.rgbaf ) ); expect(entity.polyline.material.outlineWidth.getValue(time2)).toEqual( packet.polyline.material.polylineOutline.outlineWidth ); expect(entity.polyline.width.getValue(time2)).toEqual( packet.polyline.width ); expect(entity.polyline.show.getValue(time2)).toEqual(packet.polyline.show); expect(entity.polyline.shadows.getValue(time2)).toEqual( import__55.ShadowMode[packet.polyline.shadows] ); expect(entity.polyline.classificationType.getValue(time2)).toEqual( import__55.ClassificationType[packet.polyline.classificationType] ); }); }); it("can load interval data for polyline", function() { const packet = { polyline: { interval: "2000-01-01/2001-01-01", material: { polylineOutline: { color: { rgbaf: [0.1, 0.1, 0.1, 0.1] }, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 1 } }, width: 1, show: true, shadows: "ENABLED" } }; const validTime = import__55.TimeInterval.fromIso8601({ iso8601: packet.polyline.interval }).start; const invalidTime = import__55.JulianDate.addSeconds(validTime, -1, new import__55.JulianDate()); return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polyline).toBeDefined(); expect(entity.polyline.material.getValue(validTime).color).toEqual( import__55.Color.unpack(packet.polyline.material.polylineOutline.color.rgbaf) ); expect(entity.polyline.material.getValue(validTime).outlineColor).toEqual( import__55.Color.unpack( packet.polyline.material.polylineOutline.outlineColor.rgbaf ) ); expect(entity.polyline.material.getValue(validTime).outlineWidth).toEqual( packet.polyline.material.polylineOutline.outlineWidth ); expect(entity.polyline.width.getValue(validTime)).toEqual( packet.polyline.width ); expect(entity.polyline.show.getValue(validTime)).toEqual( packet.polyline.show ); expect(entity.polyline.shadows.getValue(validTime)).toEqual( import__55.ShadowMode[packet.polyline.shadows] ); expect(entity.polyline.material.getValue(invalidTime)).toBeUndefined(); expect(entity.polyline.width.getValue(invalidTime)).toBeUndefined(); expect(entity.polyline.show.getValue(invalidTime)).toBeUndefined(); expect(entity.polyline.shadows.getValue(invalidTime)).toBeUndefined(); }); }); it("can load constant data for polyline clamped to terrain.", function() { const packet = { polyline: { material: { polylineOutline: { color: { rgbaf: [0.1, 0.1, 0.1, 0.1] }, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 1 } }, width: 1, show: true, clampToGround: true, zIndex: 1 } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polyline).toBeDefined(); expect(entity.polyline.material.color.getValue(time2)).toEqual( import__55.Color.unpack(packet.polyline.material.polylineOutline.color.rgbaf) ); expect(entity.polyline.material.outlineColor.getValue(time2)).toEqual( import__55.Color.unpack( packet.polyline.material.polylineOutline.outlineColor.rgbaf ) ); expect(entity.polyline.material.outlineWidth.getValue(time2)).toEqual( packet.polyline.material.polylineOutline.outlineWidth ); expect(entity.polyline.width.getValue(time2)).toEqual( packet.polyline.width ); expect(entity.polyline.show.getValue(time2)).toEqual(packet.polyline.show); expect(entity.polyline.clampToGround.getValue(time2)).toEqual( packet.polyline.clampToGround ); expect(entity.polyline.zIndex.getValue(time2)).toEqual( packet.polyline.zIndex ); }); }); it("can load constant data for polylineVolume", function() { const packet = { id: "id", polylineVolume: { positions: { cartesian: [1, 2, 3, 5, 6, 7] }, shape: { cartesian2: [1, 2, 3, 4] }, cornerType: "MITERED", show: true, fill: true, material: { solidColor: { color: { rgbaf: [0.1, 0.2, 0.3, 0.4] } } }, outline: true, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 6, granularity: 3, shadows: "ENABLED" } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; const dataSource = new import__55.CzmlDataSource(); return dataSource.load(makeDocument(packet)).then(function(dataSource2) { const entity = dataSource2.entities.values[0]; expect(entity.id).toEqual("id"); expect(entity.polylineVolume).toBeDefined(); expect(entity.polylineVolume.positions.getValue(time2)).toEqual( import__55.Cartesian3.unpackArray(packet.polylineVolume.positions.cartesian) ); expect(entity.polylineVolume.shape.getValue(time2)).toEqual( import__55.Cartesian2.unpackArray(packet.polylineVolume.shape.cartesian2) ); expect(entity.polylineVolume.cornerType.getValue(time2)).toEqual( import__55.CornerType[packet.polylineVolume.cornerType] ); expect(entity.polylineVolume.show.getValue(time2)).toEqual( packet.polylineVolume.show ); expect(entity.polylineVolume.fill.getValue(time2)).toEqual( packet.polylineVolume.fill ); expect(entity.polylineVolume.material.getValue(time2).color).toEqual( import__55.Color.unpack(packet.polylineVolume.material.solidColor.color.rgbaf) ); expect(entity.polylineVolume.outline.getValue(time2)).toEqual(true); expect(entity.polylineVolume.outlineColor.getValue(time2)).toEqual( import__55.Color.unpack(packet.polylineVolume.outlineColor.rgbaf) ); expect(entity.polylineVolume.outlineWidth.getValue(time2)).toEqual(6); expect(entity.polylineVolume.granularity.getValue(time2)).toEqual( packet.polylineVolume.granularity ); expect(entity.polylineVolume.shadows.getValue(time2)).toEqual( import__55.ShadowMode[packet.polylineVolume.shadows] ); packet.polylineVolume.shape = { cartesian: [1, 2, 3, 4] }; return dataSource2.load(makeDocument(packet)); }).then(function(dataSource2) { const entity = dataSource2.entities.values[0]; expect(entity.id).toEqual("id"); expect(entity.polylineVolume.shape.getValue(time2)).toEqual( import__55.Cartesian2.unpackArray(packet.polylineVolume.shape.cartesian) ); }); }); it("can load constant data for model", function() { const packet = { model: { show: true, scale: 3, minimumPixelSize: 5, maximumScale: 4, gltf: "./Data/Models/glTF-2.0/BoxArticulations/glTF/BoxArticulations.gltf", incrementallyLoadTextures: true, shadows: "ENABLED", heightReference: "CLAMP_TO_GROUND", silhouetteColor: { rgbaf: [1, 0, 0, 1] }, silhouetteSize: 2, color: { rgbaf: [0, 1, 0, 0.2] }, colorBlendMode: "HIGHLIGHT", colorBlendAmount: 0.5, nodeTransformations: { Mesh: { scale: { cartesian: [1, 2, 3] }, translation: { cartesian: [4, 5, 6] }, rotation: { unitQuaternion: [0, 0.7071, 0, 0.7071] } } }, articulations: { "SampleArticulation Yaw": 30, "SampleArticulation Pitch": 45, "SampleArticulation Roll": 60 } } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.model).toBeDefined(); expect(entity.model.show.getValue(time2)).toEqual(packet.model.show); expect(entity.model.scale.getValue(time2)).toEqual(packet.model.scale); expect(entity.model.minimumPixelSize.getValue(time2)).toEqual( packet.model.minimumPixelSize ); expect(entity.model.maximumScale.getValue(time2)).toEqual( packet.model.maximumScale ); expect(entity.model.uri.getValue(time2).url).toEqual(packet.model.gltf); expect(entity.model.incrementallyLoadTextures.getValue(time2)).toEqual( packet.model.incrementallyLoadTextures ); expect(entity.model.shadows.getValue(time2)).toEqual( import__55.ShadowMode[packet.model.shadows] ); expect(entity.model.heightReference.getValue(time2)).toEqual( import__55.HeightReference[packet.model.heightReference] ); expect(entity.model.silhouetteColor.getValue(time2)).toEqual( import__55.Color.unpack(packet.model.silhouetteColor.rgbaf) ); expect(entity.model.silhouetteSize.getValue(time2)).toEqual( packet.model.silhouetteSize ); expect(entity.model.color.getValue(time2)).toEqual( import__55.Color.unpack(packet.model.color.rgbaf) ); expect(entity.model.colorBlendMode.getValue(time2)).toEqual( import__55.ColorBlendMode[packet.model.colorBlendMode] ); expect(entity.model.colorBlendAmount.getValue(time2)).toEqual( packet.model.colorBlendAmount ); const nodeTransform = entity.model.nodeTransformations.getValue(time2).Mesh; expect(nodeTransform).toBeDefined(); expect(nodeTransform.scale).toEqual( import__55.Cartesian3.unpack(packet.model.nodeTransformations.Mesh.scale.cartesian) ); expect(nodeTransform.translation).toEqual( import__55.Cartesian3.unpack( packet.model.nodeTransformations.Mesh.translation.cartesian ) ); const expectedRotation = import__55.Quaternion.unpack( packet.model.nodeTransformations.Mesh.rotation.unitQuaternion ); import__55.Quaternion.normalize(expectedRotation, expectedRotation); expect(nodeTransform.rotation).toEqual(expectedRotation); expect( entity.model.nodeTransformations.Mesh.scale.getValue(time2) ).toEqual( import__55.Cartesian3.unpack(packet.model.nodeTransformations.Mesh.scale.cartesian) ); expect( entity.model.nodeTransformations.Mesh.translation.getValue(time2) ).toEqual( import__55.Cartesian3.unpack( packet.model.nodeTransformations.Mesh.translation.cartesian ) ); expect( entity.model.nodeTransformations.Mesh.rotation.getValue(time2) ).toEqual(expectedRotation); const articulations = entity.model.articulations.getValue(time2); expect(articulations).toBeDefined(); expect(articulations["SampleArticulation Yaw"]).toEqual( packet.model.articulations["SampleArticulation Yaw"] ); expect(articulations["SampleArticulation Pitch"]).toEqual( packet.model.articulations["SampleArticulation Pitch"] ); expect(articulations["SampleArticulation Roll"]).toEqual( packet.model.articulations["SampleArticulation Roll"] ); }); }); it("can load interval data for model", function() { const packet = { model: { interval: "2000-01-01/2001-01-01", show: true, scale: 3, minimumPixelSize: 5, gltf: "./Data/Models/glTF-2.0/BoxArticulations/glTF/BoxArticulations.gltf", incrementallyLoadTextures: true, shadows: "ENABLED", heightReference: "CLAMP_TO_GROUND", silhouetteColor: { rgbaf: [1, 0, 0, 1] }, silhouetteSize: 2, color: { rgbaf: [0, 1, 0, 0.2] }, colorBlendMode: "HIGHLIGHT", colorBlendAmount: 0.5, nodeTransformations: { Mesh: { scale: { cartesian: [1, 2, 3] }, translation: { cartesian: [4, 5, 6] }, rotation: { unitQuaternion: [0, 0.7071, 0, 0.7071] } } }, articulations: { "SampleArticulation Yaw": 30, "SampleArticulation Pitch": 45, "SampleArticulation Roll": 60 } } }; const validTime = import__55.TimeInterval.fromIso8601({ iso8601: packet.model.interval }).start; const invalidTime = import__55.JulianDate.addSeconds(validTime, -1, new import__55.JulianDate()); return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.model).toBeDefined(); expect(entity.model.show.getValue(validTime)).toEqual(packet.model.show); expect(entity.model.scale.getValue(validTime)).toEqual( packet.model.scale ); expect(entity.model.minimumPixelSize.getValue(validTime)).toEqual( packet.model.minimumPixelSize ); expect(entity.model.uri.getValue(validTime).url).toEqual( packet.model.gltf ); expect( entity.model.incrementallyLoadTextures.getValue(validTime) ).toEqual(packet.model.incrementallyLoadTextures); expect(entity.model.shadows.getValue(validTime)).toEqual( import__55.ShadowMode[packet.model.shadows] ); expect(entity.model.heightReference.getValue(validTime)).toEqual( import__55.HeightReference[packet.model.heightReference] ); expect(entity.model.silhouetteColor.getValue(validTime)).toEqual( import__55.Color.unpack(packet.model.silhouetteColor.rgbaf) ); expect(entity.model.silhouetteSize.getValue(validTime)).toEqual( packet.model.silhouetteSize ); expect(entity.model.color.getValue(validTime)).toEqual( import__55.Color.unpack(packet.model.color.rgbaf) ); expect(entity.model.colorBlendMode.getValue(validTime)).toEqual( import__55.ColorBlendMode[packet.model.colorBlendMode] ); expect(entity.model.colorBlendAmount.getValue(validTime)).toEqual( packet.model.colorBlendAmount ); const nodeTransform = entity.model.nodeTransformations.getValue(validTime).Mesh; expect(nodeTransform).toBeDefined(); expect(nodeTransform.scale).toEqual( import__55.Cartesian3.unpack(packet.model.nodeTransformations.Mesh.scale.cartesian) ); expect(nodeTransform.translation).toEqual( import__55.Cartesian3.unpack( packet.model.nodeTransformations.Mesh.translation.cartesian ) ); const expectedRotation = import__55.Quaternion.unpack( packet.model.nodeTransformations.Mesh.rotation.unitQuaternion ); import__55.Quaternion.normalize(expectedRotation, expectedRotation); expect(nodeTransform.rotation).toEqual(expectedRotation); expect( entity.model.nodeTransformations.Mesh.scale.getValue(validTime) ).toEqual( import__55.Cartesian3.unpack(packet.model.nodeTransformations.Mesh.scale.cartesian) ); expect( entity.model.nodeTransformations.Mesh.translation.getValue(validTime) ).toEqual( import__55.Cartesian3.unpack( packet.model.nodeTransformations.Mesh.translation.cartesian ) ); expect( entity.model.nodeTransformations.Mesh.rotation.getValue(validTime) ).toEqual(expectedRotation); const articulations = entity.model.articulations.getValue(validTime); expect(articulations).toBeDefined(); expect(articulations["SampleArticulation Yaw"]).toEqual( packet.model.articulations["SampleArticulation Yaw"] ); expect(articulations["SampleArticulation Pitch"]).toEqual( packet.model.articulations["SampleArticulation Pitch"] ); expect(articulations["SampleArticulation Roll"]).toEqual( packet.model.articulations["SampleArticulation Roll"] ); expect(entity.model.show.getValue(invalidTime)).toBeUndefined(); expect(entity.model.scale.getValue(invalidTime)).toBeUndefined(); expect( entity.model.minimumPixelSize.getValue(invalidTime) ).toBeUndefined(); expect(entity.model.uri.getValue(invalidTime)).toBeUndefined(); expect( entity.model.incrementallyLoadTextures.getValue(invalidTime) ).toBeUndefined(); expect(entity.model.shadows.getValue(invalidTime)).toBeUndefined(); expect( entity.model.heightReference.getValue(invalidTime) ).toBeUndefined(); expect(entity.model.color.getValue(invalidTime)).toBeUndefined(); expect( entity.model.silhouetteColor.getValue(invalidTime) ).toBeUndefined(); expect(entity.model.silhouetteSize.getValue(invalidTime)).toBeUndefined(); expect(entity.model.colorBlendMode.getValue(invalidTime)).toBeUndefined(); expect( entity.model.colorBlendAmount.getValue(invalidTime) ).toBeUndefined(); expect( entity.model.nodeTransformations.Mesh.getValue(invalidTime) ).toEqual(new import__55.TranslationRotationScale()); expect( entity.model.nodeTransformations.Mesh.scale.getValue(invalidTime) ).toBeUndefined(); expect( entity.model.nodeTransformations.Mesh.translation.getValue(invalidTime) ).toBeUndefined(); expect( entity.model.nodeTransformations.Mesh.rotation.getValue(invalidTime) ).toBeUndefined(); const invalidArticulations = entity.model.articulations.getValue( invalidTime ); expect(invalidArticulations).toBeDefined(); expect(invalidArticulations["SampleArticulation Yaw"]).toBeUndefined(); expect(invalidArticulations["SampleArticulation Pitch"]).toBeUndefined(); expect(invalidArticulations["SampleArticulation Roll"]).toBeUndefined(); }); }); it("can load node transformations expressed as intervals", function() { const packet = { model: { interval: "2012-04-02T12:00:00Z/2012-04-02T13:00:00Z", nodeTransformations: [ { interval: "2012-04-02T12:00:00Z/2012-04-02T12:00:01Z", Mesh: { scale: { cartesian: [1, 2, 3] }, translation: { cartesian: [4, 5, 6] }, rotation: { unitQuaternion: [0, 0.7071, 0, 0] } } }, { interval: "2012-04-02T12:00:01Z/2012-04-02T12:00:02Z", Mesh: { scale: { cartesian: [10, 20, 30] }, translation: { cartesian: [40, 50, 60] }, rotation: { unitQuaternion: [0, 0, 0, 0.7071] } } } ] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.model).toBeDefined(); let time2 = import__55.JulianDate.fromIso8601("2012-04-02T12:00:00Z"); let nodeTransform = entity.model.nodeTransformations.getValue(time2).Mesh; expect(nodeTransform).toBeDefined(); expect(nodeTransform.scale).toEqual( import__55.Cartesian3.unpack( packet.model.nodeTransformations[0].Mesh.scale.cartesian ) ); expect(nodeTransform.translation).toEqual( import__55.Cartesian3.unpack( packet.model.nodeTransformations[0].Mesh.translation.cartesian ) ); let expectedRotation = import__55.Quaternion.unpack( packet.model.nodeTransformations[0].Mesh.rotation.unitQuaternion ); import__55.Quaternion.normalize(expectedRotation, expectedRotation); expect(nodeTransform.rotation).toEqual(expectedRotation); time2 = import__55.JulianDate.fromIso8601("2012-04-02T12:00:01Z"); nodeTransform = entity.model.nodeTransformations.getValue(time2).Mesh; expect(nodeTransform).toBeDefined(); expect(nodeTransform.scale).toEqual( import__55.Cartesian3.unpack( packet.model.nodeTransformations[1].Mesh.scale.cartesian ) ); expect(nodeTransform.translation).toEqual( import__55.Cartesian3.unpack( packet.model.nodeTransformations[1].Mesh.translation.cartesian ) ); expectedRotation = import__55.Quaternion.unpack( packet.model.nodeTransformations[1].Mesh.rotation.unitQuaternion ); import__55.Quaternion.normalize(expectedRotation, expectedRotation); expect(nodeTransform.rotation).toEqual(expectedRotation); }); }); it("can load articulations expressed as intervals", function() { const packet = { model: { interval: "2012-04-02T12:00:00Z/2012-04-02T13:00:00Z", articulations: [ { interval: "2012-04-02T12:00:00Z/2012-04-02T12:00:01Z", "SampleArticulation Yaw": 30, "SampleArticulation Pitch": 45, "SampleArticulation Roll": 60 }, { interval: "2012-04-02T12:00:01Z/2012-04-02T12:00:02Z", "SampleArticulation Yaw": 20, "SampleArticulation Pitch": 25, "SampleArticulation Roll": 30 } ] } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.model).toBeDefined(); let time2 = import__55.JulianDate.fromIso8601("2012-04-02T12:00:00Z"); let articulations = entity.model.articulations.getValue(time2); expect(articulations).toBeDefined(); expect(articulations["SampleArticulation Yaw"]).toEqual( packet.model.articulations[0]["SampleArticulation Yaw"] ); expect(articulations["SampleArticulation Pitch"]).toEqual( packet.model.articulations[0]["SampleArticulation Pitch"] ); expect(articulations["SampleArticulation Roll"]).toEqual( packet.model.articulations[0]["SampleArticulation Roll"] ); time2 = import__55.JulianDate.fromIso8601("2012-04-02T12:00:01Z"); articulations = entity.model.articulations.getValue(time2); expect(articulations).toBeDefined(); expect(articulations["SampleArticulation Yaw"]).toEqual( packet.model.articulations[1]["SampleArticulation Yaw"] ); expect(articulations["SampleArticulation Pitch"]).toEqual( packet.model.articulations[1]["SampleArticulation Pitch"] ); expect(articulations["SampleArticulation Roll"]).toEqual( packet.model.articulations[1]["SampleArticulation Roll"] ); }); }); it("can delete an existing object", function() { const dataSource = new import__55.CzmlDataSource(); return dataSource.load(makeDocument(staticCzml)).then(function(dataSource2) { expect(dataSource2.entities.values.length).toEqual(1); return dataSource2.load(makeDocument(czmlDelete)); }).then(function(dataSource2) { expect(dataSource2.entities.values.length).toEqual(0); }); }); it("loads parent", function() { const document2 = [ { id: "document", version: "1.0" }, { id: "parent" }, { id: "child", parent: "parent" } ]; return import__55.CzmlDataSource.load(document2).then(function(dataSource) { const parent = dataSource.entities.getById("parent"); expect(parent.parent).toBeUndefined(); const child = dataSource.entities.getById("child"); expect(child.parent).toBe(parent); }); }); it("loads parent specified out of order", function() { const document2 = [ { id: "document", version: "1.0" }, { id: "child", parent: "parent" }, { id: "child2", parent: "parent" }, { id: "grandparent" }, { id: "grandparent2" }, { id: "parent", parent: "grandparent" }, { id: "parent2", parent: "grandparent" } ]; return import__55.CzmlDataSource.load(document2).then(function(dataSource) { const grandparent = dataSource.entities.getById("grandparent"); expect(grandparent.parent).toBeUndefined(); const grandparent2 = dataSource.entities.getById("grandparent"); expect(grandparent2.parent).toBeUndefined(); const parent = dataSource.entities.getById("parent"); expect(parent.parent).toBe(grandparent); const parent2 = dataSource.entities.getById("parent2"); expect(parent2.parent).toBe(grandparent); const child = dataSource.entities.getById("child"); expect(child.parent).toBe(parent); const child2 = dataSource.entities.getById("child2"); expect(child2.parent).toBe(parent); }); }); it("can process JulianDate data in packets", function() { const date = import__55.JulianDate.fromIso8601("2000-01-01"); const object = {}; import__55.CzmlDataSource.processPacketData( import__55.JulianDate, object, "simpleDate", import__55.JulianDate.toIso8601(date) ); expect(object.simpleDate).toBeDefined(); expect(object.simpleDate.getValue()).toEqual(date); import__55.CzmlDataSource.processPacketData(import__55.JulianDate, object, "objDate", { date: import__55.JulianDate.toIso8601(date) }); expect(object.objDate).toBeDefined(); expect(object.objDate.getValue()).toEqual(date); }); it("can process array data in packets", function() { const packet = { array: [1, 2, 3, 4, 5] }; const object = {}; import__55.CzmlDataSource.processPacketData(Array, object, "arrayData", packet); expect(object.arrayData).toBeDefined(); expect(object.arrayData.getValue()).toEqual(packet.array); }); it("loading CZML suspends events.", function() { const document2 = [ { id: "document", version: "1.0" }, { point: { show: true, color: { rgbaf: [0.1, 0.1, 0.1, 0.1] } } }, { point: { show: false, color: { rgbaf: [0.1, 0.1, 0.1, 0.1] } } } ]; const spy = jasmine.createSpy("changedEvent"); const dataSource = new import__55.CzmlDataSource(); dataSource.entities.collectionChanged.addEventListener(spy); return dataSource.load(document2).then(function(dataSource2) { expect(spy.calls.count()).toEqual(1); }); }); function printInterval(startTime, stopTime) { return import__55.TimeInterval.toIso8601( new import__55.TimeInterval({ start: startTime, stop: stopTime }) ); } it("can load materials specified with composite interval", function() { const beforeTime = import__55.JulianDate.fromIso8601("2012-03-15T09:23:59Z"); const solidTime = import__55.JulianDate.fromIso8601("2012-03-15T10:00:00Z"); const gridTime1 = import__55.JulianDate.fromIso8601("2012-03-15T11:00:00Z"); const gridTime2 = import__55.JulianDate.fromIso8601("2012-03-15T12:00:00Z"); const afterTime = import__55.JulianDate.fromIso8601("2012-03-15T12:00:01Z"); const packet = { id: "obj", polygon: { material: [ { interval: printInterval(solidTime, gridTime1), solidColor: { color: { rgba: [240, 0, 0, 0] } } }, { interval: printInterval(gridTime1, gridTime2), grid: { color: { rgba: [240, 255, 255, 255] }, cellAlpha: 0, lineCount: { cartesian2: [36, 9] }, lineThickness: { cartesian2: [1, 1] }, lineOffset: { cartesian2: [0.5, 0.5] } } } ] } }; let secondPacket; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.getById("obj"); expect(entity.polygon.material).toBeInstanceOf( import__55.CompositeMaterialProperty ); expect(entity.polygon.material.getType(solidTime)).toEqual("Color"); expect(entity.polygon.material.getValue(solidTime).color).toEqual( import__55.Color.unpack( packet.polygon.material[0].solidColor.color.rgba.map( import__55.Color.byteToFloat ) ) ); function assertValuesForGridMaterial(time2) { expect(entity.polygon.material.getValue(time2).color).toEqual( import__55.Color.unpack( packet.polygon.material[1].grid.color.rgba.map(import__55.Color.byteToFloat) ) ); expect(entity.polygon.material.getValue(time2).cellAlpha).toEqual( packet.polygon.material[1].grid.cellAlpha ); expect(entity.polygon.material.getValue(time2).lineCount).toEqual( import__55.Cartesian2.unpack( packet.polygon.material[1].grid.lineCount.cartesian2 ) ); expect(entity.polygon.material.getValue(time2).lineThickness).toEqual( import__55.Cartesian2.unpack( packet.polygon.material[1].grid.lineThickness.cartesian2 ) ); expect(entity.polygon.material.getValue(time2).lineOffset).toEqual( import__55.Cartesian2.unpack( packet.polygon.material[1].grid.lineOffset.cartesian2 ) ); } expect(entity.polygon.material.getType(gridTime1)).toEqual("Grid"); assertValuesForGridMaterial(gridTime1); expect(entity.polygon.material.getType(gridTime2)).toEqual("Grid"); assertValuesForGridMaterial(gridTime2); expect(entity.polygon.material.getType(beforeTime)).toBeUndefined(); expect(entity.polygon.material.getType(afterTime)).toBeUndefined(); return dataSource; }).then(function(dataSource) { secondPacket = { id: "obj", polygon: { material: [ { interval: printInterval(solidTime, gridTime1), solidColor: { color: { rgba: [200, 100, 50, 255] } } } ] } }; return dataSource.process(secondPacket); }).then(function(dataSource) { const entity = dataSource.entities.getById("obj"); expect(entity.polygon.material).toBeInstanceOf( import__55.CompositeMaterialProperty ); expect(entity.polygon.material.getType(solidTime)).toEqual("Color"); expect(entity.polygon.material.getValue(solidTime).color).toEqual( import__55.Color.unpack( secondPacket.polygon.material[0].solidColor.color.rgba.map( import__55.Color.byteToFloat ) ) ); }); }); it("can load constant data for rectangle", function() { const packet = { rectangle: { material: { solidColor: { color: { rgbaf: [0.1, 0.2, 0.3, 0.4] } } }, coordinates: { wsen: [0, 1, 2, 3] }, height: 1, extrudedHeight: 2, granularity: 3, rotation: 4, stRotation: 5, show: true, outline: true, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 6, shadows: "ENABLED", zIndex: 6, classificationType: "TERRAIN" } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.rectangle).toBeDefined(); expect(entity.rectangle.coordinates.getValue(time2)).toEqual( import__55.Rectangle.unpack(packet.rectangle.coordinates.wsen) ); expect(entity.rectangle.material.getValue(time2).color).toEqual( import__55.Color.unpack(packet.rectangle.material.solidColor.color.rgbaf) ); expect(entity.rectangle.show.getValue(time2)).toEqual( packet.rectangle.show ); expect(entity.rectangle.height.getValue(time2)).toEqual( packet.rectangle.height ); expect(entity.rectangle.extrudedHeight.getValue(time2)).toEqual( packet.rectangle.extrudedHeight ); expect(entity.rectangle.granularity.getValue(time2)).toEqual( packet.rectangle.granularity ); expect(entity.rectangle.rotation.getValue(time2)).toEqual( packet.rectangle.rotation ); expect(entity.rectangle.stRotation.getValue(time2)).toEqual( packet.rectangle.stRotation ); expect(entity.rectangle.outline.getValue(time2)).toEqual( packet.rectangle.outline ); expect(entity.rectangle.outlineColor.getValue(time2)).toEqual( import__55.Color.unpack(packet.rectangle.outlineColor.rgbaf) ); expect(entity.rectangle.outlineWidth.getValue(time2)).toEqual( packet.rectangle.outlineWidth ); expect(entity.rectangle.shadows.getValue(time2)).toEqual( import__55.ShadowMode[packet.rectangle.shadows] ); expect(entity.rectangle.zIndex.getValue(time2)).toEqual( packet.rectangle.zIndex ); expect(entity.rectangle.classificationType.getValue(time2)).toEqual( import__55.ClassificationType[packet.rectangle.classificationType] ); }); }); it("can handle constant rectangle coordinates in degrees.", function() { const packet = { rectangle: { coordinates: { wsenDegrees: [0, 1, 2, 3] } } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.rectangle.coordinates.getValue(time2)).toEqual( import__55.Rectangle.fromDegrees(0, 1, 2, 3) ); }); }); it("can handle sampled rectangle coordinates.", function() { const epoch = import__55.JulianDate.now(); const packet = { rectangle: { coordinates: { epoch: import__55.JulianDate.toIso8601(epoch), wsen: [0, 1, 2, 3, 4, 1, 3, 4, 5, 6] } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.rectangle).toBeDefined(); const date1 = epoch; const date2 = import__55.JulianDate.addSeconds(epoch, 0.5, new import__55.JulianDate()); const date3 = import__55.JulianDate.addSeconds(epoch, 1, new import__55.JulianDate()); expect(entity.rectangle.coordinates.getValue(date1)).toEqual( new import__55.Rectangle(1, 2, 3, 4) ); expect(entity.rectangle.coordinates.getValue(date2)).toEqual( new import__55.Rectangle(2, 3, 4, 5) ); expect(entity.rectangle.coordinates.getValue(date3)).toEqual( new import__55.Rectangle(3, 4, 5, 6) ); }); }); it("can handle sampled rectangle coordinates in degrees.", function() { const epoch = import__55.JulianDate.now(); const packet = { rectangle: { coordinates: { epoch: import__55.JulianDate.toIso8601(epoch), wsenDegrees: [0, 1, 2, 3, 4, 1, 3, 4, 5, 6] } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.rectangle).toBeDefined(); const date1 = epoch; const date2 = import__55.JulianDate.addSeconds(epoch, 0.5, new import__55.JulianDate()); const date3 = import__55.JulianDate.addSeconds(epoch, 1, new import__55.JulianDate()); expect(entity.rectangle.coordinates.getValue(date1)).toEqual( import__55.Rectangle.fromDegrees(1, 2, 3, 4) ); expect(entity.rectangle.coordinates.getValue(date2)).toEqualEpsilon( import__55.Rectangle.fromDegrees(2, 3, 4, 5), import__55.Math.EPSILON15 ); expect(entity.rectangle.coordinates.getValue(date3)).toEqual( import__55.Rectangle.fromDegrees(3, 4, 5, 6) ); }); }); it("can load constant data for wall", function() { const packet = { wall: { material: { solidColor: { color: { rgbaf: [0.1, 0.2, 0.3, 0.4] } } }, granularity: 3, minimumHeights: { array: [1, 2, 3] }, maximumHeights: { array: [4, 5, 6] }, show: true, outline: true, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 6, shadows: "ENABLED" } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.wall).toBeDefined(); expect(entity.wall.material.getValue(time2).color).toEqual( import__55.Color.unpack(packet.wall.material.solidColor.color.rgbaf) ); expect(entity.wall.show.getValue(time2)).toEqual(packet.wall.show); expect(entity.wall.granularity.getValue(time2)).toEqual( packet.wall.granularity ); expect(entity.wall.minimumHeights.getValue(time2)).toEqual( packet.wall.minimumHeights.array ); expect(entity.wall.maximumHeights.getValue(time2)).toEqual( packet.wall.maximumHeights.array ); expect(entity.wall.outline.getValue(time2)).toEqual(packet.wall.outline); expect(entity.wall.outlineColor.getValue(time2)).toEqual( new import__55.Color(0.2, 0.2, 0.2, 0.2) ); expect(entity.wall.outlineWidth.getValue(time2)).toEqual( packet.wall.outlineWidth ); expect(entity.wall.shadows.getValue(time2)).toEqual( import__55.ShadowMode[packet.wall.shadows] ); }); }); it("can load data for wall with minimumHeights as references.", function() { const packets = [ { id: "document", version: "1.0" }, { id: "obj1", billboard: { scale: 1 } }, { id: "obj2", billboard: { scale: 4 } }, { id: "wall", wall: { minimumHeights: { references: ["obj1#billboard.scale", "obj2#billboard.scale"] }, maximumHeights: { references: ["obj2#billboard.scale", "obj1#billboard.scale"] } } } ]; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(packets).then(function(dataSource) { const entity = dataSource.entities.getById("wall"); expect(entity.wall).toBeDefined(); expect(entity.wall.minimumHeights.getValue(time2)).toEqual([ packets[1].billboard.scale, packets[2].billboard.scale ]); expect(entity.wall.maximumHeights.getValue(time2)).toEqual([ packets[2].billboard.scale, packets[1].billboard.scale ]); }); }); it("can load array of references expressed using intervals", function() { const packets = [ { id: "document", version: "1.0" }, { id: "obj1", billboard: { scale: 1 } }, { id: "obj2", billboard: { scale: 4 } }, { id: "obj3", billboard: { scale: 6 } }, { id: "wall", wall: { minimumHeights: [ { interval: "2010-01-01T00:00:00Z/2010-01-01T01:00:00Z", references: ["obj1#billboard.scale", "obj2#billboard.scale"] }, { interval: "2010-01-01T01:00:00Z/2010-01-01T02:00:00Z", references: ["obj2#billboard.scale", "obj3#billboard.scale"] } ] } } ]; return import__55.CzmlDataSource.load(packets).then(function(dataSource) { const entity = dataSource.entities.getById("wall"); expect(entity.wall).toBeDefined(); expect(entity.wall.minimumHeights).toBeInstanceOf(import__55.CompositeProperty); expect( entity.wall.minimumHeights.getValue( import__55.JulianDate.fromIso8601("2009-01-01T00:00:00Z") ) ).toBeUndefined(); expect( entity.wall.minimumHeights.getValue( import__55.JulianDate.fromIso8601("2010-01-01T00:00:00Z") ) ).toEqual([packets[1].billboard.scale, packets[2].billboard.scale]); expect( entity.wall.minimumHeights.getValue( import__55.JulianDate.fromIso8601("2010-01-01T01:00:00Z") ) ).toEqual([packets[2].billboard.scale, packets[3].billboard.scale]); }); }); it("can load constant data for box", function() { const packet = { box: { material: { solidColor: { color: { rgbaf: [0.1, 0.2, 0.3, 0.4] } } }, dimensions: { cartesian: [1, 2, 3] }, show: true, outline: true, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 6, shadows: "ENABLED" } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.box).toBeDefined(); expect(entity.box.dimensions.getValue(time2)).toEqual( import__55.Cartesian3.unpack(packet.box.dimensions.cartesian) ); expect(entity.box.material.getValue(time2).color).toEqual( import__55.Color.unpack(packet.box.material.solidColor.color.rgbaf) ); expect(entity.box.show.getValue(time2)).toEqual(packet.box.show); expect(entity.box.outline.getValue(time2)).toEqual(packet.box.outline); expect(entity.box.outlineColor.getValue(time2)).toEqual( import__55.Color.unpack(packet.box.outlineColor.rgbaf) ); expect(entity.box.outlineWidth.getValue(time2)).toEqual( packet.box.outlineWidth ); expect(entity.box.shadows.getValue(time2)).toEqual( import__55.ShadowMode[packet.box.shadows] ); }); }); it("can load constant data for cylinder", function() { const packet = { cylinder: { material: { solidColor: { color: { rgbaf: [0.1, 0.2, 0.3, 0.4] } } }, length: 5, topRadius: 6, bottomRadius: 7, show: true, outline: true, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 6, numberOfVerticalLines: 15, slices: 100, shadows: "ENABLED" } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.cylinder).toBeDefined(); expect(entity.cylinder.length.getValue(time2)).toEqual( packet.cylinder.length ); expect(entity.cylinder.topRadius.getValue(time2)).toEqual( packet.cylinder.topRadius ); expect(entity.cylinder.bottomRadius.getValue(time2)).toEqual( packet.cylinder.bottomRadius ); expect(entity.cylinder.material.getValue(time2).color).toEqual( import__55.Color.unpack(packet.cylinder.material.solidColor.color.rgbaf) ); expect(entity.cylinder.show.getValue(time2)).toEqual(packet.cylinder.show); expect(entity.cylinder.outline.getValue(time2)).toEqual( packet.cylinder.outline ); expect(entity.cylinder.outlineColor.getValue(time2)).toEqual( import__55.Color.unpack(packet.cylinder.outlineColor.rgbaf) ); expect(entity.cylinder.outlineWidth.getValue(time2)).toEqual( packet.cylinder.outlineWidth ); expect(entity.cylinder.numberOfVerticalLines.getValue(time2)).toEqual( packet.cylinder.numberOfVerticalLines ); expect(entity.cylinder.slices.getValue(time2)).toEqual( packet.cylinder.slices ); expect(entity.cylinder.shadows.getValue(time2)).toEqual( import__55.ShadowMode[packet.cylinder.shadows] ); }); }); it("can load constant data for corridor", function() { const packet = { corridor: { material: { solidColor: { color: { rgbaf: [0.1, 0.2, 0.3, 0.4] } } }, positions: { cartesian: [1, 2, 3, 5, 6, 7] }, cornerType: "MITERED", extrudedHeight: 2, granularity: 3, height: 4, width: 9, show: true, outline: true, outlineColor: { rgbaf: [0.2, 0.2, 0.2, 0.2] }, outlineWidth: 6, shadows: "ENABLED", zIndex: 5, classificationType: "TERRAIN" } }; const time2 = import__55.Iso8601.MINIMUM_VALUE; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.corridor).toBeDefined(); expect(entity.corridor.positions.getValue(time2)).toEqual( import__55.Cartesian3.unpackArray(packet.corridor.positions.cartesian) ); expect(entity.corridor.material.getValue(time2).color).toEqual( import__55.Color.unpack(packet.corridor.material.solidColor.color.rgbaf) ); expect(entity.corridor.show.getValue(time2)).toEqual(packet.corridor.show); expect(entity.corridor.height.getValue(time2)).toEqual( packet.corridor.height ); expect(entity.corridor.width.getValue(time2)).toEqual( packet.corridor.width ); expect(entity.corridor.cornerType.getValue(time2)).toEqual( import__55.CornerType[packet.corridor.cornerType] ); expect(entity.corridor.extrudedHeight.getValue(time2)).toEqual( packet.corridor.extrudedHeight ); expect(entity.corridor.granularity.getValue(time2)).toEqual( packet.corridor.granularity ); expect(entity.corridor.outline.getValue(time2)).toEqual( packet.corridor.outline ); expect(entity.corridor.outlineColor.getValue(time2)).toEqual( import__55.Color.unpack(packet.corridor.outlineColor.rgbaf) ); expect(entity.corridor.outlineWidth.getValue(time2)).toEqual( packet.corridor.outlineWidth ); expect(entity.corridor.shadows.getValue(time2)).toEqual( import__55.ShadowMode[packet.corridor.shadows] ); expect(entity.corridor.zIndex.getValue(time2)).toEqual( packet.corridor.zIndex ); expect(entity.corridor.classificationType.getValue(time2)).toEqual( import__55.ClassificationType[packet.corridor.classificationType] ); }); }); it("has entity collection with link to data source", function() { return import__55.CzmlDataSource.load(nameCzml).then(function(dataSource) { expect(dataSource.entities.owner).toEqual(dataSource); }); }); it("has entity with link to entity collection", function() { return import__55.CzmlDataSource.load(makeDocument(staticCzml)).then(function(dataSource) { const entities = dataSource.entities; expect(entities.values[0].entityCollection).toEqual(entities); }); }); it("can use constant reference properties", function() { const time2 = import__55.JulianDate.now(); const packets = [ { id: "document", version: "1.0" }, { id: "targetId", point: { pixelSize: 1 } }, { id: "referenceId", point: { pixelSize: { reference: "targetId#point.pixelSize" } } } ]; return import__55.CzmlDataSource.load(packets).then(function(dataSource) { const targetEntity = dataSource.entities.getById("targetId"); const referenceObject = dataSource.entities.getById("referenceId"); expect(referenceObject.point.pixelSize).toBeInstanceOf(import__55.ReferenceProperty); expect(targetEntity.point.pixelSize.getValue(time2)).toEqual( referenceObject.point.pixelSize.getValue(time2) ); }); }); it("can use interval reference properties", function() { const packets = [ { id: "document", version: "1.0" }, { id: "targetId", point: { pixelSize: 1 } }, { id: "targetId2", point: { pixelSize: 2 } }, { id: "referenceId", point: { pixelSize: [ { interval: "2012/2013", reference: "targetId#point.pixelSize" }, { interval: "2013/2014", reference: "targetId2#point.pixelSize" } ] } } ]; const time1 = import__55.JulianDate.fromIso8601("2012"); const time2 = import__55.JulianDate.fromIso8601("2014"); return import__55.CzmlDataSource.load(packets).then(function(dataSource) { const targetEntity = dataSource.entities.getById("targetId"); const targetEntity2 = dataSource.entities.getById("targetId2"); const referenceObject = dataSource.entities.getById("referenceId"); expect(targetEntity.point.pixelSize.getValue(time1)).toEqual( referenceObject.point.pixelSize.getValue(time1) ); expect(targetEntity2.point.pixelSize.getValue(time2)).toEqual( referenceObject.point.pixelSize.getValue(time2) ); }); }); it("can use constant reference properties for position", function() { const time2 = import__55.JulianDate.now(); const packets = [ { id: "document", version: "1.0" }, { id: "targetId", position: { cartesian: [1, 2, 3] } }, { id: "referenceId", position: { reference: "targetId#position" } } ]; return import__55.CzmlDataSource.load(packets).then(function(dataSource) { const targetEntity = dataSource.entities.getById("targetId"); const referenceObject = dataSource.entities.getById("referenceId"); expect(referenceObject.position).toBeInstanceOf(import__55.ReferenceProperty); expect(targetEntity.position.getValue(time2)).toEqual( referenceObject.position.getValue(time2) ); }); }); it("can use interval reference properties for positions", function() { const packets = [ { id: "document", version: "1.0" }, { id: "targetId", position: { cartesian: [1, 2, 3] } }, { id: "targetId2", position: { cartesian: [4, 5, 6] } }, { id: "referenceId", position: [ { interval: "2012/2013", reference: "targetId#position" }, { interval: "2013/2014", reference: "targetId2#position" } ] } ]; const time1 = import__55.JulianDate.fromIso8601("2012"); const time2 = import__55.JulianDate.fromIso8601("2014"); return import__55.CzmlDataSource.load(packets).then(function(dataSource) { const targetEntity = dataSource.entities.getById("targetId"); const targetEntity2 = dataSource.entities.getById("targetId2"); const referenceObject = dataSource.entities.getById("referenceId"); expect(targetEntity.position.getValue(time1)).toEqual( referenceObject.position.getValue(time1) ); expect(targetEntity2.position.getValue(time2)).toEqual( referenceObject.position.getValue(time2) ); }); }); it("can reference properties before they exist.", function() { const time2 = import__55.JulianDate.now(); const packets = [ { id: "document", version: "1.0" }, { id: "referenceId", point: { pixelSize: { reference: "targetId#point.pixelSize" } } }, { id: "targetId", point: { pixelSize: 1 } } ]; return import__55.CzmlDataSource.load(packets).then(function(dataSource) { const targetEntity = dataSource.entities.getById("targetId"); const referenceObject = dataSource.entities.getById("referenceId"); expect(referenceObject.point.pixelSize).toBeInstanceOf(import__55.ReferenceProperty); expect(targetEntity.point.pixelSize.getValue(time2)).toEqual( referenceObject.point.pixelSize.getValue(time2) ); }); }); it("can reference local properties.", function() { const time2 = import__55.JulianDate.now(); const packet = { id: "testObject", point: { pixelSize: 1, outlineWidth: { reference: "#point.pixelSize" } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const targetEntity = dataSource.entities.getById("testObject"); expect(targetEntity.point.outlineWidth).toBeInstanceOf(import__55.ReferenceProperty); expect(targetEntity.point.outlineWidth.getValue(time2)).toEqual( targetEntity.point.pixelSize.getValue(time2) ); }); }); it("can load a polyline with polyline glow material", function() { const packet = { id: "polylineGlow", polyline: { material: { polylineGlow: { color: { rgbaf: [0.1, 0.2, 0.3, 0.4] }, glowPower: 0.75, taperPower: 0.55 } } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.getById("polylineGlow"); expect(entity.polyline.material.color.getValue()).toEqual( import__55.Color.unpack(packet.polyline.material.polylineGlow.color.rgbaf) ); expect(entity.polyline.material.glowPower.getValue()).toEqual( packet.polyline.material.polylineGlow.glowPower ); expect(entity.polyline.material.taperPower.getValue()).toEqual( packet.polyline.material.polylineGlow.taperPower ); }); }); it("can load a polyline with polyline arrow material", function() { const packet = { id: "polylineArrow", polyline: { material: { polylineArrow: { color: { rgbaf: [0.1, 0.2, 0.3, 0.4] } } } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.getById("polylineArrow"); expect(entity.polyline.material.color.getValue()).toEqual( import__55.Color.unpack(packet.polyline.material.polylineArrow.color.rgbaf) ); }); }); it("can load a polyline with polyline dash material", function() { const packet = { id: "polylineDash", polyline: { material: { polylineDash: { color: { rgbaf: [0.1, 0.2, 0.3, 0.4] }, dashLength: 16, dashPattern: 7 } } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.getById("polylineDash"); expect(entity.polyline.material.color.getValue()).toEqual( import__55.Color.unpack(packet.polyline.material.polylineDash.color.rgbaf) ); expect(entity.polyline.material.dashLength.getValue()).toEqual( packet.polyline.material.polylineDash.dashLength ); expect(entity.polyline.material.dashPattern.getValue()).toEqual( packet.polyline.material.polylineDash.dashPattern ); }); }); it("loads extrapolation options", function() { const packet = { id: "point", position: { forwardExtrapolationType: "HOLD", forwardExtrapolationDuration: 2, backwardExtrapolationType: "NONE", backwardExtrapolationDuration: 1, cartesian: ["2012", 0, 0, 0] }, point: { color: { forwardExtrapolationType: "NONE", forwardExtrapolationDuration: 1, backwardExtrapolationType: "HOLD", backwardExtrapolationDuration: 2, rgbaf: ["2012", 0.1, 0.2, 0.3, 0.4] } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.getById("point"); const color = entity.point.color; expect(color.forwardExtrapolationType).toEqual( import__55.ExtrapolationType[packet.point.color.forwardExtrapolationType] ); expect(color.forwardExtrapolationDuration).toEqual( packet.point.color.forwardExtrapolationDuration ); expect(color.backwardExtrapolationType).toEqual( import__55.ExtrapolationType[packet.point.color.backwardExtrapolationType] ); expect(color.backwardExtrapolationDuration).toEqual( packet.point.color.backwardExtrapolationDuration ); const position = entity.position; expect(position.forwardExtrapolationType).toEqual( import__55.ExtrapolationType[packet.position.forwardExtrapolationType] ); expect(position.forwardExtrapolationDuration).toEqual( packet.position.forwardExtrapolationDuration ); expect(position.backwardExtrapolationType).toEqual( import__55.ExtrapolationType[packet.position.backwardExtrapolationType] ); expect(position.backwardExtrapolationDuration).toEqual( packet.position.backwardExtrapolationDuration ); }); }); it("rejects if first document packet lacks version information", function() { return import__55.CzmlDataSource.load({ id: "document" }).then(function() { fail("should not be called"); }).catch(function(error) { expect(error).toBeInstanceOf(import__55.RuntimeError); expect(error.message).toEqual( "CZML version information invalid. It is expected to be a property on the document object in the . version format." ); }); }); it("rejects if first packet is not document", function() { return import__55.CzmlDataSource.load({ id: "someId" }).then(function() { fail("should not be called"); }).catch(function(error) { expect(error).toBeInstanceOf(import__55.RuntimeError); expect(error.message).toEqual( "The first CZML packet is required to be the document object." ); }); }); it("rejects if document packet contains bad version", function() { return import__55.CzmlDataSource.load({ id: "document" }).then(function() { fail("should not be called"); }).catch(function(error) { expect(error).toBeInstanceOf(import__55.RuntimeError); expect(error.message).toContain( "CZML version information invalid. It is expected to be a property on the document object in the . version format." ); }); }); it("ignores color values not expressed as a known type", function() { const packet = { billboard: { color: { invalidType: "someValue" } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.billboard).toBeDefined(); expect(entity.billboard.color).toBeUndefined(); }); }); it("ignores rectangle values not expressed as a known type", function() { const packet = { rectangle: { coordinates: { invalidType: "someValue" } } }; return import__55.CzmlDataSource.load(makeDocument(packet)).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.rectangle).toBeDefined(); expect(entity.rectangle.coordinates).toBeUndefined(); }); }); it("converts followSurface to arcType for backwards compatibility", function() { const packets = [ { id: "document", version: "1.0" }, { id: "followSurface-false", polyline: { followSurface: false } }, { id: "followSurface-true", polyline: { followSurface: true } }, { id: "followSurface-time-varying", polyline: { followSurface: [ { interval: "2013-01-01T00:00:00Z/2013-01-01T01:00:00Z", boolean: true }, { interval: "2013-01-01T01:00:00Z/2013-01-01T02:00:00Z", boolean: false } ] } }, { id: "arcType-overrides-followSurface", polyline: { followSurface: true, arcType: "RHUMB" } } ]; return import__55.CzmlDataSource.load(packets).then(function(dataSource) { const date = import__55.JulianDate.now(); let entity = dataSource.entities.getById("followSurface-false"); expect(entity.polyline.arcType.isConstant).toEqual(true); expect(entity.polyline.arcType.getValue(date)).toEqual(import__55.ArcType.NONE); entity = dataSource.entities.getById("followSurface-true"); expect(entity.polyline.arcType.isConstant).toEqual(true); expect(entity.polyline.arcType.getValue(date)).toEqual(import__55.ArcType.GEODESIC); entity = dataSource.entities.getById("followSurface-time-varying"); expect(entity.polyline.arcType.isConstant).toEqual(false); expect( entity.polyline.arcType.getValue( import__55.JulianDate.fromIso8601("2013-01-01T00:00:00Z") ) ).toEqual(import__55.ArcType.GEODESIC); expect( entity.polyline.arcType.getValue( import__55.JulianDate.fromIso8601("2013-01-01T01:00:00Z") ) ).toEqual(import__55.ArcType.NONE); entity = dataSource.entities.getById("arcType-overrides-followSurface"); expect(entity.polyline.arcType.isConstant).toEqual(true); expect(entity.polyline.arcType.getValue(date)).toEqual(import__55.ArcType.RHUMB); }); }); it("checks validation document", function() { return import__55.CzmlDataSource.load("Data/CZML/ValidationDocument.czml").then(function(dataSource) { let e; const documentStartDate = import__55.JulianDate.fromIso8601("2016-06-17T12:00:00Z"); const documentStopDate = import__55.JulianDate.fromIso8601("2016-06-17T13:00:00Z"); expect(dataSource.clock.startTime).toEqual(documentStartDate); expect(dataSource.clock.stopTime).toEqual(documentStopDate); expect(dataSource.clock.currentTime).toEqual(documentStartDate); expect(dataSource.clock.multiplier).toEqual(1); expect(dataSource.clock.clockRange).toEqual(import__55.ClockRange.UNBOUNDED); expect(dataSource.clock.clockStep).toEqual(import__55.ClockStep.SYSTEM_CLOCK_MULTIPLIER); const constant = e = dataSource.entities.getById("Constant"); expect(e).toBeDefined(); const date = import__55.JulianDate.now(); expect(e.description.getValue(date)).toEqual("string31449"); expect(e.position.getValue(date)).toEqual(new import__55.Cartesian3(24944, 16481, 24896)); expect(e.orientation.getValue(date)).toEqualEpsilon(new import__55.Quaternion(0.431493311977589, 0.560811914509339, 0.423522822587574, 0.565625261998114), 1e-14); expect(e.viewFrom.getValue(date)).toEqual(new import__55.Cartesian3(17794, 13381, 18228)); expect(e.billboard.show.getValue(date)).toEqual(true); expect(e.billboard.image.getValue(date).url).toEqual("http://example.com/3792"); expect(e.billboard.scale.getValue(date)).toEqual(27514); expect(e.billboard.pixelOffset.getValue(date)).toEqual(new import__55.Cartesian2(16996, 51010)); expect(e.billboard.eyeOffset.getValue(date)).toEqual(new import__55.Cartesian3(64633, 11516, 17196)); expect(e.billboard.horizontalOrigin.getValue(date)).toEqual(import__55.HorizontalOrigin.LEFT); expect(e.billboard.verticalOrigin.getValue(date)).toEqual(import__55.VerticalOrigin.BOTTOM); expect(e.billboard.heightReference.getValue(date)).toEqual(import__55.HeightReference.CLAMP_TO_GROUND); expect(e.billboard.color.getValue(date)).toEqual(import__55.Color.fromBytes(87, 118, 167, 140)); expect(e.billboard.rotation.getValue(date)).toEqual(57379); expect(e.billboard.alignedAxis.getValue(date)).toEqualEpsilon(new import__55.Cartesian3(0.205062091895724, 0.975768213485699, 0.0763277932228903), 1e-14); expect(e.billboard.sizeInMeters.getValue(date)).toEqual(true); expect(e.billboard.width.getValue(date)).toEqual(25197); expect(e.billboard.height.getValue(date)).toEqual(53328); expect(e.billboard.scaleByDistance.getValue(date)).toEqual(new import__55.NearFarScalar(59318, 31207, 63353, 55287)); expect(e.billboard.translucencyByDistance.getValue(date)).toEqual(new import__55.NearFarScalar(43707, 31146, 12921, 57138)); expect(e.billboard.pixelOffsetScaleByDistance.getValue(date)).toEqual(new import__55.NearFarScalar(11873, 40494, 29598, 27507)); expect(e.billboard.imageSubRegion.getValue(date)).toEqual(new import__55.BoundingRectangle(62620, 63220, 23030, 63321)); expect(e.billboard.distanceDisplayCondition.getValue(date)).toEqual(new import__55.DistanceDisplayCondition(22843, 27481)); expect(e.billboard.disableDepthTestDistance.getValue(date)).toEqual(39764); expect(e.box.show.getValue(date)).toEqual(true); expect(e.box.dimensions.getValue(date)).toEqual(new import__55.Cartesian3(57494, 62432, 42995)); expect(e.box.heightReference.getValue(date)).toEqual(import__55.HeightReference.CLAMP_TO_GROUND); expect(e.box.fill.getValue(date)).toEqual(true); expect(e.box.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(88, 226, 91, 144)); expect(e.box.outline.getValue(date)).toEqual(true); expect(e.box.outlineColor.getValue(date)).toEqual(import__55.Color.fromBytes(121, 42, 244, 168)); expect(e.box.outlineWidth.getValue(date)).toEqual(15323); expect(e.box.shadows.getValue(date)).toEqual(import__55.ShadowMode.CAST_ONLY); expect(e.box.distanceDisplayCondition.getValue(date)).toEqual(new import__55.DistanceDisplayCondition(3775, 49016)); expect(e.corridor.show.getValue(date)).toEqual(true); expect(e.corridor.positions.getValue(date)).toEqual([new import__55.Cartesian3(36415, 2702, 36618), new import__55.Cartesian3(47759, 11706, 63277)]); expect(e.corridor.width.getValue(date)).toEqual(20413); expect(e.corridor.height.getValue(date)).toEqual(8062); expect(e.corridor.heightReference.getValue(date)).toEqual(import__55.HeightReference.CLAMP_TO_GROUND); expect(e.corridor.extrudedHeight.getValue(date)).toEqual(22846); expect(e.corridor.extrudedHeightReference.getValue(date)).toEqual(import__55.HeightReference.CLAMP_TO_GROUND); expect(e.corridor.cornerType.getValue(date)).toEqual(import__55.CornerType.BEVELED); expect(e.corridor.granularity.getValue(date)).toEqual(44105); expect(e.corridor.fill.getValue(date)).toEqual(true); expect(e.corridor.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(230, 252, 22, 236)); expect(e.corridor.outline.getValue(date)).toEqual(true); expect(e.corridor.outlineColor.getValue(date)).toEqual(import__55.Color.fromBytes(198, 25, 134, 60)); expect(e.corridor.outlineWidth.getValue(date)).toEqual(9132); expect(e.corridor.shadows.getValue(date)).toEqual(import__55.ShadowMode.CAST_ONLY); expect(e.corridor.distanceDisplayCondition.getValue(date)).toEqual(new import__55.DistanceDisplayCondition(15797, 46507)); expect(e.corridor.classificationType.getValue(date)).toEqual(import__55.ClassificationType.TERRAIN); expect(e.corridor.zIndex.getValue(date)).toEqual(59315); expect(e.cylinder.show.getValue(date)).toEqual(true); expect(e.cylinder.length.getValue(date)).toEqual(33298); expect(e.cylinder.topRadius.getValue(date)).toEqual(16245); expect(e.cylinder.bottomRadius.getValue(date)).toEqual(59378); expect(e.cylinder.heightReference.getValue(date)).toEqual(import__55.HeightReference.CLAMP_TO_GROUND); expect(e.cylinder.fill.getValue(date)).toEqual(true); expect(e.cylinder.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(216, 68, 53, 64)); expect(e.cylinder.outline.getValue(date)).toEqual(true); expect(e.cylinder.outlineColor.getValue(date)).toEqual(import__55.Color.fromBytes(4, 90, 209, 96)); expect(e.cylinder.outlineWidth.getValue(date)).toEqual(64018); expect(e.cylinder.numberOfVerticalLines.getValue(date)).toEqual(38567); expect(e.cylinder.slices.getValue(date)).toEqual(39979); expect(e.cylinder.shadows.getValue(date)).toEqual(import__55.ShadowMode.CAST_ONLY); expect(e.cylinder.distanceDisplayCondition.getValue(date)).toEqual(new import__55.DistanceDisplayCondition(43860, 52395)); expect(e.ellipse.show.getValue(date)).toEqual(true); expect(e.ellipse.semiMajorAxis.getValue(date)).toEqual(60072); expect(e.ellipse.semiMinorAxis.getValue(date)).toEqual(38653); expect(e.ellipse.height.getValue(date)).toEqual(15549); expect(e.ellipse.heightReference.getValue(date)).toEqual(import__55.HeightReference.CLAMP_TO_GROUND); expect(e.ellipse.extrudedHeight.getValue(date)).toEqual(55640); expect(e.ellipse.extrudedHeightReference.getValue(date)).toEqual(import__55.HeightReference.CLAMP_TO_GROUND); expect(e.ellipse.rotation.getValue(date)).toEqual(27722); expect(e.ellipse.stRotation.getValue(date)).toEqual(4692); expect(e.ellipse.granularity.getValue(date)).toEqual(62192); expect(e.ellipse.fill.getValue(date)).toEqual(true); expect(e.ellipse.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(116, 186, 200, 40)); expect(e.ellipse.outline.getValue(date)).toEqual(true); expect(e.ellipse.outlineColor.getValue(date)).toEqual(import__55.Color.fromBytes(160, 82, 145, 104)); expect(e.ellipse.outlineWidth.getValue(date)).toEqual(8839); expect(e.ellipse.numberOfVerticalLines.getValue(date)).toEqual(38878); expect(e.ellipse.shadows.getValue(date)).toEqual(import__55.ShadowMode.CAST_ONLY); expect(e.ellipse.distanceDisplayCondition.getValue(date)).toEqual(new import__55.DistanceDisplayCondition(27813, 30828)); expect(e.ellipse.classificationType.getValue(date)).toEqual(import__55.ClassificationType.TERRAIN); expect(e.ellipse.zIndex.getValue(date)).toEqual(3341); expect(e.ellipsoid.show.getValue(date)).toEqual(true); expect(e.ellipsoid.radii.getValue(date)).toEqual(new import__55.Cartesian3(15638, 24381, 37983)); expect(e.ellipsoid.innerRadii.getValue(date)).toEqual(new import__55.Cartesian3(21988, 44373, 36013)); expect(e.ellipsoid.minimumClock.getValue(date)).toEqual(57589); expect(e.ellipsoid.maximumClock.getValue(date)).toEqual(24940); expect(e.ellipsoid.minimumCone.getValue(date)).toEqual(54533); expect(e.ellipsoid.maximumCone.getValue(date)).toEqual(64532); expect(e.ellipsoid.heightReference.getValue(date)).toEqual(import__55.HeightReference.CLAMP_TO_GROUND); expect(e.ellipsoid.fill.getValue(date)).toEqual(true); expect(e.ellipsoid.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(202, 67, 110, 69)); expect(e.ellipsoid.outline.getValue(date)).toEqual(true); expect(e.ellipsoid.outlineColor.getValue(date)).toEqual(import__55.Color.fromBytes(55, 23, 226, 7)); expect(e.ellipsoid.outlineWidth.getValue(date)).toEqual(47507); expect(e.ellipsoid.stackPartitions.getValue(date)).toEqual(54278); expect(e.ellipsoid.slicePartitions.getValue(date)).toEqual(28562); expect(e.ellipsoid.subdivisions.getValue(date)).toEqual(14008); expect(e.ellipsoid.shadows.getValue(date)).toEqual(import__55.ShadowMode.CAST_ONLY); expect(e.ellipsoid.distanceDisplayCondition.getValue(date)).toEqual(new import__55.DistanceDisplayCondition(3293, 56793)); expect(e.label.show.getValue(date)).toEqual(true); expect(e.label.text.getValue(date)).toEqual("string36641"); expect(e.label.font.getValue(date)).toEqual("14px sans-serif"); expect(e.label.style.getValue(date)).toEqual(import__55.LabelStyle.FILL_AND_OUTLINE); expect(e.label.scale.getValue(date)).toEqual(6510); expect(e.label.showBackground.getValue(date)).toEqual(true); expect(e.label.backgroundColor.getValue(date)).toEqual(import__55.Color.fromBytes(225, 114, 54, 128)); expect(e.label.backgroundPadding.getValue(date)).toEqual(new import__55.Cartesian2(5508, 56341)); expect(e.label.pixelOffset.getValue(date)).toEqual(new import__55.Cartesian2(25913, 30821)); expect(e.label.eyeOffset.getValue(date)).toEqual(new import__55.Cartesian3(30502, 29047, 25457)); expect(e.label.horizontalOrigin.getValue(date)).toEqual(import__55.HorizontalOrigin.LEFT); expect(e.label.verticalOrigin.getValue(date)).toEqual(import__55.VerticalOrigin.BOTTOM); expect(e.label.heightReference.getValue(date)).toEqual(import__55.HeightReference.CLAMP_TO_GROUND); expect(e.label.fillColor.getValue(date)).toEqual(import__55.Color.fromBytes(88, 197, 147, 137)); expect(e.label.outlineColor.getValue(date)).toEqual(import__55.Color.fromBytes(171, 128, 159, 223)); expect(e.label.outlineWidth.getValue(date)).toEqual(36637); expect(e.label.translucencyByDistance.getValue(date)).toEqual(new import__55.NearFarScalar(34067, 16517, 11328, 13612)); expect(e.label.pixelOffsetScaleByDistance.getValue(date)).toEqual(new import__55.NearFarScalar(21220, 35154, 33161, 36737)); expect(e.label.scaleByDistance.getValue(date)).toEqual(new import__55.NearFarScalar(7350, 32796, 1408, 55045)); expect(e.label.distanceDisplayCondition.getValue(date)).toEqual(new import__55.DistanceDisplayCondition(5204, 21012)); expect(e.label.disableDepthTestDistance.getValue(date)).toEqual(17959); expect(e.model.show.getValue(date)).toEqual(true); expect(e.model.uri.getValue(date).url).toEqual("http://example.com/60043"); expect(e.model.scale.getValue(date)).toEqual(44278); expect(e.model.minimumPixelSize.getValue(date)).toEqual(35888); expect(e.model.maximumScale.getValue(date)).toEqual(64305); expect(e.model.incrementallyLoadTextures.getValue(date)).toEqual(true); expect(e.model.runAnimations.getValue(date)).toEqual(true); expect(e.model.shadows.getValue(date)).toEqual(import__55.ShadowMode.CAST_ONLY); expect(e.model.heightReference.getValue(date)).toEqual(import__55.HeightReference.CLAMP_TO_GROUND); expect(e.model.silhouetteColor.getValue(date)).toEqual(import__55.Color.fromBytes(29, 61, 52, 101)); expect(e.model.silhouetteSize.getValue(date)).toEqual(4645); expect(e.model.color.getValue(date)).toEqual(import__55.Color.fromBytes(0, 52, 75, 73)); expect(e.model.colorBlendMode.getValue(date)).toEqual(import__55.ColorBlendMode.REPLACE); expect(e.model.colorBlendAmount.getValue(date)).toEqual(7475); expect(e.model.distanceDisplayCondition.getValue(date)).toEqual(new import__55.DistanceDisplayCondition(31861, 62844)); expect(e.model.nodeTransformations.prop.translation.getValue(date)).toEqual(new import__55.Cartesian3(18548, 48456, 21181)); expect(e.model.nodeTransformations.prop.rotation.getValue(date)).toEqualEpsilon(new import__55.Quaternion(0.527960606328925, 0.567156704919186, 0.624812964569899, 0.0959146992664751), 1e-14); expect(e.model.nodeTransformations.prop.scale.getValue(date)).toEqual(new import__55.Cartesian3(53739, 37841, 41107)); expect(e.model.articulations.prop.getValue(date)).toEqual(25496); expect(e.path.show.getValue(date)).toEqual(true); expect(e.path.leadTime.getValue(date)).toEqual(5997); expect(e.path.trailTime.getValue(date)).toEqual(52915); expect(e.path.width.getValue(date)).toEqual(56040); expect(e.path.resolution.getValue(date)).toEqual(31563); expect(e.path.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(10, 78, 168, 13)); expect(e.path.distanceDisplayCondition.getValue(date)).toEqual(new import__55.DistanceDisplayCondition(11646, 32422)); expect(e.point.show.getValue(date)).toEqual(true); expect(e.point.pixelSize.getValue(date)).toEqual(53869); expect(e.point.heightReference.getValue(date)).toEqual(import__55.HeightReference.CLAMP_TO_GROUND); expect(e.point.color.getValue(date)).toEqual(import__55.Color.fromBytes(3, 147, 219, 77)); expect(e.point.outlineColor.getValue(date)).toEqual(import__55.Color.fromBytes(254, 106, 11, 94)); expect(e.point.outlineWidth.getValue(date)).toEqual(27922); expect(e.point.scaleByDistance.getValue(date)).toEqual(new import__55.NearFarScalar(20128, 16462, 49728, 18882)); expect(e.point.translucencyByDistance.getValue(date)).toEqual(new import__55.NearFarScalar(52796, 43982, 61099, 50158)); expect(e.point.distanceDisplayCondition.getValue(date)).toEqual(new import__55.DistanceDisplayCondition(29646, 52915)); expect(e.point.disableDepthTestDistance.getValue(date)).toEqual(9675); expect(e.polygon.show.getValue(date)).toEqual(true); expect(e.polygon.hierarchy.getValue(date).positions).toEqual([new import__55.Cartesian3(39143, 2200, 6408), new import__55.Cartesian3(27161, 33386, 62338)]); expect(e.polygon.hierarchy.getValue(date).holes).toEqual([new import__55.PolygonHierarchy([new import__55.Cartesian3(47462, 20409, 3151), new import__55.Cartesian3(58636, 39653, 53914), new import__55.Cartesian3(31954, 4988, 47462)]), new import__55.PolygonHierarchy([new import__55.Cartesian3(20409, 3151, 58636), new import__55.Cartesian3(39653, 53914, 31954), new import__55.Cartesian3(4988, 47462, 20409), new import__55.Cartesian3(3151, 58636, 39653)])]); expect(e.polygon.arcType.getValue(date)).toEqual(import__55.ArcType.RHUMB); expect(e.polygon.height.getValue(date)).toEqual(26391); expect(e.polygon.heightReference.getValue(date)).toEqual(import__55.HeightReference.CLAMP_TO_GROUND); expect(e.polygon.extrudedHeight.getValue(date)).toEqual(15922); expect(e.polygon.extrudedHeightReference.getValue(date)).toEqual(import__55.HeightReference.CLAMP_TO_GROUND); expect(e.polygon.stRotation.getValue(date)).toEqual(2555); expect(e.polygon.granularity.getValue(date)).toEqual(17060); expect(e.polygon.fill.getValue(date)).toEqual(true); expect(e.polygon.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(216, 139, 124, 253)); expect(e.polygon.outline.getValue(date)).toEqual(true); expect(e.polygon.outlineColor.getValue(date)).toEqual(import__55.Color.fromBytes(172, 48, 134, 87)); expect(e.polygon.outlineWidth.getValue(date)).toEqual(62220); expect(e.polygon.perPositionHeight.getValue(date)).toEqual(true); expect(e.polygon.closeTop.getValue(date)).toEqual(true); expect(e.polygon.closeBottom.getValue(date)).toEqual(true); expect(e.polygon.shadows.getValue(date)).toEqual(import__55.ShadowMode.CAST_ONLY); expect(e.polygon.distanceDisplayCondition.getValue(date)).toEqual(new import__55.DistanceDisplayCondition(5989, 26104)); expect(e.polygon.classificationType.getValue(date)).toEqual(import__55.ClassificationType.TERRAIN); expect(e.polygon.zIndex.getValue(date)).toEqual(31269); expect(e.polyline.show.getValue(date)).toEqual(true); expect(e.polyline.positions.getValue(date)).toEqual([new import__55.Cartesian3(23333, 31067, 17529), new import__55.Cartesian3(57924, 41186, 31648)]); expect(e.polyline.arcType.getValue(date)).toEqual(import__55.ArcType.RHUMB); expect(e.polyline.width.getValue(date)).toEqual(14667); expect(e.polyline.granularity.getValue(date)).toEqual(53395); expect(e.polyline.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(88, 0, 232, 230)); expect(e.polyline.shadows.getValue(date)).toEqual(import__55.ShadowMode.CAST_ONLY); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqual(import__55.Color.fromBytes(197, 195, 115, 198)); expect(e.polyline.distanceDisplayCondition.getValue(date)).toEqual(new import__55.DistanceDisplayCondition(5807, 30486)); expect(e.polyline.clampToGround.getValue(date)).toEqual(true); expect(e.polyline.classificationType.getValue(date)).toEqual(import__55.ClassificationType.TERRAIN); expect(e.polyline.zIndex.getValue(date)).toEqual(17658); expect(e.polylineVolume.show.getValue(date)).toEqual(true); expect(e.polylineVolume.positions.getValue(date)).toEqual([new import__55.Cartesian3(62250, 34803, 52359), new import__55.Cartesian3(59852, 58857, 24549)]); expect(e.polylineVolume.shape.getValue(date)).toEqual([new import__55.Cartesian2(45301, 43952), new import__55.Cartesian2(34475, 28294)]); expect(e.polylineVolume.cornerType.getValue(date)).toEqual(import__55.CornerType.BEVELED); expect(e.polylineVolume.granularity.getValue(date)).toEqual(12007); expect(e.polylineVolume.fill.getValue(date)).toEqual(true); expect(e.polylineVolume.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(232, 0, 34, 154)); expect(e.polylineVolume.outline.getValue(date)).toEqual(true); expect(e.polylineVolume.outlineColor.getValue(date)).toEqual(import__55.Color.fromBytes(179, 137, 151, 42)); expect(e.polylineVolume.outlineWidth.getValue(date)).toEqual(23162); expect(e.polylineVolume.shadows.getValue(date)).toEqual(import__55.ShadowMode.CAST_ONLY); expect(e.polylineVolume.distanceDisplayCondition.getValue(date)).toEqual(new import__55.DistanceDisplayCondition(49375, 57097)); expect(e.rectangle.show.getValue(date)).toEqual(true); expect(e.rectangle.coordinates.getValue(date)).toEqual(new import__55.Rectangle(1.13325368272577, 0.703573207377445, 0.756676249095309, 0.339217858685931)); expect(e.rectangle.height.getValue(date)).toEqual(20608); expect(e.rectangle.heightReference.getValue(date)).toEqual(import__55.HeightReference.CLAMP_TO_GROUND); expect(e.rectangle.extrudedHeight.getValue(date)).toEqual(23002); expect(e.rectangle.extrudedHeightReference.getValue(date)).toEqual(import__55.HeightReference.CLAMP_TO_GROUND); expect(e.rectangle.rotation.getValue(date)).toEqual(54979); expect(e.rectangle.stRotation.getValue(date)).toEqual(8079); expect(e.rectangle.granularity.getValue(date)).toEqual(60343); expect(e.rectangle.fill.getValue(date)).toEqual(true); expect(e.rectangle.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(160, 249, 70, 249)); expect(e.rectangle.outline.getValue(date)).toEqual(true); expect(e.rectangle.outlineColor.getValue(date)).toEqual(import__55.Color.fromBytes(196, 59, 142, 36)); expect(e.rectangle.outlineWidth.getValue(date)).toEqual(59794); expect(e.rectangle.shadows.getValue(date)).toEqual(import__55.ShadowMode.CAST_ONLY); expect(e.rectangle.distanceDisplayCondition.getValue(date)).toEqual(new import__55.DistanceDisplayCondition(21388, 23379)); expect(e.rectangle.classificationType.getValue(date)).toEqual(import__55.ClassificationType.TERRAIN); expect(e.rectangle.zIndex.getValue(date)).toEqual(445); expect(e.tileset.show.getValue(date)).toEqual(true); expect(e.tileset.uri.getValue(date).url).toEqual("http://example.com/6864"); expect(e.tileset.maximumScreenSpaceError.getValue(date)).toEqual(51767); expect(e.wall.show.getValue(date)).toEqual(true); expect(e.wall.positions.getValue(date)).toEqual([new import__55.Cartesian3(21681, 40276, 30621), new import__55.Cartesian3(3959, 61967, 19442)]); expect(e.wall.minimumHeights.getValue(date)).toEqual([49466, 44737]); expect(e.wall.maximumHeights.getValue(date)).toEqual([59672, 62697]); expect(e.wall.granularity.getValue(date)).toEqual(47652); expect(e.wall.fill.getValue(date)).toEqual(true); expect(e.wall.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(64, 176, 190, 65)); expect(e.wall.outline.getValue(date)).toEqual(true); expect(e.wall.outlineColor.getValue(date)).toEqual(import__55.Color.fromBytes(107, 196, 96, 198)); expect(e.wall.outlineWidth.getValue(date)).toEqual(50458); expect(e.wall.shadows.getValue(date)).toEqual(import__55.ShadowMode.CAST_ONLY); expect(e.wall.distanceDisplayCondition.getValue(date)).toEqual(new import__55.DistanceDisplayCondition(27810, 41691)); expect(e = dataSource.entities.getById("constant_position_cartographicRadians")).toBeDefined(); expect(e.position.getValue(date)).toEqual(import__55.Cartesian3.fromRadians(0.368123392863751, 0.678098621973879, 32050)); expect(e = dataSource.entities.getById("constant_position_cartographicDegrees")).toBeDefined(); expect(e.position.getValue(date)).toEqual(import__55.Cartesian3.fromDegrees(14, 14, 24697)); expect(e = dataSource.entities.getById("constant_position_cartesianVelocity")).toBeDefined(); expect(e.position.getValue(date)).toEqual(new import__55.Cartesian3(15776, 23613, 14940)); expect(e = dataSource.entities.getById("constant_billboard_color_rgbaf")).toBeDefined(); expect(e.billboard.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.674509803921569, 0.866666666666667, 0.6, 0.650980392156863), 1e-14); expect(e = dataSource.entities.getById("constant_billboard_alignedAxis_unitSpherical")).toBeDefined(); expect(e.billboard.alignedAxis.getValue(date)).toEqualEpsilon(import__55.Cartesian3.fromSpherical(new import__55.Spherical(20514, 39760)), 1e-14); expect(e = dataSource.entities.getById("constant_box_material_solidColor_color")).toBeDefined(); expect(e.box.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.996078431372549, 0.0823529411764706, 0.494117647058824, 0.101960784313725), 1e-14); expect(e = dataSource.entities.getById("material_box_material_image")).toBeDefined(); expect(e.box.material.image.getValue(date).url).toEqual("http://example.com/50881"); expect(e.box.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(58955, 45286)); expect(e.box.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(98, 97, 133, 129)); expect(e.box.material.transparent.getValue(date)).toEqual(true); expect(e = dataSource.entities.getById("material_box_material_grid")).toBeDefined(); expect(e.box.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(178, 10, 106, 226)); expect(e.box.material.cellAlpha.getValue(date)).toEqual(47180); expect(e.box.material.lineCount.getValue(date)).toEqual(new import__55.Cartesian2(24659, 13408)); expect(e.box.material.lineThickness.getValue(date)).toEqual(new import__55.Cartesian2(13897, 25654)); expect(e.box.material.lineOffset.getValue(date)).toEqual(new import__55.Cartesian2(14153, 49207)); expect(e = dataSource.entities.getById("material_box_material_stripe")).toBeDefined(); expect(e.box.material.orientation.getValue(date)).toEqual(import__55.StripeOrientation.VERTICAL); expect(e.box.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(18, 147, 177, 80)); expect(e.box.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(189, 226, 187, 107)); expect(e.box.material.offset.getValue(date)).toEqual(43563); expect(e.box.material.repeat.getValue(date)).toEqual(24480); expect(e = dataSource.entities.getById("material_box_material_checkerboard")).toBeDefined(); expect(e.box.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(188, 19, 247, 166)); expect(e.box.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(70, 241, 211, 45)); expect(e.box.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(31491, 2427)); expect(e = dataSource.entities.getById("constant_box_material_image_color")).toBeDefined(); expect(e.box.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.733333333333333, 0.474509803921569, 0.56078431372549, 0.349019607843137), 1e-14); expect(e = dataSource.entities.getById("constant_box_material_grid_color")).toBeDefined(); expect(e.box.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.847058823529412, 0.392156862745098, 0.352941176470588, 0.898039215686275), 1e-14); expect(e = dataSource.entities.getById("constant_box_material_stripe_evenColor")).toBeDefined(); expect(e.box.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.666666666666667, 0.976470588235294, 0.83921568627451, 0.643137254901961), 1e-14); expect(e = dataSource.entities.getById("constant_box_material_stripe_oddColor")).toBeDefined(); expect(e.box.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.258823529411765, 0.796078431372549, 0.717647058823529, 0.749019607843137), 1e-14); expect(e = dataSource.entities.getById("constant_box_material_checkerboard_evenColor")).toBeDefined(); expect(e.box.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.741176470588235, 0.0941176470588235, 0.101960784313725, 0.509803921568627), 1e-14); expect(e = dataSource.entities.getById("constant_box_material_checkerboard_oddColor")).toBeDefined(); expect(e.box.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.403921568627451, 0.768627450980392, 0.717647058823529, 0.0392156862745098), 1e-14); expect(e = dataSource.entities.getById("constant_box_outlineColor_rgbaf")).toBeDefined(); expect(e.box.outlineColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.835294117647059, 0.0313725490196078, 0.282352941176471, 0.337254901960784), 1e-14); expect(e = dataSource.entities.getById("constant_corridor_positions_cartographicRadians")).toBeDefined(); expect(e.corridor.positions.getValue(date)).toEqual([import__55.Cartesian3.fromRadians(0.220356654342316, 0.879184920197648, 64909), import__55.Cartesian3.fromRadians(0.175978952571564, 1.00316515710468, 913)]); expect(e = dataSource.entities.getById("constant_corridor_positions_cartographicDegrees")).toBeDefined(); expect(e.corridor.positions.getValue(date)).toEqual([import__55.Cartesian3.fromDegrees(28, 14, 63058), import__55.Cartesian3.fromDegrees(15, 37, 26381)]); expect(e = dataSource.entities.getById("constant_corridor_material_solidColor_color")).toBeDefined(); expect(e.corridor.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.333333333333333, 0.87843137254902, 0.356862745098039, 0.435294117647059), 1e-14); expect(e = dataSource.entities.getById("material_corridor_material_image")).toBeDefined(); expect(e.corridor.material.image.getValue(date).url).toEqual("http://example.com/8903"); expect(e.corridor.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(41660, 35234)); expect(e.corridor.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(213, 25, 147, 247)); expect(e.corridor.material.transparent.getValue(date)).toEqual(true); expect(e = dataSource.entities.getById("material_corridor_material_grid")).toBeDefined(); expect(e.corridor.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(236, 51, 112, 235)); expect(e.corridor.material.cellAlpha.getValue(date)).toEqual(11472); expect(e.corridor.material.lineCount.getValue(date)).toEqual(new import__55.Cartesian2(1254, 38404)); expect(e.corridor.material.lineThickness.getValue(date)).toEqual(new import__55.Cartesian2(48962, 63679)); expect(e.corridor.material.lineOffset.getValue(date)).toEqual(new import__55.Cartesian2(39061, 47e3)); expect(e = dataSource.entities.getById("material_corridor_material_stripe")).toBeDefined(); expect(e.corridor.material.orientation.getValue(date)).toEqual(import__55.StripeOrientation.VERTICAL); expect(e.corridor.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(245, 61, 208, 138)); expect(e.corridor.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(114, 73, 91, 165)); expect(e.corridor.material.offset.getValue(date)).toEqual(12788); expect(e.corridor.material.repeat.getValue(date)).toEqual(33136); expect(e = dataSource.entities.getById("material_corridor_material_checkerboard")).toBeDefined(); expect(e.corridor.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(24, 195, 5, 165)); expect(e.corridor.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(15, 107, 210, 249)); expect(e.corridor.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(19640, 18252)); expect(e = dataSource.entities.getById("constant_corridor_material_image_color")).toBeDefined(); expect(e.corridor.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.0156862745098039, 0.0941176470588235, 0.4, 0.529411764705882), 1e-14); expect(e = dataSource.entities.getById("constant_corridor_material_grid_color")).toBeDefined(); expect(e.corridor.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.576470588235294, 0.76078431372549, 0.152941176470588, 0.00392156862745098), 1e-14); expect(e = dataSource.entities.getById("constant_corridor_material_stripe_evenColor")).toBeDefined(); expect(e.corridor.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.913725490196078, 0.63921568627451, 0.631372549019608, 0.890196078431372), 1e-14); expect(e = dataSource.entities.getById("constant_corridor_material_stripe_oddColor")).toBeDefined(); expect(e.corridor.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.2, 0.137254901960784, 0.792156862745098, 0.301960784313725), 1e-14); expect(e = dataSource.entities.getById("constant_corridor_material_checkerboard_evenColor")).toBeDefined(); expect(e.corridor.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.286274509803922, 0.619607843137255, 0.615686274509804, 0.231372549019608), 1e-14); expect(e = dataSource.entities.getById("constant_corridor_material_checkerboard_oddColor")).toBeDefined(); expect(e.corridor.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.690196078431373, 0.172549019607843, 0.984313725490196, 0.43921568627451), 1e-14); expect(e = dataSource.entities.getById("constant_corridor_outlineColor_rgbaf")).toBeDefined(); expect(e.corridor.outlineColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.690196078431373, 0.0549019607843137, 0.247058823529412, 0.298039215686275), 1e-14); expect(e = dataSource.entities.getById("constant_cylinder_material_solidColor_color")).toBeDefined(); expect(e.cylinder.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.47843137254902, 0.0509803921568627, 0.450980392156863, 0.87843137254902), 1e-14); expect(e = dataSource.entities.getById("material_cylinder_material_image")).toBeDefined(); expect(e.cylinder.material.image.getValue(date).url).toEqual("http://example.com/27447"); expect(e.cylinder.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(65243, 41470)); expect(e.cylinder.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(200, 175, 107, 217)); expect(e.cylinder.material.transparent.getValue(date)).toEqual(true); expect(e = dataSource.entities.getById("material_cylinder_material_grid")).toBeDefined(); expect(e.cylinder.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(173, 210, 231, 62)); expect(e.cylinder.material.cellAlpha.getValue(date)).toEqual(9555); expect(e.cylinder.material.lineCount.getValue(date)).toEqual(new import__55.Cartesian2(58545, 26852)); expect(e.cylinder.material.lineThickness.getValue(date)).toEqual(new import__55.Cartesian2(58520, 44260)); expect(e.cylinder.material.lineOffset.getValue(date)).toEqual(new import__55.Cartesian2(61513, 28656)); expect(e = dataSource.entities.getById("material_cylinder_material_stripe")).toBeDefined(); expect(e.cylinder.material.orientation.getValue(date)).toEqual(import__55.StripeOrientation.VERTICAL); expect(e.cylinder.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(158, 155, 154, 86)); expect(e.cylinder.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(191, 226, 188, 74)); expect(e.cylinder.material.offset.getValue(date)).toEqual(55018); expect(e.cylinder.material.repeat.getValue(date)).toEqual(33073); expect(e = dataSource.entities.getById("material_cylinder_material_checkerboard")).toBeDefined(); expect(e.cylinder.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(90, 151, 142, 93)); expect(e.cylinder.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(29, 42, 163, 118)); expect(e.cylinder.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(62750, 3317)); expect(e = dataSource.entities.getById("constant_cylinder_material_image_color")).toBeDefined(); expect(e.cylinder.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.654901960784314, 0.0627450980392157, 0.517647058823529, 0.537254901960784), 1e-14); expect(e = dataSource.entities.getById("constant_cylinder_material_grid_color")).toBeDefined(); expect(e.cylinder.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.901960784313726, 0.364705882352941, 0.305882352941176, 0.945098039215686), 1e-14); expect(e = dataSource.entities.getById("constant_cylinder_material_stripe_evenColor")).toBeDefined(); expect(e.cylinder.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.0901960784313725, 0.133333333333333, 0.372549019607843, 0.498039215686275), 1e-14); expect(e = dataSource.entities.getById("constant_cylinder_material_stripe_oddColor")).toBeDefined(); expect(e.cylinder.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.905882352941176, 0.564705882352941, 0.486274509803922, 0.67843137254902), 1e-14); expect(e = dataSource.entities.getById("constant_cylinder_material_checkerboard_evenColor")).toBeDefined(); expect(e.cylinder.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.513725490196078, 0.756862745098039, 0.764705882352941, 0.882352941176471), 1e-14); expect(e = dataSource.entities.getById("constant_cylinder_material_checkerboard_oddColor")).toBeDefined(); expect(e.cylinder.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.450980392156863, 0.392156862745098, 0.333333333333333, 0.537254901960784), 1e-14); expect(e = dataSource.entities.getById("constant_cylinder_outlineColor_rgbaf")).toBeDefined(); expect(e.cylinder.outlineColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.647058823529412, 0.564705882352941, 0.4, 0.0862745098039216), 1e-14); expect(e = dataSource.entities.getById("constant_ellipse_material_solidColor_color")).toBeDefined(); expect(e.ellipse.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.0980392156862745, 0.913725490196078, 0.811764705882353, 0.2), 1e-14); expect(e = dataSource.entities.getById("material_ellipse_material_image")).toBeDefined(); expect(e.ellipse.material.image.getValue(date).url).toEqual("http://example.com/2481"); expect(e.ellipse.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(45447, 53937)); expect(e.ellipse.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(45, 86, 136, 120)); expect(e.ellipse.material.transparent.getValue(date)).toEqual(true); expect(e = dataSource.entities.getById("material_ellipse_material_grid")).toBeDefined(); expect(e.ellipse.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(217, 159, 32, 60)); expect(e.ellipse.material.cellAlpha.getValue(date)).toEqual(24764); expect(e.ellipse.material.lineCount.getValue(date)).toEqual(new import__55.Cartesian2(25721, 6500)); expect(e.ellipse.material.lineThickness.getValue(date)).toEqual(new import__55.Cartesian2(57205, 63455)); expect(e.ellipse.material.lineOffset.getValue(date)).toEqual(new import__55.Cartesian2(49829, 3778)); expect(e = dataSource.entities.getById("material_ellipse_material_stripe")).toBeDefined(); expect(e.ellipse.material.orientation.getValue(date)).toEqual(import__55.StripeOrientation.VERTICAL); expect(e.ellipse.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(7, 152, 58, 224)); expect(e.ellipse.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(4, 228, 224, 57)); expect(e.ellipse.material.offset.getValue(date)).toEqual(26719); expect(e.ellipse.material.repeat.getValue(date)).toEqual(15097); expect(e = dataSource.entities.getById("material_ellipse_material_checkerboard")).toBeDefined(); expect(e.ellipse.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(62, 67, 234, 118)); expect(e.ellipse.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(116, 61, 76, 32)); expect(e.ellipse.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(62262, 11507)); expect(e = dataSource.entities.getById("constant_ellipse_material_image_color")).toBeDefined(); expect(e.ellipse.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.364705882352941, 0.698039215686274, 0.803921568627451, 0.843137254901961), 1e-14); expect(e = dataSource.entities.getById("constant_ellipse_material_grid_color")).toBeDefined(); expect(e.ellipse.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.67843137254902, 0.580392156862745, 0.823529411764706, 0.627450980392157), 1e-14); expect(e = dataSource.entities.getById("constant_ellipse_material_stripe_evenColor")).toBeDefined(); expect(e.ellipse.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.313725490196078, 0.768627450980392, 0.674509803921569, 0.705882352941177), 1e-14); expect(e = dataSource.entities.getById("constant_ellipse_material_stripe_oddColor")).toBeDefined(); expect(e.ellipse.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.682352941176471, 0.658823529411765, 0.952941176470588, 0.0823529411764706), 1e-14); expect(e = dataSource.entities.getById("constant_ellipse_material_checkerboard_evenColor")).toBeDefined(); expect(e.ellipse.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.0196078431372549, 0.537254901960784, 0.290196078431373, 0.403921568627451), 1e-14); expect(e = dataSource.entities.getById("constant_ellipse_material_checkerboard_oddColor")).toBeDefined(); expect(e.ellipse.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.317647058823529, 0.690196078431373, 0.223529411764706, 0.886274509803922), 1e-14); expect(e = dataSource.entities.getById("constant_ellipse_outlineColor_rgbaf")).toBeDefined(); expect(e.ellipse.outlineColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.572549019607843, 0.956862745098039, 0.968627450980392, 0.674509803921569), 1e-14); expect(e = dataSource.entities.getById("constant_ellipsoid_material_solidColor_color")).toBeDefined(); expect(e.ellipsoid.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.572549019607843, 0.533333333333333, 0.384313725490196, 0.2), 1e-14); expect(e = dataSource.entities.getById("material_ellipsoid_material_image")).toBeDefined(); expect(e.ellipsoid.material.image.getValue(date).url).toEqual("http://example.com/47428"); expect(e.ellipsoid.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(53733, 35793)); expect(e.ellipsoid.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(125, 49, 160, 165)); expect(e.ellipsoid.material.transparent.getValue(date)).toEqual(true); expect(e = dataSource.entities.getById("material_ellipsoid_material_grid")).toBeDefined(); expect(e.ellipsoid.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(95, 212, 218, 57)); expect(e.ellipsoid.material.cellAlpha.getValue(date)).toEqual(53044); expect(e.ellipsoid.material.lineCount.getValue(date)).toEqual(new import__55.Cartesian2(7763, 58654)); expect(e.ellipsoid.material.lineThickness.getValue(date)).toEqual(new import__55.Cartesian2(25480, 4707)); expect(e.ellipsoid.material.lineOffset.getValue(date)).toEqual(new import__55.Cartesian2(38422, 44182)); expect(e = dataSource.entities.getById("material_ellipsoid_material_stripe")).toBeDefined(); expect(e.ellipsoid.material.orientation.getValue(date)).toEqual(import__55.StripeOrientation.VERTICAL); expect(e.ellipsoid.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(174, 241, 84, 24)); expect(e.ellipsoid.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(134, 51, 175, 154)); expect(e.ellipsoid.material.offset.getValue(date)).toEqual(24796); expect(e.ellipsoid.material.repeat.getValue(date)).toEqual(2913); expect(e = dataSource.entities.getById("material_ellipsoid_material_checkerboard")).toBeDefined(); expect(e.ellipsoid.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(65, 215, 40, 252)); expect(e.ellipsoid.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(63, 63, 46, 195)); expect(e.ellipsoid.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(40702, 13470)); expect(e = dataSource.entities.getById("constant_ellipsoid_material_image_color")).toBeDefined(); expect(e.ellipsoid.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.247058823529412, 0.403921568627451, 0.145098039215686, 0.47843137254902), 1e-14); expect(e = dataSource.entities.getById("constant_ellipsoid_material_grid_color")).toBeDefined(); expect(e.ellipsoid.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.270588235294118, 0.784313725490196, 0.172549019607843, 0.835294117647059), 1e-14); expect(e = dataSource.entities.getById("constant_ellipsoid_material_stripe_evenColor")).toBeDefined(); expect(e.ellipsoid.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.415686274509804, 0.192156862745098, 0.368627450980392, 0.129411764705882), 1e-14); expect(e = dataSource.entities.getById("constant_ellipsoid_material_stripe_oddColor")).toBeDefined(); expect(e.ellipsoid.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.580392156862745, 0.164705882352941, 0.741176470588235, 0.0941176470588235), 1e-14); expect(e = dataSource.entities.getById("constant_ellipsoid_material_checkerboard_evenColor")).toBeDefined(); expect(e.ellipsoid.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.137254901960784, 0.784313725490196, 0.294117647058824, 0.964705882352941), 1e-14); expect(e = dataSource.entities.getById("constant_ellipsoid_material_checkerboard_oddColor")).toBeDefined(); expect(e.ellipsoid.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.905882352941176, 0.929411764705882, 0.427450980392157, 0.113725490196078), 1e-14); expect(e = dataSource.entities.getById("constant_ellipsoid_outlineColor_rgbaf")).toBeDefined(); expect(e.ellipsoid.outlineColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.494117647058824, 0.0823529411764706, 0.274509803921569, 0.823529411764706), 1e-14); expect(e = dataSource.entities.getById("constant_label_backgroundColor_rgbaf")).toBeDefined(); expect(e.label.backgroundColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.894117647058824, 0.949019607843137, 0.494117647058824, 0.843137254901961), 1e-14); expect(e = dataSource.entities.getById("constant_label_fillColor_rgbaf")).toBeDefined(); expect(e.label.fillColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.16078431372549, 0.568627450980392, 0.776470588235294, 0.505882352941176), 1e-14); expect(e = dataSource.entities.getById("constant_label_outlineColor_rgbaf")).toBeDefined(); expect(e.label.outlineColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.458823529411765, 0.325490196078431, 0.909803921568627, 0.67843137254902), 1e-14); expect(e = dataSource.entities.getById("constant_model_silhouetteColor_rgbaf")).toBeDefined(); expect(e.model.silhouetteColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.294117647058824, 0.313725490196078, 0.419607843137255, 0.87843137254902), 1e-14); expect(e = dataSource.entities.getById("constant_model_color_rgbaf")).toBeDefined(); expect(e.model.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.568627450980392, 0.333333333333333, 0.141176470588235, 0.572549019607843), 1e-14); expect(e = dataSource.entities.getById("constant_path_material_solidColor_color")).toBeDefined(); expect(e.path.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.458823529411765, 0.517647058823529, 0.52156862745098, 0.925490196078431), 1e-14); expect(e = dataSource.entities.getById("material_path_material_polylineOutline")).toBeDefined(); expect(e.path.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(158, 14, 3, 86)); expect(e.path.material.outlineColor.getValue(date)).toEqual(import__55.Color.fromBytes(137, 101, 236, 136)); expect(e.path.material.outlineWidth.getValue(date)).toEqual(11017); expect(e = dataSource.entities.getById("material_path_material_polylineArrow")).toBeDefined(); expect(e.path.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(166, 131, 155, 102)); expect(e = dataSource.entities.getById("material_path_material_polylineDash")).toBeDefined(); expect(e.path.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(190, 189, 9, 7)); expect(e.path.material.gapColor.getValue(date)).toEqual(import__55.Color.fromBytes(170, 88, 12, 24)); expect(e.path.material.dashLength.getValue(date)).toEqual(45848); expect(e.path.material.dashPattern.getValue(date)).toEqual(13519); expect(e = dataSource.entities.getById("material_path_material_polylineGlow")).toBeDefined(); expect(e.path.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(72, 114, 200, 147)); expect(e.path.material.glowPower.getValue(date)).toEqual(42344); expect(e.path.material.taperPower.getValue(date)).toEqual(39950); expect(e = dataSource.entities.getById("material_path_material_image")).toBeDefined(); expect(e.path.material.image.getValue(date).url).toEqual("http://example.com/31068"); expect(e.path.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(48351, 63420)); expect(e.path.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(105, 166, 133, 7)); expect(e.path.material.transparent.getValue(date)).toEqual(true); expect(e = dataSource.entities.getById("material_path_material_grid")).toBeDefined(); expect(e.path.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(120, 196, 99, 165)); expect(e.path.material.cellAlpha.getValue(date)).toEqual(41317); expect(e.path.material.lineCount.getValue(date)).toEqual(new import__55.Cartesian2(52557, 7629)); expect(e.path.material.lineThickness.getValue(date)).toEqual(new import__55.Cartesian2(21845, 52309)); expect(e.path.material.lineOffset.getValue(date)).toEqual(new import__55.Cartesian2(48700, 4542)); expect(e = dataSource.entities.getById("material_path_material_stripe")).toBeDefined(); expect(e.path.material.orientation.getValue(date)).toEqual(import__55.StripeOrientation.VERTICAL); expect(e.path.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(20, 43, 77, 229)); expect(e.path.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(157, 171, 93, 187)); expect(e.path.material.offset.getValue(date)).toEqual(41305); expect(e.path.material.repeat.getValue(date)).toEqual(43637); expect(e = dataSource.entities.getById("material_path_material_checkerboard")).toBeDefined(); expect(e.path.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(174, 238, 222, 107)); expect(e.path.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(184, 189, 156, 237)); expect(e.path.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(57303, 45535)); expect(e = dataSource.entities.getById("constant_path_material_polylineOutline_color")).toBeDefined(); expect(e.path.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.0588235294117647, 0.0823529411764706, 0.964705882352941, 0.317647058823529), 1e-14); expect(e = dataSource.entities.getById("constant_path_material_polylineOutline_outlineColor")).toBeDefined(); expect(e.path.material.outlineColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.266666666666667, 0.556862745098039, 0.352941176470588, 0.76078431372549), 1e-14); expect(e = dataSource.entities.getById("constant_path_material_polylineArrow_color")).toBeDefined(); expect(e.path.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.627450980392157, 0.27843137254902, 0.972549019607843, 0.92156862745098), 1e-14); expect(e = dataSource.entities.getById("constant_path_material_polylineDash_color")).toBeDefined(); expect(e.path.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.113725490196078, 0.368627450980392, 0.411764705882353, 0.745098039215686), 1e-14); expect(e = dataSource.entities.getById("constant_path_material_polylineDash_gapColor")).toBeDefined(); expect(e.path.material.gapColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.831372549019608, 0.313725490196078, 0.341176470588235, 0.749019607843137), 1e-14); expect(e = dataSource.entities.getById("constant_path_material_polylineGlow_color")).toBeDefined(); expect(e.path.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.584313725490196, 0.0156862745098039, 0.329411764705882, 0.270588235294118), 1e-14); expect(e = dataSource.entities.getById("constant_path_material_image_color")).toBeDefined(); expect(e.path.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.443137254901961, 0.450980392156863, 0.63921568627451, 0.415686274509804), 1e-14); expect(e = dataSource.entities.getById("constant_path_material_grid_color")).toBeDefined(); expect(e.path.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.984313725490196, 0.945098039215686, 0.764705882352941, 0.933333333333333), 1e-14); expect(e = dataSource.entities.getById("constant_path_material_stripe_evenColor")).toBeDefined(); expect(e.path.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.584313725490196, 0.631372549019608, 0.0196078431372549, 0.349019607843137), 1e-14); expect(e = dataSource.entities.getById("constant_path_material_stripe_oddColor")).toBeDefined(); expect(e.path.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.231372549019608, 0.211764705882353, 0.941176470588235, 0.501960784313725), 1e-14); expect(e = dataSource.entities.getById("constant_path_material_checkerboard_evenColor")).toBeDefined(); expect(e.path.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.258823529411765, 0.850980392156863, 0.196078431372549, 0.811764705882353), 1e-14); expect(e = dataSource.entities.getById("constant_path_material_checkerboard_oddColor")).toBeDefined(); expect(e.path.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.0745098039215686, 0.933333333333333, 0.184313725490196, 0.117647058823529), 1e-14); expect(e = dataSource.entities.getById("constant_point_color_rgbaf")).toBeDefined(); expect(e.point.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.662745098039216, 0.317647058823529, 0.643137254901961, 0.705882352941177), 1e-14); expect(e = dataSource.entities.getById("constant_point_outlineColor_rgbaf")).toBeDefined(); expect(e.point.outlineColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.00392156862745098, 0.388235294117647, 0.101960784313725, 0.16078431372549), 1e-14); expect(e = dataSource.entities.getById("constant_polygon_positions_cartographicRadians")).toBeDefined(); expect(e.polygon.hierarchy.getValue(date).positions).toEqual([import__55.Cartesian3.fromRadians(0.278819883450618, 1.34192534297912, 13112), import__55.Cartesian3.fromRadians(1.08460649779701, 1.26665808721843, 9013)]); expect(e = dataSource.entities.getById("constant_polygon_positions_cartographicDegrees")).toBeDefined(); expect(e.polygon.hierarchy.getValue(date).positions).toEqual([import__55.Cartesian3.fromDegrees(20, 42, 343), import__55.Cartesian3.fromDegrees(21, 14, 24042)]); expect(e = dataSource.entities.getById("constant_polygon_holes_cartographicRadians")).toBeDefined(); expect(e.polygon.hierarchy.getValue(date).holes).toEqual([new import__55.PolygonHierarchy([import__55.Cartesian3.fromRadians(0.799220652820836, 1.50366253893541, 4776), import__55.Cartesian3.fromRadians(0.179862066646486, 1.42489853818289, 42245), import__55.Cartesian3.fromRadians(0.0636782022426772, 0.558333087028927, 32510)]), new import__55.PolygonHierarchy([import__55.Cartesian3.fromRadians(1.50366253893541, 0.779166543514464, 33810), import__55.Cartesian3.fromRadians(1.42489853818289, 0.00358717805196918, 20389), import__55.Cartesian3.fromRadians(0.558333087028927, 0.799220652820836, 43134), import__55.Cartesian3.fromRadians(0.779166543514464, 0.179862066646486, 1412)])]); expect(e = dataSource.entities.getById("constant_polygon_holes_cartographicDegrees")).toBeDefined(); expect(e.polygon.hierarchy.getValue(date).holes).toEqual([new import__55.PolygonHierarchy([import__55.Cartesian3.fromDegrees(38, 39, 52122), import__55.Cartesian3.fromDegrees(30, 41, 40406), import__55.Cartesian3.fromDegrees(9, 42, 55073)]), new import__55.PolygonHierarchy([import__55.Cartesian3.fromDegrees(39, 12, 5835), import__55.Cartesian3.fromDegrees(41, 41, 39069), import__55.Cartesian3.fromDegrees(42, 38, 39639), import__55.Cartesian3.fromDegrees(12, 30, 54806)])]); expect(e = dataSource.entities.getById("constant_polygon_material_solidColor_color")).toBeDefined(); expect(e.polygon.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.980392156862745, 0.905882352941176, 0.274509803921569, 0.972549019607843), 1e-14); expect(e = dataSource.entities.getById("material_polygon_material_image")).toBeDefined(); expect(e.polygon.material.image.getValue(date).url).toEqual("http://example.com/3481"); expect(e.polygon.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(29381, 10354)); expect(e.polygon.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(36, 184, 236, 209)); expect(e.polygon.material.transparent.getValue(date)).toEqual(true); expect(e = dataSource.entities.getById("material_polygon_material_grid")).toBeDefined(); expect(e.polygon.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(246, 64, 141, 13)); expect(e.polygon.material.cellAlpha.getValue(date)).toEqual(986); expect(e.polygon.material.lineCount.getValue(date)).toEqual(new import__55.Cartesian2(26094, 44645)); expect(e.polygon.material.lineThickness.getValue(date)).toEqual(new import__55.Cartesian2(30775, 17784)); expect(e.polygon.material.lineOffset.getValue(date)).toEqual(new import__55.Cartesian2(58344, 3555)); expect(e = dataSource.entities.getById("material_polygon_material_stripe")).toBeDefined(); expect(e.polygon.material.orientation.getValue(date)).toEqual(import__55.StripeOrientation.VERTICAL); expect(e.polygon.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(98, 184, 45, 52)); expect(e.polygon.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(164, 123, 182, 228)); expect(e.polygon.material.offset.getValue(date)).toEqual(12114); expect(e.polygon.material.repeat.getValue(date)).toEqual(60350); expect(e = dataSource.entities.getById("material_polygon_material_checkerboard")).toBeDefined(); expect(e.polygon.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(187, 186, 46, 98)); expect(e.polygon.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(19, 74, 101, 217)); expect(e.polygon.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(45028, 15023)); expect(e = dataSource.entities.getById("constant_polygon_material_image_color")).toBeDefined(); expect(e.polygon.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.674509803921569, 0.8, 0.411764705882353, 0.207843137254902), 1e-14); expect(e = dataSource.entities.getById("constant_polygon_material_grid_color")).toBeDefined(); expect(e.polygon.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.603921568627451, 0.0941176470588235, 0.00784313725490196, 0.0862745098039216), 1e-14); expect(e = dataSource.entities.getById("constant_polygon_material_stripe_evenColor")).toBeDefined(); expect(e.polygon.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.772549019607843, 0.866666666666667, 0.964705882352941, 0.862745098039216), 1e-14); expect(e = dataSource.entities.getById("constant_polygon_material_stripe_oddColor")).toBeDefined(); expect(e.polygon.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.862745098039216, 0.0392156862745098, 0.458823529411765, 0.596078431372549), 1e-14); expect(e = dataSource.entities.getById("constant_polygon_material_checkerboard_evenColor")).toBeDefined(); expect(e.polygon.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.396078431372549, 0.576470588235294, 0.474509803921569, 0.909803921568627), 1e-14); expect(e = dataSource.entities.getById("constant_polygon_material_checkerboard_oddColor")).toBeDefined(); expect(e.polygon.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.117647058823529, 0.258823529411765, 0.541176470588235, 0.207843137254902), 1e-14); expect(e = dataSource.entities.getById("constant_polygon_outlineColor_rgbaf")).toBeDefined(); expect(e.polygon.outlineColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.105882352941176, 0.423529411764706, 0.619607843137255, 0.956862745098039), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_positions_cartographicRadians")).toBeDefined(); expect(e.polyline.positions.getValue(date)).toEqual([import__55.Cartesian3.fromRadians(0.23083587429617, 0.738315731088925, 41390), import__55.Cartesian3.fromRadians(0.537259577218533, 0.25389340391868, 10573)]); expect(e = dataSource.entities.getById("constant_polyline_positions_cartographicDegrees")).toBeDefined(); expect(e.polyline.positions.getValue(date)).toEqual([import__55.Cartesian3.fromDegrees(19, 5, 11802), import__55.Cartesian3.fromDegrees(15, 40, 39495)]); expect(e = dataSource.entities.getById("constant_polyline_material_solidColor_color")).toBeDefined(); expect(e.polyline.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.764705882352941, 0.894117647058824, 0.874509803921569, 0.105882352941176), 1e-14); expect(e = dataSource.entities.getById("material_polyline_material_polylineOutline")).toBeDefined(); expect(e.polyline.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(152, 14, 11, 33)); expect(e.polyline.material.outlineColor.getValue(date)).toEqual(import__55.Color.fromBytes(222, 51, 202, 92)); expect(e.polyline.material.outlineWidth.getValue(date)).toEqual(6879); expect(e = dataSource.entities.getById("material_polyline_material_polylineArrow")).toBeDefined(); expect(e.polyline.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(82, 169, 80, 107)); expect(e = dataSource.entities.getById("material_polyline_material_polylineDash")).toBeDefined(); expect(e.polyline.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(22, 214, 57, 141)); expect(e.polyline.material.gapColor.getValue(date)).toEqual(import__55.Color.fromBytes(150, 91, 109, 117)); expect(e.polyline.material.dashLength.getValue(date)).toEqual(60297); expect(e.polyline.material.dashPattern.getValue(date)).toEqual(40430); expect(e = dataSource.entities.getById("material_polyline_material_polylineGlow")).toBeDefined(); expect(e.polyline.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(59, 125, 181, 171)); expect(e.polyline.material.glowPower.getValue(date)).toEqual(41345); expect(e.polyline.material.taperPower.getValue(date)).toEqual(29908); expect(e = dataSource.entities.getById("material_polyline_material_image")).toBeDefined(); expect(e.polyline.material.image.getValue(date).url).toEqual("http://example.com/29020"); expect(e.polyline.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(8980, 60451)); expect(e.polyline.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(46, 136, 39, 94)); expect(e.polyline.material.transparent.getValue(date)).toEqual(true); expect(e = dataSource.entities.getById("material_polyline_material_grid")).toBeDefined(); expect(e.polyline.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(157, 57, 26, 26)); expect(e.polyline.material.cellAlpha.getValue(date)).toEqual(27197); expect(e.polyline.material.lineCount.getValue(date)).toEqual(new import__55.Cartesian2(17878, 15173)); expect(e.polyline.material.lineThickness.getValue(date)).toEqual(new import__55.Cartesian2(64504, 24571)); expect(e.polyline.material.lineOffset.getValue(date)).toEqual(new import__55.Cartesian2(51933, 9674)); expect(e = dataSource.entities.getById("material_polyline_material_stripe")).toBeDefined(); expect(e.polyline.material.orientation.getValue(date)).toEqual(import__55.StripeOrientation.VERTICAL); expect(e.polyline.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(98, 239, 47, 132)); expect(e.polyline.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(41, 198, 29, 144)); expect(e.polyline.material.offset.getValue(date)).toEqual(10077); expect(e.polyline.material.repeat.getValue(date)).toEqual(31817); expect(e = dataSource.entities.getById("material_polyline_material_checkerboard")).toBeDefined(); expect(e.polyline.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(29, 196, 146, 39)); expect(e.polyline.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(189, 110, 12, 32)); expect(e.polyline.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(22832, 11097)); expect(e = dataSource.entities.getById("constant_polyline_material_polylineOutline_color")).toBeDefined(); expect(e.polyline.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.450980392156863, 0.890196078431372, 0.403921568627451, 0.16078431372549), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_material_polylineOutline_outlineColor")).toBeDefined(); expect(e.polyline.material.outlineColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.815686274509804, 0.545098039215686, 0.529411764705882, 0.317647058823529), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_material_polylineArrow_color")).toBeDefined(); expect(e.polyline.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.831372549019608, 0.823529411764706, 0.631372549019608, 0.443137254901961), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_material_polylineDash_color")).toBeDefined(); expect(e.polyline.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.462745098039216, 0.184313725490196, 0.329411764705882, 0), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_material_polylineDash_gapColor")).toBeDefined(); expect(e.polyline.material.gapColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.0509803921568627, 0.0313725490196078, 0.23921568627451, 0.4), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_material_polylineGlow_color")).toBeDefined(); expect(e.polyline.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.411764705882353, 0.313725490196078, 0.858823529411765, 0.380392156862745), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_material_image_color")).toBeDefined(); expect(e.polyline.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.133333333333333, 0.552941176470588, 0.0431372549019608, 0.184313725490196), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_material_grid_color")).toBeDefined(); expect(e.polyline.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.141176470588235, 0.823529411764706, 0.588235294117647, 0.56078431372549), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_material_stripe_evenColor")).toBeDefined(); expect(e.polyline.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.647058823529412, 0.862745098039216, 0.129411764705882, 0.780392156862745), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_material_stripe_oddColor")).toBeDefined(); expect(e.polyline.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.290196078431373, 0.780392156862745, 0.0705882352941176, 0.27843137254902), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_material_checkerboard_evenColor")).toBeDefined(); expect(e.polyline.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.505882352941176, 0.466666666666667, 0.862745098039216, 0.803921568627451), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_material_checkerboard_oddColor")).toBeDefined(); expect(e.polyline.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.32156862745098, 0.454901960784314, 0.803921568627451, 0.203921568627451), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_depthFailMaterial_solidColor_color")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.905882352941176, 0.635294117647059, 0.435294117647059, 0.631372549019608), 1e-14); expect(e = dataSource.entities.getById("material_polyline_depthFailMaterial_polylineOutline")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqual(import__55.Color.fromBytes(238, 116, 228, 18)); expect(e.polyline.depthFailMaterial.outlineColor.getValue(date)).toEqual(import__55.Color.fromBytes(36, 55, 18, 134)); expect(e.polyline.depthFailMaterial.outlineWidth.getValue(date)).toEqual(33747); expect(e = dataSource.entities.getById("material_polyline_depthFailMaterial_polylineArrow")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqual(import__55.Color.fromBytes(80, 78, 117, 160)); expect(e = dataSource.entities.getById("material_polyline_depthFailMaterial_polylineDash")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqual(import__55.Color.fromBytes(139, 171, 44, 217)); expect(e.polyline.depthFailMaterial.gapColor.getValue(date)).toEqual(import__55.Color.fromBytes(253, 13, 109, 243)); expect(e.polyline.depthFailMaterial.dashLength.getValue(date)).toEqual(21429); expect(e.polyline.depthFailMaterial.dashPattern.getValue(date)).toEqual(13659); expect(e = dataSource.entities.getById("material_polyline_depthFailMaterial_polylineGlow")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqual(import__55.Color.fromBytes(82, 227, 164, 249)); expect(e.polyline.depthFailMaterial.glowPower.getValue(date)).toEqual(52932); expect(e.polyline.depthFailMaterial.taperPower.getValue(date)).toEqual(29589); expect(e = dataSource.entities.getById("material_polyline_depthFailMaterial_image")).toBeDefined(); expect(e.polyline.depthFailMaterial.image.getValue(date).url).toEqual("http://example.com/6349"); expect(e.polyline.depthFailMaterial.repeat.getValue(date)).toEqual(new import__55.Cartesian2(24549, 50015)); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqual(import__55.Color.fromBytes(71, 233, 193, 55)); expect(e.polyline.depthFailMaterial.transparent.getValue(date)).toEqual(true); expect(e = dataSource.entities.getById("material_polyline_depthFailMaterial_grid")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqual(import__55.Color.fromBytes(241, 160, 22, 116)); expect(e.polyline.depthFailMaterial.cellAlpha.getValue(date)).toEqual(32801); expect(e.polyline.depthFailMaterial.lineCount.getValue(date)).toEqual(new import__55.Cartesian2(27318, 57194)); expect(e.polyline.depthFailMaterial.lineThickness.getValue(date)).toEqual(new import__55.Cartesian2(2299, 50440)); expect(e.polyline.depthFailMaterial.lineOffset.getValue(date)).toEqual(new import__55.Cartesian2(16744, 62785)); expect(e = dataSource.entities.getById("material_polyline_depthFailMaterial_stripe")).toBeDefined(); expect(e.polyline.depthFailMaterial.orientation.getValue(date)).toEqual(import__55.StripeOrientation.VERTICAL); expect(e.polyline.depthFailMaterial.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(174, 135, 160, 224)); expect(e.polyline.depthFailMaterial.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(8, 166, 115, 198)); expect(e.polyline.depthFailMaterial.offset.getValue(date)).toEqual(58992); expect(e.polyline.depthFailMaterial.repeat.getValue(date)).toEqual(7346); expect(e = dataSource.entities.getById("material_polyline_depthFailMaterial_checkerboard")).toBeDefined(); expect(e.polyline.depthFailMaterial.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(143, 196, 196, 1)); expect(e.polyline.depthFailMaterial.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(49, 118, 113, 119)); expect(e.polyline.depthFailMaterial.repeat.getValue(date)).toEqual(new import__55.Cartesian2(32284, 46718)); expect(e = dataSource.entities.getById("constant_polyline_depthFailMaterial_polylineOutline_color")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.976470588235294, 0.133333333333333, 0.835294117647059, 0.694117647058824), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_depthFailMaterial_polylineOutline_outlineColor")).toBeDefined(); expect(e.polyline.depthFailMaterial.outlineColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.8, 0.866666666666667, 0.219607843137255, 0.262745098039216), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_depthFailMaterial_polylineArrow_color")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.0392156862745098, 0.988235294117647, 0.784313725490196, 0.211764705882353), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_depthFailMaterial_polylineDash_color")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.0431372549019608, 0.235294117647059, 0.443137254901961, 0.701960784313725), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_depthFailMaterial_polylineDash_gapColor")).toBeDefined(); expect(e.polyline.depthFailMaterial.gapColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.388235294117647, 0.0196078431372549, 0.780392156862745, 0.941176470588235), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_depthFailMaterial_polylineGlow_color")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.733333333333333, 0.180392156862745, 0.407843137254902, 0.168627450980392), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_depthFailMaterial_image_color")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.815686274509804, 0.47843137254902, 0.254901960784314, 0.47843137254902), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_depthFailMaterial_grid_color")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.247058823529412, 0.945098039215686, 0.0274509803921569, 0.968627450980392), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_depthFailMaterial_stripe_evenColor")).toBeDefined(); expect(e.polyline.depthFailMaterial.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.517647058823529, 0.576470588235294, 0.615686274509804, 0.682352941176471), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_depthFailMaterial_stripe_oddColor")).toBeDefined(); expect(e.polyline.depthFailMaterial.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.333333333333333, 0.537254901960784, 0.443137254901961, 0.658823529411765), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_depthFailMaterial_checkerboard_evenColor")).toBeDefined(); expect(e.polyline.depthFailMaterial.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.145098039215686, 0.815686274509804, 0.113725490196078, 0.729411764705882), 1e-14); expect(e = dataSource.entities.getById("constant_polyline_depthFailMaterial_checkerboard_oddColor")).toBeDefined(); expect(e.polyline.depthFailMaterial.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.0941176470588235, 0.615686274509804, 0.447058823529412, 0.00392156862745098), 1e-14); expect(e = dataSource.entities.getById("constant_polylineVolume_positions_cartographicRadians")).toBeDefined(); expect(e.polylineVolume.positions.getValue(date)).toEqual([import__55.Cartesian3.fromRadians(0.0883087457516627, 0.924587529983249, 8130), import__55.Cartesian3.fromRadians(0.613491452287313, 1.45657735287148, 19697)]); expect(e = dataSource.entities.getById("constant_polylineVolume_positions_cartographicDegrees")).toBeDefined(); expect(e.polylineVolume.positions.getValue(date)).toEqual([import__55.Cartesian3.fromDegrees(7, 43, 57136), import__55.Cartesian3.fromDegrees(44, 37, 65346)]); expect(e = dataSource.entities.getById("constant_polylineVolume_material_solidColor_color")).toBeDefined(); expect(e.polylineVolume.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.866666666666667, 0.129411764705882, 0.133333333333333, 0.643137254901961), 1e-14); expect(e = dataSource.entities.getById("material_polylineVolume_material_image")).toBeDefined(); expect(e.polylineVolume.material.image.getValue(date).url).toEqual("http://example.com/25029"); expect(e.polylineVolume.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(16806, 36161)); expect(e.polylineVolume.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(29, 171, 22, 0)); expect(e.polylineVolume.material.transparent.getValue(date)).toEqual(true); expect(e = dataSource.entities.getById("material_polylineVolume_material_grid")).toBeDefined(); expect(e.polylineVolume.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(180, 62, 202, 240)); expect(e.polylineVolume.material.cellAlpha.getValue(date)).toEqual(58563); expect(e.polylineVolume.material.lineCount.getValue(date)).toEqual(new import__55.Cartesian2(13158, 59443)); expect(e.polylineVolume.material.lineThickness.getValue(date)).toEqual(new import__55.Cartesian2(11642, 8493)); expect(e.polylineVolume.material.lineOffset.getValue(date)).toEqual(new import__55.Cartesian2(2361, 14345)); expect(e = dataSource.entities.getById("material_polylineVolume_material_stripe")).toBeDefined(); expect(e.polylineVolume.material.orientation.getValue(date)).toEqual(import__55.StripeOrientation.VERTICAL); expect(e.polylineVolume.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(100, 38, 210, 254)); expect(e.polylineVolume.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(27, 12, 194, 159)); expect(e.polylineVolume.material.offset.getValue(date)).toEqual(38819); expect(e.polylineVolume.material.repeat.getValue(date)).toEqual(1822); expect(e = dataSource.entities.getById("material_polylineVolume_material_checkerboard")).toBeDefined(); expect(e.polylineVolume.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(146, 199, 90, 246)); expect(e.polylineVolume.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(74, 232, 2, 60)); expect(e.polylineVolume.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(13666, 60213)); expect(e = dataSource.entities.getById("constant_polylineVolume_material_image_color")).toBeDefined(); expect(e.polylineVolume.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.443137254901961, 0.152941176470588, 0.462745098039216, 0.701960784313725), 1e-14); expect(e = dataSource.entities.getById("constant_polylineVolume_material_grid_color")).toBeDefined(); expect(e.polylineVolume.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.356862745098039, 0.756862745098039, 0.968627450980392, 0.109803921568627), 1e-14); expect(e = dataSource.entities.getById("constant_polylineVolume_material_stripe_evenColor")).toBeDefined(); expect(e.polylineVolume.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.0901960784313725, 0.423529411764706, 0.576470588235294, 0.266666666666667), 1e-14); expect(e = dataSource.entities.getById("constant_polylineVolume_material_stripe_oddColor")).toBeDefined(); expect(e.polylineVolume.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.682352941176471, 0.929411764705882, 0.337254901960784, 0.933333333333333), 1e-14); expect(e = dataSource.entities.getById("constant_polylineVolume_material_checkerboard_evenColor")).toBeDefined(); expect(e.polylineVolume.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.854901960784314, 0.627450980392157, 0.337254901960784, 0.243137254901961), 1e-14); expect(e = dataSource.entities.getById("constant_polylineVolume_material_checkerboard_oddColor")).toBeDefined(); expect(e.polylineVolume.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.843137254901961, 0.0352941176470588, 0.505882352941176, 0.890196078431372), 1e-14); expect(e = dataSource.entities.getById("constant_polylineVolume_outlineColor_rgbaf")).toBeDefined(); expect(e.polylineVolume.outlineColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.549019607843137, 0.407843137254902, 0.466666666666667, 0.423529411764706), 1e-14); expect(e = dataSource.entities.getById("constant_rectangle_coordinates_wsenDegrees")).toBeDefined(); expect(e.rectangle.coordinates.getValue(date)).toEqual(import__55.Rectangle.fromDegrees(42, 22, 5, 35)); expect(e = dataSource.entities.getById("constant_rectangle_material_solidColor_color")).toBeDefined(); expect(e.rectangle.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.898039215686275, 0.8, 0.905882352941176, 0.952941176470588), 1e-14); expect(e = dataSource.entities.getById("material_rectangle_material_image")).toBeDefined(); expect(e.rectangle.material.image.getValue(date).url).toEqual("http://example.com/18033"); expect(e.rectangle.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(41461, 31905)); expect(e.rectangle.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(93, 203, 88, 125)); expect(e.rectangle.material.transparent.getValue(date)).toEqual(true); expect(e = dataSource.entities.getById("material_rectangle_material_grid")).toBeDefined(); expect(e.rectangle.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(245, 105, 152, 83)); expect(e.rectangle.material.cellAlpha.getValue(date)).toEqual(57393); expect(e.rectangle.material.lineCount.getValue(date)).toEqual(new import__55.Cartesian2(4947, 4627)); expect(e.rectangle.material.lineThickness.getValue(date)).toEqual(new import__55.Cartesian2(37424, 19602)); expect(e.rectangle.material.lineOffset.getValue(date)).toEqual(new import__55.Cartesian2(43685, 31658)); expect(e = dataSource.entities.getById("material_rectangle_material_stripe")).toBeDefined(); expect(e.rectangle.material.orientation.getValue(date)).toEqual(import__55.StripeOrientation.VERTICAL); expect(e.rectangle.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(196, 12, 53, 2)); expect(e.rectangle.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(103, 243, 111, 72)); expect(e.rectangle.material.offset.getValue(date)).toEqual(26578); expect(e.rectangle.material.repeat.getValue(date)).toEqual(52842); expect(e = dataSource.entities.getById("material_rectangle_material_checkerboard")).toBeDefined(); expect(e.rectangle.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(210, 132, 163, 116)); expect(e.rectangle.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(159, 4, 119, 14)); expect(e.rectangle.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(27335, 51818)); expect(e = dataSource.entities.getById("constant_rectangle_material_image_color")).toBeDefined(); expect(e.rectangle.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.247058823529412, 0.498039215686275, 0.741176470588235, 0.968627450980392), 1e-14); expect(e = dataSource.entities.getById("constant_rectangle_material_grid_color")).toBeDefined(); expect(e.rectangle.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.458823529411765, 0.0627450980392157, 0.886274509803922, 0.83921568627451), 1e-14); expect(e = dataSource.entities.getById("constant_rectangle_material_stripe_evenColor")).toBeDefined(); expect(e.rectangle.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.576470588235294, 0.341176470588235, 0.611764705882353, 0.207843137254902), 1e-14); expect(e = dataSource.entities.getById("constant_rectangle_material_stripe_oddColor")).toBeDefined(); expect(e.rectangle.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.866666666666667, 0.949019607843137, 0.0627450980392157, 0.0196078431372549), 1e-14); expect(e = dataSource.entities.getById("constant_rectangle_material_checkerboard_evenColor")).toBeDefined(); expect(e.rectangle.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.545098039215686, 0.647058823529412, 0.603921568627451, 0.725490196078431), 1e-14); expect(e = dataSource.entities.getById("constant_rectangle_material_checkerboard_oddColor")).toBeDefined(); expect(e.rectangle.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.227450980392157, 0.164705882352941, 0.619607843137255, 0.905882352941176), 1e-14); expect(e = dataSource.entities.getById("constant_rectangle_outlineColor_rgbaf")).toBeDefined(); expect(e.rectangle.outlineColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.301960784313725, 0.0352941176470588, 0.917647058823529, 0.207843137254902), 1e-14); expect(e = dataSource.entities.getById("constant_wall_positions_cartographicRadians")).toBeDefined(); expect(e.wall.positions.getValue(date)).toEqual([import__55.Cartesian3.fromRadians(0.990822494752221, 0.11729920547879, 47975), import__55.Cartesian3.fromRadians(1.22405890229697, 1.46292679641256, 13438)]); expect(e = dataSource.entities.getById("constant_wall_positions_cartographicDegrees")).toBeDefined(); expect(e.wall.positions.getValue(date)).toEqual([import__55.Cartesian3.fromDegrees(30, 24, 27738), import__55.Cartesian3.fromDegrees(14, 41, 41667)]); expect(e = dataSource.entities.getById("constant_wall_material_solidColor_color")).toBeDefined(); expect(e.wall.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.694117647058824, 0.317647058823529, 0.909803921568627, 0.501960784313725), 1e-14); expect(e = dataSource.entities.getById("material_wall_material_image")).toBeDefined(); expect(e.wall.material.image.getValue(date).url).toEqual("http://example.com/58529"); expect(e.wall.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(36340, 47245)); expect(e.wall.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(252, 63, 12, 38)); expect(e.wall.material.transparent.getValue(date)).toEqual(true); expect(e = dataSource.entities.getById("material_wall_material_grid")).toBeDefined(); expect(e.wall.material.color.getValue(date)).toEqual(import__55.Color.fromBytes(38, 183, 237, 174)); expect(e.wall.material.cellAlpha.getValue(date)).toEqual(59606); expect(e.wall.material.lineCount.getValue(date)).toEqual(new import__55.Cartesian2(3079, 31244)); expect(e.wall.material.lineThickness.getValue(date)).toEqual(new import__55.Cartesian2(32099, 44157)); expect(e.wall.material.lineOffset.getValue(date)).toEqual(new import__55.Cartesian2(13529, 1844)); expect(e = dataSource.entities.getById("material_wall_material_stripe")).toBeDefined(); expect(e.wall.material.orientation.getValue(date)).toEqual(import__55.StripeOrientation.VERTICAL); expect(e.wall.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(202, 190, 37, 215)); expect(e.wall.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(56, 107, 92, 38)); expect(e.wall.material.offset.getValue(date)).toEqual(34142); expect(e.wall.material.repeat.getValue(date)).toEqual(33528); expect(e = dataSource.entities.getById("material_wall_material_checkerboard")).toBeDefined(); expect(e.wall.material.evenColor.getValue(date)).toEqual(import__55.Color.fromBytes(187, 134, 139, 130)); expect(e.wall.material.oddColor.getValue(date)).toEqual(import__55.Color.fromBytes(177, 172, 79, 149)); expect(e.wall.material.repeat.getValue(date)).toEqual(new import__55.Cartesian2(22341, 60503)); expect(e = dataSource.entities.getById("constant_wall_material_image_color")).toBeDefined(); expect(e.wall.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.349019607843137, 0.843137254901961, 0.290196078431373, 0.0431372549019608), 1e-14); expect(e = dataSource.entities.getById("constant_wall_material_grid_color")).toBeDefined(); expect(e.wall.material.color.getValue(date)).toEqualEpsilon(new import__55.Color(0.756862745098039, 0.992156862745098, 0.992156862745098, 0.462745098039216), 1e-14); expect(e = dataSource.entities.getById("constant_wall_material_stripe_evenColor")).toBeDefined(); expect(e.wall.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.690196078431373, 0.211764705882353, 0.615686274509804, 0.627450980392157), 1e-14); expect(e = dataSource.entities.getById("constant_wall_material_stripe_oddColor")).toBeDefined(); expect(e.wall.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.968627450980392, 0.368627450980392, 0.219607843137255, 0.00392156862745098), 1e-14); expect(e = dataSource.entities.getById("constant_wall_material_checkerboard_evenColor")).toBeDefined(); expect(e.wall.material.evenColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.376470588235294, 0.396078431372549, 0.698039215686274, 0.545098039215686), 1e-14); expect(e = dataSource.entities.getById("constant_wall_material_checkerboard_oddColor")).toBeDefined(); expect(e.wall.material.oddColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.396078431372549, 0.0196078431372549, 0.27843137254902, 0.525490196078431), 1e-14); expect(e = dataSource.entities.getById("constant_wall_outlineColor_rgbaf")).toBeDefined(); expect(e.wall.outlineColor.getValue(date)).toEqualEpsilon(new import__55.Color(0.564705882352941, 0.67843137254902, 0.764705882352941, 0.811764705882353), 1e-14); expect(e = dataSource.entities.getById("constant_agi_conicSensor_intersectionColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_lateralSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_lateralSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_lateralSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_lateralSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_lateralSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_lateralSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_lateralSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_lateralSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_lateralSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_lateralSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_lateralSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_ellipsoidSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_ellipsoidSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_ellipsoidSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_ellipsoidSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_ellipsoidSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_ellipsoidSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_ellipsoidSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_ellipsoidSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_ellipsoidSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_ellipsoidSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_ellipsoidSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_ellipsoidHorizonSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_ellipsoidHorizonSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_ellipsoidHorizonSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_ellipsoidHorizonSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_ellipsoidHorizonSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_ellipsoidHorizonSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_ellipsoidHorizonSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_ellipsoidHorizonSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_ellipsoidHorizonSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_ellipsoidHorizonSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_ellipsoidHorizonSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_domeSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_domeSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_domeSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_domeSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_domeSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_domeSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_domeSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_domeSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_domeSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_domeSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_domeSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_environmentOcclusionMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_environmentOcclusionMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_environmentOcclusionMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_environmentOcclusionMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("material_conicSensor_environmentOcclusionMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_environmentOcclusionMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_environmentOcclusionMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_environmentOcclusionMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_environmentOcclusionMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_environmentOcclusionMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_conicSensor_environmentOcclusionMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_conicSensor_environmentIntersectionColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_conicSensor_viewshedVisibleColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_conicSensor_viewshedOccludedColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_customPatternSensor_directions_unitSpherical")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_customPatternSensor_directions_cartesian")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_customPatternSensor_directions_unitCartesian")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_customPatternSensor_intersectionColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_lateralSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_lateralSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_lateralSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_lateralSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_lateralSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_lateralSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_lateralSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_lateralSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_lateralSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_lateralSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_lateralSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_ellipsoidSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_ellipsoidSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_ellipsoidSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_ellipsoidSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_ellipsoidSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_ellipsoidSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_ellipsoidSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_ellipsoidSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_ellipsoidSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_ellipsoidSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_ellipsoidSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_ellipsoidHorizonSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_ellipsoidHorizonSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_ellipsoidHorizonSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_ellipsoidHorizonSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_ellipsoidHorizonSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_ellipsoidHorizonSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_ellipsoidHorizonSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_ellipsoidHorizonSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_ellipsoidHorizonSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_ellipsoidHorizonSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_ellipsoidHorizonSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_domeSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_domeSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_domeSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_domeSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_domeSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_domeSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_domeSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_domeSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_domeSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_domeSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_domeSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_environmentOcclusionMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_environmentOcclusionMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_environmentOcclusionMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_environmentOcclusionMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("material_customPatternSensor_environmentOcclusionMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_environmentOcclusionMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_environmentOcclusionMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_environmentOcclusionMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_environmentOcclusionMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_environmentOcclusionMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_customPatternSensor_environmentOcclusionMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_customPatternSensor_environmentIntersectionColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_customPatternSensor_viewshedVisibleColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_customPatternSensor_viewshedOccludedColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_rectangularSensor_intersectionColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_lateralSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_lateralSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_lateralSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_lateralSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_lateralSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_lateralSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_lateralSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_lateralSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_lateralSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_lateralSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_lateralSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_ellipsoidSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_ellipsoidSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_ellipsoidSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_ellipsoidSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_ellipsoidSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_ellipsoidSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_ellipsoidSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_ellipsoidSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_ellipsoidSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_ellipsoidSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_ellipsoidSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_ellipsoidHorizonSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_ellipsoidHorizonSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_ellipsoidHorizonSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_ellipsoidHorizonSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_ellipsoidHorizonSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_ellipsoidHorizonSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_ellipsoidHorizonSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_ellipsoidHorizonSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_ellipsoidHorizonSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_ellipsoidHorizonSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_ellipsoidHorizonSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_domeSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_domeSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_domeSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_domeSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_domeSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_domeSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_domeSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_domeSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_domeSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_domeSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_domeSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_environmentOcclusionMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_environmentOcclusionMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_environmentOcclusionMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_environmentOcclusionMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("material_rectangularSensor_environmentOcclusionMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_environmentOcclusionMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_environmentOcclusionMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_environmentOcclusionMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_environmentOcclusionMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_environmentOcclusionMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_rectangularSensor_environmentOcclusionMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_rectangularSensor_environmentIntersectionColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_rectangularSensor_viewshedVisibleColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_rectangularSensor_viewshedOccludedColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_fan_directions_unitSpherical")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_fan_directions_cartesian")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_fan_directions_unitCartesian")).toBeDefined(); expect(e = dataSource.entities.getById("constant_fan_material_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("material_fan_material_image")).toBeDefined(); expect(e = dataSource.entities.getById("material_fan_material_grid")).toBeDefined(); expect(e = dataSource.entities.getById("material_fan_material_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("material_fan_material_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("constant_fan_material_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_fan_material_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("constant_fan_material_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_fan_material_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_fan_material_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_fan_material_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_fan_outlineColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_vector_color_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_vector_direction_unitSpherical")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_vector_direction_cartesian")).toBeDefined(); expect(e = dataSource.entities.getById("constant_agi_vector_direction_unitCartesian")).toBeDefined(); expect(e = dataSource.entities.getById("constant_custom")).toBeDefined(); expect(e.properties.custom_boolean.getValue(date)).toEqual(true); expect(e.properties.custom_boundingRectangle.getValue(date)).toEqual(new import__55.BoundingRectangle(9369, 63524, 6904, 17690)); expect(e.properties.custom_cartesian.getValue(date)).toEqual(new import__55.Cartesian3(28502, 45167, 944)); expect(e.properties.custom_cartographicRadians.getValue(date)).toEqual(import__55.Cartesian3.fromRadians(0.350571264887744, 0.633274262413284, 42979)); expect(e.properties.custom_cartographicDegrees.getValue(date)).toEqual(import__55.Cartesian3.fromDegrees(18, 36, 37743)); expect(e.properties.custom_cartesian2.getValue(date)).toEqual(new import__55.Cartesian2(44825, 16303)); expect(e.properties.custom_unitCartesian.getValue(date)).toEqualEpsilon(new import__55.Cartesian3(0.77935070007851, 0.565493818550955, 0.269868907930861), 1e-14); expect(e.properties.custom_spherical.getValue(date)).toEqual(import__55.Cartesian3.fromSpherical(new import__55.Spherical(1705, 13830, 21558))); expect(e.properties.custom_unitSpherical.getValue(date)).toEqualEpsilon(import__55.Cartesian3.fromSpherical(new import__55.Spherical(59387, 15591)), 1e-14); expect(e.properties.custom_rgba.getValue(date)).toEqual(import__55.Color.fromBytes(50, 149, 175, 147)); expect(e.properties.custom_rgbaf.getValue(date)).toEqualEpsilon(new import__55.Color(0.0666666666666667, 0.0666666666666667, 0.231372549019608, 0.427450980392157), 1e-14); expect(e.properties.custom_colorBlendMode.getValue(date)).toEqual(import__55.ColorBlendMode.REPLACE); expect(e.properties.custom_cornerType.getValue(date)).toEqual(import__55.CornerType.BEVELED); expect(e.properties.custom_heightReference.getValue(date)).toEqual(import__55.HeightReference.CLAMP_TO_GROUND); expect(e.properties.custom_horizontalOrigin.getValue(date)).toEqual(import__55.HorizontalOrigin.LEFT); expect(e.properties.custom_labelStyle.getValue(date)).toEqual(import__55.LabelStyle.FILL_AND_OUTLINE); expect(e.properties.custom_number.getValue(date)).toEqual(31507); expect(e.properties.custom_nearFarScalar.getValue(date)).toEqual(new import__55.NearFarScalar(14621, 24121, 16734, 56129)); expect(e.properties.custom_unitQuaternion.getValue(date)).toEqualEpsilon(new import__55.Quaternion(0.742737937277143, 0.267679401430615, 0.507905263014791, 0.344558178514049), 1e-14); expect(e.properties.custom_shadowMode.getValue(date)).toEqual(import__55.ShadowMode.CAST_ONLY); expect(e.properties.custom_string.getValue(date)).toEqual("string41758"); expect(e.properties.custom_stripeOrientation.getValue(date)).toEqual(import__55.StripeOrientation.VERTICAL); expect(e.properties.custom_wsen.getValue(date)).toEqual(new import__55.Rectangle(1.47520917005826, 1.17615981869183, 0.973692387723505, 1.00039738410474)); expect(e.properties.custom_wsenDegrees.getValue(date)).toEqual(import__55.Rectangle.fromDegrees(5, 3, 6, 19)); expect(e.properties.custom_uri.getValue(date).url).toEqual("http://example.com/41986"); expect(e.properties.custom_verticalOrigin.getValue(date)).toEqual(import__55.VerticalOrigin.BOTTOM); expect(e = dataSource.entities.getById("ConstantPosition1")).toBeDefined(); expect(e.position.getValue(date)).toEqual(new import__55.Cartesian3(48370, 3260, 44044)); expect(e = dataSource.entities.getById("ConstantDouble1")).toBeDefined(); expect(e.billboard.scale.getValue(date)).toEqual(1155); expect(e = dataSource.entities.getById("ConstantPosition2")).toBeDefined(); expect(e.position.getValue(date)).toEqual(new import__55.Cartesian3(2599, 10, 39168)); expect(e = dataSource.entities.getById("ConstantDouble2")).toBeDefined(); expect(e.billboard.scale.getValue(date)).toEqual(16451); expect(e = dataSource.entities.getById("ConstantPosition3")).toBeDefined(); expect(e.position.getValue(date)).toEqual(new import__55.Cartesian3(1758, 45062, 8624)); expect(e = dataSource.entities.getById("ConstantDouble3")).toBeDefined(); expect(e.billboard.scale.getValue(date)).toEqual(50938); expect(e = dataSource.entities.getById("Reference")).toBeDefined(); expect(e.description.getValue(date)).toEqual(constant.description.getValue(date)); expect(e.position.getValue(date)).toEqual(constant.position.getValue(date)); expect(e.orientation.getValue(date)).toEqual(constant.orientation.getValue(date)); expect(e.viewFrom.getValue(date)).toEqual(constant.viewFrom.getValue(date)); expect(e.billboard.show.getValue(date)).toEqual(constant.billboard.show.getValue(date)); expect(e.billboard.image.getValue(date)).toEqual(constant.billboard.image.getValue(date)); expect(e.billboard.scale.getValue(date)).toEqual(constant.billboard.scale.getValue(date)); expect(e.billboard.pixelOffset.getValue(date)).toEqual(constant.billboard.pixelOffset.getValue(date)); expect(e.billboard.eyeOffset.getValue(date)).toEqual(constant.billboard.eyeOffset.getValue(date)); expect(e.billboard.horizontalOrigin.getValue(date)).toEqual(constant.billboard.horizontalOrigin.getValue(date)); expect(e.billboard.verticalOrigin.getValue(date)).toEqual(constant.billboard.verticalOrigin.getValue(date)); expect(e.billboard.heightReference.getValue(date)).toEqual(constant.billboard.heightReference.getValue(date)); expect(e.billboard.color.getValue(date)).toEqual(constant.billboard.color.getValue(date)); expect(e.billboard.rotation.getValue(date)).toEqual(constant.billboard.rotation.getValue(date)); expect(e.billboard.alignedAxis.getValue(date)).toEqual(constant.billboard.alignedAxis.getValue(date)); expect(e.billboard.sizeInMeters.getValue(date)).toEqual(constant.billboard.sizeInMeters.getValue(date)); expect(e.billboard.width.getValue(date)).toEqual(constant.billboard.width.getValue(date)); expect(e.billboard.height.getValue(date)).toEqual(constant.billboard.height.getValue(date)); expect(e.billboard.scaleByDistance.getValue(date)).toEqual(constant.billboard.scaleByDistance.getValue(date)); expect(e.billboard.translucencyByDistance.getValue(date)).toEqual(constant.billboard.translucencyByDistance.getValue(date)); expect(e.billboard.pixelOffsetScaleByDistance.getValue(date)).toEqual(constant.billboard.pixelOffsetScaleByDistance.getValue(date)); expect(e.billboard.imageSubRegion.getValue(date)).toEqual(constant.billboard.imageSubRegion.getValue(date)); expect(e.billboard.distanceDisplayCondition.getValue(date)).toEqual(constant.billboard.distanceDisplayCondition.getValue(date)); expect(e.billboard.disableDepthTestDistance.getValue(date)).toEqual(constant.billboard.disableDepthTestDistance.getValue(date)); expect(e.box.show.getValue(date)).toEqual(constant.box.show.getValue(date)); expect(e.box.dimensions.getValue(date)).toEqual(constant.box.dimensions.getValue(date)); expect(e.box.heightReference.getValue(date)).toEqual(constant.box.heightReference.getValue(date)); expect(e.box.fill.getValue(date)).toEqual(constant.box.fill.getValue(date)); expect(e.box.material.color.getValue(date)).toEqual(constant.box.material.color.getValue(date)); expect(e.box.outline.getValue(date)).toEqual(constant.box.outline.getValue(date)); expect(e.box.outlineColor.getValue(date)).toEqual(constant.box.outlineColor.getValue(date)); expect(e.box.outlineWidth.getValue(date)).toEqual(constant.box.outlineWidth.getValue(date)); expect(e.box.shadows.getValue(date)).toEqual(constant.box.shadows.getValue(date)); expect(e.box.distanceDisplayCondition.getValue(date)).toEqual(constant.box.distanceDisplayCondition.getValue(date)); expect(e.corridor.show.getValue(date)).toEqual(constant.corridor.show.getValue(date)); expect(e.corridor.positions.getValue(date)).toEqual([dataSource.entities.getById("ConstantPosition1").position.getValue(date), dataSource.entities.getById("ConstantPosition2").position.getValue(date)]); expect(e.corridor.width.getValue(date)).toEqual(constant.corridor.width.getValue(date)); expect(e.corridor.height.getValue(date)).toEqual(constant.corridor.height.getValue(date)); expect(e.corridor.heightReference.getValue(date)).toEqual(constant.corridor.heightReference.getValue(date)); expect(e.corridor.extrudedHeight.getValue(date)).toEqual(constant.corridor.extrudedHeight.getValue(date)); expect(e.corridor.extrudedHeightReference.getValue(date)).toEqual(constant.corridor.extrudedHeightReference.getValue(date)); expect(e.corridor.cornerType.getValue(date)).toEqual(constant.corridor.cornerType.getValue(date)); expect(e.corridor.granularity.getValue(date)).toEqual(constant.corridor.granularity.getValue(date)); expect(e.corridor.fill.getValue(date)).toEqual(constant.corridor.fill.getValue(date)); expect(e.corridor.material.color.getValue(date)).toEqual(constant.corridor.material.color.getValue(date)); expect(e.corridor.outline.getValue(date)).toEqual(constant.corridor.outline.getValue(date)); expect(e.corridor.outlineColor.getValue(date)).toEqual(constant.corridor.outlineColor.getValue(date)); expect(e.corridor.outlineWidth.getValue(date)).toEqual(constant.corridor.outlineWidth.getValue(date)); expect(e.corridor.shadows.getValue(date)).toEqual(constant.corridor.shadows.getValue(date)); expect(e.corridor.distanceDisplayCondition.getValue(date)).toEqual(constant.corridor.distanceDisplayCondition.getValue(date)); expect(e.corridor.classificationType.getValue(date)).toEqual(constant.corridor.classificationType.getValue(date)); expect(e.corridor.zIndex.getValue(date)).toEqual(constant.corridor.zIndex.getValue(date)); expect(e.cylinder.show.getValue(date)).toEqual(constant.cylinder.show.getValue(date)); expect(e.cylinder.length.getValue(date)).toEqual(constant.cylinder.length.getValue(date)); expect(e.cylinder.topRadius.getValue(date)).toEqual(constant.cylinder.topRadius.getValue(date)); expect(e.cylinder.bottomRadius.getValue(date)).toEqual(constant.cylinder.bottomRadius.getValue(date)); expect(e.cylinder.heightReference.getValue(date)).toEqual(constant.cylinder.heightReference.getValue(date)); expect(e.cylinder.fill.getValue(date)).toEqual(constant.cylinder.fill.getValue(date)); expect(e.cylinder.material.color.getValue(date)).toEqual(constant.cylinder.material.color.getValue(date)); expect(e.cylinder.outline.getValue(date)).toEqual(constant.cylinder.outline.getValue(date)); expect(e.cylinder.outlineColor.getValue(date)).toEqual(constant.cylinder.outlineColor.getValue(date)); expect(e.cylinder.outlineWidth.getValue(date)).toEqual(constant.cylinder.outlineWidth.getValue(date)); expect(e.cylinder.numberOfVerticalLines.getValue(date)).toEqual(constant.cylinder.numberOfVerticalLines.getValue(date)); expect(e.cylinder.slices.getValue(date)).toEqual(constant.cylinder.slices.getValue(date)); expect(e.cylinder.shadows.getValue(date)).toEqual(constant.cylinder.shadows.getValue(date)); expect(e.cylinder.distanceDisplayCondition.getValue(date)).toEqual(constant.cylinder.distanceDisplayCondition.getValue(date)); expect(e.ellipse.show.getValue(date)).toEqual(constant.ellipse.show.getValue(date)); expect(e.ellipse.semiMajorAxis.getValue(date)).toEqual(constant.ellipse.semiMajorAxis.getValue(date)); expect(e.ellipse.semiMinorAxis.getValue(date)).toEqual(constant.ellipse.semiMinorAxis.getValue(date)); expect(e.ellipse.height.getValue(date)).toEqual(constant.ellipse.height.getValue(date)); expect(e.ellipse.heightReference.getValue(date)).toEqual(constant.ellipse.heightReference.getValue(date)); expect(e.ellipse.extrudedHeight.getValue(date)).toEqual(constant.ellipse.extrudedHeight.getValue(date)); expect(e.ellipse.extrudedHeightReference.getValue(date)).toEqual(constant.ellipse.extrudedHeightReference.getValue(date)); expect(e.ellipse.rotation.getValue(date)).toEqual(constant.ellipse.rotation.getValue(date)); expect(e.ellipse.stRotation.getValue(date)).toEqual(constant.ellipse.stRotation.getValue(date)); expect(e.ellipse.granularity.getValue(date)).toEqual(constant.ellipse.granularity.getValue(date)); expect(e.ellipse.fill.getValue(date)).toEqual(constant.ellipse.fill.getValue(date)); expect(e.ellipse.material.color.getValue(date)).toEqual(constant.ellipse.material.color.getValue(date)); expect(e.ellipse.outline.getValue(date)).toEqual(constant.ellipse.outline.getValue(date)); expect(e.ellipse.outlineColor.getValue(date)).toEqual(constant.ellipse.outlineColor.getValue(date)); expect(e.ellipse.outlineWidth.getValue(date)).toEqual(constant.ellipse.outlineWidth.getValue(date)); expect(e.ellipse.numberOfVerticalLines.getValue(date)).toEqual(constant.ellipse.numberOfVerticalLines.getValue(date)); expect(e.ellipse.shadows.getValue(date)).toEqual(constant.ellipse.shadows.getValue(date)); expect(e.ellipse.distanceDisplayCondition.getValue(date)).toEqual(constant.ellipse.distanceDisplayCondition.getValue(date)); expect(e.ellipse.classificationType.getValue(date)).toEqual(constant.ellipse.classificationType.getValue(date)); expect(e.ellipse.zIndex.getValue(date)).toEqual(constant.ellipse.zIndex.getValue(date)); expect(e.ellipsoid.show.getValue(date)).toEqual(constant.ellipsoid.show.getValue(date)); expect(e.ellipsoid.radii.getValue(date)).toEqual(constant.ellipsoid.radii.getValue(date)); expect(e.ellipsoid.innerRadii.getValue(date)).toEqual(constant.ellipsoid.innerRadii.getValue(date)); expect(e.ellipsoid.minimumClock.getValue(date)).toEqual(constant.ellipsoid.minimumClock.getValue(date)); expect(e.ellipsoid.maximumClock.getValue(date)).toEqual(constant.ellipsoid.maximumClock.getValue(date)); expect(e.ellipsoid.minimumCone.getValue(date)).toEqual(constant.ellipsoid.minimumCone.getValue(date)); expect(e.ellipsoid.maximumCone.getValue(date)).toEqual(constant.ellipsoid.maximumCone.getValue(date)); expect(e.ellipsoid.heightReference.getValue(date)).toEqual(constant.ellipsoid.heightReference.getValue(date)); expect(e.ellipsoid.fill.getValue(date)).toEqual(constant.ellipsoid.fill.getValue(date)); expect(e.ellipsoid.material.color.getValue(date)).toEqual(constant.ellipsoid.material.color.getValue(date)); expect(e.ellipsoid.outline.getValue(date)).toEqual(constant.ellipsoid.outline.getValue(date)); expect(e.ellipsoid.outlineColor.getValue(date)).toEqual(constant.ellipsoid.outlineColor.getValue(date)); expect(e.ellipsoid.outlineWidth.getValue(date)).toEqual(constant.ellipsoid.outlineWidth.getValue(date)); expect(e.ellipsoid.stackPartitions.getValue(date)).toEqual(constant.ellipsoid.stackPartitions.getValue(date)); expect(e.ellipsoid.slicePartitions.getValue(date)).toEqual(constant.ellipsoid.slicePartitions.getValue(date)); expect(e.ellipsoid.subdivisions.getValue(date)).toEqual(constant.ellipsoid.subdivisions.getValue(date)); expect(e.ellipsoid.shadows.getValue(date)).toEqual(constant.ellipsoid.shadows.getValue(date)); expect(e.ellipsoid.distanceDisplayCondition.getValue(date)).toEqual(constant.ellipsoid.distanceDisplayCondition.getValue(date)); expect(e.label.show.getValue(date)).toEqual(constant.label.show.getValue(date)); expect(e.label.text.getValue(date)).toEqual(constant.label.text.getValue(date)); expect(e.label.font.getValue(date)).toEqual(constant.label.font.getValue(date)); expect(e.label.style.getValue(date)).toEqual(constant.label.style.getValue(date)); expect(e.label.scale.getValue(date)).toEqual(constant.label.scale.getValue(date)); expect(e.label.showBackground.getValue(date)).toEqual(constant.label.showBackground.getValue(date)); expect(e.label.backgroundColor.getValue(date)).toEqual(constant.label.backgroundColor.getValue(date)); expect(e.label.backgroundPadding.getValue(date)).toEqual(constant.label.backgroundPadding.getValue(date)); expect(e.label.pixelOffset.getValue(date)).toEqual(constant.label.pixelOffset.getValue(date)); expect(e.label.eyeOffset.getValue(date)).toEqual(constant.label.eyeOffset.getValue(date)); expect(e.label.horizontalOrigin.getValue(date)).toEqual(constant.label.horizontalOrigin.getValue(date)); expect(e.label.verticalOrigin.getValue(date)).toEqual(constant.label.verticalOrigin.getValue(date)); expect(e.label.heightReference.getValue(date)).toEqual(constant.label.heightReference.getValue(date)); expect(e.label.fillColor.getValue(date)).toEqual(constant.label.fillColor.getValue(date)); expect(e.label.outlineColor.getValue(date)).toEqual(constant.label.outlineColor.getValue(date)); expect(e.label.outlineWidth.getValue(date)).toEqual(constant.label.outlineWidth.getValue(date)); expect(e.label.translucencyByDistance.getValue(date)).toEqual(constant.label.translucencyByDistance.getValue(date)); expect(e.label.pixelOffsetScaleByDistance.getValue(date)).toEqual(constant.label.pixelOffsetScaleByDistance.getValue(date)); expect(e.label.scaleByDistance.getValue(date)).toEqual(constant.label.scaleByDistance.getValue(date)); expect(e.label.distanceDisplayCondition.getValue(date)).toEqual(constant.label.distanceDisplayCondition.getValue(date)); expect(e.label.disableDepthTestDistance.getValue(date)).toEqual(constant.label.disableDepthTestDistance.getValue(date)); expect(e.model.show.getValue(date)).toEqual(constant.model.show.getValue(date)); expect(e.model.uri.getValue(date)).toEqual(constant.model.uri.getValue(date)); expect(e.model.scale.getValue(date)).toEqual(constant.model.scale.getValue(date)); expect(e.model.minimumPixelSize.getValue(date)).toEqual(constant.model.minimumPixelSize.getValue(date)); expect(e.model.maximumScale.getValue(date)).toEqual(constant.model.maximumScale.getValue(date)); expect(e.model.incrementallyLoadTextures.getValue(date)).toEqual(constant.model.incrementallyLoadTextures.getValue(date)); expect(e.model.runAnimations.getValue(date)).toEqual(constant.model.runAnimations.getValue(date)); expect(e.model.shadows.getValue(date)).toEqual(constant.model.shadows.getValue(date)); expect(e.model.heightReference.getValue(date)).toEqual(constant.model.heightReference.getValue(date)); expect(e.model.silhouetteColor.getValue(date)).toEqual(constant.model.silhouetteColor.getValue(date)); expect(e.model.silhouetteSize.getValue(date)).toEqual(constant.model.silhouetteSize.getValue(date)); expect(e.model.color.getValue(date)).toEqual(constant.model.color.getValue(date)); expect(e.model.colorBlendMode.getValue(date)).toEqual(constant.model.colorBlendMode.getValue(date)); expect(e.model.colorBlendAmount.getValue(date)).toEqual(constant.model.colorBlendAmount.getValue(date)); expect(e.model.distanceDisplayCondition.getValue(date)).toEqual(constant.model.distanceDisplayCondition.getValue(date)); expect(e.model.nodeTransformations.referenceProp.translation.getValue(date)).toEqual(constant.model.nodeTransformations.prop.translation.getValue(date)); expect(e.model.nodeTransformations.referenceProp.rotation.getValue(date)).toEqual(constant.model.nodeTransformations.prop.rotation.getValue(date)); expect(e.model.nodeTransformations.referenceProp.scale.getValue(date)).toEqual(constant.model.nodeTransformations.prop.scale.getValue(date)); expect(e.model.articulations.referenceProp.getValue(date)).toEqual(constant.model.articulations.prop.getValue(date)); expect(e.path.show.getValue(date)).toEqual(constant.path.show.getValue(date)); expect(e.path.leadTime.getValue(date)).toEqual(constant.path.leadTime.getValue(date)); expect(e.path.trailTime.getValue(date)).toEqual(constant.path.trailTime.getValue(date)); expect(e.path.width.getValue(date)).toEqual(constant.path.width.getValue(date)); expect(e.path.resolution.getValue(date)).toEqual(constant.path.resolution.getValue(date)); expect(e.path.material.color.getValue(date)).toEqual(constant.path.material.color.getValue(date)); expect(e.path.distanceDisplayCondition.getValue(date)).toEqual(constant.path.distanceDisplayCondition.getValue(date)); expect(e.point.show.getValue(date)).toEqual(constant.point.show.getValue(date)); expect(e.point.pixelSize.getValue(date)).toEqual(constant.point.pixelSize.getValue(date)); expect(e.point.heightReference.getValue(date)).toEqual(constant.point.heightReference.getValue(date)); expect(e.point.color.getValue(date)).toEqual(constant.point.color.getValue(date)); expect(e.point.outlineColor.getValue(date)).toEqual(constant.point.outlineColor.getValue(date)); expect(e.point.outlineWidth.getValue(date)).toEqual(constant.point.outlineWidth.getValue(date)); expect(e.point.scaleByDistance.getValue(date)).toEqual(constant.point.scaleByDistance.getValue(date)); expect(e.point.translucencyByDistance.getValue(date)).toEqual(constant.point.translucencyByDistance.getValue(date)); expect(e.point.distanceDisplayCondition.getValue(date)).toEqual(constant.point.distanceDisplayCondition.getValue(date)); expect(e.point.disableDepthTestDistance.getValue(date)).toEqual(constant.point.disableDepthTestDistance.getValue(date)); expect(e.polygon.show.getValue(date)).toEqual(constant.polygon.show.getValue(date)); expect(e.polygon.hierarchy.getValue(date).positions).toEqual([dataSource.entities.getById("ConstantPosition1").position.getValue(date), dataSource.entities.getById("ConstantPosition2").position.getValue(date)]); expect(e.polygon.hierarchy.getValue(date).holes).toEqual([new import__55.PolygonHierarchy([dataSource.entities.getById("ConstantPosition1").position.getValue(date), dataSource.entities.getById("ConstantPosition2").position.getValue(date), dataSource.entities.getById("ConstantPosition3").position.getValue(date)])]); expect(e.polygon.arcType.getValue(date)).toEqual(constant.polygon.arcType.getValue(date)); expect(e.polygon.height.getValue(date)).toEqual(constant.polygon.height.getValue(date)); expect(e.polygon.heightReference.getValue(date)).toEqual(constant.polygon.heightReference.getValue(date)); expect(e.polygon.extrudedHeight.getValue(date)).toEqual(constant.polygon.extrudedHeight.getValue(date)); expect(e.polygon.extrudedHeightReference.getValue(date)).toEqual(constant.polygon.extrudedHeightReference.getValue(date)); expect(e.polygon.stRotation.getValue(date)).toEqual(constant.polygon.stRotation.getValue(date)); expect(e.polygon.granularity.getValue(date)).toEqual(constant.polygon.granularity.getValue(date)); expect(e.polygon.fill.getValue(date)).toEqual(constant.polygon.fill.getValue(date)); expect(e.polygon.material.color.getValue(date)).toEqual(constant.polygon.material.color.getValue(date)); expect(e.polygon.outline.getValue(date)).toEqual(constant.polygon.outline.getValue(date)); expect(e.polygon.outlineColor.getValue(date)).toEqual(constant.polygon.outlineColor.getValue(date)); expect(e.polygon.outlineWidth.getValue(date)).toEqual(constant.polygon.outlineWidth.getValue(date)); expect(e.polygon.perPositionHeight.getValue(date)).toEqual(constant.polygon.perPositionHeight.getValue(date)); expect(e.polygon.closeTop.getValue(date)).toEqual(constant.polygon.closeTop.getValue(date)); expect(e.polygon.closeBottom.getValue(date)).toEqual(constant.polygon.closeBottom.getValue(date)); expect(e.polygon.shadows.getValue(date)).toEqual(constant.polygon.shadows.getValue(date)); expect(e.polygon.distanceDisplayCondition.getValue(date)).toEqual(constant.polygon.distanceDisplayCondition.getValue(date)); expect(e.polygon.classificationType.getValue(date)).toEqual(constant.polygon.classificationType.getValue(date)); expect(e.polygon.zIndex.getValue(date)).toEqual(constant.polygon.zIndex.getValue(date)); expect(e.polyline.show.getValue(date)).toEqual(constant.polyline.show.getValue(date)); expect(e.polyline.positions.getValue(date)).toEqual([dataSource.entities.getById("ConstantPosition1").position.getValue(date), dataSource.entities.getById("ConstantPosition2").position.getValue(date)]); expect(e.polyline.arcType.getValue(date)).toEqual(constant.polyline.arcType.getValue(date)); expect(e.polyline.width.getValue(date)).toEqual(constant.polyline.width.getValue(date)); expect(e.polyline.granularity.getValue(date)).toEqual(constant.polyline.granularity.getValue(date)); expect(e.polyline.material.color.getValue(date)).toEqual(constant.polyline.material.color.getValue(date)); expect(e.polyline.shadows.getValue(date)).toEqual(constant.polyline.shadows.getValue(date)); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqual(constant.polyline.depthFailMaterial.color.getValue(date)); expect(e.polyline.distanceDisplayCondition.getValue(date)).toEqual(constant.polyline.distanceDisplayCondition.getValue(date)); expect(e.polyline.clampToGround.getValue(date)).toEqual(constant.polyline.clampToGround.getValue(date)); expect(e.polyline.classificationType.getValue(date)).toEqual(constant.polyline.classificationType.getValue(date)); expect(e.polyline.zIndex.getValue(date)).toEqual(constant.polyline.zIndex.getValue(date)); expect(e.polylineVolume.show.getValue(date)).toEqual(constant.polylineVolume.show.getValue(date)); expect(e.polylineVolume.positions.getValue(date)).toEqual([dataSource.entities.getById("ConstantPosition1").position.getValue(date), dataSource.entities.getById("ConstantPosition2").position.getValue(date)]); expect(e.polylineVolume.cornerType.getValue(date)).toEqual(constant.polylineVolume.cornerType.getValue(date)); expect(e.polylineVolume.granularity.getValue(date)).toEqual(constant.polylineVolume.granularity.getValue(date)); expect(e.polylineVolume.fill.getValue(date)).toEqual(constant.polylineVolume.fill.getValue(date)); expect(e.polylineVolume.material.color.getValue(date)).toEqual(constant.polylineVolume.material.color.getValue(date)); expect(e.polylineVolume.outline.getValue(date)).toEqual(constant.polylineVolume.outline.getValue(date)); expect(e.polylineVolume.outlineColor.getValue(date)).toEqual(constant.polylineVolume.outlineColor.getValue(date)); expect(e.polylineVolume.outlineWidth.getValue(date)).toEqual(constant.polylineVolume.outlineWidth.getValue(date)); expect(e.polylineVolume.shadows.getValue(date)).toEqual(constant.polylineVolume.shadows.getValue(date)); expect(e.polylineVolume.distanceDisplayCondition.getValue(date)).toEqual(constant.polylineVolume.distanceDisplayCondition.getValue(date)); expect(e.rectangle.show.getValue(date)).toEqual(constant.rectangle.show.getValue(date)); expect(e.rectangle.coordinates.getValue(date)).toEqual(constant.rectangle.coordinates.getValue(date)); expect(e.rectangle.height.getValue(date)).toEqual(constant.rectangle.height.getValue(date)); expect(e.rectangle.heightReference.getValue(date)).toEqual(constant.rectangle.heightReference.getValue(date)); expect(e.rectangle.extrudedHeight.getValue(date)).toEqual(constant.rectangle.extrudedHeight.getValue(date)); expect(e.rectangle.extrudedHeightReference.getValue(date)).toEqual(constant.rectangle.extrudedHeightReference.getValue(date)); expect(e.rectangle.rotation.getValue(date)).toEqual(constant.rectangle.rotation.getValue(date)); expect(e.rectangle.stRotation.getValue(date)).toEqual(constant.rectangle.stRotation.getValue(date)); expect(e.rectangle.granularity.getValue(date)).toEqual(constant.rectangle.granularity.getValue(date)); expect(e.rectangle.fill.getValue(date)).toEqual(constant.rectangle.fill.getValue(date)); expect(e.rectangle.material.color.getValue(date)).toEqual(constant.rectangle.material.color.getValue(date)); expect(e.rectangle.outline.getValue(date)).toEqual(constant.rectangle.outline.getValue(date)); expect(e.rectangle.outlineColor.getValue(date)).toEqual(constant.rectangle.outlineColor.getValue(date)); expect(e.rectangle.outlineWidth.getValue(date)).toEqual(constant.rectangle.outlineWidth.getValue(date)); expect(e.rectangle.shadows.getValue(date)).toEqual(constant.rectangle.shadows.getValue(date)); expect(e.rectangle.distanceDisplayCondition.getValue(date)).toEqual(constant.rectangle.distanceDisplayCondition.getValue(date)); expect(e.rectangle.classificationType.getValue(date)).toEqual(constant.rectangle.classificationType.getValue(date)); expect(e.rectangle.zIndex.getValue(date)).toEqual(constant.rectangle.zIndex.getValue(date)); expect(e.tileset.show.getValue(date)).toEqual(constant.tileset.show.getValue(date)); expect(e.tileset.uri.getValue(date)).toEqual(constant.tileset.uri.getValue(date)); expect(e.tileset.maximumScreenSpaceError.getValue(date)).toEqual(constant.tileset.maximumScreenSpaceError.getValue(date)); expect(e.wall.show.getValue(date)).toEqual(constant.wall.show.getValue(date)); expect(e.wall.positions.getValue(date)).toEqual([dataSource.entities.getById("ConstantPosition1").position.getValue(date), dataSource.entities.getById("ConstantPosition2").position.getValue(date)]); expect(e.wall.minimumHeights.getValue(date)).toEqual([dataSource.entities.getById("ConstantDouble1").billboard.scale.getValue(date), dataSource.entities.getById("ConstantDouble2").billboard.scale.getValue(date)]); expect(e.wall.maximumHeights.getValue(date)).toEqual([dataSource.entities.getById("ConstantDouble1").billboard.scale.getValue(date), dataSource.entities.getById("ConstantDouble2").billboard.scale.getValue(date)]); expect(e.wall.granularity.getValue(date)).toEqual(constant.wall.granularity.getValue(date)); expect(e.wall.fill.getValue(date)).toEqual(constant.wall.fill.getValue(date)); expect(e.wall.material.color.getValue(date)).toEqual(constant.wall.material.color.getValue(date)); expect(e.wall.outline.getValue(date)).toEqual(constant.wall.outline.getValue(date)); expect(e.wall.outlineColor.getValue(date)).toEqual(constant.wall.outlineColor.getValue(date)); expect(e.wall.outlineWidth.getValue(date)).toEqual(constant.wall.outlineWidth.getValue(date)); expect(e.wall.shadows.getValue(date)).toEqual(constant.wall.shadows.getValue(date)); expect(e.wall.distanceDisplayCondition.getValue(date)).toEqual(constant.wall.distanceDisplayCondition.getValue(date)); expect(e = dataSource.entities.getById("reference_box_material_image")).toBeDefined(); expect(e.box.material.image.getValue(date)).toEqual(dataSource.entities.getById("material_box_material_image").box.material.image.getValue(date)); expect(e.box.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_box_material_image").box.material.repeat.getValue(date)); expect(e.box.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_box_material_image").box.material.color.getValue(date)); expect(e.box.material.transparent.getValue(date)).toEqual(dataSource.entities.getById("material_box_material_image").box.material.transparent.getValue(date)); expect(e = dataSource.entities.getById("reference_box_material_grid")).toBeDefined(); expect(e.box.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_box_material_grid").box.material.color.getValue(date)); expect(e.box.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById("material_box_material_grid").box.material.cellAlpha.getValue(date)); expect(e.box.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById("material_box_material_grid").box.material.lineCount.getValue(date)); expect(e.box.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById("material_box_material_grid").box.material.lineThickness.getValue(date)); expect(e.box.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById("material_box_material_grid").box.material.lineOffset.getValue(date)); expect(e = dataSource.entities.getById("reference_box_material_stripe")).toBeDefined(); expect(e.box.material.orientation.getValue(date)).toEqual(dataSource.entities.getById("material_box_material_stripe").box.material.orientation.getValue(date)); expect(e.box.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_box_material_stripe").box.material.evenColor.getValue(date)); expect(e.box.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_box_material_stripe").box.material.oddColor.getValue(date)); expect(e.box.material.offset.getValue(date)).toEqual(dataSource.entities.getById("material_box_material_stripe").box.material.offset.getValue(date)); expect(e.box.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_box_material_stripe").box.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_box_material_checkerboard")).toBeDefined(); expect(e.box.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_box_material_checkerboard").box.material.evenColor.getValue(date)); expect(e.box.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_box_material_checkerboard").box.material.oddColor.getValue(date)); expect(e.box.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_box_material_checkerboard").box.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_corridor_material_image")).toBeDefined(); expect(e.corridor.material.image.getValue(date)).toEqual(dataSource.entities.getById("material_corridor_material_image").corridor.material.image.getValue(date)); expect(e.corridor.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_corridor_material_image").corridor.material.repeat.getValue(date)); expect(e.corridor.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_corridor_material_image").corridor.material.color.getValue(date)); expect(e.corridor.material.transparent.getValue(date)).toEqual(dataSource.entities.getById("material_corridor_material_image").corridor.material.transparent.getValue(date)); expect(e = dataSource.entities.getById("reference_corridor_material_grid")).toBeDefined(); expect(e.corridor.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_corridor_material_grid").corridor.material.color.getValue(date)); expect(e.corridor.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById("material_corridor_material_grid").corridor.material.cellAlpha.getValue(date)); expect(e.corridor.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById("material_corridor_material_grid").corridor.material.lineCount.getValue(date)); expect(e.corridor.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById("material_corridor_material_grid").corridor.material.lineThickness.getValue(date)); expect(e.corridor.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById("material_corridor_material_grid").corridor.material.lineOffset.getValue(date)); expect(e = dataSource.entities.getById("reference_corridor_material_stripe")).toBeDefined(); expect(e.corridor.material.orientation.getValue(date)).toEqual(dataSource.entities.getById("material_corridor_material_stripe").corridor.material.orientation.getValue(date)); expect(e.corridor.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_corridor_material_stripe").corridor.material.evenColor.getValue(date)); expect(e.corridor.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_corridor_material_stripe").corridor.material.oddColor.getValue(date)); expect(e.corridor.material.offset.getValue(date)).toEqual(dataSource.entities.getById("material_corridor_material_stripe").corridor.material.offset.getValue(date)); expect(e.corridor.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_corridor_material_stripe").corridor.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_corridor_material_checkerboard")).toBeDefined(); expect(e.corridor.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_corridor_material_checkerboard").corridor.material.evenColor.getValue(date)); expect(e.corridor.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_corridor_material_checkerboard").corridor.material.oddColor.getValue(date)); expect(e.corridor.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_corridor_material_checkerboard").corridor.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_cylinder_material_image")).toBeDefined(); expect(e.cylinder.material.image.getValue(date)).toEqual(dataSource.entities.getById("material_cylinder_material_image").cylinder.material.image.getValue(date)); expect(e.cylinder.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_cylinder_material_image").cylinder.material.repeat.getValue(date)); expect(e.cylinder.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_cylinder_material_image").cylinder.material.color.getValue(date)); expect(e.cylinder.material.transparent.getValue(date)).toEqual(dataSource.entities.getById("material_cylinder_material_image").cylinder.material.transparent.getValue(date)); expect(e = dataSource.entities.getById("reference_cylinder_material_grid")).toBeDefined(); expect(e.cylinder.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_cylinder_material_grid").cylinder.material.color.getValue(date)); expect(e.cylinder.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById("material_cylinder_material_grid").cylinder.material.cellAlpha.getValue(date)); expect(e.cylinder.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById("material_cylinder_material_grid").cylinder.material.lineCount.getValue(date)); expect(e.cylinder.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById("material_cylinder_material_grid").cylinder.material.lineThickness.getValue(date)); expect(e.cylinder.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById("material_cylinder_material_grid").cylinder.material.lineOffset.getValue(date)); expect(e = dataSource.entities.getById("reference_cylinder_material_stripe")).toBeDefined(); expect(e.cylinder.material.orientation.getValue(date)).toEqual(dataSource.entities.getById("material_cylinder_material_stripe").cylinder.material.orientation.getValue(date)); expect(e.cylinder.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_cylinder_material_stripe").cylinder.material.evenColor.getValue(date)); expect(e.cylinder.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_cylinder_material_stripe").cylinder.material.oddColor.getValue(date)); expect(e.cylinder.material.offset.getValue(date)).toEqual(dataSource.entities.getById("material_cylinder_material_stripe").cylinder.material.offset.getValue(date)); expect(e.cylinder.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_cylinder_material_stripe").cylinder.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_cylinder_material_checkerboard")).toBeDefined(); expect(e.cylinder.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_cylinder_material_checkerboard").cylinder.material.evenColor.getValue(date)); expect(e.cylinder.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_cylinder_material_checkerboard").cylinder.material.oddColor.getValue(date)); expect(e.cylinder.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_cylinder_material_checkerboard").cylinder.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_ellipse_material_image")).toBeDefined(); expect(e.ellipse.material.image.getValue(date)).toEqual(dataSource.entities.getById("material_ellipse_material_image").ellipse.material.image.getValue(date)); expect(e.ellipse.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_ellipse_material_image").ellipse.material.repeat.getValue(date)); expect(e.ellipse.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_ellipse_material_image").ellipse.material.color.getValue(date)); expect(e.ellipse.material.transparent.getValue(date)).toEqual(dataSource.entities.getById("material_ellipse_material_image").ellipse.material.transparent.getValue(date)); expect(e = dataSource.entities.getById("reference_ellipse_material_grid")).toBeDefined(); expect(e.ellipse.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_ellipse_material_grid").ellipse.material.color.getValue(date)); expect(e.ellipse.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById("material_ellipse_material_grid").ellipse.material.cellAlpha.getValue(date)); expect(e.ellipse.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById("material_ellipse_material_grid").ellipse.material.lineCount.getValue(date)); expect(e.ellipse.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById("material_ellipse_material_grid").ellipse.material.lineThickness.getValue(date)); expect(e.ellipse.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById("material_ellipse_material_grid").ellipse.material.lineOffset.getValue(date)); expect(e = dataSource.entities.getById("reference_ellipse_material_stripe")).toBeDefined(); expect(e.ellipse.material.orientation.getValue(date)).toEqual(dataSource.entities.getById("material_ellipse_material_stripe").ellipse.material.orientation.getValue(date)); expect(e.ellipse.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_ellipse_material_stripe").ellipse.material.evenColor.getValue(date)); expect(e.ellipse.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_ellipse_material_stripe").ellipse.material.oddColor.getValue(date)); expect(e.ellipse.material.offset.getValue(date)).toEqual(dataSource.entities.getById("material_ellipse_material_stripe").ellipse.material.offset.getValue(date)); expect(e.ellipse.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_ellipse_material_stripe").ellipse.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_ellipse_material_checkerboard")).toBeDefined(); expect(e.ellipse.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_ellipse_material_checkerboard").ellipse.material.evenColor.getValue(date)); expect(e.ellipse.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_ellipse_material_checkerboard").ellipse.material.oddColor.getValue(date)); expect(e.ellipse.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_ellipse_material_checkerboard").ellipse.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_ellipsoid_material_image")).toBeDefined(); expect(e.ellipsoid.material.image.getValue(date)).toEqual(dataSource.entities.getById("material_ellipsoid_material_image").ellipsoid.material.image.getValue(date)); expect(e.ellipsoid.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_ellipsoid_material_image").ellipsoid.material.repeat.getValue(date)); expect(e.ellipsoid.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_ellipsoid_material_image").ellipsoid.material.color.getValue(date)); expect(e.ellipsoid.material.transparent.getValue(date)).toEqual(dataSource.entities.getById("material_ellipsoid_material_image").ellipsoid.material.transparent.getValue(date)); expect(e = dataSource.entities.getById("reference_ellipsoid_material_grid")).toBeDefined(); expect(e.ellipsoid.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_ellipsoid_material_grid").ellipsoid.material.color.getValue(date)); expect(e.ellipsoid.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById("material_ellipsoid_material_grid").ellipsoid.material.cellAlpha.getValue(date)); expect(e.ellipsoid.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById("material_ellipsoid_material_grid").ellipsoid.material.lineCount.getValue(date)); expect(e.ellipsoid.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById("material_ellipsoid_material_grid").ellipsoid.material.lineThickness.getValue(date)); expect(e.ellipsoid.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById("material_ellipsoid_material_grid").ellipsoid.material.lineOffset.getValue(date)); expect(e = dataSource.entities.getById("reference_ellipsoid_material_stripe")).toBeDefined(); expect(e.ellipsoid.material.orientation.getValue(date)).toEqual(dataSource.entities.getById("material_ellipsoid_material_stripe").ellipsoid.material.orientation.getValue(date)); expect(e.ellipsoid.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_ellipsoid_material_stripe").ellipsoid.material.evenColor.getValue(date)); expect(e.ellipsoid.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_ellipsoid_material_stripe").ellipsoid.material.oddColor.getValue(date)); expect(e.ellipsoid.material.offset.getValue(date)).toEqual(dataSource.entities.getById("material_ellipsoid_material_stripe").ellipsoid.material.offset.getValue(date)); expect(e.ellipsoid.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_ellipsoid_material_stripe").ellipsoid.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_ellipsoid_material_checkerboard")).toBeDefined(); expect(e.ellipsoid.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_ellipsoid_material_checkerboard").ellipsoid.material.evenColor.getValue(date)); expect(e.ellipsoid.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_ellipsoid_material_checkerboard").ellipsoid.material.oddColor.getValue(date)); expect(e.ellipsoid.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_ellipsoid_material_checkerboard").ellipsoid.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_path_material_polylineOutline")).toBeDefined(); expect(e.path.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_polylineOutline").path.material.color.getValue(date)); expect(e.path.material.outlineColor.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_polylineOutline").path.material.outlineColor.getValue(date)); expect(e.path.material.outlineWidth.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_polylineOutline").path.material.outlineWidth.getValue(date)); expect(e = dataSource.entities.getById("reference_path_material_polylineArrow")).toBeDefined(); expect(e.path.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_polylineArrow").path.material.color.getValue(date)); expect(e = dataSource.entities.getById("reference_path_material_polylineDash")).toBeDefined(); expect(e.path.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_polylineDash").path.material.color.getValue(date)); expect(e.path.material.gapColor.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_polylineDash").path.material.gapColor.getValue(date)); expect(e.path.material.dashLength.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_polylineDash").path.material.dashLength.getValue(date)); expect(e.path.material.dashPattern.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_polylineDash").path.material.dashPattern.getValue(date)); expect(e = dataSource.entities.getById("reference_path_material_polylineGlow")).toBeDefined(); expect(e.path.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_polylineGlow").path.material.color.getValue(date)); expect(e.path.material.glowPower.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_polylineGlow").path.material.glowPower.getValue(date)); expect(e.path.material.taperPower.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_polylineGlow").path.material.taperPower.getValue(date)); expect(e = dataSource.entities.getById("reference_path_material_image")).toBeDefined(); expect(e.path.material.image.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_image").path.material.image.getValue(date)); expect(e.path.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_image").path.material.repeat.getValue(date)); expect(e.path.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_image").path.material.color.getValue(date)); expect(e.path.material.transparent.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_image").path.material.transparent.getValue(date)); expect(e = dataSource.entities.getById("reference_path_material_grid")).toBeDefined(); expect(e.path.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_grid").path.material.color.getValue(date)); expect(e.path.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_grid").path.material.cellAlpha.getValue(date)); expect(e.path.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_grid").path.material.lineCount.getValue(date)); expect(e.path.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_grid").path.material.lineThickness.getValue(date)); expect(e.path.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_grid").path.material.lineOffset.getValue(date)); expect(e = dataSource.entities.getById("reference_path_material_stripe")).toBeDefined(); expect(e.path.material.orientation.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_stripe").path.material.orientation.getValue(date)); expect(e.path.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_stripe").path.material.evenColor.getValue(date)); expect(e.path.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_stripe").path.material.oddColor.getValue(date)); expect(e.path.material.offset.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_stripe").path.material.offset.getValue(date)); expect(e.path.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_stripe").path.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_path_material_checkerboard")).toBeDefined(); expect(e.path.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_checkerboard").path.material.evenColor.getValue(date)); expect(e.path.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_checkerboard").path.material.oddColor.getValue(date)); expect(e.path.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_path_material_checkerboard").path.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_polygon_material_image")).toBeDefined(); expect(e.polygon.material.image.getValue(date)).toEqual(dataSource.entities.getById("material_polygon_material_image").polygon.material.image.getValue(date)); expect(e.polygon.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_polygon_material_image").polygon.material.repeat.getValue(date)); expect(e.polygon.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_polygon_material_image").polygon.material.color.getValue(date)); expect(e.polygon.material.transparent.getValue(date)).toEqual(dataSource.entities.getById("material_polygon_material_image").polygon.material.transparent.getValue(date)); expect(e = dataSource.entities.getById("reference_polygon_material_grid")).toBeDefined(); expect(e.polygon.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_polygon_material_grid").polygon.material.color.getValue(date)); expect(e.polygon.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById("material_polygon_material_grid").polygon.material.cellAlpha.getValue(date)); expect(e.polygon.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById("material_polygon_material_grid").polygon.material.lineCount.getValue(date)); expect(e.polygon.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById("material_polygon_material_grid").polygon.material.lineThickness.getValue(date)); expect(e.polygon.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById("material_polygon_material_grid").polygon.material.lineOffset.getValue(date)); expect(e = dataSource.entities.getById("reference_polygon_material_stripe")).toBeDefined(); expect(e.polygon.material.orientation.getValue(date)).toEqual(dataSource.entities.getById("material_polygon_material_stripe").polygon.material.orientation.getValue(date)); expect(e.polygon.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_polygon_material_stripe").polygon.material.evenColor.getValue(date)); expect(e.polygon.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_polygon_material_stripe").polygon.material.oddColor.getValue(date)); expect(e.polygon.material.offset.getValue(date)).toEqual(dataSource.entities.getById("material_polygon_material_stripe").polygon.material.offset.getValue(date)); expect(e.polygon.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_polygon_material_stripe").polygon.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_polygon_material_checkerboard")).toBeDefined(); expect(e.polygon.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_polygon_material_checkerboard").polygon.material.evenColor.getValue(date)); expect(e.polygon.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_polygon_material_checkerboard").polygon.material.oddColor.getValue(date)); expect(e.polygon.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_polygon_material_checkerboard").polygon.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_polyline_material_polylineOutline")).toBeDefined(); expect(e.polyline.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_polylineOutline").polyline.material.color.getValue(date)); expect(e.polyline.material.outlineColor.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_polylineOutline").polyline.material.outlineColor.getValue(date)); expect(e.polyline.material.outlineWidth.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_polylineOutline").polyline.material.outlineWidth.getValue(date)); expect(e = dataSource.entities.getById("reference_polyline_material_polylineArrow")).toBeDefined(); expect(e.polyline.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_polylineArrow").polyline.material.color.getValue(date)); expect(e = dataSource.entities.getById("reference_polyline_material_polylineDash")).toBeDefined(); expect(e.polyline.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_polylineDash").polyline.material.color.getValue(date)); expect(e.polyline.material.gapColor.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_polylineDash").polyline.material.gapColor.getValue(date)); expect(e.polyline.material.dashLength.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_polylineDash").polyline.material.dashLength.getValue(date)); expect(e.polyline.material.dashPattern.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_polylineDash").polyline.material.dashPattern.getValue(date)); expect(e = dataSource.entities.getById("reference_polyline_material_polylineGlow")).toBeDefined(); expect(e.polyline.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_polylineGlow").polyline.material.color.getValue(date)); expect(e.polyline.material.glowPower.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_polylineGlow").polyline.material.glowPower.getValue(date)); expect(e.polyline.material.taperPower.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_polylineGlow").polyline.material.taperPower.getValue(date)); expect(e = dataSource.entities.getById("reference_polyline_material_image")).toBeDefined(); expect(e.polyline.material.image.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_image").polyline.material.image.getValue(date)); expect(e.polyline.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_image").polyline.material.repeat.getValue(date)); expect(e.polyline.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_image").polyline.material.color.getValue(date)); expect(e.polyline.material.transparent.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_image").polyline.material.transparent.getValue(date)); expect(e = dataSource.entities.getById("reference_polyline_material_grid")).toBeDefined(); expect(e.polyline.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_grid").polyline.material.color.getValue(date)); expect(e.polyline.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_grid").polyline.material.cellAlpha.getValue(date)); expect(e.polyline.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_grid").polyline.material.lineCount.getValue(date)); expect(e.polyline.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_grid").polyline.material.lineThickness.getValue(date)); expect(e.polyline.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_grid").polyline.material.lineOffset.getValue(date)); expect(e = dataSource.entities.getById("reference_polyline_material_stripe")).toBeDefined(); expect(e.polyline.material.orientation.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_stripe").polyline.material.orientation.getValue(date)); expect(e.polyline.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_stripe").polyline.material.evenColor.getValue(date)); expect(e.polyline.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_stripe").polyline.material.oddColor.getValue(date)); expect(e.polyline.material.offset.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_stripe").polyline.material.offset.getValue(date)); expect(e.polyline.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_stripe").polyline.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_polyline_material_checkerboard")).toBeDefined(); expect(e.polyline.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_checkerboard").polyline.material.evenColor.getValue(date)); expect(e.polyline.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_checkerboard").polyline.material.oddColor.getValue(date)); expect(e.polyline.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_material_checkerboard").polyline.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_polyline_depthFailMaterial_polylineOutline")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_polylineOutline").polyline.depthFailMaterial.color.getValue(date)); expect(e.polyline.depthFailMaterial.outlineColor.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_polylineOutline").polyline.depthFailMaterial.outlineColor.getValue(date)); expect(e.polyline.depthFailMaterial.outlineWidth.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_polylineOutline").polyline.depthFailMaterial.outlineWidth.getValue(date)); expect(e = dataSource.entities.getById("reference_polyline_depthFailMaterial_polylineArrow")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_polylineArrow").polyline.depthFailMaterial.color.getValue(date)); expect(e = dataSource.entities.getById("reference_polyline_depthFailMaterial_polylineDash")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_polylineDash").polyline.depthFailMaterial.color.getValue(date)); expect(e.polyline.depthFailMaterial.gapColor.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_polylineDash").polyline.depthFailMaterial.gapColor.getValue(date)); expect(e.polyline.depthFailMaterial.dashLength.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_polylineDash").polyline.depthFailMaterial.dashLength.getValue(date)); expect(e.polyline.depthFailMaterial.dashPattern.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_polylineDash").polyline.depthFailMaterial.dashPattern.getValue(date)); expect(e = dataSource.entities.getById("reference_polyline_depthFailMaterial_polylineGlow")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_polylineGlow").polyline.depthFailMaterial.color.getValue(date)); expect(e.polyline.depthFailMaterial.glowPower.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_polylineGlow").polyline.depthFailMaterial.glowPower.getValue(date)); expect(e.polyline.depthFailMaterial.taperPower.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_polylineGlow").polyline.depthFailMaterial.taperPower.getValue(date)); expect(e = dataSource.entities.getById("reference_polyline_depthFailMaterial_image")).toBeDefined(); expect(e.polyline.depthFailMaterial.image.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_image").polyline.depthFailMaterial.image.getValue(date)); expect(e.polyline.depthFailMaterial.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_image").polyline.depthFailMaterial.repeat.getValue(date)); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_image").polyline.depthFailMaterial.color.getValue(date)); expect(e.polyline.depthFailMaterial.transparent.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_image").polyline.depthFailMaterial.transparent.getValue(date)); expect(e = dataSource.entities.getById("reference_polyline_depthFailMaterial_grid")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_grid").polyline.depthFailMaterial.color.getValue(date)); expect(e.polyline.depthFailMaterial.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_grid").polyline.depthFailMaterial.cellAlpha.getValue(date)); expect(e.polyline.depthFailMaterial.lineCount.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_grid").polyline.depthFailMaterial.lineCount.getValue(date)); expect(e.polyline.depthFailMaterial.lineThickness.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_grid").polyline.depthFailMaterial.lineThickness.getValue(date)); expect(e.polyline.depthFailMaterial.lineOffset.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_grid").polyline.depthFailMaterial.lineOffset.getValue(date)); expect(e = dataSource.entities.getById("reference_polyline_depthFailMaterial_stripe")).toBeDefined(); expect(e.polyline.depthFailMaterial.orientation.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_stripe").polyline.depthFailMaterial.orientation.getValue(date)); expect(e.polyline.depthFailMaterial.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_stripe").polyline.depthFailMaterial.evenColor.getValue(date)); expect(e.polyline.depthFailMaterial.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_stripe").polyline.depthFailMaterial.oddColor.getValue(date)); expect(e.polyline.depthFailMaterial.offset.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_stripe").polyline.depthFailMaterial.offset.getValue(date)); expect(e.polyline.depthFailMaterial.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_stripe").polyline.depthFailMaterial.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_polyline_depthFailMaterial_checkerboard")).toBeDefined(); expect(e.polyline.depthFailMaterial.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_checkerboard").polyline.depthFailMaterial.evenColor.getValue(date)); expect(e.polyline.depthFailMaterial.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_checkerboard").polyline.depthFailMaterial.oddColor.getValue(date)); expect(e.polyline.depthFailMaterial.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_polyline_depthFailMaterial_checkerboard").polyline.depthFailMaterial.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_polylineVolume_material_image")).toBeDefined(); expect(e.polylineVolume.material.image.getValue(date)).toEqual(dataSource.entities.getById("material_polylineVolume_material_image").polylineVolume.material.image.getValue(date)); expect(e.polylineVolume.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_polylineVolume_material_image").polylineVolume.material.repeat.getValue(date)); expect(e.polylineVolume.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_polylineVolume_material_image").polylineVolume.material.color.getValue(date)); expect(e.polylineVolume.material.transparent.getValue(date)).toEqual(dataSource.entities.getById("material_polylineVolume_material_image").polylineVolume.material.transparent.getValue(date)); expect(e = dataSource.entities.getById("reference_polylineVolume_material_grid")).toBeDefined(); expect(e.polylineVolume.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_polylineVolume_material_grid").polylineVolume.material.color.getValue(date)); expect(e.polylineVolume.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById("material_polylineVolume_material_grid").polylineVolume.material.cellAlpha.getValue(date)); expect(e.polylineVolume.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById("material_polylineVolume_material_grid").polylineVolume.material.lineCount.getValue(date)); expect(e.polylineVolume.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById("material_polylineVolume_material_grid").polylineVolume.material.lineThickness.getValue(date)); expect(e.polylineVolume.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById("material_polylineVolume_material_grid").polylineVolume.material.lineOffset.getValue(date)); expect(e = dataSource.entities.getById("reference_polylineVolume_material_stripe")).toBeDefined(); expect(e.polylineVolume.material.orientation.getValue(date)).toEqual(dataSource.entities.getById("material_polylineVolume_material_stripe").polylineVolume.material.orientation.getValue(date)); expect(e.polylineVolume.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_polylineVolume_material_stripe").polylineVolume.material.evenColor.getValue(date)); expect(e.polylineVolume.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_polylineVolume_material_stripe").polylineVolume.material.oddColor.getValue(date)); expect(e.polylineVolume.material.offset.getValue(date)).toEqual(dataSource.entities.getById("material_polylineVolume_material_stripe").polylineVolume.material.offset.getValue(date)); expect(e.polylineVolume.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_polylineVolume_material_stripe").polylineVolume.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_polylineVolume_material_checkerboard")).toBeDefined(); expect(e.polylineVolume.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_polylineVolume_material_checkerboard").polylineVolume.material.evenColor.getValue(date)); expect(e.polylineVolume.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_polylineVolume_material_checkerboard").polylineVolume.material.oddColor.getValue(date)); expect(e.polylineVolume.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_polylineVolume_material_checkerboard").polylineVolume.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_rectangle_material_image")).toBeDefined(); expect(e.rectangle.material.image.getValue(date)).toEqual(dataSource.entities.getById("material_rectangle_material_image").rectangle.material.image.getValue(date)); expect(e.rectangle.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_rectangle_material_image").rectangle.material.repeat.getValue(date)); expect(e.rectangle.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_rectangle_material_image").rectangle.material.color.getValue(date)); expect(e.rectangle.material.transparent.getValue(date)).toEqual(dataSource.entities.getById("material_rectangle_material_image").rectangle.material.transparent.getValue(date)); expect(e = dataSource.entities.getById("reference_rectangle_material_grid")).toBeDefined(); expect(e.rectangle.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_rectangle_material_grid").rectangle.material.color.getValue(date)); expect(e.rectangle.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById("material_rectangle_material_grid").rectangle.material.cellAlpha.getValue(date)); expect(e.rectangle.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById("material_rectangle_material_grid").rectangle.material.lineCount.getValue(date)); expect(e.rectangle.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById("material_rectangle_material_grid").rectangle.material.lineThickness.getValue(date)); expect(e.rectangle.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById("material_rectangle_material_grid").rectangle.material.lineOffset.getValue(date)); expect(e = dataSource.entities.getById("reference_rectangle_material_stripe")).toBeDefined(); expect(e.rectangle.material.orientation.getValue(date)).toEqual(dataSource.entities.getById("material_rectangle_material_stripe").rectangle.material.orientation.getValue(date)); expect(e.rectangle.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_rectangle_material_stripe").rectangle.material.evenColor.getValue(date)); expect(e.rectangle.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_rectangle_material_stripe").rectangle.material.oddColor.getValue(date)); expect(e.rectangle.material.offset.getValue(date)).toEqual(dataSource.entities.getById("material_rectangle_material_stripe").rectangle.material.offset.getValue(date)); expect(e.rectangle.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_rectangle_material_stripe").rectangle.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_rectangle_material_checkerboard")).toBeDefined(); expect(e.rectangle.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_rectangle_material_checkerboard").rectangle.material.evenColor.getValue(date)); expect(e.rectangle.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_rectangle_material_checkerboard").rectangle.material.oddColor.getValue(date)); expect(e.rectangle.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_rectangle_material_checkerboard").rectangle.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_wall_material_image")).toBeDefined(); expect(e.wall.material.image.getValue(date)).toEqual(dataSource.entities.getById("material_wall_material_image").wall.material.image.getValue(date)); expect(e.wall.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_wall_material_image").wall.material.repeat.getValue(date)); expect(e.wall.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_wall_material_image").wall.material.color.getValue(date)); expect(e.wall.material.transparent.getValue(date)).toEqual(dataSource.entities.getById("material_wall_material_image").wall.material.transparent.getValue(date)); expect(e = dataSource.entities.getById("reference_wall_material_grid")).toBeDefined(); expect(e.wall.material.color.getValue(date)).toEqual(dataSource.entities.getById("material_wall_material_grid").wall.material.color.getValue(date)); expect(e.wall.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById("material_wall_material_grid").wall.material.cellAlpha.getValue(date)); expect(e.wall.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById("material_wall_material_grid").wall.material.lineCount.getValue(date)); expect(e.wall.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById("material_wall_material_grid").wall.material.lineThickness.getValue(date)); expect(e.wall.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById("material_wall_material_grid").wall.material.lineOffset.getValue(date)); expect(e = dataSource.entities.getById("reference_wall_material_stripe")).toBeDefined(); expect(e.wall.material.orientation.getValue(date)).toEqual(dataSource.entities.getById("material_wall_material_stripe").wall.material.orientation.getValue(date)); expect(e.wall.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_wall_material_stripe").wall.material.evenColor.getValue(date)); expect(e.wall.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_wall_material_stripe").wall.material.oddColor.getValue(date)); expect(e.wall.material.offset.getValue(date)).toEqual(dataSource.entities.getById("material_wall_material_stripe").wall.material.offset.getValue(date)); expect(e.wall.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_wall_material_stripe").wall.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_wall_material_checkerboard")).toBeDefined(); expect(e.wall.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById("material_wall_material_checkerboard").wall.material.evenColor.getValue(date)); expect(e.wall.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById("material_wall_material_checkerboard").wall.material.oddColor.getValue(date)); expect(e.wall.material.repeat.getValue(date)).toEqual(dataSource.entities.getById("material_wall_material_checkerboard").wall.material.repeat.getValue(date)); expect(e = dataSource.entities.getById("reference_conicSensor_lateralSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_lateralSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_lateralSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_lateralSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_ellipsoidSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_ellipsoidSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_ellipsoidSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_ellipsoidSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_ellipsoidHorizonSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_ellipsoidHorizonSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_ellipsoidHorizonSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_ellipsoidHorizonSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_domeSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_domeSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_domeSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_domeSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_environmentOcclusionMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_environmentOcclusionMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_environmentOcclusionMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("reference_conicSensor_environmentOcclusionMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_lateralSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_lateralSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_lateralSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_lateralSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_ellipsoidSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_ellipsoidSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_ellipsoidSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_ellipsoidSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_ellipsoidHorizonSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_ellipsoidHorizonSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_ellipsoidHorizonSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_ellipsoidHorizonSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_domeSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_domeSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_domeSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_domeSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_environmentOcclusionMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_environmentOcclusionMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_environmentOcclusionMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("reference_customPatternSensor_environmentOcclusionMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_lateralSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_lateralSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_lateralSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_lateralSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_ellipsoidSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_ellipsoidSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_ellipsoidSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_ellipsoidSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_ellipsoidHorizonSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_ellipsoidHorizonSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_ellipsoidHorizonSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_ellipsoidHorizonSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_domeSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_domeSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_domeSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_domeSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_environmentOcclusionMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_environmentOcclusionMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_environmentOcclusionMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("reference_rectangularSensor_environmentOcclusionMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("reference_fan_material_image")).toBeDefined(); expect(e = dataSource.entities.getById("reference_fan_material_grid")).toBeDefined(); expect(e = dataSource.entities.getById("reference_fan_material_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("reference_fan_material_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("VelocityPosition")).toBeDefined(); expect(e.position.getValue(documentStartDate)).toEqual(new import__55.Cartesian3(1, 2, 3)); expect(e.position.getValue(import__55.JulianDate.addSeconds(documentStartDate, 60, new import__55.JulianDate()))).toEqual(new import__55.Cartesian3(61, 122, 183)); expect(e = dataSource.entities.getById("velocityReference_billboard_alignedAxis")).toBeDefined(); expect(e.billboard.alignedAxis.getValue(import__55.JulianDate.addSeconds(documentStartDate, 50, new import__55.JulianDate()))).toEqualEpsilon(new import__55.Cartesian3(0.267261241912424, 0.534522483824849, 0.801783725737273), 1e-13); expect(e = dataSource.entities.getById("Sampled")).toBeDefined(); expect(e.position.getValue(documentStartDate)).toEqual(new import__55.Cartesian3(14893, 22330, 50775)); expect(e.position.getValue(documentStopDate)).toEqual(new import__55.Cartesian3(44952, 52911, 45006)); expect(e.orientation.getValue(documentStartDate)).toEqualEpsilon(new import__55.Quaternion(0.63382030572505, 0.114406464045845, 0.748788933003267, 0.156518736408648), 1e-14); expect(e.orientation.getValue(documentStopDate)).toEqualEpsilon(new import__55.Quaternion(0.670778929875422, 0.608790403475694, 0.320013828781515, 0.277526613606122), 1e-14); expect(e.viewFrom.getValue(documentStartDate)).toEqual(new import__55.Cartesian3(36965, 47504, 12985)); expect(e.viewFrom.getValue(documentStopDate)).toEqual(new import__55.Cartesian3(16155, 2367, 57353)); expect(e.billboard.scale.getValue(documentStartDate)).toEqual(5763); expect(e.billboard.scale.getValue(documentStopDate)).toEqual(31607); expect(e.billboard.pixelOffset.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(2029, 62215)); expect(e.billboard.pixelOffset.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(30658, 12919)); expect(e.billboard.eyeOffset.getValue(documentStartDate)).toEqual(new import__55.Cartesian3(3553, 23821, 42589)); expect(e.billboard.eyeOffset.getValue(documentStopDate)).toEqual(new import__55.Cartesian3(3059, 48139, 28860)); expect(e.billboard.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(85, 19, 239, 63)); expect(e.billboard.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(160, 189, 87, 99)); expect(e.billboard.rotation.getValue(documentStartDate)).toEqual(4554); expect(e.billboard.rotation.getValue(documentStopDate)).toEqual(21210); expect(e.billboard.alignedAxis.getValue(documentStartDate)).toEqualEpsilon(new import__55.Cartesian3(0.971559394453729, 0.230094854374832, 0.0559347927405484), 1e-14); expect(e.billboard.alignedAxis.getValue(documentStopDate)).toEqualEpsilon(new import__55.Cartesian3(0.384810775516236, 0.82287332508932, 0.418091088045462), 1e-14); expect(e.billboard.width.getValue(documentStartDate)).toEqual(21333); expect(e.billboard.width.getValue(documentStopDate)).toEqual(51893); expect(e.billboard.height.getValue(documentStartDate)).toEqual(48314); expect(e.billboard.height.getValue(documentStopDate)).toEqual(61118); expect(e.billboard.scaleByDistance.getValue(documentStartDate)).toEqual(new import__55.NearFarScalar(46842, 10678, 46377, 15029)); expect(e.billboard.scaleByDistance.getValue(documentStopDate)).toEqual(new import__55.NearFarScalar(20642, 43600, 7082, 11291)); expect(e.billboard.translucencyByDistance.getValue(documentStartDate)).toEqual(new import__55.NearFarScalar(64366, 52219, 8139, 10015)); expect(e.billboard.translucencyByDistance.getValue(documentStopDate)).toEqual(new import__55.NearFarScalar(10918, 18986, 49738, 60610)); expect(e.billboard.pixelOffsetScaleByDistance.getValue(documentStartDate)).toEqual(new import__55.NearFarScalar(54503, 26068, 41061, 59552)); expect(e.billboard.pixelOffsetScaleByDistance.getValue(documentStopDate)).toEqual(new import__55.NearFarScalar(37417, 4754, 19986, 15182)); expect(e.billboard.imageSubRegion.getValue(documentStartDate)).toEqual(new import__55.BoundingRectangle(26590, 12135, 16431, 56640)); expect(e.billboard.imageSubRegion.getValue(documentStopDate)).toEqual(new import__55.BoundingRectangle(43063, 42664, 60326, 52715)); expect(e.billboard.distanceDisplayCondition.getValue(documentStartDate)).toEqual(new import__55.DistanceDisplayCondition(952, 47317)); expect(e.billboard.distanceDisplayCondition.getValue(documentStopDate)).toEqual(new import__55.DistanceDisplayCondition(16896, 28226)); expect(e.billboard.disableDepthTestDistance.getValue(documentStartDate)).toEqual(18661); expect(e.billboard.disableDepthTestDistance.getValue(documentStopDate)).toEqual(61609); expect(e.box.dimensions.getValue(documentStartDate)).toEqual(new import__55.Cartesian3(37525, 42898, 18087)); expect(e.box.dimensions.getValue(documentStopDate)).toEqual(new import__55.Cartesian3(49399, 59584, 63976)); expect(e.box.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(172, 28, 222, 165)); expect(e.box.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(16, 192, 121, 150)); expect(e.box.outlineColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(53, 66, 217, 237)); expect(e.box.outlineColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(163, 75, 228, 48)); expect(e.box.outlineWidth.getValue(documentStartDate)).toEqual(45211); expect(e.box.outlineWidth.getValue(documentStopDate)).toEqual(20490); expect(e.box.distanceDisplayCondition.getValue(documentStartDate)).toEqual(new import__55.DistanceDisplayCondition(8940, 60664)); expect(e.box.distanceDisplayCondition.getValue(documentStopDate)).toEqual(new import__55.DistanceDisplayCondition(41202, 60832)); expect(e.corridor.width.getValue(documentStartDate)).toEqual(62443); expect(e.corridor.width.getValue(documentStopDate)).toEqual(13988); expect(e.corridor.height.getValue(documentStartDate)).toEqual(20585); expect(e.corridor.height.getValue(documentStopDate)).toEqual(63872); expect(e.corridor.extrudedHeight.getValue(documentStartDate)).toEqual(63407); expect(e.corridor.extrudedHeight.getValue(documentStopDate)).toEqual(42397); expect(e.corridor.granularity.getValue(documentStartDate)).toEqual(43027); expect(e.corridor.granularity.getValue(documentStopDate)).toEqual(55912); expect(e.corridor.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(35, 213, 31, 79)); expect(e.corridor.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(87, 126, 23, 40)); expect(e.corridor.outlineColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(137, 114, 57, 34)); expect(e.corridor.outlineColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(93, 178, 74, 64)); expect(e.corridor.outlineWidth.getValue(documentStartDate)).toEqual(14678); expect(e.corridor.outlineWidth.getValue(documentStopDate)).toEqual(57820); expect(e.corridor.distanceDisplayCondition.getValue(documentStartDate)).toEqual(new import__55.DistanceDisplayCondition(10884, 63530)); expect(e.corridor.distanceDisplayCondition.getValue(documentStopDate)).toEqual(new import__55.DistanceDisplayCondition(20076, 27683)); expect(e.corridor.zIndex.getValue(documentStartDate)).toEqual(36068); expect(e.corridor.zIndex.getValue(documentStopDate)).toEqual(60697); expect(e.cylinder.length.getValue(documentStartDate)).toEqual(30241); expect(e.cylinder.length.getValue(documentStopDate)).toEqual(48364); expect(e.cylinder.topRadius.getValue(documentStartDate)).toEqual(62881); expect(e.cylinder.topRadius.getValue(documentStopDate)).toEqual(16270); expect(e.cylinder.bottomRadius.getValue(documentStartDate)).toEqual(61925); expect(e.cylinder.bottomRadius.getValue(documentStopDate)).toEqual(21514); expect(e.cylinder.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(133, 36, 52, 121)); expect(e.cylinder.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(7, 13, 34, 201)); expect(e.cylinder.outlineColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(112, 241, 40, 103)); expect(e.cylinder.outlineColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(237, 75, 59, 51)); expect(e.cylinder.outlineWidth.getValue(documentStartDate)).toEqual(36483); expect(e.cylinder.outlineWidth.getValue(documentStopDate)).toEqual(32586); expect(e.cylinder.numberOfVerticalLines.getValue(documentStartDate)).toEqual(45816); expect(e.cylinder.numberOfVerticalLines.getValue(documentStopDate)).toEqual(42247); expect(e.cylinder.slices.getValue(documentStartDate)).toEqual(46140); expect(e.cylinder.slices.getValue(documentStopDate)).toEqual(53530); expect(e.cylinder.distanceDisplayCondition.getValue(documentStartDate)).toEqual(new import__55.DistanceDisplayCondition(2783, 57220)); expect(e.cylinder.distanceDisplayCondition.getValue(documentStopDate)).toEqual(new import__55.DistanceDisplayCondition(13855, 50230)); expect(e.ellipse.semiMajorAxis.getValue(documentStartDate)).toEqual(13136); expect(e.ellipse.semiMajorAxis.getValue(documentStopDate)).toEqual(55507); expect(e.ellipse.semiMinorAxis.getValue(documentStartDate)).toEqual(41580); expect(e.ellipse.semiMinorAxis.getValue(documentStopDate)).toEqual(60905); expect(e.ellipse.height.getValue(documentStartDate)).toEqual(5567); expect(e.ellipse.height.getValue(documentStopDate)).toEqual(45588); expect(e.ellipse.extrudedHeight.getValue(documentStartDate)).toEqual(16542); expect(e.ellipse.extrudedHeight.getValue(documentStopDate)).toEqual(13545); expect(e.ellipse.rotation.getValue(documentStartDate)).toEqual(5797); expect(e.ellipse.rotation.getValue(documentStopDate)).toEqual(24542); expect(e.ellipse.stRotation.getValue(documentStartDate)).toEqual(20596); expect(e.ellipse.stRotation.getValue(documentStopDate)).toEqual(58204); expect(e.ellipse.granularity.getValue(documentStartDate)).toEqual(2228); expect(e.ellipse.granularity.getValue(documentStopDate)).toEqual(43731); expect(e.ellipse.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(174, 250, 78, 96)); expect(e.ellipse.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(63, 102, 221, 174)); expect(e.ellipse.outlineColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(243, 123, 194, 31)); expect(e.ellipse.outlineColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(236, 100, 22, 203)); expect(e.ellipse.outlineWidth.getValue(documentStartDate)).toEqual(60636); expect(e.ellipse.outlineWidth.getValue(documentStopDate)).toEqual(24194); expect(e.ellipse.numberOfVerticalLines.getValue(documentStartDate)).toEqual(52822); expect(e.ellipse.numberOfVerticalLines.getValue(documentStopDate)).toEqual(45768); expect(e.ellipse.distanceDisplayCondition.getValue(documentStartDate)).toEqual(new import__55.DistanceDisplayCondition(38393, 63947)); expect(e.ellipse.distanceDisplayCondition.getValue(documentStopDate)).toEqual(new import__55.DistanceDisplayCondition(29119, 43121)); expect(e.ellipse.zIndex.getValue(documentStartDate)).toEqual(8989); expect(e.ellipse.zIndex.getValue(documentStopDate)).toEqual(52730); expect(e.ellipsoid.radii.getValue(documentStartDate)).toEqual(new import__55.Cartesian3(5183, 10004, 13863)); expect(e.ellipsoid.radii.getValue(documentStopDate)).toEqual(new import__55.Cartesian3(39497, 12186, 45103)); expect(e.ellipsoid.innerRadii.getValue(documentStartDate)).toEqual(new import__55.Cartesian3(40318, 27037, 59497)); expect(e.ellipsoid.innerRadii.getValue(documentStopDate)).toEqual(new import__55.Cartesian3(57650, 53729, 12241)); expect(e.ellipsoid.minimumClock.getValue(documentStartDate)).toEqual(13484); expect(e.ellipsoid.minimumClock.getValue(documentStopDate)).toEqual(2170); expect(e.ellipsoid.maximumClock.getValue(documentStartDate)).toEqual(10874); expect(e.ellipsoid.maximumClock.getValue(documentStopDate)).toEqual(2968); expect(e.ellipsoid.minimumCone.getValue(documentStartDate)).toEqual(54230); expect(e.ellipsoid.minimumCone.getValue(documentStopDate)).toEqual(59454); expect(e.ellipsoid.maximumCone.getValue(documentStartDate)).toEqual(49077); expect(e.ellipsoid.maximumCone.getValue(documentStopDate)).toEqual(26303); expect(e.ellipsoid.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(137, 128, 194, 84)); expect(e.ellipsoid.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(50, 122, 190, 247)); expect(e.ellipsoid.outlineColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(247, 210, 180, 171)); expect(e.ellipsoid.outlineColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(239, 35, 237, 247)); expect(e.ellipsoid.outlineWidth.getValue(documentStartDate)).toEqual(10713); expect(e.ellipsoid.outlineWidth.getValue(documentStopDate)).toEqual(10444); expect(e.ellipsoid.stackPartitions.getValue(documentStartDate)).toEqual(5841); expect(e.ellipsoid.stackPartitions.getValue(documentStopDate)).toEqual(39170); expect(e.ellipsoid.slicePartitions.getValue(documentStartDate)).toEqual(50327); expect(e.ellipsoid.slicePartitions.getValue(documentStopDate)).toEqual(4672); expect(e.ellipsoid.subdivisions.getValue(documentStartDate)).toEqual(10225); expect(e.ellipsoid.subdivisions.getValue(documentStopDate)).toEqual(53957); expect(e.ellipsoid.distanceDisplayCondition.getValue(documentStartDate)).toEqual(new import__55.DistanceDisplayCondition(11751, 59227)); expect(e.ellipsoid.distanceDisplayCondition.getValue(documentStopDate)).toEqual(new import__55.DistanceDisplayCondition(4769, 41441)); expect(e.label.scale.getValue(documentStartDate)).toEqual(40153); expect(e.label.scale.getValue(documentStopDate)).toEqual(42123); expect(e.label.backgroundColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(30, 92, 161, 169)); expect(e.label.backgroundColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(85, 52, 166, 62)); expect(e.label.backgroundPadding.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(32945, 5504)); expect(e.label.backgroundPadding.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(35323, 6281)); expect(e.label.pixelOffset.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(8539, 9761)); expect(e.label.pixelOffset.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(10537, 54569)); expect(e.label.eyeOffset.getValue(documentStartDate)).toEqual(new import__55.Cartesian3(5984, 34327, 59014)); expect(e.label.eyeOffset.getValue(documentStopDate)).toEqual(new import__55.Cartesian3(1931, 5127, 18964)); expect(e.label.fillColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(17, 212, 62, 58)); expect(e.label.fillColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(214, 69, 90, 116)); expect(e.label.outlineColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(205, 14, 169, 70)); expect(e.label.outlineColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(143, 73, 168, 17)); expect(e.label.outlineWidth.getValue(documentStartDate)).toEqual(53305); expect(e.label.outlineWidth.getValue(documentStopDate)).toEqual(43838); expect(e.label.translucencyByDistance.getValue(documentStartDate)).toEqual(new import__55.NearFarScalar(25055, 32865, 32128, 29309)); expect(e.label.translucencyByDistance.getValue(documentStopDate)).toEqual(new import__55.NearFarScalar(58875, 9189, 20515, 15696)); expect(e.label.pixelOffsetScaleByDistance.getValue(documentStartDate)).toEqual(new import__55.NearFarScalar(45296, 62896, 38133, 40084)); expect(e.label.pixelOffsetScaleByDistance.getValue(documentStopDate)).toEqual(new import__55.NearFarScalar(28657, 25711, 9316, 62756)); expect(e.label.scaleByDistance.getValue(documentStartDate)).toEqual(new import__55.NearFarScalar(22356, 26711, 58216, 52963)); expect(e.label.scaleByDistance.getValue(documentStopDate)).toEqual(new import__55.NearFarScalar(26464, 26471, 23143, 37466)); expect(e.label.distanceDisplayCondition.getValue(documentStartDate)).toEqual(new import__55.DistanceDisplayCondition(2314, 2614)); expect(e.label.distanceDisplayCondition.getValue(documentStopDate)).toEqual(new import__55.DistanceDisplayCondition(23998, 48733)); expect(e.label.disableDepthTestDistance.getValue(documentStartDate)).toEqual(250); expect(e.label.disableDepthTestDistance.getValue(documentStopDate)).toEqual(40425); expect(e.model.scale.getValue(documentStartDate)).toEqual(63647); expect(e.model.scale.getValue(documentStopDate)).toEqual(53878); expect(e.model.minimumPixelSize.getValue(documentStartDate)).toEqual(16357); expect(e.model.minimumPixelSize.getValue(documentStopDate)).toEqual(40522); expect(e.model.maximumScale.getValue(documentStartDate)).toEqual(8290); expect(e.model.maximumScale.getValue(documentStopDate)).toEqual(25558); expect(e.model.silhouetteColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(33, 239, 70, 81)); expect(e.model.silhouetteColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(60, 48, 26, 123)); expect(e.model.silhouetteSize.getValue(documentStartDate)).toEqual(65103); expect(e.model.silhouetteSize.getValue(documentStopDate)).toEqual(29065); expect(e.model.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(74, 69, 164, 116)); expect(e.model.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(127, 30, 46, 170)); expect(e.model.colorBlendAmount.getValue(documentStartDate)).toEqual(64130); expect(e.model.colorBlendAmount.getValue(documentStopDate)).toEqual(21967); expect(e.model.distanceDisplayCondition.getValue(documentStartDate)).toEqual(new import__55.DistanceDisplayCondition(33246, 36993)); expect(e.model.distanceDisplayCondition.getValue(documentStopDate)).toEqual(new import__55.DistanceDisplayCondition(5814, 10006)); expect(e.path.leadTime.getValue(documentStartDate)).toEqual(40222); expect(e.path.leadTime.getValue(documentStopDate)).toEqual(33294); expect(e.path.trailTime.getValue(documentStartDate)).toEqual(34052); expect(e.path.trailTime.getValue(documentStopDate)).toEqual(57713); expect(e.path.width.getValue(documentStartDate)).toEqual(32449); expect(e.path.width.getValue(documentStopDate)).toEqual(33819); expect(e.path.resolution.getValue(documentStartDate)).toEqual(8399); expect(e.path.resolution.getValue(documentStopDate)).toEqual(19400); expect(e.path.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(97, 239, 22, 105)); expect(e.path.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(242, 157, 215, 125)); expect(e.path.distanceDisplayCondition.getValue(documentStartDate)).toEqual(new import__55.DistanceDisplayCondition(42994, 62047)); expect(e.path.distanceDisplayCondition.getValue(documentStopDate)).toEqual(new import__55.DistanceDisplayCondition(52406, 59340)); expect(e.point.pixelSize.getValue(documentStartDate)).toEqual(39714); expect(e.point.pixelSize.getValue(documentStopDate)).toEqual(3313); expect(e.point.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(137, 151, 128, 95)); expect(e.point.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(99, 157, 124, 108)); expect(e.point.outlineColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(225, 246, 102, 195)); expect(e.point.outlineColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(248, 38, 75, 222)); expect(e.point.outlineWidth.getValue(documentStartDate)).toEqual(48323); expect(e.point.outlineWidth.getValue(documentStopDate)).toEqual(50914); expect(e.point.scaleByDistance.getValue(documentStartDate)).toEqual(new import__55.NearFarScalar(39727, 50843, 56262, 15579)); expect(e.point.scaleByDistance.getValue(documentStopDate)).toEqual(new import__55.NearFarScalar(60522, 63980, 30201, 25205)); expect(e.point.translucencyByDistance.getValue(documentStartDate)).toEqual(new import__55.NearFarScalar(61190, 16879, 16449, 10048)); expect(e.point.translucencyByDistance.getValue(documentStopDate)).toEqual(new import__55.NearFarScalar(46491, 47541, 35769, 13707)); expect(e.point.distanceDisplayCondition.getValue(documentStartDate)).toEqual(new import__55.DistanceDisplayCondition(7642, 55841)); expect(e.point.distanceDisplayCondition.getValue(documentStopDate)).toEqual(new import__55.DistanceDisplayCondition(24270, 29534)); expect(e.point.disableDepthTestDistance.getValue(documentStartDate)).toEqual(30881); expect(e.point.disableDepthTestDistance.getValue(documentStopDate)).toEqual(6667); expect(e.polygon.height.getValue(documentStartDate)).toEqual(64265); expect(e.polygon.height.getValue(documentStopDate)).toEqual(19257); expect(e.polygon.extrudedHeight.getValue(documentStartDate)).toEqual(12315); expect(e.polygon.extrudedHeight.getValue(documentStopDate)).toEqual(4797); expect(e.polygon.stRotation.getValue(documentStartDate)).toEqual(24959); expect(e.polygon.stRotation.getValue(documentStopDate)).toEqual(32341); expect(e.polygon.granularity.getValue(documentStartDate)).toEqual(51922); expect(e.polygon.granularity.getValue(documentStopDate)).toEqual(9185); expect(e.polygon.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(19, 40, 12, 31)); expect(e.polygon.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(179, 204, 8, 194)); expect(e.polygon.outlineColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(187, 223, 120, 26)); expect(e.polygon.outlineColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(20, 135, 105, 81)); expect(e.polygon.outlineWidth.getValue(documentStartDate)).toEqual(48428); expect(e.polygon.outlineWidth.getValue(documentStopDate)).toEqual(41508); expect(e.polygon.distanceDisplayCondition.getValue(documentStartDate)).toEqual(new import__55.DistanceDisplayCondition(22140, 31962)); expect(e.polygon.distanceDisplayCondition.getValue(documentStopDate)).toEqual(new import__55.DistanceDisplayCondition(3927, 22422)); expect(e.polygon.zIndex.getValue(documentStartDate)).toEqual(37357); expect(e.polygon.zIndex.getValue(documentStopDate)).toEqual(64769); expect(e.polyline.width.getValue(documentStartDate)).toEqual(60367); expect(e.polyline.width.getValue(documentStopDate)).toEqual(31077); expect(e.polyline.granularity.getValue(documentStartDate)).toEqual(62537); expect(e.polyline.granularity.getValue(documentStopDate)).toEqual(14676); expect(e.polyline.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(90, 30, 195, 220)); expect(e.polyline.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(39, 17, 221, 74)); expect(e.polyline.depthFailMaterial.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(217, 122, 10, 152)); expect(e.polyline.depthFailMaterial.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(76, 105, 5, 67)); expect(e.polyline.distanceDisplayCondition.getValue(documentStartDate)).toEqual(new import__55.DistanceDisplayCondition(4857, 10258)); expect(e.polyline.distanceDisplayCondition.getValue(documentStopDate)).toEqual(new import__55.DistanceDisplayCondition(36588, 47246)); expect(e.polyline.zIndex.getValue(documentStartDate)).toEqual(55130); expect(e.polyline.zIndex.getValue(documentStopDate)).toEqual(15491); expect(e.polylineVolume.granularity.getValue(documentStartDate)).toEqual(9144); expect(e.polylineVolume.granularity.getValue(documentStopDate)).toEqual(5282); expect(e.polylineVolume.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(3, 0, 198, 193)); expect(e.polylineVolume.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(210, 44, 29, 16)); expect(e.polylineVolume.outlineColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(248, 163, 212, 115)); expect(e.polylineVolume.outlineColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(22, 27, 199, 98)); expect(e.polylineVolume.outlineWidth.getValue(documentStartDate)).toEqual(17507); expect(e.polylineVolume.outlineWidth.getValue(documentStopDate)).toEqual(55396); expect(e.polylineVolume.distanceDisplayCondition.getValue(documentStartDate)).toEqual(new import__55.DistanceDisplayCondition(20986, 34897)); expect(e.polylineVolume.distanceDisplayCondition.getValue(documentStopDate)).toEqual(new import__55.DistanceDisplayCondition(14877, 46650)); expect(e.rectangle.coordinates.getValue(documentStartDate)).toEqual(new import__55.Rectangle(0.392205830501108, 1.04907471338688, 0.00211010473645246, 0.064281089310235)); expect(e.rectangle.coordinates.getValue(documentStopDate)).toEqual(new import__55.Rectangle(0.523469985903937, 0.229690388867811, 0.399550037703662, 0.48478405941078)); expect(e.rectangle.height.getValue(documentStartDate)).toEqual(56388); expect(e.rectangle.height.getValue(documentStopDate)).toEqual(59991); expect(e.rectangle.extrudedHeight.getValue(documentStartDate)).toEqual(39796); expect(e.rectangle.extrudedHeight.getValue(documentStopDate)).toEqual(33335); expect(e.rectangle.rotation.getValue(documentStartDate)).toEqual(26921); expect(e.rectangle.rotation.getValue(documentStopDate)).toEqual(46937); expect(e.rectangle.stRotation.getValue(documentStartDate)).toEqual(65255); expect(e.rectangle.stRotation.getValue(documentStopDate)).toEqual(12220); expect(e.rectangle.granularity.getValue(documentStartDate)).toEqual(6948); expect(e.rectangle.granularity.getValue(documentStopDate)).toEqual(2204); expect(e.rectangle.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(106, 81, 64, 152)); expect(e.rectangle.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(94, 108, 96, 154)); expect(e.rectangle.outlineColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(6, 244, 49, 131)); expect(e.rectangle.outlineColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(87, 190, 148, 55)); expect(e.rectangle.outlineWidth.getValue(documentStartDate)).toEqual(41576); expect(e.rectangle.outlineWidth.getValue(documentStopDate)).toEqual(33933); expect(e.rectangle.distanceDisplayCondition.getValue(documentStartDate)).toEqual(new import__55.DistanceDisplayCondition(24813, 30560)); expect(e.rectangle.distanceDisplayCondition.getValue(documentStopDate)).toEqual(new import__55.DistanceDisplayCondition(34617, 40071)); expect(e.rectangle.zIndex.getValue(documentStartDate)).toEqual(27256); expect(e.rectangle.zIndex.getValue(documentStopDate)).toEqual(53581); expect(e.tileset.maximumScreenSpaceError.getValue(documentStartDate)).toEqual(17401); expect(e.tileset.maximumScreenSpaceError.getValue(documentStopDate)).toEqual(7930); expect(e.wall.granularity.getValue(documentStartDate)).toEqual(64428); expect(e.wall.granularity.getValue(documentStopDate)).toEqual(25333); expect(e.wall.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(31, 188, 250, 46)); expect(e.wall.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(78, 91, 199, 227)); expect(e.wall.outlineColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(241, 39, 105, 205)); expect(e.wall.outlineColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(184, 17, 208, 44)); expect(e.wall.outlineWidth.getValue(documentStartDate)).toEqual(62e3); expect(e.wall.outlineWidth.getValue(documentStopDate)).toEqual(40549); expect(e.wall.distanceDisplayCondition.getValue(documentStartDate)).toEqual(new import__55.DistanceDisplayCondition(12470, 36912)); expect(e.wall.distanceDisplayCondition.getValue(documentStopDate)).toEqual(new import__55.DistanceDisplayCondition(35574, 63040)); expect(e = dataSource.entities.getById("sampled_position_cartographicRadians")).toBeDefined(); expect(e.position.getValue(documentStartDate)).toEqual(import__55.Cartesian3.fromRadians(1.00319530145806, 0.889718921347432, 16911)); expect(e.position.getValue(documentStopDate)).toEqual(import__55.Cartesian3.fromRadians(0.828301545608097, 0.517994728610812, 62937)); expect(e = dataSource.entities.getById("sampled_position_cartographicDegrees")).toBeDefined(); expect(e.position.getValue(documentStartDate)).toEqual(import__55.Cartesian3.fromDegrees(43, 23, 63733)); expect(e.position.getValue(documentStopDate)).toEqual(import__55.Cartesian3.fromDegrees(28, 12, 9806)); expect(e = dataSource.entities.getById("sampled_position_cartesianVelocity")).toBeDefined(); expect(e.position.getValue(documentStartDate)).toEqual(new import__55.Cartesian3(40342, 23709, 14940)); expect(e.position.getValue(documentStopDate)).toEqual(new import__55.Cartesian3(25648, 55396, 53208)); expect(e = dataSource.entities.getById("sampled_billboard_color_rgbaf")).toBeDefined(); expect(e.billboard.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.0235294117647059, 0.427450980392157, 0.658823529411765, 0.0980392156862745), 1e-14); expect(e.billboard.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.968627450980392, 0.752941176470588, 0.843137254901961, 0.164705882352941), 1e-14); expect(e = dataSource.entities.getById("sampled_billboard_alignedAxis_unitSpherical")).toBeDefined(); expect(e.billboard.alignedAxis.getValue(documentStartDate)).toEqualEpsilon(import__55.Cartesian3.fromSpherical(new import__55.Spherical(57328, 53471)), 1e-14); expect(e.billboard.alignedAxis.getValue(documentStopDate)).toEqualEpsilon(import__55.Cartesian3.fromSpherical(new import__55.Spherical(51360, 27848)), 1e-14); expect(e = dataSource.entities.getById("sampled_box_material_solidColor_color")).toBeDefined(); expect(e.box.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.556862745098039, 0.541176470588235, 0.956862745098039, 0.317647058823529), 1e-14); expect(e.box.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.792156862745098, 0.92156862745098, 0.125490196078431, 0.784313725490196), 1e-14); expect(e = dataSource.entities.getById("sampled_box_material_image")).toBeDefined(); expect(e.box.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(21562, 11604)); expect(e.box.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(56719, 11741)); expect(e.box.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(146, 124, 215, 53)); expect(e.box.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(229, 219, 61, 100)); expect(e = dataSource.entities.getById("sampled_box_material_grid")).toBeDefined(); expect(e.box.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(111, 151, 56, 118)); expect(e.box.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(178, 77, 41, 86)); expect(e.box.material.cellAlpha.getValue(documentStartDate)).toEqual(10400); expect(e.box.material.cellAlpha.getValue(documentStopDate)).toEqual(10941); expect(e.box.material.lineCount.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(3433, 28173)); expect(e.box.material.lineCount.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(53350, 6864)); expect(e.box.material.lineThickness.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(36990, 37264)); expect(e.box.material.lineThickness.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(38412, 45974)); expect(e.box.material.lineOffset.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(38761, 46487)); expect(e.box.material.lineOffset.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(62553, 37876)); expect(e = dataSource.entities.getById("sampled_box_material_stripe")).toBeDefined(); expect(e.box.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(251, 59, 84, 41)); expect(e.box.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(20, 214, 81, 152)); expect(e.box.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(233, 71, 17, 115)); expect(e.box.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(20, 178, 40, 30)); expect(e.box.material.offset.getValue(documentStartDate)).toEqual(46979); expect(e.box.material.offset.getValue(documentStopDate)).toEqual(1457); expect(e.box.material.repeat.getValue(documentStartDate)).toEqual(10283); expect(e.box.material.repeat.getValue(documentStopDate)).toEqual(63419); expect(e = dataSource.entities.getById("sampled_box_material_checkerboard")).toBeDefined(); expect(e.box.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(2, 215, 87, 218)); expect(e.box.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(164, 235, 142, 227)); expect(e.box.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(117, 88, 89, 243)); expect(e.box.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(104, 182, 78, 49)); expect(e.box.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(6238, 42520)); expect(e.box.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(34685, 17543)); expect(e = dataSource.entities.getById("sampled_box_material_image_color")).toBeDefined(); expect(e.box.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.149019607843137, 0.929411764705882, 0.462745098039216, 0.764705882352941), 1e-14); expect(e.box.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.890196078431372, 0.262745098039216, 0.866666666666667, 0.792156862745098), 1e-14); expect(e = dataSource.entities.getById("sampled_box_material_grid_color")).toBeDefined(); expect(e.box.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.501960784313725, 0.447058823529412, 0.72156862745098, 0.392156862745098), 1e-14); expect(e.box.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.890196078431372, 0.505882352941176, 0.56078431372549, 0.674509803921569), 1e-14); expect(e = dataSource.entities.getById("sampled_box_material_stripe_evenColor")).toBeDefined(); expect(e.box.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.980392156862745, 0.345098039215686, 0.929411764705882, 0.533333333333333), 1e-14); expect(e.box.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.988235294117647, 0.372549019607843, 0.713725490196078, 0.466666666666667), 1e-14); expect(e = dataSource.entities.getById("sampled_box_material_stripe_oddColor")).toBeDefined(); expect(e.box.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.545098039215686, 0.168627450980392, 0.654901960784314, 0.196078431372549), 1e-14); expect(e.box.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.407843137254902, 0.450980392156863, 0.874509803921569, 0.603921568627451), 1e-14); expect(e = dataSource.entities.getById("sampled_box_material_checkerboard_evenColor")).toBeDefined(); expect(e.box.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.137254901960784, 0.937254901960784, 0.513725490196078, 0.87843137254902), 1e-14); expect(e.box.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.72156862745098, 0.0666666666666667, 0.274509803921569, 0.207843137254902), 1e-14); expect(e = dataSource.entities.getById("sampled_box_material_checkerboard_oddColor")).toBeDefined(); expect(e.box.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.352941176470588, 0.274509803921569, 0.850980392156863, 0.00784313725490196), 1e-14); expect(e.box.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.83921568627451, 0.780392156862745, 0.796078431372549, 0.384313725490196), 1e-14); expect(e = dataSource.entities.getById("sampled_box_outlineColor_rgbaf")).toBeDefined(); expect(e.box.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.215686274509804, 0.498039215686275, 0.274509803921569, 0.129411764705882), 1e-14); expect(e.box.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.854901960784314, 0.729411764705882, 0.172549019607843, 0.956862745098039), 1e-14); expect(e = dataSource.entities.getById("sampled_corridor_material_solidColor_color")).toBeDefined(); expect(e.corridor.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.858823529411765, 0.988235294117647, 0.733333333333333, 0.690196078431373), 1e-14); expect(e.corridor.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.549019607843137, 0.368627450980392, 0.964705882352941, 0.133333333333333), 1e-14); expect(e = dataSource.entities.getById("sampled_corridor_material_image")).toBeDefined(); expect(e.corridor.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(14885, 62522)); expect(e.corridor.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(45129, 25776)); expect(e.corridor.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(57, 37, 208, 54)); expect(e.corridor.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(24, 80, 140, 151)); expect(e = dataSource.entities.getById("sampled_corridor_material_grid")).toBeDefined(); expect(e.corridor.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(130, 99, 15, 168)); expect(e.corridor.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(246, 60, 236, 5)); expect(e.corridor.material.cellAlpha.getValue(documentStartDate)).toEqual(22161); expect(e.corridor.material.cellAlpha.getValue(documentStopDate)).toEqual(55997); expect(e.corridor.material.lineCount.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(7285, 25116)); expect(e.corridor.material.lineCount.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(18095, 8262)); expect(e.corridor.material.lineThickness.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(31150, 55929)); expect(e.corridor.material.lineThickness.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(40043, 22428)); expect(e.corridor.material.lineOffset.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(41105, 52128)); expect(e.corridor.material.lineOffset.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(2387, 32009)); expect(e = dataSource.entities.getById("sampled_corridor_material_stripe")).toBeDefined(); expect(e.corridor.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(8, 64, 254, 66)); expect(e.corridor.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(47, 28, 112, 168)); expect(e.corridor.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(17, 233, 150, 181)); expect(e.corridor.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(171, 148, 181, 68)); expect(e.corridor.material.offset.getValue(documentStartDate)).toEqual(21351); expect(e.corridor.material.offset.getValue(documentStopDate)).toEqual(20709); expect(e.corridor.material.repeat.getValue(documentStartDate)).toEqual(25188); expect(e.corridor.material.repeat.getValue(documentStopDate)).toEqual(19705); expect(e = dataSource.entities.getById("sampled_corridor_material_checkerboard")).toBeDefined(); expect(e.corridor.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(135, 211, 180, 110)); expect(e.corridor.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(44, 134, 8, 155)); expect(e.corridor.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(212, 71, 156, 47)); expect(e.corridor.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(34, 36, 157, 104)); expect(e.corridor.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(62107, 62450)); expect(e.corridor.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(51782, 25290)); expect(e = dataSource.entities.getById("sampled_corridor_material_image_color")).toBeDefined(); expect(e.corridor.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.949019607843137, 0.666666666666667, 0.0588235294117647, 0.784313725490196), 1e-14); expect(e.corridor.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.388235294117647, 0.262745098039216, 0.764705882352941, 0.882352941176471), 1e-14); expect(e = dataSource.entities.getById("sampled_corridor_material_grid_color")).toBeDefined(); expect(e.corridor.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.290196078431373, 0.83921568627451, 0.588235294117647, 0.525490196078431), 1e-14); expect(e.corridor.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.266666666666667, 0.00392156862745098, 0.180392156862745, 0.701960784313725), 1e-14); expect(e = dataSource.entities.getById("sampled_corridor_material_stripe_evenColor")).toBeDefined(); expect(e.corridor.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.517647058823529, 0.282352941176471, 0.709803921568627, 0.737254901960784), 1e-14); expect(e.corridor.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.564705882352941, 0.407843137254902, 0.945098039215686, 0.666666666666667), 1e-14); expect(e = dataSource.entities.getById("sampled_corridor_material_stripe_oddColor")).toBeDefined(); expect(e.corridor.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.137254901960784, 0.4, 0.356862745098039, 0.501960784313725), 1e-14); expect(e.corridor.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.992156862745098, 0.431372549019608, 0.301960784313725, 0.254901960784314), 1e-14); expect(e = dataSource.entities.getById("sampled_corridor_material_checkerboard_evenColor")).toBeDefined(); expect(e.corridor.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.294117647058824, 0.0588235294117647, 0.149019607843137, 0.756862745098039), 1e-14); expect(e.corridor.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.243137254901961, 0.56078431372549, 0.254901960784314, 0.83921568627451), 1e-14); expect(e = dataSource.entities.getById("sampled_corridor_material_checkerboard_oddColor")).toBeDefined(); expect(e.corridor.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.768627450980392, 0.650980392156863, 0.529411764705882, 0.372549019607843), 1e-14); expect(e.corridor.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.12156862745098, 0.780392156862745, 0.745098039215686, 0.725490196078431), 1e-14); expect(e = dataSource.entities.getById("sampled_corridor_outlineColor_rgbaf")).toBeDefined(); expect(e.corridor.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.882352941176471, 0.262745098039216, 0.247058823529412, 0.937254901960784), 1e-14); expect(e.corridor.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.701960784313725, 0.262745098039216, 0.0627450980392157, 0.627450980392157), 1e-14); expect(e = dataSource.entities.getById("sampled_cylinder_material_solidColor_color")).toBeDefined(); expect(e.cylinder.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.117647058823529, 0.349019607843137, 0.411764705882353, 0.105882352941176), 1e-14); expect(e.cylinder.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.513725490196078, 0.513725490196078, 0.666666666666667, 0.596078431372549), 1e-14); expect(e = dataSource.entities.getById("sampled_cylinder_material_image")).toBeDefined(); expect(e.cylinder.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(42846, 26023)); expect(e.cylinder.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(19184, 35658)); expect(e.cylinder.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(59, 239, 245, 44)); expect(e.cylinder.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(77, 93, 176, 39)); expect(e = dataSource.entities.getById("sampled_cylinder_material_grid")).toBeDefined(); expect(e.cylinder.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(211, 199, 71, 148)); expect(e.cylinder.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(142, 126, 167, 247)); expect(e.cylinder.material.cellAlpha.getValue(documentStartDate)).toEqual(12751); expect(e.cylinder.material.cellAlpha.getValue(documentStopDate)).toEqual(16373); expect(e.cylinder.material.lineCount.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(11469, 5164)); expect(e.cylinder.material.lineCount.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(8167, 36383)); expect(e.cylinder.material.lineThickness.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(22021, 38742)); expect(e.cylinder.material.lineThickness.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(45350, 43441)); expect(e.cylinder.material.lineOffset.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(23237, 58970)); expect(e.cylinder.material.lineOffset.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(62223, 62963)); expect(e = dataSource.entities.getById("sampled_cylinder_material_stripe")).toBeDefined(); expect(e.cylinder.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(131, 133, 216, 18)); expect(e.cylinder.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(78, 238, 32, 231)); expect(e.cylinder.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(209, 149, 133, 207)); expect(e.cylinder.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(53, 207, 16, 210)); expect(e.cylinder.material.offset.getValue(documentStartDate)).toEqual(49593); expect(e.cylinder.material.offset.getValue(documentStopDate)).toEqual(25216); expect(e.cylinder.material.repeat.getValue(documentStartDate)).toEqual(16819); expect(e.cylinder.material.repeat.getValue(documentStopDate)).toEqual(12539); expect(e = dataSource.entities.getById("sampled_cylinder_material_checkerboard")).toBeDefined(); expect(e.cylinder.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(199, 80, 86, 158)); expect(e.cylinder.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(207, 161, 23, 187)); expect(e.cylinder.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(175, 210, 242, 198)); expect(e.cylinder.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(116, 91, 127, 24)); expect(e.cylinder.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(27893, 32108)); expect(e.cylinder.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(57420, 52960)); expect(e = dataSource.entities.getById("sampled_cylinder_material_image_color")).toBeDefined(); expect(e.cylinder.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.76078431372549, 0.133333333333333, 0.231372549019608, 0.631372549019608), 1e-14); expect(e.cylinder.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.882352941176471, 0.0823529411764706, 0.8, 0.0823529411764706), 1e-14); expect(e = dataSource.entities.getById("sampled_cylinder_material_grid_color")).toBeDefined(); expect(e.cylinder.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.176470588235294, 0.407843137254902, 0.623529411764706, 0.729411764705882), 1e-14); expect(e.cylinder.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.43921568627451, 0.0745098039215686, 0.603921568627451, 0.713725490196078), 1e-14); expect(e = dataSource.entities.getById("sampled_cylinder_material_stripe_evenColor")).toBeDefined(); expect(e.cylinder.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.380392156862745, 0.149019607843137, 0.8, 0.658823529411765), 1e-14); expect(e.cylinder.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.462745098039216, 0.172549019607843, 0.325490196078431, 0.854901960784314), 1e-14); expect(e = dataSource.entities.getById("sampled_cylinder_material_stripe_oddColor")).toBeDefined(); expect(e.cylinder.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.207843137254902, 0.466666666666667, 0.427450980392157, 0.109803921568627), 1e-14); expect(e.cylinder.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.313725490196078, 0.498039215686275, 0.2, 0.423529411764706), 1e-14); expect(e = dataSource.entities.getById("sampled_cylinder_material_checkerboard_evenColor")).toBeDefined(); expect(e.cylinder.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.52156862745098, 0.72156862745098, 0.294117647058824, 0.513725490196078), 1e-14); expect(e.cylinder.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.964705882352941, 0.411764705882353, 0.0549019607843137, 0.0392156862745098), 1e-14); expect(e = dataSource.entities.getById("sampled_cylinder_material_checkerboard_oddColor")).toBeDefined(); expect(e.cylinder.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.784313725490196, 0.309803921568627, 0.0666666666666667, 0.403921568627451), 1e-14); expect(e.cylinder.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.643137254901961, 0.737254901960784, 0.337254901960784, 0.925490196078431), 1e-14); expect(e = dataSource.entities.getById("sampled_cylinder_outlineColor_rgbaf")).toBeDefined(); expect(e.cylinder.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.780392156862745, 0.658823529411765, 0.235294117647059, 0.0705882352941176), 1e-14); expect(e.cylinder.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.643137254901961, 0.372549019607843, 0.16078431372549, 0.588235294117647), 1e-14); expect(e = dataSource.entities.getById("sampled_ellipse_material_solidColor_color")).toBeDefined(); expect(e.ellipse.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.67843137254902, 0.807843137254902, 0.541176470588235, 0.290196078431373), 1e-14); expect(e.ellipse.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.749019607843137, 0.258823529411765, 0.733333333333333, 0.247058823529412), 1e-14); expect(e = dataSource.entities.getById("sampled_ellipse_material_image")).toBeDefined(); expect(e.ellipse.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(41027, 32928)); expect(e.ellipse.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(30513, 54647)); expect(e.ellipse.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(243, 25, 233, 224)); expect(e.ellipse.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(230, 62, 9, 20)); expect(e = dataSource.entities.getById("sampled_ellipse_material_grid")).toBeDefined(); expect(e.ellipse.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(103, 140, 88, 233)); expect(e.ellipse.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(224, 133, 210, 4)); expect(e.ellipse.material.cellAlpha.getValue(documentStartDate)).toEqual(39159); expect(e.ellipse.material.cellAlpha.getValue(documentStopDate)).toEqual(47494); expect(e.ellipse.material.lineCount.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(40987, 3488)); expect(e.ellipse.material.lineCount.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(5066, 58131)); expect(e.ellipse.material.lineThickness.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(11466, 25388)); expect(e.ellipse.material.lineThickness.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(17761, 21317)); expect(e.ellipse.material.lineOffset.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(478, 18945)); expect(e.ellipse.material.lineOffset.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(25914, 29541)); expect(e = dataSource.entities.getById("sampled_ellipse_material_stripe")).toBeDefined(); expect(e.ellipse.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(218, 225, 186, 34)); expect(e.ellipse.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(109, 193, 18, 44)); expect(e.ellipse.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(119, 198, 180, 58)); expect(e.ellipse.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(79, 137, 65, 31)); expect(e.ellipse.material.offset.getValue(documentStartDate)).toEqual(16964); expect(e.ellipse.material.offset.getValue(documentStopDate)).toEqual(16523); expect(e.ellipse.material.repeat.getValue(documentStartDate)).toEqual(50015); expect(e.ellipse.material.repeat.getValue(documentStopDate)).toEqual(64942); expect(e = dataSource.entities.getById("sampled_ellipse_material_checkerboard")).toBeDefined(); expect(e.ellipse.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(65, 135, 226, 200)); expect(e.ellipse.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(70, 33, 98, 112)); expect(e.ellipse.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(246, 224, 230, 224)); expect(e.ellipse.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(110, 127, 138, 204)); expect(e.ellipse.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(24670, 352)); expect(e.ellipse.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(16830, 33857)); expect(e = dataSource.entities.getById("sampled_ellipse_material_image_color")).toBeDefined(); expect(e.ellipse.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.207843137254902, 0.0392156862745098, 0.12156862745098, 0.611764705882353), 1e-14); expect(e.ellipse.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.611764705882353, 0.0117647058823529, 0.694117647058824, 0.576470588235294), 1e-14); expect(e = dataSource.entities.getById("sampled_ellipse_material_grid_color")).toBeDefined(); expect(e.ellipse.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.580392156862745, 0.0313725490196078, 0.27843137254902, 0.203921568627451), 1e-14); expect(e.ellipse.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.0509803921568627, 0.870588235294118, 0.117647058823529, 0.588235294117647), 1e-14); expect(e = dataSource.entities.getById("sampled_ellipse_material_stripe_evenColor")).toBeDefined(); expect(e.ellipse.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.0549019607843137, 0.117647058823529, 0.623529411764706, 0.929411764705882), 1e-14); expect(e.ellipse.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.266666666666667, 0.113725490196078, 0.937254901960784, 0.168627450980392), 1e-14); expect(e = dataSource.entities.getById("sampled_ellipse_material_stripe_oddColor")).toBeDefined(); expect(e.ellipse.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.262745098039216, 0.172549019607843, 0.282352941176471, 0.129411764705882), 1e-14); expect(e.ellipse.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.968627450980392, 0.635294117647059, 0.525490196078431, 0.831372549019608), 1e-14); expect(e = dataSource.entities.getById("sampled_ellipse_material_checkerboard_evenColor")).toBeDefined(); expect(e.ellipse.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.207843137254902, 0.156862745098039, 0.952941176470588, 0.717647058823529), 1e-14); expect(e.ellipse.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.635294117647059, 0.835294117647059, 0.76078431372549, 0.235294117647059), 1e-14); expect(e = dataSource.entities.getById("sampled_ellipse_material_checkerboard_oddColor")).toBeDefined(); expect(e.ellipse.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.890196078431372, 0.141176470588235, 0.231372549019608, 0.623529411764706), 1e-14); expect(e.ellipse.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.192156862745098, 0.294117647058824, 0.741176470588235, 0.0274509803921569), 1e-14); expect(e = dataSource.entities.getById("sampled_ellipse_outlineColor_rgbaf")).toBeDefined(); expect(e.ellipse.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.76078431372549, 0.36078431372549, 0.223529411764706, 0.611764705882353), 1e-14); expect(e.ellipse.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.16078431372549, 0.83921568627451, 0.752941176470588, 0.647058823529412), 1e-14); expect(e = dataSource.entities.getById("sampled_ellipsoid_material_solidColor_color")).toBeDefined(); expect(e.ellipsoid.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.592156862745098, 0.976470588235294, 0.207843137254902, 0.501960784313725), 1e-14); expect(e.ellipsoid.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.0901960784313725, 0.662745098039216, 0.819607843137255, 0.235294117647059), 1e-14); expect(e = dataSource.entities.getById("sampled_ellipsoid_material_image")).toBeDefined(); expect(e.ellipsoid.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(63583, 15096)); expect(e.ellipsoid.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(48977, 60351)); expect(e.ellipsoid.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(49, 50, 177, 104)); expect(e.ellipsoid.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(131, 27, 208, 157)); expect(e = dataSource.entities.getById("sampled_ellipsoid_material_grid")).toBeDefined(); expect(e.ellipsoid.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(121, 105, 70, 72)); expect(e.ellipsoid.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(204, 122, 157, 57)); expect(e.ellipsoid.material.cellAlpha.getValue(documentStartDate)).toEqual(39442); expect(e.ellipsoid.material.cellAlpha.getValue(documentStopDate)).toEqual(463); expect(e.ellipsoid.material.lineCount.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(33778, 30083)); expect(e.ellipsoid.material.lineCount.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(5202, 18708)); expect(e.ellipsoid.material.lineThickness.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(44058, 37804)); expect(e.ellipsoid.material.lineThickness.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(34449, 3718)); expect(e.ellipsoid.material.lineOffset.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(33149, 21889)); expect(e.ellipsoid.material.lineOffset.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(35482, 10122)); expect(e = dataSource.entities.getById("sampled_ellipsoid_material_stripe")).toBeDefined(); expect(e.ellipsoid.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(153, 245, 201, 196)); expect(e.ellipsoid.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(245, 113, 5, 131)); expect(e.ellipsoid.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(99, 151, 174, 111)); expect(e.ellipsoid.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(188, 89, 18, 1)); expect(e.ellipsoid.material.offset.getValue(documentStartDate)).toEqual(44961); expect(e.ellipsoid.material.offset.getValue(documentStopDate)).toEqual(5690); expect(e.ellipsoid.material.repeat.getValue(documentStartDate)).toEqual(3351); expect(e.ellipsoid.material.repeat.getValue(documentStopDate)).toEqual(44332); expect(e = dataSource.entities.getById("sampled_ellipsoid_material_checkerboard")).toBeDefined(); expect(e.ellipsoid.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(147, 239, 19, 56)); expect(e.ellipsoid.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(5, 32, 143, 178)); expect(e.ellipsoid.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(131, 51, 246, 186)); expect(e.ellipsoid.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(214, 117, 149, 89)); expect(e.ellipsoid.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(28116, 51821)); expect(e.ellipsoid.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(60296, 50923)); expect(e = dataSource.entities.getById("sampled_ellipsoid_material_image_color")).toBeDefined(); expect(e.ellipsoid.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.654901960784314, 0.517647058823529, 0.858823529411765, 0.486274509803922), 1e-14); expect(e.ellipsoid.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.862745098039216, 0.713725490196078, 0.564705882352941, 0.0901960784313725), 1e-14); expect(e = dataSource.entities.getById("sampled_ellipsoid_material_grid_color")).toBeDefined(); expect(e.ellipsoid.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.6, 0.427450980392157, 0.203921568627451, 0.223529411764706), 1e-14); expect(e.ellipsoid.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.525490196078431, 0.305882352941176, 0.16078431372549, 0.819607843137255), 1e-14); expect(e = dataSource.entities.getById("sampled_ellipsoid_material_stripe_evenColor")).toBeDefined(); expect(e.ellipsoid.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.301960784313725, 0.572549019607843, 0.87843137254902, 0.219607843137255), 1e-14); expect(e.ellipsoid.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.337254901960784, 0.835294117647059, 0.964705882352941, 0.909803921568627), 1e-14); expect(e = dataSource.entities.getById("sampled_ellipsoid_material_stripe_oddColor")).toBeDefined(); expect(e.ellipsoid.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.647058823529412, 0.635294117647059, 0.258823529411765, 0.250980392156863), 1e-14); expect(e.ellipsoid.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.917647058823529, 0.262745098039216, 0.666666666666667, 0.980392156862745), 1e-14); expect(e = dataSource.entities.getById("sampled_ellipsoid_material_checkerboard_evenColor")).toBeDefined(); expect(e.ellipsoid.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.819607843137255, 0.282352941176471, 0.929411764705882, 0.501960784313725), 1e-14); expect(e.ellipsoid.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.850980392156863, 0.294117647058824, 0.498039215686275, 0.956862745098039), 1e-14); expect(e = dataSource.entities.getById("sampled_ellipsoid_material_checkerboard_oddColor")).toBeDefined(); expect(e.ellipsoid.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.227450980392157, 0.862745098039216, 0.890196078431372, 0.207843137254902), 1e-14); expect(e.ellipsoid.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.796078431372549, 0.0470588235294118, 0.843137254901961, 0.388235294117647), 1e-14); expect(e = dataSource.entities.getById("sampled_ellipsoid_outlineColor_rgbaf")).toBeDefined(); expect(e.ellipsoid.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.552941176470588, 0.549019607843137, 0.431372549019608, 0.568627450980392), 1e-14); expect(e.ellipsoid.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.435294117647059, 0.698039215686274, 0.396078431372549, 0.772549019607843), 1e-14); expect(e = dataSource.entities.getById("sampled_label_backgroundColor_rgbaf")).toBeDefined(); expect(e.label.backgroundColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.96078431372549, 0.188235294117647, 0.870588235294118, 0.270588235294118), 1e-14); expect(e.label.backgroundColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.882352941176471, 0.796078431372549, 0.603921568627451, 0.823529411764706), 1e-14); expect(e = dataSource.entities.getById("sampled_label_fillColor_rgbaf")).toBeDefined(); expect(e.label.fillColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.709803921568627, 0.556862745098039, 0.337254901960784, 0.247058823529412), 1e-14); expect(e.label.fillColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.43921568627451, 0.694117647058824, 0.901960784313726, 0.0823529411764706), 1e-14); expect(e = dataSource.entities.getById("sampled_label_outlineColor_rgbaf")).toBeDefined(); expect(e.label.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.631372549019608, 0.709803921568627, 0.270588235294118, 0.792156862745098), 1e-14); expect(e.label.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.435294117647059, 0.176470588235294, 0.235294117647059, 0.631372549019608), 1e-14); expect(e = dataSource.entities.getById("sampled_model_silhouetteColor_rgbaf")).toBeDefined(); expect(e.model.silhouetteColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.231372549019608, 0.866666666666667, 0.266666666666667, 0.635294117647059), 1e-14); expect(e.model.silhouetteColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.749019607843137, 0.227450980392157, 0.807843137254902, 0.0823529411764706), 1e-14); expect(e = dataSource.entities.getById("sampled_model_color_rgbaf")).toBeDefined(); expect(e.model.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.0509803921568627, 0.83921568627451, 0.470588235294118, 0.956862745098039), 1e-14); expect(e.model.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.435294117647059, 0.945098039215686, 0.431372549019608, 0.619607843137255), 1e-14); expect(e = dataSource.entities.getById("sampled_path_material_solidColor_color")).toBeDefined(); expect(e.path.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.517647058823529, 0.56078431372549, 0.254901960784314, 0.494117647058824), 1e-14); expect(e.path.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.905882352941176, 0.152941176470588, 0.854901960784314, 0.890196078431372), 1e-14); expect(e = dataSource.entities.getById("sampled_path_material_polylineOutline")).toBeDefined(); expect(e.path.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(209, 154, 35, 76)); expect(e.path.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(186, 25, 242, 140)); expect(e.path.material.outlineColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(218, 241, 216, 157)); expect(e.path.material.outlineColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(70, 200, 183, 199)); expect(e.path.material.outlineWidth.getValue(documentStartDate)).toEqual(2699); expect(e.path.material.outlineWidth.getValue(documentStopDate)).toEqual(1320); expect(e = dataSource.entities.getById("sampled_path_material_polylineArrow")).toBeDefined(); expect(e.path.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(150, 221, 161, 136)); expect(e.path.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(19, 231, 68, 117)); expect(e = dataSource.entities.getById("sampled_path_material_polylineDash")).toBeDefined(); expect(e.path.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(140, 167, 151, 119)); expect(e.path.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(65, 100, 228, 104)); expect(e.path.material.gapColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(154, 198, 168, 151)); expect(e.path.material.gapColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(16, 23, 0, 42)); expect(e.path.material.dashLength.getValue(documentStartDate)).toEqual(38294); expect(e.path.material.dashLength.getValue(documentStopDate)).toEqual(33057); expect(e.path.material.dashPattern.getValue(documentStartDate)).toEqual(58660); expect(e.path.material.dashPattern.getValue(documentStopDate)).toEqual(3340); expect(e = dataSource.entities.getById("sampled_path_material_polylineGlow")).toBeDefined(); expect(e.path.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(197, 117, 196, 254)); expect(e.path.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(18, 17, 195, 230)); expect(e.path.material.glowPower.getValue(documentStartDate)).toEqual(5579); expect(e.path.material.glowPower.getValue(documentStopDate)).toEqual(59951); expect(e.path.material.taperPower.getValue(documentStartDate)).toEqual(30159); expect(e.path.material.taperPower.getValue(documentStopDate)).toEqual(35636); expect(e = dataSource.entities.getById("sampled_path_material_image")).toBeDefined(); expect(e.path.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(25033, 47457)); expect(e.path.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(30413, 15734)); expect(e.path.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(225, 149, 237, 92)); expect(e.path.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(234, 146, 229, 9)); expect(e = dataSource.entities.getById("sampled_path_material_grid")).toBeDefined(); expect(e.path.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(99, 177, 19, 203)); expect(e.path.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(231, 169, 202, 127)); expect(e.path.material.cellAlpha.getValue(documentStartDate)).toEqual(63572); expect(e.path.material.cellAlpha.getValue(documentStopDate)).toEqual(26232); expect(e.path.material.lineCount.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(34101, 5509)); expect(e.path.material.lineCount.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(11991, 23086)); expect(e.path.material.lineThickness.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(39225, 58265)); expect(e.path.material.lineThickness.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(60443, 36332)); expect(e.path.material.lineOffset.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(25536, 59747)); expect(e.path.material.lineOffset.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(43164, 57256)); expect(e = dataSource.entities.getById("sampled_path_material_stripe")).toBeDefined(); expect(e.path.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(252, 51, 215, 123)); expect(e.path.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(164, 66, 75, 80)); expect(e.path.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(192, 190, 37, 99)); expect(e.path.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(196, 81, 62, 248)); expect(e.path.material.offset.getValue(documentStartDate)).toEqual(45320); expect(e.path.material.offset.getValue(documentStopDate)).toEqual(41173); expect(e.path.material.repeat.getValue(documentStartDate)).toEqual(42078); expect(e.path.material.repeat.getValue(documentStopDate)).toEqual(11633); expect(e = dataSource.entities.getById("sampled_path_material_checkerboard")).toBeDefined(); expect(e.path.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(29, 130, 90, 174)); expect(e.path.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(42, 131, 191, 181)); expect(e.path.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(32, 82, 30, 56)); expect(e.path.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(161, 13, 144, 118)); expect(e.path.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(14368, 54840)); expect(e.path.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(58386, 2276)); expect(e = dataSource.entities.getById("sampled_path_material_polylineOutline_color")).toBeDefined(); expect(e.path.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.490196078431373, 0.498039215686275, 0.819607843137255, 0.72156862745098), 1e-14); expect(e.path.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.309803921568627, 0.329411764705882, 0.807843137254902, 0.368627450980392), 1e-14); expect(e = dataSource.entities.getById("sampled_path_material_polylineOutline_outlineColor")).toBeDefined(); expect(e.path.material.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.427450980392157, 0.96078431372549, 0.996078431372549, 0.662745098039216), 1e-14); expect(e.path.material.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.917647058823529, 0.635294117647059, 0.674509803921569, 0.298039215686275), 1e-14); expect(e = dataSource.entities.getById("sampled_path_material_polylineArrow_color")).toBeDefined(); expect(e.path.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.0666666666666667, 0.972549019607843, 0.686274509803922, 0.325490196078431), 1e-14); expect(e.path.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.2, 0.482352941176471, 0.498039215686275, 0.219607843137255), 1e-14); expect(e = dataSource.entities.getById("sampled_path_material_polylineDash_color")).toBeDefined(); expect(e.path.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.803921568627451, 0.67843137254902, 0.176470588235294, 0.709803921568627), 1e-14); expect(e.path.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.674509803921569, 0.0980392156862745, 0.447058823529412, 0.803921568627451), 1e-14); expect(e = dataSource.entities.getById("sampled_path_material_polylineDash_gapColor")).toBeDefined(); expect(e.path.material.gapColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.231372549019608, 0.745098039215686, 0.772549019607843, 0.901960784313726), 1e-14); expect(e.path.material.gapColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.713725490196078, 0.180392156862745, 0.317647058823529, 0.309803921568627), 1e-14); expect(e = dataSource.entities.getById("sampled_path_material_polylineGlow_color")).toBeDefined(); expect(e.path.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.63921568627451, 0.2, 0.0196078431372549, 0.984313725490196), 1e-14); expect(e.path.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.376470588235294, 0.815686274509804, 0.933333333333333, 0.0235294117647059), 1e-14); expect(e = dataSource.entities.getById("sampled_path_material_image_color")).toBeDefined(); expect(e.path.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.898039215686275, 0.772549019607843, 0.294117647058824, 0.0431372549019608), 1e-14); expect(e.path.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.815686274509804, 0.0901960784313725, 0.898039215686275, 0.309803921568627), 1e-14); expect(e = dataSource.entities.getById("sampled_path_material_grid_color")).toBeDefined(); expect(e.path.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.890196078431372, 0, 0.717647058823529, 0.329411764705882), 1e-14); expect(e.path.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.474509803921569, 0.690196078431373, 0.0431372549019608, 0.258823529411765), 1e-14); expect(e = dataSource.entities.getById("sampled_path_material_stripe_evenColor")).toBeDefined(); expect(e.path.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.368627450980392, 0.584313725490196, 0.831372549019608, 0.541176470588235), 1e-14); expect(e.path.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.317647058823529, 0.4, 0.83921568627451, 0.537254901960784), 1e-14); expect(e = dataSource.entities.getById("sampled_path_material_stripe_oddColor")).toBeDefined(); expect(e.path.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.145098039215686, 0.588235294117647, 0.917647058823529, 0.607843137254902), 1e-14); expect(e.path.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.117647058823529, 0.0705882352941176, 0.901960784313726, 0.525490196078431), 1e-14); expect(e = dataSource.entities.getById("sampled_path_material_checkerboard_evenColor")).toBeDefined(); expect(e.path.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.631372549019608, 0.741176470588235, 0.282352941176471, 0.196078431372549), 1e-14); expect(e.path.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.250980392156863, 0.109803921568627, 0.188235294117647, 0.796078431372549), 1e-14); expect(e = dataSource.entities.getById("sampled_path_material_checkerboard_oddColor")).toBeDefined(); expect(e.path.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.388235294117647, 0.129411764705882, 0.333333333333333, 0.658823529411765), 1e-14); expect(e.path.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.156862745098039, 0.631372549019608, 0.290196078431373, 0.713725490196078), 1e-14); expect(e = dataSource.entities.getById("sampled_point_color_rgbaf")).toBeDefined(); expect(e.point.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.67843137254902, 0.356862745098039, 0.588235294117647, 0.796078431372549), 1e-14); expect(e.point.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.968627450980392, 0.298039215686275, 0.513725490196078, 0.631372549019608), 1e-14); expect(e = dataSource.entities.getById("sampled_point_outlineColor_rgbaf")).toBeDefined(); expect(e.point.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.427450980392157, 0.894117647058824, 0.168627450980392, 0.768627450980392), 1e-14); expect(e.point.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.458823529411765, 0.466666666666667, 0.388235294117647, 0.792156862745098), 1e-14); expect(e = dataSource.entities.getById("sampled_polygon_material_solidColor_color")).toBeDefined(); expect(e.polygon.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.305882352941176, 0.615686274509804, 0.337254901960784, 0.894117647058824), 1e-14); expect(e.polygon.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.184313725490196, 0.619607843137255, 0.352941176470588, 0.0313725490196078), 1e-14); expect(e = dataSource.entities.getById("sampled_polygon_material_image")).toBeDefined(); expect(e.polygon.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(19536, 17484)); expect(e.polygon.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(46291, 28852)); expect(e.polygon.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(157, 5, 231, 29)); expect(e.polygon.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(53, 2, 148, 36)); expect(e = dataSource.entities.getById("sampled_polygon_material_grid")).toBeDefined(); expect(e.polygon.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(179, 243, 247, 124)); expect(e.polygon.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(15, 128, 159, 42)); expect(e.polygon.material.cellAlpha.getValue(documentStartDate)).toEqual(11565); expect(e.polygon.material.cellAlpha.getValue(documentStopDate)).toEqual(42611); expect(e.polygon.material.lineCount.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(47065, 65463)); expect(e.polygon.material.lineCount.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(29170, 16497)); expect(e.polygon.material.lineThickness.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(62674, 26868)); expect(e.polygon.material.lineThickness.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(22008, 39509)); expect(e.polygon.material.lineOffset.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(28793, 1648)); expect(e.polygon.material.lineOffset.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(44991, 42159)); expect(e = dataSource.entities.getById("sampled_polygon_material_stripe")).toBeDefined(); expect(e.polygon.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(113, 233, 143, 146)); expect(e.polygon.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(106, 138, 115, 44)); expect(e.polygon.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(104, 146, 138, 244)); expect(e.polygon.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(161, 95, 25, 36)); expect(e.polygon.material.offset.getValue(documentStartDate)).toEqual(4711); expect(e.polygon.material.offset.getValue(documentStopDate)).toEqual(65087); expect(e.polygon.material.repeat.getValue(documentStartDate)).toEqual(44013); expect(e.polygon.material.repeat.getValue(documentStopDate)).toEqual(7595); expect(e = dataSource.entities.getById("sampled_polygon_material_checkerboard")).toBeDefined(); expect(e.polygon.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(167, 56, 202, 219)); expect(e.polygon.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(231, 169, 74, 125)); expect(e.polygon.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(88, 174, 167, 35)); expect(e.polygon.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(12, 69, 69, 23)); expect(e.polygon.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(32132, 20093)); expect(e.polygon.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(31300, 27514)); expect(e = dataSource.entities.getById("sampled_polygon_material_image_color")).toBeDefined(); expect(e.polygon.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.501960784313725, 0.0823529411764706, 0.282352941176471, 0.305882352941176), 1e-14); expect(e.polygon.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.0745098039215686, 0.654901960784314, 0.6, 0.886274509803922), 1e-14); expect(e = dataSource.entities.getById("sampled_polygon_material_grid_color")).toBeDefined(); expect(e.polygon.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.192156862745098, 0.709803921568627, 0.807843137254902, 0.737254901960784), 1e-14); expect(e.polygon.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.674509803921569, 0.0235294117647059, 0.764705882352941, 0.976470588235294), 1e-14); expect(e = dataSource.entities.getById("sampled_polygon_material_stripe_evenColor")).toBeDefined(); expect(e.polygon.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.568627450980392, 0.352941176470588, 0.396078431372549, 0.435294117647059), 1e-14); expect(e.polygon.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.274509803921569, 0.43921568627451, 0.686274509803922, 0.419607843137255), 1e-14); expect(e = dataSource.entities.getById("sampled_polygon_material_stripe_oddColor")).toBeDefined(); expect(e.polygon.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.325490196078431, 0.349019607843137, 0.580392156862745, 0.725490196078431), 1e-14); expect(e.polygon.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.568627450980392, 0.690196078431373, 0.00392156862745098, 0.858823529411765), 1e-14); expect(e = dataSource.entities.getById("sampled_polygon_material_checkerboard_evenColor")).toBeDefined(); expect(e.polygon.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.831372549019608, 0.454901960784314, 0.882352941176471, 0.270588235294118), 1e-14); expect(e.polygon.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.494117647058824, 0.384313725490196, 0.345098039215686, 0.16078431372549), 1e-14); expect(e = dataSource.entities.getById("sampled_polygon_material_checkerboard_oddColor")).toBeDefined(); expect(e.polygon.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.0117647058823529, 0.905882352941176, 0.592156862745098, 0.784313725490196), 1e-14); expect(e.polygon.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.427450980392157, 0.701960784313725, 0.0901960784313725, 0.643137254901961), 1e-14); expect(e = dataSource.entities.getById("sampled_polygon_outlineColor_rgbaf")).toBeDefined(); expect(e.polygon.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.674509803921569, 0.556862745098039, 0.113725490196078, 0.6), 1e-14); expect(e.polygon.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.650980392156863, 0.827450980392157, 0.537254901960784, 0.713725490196078), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_material_solidColor_color")).toBeDefined(); expect(e.polyline.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.976470588235294, 0.949019607843137, 0.450980392156863, 0.466666666666667), 1e-14); expect(e.polyline.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.262745098039216, 0.509803921568627, 0.537254901960784, 0.850980392156863), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_material_polylineOutline")).toBeDefined(); expect(e.polyline.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(245, 92, 109, 218)); expect(e.polyline.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(241, 96, 196, 167)); expect(e.polyline.material.outlineColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(174, 2, 11, 244)); expect(e.polyline.material.outlineColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(31, 126, 140, 138)); expect(e.polyline.material.outlineWidth.getValue(documentStartDate)).toEqual(33279); expect(e.polyline.material.outlineWidth.getValue(documentStopDate)).toEqual(26855); expect(e = dataSource.entities.getById("sampled_polyline_material_polylineArrow")).toBeDefined(); expect(e.polyline.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(141, 137, 252, 157)); expect(e.polyline.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(8, 236, 198, 57)); expect(e = dataSource.entities.getById("sampled_polyline_material_polylineDash")).toBeDefined(); expect(e.polyline.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(77, 159, 238, 158)); expect(e.polyline.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(206, 194, 234, 158)); expect(e.polyline.material.gapColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(232, 145, 15, 164)); expect(e.polyline.material.gapColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(173, 151, 118, 138)); expect(e.polyline.material.dashLength.getValue(documentStartDate)).toEqual(41757); expect(e.polyline.material.dashLength.getValue(documentStopDate)).toEqual(10126); expect(e.polyline.material.dashPattern.getValue(documentStartDate)).toEqual(33948); expect(e.polyline.material.dashPattern.getValue(documentStopDate)).toEqual(16892); expect(e = dataSource.entities.getById("sampled_polyline_material_polylineGlow")).toBeDefined(); expect(e.polyline.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(174, 178, 78, 176)); expect(e.polyline.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(79, 191, 38, 195)); expect(e.polyline.material.glowPower.getValue(documentStartDate)).toEqual(55378); expect(e.polyline.material.glowPower.getValue(documentStopDate)).toEqual(60643); expect(e.polyline.material.taperPower.getValue(documentStartDate)).toEqual(50068); expect(e.polyline.material.taperPower.getValue(documentStopDate)).toEqual(2516); expect(e = dataSource.entities.getById("sampled_polyline_material_image")).toBeDefined(); expect(e.polyline.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(50957, 35783)); expect(e.polyline.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(59533, 65e3)); expect(e.polyline.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(174, 154, 113, 185)); expect(e.polyline.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(123, 236, 118, 155)); expect(e = dataSource.entities.getById("sampled_polyline_material_grid")).toBeDefined(); expect(e.polyline.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(26, 89, 33, 224)); expect(e.polyline.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(215, 131, 203, 1)); expect(e.polyline.material.cellAlpha.getValue(documentStartDate)).toEqual(34343); expect(e.polyline.material.cellAlpha.getValue(documentStopDate)).toEqual(63863); expect(e.polyline.material.lineCount.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(52308, 51660)); expect(e.polyline.material.lineCount.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(45338, 51633)); expect(e.polyline.material.lineThickness.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(47738, 52154)); expect(e.polyline.material.lineThickness.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(42674, 38822)); expect(e.polyline.material.lineOffset.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(29194, 52338)); expect(e.polyline.material.lineOffset.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(25319, 28514)); expect(e = dataSource.entities.getById("sampled_polyline_material_stripe")).toBeDefined(); expect(e.polyline.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(141, 205, 78, 73)); expect(e.polyline.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(107, 159, 97, 34)); expect(e.polyline.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(19, 76, 127, 197)); expect(e.polyline.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(214, 222, 19, 168)); expect(e.polyline.material.offset.getValue(documentStartDate)).toEqual(51126); expect(e.polyline.material.offset.getValue(documentStopDate)).toEqual(10891); expect(e.polyline.material.repeat.getValue(documentStartDate)).toEqual(25313); expect(e.polyline.material.repeat.getValue(documentStopDate)).toEqual(22020); expect(e = dataSource.entities.getById("sampled_polyline_material_checkerboard")).toBeDefined(); expect(e.polyline.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(94, 152, 152, 31)); expect(e.polyline.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(76, 129, 223, 102)); expect(e.polyline.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(71, 237, 5, 172)); expect(e.polyline.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(209, 132, 204, 160)); expect(e.polyline.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(19943, 17997)); expect(e.polyline.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(55528, 16856)); expect(e = dataSource.entities.getById("sampled_polyline_material_polylineOutline_color")).toBeDefined(); expect(e.polyline.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.384313725490196, 0.168627450980392, 0.443137254901961, 0.658823529411765), 1e-14); expect(e.polyline.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.0274509803921569, 0.647058823529412, 0.396078431372549, 0.105882352941176), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_material_polylineOutline_outlineColor")).toBeDefined(); expect(e.polyline.material.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.0823529411764706, 0.0549019607843137, 0.149019607843137, 0.580392156862745), 1e-14); expect(e.polyline.material.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.733333333333333, 0.792156862745098, 0.63921568627451, 0.564705882352941), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_material_polylineArrow_color")).toBeDefined(); expect(e.polyline.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.52156862745098, 0.725490196078431, 0.87843137254902, 0.823529411764706), 1e-14); expect(e.polyline.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.772549019607843, 0.862745098039216, 0.325490196078431, 0), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_material_polylineDash_color")).toBeDefined(); expect(e.polyline.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.525490196078431, 0.992156862745098, 0.964705882352941, 0.364705882352941), 1e-14); expect(e.polyline.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.27843137254902, 0.133333333333333, 0.447058823529412, 0.192156862745098), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_material_polylineDash_gapColor")).toBeDefined(); expect(e.polyline.material.gapColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.498039215686275, 0.776470588235294, 0.803921568627451, 0.690196078431373), 1e-14); expect(e.polyline.material.gapColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.376470588235294, 0.898039215686275, 0.168627450980392, 0.898039215686275), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_material_polylineGlow_color")).toBeDefined(); expect(e.polyline.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.705882352941177, 0.901960784313726, 0.0784313725490196, 0.356862745098039), 1e-14); expect(e.polyline.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.517647058823529, 0.207843137254902, 0.701960784313725, 0.105882352941176), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_material_image_color")).toBeDefined(); expect(e.polyline.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.796078431372549, 0.741176470588235, 0.741176470588235, 0.349019607843137), 1e-14); expect(e.polyline.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.925490196078431, 0.266666666666667, 0.0941176470588235, 0.556862745098039), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_material_grid_color")).toBeDefined(); expect(e.polyline.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.545098039215686, 0.847058823529412, 0.341176470588235, 0.101960784313725), 1e-14); expect(e.polyline.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.431372549019608, 0.952941176470588, 0.184313725490196, 0.184313725490196), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_material_stripe_evenColor")).toBeDefined(); expect(e.polyline.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.807843137254902, 0.262745098039216, 0.898039215686275, 0.811764705882353), 1e-14); expect(e.polyline.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.415686274509804, 0.968627450980392, 0.0980392156862745, 0.423529411764706), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_material_stripe_oddColor")).toBeDefined(); expect(e.polyline.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.427450980392157, 0.407843137254902, 0.470588235294118, 0.874509803921569), 1e-14); expect(e.polyline.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.509803921568627, 0.427450980392157, 0.976470588235294, 0), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_material_checkerboard_evenColor")).toBeDefined(); expect(e.polyline.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.313725490196078, 0.415686274509804, 0.0823529411764706, 0.576470588235294), 1e-14); expect(e.polyline.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.0196078431372549, 0.309803921568627, 0.23921568627451, 0.933333333333333), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_material_checkerboard_oddColor")).toBeDefined(); expect(e.polyline.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.784313725490196, 0.235294117647059, 0.525490196078431, 0.180392156862745), 1e-14); expect(e.polyline.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.356862745098039, 0.125490196078431, 0.243137254901961, 0.788235294117647), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_solidColor_color")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.568627450980392, 0.243137254901961, 0.43921568627451, 0.541176470588235), 1e-14); expect(e.polyline.depthFailMaterial.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.729411764705882, 0.505882352941176, 0.282352941176471, 0.0274509803921569), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_polylineOutline")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(247, 124, 164, 106)); expect(e.polyline.depthFailMaterial.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(91, 114, 116, 82)); expect(e.polyline.depthFailMaterial.outlineColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(35, 216, 157, 243)); expect(e.polyline.depthFailMaterial.outlineColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(111, 11, 143, 175)); expect(e.polyline.depthFailMaterial.outlineWidth.getValue(documentStartDate)).toEqual(45494); expect(e.polyline.depthFailMaterial.outlineWidth.getValue(documentStopDate)).toEqual(8666); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_polylineArrow")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(143, 46, 33, 146)); expect(e.polyline.depthFailMaterial.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(1, 147, 34, 93)); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_polylineDash")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(64, 52, 179, 199)); expect(e.polyline.depthFailMaterial.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(251, 205, 86, 110)); expect(e.polyline.depthFailMaterial.gapColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(98, 214, 1, 23)); expect(e.polyline.depthFailMaterial.gapColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(108, 132, 28, 207)); expect(e.polyline.depthFailMaterial.dashLength.getValue(documentStartDate)).toEqual(59636); expect(e.polyline.depthFailMaterial.dashLength.getValue(documentStopDate)).toEqual(9250); expect(e.polyline.depthFailMaterial.dashPattern.getValue(documentStartDate)).toEqual(33949); expect(e.polyline.depthFailMaterial.dashPattern.getValue(documentStopDate)).toEqual(58673); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_polylineGlow")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(253, 71, 171, 138)); expect(e.polyline.depthFailMaterial.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(112, 154, 76, 178)); expect(e.polyline.depthFailMaterial.glowPower.getValue(documentStartDate)).toEqual(8542); expect(e.polyline.depthFailMaterial.glowPower.getValue(documentStopDate)).toEqual(54440); expect(e.polyline.depthFailMaterial.taperPower.getValue(documentStartDate)).toEqual(61950); expect(e.polyline.depthFailMaterial.taperPower.getValue(documentStopDate)).toEqual(36891); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_image")).toBeDefined(); expect(e.polyline.depthFailMaterial.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(59796, 25065)); expect(e.polyline.depthFailMaterial.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(38054, 9108)); expect(e.polyline.depthFailMaterial.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(32, 24, 155, 151)); expect(e.polyline.depthFailMaterial.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(9, 142, 253, 92)); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_grid")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(206, 138, 53, 173)); expect(e.polyline.depthFailMaterial.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(20, 11, 131, 253)); expect(e.polyline.depthFailMaterial.cellAlpha.getValue(documentStartDate)).toEqual(36676); expect(e.polyline.depthFailMaterial.cellAlpha.getValue(documentStopDate)).toEqual(5143); expect(e.polyline.depthFailMaterial.lineCount.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(55344, 11736)); expect(e.polyline.depthFailMaterial.lineCount.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(20410, 11343)); expect(e.polyline.depthFailMaterial.lineThickness.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(22967, 31065)); expect(e.polyline.depthFailMaterial.lineThickness.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(59168, 51431)); expect(e.polyline.depthFailMaterial.lineOffset.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(59e3, 31974)); expect(e.polyline.depthFailMaterial.lineOffset.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(65334, 48383)); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_stripe")).toBeDefined(); expect(e.polyline.depthFailMaterial.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(166, 16, 249, 230)); expect(e.polyline.depthFailMaterial.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(250, 177, 111, 216)); expect(e.polyline.depthFailMaterial.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(210, 161, 181, 206)); expect(e.polyline.depthFailMaterial.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(194, 73, 70, 224)); expect(e.polyline.depthFailMaterial.offset.getValue(documentStartDate)).toEqual(43239); expect(e.polyline.depthFailMaterial.offset.getValue(documentStopDate)).toEqual(47157); expect(e.polyline.depthFailMaterial.repeat.getValue(documentStartDate)).toEqual(58315); expect(e.polyline.depthFailMaterial.repeat.getValue(documentStopDate)).toEqual(45308); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_checkerboard")).toBeDefined(); expect(e.polyline.depthFailMaterial.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(0, 159, 59, 160)); expect(e.polyline.depthFailMaterial.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(202, 33, 125, 165)); expect(e.polyline.depthFailMaterial.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(19, 37, 14, 24)); expect(e.polyline.depthFailMaterial.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(66, 150, 238, 84)); expect(e.polyline.depthFailMaterial.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(15034, 58938)); expect(e.polyline.depthFailMaterial.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(62661, 23796)); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_polylineOutline_color")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.611764705882353, 0.407843137254902, 0.807843137254902, 0.380392156862745), 1e-14); expect(e.polyline.depthFailMaterial.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.52156862745098, 0.654901960784314, 0.756862745098039, 0.368627450980392), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_polylineOutline_outlineColor")).toBeDefined(); expect(e.polyline.depthFailMaterial.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.670588235294118, 0.211764705882353, 0.607843137254902, 0.388235294117647), 1e-14); expect(e.polyline.depthFailMaterial.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.611764705882353, 0.611764705882353, 0.298039215686275, 0.749019607843137), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_polylineArrow_color")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.874509803921569, 0.541176470588235, 0.231372549019608, 0.596078431372549), 1e-14); expect(e.polyline.depthFailMaterial.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.729411764705882, 0.533333333333333, 0.411764705882353, 0.454901960784314), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_polylineDash_color")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.776470588235294, 0.0823529411764706, 0.96078431372549, 0.776470588235294), 1e-14); expect(e.polyline.depthFailMaterial.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.0941176470588235, 0.643137254901961, 0.717647058823529, 0.890196078431372), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_polylineDash_gapColor")).toBeDefined(); expect(e.polyline.depthFailMaterial.gapColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.219607843137255, 0.403921568627451, 0.815686274509804, 0.803921568627451), 1e-14); expect(e.polyline.depthFailMaterial.gapColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.294117647058824, 0.615686274509804, 0.172549019607843, 0.0235294117647059), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_polylineGlow_color")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.168627450980392, 0.847058823529412, 0.968627450980392, 0.431372549019608), 1e-14); expect(e.polyline.depthFailMaterial.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.2, 0.603921568627451, 0.941176470588235, 0.0901960784313725), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_image_color")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.980392156862745, 0.450980392156863, 0.329411764705882, 0.670588235294118), 1e-14); expect(e.polyline.depthFailMaterial.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.556862745098039, 0.63921568627451, 0.156862745098039, 0.705882352941177), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_grid_color")).toBeDefined(); expect(e.polyline.depthFailMaterial.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.623529411764706, 0.607843137254902, 0.913725490196078, 0.596078431372549), 1e-14); expect(e.polyline.depthFailMaterial.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.423529411764706, 0.968627450980392, 0.815686274509804, 0.968627450980392), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_stripe_evenColor")).toBeDefined(); expect(e.polyline.depthFailMaterial.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.854901960784314, 0.843137254901961, 0.701960784313725, 0.113725490196078), 1e-14); expect(e.polyline.depthFailMaterial.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.941176470588235, 0.890196078431372, 0.933333333333333, 0.588235294117647), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_stripe_oddColor")).toBeDefined(); expect(e.polyline.depthFailMaterial.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.427450980392157, 0.870588235294118, 0.96078431372549, 0.219607843137255), 1e-14); expect(e.polyline.depthFailMaterial.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.219607843137255, 0.847058823529412, 0.752941176470588, 0.172549019607843), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_checkerboard_evenColor")).toBeDefined(); expect(e.polyline.depthFailMaterial.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.96078431372549, 0.0941176470588235, 0.725490196078431, 0.819607843137255), 1e-14); expect(e.polyline.depthFailMaterial.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.0588235294117647, 0.447058823529412, 0.572549019607843, 0.0549019607843137), 1e-14); expect(e = dataSource.entities.getById("sampled_polyline_depthFailMaterial_checkerboard_oddColor")).toBeDefined(); expect(e.polyline.depthFailMaterial.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.333333333333333, 0.0431372549019608, 0.886274509803922, 0.384313725490196), 1e-14); expect(e.polyline.depthFailMaterial.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.235294117647059, 0.733333333333333, 0.752941176470588, 0.537254901960784), 1e-14); expect(e = dataSource.entities.getById("sampled_polylineVolume_material_solidColor_color")).toBeDefined(); expect(e.polylineVolume.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.0235294117647059, 0.87843137254902, 0.0549019607843137, 0.76078431372549), 1e-14); expect(e.polylineVolume.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.407843137254902, 0.788235294117647, 0.580392156862745, 0.701960784313725), 1e-14); expect(e = dataSource.entities.getById("sampled_polylineVolume_material_image")).toBeDefined(); expect(e.polylineVolume.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(54883, 39382)); expect(e.polylineVolume.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(42188, 27300)); expect(e.polylineVolume.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(145, 236, 4, 141)); expect(e.polylineVolume.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(126, 69, 220, 191)); expect(e = dataSource.entities.getById("sampled_polylineVolume_material_grid")).toBeDefined(); expect(e.polylineVolume.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(98, 87, 231, 46)); expect(e.polylineVolume.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(222, 91, 113, 105)); expect(e.polylineVolume.material.cellAlpha.getValue(documentStartDate)).toEqual(32451); expect(e.polylineVolume.material.cellAlpha.getValue(documentStopDate)).toEqual(49677); expect(e.polylineVolume.material.lineCount.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(14089, 52279)); expect(e.polylineVolume.material.lineCount.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(59996, 36842)); expect(e.polylineVolume.material.lineThickness.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(49037, 8639)); expect(e.polylineVolume.material.lineThickness.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(59785, 47337)); expect(e.polylineVolume.material.lineOffset.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(40768, 50335)); expect(e.polylineVolume.material.lineOffset.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(6098, 48919)); expect(e = dataSource.entities.getById("sampled_polylineVolume_material_stripe")).toBeDefined(); expect(e.polylineVolume.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(206, 34, 152, 54)); expect(e.polylineVolume.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(182, 38, 96, 39)); expect(e.polylineVolume.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(84, 117, 45, 107)); expect(e.polylineVolume.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(79, 76, 73, 177)); expect(e.polylineVolume.material.offset.getValue(documentStartDate)).toEqual(18479); expect(e.polylineVolume.material.offset.getValue(documentStopDate)).toEqual(19855); expect(e.polylineVolume.material.repeat.getValue(documentStartDate)).toEqual(36294); expect(e.polylineVolume.material.repeat.getValue(documentStopDate)).toEqual(34071); expect(e = dataSource.entities.getById("sampled_polylineVolume_material_checkerboard")).toBeDefined(); expect(e.polylineVolume.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(185, 168, 171, 241)); expect(e.polylineVolume.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(111, 194, 153, 164)); expect(e.polylineVolume.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(84, 96, 248, 117)); expect(e.polylineVolume.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(129, 55, 81, 196)); expect(e.polylineVolume.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(45209, 63152)); expect(e.polylineVolume.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(42552, 3238)); expect(e = dataSource.entities.getById("sampled_polylineVolume_material_image_color")).toBeDefined(); expect(e.polylineVolume.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.52156862745098, 0.745098039215686, 0.537254901960784, 0.227450980392157), 1e-14); expect(e.polylineVolume.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.792156862745098, 0.192156862745098, 0.564705882352941, 0.0705882352941176), 1e-14); expect(e = dataSource.entities.getById("sampled_polylineVolume_material_grid_color")).toBeDefined(); expect(e.polylineVolume.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.274509803921569, 0.545098039215686, 0.203921568627451, 0.650980392156863), 1e-14); expect(e.polylineVolume.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.384313725490196, 0.384313725490196, 0.670588235294118, 0.36078431372549), 1e-14); expect(e = dataSource.entities.getById("sampled_polylineVolume_material_stripe_evenColor")).toBeDefined(); expect(e.polylineVolume.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.0588235294117647, 0.341176470588235, 0.83921568627451, 0.823529411764706), 1e-14); expect(e.polylineVolume.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.83921568627451, 0.247058823529412, 0.568627450980392, 0.905882352941176), 1e-14); expect(e = dataSource.entities.getById("sampled_polylineVolume_material_stripe_oddColor")).toBeDefined(); expect(e.polylineVolume.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.850980392156863, 0.309803921568627, 0.823529411764706, 0.12156862745098), 1e-14); expect(e.polylineVolume.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.976470588235294, 0.564705882352941, 0.776470588235294, 0.607843137254902), 1e-14); expect(e = dataSource.entities.getById("sampled_polylineVolume_material_checkerboard_evenColor")).toBeDefined(); expect(e.polylineVolume.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.396078431372549, 0.717647058823529, 0.976470588235294, 0.564705882352941), 1e-14); expect(e.polylineVolume.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.388235294117647, 0.568627450980392, 0.0235294117647059, 0.807843137254902), 1e-14); expect(e = dataSource.entities.getById("sampled_polylineVolume_material_checkerboard_oddColor")).toBeDefined(); expect(e.polylineVolume.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.0666666666666667, 0.796078431372549, 0.576470588235294, 0.180392156862745), 1e-14); expect(e.polylineVolume.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.576470588235294, 0.52156862745098, 0.623529411764706, 0.384313725490196), 1e-14); expect(e = dataSource.entities.getById("sampled_polylineVolume_outlineColor_rgbaf")).toBeDefined(); expect(e.polylineVolume.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.454901960784314, 0.674509803921569, 0.368627450980392, 0.850980392156863), 1e-14); expect(e.polylineVolume.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.23921568627451, 0.525490196078431, 0.133333333333333, 0.949019607843137), 1e-14); expect(e = dataSource.entities.getById("sampled_rectangle_coordinates_wsenDegrees")).toBeDefined(); expect(e.rectangle.coordinates.getValue(documentStartDate)).toEqual(import__55.Rectangle.fromDegrees(35, 18, 38, 15)); expect(e.rectangle.coordinates.getValue(documentStopDate)).toEqual(import__55.Rectangle.fromDegrees(38, 1, 12, 30)); expect(e = dataSource.entities.getById("sampled_rectangle_material_solidColor_color")).toBeDefined(); expect(e.rectangle.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.203921568627451, 0.243137254901961, 0.576470588235294, 0.0980392156862745), 1e-14); expect(e.rectangle.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.913725490196078, 0.831372549019608, 0.76078431372549, 0.952941176470588), 1e-14); expect(e = dataSource.entities.getById("sampled_rectangle_material_image")).toBeDefined(); expect(e.rectangle.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(3711, 44302)); expect(e.rectangle.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(52318, 60108)); expect(e.rectangle.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(49, 142, 97, 190)); expect(e.rectangle.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(189, 250, 238, 118)); expect(e = dataSource.entities.getById("sampled_rectangle_material_grid")).toBeDefined(); expect(e.rectangle.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(95, 53, 115, 82)); expect(e.rectangle.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(204, 71, 209, 187)); expect(e.rectangle.material.cellAlpha.getValue(documentStartDate)).toEqual(48813); expect(e.rectangle.material.cellAlpha.getValue(documentStopDate)).toEqual(21269); expect(e.rectangle.material.lineCount.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(22945, 32857)); expect(e.rectangle.material.lineCount.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(55972, 34522)); expect(e.rectangle.material.lineThickness.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(37146, 39825)); expect(e.rectangle.material.lineThickness.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(64636, 13052)); expect(e.rectangle.material.lineOffset.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(8882, 38690)); expect(e.rectangle.material.lineOffset.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(8857, 21794)); expect(e = dataSource.entities.getById("sampled_rectangle_material_stripe")).toBeDefined(); expect(e.rectangle.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(243, 96, 246, 5)); expect(e.rectangle.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(74, 28, 207, 87)); expect(e.rectangle.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(147, 18, 134, 10)); expect(e.rectangle.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(59, 151, 72, 114)); expect(e.rectangle.material.offset.getValue(documentStartDate)).toEqual(57328); expect(e.rectangle.material.offset.getValue(documentStopDate)).toEqual(2602); expect(e.rectangle.material.repeat.getValue(documentStartDate)).toEqual(29729); expect(e.rectangle.material.repeat.getValue(documentStopDate)).toEqual(30206); expect(e = dataSource.entities.getById("sampled_rectangle_material_checkerboard")).toBeDefined(); expect(e.rectangle.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(142, 184, 89, 24)); expect(e.rectangle.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(200, 249, 166, 224)); expect(e.rectangle.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(237, 53, 233, 244)); expect(e.rectangle.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(101, 61, 234, 150)); expect(e.rectangle.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(44089, 8876)); expect(e.rectangle.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(60682, 18669)); expect(e = dataSource.entities.getById("sampled_rectangle_material_image_color")).toBeDefined(); expect(e.rectangle.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.552941176470588, 0.101960784313725, 0.772549019607843, 0.00392156862745098), 1e-14); expect(e.rectangle.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.0156862745098039, 0.964705882352941, 0.592156862745098, 0.396078431372549), 1e-14); expect(e = dataSource.entities.getById("sampled_rectangle_material_grid_color")).toBeDefined(); expect(e.rectangle.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.490196078431373, 0.384313725490196, 0.937254901960784, 0.168627450980392), 1e-14); expect(e.rectangle.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.392156862745098, 0.756862745098039, 0.454901960784314, 0.529411764705882), 1e-14); expect(e = dataSource.entities.getById("sampled_rectangle_material_stripe_evenColor")).toBeDefined(); expect(e.rectangle.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.32156862745098, 0.776470588235294, 0.227450980392157, 0.0823529411764706), 1e-14); expect(e.rectangle.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.929411764705882, 0.725490196078431, 0.00392156862745098, 0.364705882352941), 1e-14); expect(e = dataSource.entities.getById("sampled_rectangle_material_stripe_oddColor")).toBeDefined(); expect(e.rectangle.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.984313725490196, 0.831372549019608, 0.827450980392157, 0.925490196078431), 1e-14); expect(e.rectangle.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.145098039215686, 0.0156862745098039, 0.380392156862745, 0.490196078431373), 1e-14); expect(e = dataSource.entities.getById("sampled_rectangle_material_checkerboard_evenColor")).toBeDefined(); expect(e.rectangle.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.286274509803922, 0.831372549019608, 0.184313725490196, 0.172549019607843), 1e-14); expect(e.rectangle.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.596078431372549, 0.603921568627451, 0.694117647058824, 0.235294117647059), 1e-14); expect(e = dataSource.entities.getById("sampled_rectangle_material_checkerboard_oddColor")).toBeDefined(); expect(e.rectangle.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.929411764705882, 0.92156862745098, 0.270588235294118, 0.0666666666666667), 1e-14); expect(e.rectangle.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.411764705882353, 0.125490196078431, 0.505882352941176, 0.509803921568627), 1e-14); expect(e = dataSource.entities.getById("sampled_rectangle_outlineColor_rgbaf")).toBeDefined(); expect(e.rectangle.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.980392156862745, 0.466666666666667, 0.752941176470588, 0.709803921568627), 1e-14); expect(e.rectangle.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.549019607843137, 0.949019607843137, 0.545098039215686, 0.380392156862745), 1e-14); expect(e = dataSource.entities.getById("sampled_wall_material_solidColor_color")).toBeDefined(); expect(e.wall.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.384313725490196, 0.964705882352941, 0.827450980392157, 0.815686274509804), 1e-14); expect(e.wall.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.00784313725490196, 0.325490196078431, 0.952941176470588, 0.0549019607843137), 1e-14); expect(e = dataSource.entities.getById("sampled_wall_material_image")).toBeDefined(); expect(e.wall.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(13369, 38196)); expect(e.wall.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(36874, 55696)); expect(e.wall.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(1, 152, 139, 83)); expect(e.wall.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(127, 110, 56, 69)); expect(e = dataSource.entities.getById("sampled_wall_material_grid")).toBeDefined(); expect(e.wall.material.color.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(243, 153, 88, 43)); expect(e.wall.material.color.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(169, 159, 82, 75)); expect(e.wall.material.cellAlpha.getValue(documentStartDate)).toEqual(32179); expect(e.wall.material.cellAlpha.getValue(documentStopDate)).toEqual(55901); expect(e.wall.material.lineCount.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(46941, 30391)); expect(e.wall.material.lineCount.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(51565, 6089)); expect(e.wall.material.lineThickness.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(35543, 16778)); expect(e.wall.material.lineThickness.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(32904, 18048)); expect(e.wall.material.lineOffset.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(2955, 19723)); expect(e.wall.material.lineOffset.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(58723, 15333)); expect(e = dataSource.entities.getById("sampled_wall_material_stripe")).toBeDefined(); expect(e.wall.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(204, 233, 122, 70)); expect(e.wall.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(215, 44, 132, 84)); expect(e.wall.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(20, 6, 10, 253)); expect(e.wall.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(96, 118, 90, 117)); expect(e.wall.material.offset.getValue(documentStartDate)).toEqual(63629); expect(e.wall.material.offset.getValue(documentStopDate)).toEqual(38486); expect(e.wall.material.repeat.getValue(documentStartDate)).toEqual(41791); expect(e.wall.material.repeat.getValue(documentStopDate)).toEqual(56258); expect(e = dataSource.entities.getById("sampled_wall_material_checkerboard")).toBeDefined(); expect(e.wall.material.evenColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(38, 200, 78, 42)); expect(e.wall.material.evenColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(115, 149, 62, 135)); expect(e.wall.material.oddColor.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(79, 103, 165, 56)); expect(e.wall.material.oddColor.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(201, 220, 190, 217)); expect(e.wall.material.repeat.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(30510, 28535)); expect(e.wall.material.repeat.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(22105, 29014)); expect(e = dataSource.entities.getById("sampled_wall_material_image_color")).toBeDefined(); expect(e.wall.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.584313725490196, 0.752941176470588, 0.588235294117647, 0.733333333333333), 1e-14); expect(e.wall.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.309803921568627, 0.988235294117647, 0.0784313725490196, 0.458823529411765), 1e-14); expect(e = dataSource.entities.getById("sampled_wall_material_grid_color")).toBeDefined(); expect(e.wall.material.color.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.27843137254902, 0.549019607843137, 0.964705882352941, 0.96078431372549), 1e-14); expect(e.wall.material.color.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.709803921568627, 0.831372549019608, 0.67843137254902, 0.407843137254902), 1e-14); expect(e = dataSource.entities.getById("sampled_wall_material_stripe_evenColor")).toBeDefined(); expect(e.wall.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.0901960784313725, 0.243137254901961, 0.537254901960784, 0.168627450980392), 1e-14); expect(e.wall.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.388235294117647, 0.847058823529412, 0.258823529411765, 0.113725490196078), 1e-14); expect(e = dataSource.entities.getById("sampled_wall_material_stripe_oddColor")).toBeDefined(); expect(e.wall.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.345098039215686, 0.0196078431372549, 0.0549019607843137, 0.662745098039216), 1e-14); expect(e.wall.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.694117647058824, 0.890196078431372, 0.380392156862745, 0.317647058823529), 1e-14); expect(e = dataSource.entities.getById("sampled_wall_material_checkerboard_evenColor")).toBeDefined(); expect(e.wall.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.670588235294118, 0.462745098039216, 0.443137254901961, 0.23921568627451), 1e-14); expect(e.wall.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.313725490196078, 0.0901960784313725, 0.623529411764706, 0.933333333333333), 1e-14); expect(e = dataSource.entities.getById("sampled_wall_material_checkerboard_oddColor")).toBeDefined(); expect(e.wall.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.184313725490196, 0.725490196078431, 0.894117647058824, 0.572549019607843), 1e-14); expect(e.wall.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.745098039215686, 0.435294117647059, 0.611764705882353, 0.776470588235294), 1e-14); expect(e = dataSource.entities.getById("sampled_wall_outlineColor_rgbaf")).toBeDefined(); expect(e.wall.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.933333333333333, 0.105882352941176, 0.0627450980392157, 0.396078431372549), 1e-14); expect(e.wall.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.901960784313726, 0.435294117647059, 0.352941176470588, 0.713725490196078), 1e-14); expect(e = dataSource.entities.getById("sampled_conicSensor_intersectionColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_lateralSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_lateralSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_lateralSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_lateralSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_lateralSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_lateralSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_lateralSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_lateralSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_lateralSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_lateralSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_lateralSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidHorizonSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidHorizonSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidHorizonSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidHorizonSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidHorizonSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidHorizonSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidHorizonSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidHorizonSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidHorizonSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidHorizonSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_ellipsoidHorizonSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_domeSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_domeSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_domeSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_domeSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_domeSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_domeSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_domeSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_domeSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_domeSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_domeSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_domeSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_environmentOcclusionMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_environmentOcclusionMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_environmentOcclusionMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_environmentOcclusionMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_environmentOcclusionMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_environmentOcclusionMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_environmentOcclusionMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_environmentOcclusionMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_environmentOcclusionMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_environmentOcclusionMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_environmentOcclusionMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_environmentIntersectionColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_viewshedVisibleColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_conicSensor_viewshedOccludedColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_intersectionColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_lateralSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_lateralSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_lateralSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_lateralSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_lateralSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_lateralSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_lateralSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_lateralSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_lateralSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_lateralSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_lateralSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidHorizonSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidHorizonSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidHorizonSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidHorizonSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidHorizonSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidHorizonSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidHorizonSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidHorizonSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidHorizonSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidHorizonSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_ellipsoidHorizonSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_domeSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_domeSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_domeSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_domeSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_domeSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_domeSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_domeSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_domeSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_domeSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_domeSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_domeSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_environmentOcclusionMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_environmentOcclusionMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_environmentOcclusionMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_environmentOcclusionMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_environmentOcclusionMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_environmentOcclusionMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_environmentOcclusionMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_environmentOcclusionMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_environmentOcclusionMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_environmentOcclusionMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_environmentOcclusionMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_environmentIntersectionColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_viewshedVisibleColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_customPatternSensor_viewshedOccludedColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_intersectionColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_lateralSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_lateralSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_lateralSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_lateralSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_lateralSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_lateralSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_lateralSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_lateralSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_lateralSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_lateralSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_lateralSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidHorizonSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidHorizonSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidHorizonSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidHorizonSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidHorizonSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidHorizonSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidHorizonSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidHorizonSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidHorizonSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidHorizonSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_ellipsoidHorizonSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_domeSurfaceMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_domeSurfaceMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_domeSurfaceMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_domeSurfaceMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_domeSurfaceMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_domeSurfaceMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_domeSurfaceMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_domeSurfaceMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_domeSurfaceMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_domeSurfaceMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_domeSurfaceMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_environmentOcclusionMaterial_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_environmentOcclusionMaterial_image")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_environmentOcclusionMaterial_grid")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_environmentOcclusionMaterial_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_environmentOcclusionMaterial_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_environmentOcclusionMaterial_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_environmentOcclusionMaterial_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_environmentOcclusionMaterial_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_environmentOcclusionMaterial_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_environmentOcclusionMaterial_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_environmentOcclusionMaterial_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_environmentIntersectionColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_viewshedVisibleColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_rectangularSensor_viewshedOccludedColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_fan_material_solidColor_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_fan_material_image")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_fan_material_grid")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_fan_material_stripe")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_fan_material_checkerboard")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_fan_material_image_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_fan_material_grid_color")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_fan_material_stripe_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_fan_material_stripe_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_fan_material_checkerboard_evenColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_fan_material_checkerboard_oddColor")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_fan_outlineColor_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_vector_color_rgbaf")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_vector_direction_unitSpherical")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_vector_direction_cartesian")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_vector_direction_unitCartesian")).toBeDefined(); expect(e = dataSource.entities.getById("sampled_custom")).toBeDefined(); expect(e.properties.custom_boundingRectangle.getValue(documentStartDate)).toEqual(new import__55.BoundingRectangle(10924, 3626, 12558, 56113)); expect(e.properties.custom_boundingRectangle.getValue(documentStopDate)).toEqual(new import__55.BoundingRectangle(59127, 45286, 34992, 17032)); expect(e.properties.custom_cartesian.getValue(documentStartDate)).toEqual(new import__55.Cartesian3(59456, 60648, 1004)); expect(e.properties.custom_cartesian.getValue(documentStopDate)).toEqual(new import__55.Cartesian3(37915, 14740, 14905)); expect(e.properties.custom_cartographicRadians.getValue(documentStartDate)).toEqual(import__55.Cartesian3.fromRadians(1.25380297085855, 1.03510976346284, 7102)); expect(e.properties.custom_cartographicRadians.getValue(documentStopDate)).toEqual(import__55.Cartesian3.fromRadians(1.10648839763778, 0.231915563506949, 340)); expect(e.properties.custom_cartographicDegrees.getValue(documentStartDate)).toEqual(import__55.Cartesian3.fromDegrees(44, 31, 55762)); expect(e.properties.custom_cartographicDegrees.getValue(documentStopDate)).toEqual(import__55.Cartesian3.fromDegrees(10, 18, 28847)); expect(e.properties.custom_cartesian2.getValue(documentStartDate)).toEqual(new import__55.Cartesian2(9033, 9251)); expect(e.properties.custom_cartesian2.getValue(documentStopDate)).toEqual(new import__55.Cartesian2(34048, 58501)); expect(e.properties.custom_unitCartesian.getValue(documentStartDate)).toEqualEpsilon(new import__55.Cartesian3(0.0501133095086564, 0.917195967206924, 0.395272328843601), 1e-14); expect(e.properties.custom_unitCartesian.getValue(documentStopDate)).toEqualEpsilon(new import__55.Cartesian3(0.797476048450763, 0.40584478979077, 0.446454878735849), 1e-14); expect(e.properties.custom_spherical.getValue(documentStartDate)).toEqual(import__55.Cartesian3.fromSpherical(new import__55.Spherical(47098, 2231, 14088))); expect(e.properties.custom_spherical.getValue(documentStopDate)).toEqual(import__55.Cartesian3.fromSpherical(new import__55.Spherical(34883, 48264, 41148))); expect(e.properties.custom_unitSpherical.getValue(documentStartDate)).toEqualEpsilon(import__55.Cartesian3.fromSpherical(new import__55.Spherical(48811, 24254)), 1e-14); expect(e.properties.custom_unitSpherical.getValue(documentStopDate)).toEqualEpsilon(import__55.Cartesian3.fromSpherical(new import__55.Spherical(44800, 8111)), 1e-14); expect(e.properties.custom_rgba.getValue(documentStartDate)).toEqual(import__55.Color.fromBytes(179, 175, 115, 46)); expect(e.properties.custom_rgba.getValue(documentStopDate)).toEqual(import__55.Color.fromBytes(136, 187, 237, 156)); expect(e.properties.custom_rgbaf.getValue(documentStartDate)).toEqualEpsilon(new import__55.Color(0.890196078431372, 0.450980392156863, 0.588235294117647, 0.72156862745098), 1e-14); expect(e.properties.custom_rgbaf.getValue(documentStopDate)).toEqualEpsilon(new import__55.Color(0.419607843137255, 0.843137254901961, 0.36078431372549, 0.423529411764706), 1e-14); expect(e.properties.custom_number.getValue(documentStartDate)).toEqual(24561); expect(e.properties.custom_number.getValue(documentStopDate)).toEqual(45446); expect(e.properties.custom_nearFarScalar.getValue(documentStartDate)).toEqual(new import__55.NearFarScalar(64112, 15354, 32827, 10368)); expect(e.properties.custom_nearFarScalar.getValue(documentStopDate)).toEqual(new import__55.NearFarScalar(55643, 45785, 33458, 29826)); expect(e.properties.custom_unitQuaternion.getValue(documentStartDate)).toEqualEpsilon(new import__55.Quaternion(0.697299305414108, 0.26496667122144, 0.615947719782462, 0.253327354041402), 1e-14); expect(e.properties.custom_unitQuaternion.getValue(documentStopDate)).toEqualEpsilon(new import__55.Quaternion(0.134764165794432, 0.408681085292446, 0.902060273565587, 0.0332513608247514), 1e-14); expect(e.properties.custom_wsen.getValue(documentStartDate)).toEqual(new import__55.Rectangle(1.4164143530628, 1.2888469381038, 0.679756561409663, 1.29649258884014)); expect(e.properties.custom_wsen.getValue(documentStopDate)).toEqual(new import__55.Rectangle(1.19133054275098, 0.9154648059314, 0.71347968461712, 1.32750822775441)); expect(e.properties.custom_wsenDegrees.getValue(documentStartDate)).toEqual(import__55.Rectangle.fromDegrees(29, 11, 17, 36)); expect(e.properties.custom_wsenDegrees.getValue(documentStopDate)).toEqual(import__55.Rectangle.fromDegrees(37, 16, 25, 23)); }); }); it("registers custom updaters", () => { function processFakeEntity() { } expect(import__55.CzmlDataSource.updaters.length).withContext("length before register").toEqual(23); import__55.CzmlDataSource.registerUpdater(processFakeEntity); expect(import__55.CzmlDataSource.updaters.length).withContext("length after register").toEqual(24); expect(import__55.CzmlDataSource.updaters[23]).toEqual(processFakeEntity); import__55.CzmlDataSource.unregisterUpdater(processFakeEntity); expect(import__55.CzmlDataSource.updaters.length).withContext("length after unregister").toEqual(23); }); }); // packages/engine/Specs/DataSources/DataSourceClockSpec.js var import__56 = __toESM(require_Cesium(), 1); describe("DataSources/DataSourceClock", function() { it("merge assigns unassigned properties", function() { const source = new import__56.DataSourceClock(); source.startTime = import__56.JulianDate.now(); source.stopTime = import__56.JulianDate.now(); source.currentTime = import__56.JulianDate.now(); source.clockRange = import__56.ClockRange.CLAMPED; source.clockStep = import__56.ClockStep.TICK_DEPENDENT; source.multiplier = 1; const target = new import__56.DataSourceClock(); target.merge(source); expect(target.startTime).toBe(source.startTime); expect(target.stopTime).toBe(source.stopTime); expect(target.currentTime).toBe(source.currentTime); expect(target.clockRange).toBe(source.clockRange); expect(target.clockStep).toBe(source.clockStep); expect(target.multiplier).toBe(source.multiplier); }); it("merge does not assign assigned properties", function() { const source = new import__56.DataSourceClock(); source.startTime = import__56.JulianDate.now(); source.stopTime = import__56.JulianDate.now(); source.currentTime = import__56.JulianDate.now(); source.clockRange = import__56.ClockRange.CLAMPED; source.clockStep = import__56.ClockStep.TICK_DEPENDENT; source.multiplier = 1; const startTime = import__56.JulianDate.now(); const stopTime = import__56.JulianDate.now(); const currentTime = import__56.JulianDate.now(); const clockRange = import__56.ClockRange.CLAMPED; const clockStep = import__56.ClockStep.TICK_DEPENDENT; const multiplier = 1; const target = new import__56.DataSourceClock(); target.startTime = startTime; target.stopTime = stopTime; target.currentTime = currentTime; target.clockRange = clockRange; target.clockStep = clockStep; target.multiplier = multiplier; target.merge(source); expect(target.startTime).toBe(startTime); expect(target.stopTime).toBe(stopTime); expect(target.currentTime).toBe(currentTime); expect(target.clockRange).toBe(clockRange); expect(target.clockStep).toBe(clockStep); expect(target.multiplier).toBe(multiplier); }); it("clone works", function() { const source = new import__56.DataSourceClock(); source.startTime = import__56.JulianDate.now(); source.stopTime = import__56.JulianDate.now(); source.currentTime = import__56.JulianDate.now(); source.clockRange = import__56.ClockRange.CLAMPED; source.clockStep = import__56.ClockStep.TICK_DEPENDENT; source.multiplier = 1; const result = source.clone(); expect(result.startTime).toBe(source.startTime); expect(result.stopTime).toBe(source.stopTime); expect(result.currentTime).toBe(source.currentTime); expect(result.clockRange).toBe(source.clockRange); expect(result.clockStep).toBe(source.clockStep); expect(result.multiplier).toBe(source.multiplier); }); it("merge throws if source undefined", function() { const target = new import__56.DataSourceClock(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); it("gets value as a clock instance", function() { const source = new import__56.DataSourceClock(); source.startTime = import__56.JulianDate.now(); source.stopTime = import__56.JulianDate.now(); source.currentTime = import__56.JulianDate.now(); source.clockRange = import__56.ClockRange.CLAMPED; source.clockStep = import__56.ClockStep.TICK_DEPENDENT; source.multiplier = 2; let clock = source.getValue(); expect(clock.startTime).toEqual(source.startTime); expect(clock.stopTime).toEqual(source.stopTime); expect(clock.currentTime).toEqual(source.currentTime); expect(clock.clockRange).toEqual(source.clockRange); expect(clock.clockStep).toEqual(source.clockStep); expect(clock.multiplier).toEqual(source.multiplier); source.multiplier = void 0; source.clockStep = void 0; source.clockRange = void 0; clock = source.getValue(); expect(clock.startTime).toEqual(source.startTime); expect(clock.stopTime).toEqual(source.stopTime); expect(clock.currentTime).toEqual(source.currentTime); expect(clock.clockRange).toEqual(import__56.ClockRange.UNBOUNDED); expect(clock.clockStep).toEqual(import__56.ClockStep.SYSTEM_CLOCK_MULTIPLIER); expect(clock.multiplier).toEqual(1); }); }); // packages/engine/Specs/DataSources/DataSourceCollectionSpec.js var import__57 = __toESM(require_Cesium(), 1); // Specs/MockDataSource.js var import_engine15 = __toESM(require_Cesium(), 1); function MockDataSource() { this.changedEvent = new import_engine15.Event(); this.errorEvent = new import_engine15.Event(); this.entities = new import_engine15.EntityCollection(); this.name = "Mock Data"; this.clock = void 0; this.isTimeVarying = false; this.isLoading = false; this.loadingEvent = new import_engine15.Event(); this.destroyed = false; this.clustering = new import_engine15.EntityCluster(); } MockDataSource.prototype.update = function() { return true; }; MockDataSource.prototype.destroy = function() { this.destroyed = true; }; var MockDataSource_default = MockDataSource; // packages/engine/Specs/DataSources/DataSourceCollectionSpec.js describe("DataSources/DataSourceCollection", function() { it("contains, get, getLength, and indexOf work", function() { const collection = new import__57.DataSourceCollection(); const source = new MockDataSource_default(); expect(collection.length).toEqual(0); expect(collection.contains(source)).toEqual(false); return Promise.all([ collection.add(new MockDataSource_default()), collection.add(source), collection.add(new MockDataSource_default()) ]).then(function() { expect(collection.length).toEqual(3); expect(collection.get(1)).toBe(source); expect(collection.indexOf(source)).toEqual(1); expect(collection.contains(source)).toEqual(true); collection.remove(collection.get(0)); expect(collection.indexOf(source)).toEqual(0); expect(collection.remove(source)).toEqual(true); expect(collection.contains(source)).toEqual(false); }); }); it("getByName works", function() { const collection = new import__57.DataSourceCollection(); const promises = []; const source1 = new MockDataSource_default(); source1.name = "Name1"; promises.push(collection.add(source1)); const source2 = new MockDataSource_default(); source2.name = "Name1"; promises.push(collection.add(source2)); const source3 = new MockDataSource_default(); source3.name = "Name2"; promises.push(collection.add(source3)); return Promise.all(promises).then(function() { const res = collection.getByName("Name1"); expect(res.length).toEqual(2); expect(res[0].name).toEqual("Name1"); expect(res[1].name).toEqual("Name1"); }); }); it("add and remove events work", function() { const source = new MockDataSource_default(); const collection = new import__57.DataSourceCollection(); const addSpy = jasmine.createSpy("dataSourceAdded"); collection.dataSourceAdded.addEventListener(addSpy); const removeSpy = jasmine.createSpy("dataSourceRemoved"); collection.dataSourceRemoved.addEventListener(removeSpy); return collection.add(source).then(function() { expect(addSpy).toHaveBeenCalledWith(collection, source); expect(removeSpy).not.toHaveBeenCalled(); addSpy.calls.reset(); removeSpy.calls.reset(); expect(collection.remove(source)).toEqual(true); expect(addSpy).not.toHaveBeenCalled(); expect(removeSpy).toHaveBeenCalledWith(collection, source); }); }); it("move event works", function() { const source = new MockDataSource_default(); const collection = new import__57.DataSourceCollection(); const moveSpy = jasmine.createSpy("dataSourceMoved"); collection.dataSourceMoved.addEventListener(moveSpy); return collection.add(source).then(function() { collection.raise(source); collection.lower(source); collection.raiseToTop(source); collection.lowerToBottom(source); expect(moveSpy).not.toHaveBeenCalled(); return Promise.all([ collection.add(new MockDataSource_default()), collection.add(new MockDataSource_default()) ]); }).then(function() { collection.raise(source); expect(moveSpy).toHaveBeenCalledWith(source, 1, 0); collection.lower(source); expect(moveSpy).toHaveBeenCalledWith(source, 0, 1); collection.raiseToTop(source); expect(moveSpy).toHaveBeenCalledWith(source, 2, 0); collection.lowerToBottom(source); expect(moveSpy).toHaveBeenCalledWith(source, 0, 2); }); }); it("add works with promise", function() { const source = new MockDataSource_default(); const sourcePromise = Promise.resolve(source); const collection = new import__57.DataSourceCollection(); const addSpy = jasmine.createSpy("dataSourceAdded"); collection.dataSourceAdded.addEventListener(addSpy); const promise = collection.add(sourcePromise); expect(collection.length).toEqual(0); expect(addSpy).not.toHaveBeenCalled(); return promise.then(function() { expect(addSpy).toHaveBeenCalledWith(collection, source); expect(collection.length).toEqual(1); }); }); it("promise does not get added if not resolved before removeAll", function() { const source = new MockDataSource_default(); const sourcePromise = Promise.resolve(source); const collection = new import__57.DataSourceCollection(); const addSpy = jasmine.createSpy("dataSourceAdded"); collection.dataSourceAdded.addEventListener(addSpy); const promise = collection.add(sourcePromise); expect(collection.length).toEqual(0); expect(addSpy).not.toHaveBeenCalled(); collection.removeAll(); return promise.then(function() { expect(addSpy).not.toHaveBeenCalled(); expect(collection.length).toEqual(0); }); }); it("removeAll triggers events", function() { const sources = [ new MockDataSource_default(), new MockDataSource_default(), new MockDataSource_default() ]; const collection = new import__57.DataSourceCollection(); let removeCalled = 0; collection.dataSourceRemoved.addEventListener(function(sender, dataSource) { expect(sender).toBe(collection); expect(sources.indexOf(dataSource)).not.toEqual(-1); removeCalled++; }); return Promise.all([ collection.add(sources[0]), collection.add(sources[1]), collection.add(sources[2]) ]).then(function() { collection.removeAll(); expect(collection.length).toEqual(0); expect(removeCalled).toEqual(sources.length); }); }); it("destroy triggers remove events and calls destroy", function() { const sources = [ new MockDataSource_default(), new MockDataSource_default(), new MockDataSource_default() ]; const collection = new import__57.DataSourceCollection(); let removeCalled = 0; collection.dataSourceRemoved.addEventListener(function(sender, dataSource) { expect(sender).toBe(collection); expect(sources.indexOf(dataSource)).not.toEqual(-1); removeCalled++; }); return Promise.all([ collection.add(sources[0]), collection.add(sources[1]), collection.add(sources[2]) ]).then(function() { expect(collection.isDestroyed()).toEqual(false); collection.destroy(); expect(collection.isDestroyed()).toEqual(true); expect(removeCalled).toEqual(sources.length); expect(sources[0].destroyed).toEqual(true); expect(sources[1].destroyed).toEqual(true); expect(sources[2].destroyed).toEqual(true); }); }); it("remove returns fails for non-member", function() { const collection = new import__57.DataSourceCollection(); expect(collection.remove(new MockDataSource_default())).toEqual(false); }); it("get throws if passed undefined", function() { const collection = new import__57.DataSourceCollection(); expect(function() { collection.get(void 0); }).toThrowDeveloperError(); }); it("add throws if passed undefined", function() { const collection = new import__57.DataSourceCollection(); expect(function() { collection.add(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/DataSourceDisplaySpec.js var import__58 = __toESM(require_Cesium(), 1); describe( "DataSources/DataSourceDisplay", function() { let dataSourceCollection; let scene2; let display; beforeAll(function() { scene2 = createScene_default(); dataSourceCollection = new import__58.DataSourceCollection(); return Promise.all([ import__58.GroundPrimitive.initializeTerrainHeights(), import__58.GroundPolylinePrimitive.initializeTerrainHeights() ]); }); afterAll(function() { scene2.destroyForSpecs(); import__58.ApproximateTerrainHeights._initPromise = void 0; import__58.ApproximateTerrainHeights._terrainHeights = void 0; }); afterEach(function() { if ((0, import__58.defined)(display) && !display.isDestroyed()) { display.destroy(); } dataSourceCollection.removeAll(); }); function MockVisualizer() { this.updatesCalled = 0; this.lastUpdateTime = void 0; this.destroyed = false; this.getBoundingSphereResult = void 0; this.getBoundingSphereState = void 0; } MockVisualizer.prototype.update = function(time2) { this.lastUpdateTime = time2; this.updatesCalled++; return true; }; MockVisualizer.prototype.getBoundingSphere = function(entity, result) { this.getBoundingSphereResult.clone(result); return this.getBoundingSphereState; }; MockVisualizer.prototype.isDestroyed = function() { return this.destroyed; }; MockVisualizer.prototype.destroy = function() { this.destroyed = true; }; function visualizersCallback() { return [new MockVisualizer()]; } it("constructor sets expected values", function() { display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback }); expect(display.scene).toBe(scene2); expect(display.dataSources).toBe(dataSourceCollection); expect(display.isDestroyed()).toEqual(false); expect(display.defaultDataSource).toBeDefined(); display.destroy(); }); it("Computes complete bounding sphere.", function() { const visualizer1 = new MockVisualizer(); visualizer1.getBoundingSphereResult = new import__58.BoundingSphere( new import__58.Cartesian3(1, 2, 3), 456 ); visualizer1.getBoundingSphereState = import__58.BoundingSphereState.DONE; const visualizer2 = new MockVisualizer(); visualizer2.getBoundingSphereResult = new import__58.BoundingSphere( new import__58.Cartesian3(7, 8, 9), 1011 ); visualizer2.getBoundingSphereState = import__58.BoundingSphereState.DONE; display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback: function() { return [visualizer1, visualizer2]; } }); const entity = new import__58.Entity(); const dataSource = new MockDataSource_default(); dataSource.entities.add(entity); return display.dataSources.add(dataSource).then(function() { display.update(import__58.Iso8601.MINIMUM_VALUE); const result = new import__58.BoundingSphere(); const state2 = display.getBoundingSphere(entity, true, result); const expected = import__58.BoundingSphere.union( visualizer1.getBoundingSphereResult, visualizer2.getBoundingSphereResult ); expect(state2).toBe(import__58.BoundingSphereState.DONE); expect(result).toEqual(expected); }); }); it("Computes partial bounding sphere.", function() { const visualizer1 = new MockVisualizer(); visualizer1.getBoundingSphereResult = new import__58.BoundingSphere( new import__58.Cartesian3(1, 2, 3), 456 ); visualizer1.getBoundingSphereState = import__58.BoundingSphereState.PENDING; const visualizer2 = new MockVisualizer(); visualizer2.getBoundingSphereResult = new import__58.BoundingSphere( new import__58.Cartesian3(7, 8, 9), 1011 ); visualizer2.getBoundingSphereState = import__58.BoundingSphereState.DONE; display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback: function() { return [visualizer1, visualizer2]; } }); const entity = new import__58.Entity(); const dataSource = new MockDataSource_default(); dataSource.entities.add(entity); return display.dataSources.add(dataSource).then(function() { display.update(import__58.Iso8601.MINIMUM_VALUE); const result = new import__58.BoundingSphere(); const state2 = display.getBoundingSphere(entity, true, result); expect(state2).toBe(import__58.BoundingSphereState.DONE); expect(result).toEqual(visualizer2.getBoundingSphereResult); }); }); it("Fails complete bounding sphere if allowPartial false.", function() { const visualizer1 = new MockVisualizer(); visualizer1.getBoundingSphereResult = new import__58.BoundingSphere( new import__58.Cartesian3(1, 2, 3), 456 ); visualizer1.getBoundingSphereState = import__58.BoundingSphereState.PENDING; const visualizer2 = new MockVisualizer(); visualizer2.getBoundingSphereResult = new import__58.BoundingSphere( new import__58.Cartesian3(7, 8, 9), 1011 ); visualizer2.getBoundingSphereState = import__58.BoundingSphereState.DONE; display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback: function() { return [visualizer1, visualizer2]; } }); const entity = new import__58.Entity(); display.defaultDataSource.entities.add(entity); const result = new import__58.BoundingSphere(); const state2 = display.getBoundingSphere(entity, false, result); expect(state2).toBe(import__58.BoundingSphereState.PENDING); }); it("Fails bounding sphere for entity without visualization.", function() { display = new import__58.DataSourceDisplay({ dataSourceCollection, scene: scene2 }); const entity = new import__58.Entity(); const dataSource = new MockDataSource_default(); dataSource.entities.add(entity); return display.dataSources.add(dataSource).then(function() { display.update(import__58.Iso8601.MINIMUM_VALUE); const result = new import__58.BoundingSphere(); const state2 = display.getBoundingSphere(entity, false, result); expect(state2).toBe(import__58.BoundingSphereState.FAILED); display.destroy(); }); }); it("Fails bounding sphere for entity not in a data source.", function() { display = new import__58.DataSourceDisplay({ dataSourceCollection, scene: scene2 }); display.update(import__58.Iso8601.MINIMUM_VALUE); const entity = new import__58.Entity(); const result = new import__58.BoundingSphere(); const state2 = display.getBoundingSphere(entity, false, result); expect(state2).toBe(import__58.BoundingSphereState.FAILED); display.destroy(); }); it("Compute bounding sphere throws without entity.", function() { display = new import__58.DataSourceDisplay({ dataSourceCollection, scene: scene2 }); const result = new import__58.BoundingSphere(); expect(function() { display.getBoundingSphere(void 0, false, result); }).toThrowDeveloperError(); }); it("Compute bounding sphere throws without result.", function() { display = new import__58.DataSourceDisplay({ dataSourceCollection, scene: scene2 }); const entity = new import__58.Entity(); expect(function() { display.getBoundingSphere(entity, false, void 0); }).toThrowDeveloperError(); }); it("Compute bounding sphere throws without allowPartial.", function() { display = new import__58.DataSourceDisplay({ dataSourceCollection, scene: scene2 }); const entity = new import__58.Entity(); const result = new import__58.BoundingSphere(); expect(function() { display.getBoundingSphere(entity, void 0, result); }).toThrowDeveloperError(); }); it("destroy does not destroy underlying data sources", function() { const dataSource = new MockDataSource_default(); return dataSourceCollection.add(dataSource).then(function() { display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection }); expect(dataSource.destroyed).toEqual(false); display.destroy(); expect(dataSource.destroyed).toEqual(false); expect(display.isDestroyed()).toEqual(true); }); }); it("calling update updates data sources", function() { const source1 = new MockDataSource_default(); const source2 = new MockDataSource_default(); display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback }); return Promise.all([ dataSourceCollection.add(source1), dataSourceCollection.add(source2) ]).then(function() { const source1Visualizer = source1._visualizers[0]; expect(source1Visualizer).toBeInstanceOf(MockVisualizer); const source2Visualizer = source2._visualizers[0]; expect(source2Visualizer).toBeInstanceOf(MockVisualizer); expect(source1Visualizer.updatesCalled).toEqual(0); expect(source2Visualizer.updatesCalled).toEqual(0); display.update(import__58.Iso8601.MINIMUM_VALUE); expect(source1Visualizer.lastUpdateTime).toEqual(import__58.Iso8601.MINIMUM_VALUE); expect(source1Visualizer.updatesCalled).toEqual(1); expect(source2Visualizer.lastUpdateTime).toEqual(import__58.Iso8601.MINIMUM_VALUE); expect(source2Visualizer.updatesCalled).toEqual(1); }); }); it("ready is true when datasources are ready", function() { const source1 = new MockDataSource_default(); const source2 = new MockDataSource_default(); display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback }); expect(display.ready).toBe(false); return Promise.all([ dataSourceCollection.add(source1), dataSourceCollection.add(source2) ]).then(function() { display.update(import__58.Iso8601.MINIMUM_VALUE); expect(display.ready).toBe(true); spyOn(MockVisualizer.prototype, "update").and.returnValue(false); display.update(import__58.Iso8601.MINIMUM_VALUE); expect(display.ready).toBe(false); }); }); it("triggers a rendering when the data source becomes ready", function() { scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; scene2.renderForSpecs(); const source = new MockDataSource_default(); display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback }); expect(display.ready).toBe(false); return dataSourceCollection.add(source).then(function() { display.update(import__58.Iso8601.MINIMUM_VALUE); expect(display.ready).toBe(true); expect(scene2._renderRequested).toBe(true); scene2.renderForSpecs(); display.update(import__58.Iso8601.MINIMUM_VALUE); expect(display.ready).toBe(true); expect(scene2._renderRequested).toBe(false); }); }); it("constructor throws if scene undefined", function() { expect(function() { return new import__58.DataSourceDisplay({ scene: void 0, dataSourceCollection, visualizersCallback }); }).toThrowDeveloperError(); }); it("constructor throws if options undefined", function() { expect(function() { return new import__58.DataSourceDisplay(void 0); }).toThrowDeveloperError(); }); it("constructor throws if dataSourceCollection undefined", function() { expect(function() { return new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection: void 0, visualizersCallback }); }).toThrowDeveloperError(); }); it("update throws if time undefined", function() { display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback }); expect(function() { return display.update(); }).toThrowDeveloperError(); }); it("verify update returns false till terrain heights are initialized", function() { import__58.ApproximateTerrainHeights._initPromise = void 0; import__58.ApproximateTerrainHeights._terrainHeights = void 0; const source1 = new MockDataSource_default(); const source2 = new MockDataSource_default(); display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback }); return Promise.all([ dataSourceCollection.add(source1), dataSourceCollection.add(source2) ]).then(function() { display.update(import__58.Iso8601.MINIMUM_VALUE); expect(display.ready).toBe(false); return import__58.GroundPrimitive.initializeTerrainHeights(); }).then(function() { display.update(import__58.Iso8601.MINIMUM_VALUE); expect(display.ready).toBe(true); }); }); it("sets dataSource primitives on add", function() { const source = new MockDataSource_default(); display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback }); return dataSourceCollection.add(source).then(function() { expect(source._primitives).toBeDefined(); expect(source._groundPrimitives).toBeDefined(); expect(display._primitives.contains(source._primitives)).toBe(true); expect( display._groundPrimitives.contains(source._groundPrimitives) ).toBe(true); }); }); it("cleans up primitives on dataSource removed", function() { const source = new MockDataSource_default(); display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback }); return dataSourceCollection.add(source).then(function() { expect(display._primitives.contains(source._primitives)).toBe(true); expect( display._groundPrimitives.contains(source._groundPrimitives) ).toBe(true); dataSourceCollection.remove(source); expect(display._primitives.length).toBe(1); expect(display._groundPrimitives.length).toBe(1); }); }); it("raises primitives on dataSource raise", function() { const source1 = new MockDataSource_default(); const source2 = new MockDataSource_default(); const source3 = new MockDataSource_default(); display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback }); return Promise.all([ dataSourceCollection.add(source1), dataSourceCollection.add(source2), dataSourceCollection.add(source3) ]).then(function() { dataSourceCollection.raise(source1); expect(display._primitives.get(1)).toBe(source2._primitives); expect(display._primitives.get(2)).toBe(source1._primitives); expect(display._primitives.get(3)).toBe(source3._primitives); }); }); it("lowers primitives on dataSource lower", function() { const source1 = new MockDataSource_default(); const source2 = new MockDataSource_default(); const source3 = new MockDataSource_default(); display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback }); return Promise.all([ dataSourceCollection.add(source1), dataSourceCollection.add(source2), dataSourceCollection.add(source3) ]).then(function() { dataSourceCollection.lower(source3); expect(display._primitives.get(1)).toBe(source1._primitives); expect(display._primitives.get(2)).toBe(source3._primitives); expect(display._primitives.get(3)).toBe(source2._primitives); }); }); it("raises primitives to top on dataSource raiseToTop", function() { const source1 = new MockDataSource_default(); const source2 = new MockDataSource_default(); const source3 = new MockDataSource_default(); display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback }); return Promise.all([ dataSourceCollection.add(source1), dataSourceCollection.add(source2), dataSourceCollection.add(source3) ]).then(function() { dataSourceCollection.raiseToTop(source1); expect(display._primitives.get(1)).toBe(source2._primitives); expect(display._primitives.get(2)).toBe(source3._primitives); expect(display._primitives.get(3)).toBe(source1._primitives); }); }); it("lowers primitives to bottom on dataSource lowerToBottom", function() { const source1 = new MockDataSource_default(); const source2 = new MockDataSource_default(); const source3 = new MockDataSource_default(); display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback }); return Promise.all([ dataSourceCollection.add(source1), dataSourceCollection.add(source2), dataSourceCollection.add(source3) ]).then(function() { dataSourceCollection.lowerToBottom(source3); expect(display._primitives.get(1)).toBe(source3._primitives); expect(display._primitives.get(2)).toBe(source1._primitives); expect(display._primitives.get(3)).toBe(source2._primitives); }); }); it("adds primitives to scene when dataSource is added to the collection", function() { display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback }); expect(scene2.primitives.contains(display._primitives)).toBe(false); expect(scene2.groundPrimitives.contains(display._groundPrimitives)).toBe( false ); return dataSourceCollection.add(new MockDataSource_default()).then(function() { expect(scene2.primitives.contains(display._primitives)).toBe(true); expect(scene2.groundPrimitives.contains(display._groundPrimitives)).toBe( true ); }); }); it("adds primitives to scene if dataSourceCollection is not empty", function() { return dataSourceCollection.add(new MockDataSource_default()).then(function() { display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback }); expect(scene2.primitives.contains(display._primitives)).toBe(true); expect(scene2.groundPrimitives.contains(display._groundPrimitives)).toBe( true ); }); }); it("adds primitives to the scene when entities are added to the default dataSource", function() { display = new import__58.DataSourceDisplay({ scene: scene2, dataSourceCollection, visualizersCallback }); expect(scene2.primitives.contains(display._primitives)).toBe(false); expect(scene2.groundPrimitives.contains(display._groundPrimitives)).toBe( false ); display.defaultDataSource.entities.add(new import__58.Entity()); expect(scene2.primitives.contains(display._primitives)).toBe(true); expect(scene2.groundPrimitives.contains(display._groundPrimitives)).toBe( true ); }); it("has expected default visualizers", () => { const dataSource = new MockDataSource_default(); const entityCluster = dataSource.clustering; const callback = import__58.DataSourceDisplay.defaultVisualizersCallback( scene2, entityCluster, dataSource ); expect(callback.length).toEqual(8); expect(callback[0]).toBeInstanceOf(import__58.BillboardVisualizer); expect(callback[1]).toBeInstanceOf(import__58.GeometryVisualizer); expect(callback[2]).toBeInstanceOf(import__58.LabelVisualizer); expect(callback[3]).toBeInstanceOf(import__58.ModelVisualizer); expect(callback[4]).toBeInstanceOf(import__58.Cesium3DTilesetVisualizer); expect(callback[5]).toBeInstanceOf(import__58.PointVisualizer); expect(callback[6]).toBeInstanceOf(import__58.PathVisualizer); expect(callback[7]).toBeInstanceOf(import__58.PolylineVisualizer); }); it("registers extra visualizers", () => { function FakeVisualizer() { } const dataSource = new MockDataSource_default(); const entityCluster = dataSource.clustering; const callback = import__58.DataSourceDisplay.defaultVisualizersCallback( scene2, entityCluster, dataSource ); expect(callback.length).withContext("length before register").toEqual(8); import__58.DataSourceDisplay.registerVisualizer(FakeVisualizer); const callback2 = import__58.DataSourceDisplay.defaultVisualizersCallback( scene2, entityCluster, dataSource ); expect(callback2.length).withContext("length after register").toEqual(9); expect(callback2[8]).toBeInstanceOf(FakeVisualizer); import__58.DataSourceDisplay.unregisterVisualizer(FakeVisualizer); const callback3 = import__58.DataSourceDisplay.defaultVisualizersCallback( scene2, entityCluster, dataSource ); expect(callback3.length).withContext("length after unregister").toEqual(8); }); }, "WebGL" ); // packages/engine/Specs/DataSources/DynamicGeometryUpdaterSpec.js var import__59 = __toESM(require_Cesium(), 1); describe("DataSources/DynamicGeometryUpdater", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); it("Constructor throws with no updater", function() { expect(function() { return new import__59.DynamicGeometryUpdater( void 0, new import__59.PrimitiveCollection(), new import__59.PrimitiveCollection() ); }).toThrowDeveloperError(); }); it("Constructor throws with no primitives", function() { const updater = new import__59.GeometryUpdater({ entity: new import__59.Entity(), scene: scene2, geometryOptions: {}, geometryPropertyName: "box", observedPropertyNames: ["availability", "box"] }); expect(function() { return new import__59.DynamicGeometryUpdater( updater, void 0, new import__59.PrimitiveCollection() ); }).toThrowDeveloperError(); }); it("Constructor throws with no groundPrimitives", function() { const updater = new import__59.GeometryUpdater({ entity: new import__59.Entity(), scene: scene2, geometryOptions: {}, geometryPropertyName: "box", observedPropertyNames: ["availability", "box"] }); expect(function() { return new import__59.DynamicGeometryUpdater( updater, void 0, new import__59.PrimitiveCollection() ); }).toThrowDeveloperError(); }); it("update throws with no time", function() { const updater = new import__59.GeometryUpdater({ entity: new import__59.Entity(), scene: scene2, geometryOptions: {}, geometryPropertyName: "box", observedPropertyNames: ["availability", "box"] }); const dynamicUpdater = new import__59.DynamicGeometryUpdater( updater, new import__59.PrimitiveCollection(), new import__59.PrimitiveCollection() ); expect(function() { return dynamicUpdater.update(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/EllipseGeometryUpdaterSpec.js var import__60 = __toESM(require_Cesium(), 1); describe( "DataSources/EllipseGeometryUpdater", function() { let scene2; let time2; beforeAll(function() { scene2 = createScene_default(); time2 = import__60.JulianDate.now(); return import__60.ApproximateTerrainHeights.initialize(); }); afterAll(function() { scene2.destroyForSpecs(); import__60.ApproximateTerrainHeights._initPromise = void 0; import__60.ApproximateTerrainHeights._terrainHeights = void 0; }); function createBasicEllipse() { const ellipse = new import__60.EllipseGraphics(); ellipse.semiMajorAxis = new import__60.ConstantProperty(2); ellipse.semiMinorAxis = new import__60.ConstantProperty(1); ellipse.height = new import__60.ConstantProperty(0); const entity = new import__60.Entity(); entity.position = new import__60.ConstantPositionProperty( import__60.Cartesian3.fromDegrees(0, 0, 0) ); entity.ellipse = ellipse; return entity; } function createDynamicEllipse() { const entity = createBasicEllipse(); entity.ellipse.semiMajorAxis = createDynamicProperty_default(4); return entity; } function createBasicEllipseWithoutHeight() { const ellipse = new import__60.EllipseGraphics(); ellipse.semiMajorAxis = new import__60.ConstantProperty(2); ellipse.semiMinorAxis = new import__60.ConstantProperty(1); const entity = new import__60.Entity(); entity.position = new import__60.ConstantPositionProperty( import__60.Cartesian3.fromDegrees(0, 0, 0) ); entity.ellipse = ellipse; return entity; } function createDynamicEllipseWithoutHeight() { const entity = createBasicEllipseWithoutHeight(); entity.ellipse.semiMajorAxis = createDynamicProperty_default(4); return entity; } it("No geometry available when semiMajorAxis is undefined", function() { const entity = createBasicEllipse(); const updater = new import__60.EllipseGeometryUpdater(entity, scene2); entity.ellipse.semiMajorAxis = void 0; updater._onEntityPropertyChanged(entity, "ellipse"); expect(updater.fillEnabled).toBe(false); expect(updater.outlineEnabled).toBe(false); expect(updater.isDynamic).toBe(false); }); it("No geometry available when semiMinorAxis is undefined", function() { const entity = createBasicEllipse(); const updater = new import__60.EllipseGeometryUpdater(entity, scene2); entity.ellipse.semiMinorAxis = void 0; updater._onEntityPropertyChanged(entity, "ellipse"); expect(updater.fillEnabled).toBe(false); expect(updater.outlineEnabled).toBe(false); expect(updater.isDynamic).toBe(false); }); it("A time-varying position causes geometry to be dynamic", function() { const entity = createBasicEllipse(); const updater = new import__60.EllipseGeometryUpdater(entity, scene2); entity.position = new import__60.SampledPositionProperty(); entity.position.addSample(time2, import__60.Cartesian3.ZERO); updater._onEntityPropertyChanged(entity, "position"); expect(updater.isDynamic).toBe(true); }); it("A time-varying semiMinorAxis causes geometry to be dynamic", function() { const entity = createBasicEllipse(); const updater = new import__60.EllipseGeometryUpdater(entity, scene2); entity.ellipse.semiMinorAxis = new import__60.SampledProperty(Number); entity.ellipse.semiMinorAxis.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "ellipse"); expect(updater.isDynamic).toBe(true); }); it("A time-varying semiMajorAxis causes geometry to be dynamic", function() { const entity = createBasicEllipse(); const updater = new import__60.EllipseGeometryUpdater(entity, scene2); entity.ellipse.semiMajorAxis = new import__60.SampledProperty(Number); entity.ellipse.semiMajorAxis.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "ellipse"); expect(updater.isDynamic).toBe(true); }); it("A time-varying rotation causes geometry to be dynamic", function() { const entity = createBasicEllipse(); const updater = new import__60.EllipseGeometryUpdater(entity, scene2); entity.ellipse.rotation = new import__60.SampledProperty(Number); entity.ellipse.rotation.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "ellipse"); expect(updater.isDynamic).toBe(true); }); it("A time-varying height causes geometry to be dynamic", function() { const entity = createBasicEllipse(); const updater = new import__60.EllipseGeometryUpdater(entity, scene2); entity.ellipse.height = new import__60.SampledProperty(Number); entity.ellipse.height.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "ellipse"); expect(updater.isDynamic).toBe(true); }); it("A time-varying extrudedHeight causes geometry to be dynamic", function() { const entity = createBasicEllipse(); const updater = new import__60.EllipseGeometryUpdater(entity, scene2); entity.ellipse.extrudedHeight = new import__60.SampledProperty(Number); entity.ellipse.extrudedHeight.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "ellipse"); expect(updater.isDynamic).toBe(true); }); it("A time-varying granularity causes geometry to be dynamic", function() { const entity = createBasicEllipse(); const updater = new import__60.EllipseGeometryUpdater(entity, scene2); entity.ellipse.granularity = new import__60.SampledProperty(Number); entity.ellipse.granularity.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "ellipse"); expect(updater.isDynamic).toBe(true); }); it("A time-varying stRotation causes geometry to be dynamic", function() { const entity = createBasicEllipse(); const updater = new import__60.EllipseGeometryUpdater(entity, scene2); entity.ellipse.stRotation = new import__60.SampledProperty(Number); entity.ellipse.stRotation.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "ellipse"); expect(updater.isDynamic).toBe(true); }); it("A time-varying numberOfVerticalLines causes geometry to be dynamic", function() { const entity = createBasicEllipse(); const updater = new import__60.EllipseGeometryUpdater(entity, scene2); entity.ellipse.numberOfVerticalLines = new import__60.SampledProperty(Number); entity.ellipse.numberOfVerticalLines.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "ellipse"); expect(updater.isDynamic).toBe(true); }); it("Creates geometry with expected properties", function() { const options = { center: new import__60.Cartesian3(4, 5, 6), rotation: 1, semiMajorAxis: 3, semiMinorAxis: 2, height: 431, extrudedHeight: 123, granularity: 0.97, stRotation: 12, numberOfVerticalLines: 15 }; const entity = new import__60.Entity(); entity.position = new import__60.ConstantPositionProperty(options.center); const ellipse = new import__60.EllipseGraphics(); ellipse.outline = true; ellipse.numberOfVerticalLines = new import__60.ConstantProperty( options.numberOfVerticalLines ); ellipse.semiMajorAxis = new import__60.ConstantProperty(options.semiMajorAxis); ellipse.semiMinorAxis = new import__60.ConstantProperty(options.semiMinorAxis); ellipse.rotation = new import__60.ConstantProperty(options.rotation); ellipse.stRotation = new import__60.ConstantProperty(options.stRotation); ellipse.height = new import__60.ConstantProperty(options.height); ellipse.extrudedHeight = new import__60.ConstantProperty(options.extrudedHeight); ellipse.granularity = new import__60.ConstantProperty(options.granularity); entity.ellipse = ellipse; const updater = new import__60.EllipseGeometryUpdater(entity, scene2); let instance; let geometry; instance = updater.createFillGeometryInstance(time2); geometry = instance.geometry; expect(geometry._center).toEqual(options.center); expect(geometry._semiMajorAxis).toEqual(options.semiMajorAxis); expect(geometry._semiMinorAxis).toEqual(options.semiMinorAxis); expect(geometry._rotation).toEqual(options.rotation); expect(geometry._stRotation).toEqual(options.stRotation); expect(geometry._height).toEqual(options.height); expect(geometry._granularity).toEqual(options.granularity); expect(geometry._extrudedHeight).toEqual(options.extrudedHeight); expect(geometry._offsetAttribute).toBeUndefined(); instance = updater.createOutlineGeometryInstance(time2); geometry = instance.geometry; expect(geometry._center).toEqual(options.center); expect(geometry._semiMajorAxis).toEqual(options.semiMajorAxis); expect(geometry._semiMinorAxis).toEqual(options.semiMinorAxis); expect(geometry._rotation).toEqual(options.rotation); expect(geometry._height).toEqual(options.height); expect(geometry._granularity).toEqual(options.granularity); expect(geometry._extrudedHeight).toEqual(options.extrudedHeight); expect(geometry._numberOfVerticalLines).toEqual( options.numberOfVerticalLines ); expect(geometry._offsetAttribute).toBeUndefined(); }); it("dynamic updater sets properties", function() { const ellipse = new import__60.EllipseGraphics(); ellipse.semiMajorAxis = createDynamicProperty_default(2); ellipse.semiMinorAxis = createDynamicProperty_default(1); ellipse.height = createDynamicProperty_default(1); const entity = new import__60.Entity(); entity.position = createDynamicProperty_default(import__60.Cartesian3.UNIT_Z); entity.ellipse = ellipse; const updater = new import__60.EllipseGeometryUpdater(entity, scene2); const dynamicUpdater = updater.createDynamicUpdater( new import__60.PrimitiveCollection(), new import__60.PrimitiveCollection() ); dynamicUpdater.update(import__60.JulianDate.now()); const options = dynamicUpdater._options; expect(options.semiMajorAxis).toEqual(ellipse.semiMajorAxis.getValue()); expect(options.semiMinorAxis).toEqual(ellipse.semiMinorAxis.getValue()); expect(options.height).toEqual(ellipse.height.getValue()); expect(options.offsetAttribute).toBeUndefined(); }); it("geometryChanged event is raised when expected", function() { const entity = createBasicEllipse(); const updater = new import__60.EllipseGeometryUpdater(entity, scene2); const listener = jasmine.createSpy("listener"); updater.geometryChanged.addEventListener(listener); entity.position = new import__60.ConstantPositionProperty(import__60.Cartesian3.UNIT_Z); updater._onEntityPropertyChanged(entity, "position"); expect(listener.calls.count()).toEqual(1); entity.ellipse.semiMajorAxis = new import__60.ConstantProperty(82); updater._onEntityPropertyChanged(entity, "ellipse"); expect(listener.calls.count()).toEqual(2); entity.availability = new import__60.TimeIntervalCollection(); updater._onEntityPropertyChanged(entity, "availability"); expect(listener.calls.count()).toEqual(3); entity.ellipse.semiMajorAxis = void 0; updater._onEntityPropertyChanged(entity, "ellipse"); expect(listener.calls.count()).toEqual(4); entity.ellipse.semiMinorAxis = void 0; updater._onEntityPropertyChanged(entity, "ellipse"); entity.viewFrom = new import__60.ConstantProperty(import__60.Cartesian3.UNIT_X); updater._onEntityPropertyChanged(entity, "viewFrom"); expect(listener.calls.count()).toEqual(4); entity.ellipse.semiMajorAxis = new import__60.SampledProperty(Number); entity.ellipse.semiMinorAxis = new import__60.SampledProperty(Number); updater._onEntityPropertyChanged(entity, "ellipse"); expect(listener.calls.count()).toEqual(5); }); it("computes center", function() { const entity = createBasicEllipse(); const updater = new import__60.EllipseGeometryUpdater(entity, scene2); expect(updater._computeCenter(time2)).toEqual( entity.position.getValue(time2) ); }); function getScene() { return scene2; } createGeometryUpdaterSpecs_default( import__60.EllipseGeometryUpdater, "ellipse", createBasicEllipse, getScene ); createDynamicGeometryUpdaterSpecs_default( import__60.EllipseGeometryUpdater, "ellipse", createDynamicEllipse, getScene ); createGeometryUpdaterGroundGeometrySpecs_default( import__60.EllipseGeometryUpdater, "ellipse", createBasicEllipseWithoutHeight, createDynamicEllipseWithoutHeight, getScene ); }, "WebGL" ); // packages/engine/Specs/DataSources/EllipseGraphicsSpec.js var import__61 = __toESM(require_Cesium(), 1); describe("DataSources/EllipseGraphics", function() { it("creates expected instance from raw assignment and construction", function() { const options = { material: import__61.Color.BLUE, show: true, semiMinorAxis: 1, semiMajorAxis: 2, height: 3, extrudedHeight: 4, granularity: 5, rotation: 6, stRotation: 7, numberOfVerticalLines: 8, fill: false, outline: false, outlineColor: import__61.Color.RED, outlineWidth: 9, shadows: import__61.ShadowMode.DISABLED, distanceDisplayCondition: new import__61.DistanceDisplayCondition(), classificationType: import__61.ClassificationType.TERRAIN, zIndex: 3 }; const ellipse = new import__61.EllipseGraphics(options); expect(ellipse.material).toBeInstanceOf(import__61.ColorMaterialProperty); expect(ellipse.show).toBeInstanceOf(import__61.ConstantProperty); expect(ellipse.semiMinorAxis).toBeInstanceOf(import__61.ConstantProperty); expect(ellipse.semiMajorAxis).toBeInstanceOf(import__61.ConstantProperty); expect(ellipse.height).toBeInstanceOf(import__61.ConstantProperty); expect(ellipse.extrudedHeight).toBeInstanceOf(import__61.ConstantProperty); expect(ellipse.granularity).toBeInstanceOf(import__61.ConstantProperty); expect(ellipse.rotation).toBeInstanceOf(import__61.ConstantProperty); expect(ellipse.stRotation).toBeInstanceOf(import__61.ConstantProperty); expect(ellipse.numberOfVerticalLines).toBeInstanceOf(import__61.ConstantProperty); expect(ellipse.fill).toBeInstanceOf(import__61.ConstantProperty); expect(ellipse.outline).toBeInstanceOf(import__61.ConstantProperty); expect(ellipse.outlineColor).toBeInstanceOf(import__61.ConstantProperty); expect(ellipse.outlineWidth).toBeInstanceOf(import__61.ConstantProperty); expect(ellipse.shadows).toBeInstanceOf(import__61.ConstantProperty); expect(ellipse.distanceDisplayCondition).toBeInstanceOf(import__61.ConstantProperty); expect(ellipse.classificationType).toBeInstanceOf(import__61.ConstantProperty); expect(ellipse.zIndex).toBeInstanceOf(import__61.ConstantProperty); expect(ellipse.material.color.getValue()).toEqual(options.material); expect(ellipse.show.getValue()).toEqual(options.show); expect(ellipse.semiMinorAxis.getValue()).toEqual(options.semiMinorAxis); expect(ellipse.semiMajorAxis.getValue()).toEqual(options.semiMajorAxis); expect(ellipse.height.getValue()).toEqual(options.height); expect(ellipse.extrudedHeight.getValue()).toEqual(options.extrudedHeight); expect(ellipse.granularity.getValue()).toEqual(options.granularity); expect(ellipse.rotation.getValue()).toEqual(options.rotation); expect(ellipse.stRotation.getValue()).toEqual(options.stRotation); expect(ellipse.numberOfVerticalLines.getValue()).toEqual( options.numberOfVerticalLines ); expect(ellipse.fill.getValue()).toEqual(options.fill); expect(ellipse.outline.getValue()).toEqual(options.outline); expect(ellipse.outlineColor.getValue()).toEqual(options.outlineColor); expect(ellipse.outlineWidth.getValue()).toEqual(options.outlineWidth); expect(ellipse.shadows.getValue()).toEqual(options.shadows); expect(ellipse.distanceDisplayCondition.getValue()).toEqual( options.distanceDisplayCondition ); expect(ellipse.classificationType.getValue()).toEqual( options.classificationType ); expect(ellipse.zIndex.getValue()).toEqual(options.zIndex); }); it("merge assigns unassigned properties", function() { const source = new import__61.EllipseGraphics(); source.material = new import__61.ColorMaterialProperty(); source.semiMinorAxis = new import__61.ConstantProperty(); source.semiMajorAxis = new import__61.ConstantProperty(); source.show = new import__61.ConstantProperty(); source.height = new import__61.ConstantProperty(); source.extrudedHeight = new import__61.ConstantProperty(); source.granularity = new import__61.ConstantProperty(); source.rotation = new import__61.ConstantProperty(); source.stRotation = new import__61.ConstantProperty(); source.fill = new import__61.ConstantProperty(); source.outline = new import__61.ConstantProperty(); source.outlineColor = new import__61.ConstantProperty(); source.outlineWidth = new import__61.ConstantProperty(); source.numberOfVerticalLines = new import__61.ConstantProperty(); source.shadows = new import__61.ConstantProperty(import__61.ShadowMode.ENABLED); source.distanceDisplayCondition = new import__61.ConstantProperty( new import__61.DistanceDisplayCondition(10, 100) ); source.classificationType = new import__61.ConstantProperty( import__61.ClassificationType.TERRAIN ); source.zIndex = new import__61.ConstantProperty(3); const target = new import__61.EllipseGraphics(); target.merge(source); expect(target.material).toBe(source.material); expect(target.semiMinorAxis).toBe(source.semiMinorAxis); expect(target.semiMajorAxis).toBe(source.semiMajorAxis); expect(target.show).toBe(source.show); expect(target.height).toBe(source.height); expect(target.extrudedHeight).toBe(source.extrudedHeight); expect(target.granularity).toBe(source.granularity); expect(target.rotation).toBe(source.rotation); expect(target.stRotation).toBe(source.stRotation); expect(target.fill).toBe(source.fill); expect(target.outline).toBe(source.outline); expect(target.outlineColor).toBe(source.outlineColor); expect(target.outlineWidth).toBe(source.outlineWidth); expect(target.numberOfVerticalLines).toBe(source.numberOfVerticalLines); expect(target.shadows).toBe(source.shadows); expect(target.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(target.classificationType).toBe(source.classificationType); expect(target.zIndex).toBe(source.zIndex); }); it("merge does not assign assigned properties", function() { const source = new import__61.EllipseGraphics(); const material = new import__61.ColorMaterialProperty(); const semiMajorAxis = new import__61.ConstantProperty(); const semiMinorAxis = new import__61.ConstantProperty(); const show = new import__61.ConstantProperty(); const height = new import__61.ConstantProperty(); const extrudedHeight = new import__61.ConstantProperty(); const granularity = new import__61.ConstantProperty(); const rotation = new import__61.ConstantProperty(); const stRotation = new import__61.ConstantProperty(); const fill = new import__61.ConstantProperty(); const outline = new import__61.ConstantProperty(); const outlineColor = new import__61.ConstantProperty(); const outlineWidth = new import__61.ConstantProperty(); const numberOfVerticalLines = new import__61.ConstantProperty(); const shadows = new import__61.ConstantProperty(); const distanceDisplayCondition = new import__61.ConstantProperty(); const classificationType = new import__61.ConstantProperty(); const zIndex = new import__61.ConstantProperty(); const target = new import__61.EllipseGraphics(); target.material = material; target.semiMinorAxis = semiMinorAxis; target.semiMajorAxis = semiMajorAxis; target.show = show; target.height = height; target.extrudedHeight = extrudedHeight; target.granularity = granularity; target.rotation = rotation; target.stRotation = stRotation; target.fill = fill; target.outline = outline; target.outlineColor = outlineColor; target.outlineWidth = outlineWidth; target.numberOfVerticalLines = numberOfVerticalLines; target.shadows = shadows; target.distanceDisplayCondition = distanceDisplayCondition; target.classificationType = classificationType; target.zIndex = zIndex; target.merge(source); expect(target.material).toBe(material); expect(target.semiMinorAxis).toBe(semiMinorAxis); expect(target.semiMajorAxis).toBe(semiMajorAxis); expect(target.show).toBe(show); expect(target.height).toBe(height); expect(target.extrudedHeight).toBe(extrudedHeight); expect(target.granularity).toBe(granularity); expect(target.rotation).toBe(rotation); expect(target.stRotation).toBe(stRotation); expect(target.fill).toBe(fill); expect(target.outline).toBe(outline); expect(target.outlineColor).toBe(outlineColor); expect(target.outlineWidth).toBe(outlineWidth); expect(target.numberOfVerticalLines).toBe(numberOfVerticalLines); expect(target.shadows).toBe(shadows); expect(target.distanceDisplayCondition).toBe(distanceDisplayCondition); expect(target.classificationType).toBe(classificationType); expect(target.zIndex).toBe(zIndex); }); it("clone works", function() { const source = new import__61.EllipseGraphics(); source.material = new import__61.ColorMaterialProperty(); source.semiMinorAxis = new import__61.ConstantProperty(); source.semiMajorAxis = new import__61.ConstantProperty(); source.show = new import__61.ConstantProperty(); source.height = new import__61.ConstantProperty(); source.extrudedHeight = new import__61.ConstantProperty(); source.granularity = new import__61.ConstantProperty(); source.rotation = new import__61.ConstantProperty(); source.stRotation = new import__61.ConstantProperty(); source.fill = new import__61.ConstantProperty(); source.outline = new import__61.ConstantProperty(); source.outlineColor = new import__61.ConstantProperty(); source.outlineWidth = new import__61.ConstantProperty(); source.numberOfVerticalLines = new import__61.ConstantProperty(); source.shadows = new import__61.ConstantProperty(); source.distanceDisplayCondition = new import__61.ConstantProperty(); source.classificationType = new import__61.ConstantProperty(); source.zIndex = new import__61.ConstantProperty(); const result = source.clone(); expect(result.material).toBe(source.material); expect(result.semiMinorAxis).toBe(source.semiMinorAxis); expect(result.semiMajorAxis).toBe(source.semiMajorAxis); expect(result.show).toBe(source.show); expect(result.height).toBe(source.height); expect(result.extrudedHeight).toBe(source.extrudedHeight); expect(result.granularity).toBe(source.granularity); expect(result.rotation).toBe(source.rotation); expect(result.stRotation).toBe(source.stRotation); expect(result.fill).toBe(source.fill); expect(result.outline).toBe(source.outline); expect(result.outlineColor).toBe(source.outlineColor); expect(result.outlineWidth).toBe(source.outlineWidth); expect(result.numberOfVerticalLines).toBe(source.numberOfVerticalLines); expect(result.shadows).toBe(source.shadows); expect(result.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(result.classificationType).toBe(source.classificationType); expect(result.zIndex).toBe(source.zIndex); }); it("merge throws if source undefined", function() { const target = new import__61.EllipseGraphics(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__61.EllipseGraphics(); testMaterialDefinitionChanged_default(property, "material", import__61.Color.RED, import__61.Color.BLUE); testDefinitionChanged_default(property, "semiMinorAxis", 2, 3); testDefinitionChanged_default(property, "semiMajorAxis", 3, 4); testDefinitionChanged_default(property, "show", true, false); testDefinitionChanged_default(property, "height", 3, 4); testDefinitionChanged_default(property, "extrudedHeight", 4, 3); testDefinitionChanged_default(property, "granularity", 1, 2); testDefinitionChanged_default(property, "rotation", 5, 6); testDefinitionChanged_default(property, "stRotation", 5, 6); testDefinitionChanged_default(property, "fill", false, true); testDefinitionChanged_default(property, "outline", true, false); testDefinitionChanged_default(property, "outlineColor", import__61.Color.RED, import__61.Color.BLUE); testDefinitionChanged_default(property, "outlineWidth", 2, 3); testDefinitionChanged_default(property, "numberOfVerticalLines", 16, 32); testDefinitionChanged_default( property, "shadows", import__61.ShadowMode.ENABLED, import__61.ShadowMode.DISABLED ); testDefinitionChanged_default( property, "distanceDisplayCondition", new import__61.DistanceDisplayCondition(), new import__61.DistanceDisplayCondition(10, 100) ); testDefinitionChanged_default( property, "classificationType", import__61.ClassificationType.TERRAIN, import__61.ClassificationType.BOTH ); testDefinitionChanged_default(property, "zIndex", 4, 0); }); }); // packages/engine/Specs/DataSources/EllipsoidGeometryUpdaterSpec.js var import__62 = __toESM(require_Cesium(), 1); var import__63 = __toESM(require_Cesium(), 1); describe( "DataSources/EllipsoidGeometryUpdater", function() { const time2 = import__62.JulianDate.now(); let scene2; beforeEach(function() { scene2 = createScene_default(); }); afterEach(function() { scene2.destroyForSpecs(); }); function createBasicEllipsoid() { const ellipsoid = new import__62.EllipsoidGraphics(); ellipsoid.radii = new import__62.ConstantProperty(new import__62.Cartesian3(1, 2, 3)); const entity = new import__62.Entity(); entity.position = new import__62.ConstantPositionProperty( import__62.Cartesian3.fromDegrees(0, 0, 0) ); entity.ellipsoid = ellipsoid; return entity; } function createDynamicEllipsoid() { const entity = createBasicEllipsoid(); entity.ellipsoid.radii = createDynamicProperty_default(new import__62.Cartesian3(1, 2, 3)); return entity; } it("No geometry available when radii is undefined", function() { const entity = createBasicEllipsoid(); const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); entity.ellipsoid.radii = void 0; updater._onEntityPropertyChanged(entity, "ellipsoid"); expect(updater.fillEnabled).toBe(false); expect(updater.outlineEnabled).toBe(false); expect(updater.isDynamic).toBe(false); }); it("A time-varying position causes geometry to be dynamic", function() { const entity = createBasicEllipsoid(); const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); entity.position = new import__62.SampledPositionProperty(); entity.position.addSample(time2, import__62.Cartesian3.ZERO); updater._onEntityPropertyChanged(entity, "position"); expect(updater.isDynamic).toBe(true); }); it("A time-varying radii causes geometry to be dynamic", function() { const entity = createBasicEllipsoid(); const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); entity.ellipsoid.radii = new import__62.SampledProperty(import__62.Cartesian3); entity.ellipsoid.radii.addSample(time2, new import__62.Cartesian3(1, 2, 3)); updater._onEntityPropertyChanged(entity, "ellipsoid"); expect(updater.isDynamic).toBe(true); }); it("A time-varying stackPartitions causes geometry to be dynamic", function() { const entity = createBasicEllipsoid(); const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); entity.ellipsoid.stackPartitions = new import__62.SampledProperty(Number); entity.ellipsoid.stackPartitions.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "ellipsoid"); expect(updater.isDynamic).toBe(true); }); it("A time-varying slicePartitions causes geometry to be dynamic", function() { const entity = createBasicEllipsoid(); const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); entity.ellipsoid.slicePartitions = new import__62.SampledProperty(Number); entity.ellipsoid.slicePartitions.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "ellipsoid"); expect(updater.isDynamic).toBe(true); }); it("A time-varying subdivisions causes geometry to be dynamic", function() { const entity = createBasicEllipsoid(); const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); entity.ellipsoid.subdivisions = new import__62.SampledProperty(Number); entity.ellipsoid.subdivisions.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "ellipsoid"); expect(updater.isDynamic).toBe(true); }); it("A time-varying innerRadii causes geometry to be dynamic", function() { const entity = createBasicEllipsoid(); const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); entity.ellipsoid.innerRadii = new import__62.SampledProperty(import__62.Cartesian3); entity.ellipsoid.innerRadii.addSample(time2, new import__62.Cartesian3(1, 2, 3)); updater._onEntityPropertyChanged(entity, "ellipsoid"); expect(updater.isDynamic).toBe(true); }); it("A time-varying minimumClock causes geometry to be dynamic", function() { const entity = createBasicEllipsoid(); const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); entity.ellipsoid.minimumClock = new import__62.SampledProperty(Number); entity.ellipsoid.minimumClock.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "ellipsoid"); expect(updater.isDynamic).toBe(true); }); it("A time-varying maximumClock causes geometry to be dynamic", function() { const entity = createBasicEllipsoid(); const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); entity.ellipsoid.maximumClock = new import__62.SampledProperty(Number); entity.ellipsoid.maximumClock.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "ellipsoid"); expect(updater.isDynamic).toBe(true); }); it("A time-varying minimumCone causes geometry to be dynamic", function() { const entity = createBasicEllipsoid(); const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); entity.ellipsoid.minimumCone = new import__62.SampledProperty(Number); entity.ellipsoid.minimumCone.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "ellipsoid"); expect(updater.isDynamic).toBe(true); }); it("A time-varying maximumCone causes geometry to be dynamic", function() { const entity = createBasicEllipsoid(); const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); entity.ellipsoid.maximumCone = new import__62.SampledProperty(Number); entity.ellipsoid.maximumCone.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "ellipsoid"); expect(updater.isDynamic).toBe(true); }); it("Creates geometry with expected properties", function() { const options = { radii: new import__62.Cartesian3(1, 2, 3), innerRadii: new import__62.Cartesian3(0.5, 1, 1.5), minimumClock: import__63.Math.toRadians(90), maximumClock: import__63.Math.toRadians(270), minimumCone: import__63.Math.toRadians(45), maximumCone: import__63.Math.toRadians(90), stackPartitions: 32, slicePartitions: 64, subdivisions: 15 }; const entity = new import__62.Entity(); entity.position = new import__62.ConstantPositionProperty(new import__62.Cartesian3(4, 5, 6)); entity.orientation = new import__62.ConstantProperty(import__62.Quaternion.IDENTITY); const ellipsoid = new import__62.EllipsoidGraphics(); ellipsoid.outline = true; ellipsoid.radii = new import__62.ConstantProperty(options.radii); ellipsoid.stackPartitions = new import__62.ConstantProperty(options.stackPartitions); ellipsoid.slicePartitions = new import__62.ConstantProperty(options.slicePartitions); ellipsoid.innerRadii = new import__62.ConstantProperty(options.innerRadii); ellipsoid.minimumClock = new import__62.ConstantProperty(options.minimumClock); ellipsoid.maximumClock = new import__62.ConstantProperty(options.maximumClock); ellipsoid.minimumCone = new import__62.ConstantProperty(options.minimumCone); ellipsoid.maximumCone = new import__62.ConstantProperty(options.maximumCone); ellipsoid.subdivisions = new import__62.ConstantProperty(options.subdivisions); entity.ellipsoid = ellipsoid; const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); let instance; let geometry; instance = updater.createFillGeometryInstance(time2); geometry = instance.geometry; expect(geometry._center).toEqual(options.center); expect(geometry._radii).toEqual(options.radii); expect(geometry._innerRadii).toEqual(options.innerRadii); expect(geometry._minimumClock).toEqual(options.minimumClock); expect(geometry._maximumClock).toEqual(options.maximumClock); expect(geometry._minimumCone).toEqual(options.minimumCone); expect(geometry._maximumCone).toEqual(options.maximumCone); expect(geometry._stackPartitions).toEqual(options.stackPartitions); expect(geometry._slicePartitions).toEqual(options.slicePartitions); expect(geometry._offsetAttribute).toBeUndefined(); instance = updater.createOutlineGeometryInstance(time2); geometry = instance.geometry; expect(geometry._center).toEqual(options.center); expect(geometry._radii).toEqual(options.radii); expect(geometry._innerRadii).toEqual(options.innerRadii); expect(geometry._minimumClock).toEqual(options.minimumClock); expect(geometry._maximumClock).toEqual(options.maximumClock); expect(geometry._minimumCone).toEqual(options.minimumCone); expect(geometry._maximumCone).toEqual(options.maximumCone); expect(geometry._stackPartitions).toEqual(options.stackPartitions); expect(geometry._slicePartitions).toEqual(options.slicePartitions); expect(geometry._subdivisions).toEqual(options.subdivisions); expect(geometry._offsetAttribute).toBeUndefined(); }); it("Creates geometry with expected offsetAttribute", function() { const entity = createBasicEllipsoid(); const graphics = entity.ellipsoid; graphics.outline = true; graphics.outlineColor = import__62.Color.BLACK; graphics.height = new import__62.ConstantProperty(20); graphics.extrudedHeight = new import__62.ConstantProperty(0); const updater = new import__62.EllipsoidGeometryUpdater(entity, getScene()); let instance; updater._onEntityPropertyChanged(entity, "ellipsoid"); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); graphics.heightReference = new import__62.ConstantProperty(import__62.HeightReference.NONE); updater._onEntityPropertyChanged(entity, "ellipsoid"); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); graphics.heightReference = new import__62.ConstantProperty( import__62.HeightReference.CLAMP_TO_GROUND ); updater._onEntityPropertyChanged(entity, "ellipsoid"); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import__62.GeometryOffsetAttribute.ALL ); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import__62.GeometryOffsetAttribute.ALL ); graphics.heightReference = new import__62.ConstantProperty( import__62.HeightReference.RELATIVE_TO_GROUND ); updater._onEntityPropertyChanged(entity, "ellipsoid"); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import__62.GeometryOffsetAttribute.ALL ); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toEqual( import__62.GeometryOffsetAttribute.ALL ); }); it("computes center", function() { const entity = createBasicEllipsoid(); const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); expect(updater._computeCenter(time2)).toEqual( entity.position.getValue(time2) ); }); it("dynamic ellipsoid creates and updates", function() { const ellipsoid = new import__62.EllipsoidGraphics(); ellipsoid.show = createDynamicProperty_default(true); ellipsoid.radii = createDynamicProperty_default(new import__62.Cartesian3(1, 2, 3)); ellipsoid.outline = createDynamicProperty_default(true); ellipsoid.fill = createDynamicProperty_default(true); const entity = new import__62.Entity(); entity.position = createDynamicProperty_default(import__62.Cartesian3.fromDegrees(0, 0, 0)); entity.orientation = createDynamicProperty_default(import__62.Quaternion.IDENTITY); entity.ellipsoid = ellipsoid; const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); const primitives = new import__62.PrimitiveCollection(); const dynamicUpdater = updater.createDynamicUpdater( primitives, new import__62.PrimitiveCollection() ); expect(dynamicUpdater.isDestroyed()).toBe(false); expect(primitives.length).toBe(0); dynamicUpdater.update(time2); expect(primitives.length).toBe(2); expect(primitives.get(0).show).toBe(true); expect(primitives.get(1).show).toBe(true); ellipsoid.show.setValue(false); updater._onEntityPropertyChanged(entity, "ellipsoid"); dynamicUpdater.update(time2); expect(primitives.get(0).show).toBe(false); expect(primitives.get(1).show).toBe(false); expect(primitives.length).toBe(2); dynamicUpdater.destroy(); expect(primitives.length).toBe(0); updater.destroy(); }); it("dynamic ellipsoid is hidden if missing required values", function() { const ellipsoid = new import__62.EllipsoidGraphics(); ellipsoid.show = createDynamicProperty_default(true); ellipsoid.radii = createDynamicProperty_default(new import__62.Cartesian3(1, 2, 3)); ellipsoid.outline = createDynamicProperty_default(true); ellipsoid.fill = createDynamicProperty_default(true); const entity = new import__62.Entity(); entity.position = createDynamicProperty_default(import__62.Cartesian3.fromDegrees(0, 0, 0)); entity.ellipsoid = ellipsoid; const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); const primitives = scene2.primitives; const dynamicUpdater = updater.createDynamicUpdater( primitives, new import__62.PrimitiveCollection() ); dynamicUpdater.update(time2); expect(primitives.length).toBe(2); scene2.initializeFrame(); scene2.render(); entity.position.setValue(void 0); updater._onEntityPropertyChanged(entity, "position"); dynamicUpdater.update(time2); expect(primitives.get(0).show).toBe(false); expect(primitives.get(1).show).toBe(false); expect(primitives.length).toBe(2); entity.position.setValue(import__62.Cartesian3.fromDegrees(0, 0, 0)); updater._onEntityPropertyChanged(entity, "position"); ellipsoid.radii.setValue(void 0); updater._onEntityPropertyChanged(entity, "ellipsoid"); dynamicUpdater.update(time2); expect(primitives.get(0).show).toBe(false); expect(primitives.get(1).show).toBe(false); expect(primitives.length).toBe(2); ellipsoid.radii.setValue(new import__62.Cartesian3(1, 2, 3)); updater._onEntityPropertyChanged(entity, "ellipsoid"); dynamicUpdater.update(time2); expect(primitives.get(0).show).toBe(true); expect(primitives.get(1).show).toBe(true); expect(primitives.length).toBe(2); dynamicUpdater.destroy(); expect(primitives.length).toBe(0); updater.destroy(); }); it("Inner radii should be set when not in 3D mode", function() { const ellipsoid = new import__62.EllipsoidGraphics(); ellipsoid.radii = createDynamicProperty_default(new import__62.Cartesian3(1, 2, 3)); ellipsoid.innerRadii = createDynamicProperty_default(new import__62.Cartesian3(0.5, 1, 1.5)); ellipsoid.heightReference = new import__62.ConstantProperty( import__62.HeightReference.RELATIVE_TO_GROUND ); ellipsoid.material = new import__62.ColorMaterialProperty(import__62.Color.RED); const entity = new import__62.Entity(); entity.position = createDynamicProperty_default(import__62.Cartesian3.fromDegrees(0, 0, 0)); entity.orientation = createDynamicProperty_default(import__62.Quaternion.IDENTITY); entity.ellipsoid = ellipsoid; const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); const primitives = scene2.primitives; const dynamicUpdater = updater.createDynamicUpdater( primitives, new import__62.PrimitiveCollection() ); dynamicUpdater.update(time2); scene2.initializeFrame(); scene2.render(); expect(dynamicUpdater._options.innerRadii).toEqual( ellipsoid.innerRadii.getValue() ); }); it("Inner radii should be scaled when in 3D mode", function() { const ellipsoid = new import__62.EllipsoidGraphics(); ellipsoid.radii = createDynamicProperty_default(new import__62.Cartesian3(1, 2, 3)); ellipsoid.innerRadii = createDynamicProperty_default(new import__62.Cartesian3(0.5, 1, 1.5)); const entity = new import__62.Entity(); entity.position = createDynamicProperty_default(import__62.Cartesian3.fromDegrees(0, 0, 0)); entity.orientation = createDynamicProperty_default(import__62.Quaternion.IDENTITY); entity.ellipsoid = ellipsoid; const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); const primitives = scene2.primitives; const dynamicUpdater = updater.createDynamicUpdater( primitives, new import__62.PrimitiveCollection() ); dynamicUpdater.update(time2); scene2.initializeFrame(); scene2.render(); expect(dynamicUpdater._options.innerRadii.x).toEqual(0.5); expect(dynamicUpdater._options.innerRadii.y).toEqual(0.5); expect(dynamicUpdater._options.innerRadii.z).toEqual(0.5); }); it("dynamic ellipsoid fast path updates attributes", function() { const ellipsoid = new import__62.EllipsoidGraphics(); ellipsoid.show = createDynamicProperty_default(true); ellipsoid.radii = createDynamicProperty_default(new import__62.Cartesian3(1, 2, 3)); ellipsoid.outline = createDynamicProperty_default(true); ellipsoid.fill = createDynamicProperty_default(true); ellipsoid.outlineColor = createDynamicProperty_default(import__62.Color.BLUE); ellipsoid.material = new import__62.ColorMaterialProperty(import__62.Color.RED); const entity = new import__62.Entity(); entity.position = createDynamicProperty_default(import__62.Cartesian3.fromDegrees(0, 0, 0)); entity.orientation = createDynamicProperty_default(import__62.Quaternion.IDENTITY); entity.ellipsoid = ellipsoid; const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); const primitives = scene2.primitives; const dynamicUpdater = updater.createDynamicUpdater( primitives, new import__62.PrimitiveCollection() ); dynamicUpdater.update(time2); expect(primitives.length).toBe(2); scene2.initializeFrame(); scene2.render(); ellipsoid.fill.setValue(false); ellipsoid.outline.setValue(false); ellipsoid.outlineColor = createDynamicProperty_default(import__62.Color.YELLOW); ellipsoid.material = new import__62.ColorMaterialProperty(import__62.Color.ORANGE); updater._onEntityPropertyChanged(entity, "ellipsoid"); dynamicUpdater.update(time2); let attributes = primitives.get(0).getGeometryInstanceAttributes(entity); expect(attributes.show[0]).toEqual(0); expect(primitives.get(0).appearance.material.uniforms.color).toEqual( ellipsoid.material.color.getValue() ); attributes = primitives.get(1).getGeometryInstanceAttributes(entity); expect(attributes.show[0]).toEqual(0); expect(attributes.color).toEqual( import__62.ColorGeometryInstanceAttribute.toValue( ellipsoid.outlineColor.getValue() ) ); }); it("geometryChanged event is raised when expected", function() { const entity = createBasicEllipsoid(); const updater = new import__62.EllipsoidGeometryUpdater(entity, scene2); const listener = jasmine.createSpy("listener"); updater.geometryChanged.addEventListener(listener); entity.position = new import__62.ConstantPositionProperty(import__62.Cartesian3.UNIT_Z); updater._onEntityPropertyChanged(entity, "position"); expect(listener.calls.count()).toEqual(1); entity.ellipsoid.radii = new import__62.ConstantProperty(new import__62.Cartesian3(1, 2, 3)); updater._onEntityPropertyChanged(entity, "ellipsoid"); expect(listener.calls.count()).toEqual(2); entity.availability = new import__62.TimeIntervalCollection(); updater._onEntityPropertyChanged(entity, "availability"); expect(listener.calls.count()).toEqual(3); entity.ellipsoid.radii = void 0; updater._onEntityPropertyChanged(entity, "ellipsoid"); expect(listener.calls.count()).toEqual(4); entity.viewFrom = new import__62.ConstantProperty(import__62.Cartesian3.UNIT_X); updater._onEntityPropertyChanged(entity, "viewFrom"); expect(listener.calls.count()).toEqual(4); entity.ellipsoid.radii = new import__62.SampledProperty(import__62.Cartesian3); updater._onEntityPropertyChanged(entity, "ellipsoid"); expect(listener.calls.count()).toEqual(5); }); function getScene() { return scene2; } createGeometryUpdaterSpecs_default( import__62.EllipsoidGeometryUpdater, "ellipsoid", createBasicEllipsoid, getScene ); createDynamicGeometryUpdaterSpecs_default( import__62.EllipsoidGeometryUpdater, "ellipsoid", createDynamicEllipsoid, getScene ); }, "WebGL" ); // packages/engine/Specs/DataSources/EllipsoidGraphicsSpec.js var import__64 = __toESM(require_Cesium(), 1); describe("DataSources/EllipsoidGraphics", function() { it("creates expected instance from raw assignment and construction", function() { const options = { material: import__64.Color.BLUE, show: true, stackPartitions: 1, slicePartitions: 2, subdivisions: 3, fill: false, outline: false, outlineColor: import__64.Color.RED, outlineWidth: 4, shadows: import__64.ShadowMode.DISABLED, distanceDisplayCondition: new import__64.DistanceDisplayCondition() }; const ellipsoid = new import__64.EllipsoidGraphics(options); expect(ellipsoid.material).toBeInstanceOf(import__64.ColorMaterialProperty); expect(ellipsoid.show).toBeInstanceOf(import__64.ConstantProperty); expect(ellipsoid.stackPartitions).toBeInstanceOf(import__64.ConstantProperty); expect(ellipsoid.slicePartitions).toBeInstanceOf(import__64.ConstantProperty); expect(ellipsoid.subdivisions).toBeInstanceOf(import__64.ConstantProperty); expect(ellipsoid.fill).toBeInstanceOf(import__64.ConstantProperty); expect(ellipsoid.outline).toBeInstanceOf(import__64.ConstantProperty); expect(ellipsoid.outlineColor).toBeInstanceOf(import__64.ConstantProperty); expect(ellipsoid.outlineWidth).toBeInstanceOf(import__64.ConstantProperty); expect(ellipsoid.shadows).toBeInstanceOf(import__64.ConstantProperty); expect(ellipsoid.distanceDisplayCondition).toBeInstanceOf(import__64.ConstantProperty); expect(ellipsoid.material.color.getValue()).toEqual(options.material); expect(ellipsoid.show.getValue()).toEqual(options.show); expect(ellipsoid.stackPartitions.getValue()).toEqual( options.stackPartitions ); expect(ellipsoid.slicePartitions.getValue()).toEqual( options.slicePartitions ); expect(ellipsoid.subdivisions.getValue()).toEqual(options.subdivisions); expect(ellipsoid.fill.getValue()).toEqual(options.fill); expect(ellipsoid.outline.getValue()).toEqual(options.outline); expect(ellipsoid.outlineColor.getValue()).toEqual(options.outlineColor); expect(ellipsoid.outlineWidth.getValue()).toEqual(options.outlineWidth); expect(ellipsoid.shadows.getValue()).toEqual(options.shadows); expect(ellipsoid.distanceDisplayCondition.getValue()).toEqual( options.distanceDisplayCondition ); }); it("merge assigns unassigned properties", function() { const source = new import__64.EllipsoidGraphics(); source.material = new import__64.ColorMaterialProperty(); source.radii = new import__64.ConstantProperty(); source.innerRadii = new import__64.ConstantProperty(); source.minimumClock = new import__64.ConstantProperty(); source.maximumClock = new import__64.ConstantProperty(); source.minimumCone = new import__64.ConstantProperty(); source.maximumCone = new import__64.ConstantProperty(); source.show = new import__64.ConstantProperty(); source.stackPartitions = new import__64.ConstantProperty(); source.slicePartitions = new import__64.ConstantProperty(); source.subdivisions = new import__64.ConstantProperty(); source.fill = new import__64.ConstantProperty(); source.outline = new import__64.ConstantProperty(); source.outlineColor = new import__64.ConstantProperty(); source.outlineWidth = new import__64.ConstantProperty(); source.shadows = new import__64.ConstantProperty(import__64.ShadowMode.ENABLED); source.distanceDisplayCondition = new import__64.ConstantProperty( new import__64.DistanceDisplayCondition() ); const target = new import__64.EllipsoidGraphics(); target.merge(source); expect(target.material).toBe(source.material); expect(target.radii).toBe(source.radii); expect(target.innerRadii).toBe(source.innerRadii); expect(target.minimumClock).toBe(source.minimumClock); expect(target.maximumClock).toBe(source.maximumClock); expect(target.minimumCone).toBe(source.minimumCone); expect(target.maximumCone).toBe(source.maximumCone); expect(target.show).toBe(source.show); expect(target.stackPartitions).toBe(source.stackPartitions); expect(target.slicePartitions).toBe(source.slicePartitions); expect(target.subdivisions).toBe(source.subdivisions); expect(target.fill).toBe(source.fill); expect(target.outline).toBe(source.outline); expect(target.outlineColor).toBe(source.outlineColor); expect(target.outlineWidth).toBe(source.outlineWidth); expect(target.shadows).toBe(source.shadows); expect(target.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); }); it("merge does not assign assigned properties", function() { const source = new import__64.EllipsoidGraphics(); const material = new import__64.ColorMaterialProperty(); const radii = new import__64.ConstantProperty(); const innerRadii = new import__64.ConstantProperty(); const minimumClock = new import__64.ConstantProperty(); const maximumClock = new import__64.ConstantProperty(); const minimumCone = new import__64.ConstantProperty(); const maximumCone = new import__64.ConstantProperty(); const show = new import__64.ConstantProperty(); const stackPartitions = new import__64.ConstantProperty(); const slicePartitions = new import__64.ConstantProperty(); const subdivisions = new import__64.ConstantProperty(); const fill = new import__64.ConstantProperty(); const outline = new import__64.ConstantProperty(); const outlineColor = new import__64.ConstantProperty(); const outlineWidth = new import__64.ConstantProperty(); const shadows = new import__64.ConstantProperty(); const distanecDisplayCondition = new import__64.ConstantProperty(); const target = new import__64.EllipsoidGraphics(); target.material = material; target.radii = radii; target.innerRadii = innerRadii; target.minimumClock = minimumClock; target.maximumClock = maximumClock; target.minimumCone = minimumCone; target.maximumCone = maximumCone; target.show = show; target.stackPartitions = stackPartitions; target.slicePartitions = slicePartitions; target.subdivisions = subdivisions; target.shadows = shadows; target.distanceDisplayCondition = distanecDisplayCondition; source.fill = fill; source.outline = outline; source.outlineColor = outlineColor; source.outlineWidth = outlineWidth; target.merge(source); expect(target.material).toBe(material); expect(target.radii).toBe(radii); expect(target.innerRadii).toBe(innerRadii); expect(target.minimumClock).toBe(minimumClock); expect(target.maximumClock).toBe(maximumClock); expect(target.minimumCone).toBe(minimumCone); expect(target.maximumCone).toBe(maximumCone); expect(target.show).toBe(show); expect(target.stackPartitions).toBe(stackPartitions); expect(target.slicePartitions).toBe(slicePartitions); expect(target.subdivisions).toBe(subdivisions); expect(target.fill).toBe(fill); expect(target.outline).toBe(outline); expect(target.outlineColor).toBe(outlineColor); expect(target.outlineWidth).toBe(outlineWidth); expect(target.shadows).toBe(shadows); expect(target.distanceDisplayCondition).toBe(distanecDisplayCondition); }); it("clone works", function() { const source = new import__64.EllipsoidGraphics(); source.material = new import__64.ColorMaterialProperty(); source.radii = new import__64.ConstantProperty(); source.show = new import__64.ConstantProperty(); source.stackPartitions = new import__64.ConstantProperty(); source.slicePartitions = new import__64.ConstantProperty(); source.subdivisions = new import__64.ConstantProperty(); source.fill = new import__64.ConstantProperty(); source.outline = new import__64.ConstantProperty(); source.outlineColor = new import__64.ConstantProperty(); source.outlineWidth = new import__64.ConstantProperty(); source.shadows = new import__64.ConstantProperty(); source.distanceDisplayCondition = new import__64.ConstantProperty(); let result = source.clone(); expect(result.material).toBe(source.material); expect(result.radii).toBe(source.radii); expect(result.show).toBe(source.show); expect(result.stackPartitions).toBe(source.stackPartitions); expect(result.slicePartitions).toBe(source.slicePartitions); expect(result.subdivisions).toBe(source.subdivisions); expect(result.fill).toBe(source.fill); expect(result.outline).toBe(source.outline); expect(result.outlineColor).toBe(source.outlineColor); expect(result.outlineWidth).toBe(source.outlineWidth); expect(result.shadows).toBe(source.shadows); expect(result.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); result = source.clone(source); expect(result.material).toBe(source.material); expect(result.radii).toBe(source.radii); expect(result.show).toBe(source.show); expect(result.stackPartitions).toBe(source.stackPartitions); expect(result.slicePartitions).toBe(source.slicePartitions); expect(result.subdivisions).toBe(source.subdivisions); expect(result.fill).toBe(source.fill); expect(result.outline).toBe(source.outline); expect(result.outlineColor).toBe(source.outlineColor); expect(result.outlineWidth).toBe(source.outlineWidth); expect(result.shadows).toBe(source.shadows); expect(result.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); }); it("merge throws if source undefined", function() { const target = new import__64.EllipsoidGraphics(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__64.EllipsoidGraphics(); testMaterialDefinitionChanged_default(property, "material", import__64.Color.RED, import__64.Color.BLUE); testDefinitionChanged_default( property, "radii", new import__64.Cartesian3(1, 2, 3), new import__64.Cartesian3(4, 5, 6) ); testDefinitionChanged_default(property, "show", true, false); testDefinitionChanged_default(property, "stackPartitions", 1, 2); testDefinitionChanged_default(property, "slicePartitions", 1, 2); testDefinitionChanged_default(property, "subdivisions", 1, 2); testDefinitionChanged_default(property, "fill", false, true); testDefinitionChanged_default(property, "outline", true, false); testDefinitionChanged_default(property, "outlineColor", import__64.Color.RED, import__64.Color.BLUE); testDefinitionChanged_default(property, "outlineWidth", 2, 3); testDefinitionChanged_default( property, "shadows", import__64.ShadowMode.ENABLED, import__64.ShadowMode.DISABLED ); testDefinitionChanged_default( property, "distanceDisplayCondition", new import__64.DistanceDisplayCondition(), new import__64.DistanceDisplayCondition(10, 100) ); }); }); // packages/engine/Specs/DataSources/EntityClusterSpec.js var import__65 = __toESM(require_Cesium(), 1); describe( "DataSources/EntityCluster", function() { let scene2; let cluster; let depth; let farDepth; beforeAll(function() { scene2 = createScene_default({ canvas: createCanvas_default(10, 10) }); scene2.globe = { ellipsoid: import__65.Ellipsoid.WGS84, _surface: { tileProvider: {}, _tileLoadQueueHigh: [], _tileLoadQueueMedium: [], _tileLoadQueueLow: [], _debug: { tilesWaitingForChildren: 0 }, updateHeight: function() { } }, terrainProviderChanged: new import__65.Event(), imageryLayersUpdatedEvent: new import__65.Event(), tileLoadProgressEvent: new import__65.Event(), beginFrame: function() { }, update: function() { }, render: function() { }, endFrame: function() { }, destroy: function() { }, isDestroyed: () => false }; scene2.globe.getHeight = function() { return 0; }; scene2.globe.terrainProviderChanged = new import__65.Event(); Object.defineProperties(scene2.globe, { terrainProvider: { set: function(value) { this.terrainProviderChanged.raiseEvent(value); } } }); const camera = scene2.camera; camera.setView({ destination: import__65.Cartesian3.fromDegrees(0, 0, 1e4) }); scene2.initializeFrame(); scene2.render(); if (scene2.logarithmicDepthBuffer) { depth = farDepth = 0.1; } else { depth = 0.5; farDepth = 0.9; } }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { cluster = cluster && cluster.destroy(); }); it("constructor sets default properties", function() { cluster = new import__65.EntityCluster(); expect(cluster.enabled).toEqual(false); expect(cluster.show).toEqual(true); expect(cluster.pixelRange).toEqual(80); expect(cluster.minimumClusterSize).toEqual(2); expect(cluster.clusterBillboards).toEqual(true); expect(cluster.clusterLabels).toEqual(true); expect(cluster.clusterPoints).toEqual(true); cluster.enabled = true; expect(cluster.enabled).toEqual(true); cluster.pixelRange = 30; expect(cluster.pixelRange).toEqual(30); cluster.minimumClusterSize = 5; expect(cluster.minimumClusterSize).toEqual(5); }); it("constructor sets expected properties", function() { const options = { enabled: true, show: false, pixelRange: 30, minimumClusterSize: 5, clusterBillboards: false, clusterLabels: false, clusterPoints: false }; cluster = new import__65.EntityCluster(options); expect(cluster.enabled).toEqual(options.enabled); expect(cluster.show).toEqual(false); expect(cluster.pixelRange).toEqual(options.pixelRange); expect(cluster.minimumClusterSize).toEqual(options.minimumClusterSize); expect(cluster.clusterBillboards).toEqual(options.clusterBillboards); expect(cluster.clusterLabels).toEqual(options.clusterLabels); expect(cluster.clusterPoints).toEqual(options.clusterPoints); }); function createBillboardImage() { const canvas = document.createElement("canvas"); canvas.height = canvas.width = 1; const context2D = canvas.getContext("2d"); context2D.clearRect(0, 0, length, length); context2D.fillStyle = "#FF0000"; context2D.fillRect(0, 0, length, length); return canvas; } function updateUntilDone(cluster2) { return pollToPromise_default(function() { const ready = !cluster2._enabledDirty && !cluster2._clusterDirty; cluster2.update(scene2.frameState); return ready; }); } it("clusters billboards", function() { cluster = new import__65.EntityCluster(); cluster._initialize(scene2); let entity = new import__65.Entity(); let billboard = cluster.getBillboard(entity); billboard.id = entity; billboard.image = createBillboardImage(); billboard.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(0, 0), depth ); entity = new import__65.Entity(); billboard = cluster.getBillboard(entity); billboard.id = entity; billboard.image = createBillboardImage(); billboard.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(scene2.canvas.clientWidth, scene2.canvas.clientHeight), depth ); const frameState2 = scene2.frameState; cluster.update(frameState2); expect(cluster._clusterLabelCollection).not.toBeDefined(); cluster.enabled = true; return updateUntilDone(cluster).then(function() { expect(cluster._clusterLabelCollection).toBeDefined(); expect(cluster._clusterLabelCollection.length).toEqual(1); cluster.clusterBillboards = false; cluster.update(frameState2); expect(cluster._clusterLabelCollection).not.toBeDefined(); }); }); it("clusters labels", function() { cluster = new import__65.EntityCluster(); cluster._initialize(scene2); let entity = new import__65.Entity(); let label = cluster.getLabel(entity); label.id = entity; label.text = "a"; label.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(0, 0), depth ); entity = new import__65.Entity(); label = cluster.getLabel(entity); label.id = entity; label.text = "b"; label.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(scene2.canvas.clientWidth, scene2.canvas.clientHeight), depth ); const frameState2 = scene2.frameState; cluster.update(frameState2); expect(cluster._clusterLabelCollection).not.toBeDefined(); cluster.enabled = true; return updateUntilDone(cluster).then(function() { expect(cluster._clusterLabelCollection).toBeDefined(); expect(cluster._clusterLabelCollection.length).toEqual(1); cluster.clusterLabels = false; cluster.update(frameState2); expect(cluster._clusterLabelCollection).not.toBeDefined(); }); }); it("clusters points", function() { cluster = new import__65.EntityCluster(); cluster._initialize(scene2); let entity = new import__65.Entity(); let point = cluster.getPoint(entity); point.id = entity; point.pixelSize = 1; point.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(0, 0), depth ); entity = new import__65.Entity(); point = cluster.getPoint(entity); point.id = entity; point.pixelSize = 1; point.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(scene2.canvas.clientWidth, scene2.canvas.clientHeight), depth ); const frameState2 = scene2.frameState; cluster.update(frameState2); expect(cluster._clusterLabelCollection).not.toBeDefined(); cluster.enabled = true; return updateUntilDone(cluster).then(function() { expect(cluster._clusterLabelCollection).toBeDefined(); expect(cluster._clusterLabelCollection.length).toEqual(1); cluster.clusterPoints = false; cluster.update(frameState2); expect(cluster._clusterLabelCollection).not.toBeDefined(); }); }); it("clusters points on first update", function() { cluster = new import__65.EntityCluster(); cluster._initialize(scene2); let entity = new import__65.Entity(); let point = cluster.getPoint(entity); point.id = entity; point.pixelSize = 1; point.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(0, 0), depth ); entity = new import__65.Entity(); point = cluster.getPoint(entity); point.id = entity; point.pixelSize = 1; point.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(scene2.canvas.clientWidth, scene2.canvas.clientHeight), depth ); cluster.enabled = true; cluster.update(scene2.frameState); expect(cluster._clusterLabelCollection).toBeDefined(); expect(cluster._clusterLabelCollection.length).toEqual(1); }); it("clusters points that have labels", function() { cluster = new import__65.EntityCluster(); cluster._initialize(scene2); let entity = new import__65.Entity(); let point = cluster.getPoint(entity); point.id = entity; point.pixelSize = 1; point.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(0, 0), depth ); entity = new import__65.Entity(); point = cluster.getPoint(entity); point.id = entity; point.pixelSize = 1; point.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(scene2.canvas.clientWidth, scene2.canvas.clientHeight), depth ); const frameState2 = scene2.frameState; cluster.update(frameState2); expect(cluster._clusterLabelCollection).not.toBeDefined(); point.id.label = cluster.getLabel(entity); cluster.enabled = true; cluster.update(frameState2); expect(cluster._clusterLabelCollection).toBeDefined(); expect(cluster._clusterLabelCollection.length).toEqual(1); cluster.clusterPoints = false; cluster.update(frameState2); expect(cluster._clusterLabelCollection).not.toBeDefined(); }); it("records entity collection indices on getting billboard, label and point", function() { cluster = new import__65.EntityCluster(); cluster._initialize(scene2); const entity = new import__65.Entity(); cluster.getBillboard(entity); cluster.getLabel(entity); cluster.getPoint(entity); expect( cluster._collectionIndicesByEntity[entity.id].billboardIndex ).toBeDefined(); expect( cluster._collectionIndicesByEntity[entity.id].labelIndex ).toBeDefined(); expect( cluster._collectionIndicesByEntity[entity.id].pointIndex ).toBeDefined(); }); it("removes entity collection indices when billboard, label and point have been removed", function() { cluster = new import__65.EntityCluster(); cluster._initialize(scene2); const entity = new import__65.Entity(); cluster.getBillboard(entity); cluster.getLabel(entity); cluster.getPoint(entity); cluster.removeBillboard(entity); cluster.removeLabel(entity); cluster.removePoint(entity); expect(cluster._collectionIndicesByEntity[entity.id]).toBeUndefined(); }); it("can destroy cluster and re-add entities", function() { cluster = new import__65.EntityCluster(); cluster._initialize(scene2); const entity1 = new import__65.Entity(); const billboard = cluster.getBillboard(entity1); billboard.id = entity1; const entity2 = new import__65.Entity(); const label = cluster.getLabel(entity2); label.id = entity2; const entity3 = new import__65.Entity(); const point = cluster.getPoint(entity3); point.id = entity3; cluster.destroy(); expect(cluster._billboardCollection).not.toBeDefined(); expect(cluster._labelCollection).not.toBeDefined(); expect(cluster._pointCollection).not.toBeDefined(); expect(cluster.getBillboard(entity1)).toBeDefined(); expect(cluster.getLabel(entity2)).toBeDefined(); expect(cluster.getPoint(entity3)).toBeDefined(); expect(cluster._billboardCollection).toBeDefined(); expect(cluster._labelCollection).toBeDefined(); expect(cluster._pointCollection).toBeDefined(); }); it("does not remove entity collection indices when at least one of billboard, label and point remain", function() { cluster = new import__65.EntityCluster(); cluster._initialize(scene2); const entity = new import__65.Entity(); cluster.getBillboard(entity); cluster.getLabel(entity); cluster.getPoint(entity); cluster.removeBillboard(entity); cluster.removeLabel(entity); expect(cluster._collectionIndicesByEntity[entity.id]).toBeDefined(); }); it("pixel range", function() { cluster = new import__65.EntityCluster(); cluster._initialize(scene2); let entity = new import__65.Entity(); let billboard = cluster.getBillboard(entity); billboard.id = entity; billboard.image = createBillboardImage(); billboard.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(0, 0), depth ); entity = new import__65.Entity(); billboard = cluster.getBillboard(entity); billboard.id = entity; billboard.image = createBillboardImage(); billboard.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(scene2.canvas.clientWidth, scene2.canvas.clientHeight), depth ); const frameState2 = scene2.frameState; cluster.update(frameState2); expect(cluster._clusterLabelCollection).not.toBeDefined(); cluster.enabled = true; return updateUntilDone(cluster).then(function() { expect(cluster._clusterLabelCollection).toBeDefined(); expect(cluster._clusterLabelCollection.length).toEqual(1); cluster.pixelRange = 1; cluster.update(frameState2); expect(cluster._clusterLabelCollection).not.toBeDefined(); }); }); it("minimum cluster size", function() { cluster = new import__65.EntityCluster(); cluster._initialize(scene2); let entity = new import__65.Entity(); let billboard = cluster.getBillboard(entity); billboard.id = entity; billboard.image = createBillboardImage(); billboard.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(0, 0), depth ); entity = new import__65.Entity(); billboard = cluster.getBillboard(entity); billboard.id = entity; billboard.image = createBillboardImage(); billboard.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(scene2.canvas.clientWidth, 0), depth ); entity = new import__65.Entity(); billboard = cluster.getBillboard(entity); billboard.id = entity; billboard.image = createBillboardImage(); billboard.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(0, scene2.canvas.clientHeight), depth ); entity = new import__65.Entity(); billboard = cluster.getBillboard(entity); billboard.id = entity; billboard.image = createBillboardImage(); billboard.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(scene2.canvas.clientWidth, scene2.canvas.clientHeight), depth ); const frameState2 = scene2.frameState; cluster.update(frameState2); expect(cluster._clusterLabelCollection).not.toBeDefined(); cluster.enabled = true; return updateUntilDone(cluster).then(function() { expect(cluster._clusterLabelCollection).toBeDefined(); expect(cluster._clusterLabelCollection.length).toEqual(1); cluster.minimumClusterSize = 5; cluster.update(frameState2); expect(cluster._clusterLabelCollection).not.toBeDefined(); }); }); it("clusters around the same point", function() { cluster = new import__65.EntityCluster(); cluster._initialize(scene2); let entity = new import__65.Entity(); let billboard = cluster.getBillboard(entity); billboard.id = entity; billboard.image = createBillboardImage(); billboard.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(0, 0), farDepth ); entity = new import__65.Entity(); billboard = cluster.getBillboard(entity); billboard.id = entity; billboard.image = createBillboardImage(); billboard.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(scene2.canvas.clientWidth, scene2.canvas.clientHeight), farDepth ); const frameState2 = scene2.frameState; cluster.update(frameState2); expect(cluster._clusterLabelCollection).not.toBeDefined(); cluster.enabled = true; return updateUntilDone(cluster).then(function() { expect(cluster._clusterLabelCollection).toBeDefined(); expect(cluster._clusterLabelCollection.length).toEqual(1); const position = import__65.Cartesian3.clone( cluster._clusterLabelCollection.get(0).position ); scene2.camera.moveForward(1e-6); cluster.pixelRange = cluster.pixelRange - 1; cluster.update(frameState2); expect(cluster._clusterLabelCollection).toBeDefined(); expect(cluster._clusterLabelCollection.length).toEqual(1); expect(cluster._clusterLabelCollection.get(0).position).toEqual( position ); }); }); it("custom cluster styling", function() { cluster = new import__65.EntityCluster(); cluster._initialize(scene2); cluster.clusterEvent.addEventListener(function(clusteredEntities, cluster2) { cluster2.billboard.show = true; cluster2.billboard.image = createBillboardImage(); cluster2.label.text = "cluster"; }); let entity = new import__65.Entity(); let point = cluster.getPoint(entity); point.id = entity; point.pixelSize = 1; point.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(0, 0), farDepth ); entity = new import__65.Entity(); point = cluster.getPoint(entity); point.id = entity; point.pixelSize = 1; point.position = import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(scene2.canvas.clientWidth, scene2.canvas.clientHeight), farDepth ); const frameState2 = scene2.frameState; cluster.update(frameState2); expect(cluster._clusterBillboardCollection).not.toBeDefined(); expect(cluster._clusterLabelCollection).not.toBeDefined(); cluster.enabled = true; cluster.update(frameState2); expect(cluster._clusterLabelCollection).toBeDefined(); expect(cluster._clusterLabelCollection.length).toEqual(1); expect(cluster._clusterLabelCollection.get(0).text).toEqual("cluster"); expect(cluster._clusterBillboardCollection).toBeDefined(); expect(cluster._clusterBillboardCollection.length).toEqual(1); }); it("renders billboards with invisible labels that are not clustered", function() { cluster = new import__65.EntityCluster(); cluster._initialize(scene2); cluster.minimumClusterSize = 3; const dataSource = new import__65.CustomDataSource("test"); dataSource.clustering = cluster; dataSource._visualizers = import__65.DataSourceDisplay.defaultVisualizersCallback( scene2, cluster, dataSource ); const entityCollection = dataSource.entities; entityCollection.add({ position: import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(0, 0), depth ), billboard: { image: createBillboardImage() }, label: { show: true } }); entityCollection.add({ position: import__65.SceneTransforms.drawingBufferToWgs84Coordinates( scene2, new import__65.Cartesian2(scene2.canvas.clientWidth, scene2.canvas.clientHeight), depth ), billboard: { image: createBillboardImage() }, label: { show: true } }); const visualizers = dataSource._visualizers; const length2 = visualizers.length; for (let i = 0; i < length2; i++) { visualizers[i].update(import__65.JulianDate.now()); } const frameState2 = scene2.frameState; cluster.update(frameState2); expect(cluster._clusterBillboardCollection).not.toBeDefined(); expect(cluster._clusterLabelCollection).not.toBeDefined(); cluster.enabled = true; cluster.update(frameState2); expect(cluster._clusterLabelCollection).not.toBeDefined(); expect(cluster._clusterBillboardCollection).not.toBeDefined(); expect(cluster._labelCollection).not.toBeDefined(); expect(cluster._billboardCollection).toBeDefined(); expect(cluster._billboardCollection.length).toEqual(2); }); }, "WebGL" ); // packages/engine/Specs/DataSources/EntityCollectionSpec.js var import__66 = __toESM(require_Cesium(), 1); describe("DataSources/EntityCollection", function() { function CollectionListener() { this.timesCalled = 0; this.added = void 0; this.removed = void 0; this.changed = void 0; } CollectionListener.prototype.onCollectionChanged = function(collection, added, removed, changed) { this.timesCalled++; this.added = added.slice(0); this.removed = removed.slice(0); this.changed = changed.slice(0); }; it("constructor has expected defaults", function() { const entityCollection = new import__66.EntityCollection(); expect(entityCollection.id).toBeDefined(); expect(entityCollection.values.length).toEqual(0); }); it("add/remove works", function() { const entity = new import__66.Entity(); const entity2 = new import__66.Entity(); const entityCollection = new import__66.EntityCollection(); entityCollection.add(entity); expect(entityCollection.values.length).toEqual(1); entityCollection.add(entity2); expect(entityCollection.values.length).toEqual(2); entityCollection.remove(entity2); expect(entityCollection.values.length).toEqual(1); entityCollection.remove(entity); expect(entityCollection.values.length).toEqual(0); }); it("add sets entityCollection on entity", function() { const entity = new import__66.Entity(); const entityCollection = new import__66.EntityCollection(); entityCollection.add(entity); expect(entity.entityCollection).toBe(entityCollection); }); it("Entity.isShowing changes when collection show changes.", function() { const entity = new import__66.Entity(); const entityCollection = new import__66.EntityCollection(); entityCollection.add(entity); expect(entity.isShowing).toBe(true); const listener = jasmine.createSpy("listener"); entity.definitionChanged.addEventListener(listener); entityCollection.show = false; expect(listener.calls.count()).toBe(1); expect(listener.calls.argsFor(0)).toEqual([ entity, "isShowing", false, true ]); expect(entity.isShowing).toBe(false); }); it("add with template", function() { const entityCollection = new import__66.EntityCollection(); const entity = entityCollection.add({ id: "1" }); expect(entityCollection.values.length).toEqual(1); expect(entity.id).toBe("1"); expect(entity.constructor).toBe(import__66.Entity); }); it("add/remove raises expected events", function() { const entity = new import__66.Entity(); const entity2 = new import__66.Entity(); const entityCollection = new import__66.EntityCollection(); const listener = new CollectionListener(); entityCollection.collectionChanged.addEventListener( listener.onCollectionChanged, listener ); entityCollection.add(entity); expect(listener.timesCalled).toEqual(1); expect(listener.added.length).toEqual(1); expect(listener.added[0]).toBe(entity); expect(listener.removed.length).toEqual(0); expect(listener.changed.length).toEqual(0); entity.name = "newName"; expect(listener.timesCalled).toEqual(2); expect(listener.added.length).toEqual(0); expect(listener.removed.length).toEqual(0); expect(listener.changed.length).toEqual(1); expect(listener.changed[0]).toBe(entity); entityCollection.add(entity2); expect(listener.timesCalled).toEqual(3); expect(listener.added.length).toEqual(1); expect(listener.added[0]).toBe(entity2); expect(listener.removed.length).toEqual(0); expect(listener.changed.length).toEqual(0); entityCollection.remove(entity2); expect(listener.timesCalled).toEqual(4); expect(listener.added.length).toEqual(0); expect(listener.removed.length).toEqual(1); expect(listener.removed[0]).toBe(entity2); expect(listener.changed.length).toEqual(0); entityCollection.remove(entity); expect(listener.timesCalled).toEqual(5); expect(listener.added.length).toEqual(0); expect(listener.removed.length).toEqual(1); expect(listener.removed[0]).toBe(entity); entityCollection.collectionChanged.removeEventListener( listener.onCollectionChanged, listener ); }); it("raises expected events when reentrant", function() { const entityCollection = new import__66.EntityCollection(); const entity = new import__66.Entity(); const entity2 = new import__66.Entity(); entityCollection.add(entity); entityCollection.add(entity2); const entityToDelete = new import__66.Entity(); entityCollection.add(entityToDelete); const entityToAdd = new import__66.Entity(); let inCallback = false; const listener = jasmine.createSpy("listener").and.callFake(function(collection, added, removed, changed) { expect(inCallback).toBe(false); inCallback = true; if (entity2.name !== "Bob") { entity2.name = "Bob"; } if (entityCollection.contains(entityToDelete)) { entityCollection.removeById(entityToDelete.id); } if (!entityCollection.contains(entityToAdd)) { entityCollection.add(entityToAdd); } inCallback = false; }); entityCollection.collectionChanged.addEventListener(listener); entity.name = "newName"; expect(listener.calls.count()).toBe(2); expect(listener.calls.argsFor(0)).toEqual([ entityCollection, [], [], [entity] ]); expect(listener.calls.argsFor(1)).toEqual([ entityCollection, [entityToAdd], [entityToDelete], [entity2] ]); expect(entity.name).toEqual("newName"); expect(entity2.name).toEqual("Bob"); expect(entityCollection.contains(entityToDelete)).toEqual(false); expect(entityCollection.contains(entityToAdd)).toEqual(true); }); it("suspended add/remove raises expected events", function() { const entity = new import__66.Entity(); const entity2 = new import__66.Entity(); const entity3 = new import__66.Entity(); const entityCollection = new import__66.EntityCollection(); const listener = new CollectionListener(); entityCollection.collectionChanged.addEventListener( listener.onCollectionChanged, listener ); entityCollection.suspendEvents(); entityCollection.suspendEvents(); entityCollection.add(entity); entityCollection.add(entity2); entityCollection.add(entity3); entity2.name = "newName2"; entity3.name = "newName3"; entityCollection.remove(entity2); expect(listener.timesCalled).toEqual(0); entityCollection.resumeEvents(); expect(listener.timesCalled).toEqual(0); entityCollection.resumeEvents(); expect(listener.timesCalled).toEqual(1); expect(listener.added.length).toEqual(2); expect(listener.added[0]).toBe(entity); expect(listener.added[1]).toBe(entity3); expect(listener.removed.length).toEqual(0); expect(listener.changed.length).toEqual(0); entityCollection.suspendEvents(); entity.name = "newName"; entity3.name = "newewName3"; entityCollection.remove(entity3); entityCollection.resumeEvents(); expect(listener.timesCalled).toEqual(2); expect(listener.added.length).toEqual(0); expect(listener.removed.length).toEqual(1); expect(listener.removed[0]).toBe(entity3); expect(listener.changed.length).toEqual(1); expect(listener.changed[0]).toBe(entity); entityCollection.suspendEvents(); entityCollection.remove(entity); entityCollection.add(entity); entityCollection.resumeEvents(); expect(listener.timesCalled).toEqual(2); entityCollection.collectionChanged.removeEventListener( listener.onCollectionChanged, listener ); }); it("removeAll works", function() { const entity = new import__66.Entity(); const entity2 = new import__66.Entity(); const entityCollection = new import__66.EntityCollection(); entityCollection.add(entity); entityCollection.add(entity2); entityCollection.removeAll(); expect(entityCollection.values.length).toEqual(0); }); it("removeAll raises expected events", function() { const entity = new import__66.Entity(); const entity2 = new import__66.Entity(); const entityCollection = new import__66.EntityCollection(); const listener = new CollectionListener(); entityCollection.add(entity); entityCollection.add(entity2); entityCollection.collectionChanged.addEventListener( listener.onCollectionChanged, listener ); entityCollection.removeAll(); expect(listener.timesCalled).toEqual(1); expect(listener.removed.length).toEqual(2); expect(listener.removed[0]).toBe(entity); expect(listener.removed[1]).toBe(entity2); expect(listener.added.length).toEqual(0); entityCollection.removeAll(); expect(listener.timesCalled).toEqual(1); entityCollection.collectionChanged.removeEventListener( listener.onCollectionChanged, listener ); }); it("suspended removeAll raises expected events", function() { const entity = new import__66.Entity(); const entity2 = new import__66.Entity(); const entityCollection = new import__66.EntityCollection(); const listener = new CollectionListener(); entityCollection.add(entity); entityCollection.add(entity2); entityCollection.collectionChanged.addEventListener( listener.onCollectionChanged, listener ); entityCollection.suspendEvents(); entity2.name = "newName"; entityCollection.removeAll(); entityCollection.resumeEvents(); expect(listener.timesCalled).toEqual(1); expect(listener.removed.length).toEqual(2); expect(listener.removed[0]).toBe(entity); expect(listener.removed[1]).toBe(entity2); expect(listener.added.length).toEqual(0); expect(listener.changed.length).toEqual(0); entityCollection.suspendEvents(); entityCollection.add(entity); entityCollection.add(entity2); entityCollection.remove(entity2); entityCollection.removeAll(); entityCollection.resumeEvents(); expect(listener.timesCalled).toEqual(1); entityCollection.collectionChanged.removeEventListener( listener.onCollectionChanged, listener ); }); it("removeById returns false if id not in collection.", function() { const entityCollection = new import__66.EntityCollection(); expect(entityCollection.removeById("notThere")).toBe(false); }); it("getById works", function() { const entity = new import__66.Entity(); const entity2 = new import__66.Entity(); const entityCollection = new import__66.EntityCollection(); entityCollection.add(entity); entityCollection.add(entity2); expect(entityCollection.getById(entity.id)).toBe(entity); expect(entityCollection.getById(entity2.id)).toBe(entity2); }); it("getById returns undefined for non-existent object", function() { const entityCollection = new import__66.EntityCollection(); expect(entityCollection.getById("123")).toBeUndefined(); }); it("getOrCreateEntity creates a new object if it does not exist.", function() { const entityCollection = new import__66.EntityCollection(); expect(entityCollection.values.length).toEqual(0); const testObject = entityCollection.getOrCreateEntity("test"); expect(entityCollection.values.length).toEqual(1); expect(entityCollection.values[0]).toEqual(testObject); }); it("getOrCreateEntity does not create a new object if it already exists.", function() { const entityCollection = new import__66.EntityCollection(); expect(entityCollection.values.length).toEqual(0); const testObject = entityCollection.getOrCreateEntity("test"); expect(entityCollection.values.length).toEqual(1); expect(entityCollection.values[0]).toEqual(testObject); const testObject2 = entityCollection.getOrCreateEntity("test"); expect(entityCollection.values.length).toEqual(1); expect(entityCollection.values[0]).toEqual(testObject); expect(testObject2).toEqual(testObject); }); it("computeAvailability returns infinite with no data.", function() { const entityCollection = new import__66.EntityCollection(); const availability = entityCollection.computeAvailability(); expect(availability.start).toEqual(import__66.Iso8601.MINIMUM_VALUE); expect(availability.stop).toEqual(import__66.Iso8601.MAXIMUM_VALUE); }); it("computeAvailability returns intersction of collections.", function() { const entityCollection = new import__66.EntityCollection(); const entity = entityCollection.getOrCreateEntity("1"); const entity2 = entityCollection.getOrCreateEntity("2"); const entity3 = entityCollection.getOrCreateEntity("3"); entity.availability = new import__66.TimeIntervalCollection(); entity.availability.addInterval( import__66.TimeInterval.fromIso8601({ iso8601: "2012-08-01/2012-08-02" }) ); entity2.availability = new import__66.TimeIntervalCollection(); entity2.availability.addInterval( import__66.TimeInterval.fromIso8601({ iso8601: "2012-08-05/2012-08-06" }) ); entity3.availability = void 0; const availability = entityCollection.computeAvailability(); expect(availability.start).toEqual(import__66.JulianDate.fromIso8601("2012-08-01")); expect(availability.stop).toEqual(import__66.JulianDate.fromIso8601("2012-08-06")); }); it("computeAvailability works if only start or stop time is infinite.", function() { const entityCollection = new import__66.EntityCollection(); const entity = entityCollection.getOrCreateEntity("1"); const entity2 = entityCollection.getOrCreateEntity("2"); const entity3 = entityCollection.getOrCreateEntity("3"); entity.availability = new import__66.TimeIntervalCollection(); entity.availability.addInterval( import__66.TimeInterval.fromIso8601({ iso8601: "2012-08-01/9999-12-31T24:00:00Z" }) ); entity2.availability = new import__66.TimeIntervalCollection(); entity2.availability.addInterval( import__66.TimeInterval.fromIso8601({ iso8601: "0000-01-01T00:00:00Z/2012-08-06" }) ); entity3.availability = void 0; const availability = entityCollection.computeAvailability(); expect(availability.start).toEqual(import__66.JulianDate.fromIso8601("2012-08-01")); expect(availability.stop).toEqual(import__66.JulianDate.fromIso8601("2012-08-06")); }); it("resumeEvents throws if no matching suspendEvents ", function() { const entityCollection = new import__66.EntityCollection(); expect(function() { entityCollection.resumeEvents(); }).toThrowDeveloperError(); }); it("add throws with undefined Entity", function() { const entityCollection = new import__66.EntityCollection(); expect(function() { entityCollection.add(void 0); }).toThrowDeveloperError(); }); it("add throws for Entity with same id", function() { const entityCollection = new import__66.EntityCollection(); const entity = new import__66.Entity({ id: "1" }); const entity2 = new import__66.Entity({ id: "1" }); entityCollection.add(entity); expect(function() { entityCollection.add(entity2); }).toThrowDeveloperError(); }); it("contains returns true if in collection", function() { const entityCollection = new import__66.EntityCollection(); const entity = entityCollection.getOrCreateEntity("asd"); expect(entityCollection.contains(entity)).toBe(true); }); it("contains returns false if not in collection", function() { const entityCollection = new import__66.EntityCollection(); expect(entityCollection.contains(new import__66.Entity())).toBe(false); }); it("contains throws with undefined Entity", function() { const entityCollection = new import__66.EntityCollection(); expect(function() { entityCollection.contains(void 0); }).toThrowDeveloperError(); }); it("remove returns false with undefined Entity", function() { const entityCollection = new import__66.EntityCollection(); expect(entityCollection.remove(void 0)).toBe(false); }); it("removeById returns false with undefined id", function() { const entityCollection = new import__66.EntityCollection(); expect(entityCollection.removeById(void 0)).toBe(false); }); it("getById throws if no id specified", function() { const entityCollection = new import__66.EntityCollection(); expect(function() { entityCollection.getById(void 0); }).toThrowDeveloperError(); }); it("getOrCreateEntity throws if no id specified", function() { const entityCollection = new import__66.EntityCollection(); expect(function() { entityCollection.getOrCreateEntity(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/EntitySpec.js var import__67 = __toESM(require_Cesium(), 1); describe("DataSources/Entity", function() { it("constructor sets expected properties.", function() { let entity = new import__67.Entity(); expect(entity.id).toBeDefined(); expect(entity.name).toBeUndefined(); expect(entity.billboard).toBeUndefined(); expect(entity.box).toBeUndefined(); expect(entity.corridor).toBeUndefined(); expect(entity.cylinder).toBeUndefined(); expect(entity.description).toBeUndefined(); expect(entity.ellipse).toBeUndefined(); expect(entity.ellipsoid).toBeUndefined(); expect(entity.label).toBeUndefined(); expect(entity.model).toBeUndefined(); expect(entity.orientation).toBeUndefined(); expect(entity.path).toBeUndefined(); expect(entity.plane).toBeUndefined(); expect(entity.point).toBeUndefined(); expect(entity.polygon).toBeUndefined(); expect(entity.polyline).toBeUndefined(); expect(entity.polylineVolume).toBeUndefined(); expect(entity.position).toBeUndefined(); expect(entity.rectangle).toBeUndefined(); expect(entity.viewFrom).toBeUndefined(); expect(entity.wall).toBeUndefined(); expect(entity.entityCollection).toBeUndefined(); const options = { id: "someId", name: "bob", show: false, availability: new import__67.TimeIntervalCollection(), parent: new import__67.Entity(), customProperty: {}, billboard: {}, box: {}, corridor: {}, cylinder: {}, description: "description", ellipse: {}, ellipsoid: {}, label: {}, model: {}, orientation: new import__67.Quaternion(1, 2, 3, 4), path: {}, plane: {}, point: {}, polygon: {}, polyline: {}, polylineVolume: {}, position: new import__67.Cartesian3(5, 6, 7), rectangle: {}, viewFrom: new import__67.Cartesian3(8, 9, 10), wall: {} }; entity = new import__67.Entity(options); expect(entity.id).toEqual(options.id); expect(entity.name).toEqual(options.name); expect(entity.show).toBe(options.show); expect(entity.availability).toBe(options.availability); expect(entity.parent).toBe(options.parent); expect(entity.customProperty).toBe(options.customProperty); expect(entity.billboard).toBeInstanceOf(import__67.BillboardGraphics); expect(entity.box).toBeInstanceOf(import__67.BoxGraphics); expect(entity.corridor).toBeInstanceOf(import__67.CorridorGraphics); expect(entity.cylinder).toBeInstanceOf(import__67.CylinderGraphics); expect(entity.description).toBeInstanceOf(import__67.ConstantProperty); expect(entity.ellipse).toBeInstanceOf(import__67.EllipseGraphics); expect(entity.ellipsoid).toBeInstanceOf(import__67.EllipsoidGraphics); expect(entity.label).toBeInstanceOf(import__67.LabelGraphics); expect(entity.model).toBeInstanceOf(import__67.ModelGraphics); expect(entity.orientation).toBeInstanceOf(import__67.ConstantProperty); expect(entity.path).toBeInstanceOf(import__67.PathGraphics); expect(entity.plane).toBeInstanceOf(import__67.PlaneGraphics); expect(entity.point).toBeInstanceOf(import__67.PointGraphics); expect(entity.polygon).toBeInstanceOf(import__67.PolygonGraphics); expect(entity.polyline).toBeInstanceOf(import__67.PolylineGraphics); expect(entity.polylineVolume).toBeInstanceOf(import__67.PolylineVolumeGraphics); expect(entity.position).toBeInstanceOf(import__67.ConstantPositionProperty); expect(entity.rectangle).toBeInstanceOf(import__67.RectangleGraphics); expect(entity.viewFrom).toBeInstanceOf(import__67.ConstantProperty); expect(entity.wall).toBeInstanceOf(import__67.WallGraphics); expect(entity.entityCollection).toBeUndefined(); }); it("isAvailable is always true if no availability defined.", function() { const entity = new import__67.Entity(); expect(entity.isAvailable(import__67.JulianDate.now())).toEqual(true); }); it("isAvailable throw if no time specified.", function() { const entity = new import__67.Entity(); expect(function() { entity.isAvailable(); }).toThrowDeveloperError(); }); it("constructor creates a unique id if one is not provided.", function() { const object = new import__67.Entity(); const object2 = new import__67.Entity(); expect(object.id).toBeDefined(); expect(object.id).not.toEqual(object2.id); }); it("isAvailable works.", function() { const entity = new import__67.Entity(); const interval = import__67.TimeInterval.fromIso8601({ iso8601: "2000-01-01/2001-01-01" }); const intervals = new import__67.TimeIntervalCollection(); intervals.addInterval(interval); entity.availability = intervals; expect( entity.isAvailable( import__67.JulianDate.addSeconds(interval.start, -1, new import__67.JulianDate()) ) ).toEqual(false); expect(entity.isAvailable(interval.start)).toEqual(true); expect(entity.isAvailable(interval.stop)).toEqual(true); expect( entity.isAvailable( import__67.JulianDate.addSeconds(interval.stop, 1, new import__67.JulianDate()) ) ).toEqual(false); }); it("definitionChanged works for all properties", function() { const entity = new import__67.Entity(); const propertyNames = entity.propertyNames; const propertyNamesLength = propertyNames.length; const listener = jasmine.createSpy("listener"); entity.definitionChanged.addEventListener(listener); let i; let name; let newValue; let oldValue; for (let x = 0; x < 2; x++) { for (i = 0; i < propertyNamesLength; i++) { name = propertyNames[i]; newValue = new import__67.ConstantProperty(1); oldValue = entity[propertyNames[i]]; entity[name] = newValue; expect(listener).toHaveBeenCalledWith(entity, name, newValue, oldValue); } } }); it("definitionChanged works for properties added via addProperty", function() { const entity = new import__67.Entity(); const propertyName = "justForTest"; entity.addProperty(propertyName); const oldValue = new import__67.ConstantProperty(1); entity[propertyName] = oldValue; const listener = jasmine.createSpy("listener"); entity.definitionChanged.addEventListener(listener); const newValue = new import__67.ConstantProperty(1); entity[propertyName] = newValue; expect(listener).toHaveBeenCalledWith( entity, propertyName, newValue, oldValue ); }); it("merge ignores reserved property names when called with a plain object.", function() { const entity = new import__67.Entity(); entity.merge({ name: void 0, availability: void 0, parent: void 0 }); expect(entity.name).toBeUndefined(); expect(entity.availability).toBeUndefined(); expect(entity.parent).toBeUndefined(); }); it("merge does not overwrite availability", function() { const entity = new import__67.Entity(); const interval = import__67.TimeInterval.fromIso8601({ iso8601: "2000-01-01/2001-01-01" }); entity.availability = interval; const entity2 = new import__67.Entity(); const interval2 = import__67.TimeInterval.fromIso8601({ iso8601: "2000-01-01/2001-01-01" }); entity2.availability = interval2; entity.merge(entity2); expect(entity.availability).toBe(interval); }); it("merge does not overwrite _children", function() { const entity = new import__67.Entity(); entity.merge({ children: true }); expect(entity._children).toEqual([]); }); it("merge works with custom properties.", function() { const propertyName = "customProperty"; const value = "fizzbuzz"; const source = new import__67.Entity({ id: "source" }); source.addProperty(propertyName); source[propertyName] = value; const target = new import__67.Entity({ id: "target" }); spyOn(target, "addProperty").and.callThrough(); target.merge(source); expect(target.addProperty).toHaveBeenCalledWith(propertyName); expect(target[propertyName]).toEqual(source[propertyName]); }); it("merge throws with undefined source", function() { const entity = new import__67.Entity(); expect(function() { entity.merge(void 0); }).toThrowDeveloperError(); }); it("computeModelMatrix throws if no time specified.", function() { const entity = new import__67.Entity(); expect(function() { entity.computeModelMatrix(); }).toThrowDeveloperError(); }); it("computeModelMatrix returns undefined when position is undefined.", function() { const entity = new import__67.Entity(); entity.orientation = new import__67.ConstantProperty(import__67.Quaternion.IDENTITY); expect(entity.computeModelMatrix(new import__67.JulianDate())).toBeUndefined(); }); it("computeModelMatrix returns correct value.", function() { const entity = new import__67.Entity(); const position = new import__67.Cartesian3(123456, 654321, 123456); const orientation = new import__67.Quaternion(1, 2, 3, 4); import__67.Quaternion.normalize(orientation, orientation); entity.position = new import__67.ConstantProperty(position); entity.orientation = new import__67.ConstantProperty(orientation); const modelMatrix = entity.computeModelMatrix(new import__67.JulianDate()); const expected = import__67.Matrix4.fromRotationTranslation( import__67.Matrix3.fromQuaternion(orientation), position ); expect(modelMatrix).toEqual(expected); }); it("computeModelMatrix returns ENU when quaternion is undefined.", function() { const entity = new import__67.Entity(); const position = new import__67.Cartesian3(123456, 654321, 123456); entity.position = new import__67.ConstantProperty(position); const modelMatrix = entity.computeModelMatrix(new import__67.JulianDate()); const expected = import__67.Transforms.eastNorthUpToFixedFrame(position); expect(modelMatrix).toEqual(expected); }); it("computeModelMatrix works with result parameter.", function() { const entity = new import__67.Entity(); const position = new import__67.Cartesian3(123456, 654321, 123456); entity.position = new import__67.ConstantProperty(position); const result = new import__67.Matrix4(); const modelMatrix = entity.computeModelMatrix(new import__67.JulianDate(), result); const expected = import__67.Transforms.eastNorthUpToFixedFrame(position); expect(modelMatrix).toBe(result); expect(modelMatrix).toEqual(expected); }); it("can add and remove custom properties.", function() { const entity = new import__67.Entity(); expect(entity.hasOwnProperty("bob")).toBe(false); expect(entity.propertyNames).not.toContain("bob"); entity.addProperty("bob"); expect(entity.hasOwnProperty("bob")).toBe(true); expect(entity.propertyNames).toContain("bob"); entity.removeProperty("bob"); expect(entity.hasOwnProperty("bob")).toBe(false); expect(entity.propertyNames).not.toContain("bob"); }); it("can re-add removed properties", function() { const entity = new import__67.Entity(); entity.addProperty("bob"); entity.removeProperty("bob"); entity.addProperty("bob"); expect(entity.hasOwnProperty("bob")).toBe(true); expect(entity.propertyNames).toContain("bob"); }); it("addProperty throws with no property specified.", function() { const entity = new import__67.Entity(); expect(function() { entity.addProperty(void 0); }).toThrowDeveloperError(); }); it("addProperty throws with no property specified.", function() { const entity = new import__67.Entity(); expect(function() { entity.addProperty(void 0); }).toThrowDeveloperError(); }); it("removeProperty throws with no property specified.", function() { const entity = new import__67.Entity(); expect(function() { entity.removeProperty(void 0); }).toThrowDeveloperError(); }); it("addProperty throws when adding an existing property.", function() { const entity = new import__67.Entity(); entity.addProperty("bob"); expect(function() { entity.addProperty("bob"); }).toThrowDeveloperError(); }); it("removeProperty throws when non-existent property.", function() { const entity = new import__67.Entity(); expect(function() { entity.removeProperty("bob"); }).toThrowDeveloperError(); }); it("addProperty throws with defined reserved property name.", function() { const entity = new import__67.Entity(); expect(function() { entity.addProperty("merge"); }).toThrowDeveloperError(); }); it("removeProperty throws with defined reserved property name.", function() { const entity = new import__67.Entity(); expect(function() { entity.removeProperty("merge"); }).toThrowDeveloperError(); }); it("addProperty throws with undefined reserved property name.", function() { const entity = new import__67.Entity(); expect(entity.name).toBeUndefined(); expect(function() { entity.addProperty("name"); }).toThrowDeveloperError(); }); it("removeProperty throws with undefined reserved property name.", function() { const entity = new import__67.Entity(); expect(entity.name).toBeUndefined(); expect(function() { entity.removeProperty("name"); }).toThrowDeveloperError(); }); it("isShowing works without parent.", function() { const entity = new import__67.Entity({ show: false }); expect(entity.isShowing).toBe(false); const listener = jasmine.createSpy("listener"); entity.definitionChanged.addEventListener(listener); entity.show = true; expect(listener.calls.count()).toBe(2); expect(listener.calls.argsFor(0)).toEqual([ entity, "isShowing", true, false ]); expect(listener.calls.argsFor(1)).toEqual([entity, "show", true, false]); expect(entity.isShowing).toBe(true); listener.calls.reset(); entity.show = false; expect(listener.calls.count()).toBe(2); expect(listener.calls.argsFor(0)).toEqual([ entity, "isShowing", false, true ]); expect(listener.calls.argsFor(1)).toEqual([entity, "show", false, true]); expect(entity.isShowing).toBe(false); }); function ancestorShowTest(entity, ancestor) { const listener = jasmine.createSpy("listener"); entity.definitionChanged.addEventListener(listener); ancestor.show = false; expect(listener.calls.count()).toBe(1); expect(listener.calls.argsFor(0)).toEqual([ entity, "isShowing", false, true ]); expect(entity.show).toBe(true); expect(entity.isShowing).toBe(false); listener.calls.reset(); entity.show = false; expect(entity.show).toBe(false); expect(listener.calls.count()).toBe(1); expect(listener.calls.argsFor(0)).toEqual([entity, "show", false, true]); listener.calls.reset(); ancestor.show = true; expect(entity.show).toBe(false); expect(entity.isShowing).toBe(false); expect(listener.calls.count()).toBe(0); listener.calls.reset(); entity.show = true; expect(listener.calls.count()).toBe(2); expect(listener.calls.argsFor(0)).toEqual([ entity, "isShowing", true, false ]); expect(listener.calls.argsFor(1)).toEqual([entity, "show", true, false]); expect(entity.show).toBe(true); expect(entity.isShowing).toBe(true); } it("isShowing works with parent.", function() { const parent = new import__67.Entity(); const entity = new import__67.Entity(); entity.parent = parent; ancestorShowTest(entity, parent); }); it("isShowing works with grandparent.", function() { const grandparent = new import__67.Entity(); const parent = new import__67.Entity(); parent.parent = grandparent; const entity = new import__67.Entity(); entity.parent = parent; ancestorShowTest(entity, grandparent); }); it("isShowing works when replacing parent.", function() { const entity = new import__67.Entity(); entity.parent = new import__67.Entity(); const listener = jasmine.createSpy("listener"); entity.definitionChanged.addEventListener(listener); entity.parent = new import__67.Entity({ show: false }); expect(listener.calls.count()).toBe(2); expect(listener.calls.argsFor(0)).toEqual([ entity, "isShowing", false, true ]); expect(entity.show).toBe(true); expect(entity.isShowing).toBe(false); }); it("isShowing works when removing parent.", function() { const entity = new import__67.Entity(); entity.parent = new import__67.Entity({ show: false }); expect(entity.isShowing).toBe(false); const listener = jasmine.createSpy("listener"); entity.definitionChanged.addEventListener(listener); entity.parent = void 0; expect(listener.calls.count()).toBe(2); expect(listener.calls.argsFor(0)).toEqual([ entity, "isShowing", true, false ]); expect(entity.isShowing).toBe(true); }); }); // packages/engine/Specs/DataSources/EntityViewSpec.js var import__68 = __toESM(require_Cesium(), 1); describe( "DataSources/EntityView", function() { let scene2; const defaultOffset = import__68.EntityView.defaultOffset3D; beforeAll(function() { scene2 = createScene_default(); }); beforeEach(function() { import__68.EntityView.defaultOffset3D = defaultOffset.clone(); }); afterAll(function() { scene2.destroyForSpecs(); }); it("throws when constructed without required values", function() { const entity = new import__68.Entity(); let view; expect(function() { view = new import__68.EntityView(void 0, scene2); }).toThrowDeveloperError(); expect(function() { view = new import__68.EntityView(entity, void 0); }).toThrowDeveloperError(); view = new import__68.EntityView(entity, scene2); expect(view.ellipsoid).toBe(import__68.Ellipsoid.WGS84); }); it("constructor sets expected values", function() { const entity = new import__68.Entity(); const ellipsoid = import__68.Ellipsoid.UNIT_SPHERE; const view = new import__68.EntityView(entity, scene2, ellipsoid); expect(view.entity).toBe(entity); expect(view.scene).toBe(scene2); expect(view.ellipsoid).toBe(import__68.Ellipsoid.UNIT_SPHERE); }); it("can set and get defaultOffset3D", function() { const sampleOffset = new import__68.Cartesian3(1, 2, 3); import__68.EntityView.defaultOffset3D = sampleOffset; const entity = new import__68.Entity(); entity.position = new import__68.ConstantPositionProperty( import__68.Cartesian3.fromDegrees(0, 0) ); const view = new import__68.EntityView(entity, scene2); view.update(import__68.JulianDate.now()); expect(import__68.EntityView.defaultOffset3D).toEqualEpsilon(sampleOffset, 1e-10); expect(view.scene.camera.position).toEqualEpsilon(sampleOffset, 1e-10); }); it("uses entity viewFrom", function() { const sampleOffset = new import__68.Cartesian3(1, 2, 3); const entity = new import__68.Entity(); entity.position = new import__68.ConstantPositionProperty( import__68.Cartesian3.fromDegrees(0, 0) ); entity.viewFrom = sampleOffset; const view = new import__68.EntityView(entity, scene2); view.update(import__68.JulianDate.now()); expect(view.scene.camera.position).toEqualEpsilon(sampleOffset, 1e-10); }); it("uses entity bounding sphere", function() { const sampleOffset = new import__68.Cartesian3( -13322676295501878e-31, -7.348469228349534, 7.3484692283495345 ); const entity = new import__68.Entity(); entity.position = new import__68.ConstantPositionProperty( import__68.Cartesian3.fromDegrees(0, 0) ); const view = new import__68.EntityView(entity, scene2, void 0); view.update( import__68.JulianDate.now(), new import__68.BoundingSphere(new import__68.Cartesian3(3, 4, 5), 6) ); expect(view.scene.camera.position).toEqualEpsilon(sampleOffset, 1e-10); }); it("uses entity viewFrom if available and boundingsphere is supplied", function() { const sampleOffset = new import__68.Cartesian3(1, 2, 3); const entity = new import__68.Entity(); entity.position = new import__68.ConstantPositionProperty( import__68.Cartesian3.fromDegrees(0, 0) ); entity.viewFrom = sampleOffset; const view = new import__68.EntityView( entity, scene2, void 0, new import__68.BoundingSphere(new import__68.Cartesian3(3, 4, 5), 6) ); view.update(import__68.JulianDate.now()); expect(view.scene.camera.position).toEqualEpsilon(sampleOffset, 1e-10); }); it("update throws without time parameter", function() { const entity = new import__68.Entity(); entity.position = new import__68.ConstantPositionProperty(import__68.Cartesian3.ZERO); const view = new import__68.EntityView(entity, scene2); expect(function() { view.update(void 0); }).toThrowDeveloperError(); }); it("update returns without entity.position property.", function() { const entity = new import__68.Entity(); const view = new import__68.EntityView(entity, scene2); view.update(import__68.JulianDate.now()); }); }, "WebGL" ); // packages/engine/Specs/DataSources/GeoJsonDataSourceSpec.js var import__69 = __toESM(require_Cesium(), 1); describe("DataSources/GeoJsonDataSource", function() { let defaultMarkerSize; let defaultSymbol; let defaultMarkerColor; let defaultStroke; let defaultStrokeWidth; let defaultFill; let defaultClampToGround; beforeAll(function() { defaultMarkerSize = import__69.GeoJsonDataSource.markerSize; defaultSymbol = import__69.GeoJsonDataSource.markerSymbol; defaultMarkerColor = import__69.GeoJsonDataSource.markerColor; defaultStroke = import__69.GeoJsonDataSource.stroke; defaultStrokeWidth = import__69.GeoJsonDataSource.strokeWidth; defaultFill = import__69.GeoJsonDataSource.fill; defaultClampToGround = import__69.GeoJsonDataSource.clampToGround; }); beforeEach(function() { import__69.GeoJsonDataSource.markerSize = defaultMarkerSize; import__69.GeoJsonDataSource.markerSymbol = defaultSymbol; import__69.GeoJsonDataSource.markerColor = defaultMarkerColor; import__69.GeoJsonDataSource.stroke = defaultStroke; import__69.GeoJsonDataSource.strokeWidth = defaultStrokeWidth; import__69.GeoJsonDataSource.fill = defaultFill; import__69.GeoJsonDataSource.clampToGround = defaultClampToGround; }); const time2 = new import__69.JulianDate(); function coordinatesToCartesian(coordinates) { return import__69.Cartesian3.fromDegrees( coordinates[0], coordinates[1], coordinates[2] ); } function coordinatesArrayToCartesian(coordinates) { const result = []; for (let i = 0; i < coordinates.length; i++) { result.push(coordinatesToCartesian(coordinates[i])); } return result; } function multiLineToCartesian(geometry) { const coordinates = geometry.coordinates; const result = []; for (let i = 0; i < coordinates.length; i++) { result.push(coordinatesArrayToCartesian(coordinates[i])); } return result; } function polygonCoordinatesToCartesian(coordinates) { return coordinatesArrayToCartesian(coordinates); } function multiPolygonCoordinatesToCartesian(coordinates) { const result = []; for (let i = 0; i < coordinates.length; i++) { result.push(coordinatesArrayToCartesian(coordinates[i][0])); } return result; } const point = { type: "Point", coordinates: [102, 0.5] }; const pointNamedCrs = { type: "Point", coordinates: [102, 0.5], crs: { type: "name", properties: { name: "EPSG:4326" } } }; const pointNamedCrsOgc = { type: "Point", coordinates: [102, 0.5], crs: { type: "name", properties: { name: "urn:ogc:def:crs:OGC:1.3:CRS84" } } }; const pointNamedCrsEpsg = { type: "Point", coordinates: [102, 0.5], crs: { type: "name", properties: { name: "urn:ogc:def:crs:EPSG::4326" } } }; const pointCrsLinkHref = { type: "Point", coordinates: [102, 0.5], crs: { type: "link", properties: { href: "http://crs.invalid" } } }; const pointCrsEpsg = { type: "Point", coordinates: [102, 0.5], crs: { type: "EPSG", properties: { code: 4326 } } }; const lineString = { type: "LineString", coordinates: [ [100, 0], [101, 1] ] }; const polygon = { type: "Polygon", coordinates: [ [ [100, 0], [101, 0], [101, 1], [100, 1], [100, 0] ] ] }; const polygonWithHoles = { type: "Polygon", coordinates: [ [ [100, 0], [101, 0], [101, 1], [100, 1], [100, 0] ], [ [100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ] ] }; const polygonWithHeights = { type: "Polygon", coordinates: [ [ [100, 0, 1], [101, 0, 2], [101, 1, 1], [100, 1, 2], [100, 0, 3] ] ] }; const multiPoint = { type: "MultiPoint", coordinates: [ [100, 0], [101, 1], [101, 3] ] }; const multiLineString = { type: "MultiLineString", coordinates: [ [ [100, 0], [101, 1] ], [ [102, 2], [103, 3] ] ] }; const multiPolygon = { type: "MultiPolygon", coordinates: [ [ [ [102, 2], [103, 2], [103, 3], [102, 3], [102, 2] ] ], [ [ [100, 0], [101, 0], [101, 1], [100, 1], [100, 0] ] ] ] }; const geometryCollection = { type: "GeometryCollection", geometries: [ { type: "Point", coordinates: [100, 0] }, { type: "LineString", coordinates: [ [101, 0], [102, 1] ] } ] }; const feature = { type: "Feature", geometry: point }; const featureWithNullName = { type: "Feature", geometry: point, properties: { name: null } }; const featureWithId = { id: "myId", type: "Feature", geometry: geometryCollection }; const featureUndefinedGeometry = { type: "Feature" }; const featureNullGeometry = { type: "Feature", geometry: null }; const unknownGeometry = { type: "TimeyWimey", coordinates: [0, 0] }; const featureUnknownGeometry = { type: "Feature", geometry: unknownGeometry }; const geometryCollectionUnknownType = { type: "GeometryCollection", geometries: [unknownGeometry] }; const topoJson = { type: "Topology", transform: { scale: [1, 1], translate: [0, 0] }, objects: { polygon: { type: "Polygon", arcs: [[0, 1, 2, 3]], properties: { myProps: 0 } }, lineString: { type: "LineString", arcs: [4], properties: { myProps: 1 } } }, arcs: [ [ [0, 0], [1, 0], [0, 1], [-1, 0], [0, -1] ], [ [0, 0], [1, 0], [0, 1] ], [ [1, 1], [-1, 0], [0, -1] ], [[1, 1]], [[0, 0]] ] }; const mixedGeometries = { type: "GeometryCollection", geometries: [lineString, polygon, point] }; it("default constructor has expected values", function() { const dataSource = new import__69.GeoJsonDataSource(); expect(dataSource.changedEvent).toBeInstanceOf(import__69.Event); expect(dataSource.errorEvent).toBeInstanceOf(import__69.Event); expect(dataSource.clock).toBeUndefined(); expect(dataSource.name).toBeUndefined(); expect(dataSource.entities).toBeInstanceOf(import__69.EntityCollection); expect(dataSource.entities.values.length).toEqual(0); expect(dataSource.show).toBe(true); expect(dataSource.credit).toBeUndefined(); }); it("credit gets set from options", function() { return import__69.GeoJsonDataSource.load(point, { credit: "This is my credit" }).then(function(dataSource) { expect(dataSource.credit).toBeInstanceOf(import__69.Credit); }); }); it("setting name raises changed event", function() { const dataSource = new import__69.GeoJsonDataSource(); const spy = jasmine.createSpy("changedEvent"); dataSource.changedEvent.addEventListener(spy); const newName = "chester"; dataSource.name = newName; expect(dataSource.name).toEqual(newName); expect(spy.calls.count()).toEqual(1); expect(spy).toHaveBeenCalledWith(dataSource); }); it("show sets underlying entity collection show.", function() { const dataSource = new import__69.GeoJsonDataSource(); dataSource.show = false; expect(dataSource.show).toBe(false); expect(dataSource.show).toEqual(dataSource.entities.show); dataSource.show = true; expect(dataSource.show).toBe(true); expect(dataSource.show).toEqual(dataSource.entities.show); }); it("Works with null geometry", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(featureNullGeometry).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.properties).toBe(featureNullGeometry.properties); expect(entity.position).toBeUndefined(); }); }); it("Works with feature", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(feature).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.properties).toBe(feature.properties); expect(entity.position.getValue(time2)).toEqual( coordinatesToCartesian(feature.geometry.coordinates) ); expect(entity.billboard).toBeDefined(); }); }); it("Adds a feature without removing existing entities", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(feature).then(function() { return dataSource.process(mixedGeometries).then(function() { expect(dataSource.entities.values.length).toBe(4); }); }); }); it("Creates default description from properties", function() { const featureWithProperties = { type: "Feature", geometry: point, properties: { prop1: "dog", prop2: "cat", prop3: "liger" } }; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(featureWithProperties).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.description).toBeDefined(); const description = entity.description.getValue(time2); expect(description).toContain("prop1"); expect(description).toContain("prop2"); expect(description).toContain("prop3"); expect(description).toContain("dog"); expect(description).toContain("cat"); expect(description).toContain("liger"); }); }); it("Creates custom description string from properties", function() { const featureWithProperties = { type: "Feature", geometry: point, properties: { prop1: "dog", prop2: "cat" } }; function testDescribe(properties) { let desc = ""; for (const key in properties) { if (properties.hasOwnProperty(key)) { const value = properties[key]; desc += `${key} = ${value}. `; } } return desc; } const dataSource = new import__69.GeoJsonDataSource(); const options = { describe: testDescribe }; return dataSource.load(featureWithProperties, options).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.description).toBeDefined(); const description = entity.description.getValue(time2); expect(description).toContain("prop1 = dog."); expect(description).toContain("prop2 = cat."); }); }); it("Creates custom description from properties, using a describeProperty", function() { const featureWithProperties = { type: "Feature", geometry: point, properties: { prop1: "dog", prop2: "cat" } }; function testDescribe(properties) { let desc = ""; for (const key in properties) { if (properties.hasOwnProperty(key)) { const value = properties[key]; desc += `${key} = ${value}; `; } } return desc; } function createDescriptionCallback(describe2, properties, nameProperty) { let description; return function(time3, result) { if (!description) { description = describe2(properties, nameProperty); } return description; }; } function testDescribeProperty(properties, nameProperty) { return new import__69.CallbackProperty( createDescriptionCallback(testDescribe, properties, nameProperty), true ); } const dataSource = new import__69.GeoJsonDataSource(); const options = { describe: testDescribeProperty }; return dataSource.load(featureWithProperties, options).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.description).toBeDefined(); const description = entity.description.getValue(time2); expect(description).toContain("prop1 = dog;"); expect(description).toContain("prop2 = cat;"); }); }); it("Uses description if present", function() { const featureWithDescription = { type: "Feature", geometry: point, properties: { prop1: "dog", prop2: "cat", prop3: "liger", description: "This is my descriptiong!" } }; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(featureWithDescription).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.description).toBeDefined(); expect(entity.description.getValue(time2)).toEqual( featureWithDescription.properties.description ); }); }); it("Handles null description", function() { const featureWithNullDescription = { type: "Feature", geometry: point, properties: { description: null } }; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(featureWithNullDescription).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.description).toBeUndefined(); }); }); it(`Does not use "name" property as the object's name if it is null`, function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(featureWithNullName).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.name).toBeUndefined(); expect(entity.properties.name.getValue()).toBe( featureWithNullName.properties.name ); expect(entity.properties.getValue(time2)).toEqual( featureWithNullName.properties ); expect(entity.position.getValue(time2)).toEqual( coordinatesToCartesian(featureWithNullName.geometry.coordinates) ); expect(entity.billboard).toBeDefined(); }); }); it("Works with feature with id", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(featureWithId).then(function() { const entityCollection = dataSource.entities; let entity = entityCollection.values[0]; expect(entity.id).toEqual(featureWithId.id); entity = entityCollection.values[1]; expect(entity.id).toEqual(`${featureWithId.id}_2`); }); }); it("Works with null id", function() { const geojson = { id: null, type: "Feature", geometry: null }; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(geojson).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.id).not.toEqual(null); }); }); it("Works with null properties", function() { const geojson = { type: "Feature", geometry: null, properties: null }; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(geojson).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.properties).toBeUndefined(); }); }); it("Has entity collection with link to data source", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(featureWithId).then(function() { const entityCollection = dataSource.entities; expect(entityCollection.owner).toEqual(dataSource); }); }); it("Has entity with link to entity collection", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(featureWithId).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.entityCollection).toEqual(entityCollection); }); }); it("Works with point geometry", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(point).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.properties).toBe(point.properties); expect(entity.position.getValue(time2)).toEqual( coordinatesToCartesian(point.coordinates) ); expect(entity.billboard).toBeDefined(); expect(entity.billboard.image).toBeDefined(); }); }); it("Works with point geometry clamped to ground", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(point, { clampToGround: true }).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.properties).toBe(point.properties); expect(entity.position.getValue(time2)).toEqual( coordinatesToCartesian(point.coordinates) ); expect(entity.billboard).toBeDefined(); expect(entity.billboard.image).toBeDefined(); expect(entity.billboard.heightReference.getValue(time2)).toBe( import__69.HeightReference.CLAMP_TO_GROUND ); }); }); it("Works with point geometry with simplystyle", function() { const geojson = { type: "Point", coordinates: [102, 0.5], properties: { "marker-size": "large", "marker-symbol": "bus", "marker-color": "#ffffff" } }; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(geojson).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.billboard).toBeDefined(); return Promise.resolve( dataSource._pinBuilder.fromMakiIconId("bus", import__69.Color.WHITE, 64) ).then(function(image) { expect(entity.billboard.image.getValue()).toBe(image); }); }); }); it("Works with point geometry with null simplystyle", function() { const geojson = { type: "Point", coordinates: [102, 0.5], properties: { "marker-size": null, "marker-symbol": null, "marker-color": null } }; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(geojson).then(function() { const image = dataSource._pinBuilder.fromColor( import__69.GeoJsonDataSource.markerColor, import__69.GeoJsonDataSource.markerSize ); const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.billboard).toBeDefined(); expect(entity.billboard.image.getValue()).toBe(image); }); }); it("Works with point geometry and unknown simplystyle", function() { const geojson = { type: "Point", coordinates: [102, 0.5], properties: { "marker-size": "large", "marker-symbol": "notAnIcon", "marker-color": "#ffffff" } }; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(geojson).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.billboard).toBeDefined(); return Promise.resolve( dataSource._pinBuilder.fromColor(import__69.Color.WHITE, 64) ).then(function(image) { expect(entity.billboard.image.getValue()).toBe(image); }); }); }); it("Works with multipoint geometry", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(multiPoint).then(function() { const entityCollection = dataSource.entities; const entities = entityCollection.values; const expectedPositions = coordinatesArrayToCartesian( multiPoint.coordinates ); for (let i = 0; i < multiPoint.coordinates.length; i++) { const entity = entities[i]; expect(entity.properties).toBe(multiPoint.properties); expect(entity.position.getValue(time2)).toEqual(expectedPositions[i]); expect(entity.billboard).toBeDefined(); expect(entity.billboard.image).toBeDefined(); } }); }); it("Works with multipoint geometry clamped to ground", function() { import__69.GeoJsonDataSource.clampToGround = true; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(multiPoint).then(function() { const entityCollection = dataSource.entities; const entities = entityCollection.values; const expectedPositions = coordinatesArrayToCartesian( multiPoint.coordinates ); for (let i = 0; i < multiPoint.coordinates.length; i++) { const entity = entities[i]; expect(entity.properties).toBe(multiPoint.properties); expect(entity.position.getValue(time2)).toEqual(expectedPositions[i]); expect(entity.billboard).toBeDefined(); expect(entity.billboard.image).toBeDefined(); expect(entity.billboard.heightReference.getValue()).toBe( import__69.HeightReference.CLAMP_TO_GROUND ); } }); }); it("Works with lineString geometry", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(lineString).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.properties).toBe(lineString.properties); expect(entity.polyline.positions.getValue(time2)).toEqual( coordinatesArrayToCartesian(lineString.coordinates) ); expect(entity.polyline.material.color.getValue(time2)).toEqual( import__69.GeoJsonDataSource.stroke ); expect(entity.polyline.width.getValue(time2)).toEqual(2); }); }); it("Works with lineString geometry clamped to ground", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(lineString, { clampToGround: true }).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.properties).toBe(lineString.properties); expect(entity.polyline.positions.getValue(time2)).toEqual( coordinatesArrayToCartesian(lineString.coordinates) ); expect(entity.polyline.material.color.getValue(time2)).toEqual( import__69.GeoJsonDataSource.stroke ); expect(entity.polyline.width.getValue(time2)).toEqual(2); expect(entity.polyline.clampToGround.getValue(time2)).toEqual(true); }); }); it("Works with multiLineString geometry", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(multiLineString).then(function() { const entityCollection = dataSource.entities; const entities = entityCollection.values; const lines = multiLineToCartesian(multiLineString); for (let i = 0; i < multiLineString.coordinates.length; i++) { const entity = entities[i]; expect(entity.properties).toBe(multiLineString.properties); expect(entity.polyline.positions.getValue(time2)).toEqual(lines[i]); expect(entity.polyline.material.color.getValue(time2)).toEqual( import__69.Color.YELLOW ); expect(entity.polyline.width.getValue(time2)).toEqual(2); } }); }); it("Works with multiLineString geometry clamped to ground", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(multiLineString, { clampToGround: true }).then(function() { const entityCollection = dataSource.entities; const entities = entityCollection.values; const lines = multiLineToCartesian(multiLineString); for (let i = 0; i < multiLineString.coordinates.length; i++) { const entity = entities[i]; expect(entity.properties).toBe(multiLineString.properties); expect(entity.polyline.positions.getValue(time2)).toEqual(lines[i]); expect(entity.polyline.material.color.getValue(time2)).toEqual( import__69.Color.YELLOW ); expect(entity.polyline.width.getValue(time2)).toEqual(2); expect(entity.polyline.clampToGround.getValue(time2)).toEqual(true); } }); }); it("Works with polygon geometry", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(polygon).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.properties).toBe(polygon.properties); expect(entity.polygon.hierarchy.getValue(time2)).toEqual( new import__69.PolygonHierarchy( polygonCoordinatesToCartesian(polygon.coordinates[0]) ) ); expect(entity.polygon.perPositionHeight).toBeUndefined(); expect(entity.polygon.material.color.getValue(time2)).toEqual( import__69.GeoJsonDataSource.fill ); expect(entity.polygon.outline.getValue(time2)).toEqual(true); expect(entity.polygon.outlineWidth.getValue(time2)).toEqual( import__69.GeoJsonDataSource.strokeWidth ); expect(entity.polygon.outlineColor.getValue(time2)).toEqual( import__69.GeoJsonDataSource.stroke ); expect(entity.polygon.height).toBeInstanceOf(import__69.ConstantProperty); }); }); it("Works with polygon geometry clamped to ground", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(polygon, { clampToGround: true }).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.properties).toBe(polygon.properties); expect(entity.polygon.hierarchy.getValue(time2)).toEqual( new import__69.PolygonHierarchy( polygonCoordinatesToCartesian(polygon.coordinates[0]) ) ); expect(entity.polygon.perPositionHeight).toBeUndefined(); expect(entity.polygon.material.color.getValue(time2)).toEqual( import__69.GeoJsonDataSource.fill ); expect(entity.polygon.outline.getValue(time2)).toEqual(true); expect(entity.polygon.outlineWidth.getValue(time2)).toEqual( import__69.GeoJsonDataSource.strokeWidth ); expect(entity.polygon.outlineColor.getValue(time2)).toEqual( import__69.GeoJsonDataSource.stroke ); expect(entity.polygon.height).toBeUndefined(); }); }); it("Works with polygon geometry with Heights", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(polygonWithHeights).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.properties).toBe(polygonWithHeights.properties); expect(entity.polygon.hierarchy.getValue(time2)).toEqual( new import__69.PolygonHierarchy( polygonCoordinatesToCartesian(polygonWithHeights.coordinates[0]) ) ); expect(entity.polygon.perPositionHeight.getValue(time2)).toBe(true); expect(entity.polygon.material.color.getValue(time2)).toEqual( import__69.GeoJsonDataSource.fill ); expect(entity.polygon.outline.getValue(time2)).toEqual(true); expect(entity.polygon.outlineWidth.getValue(time2)).toEqual( import__69.GeoJsonDataSource.strokeWidth ); expect(entity.polygon.outlineColor.getValue(time2)).toEqual( import__69.GeoJsonDataSource.stroke ); }); }); it("Works with polygon geometry with holes", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(polygonWithHoles).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.properties).toBe(polygonWithHoles.properties); expect(entity.polygon.hierarchy.getValue(time2)).toEqual( new import__69.PolygonHierarchy( polygonCoordinatesToCartesian(polygonWithHoles.coordinates[0]), [ new import__69.PolygonHierarchy( polygonCoordinatesToCartesian(polygonWithHoles.coordinates[1]) ) ] ) ); }); }); it("Works with multiPolygon geometry", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(multiPolygon).then(function() { const entityCollection = dataSource.entities; const entities = entityCollection.values; const positions = multiPolygonCoordinatesToCartesian( multiPolygon.coordinates ); for (let i = 0; i < multiPolygon.coordinates.length; i++) { const entity = entities[i]; expect(entity.properties).toBe(multiPolygon.properties); expect(entity.polygon.hierarchy.getValue(time2)).toEqual( new import__69.PolygonHierarchy(positions[i]) ); } }); }); it("Works with topojson geometry", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(topoJson).then(function() { const entityCollection = dataSource.entities; const entities = entityCollection.values; const polygon2 = entities[0]; expect(polygon2.properties.myProps.getValue()).toBe( topoJson.objects.polygon.properties.myProps ); expect(polygon2.properties.getValue(time2)).toEqual( topoJson.objects.polygon.properties ); expect(polygon2.polygon.hierarchy).toBeDefined(); const lineString2 = entities[1]; expect(lineString2.properties.myProps.getValue()).toBe( topoJson.objects.lineString.properties.myProps ); expect(lineString2.properties.getValue(time2)).toEqual( topoJson.objects.lineString.properties ); expect(lineString2.polyline).toBeDefined(); }); }); it("Can provide base styling options", function() { const options = { markerSize: 10, markerSymbol: "bus", markerColor: import__69.Color.GREEN, stroke: import__69.Color.ORANGE, strokeWidth: 8, fill: import__69.Color.RED }; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(mixedGeometries, options).then(function() { const entityCollection = dataSource.entities; const entities = entityCollection.values; let entity = entities[0]; expect(entity.polyline.material.color.getValue()).toEqual(options.stroke); expect(entity.polyline.width.getValue()).toEqual(options.strokeWidth); entity = entities[1]; expect(entity.polygon.material.color.getValue()).toEqual(options.fill); expect(entity.polygon.outlineColor.getValue()).toEqual(options.stroke); expect(entity.polygon.outlineWidth.getValue()).toEqual( options.strokeWidth ); entity = entities[2]; const expectedImage = dataSource._pinBuilder.fromMakiIconId( options.markerSymbol, options.markerColor, options.markerSize ); expect(entity.billboard.image.getValue()).toEqual(expectedImage); }); }); it("Can set default graphics", function() { import__69.GeoJsonDataSource.markerSize = 10; import__69.GeoJsonDataSource.markerSymbol = "bus"; import__69.GeoJsonDataSource.markerColor = import__69.Color.GREEN; import__69.GeoJsonDataSource.stroke = import__69.Color.ORANGE; import__69.GeoJsonDataSource.strokeWidth = 8; import__69.GeoJsonDataSource.fill = import__69.Color.RED; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(mixedGeometries).then(function() { const entityCollection = dataSource.entities; const entities = entityCollection.values; let entity = entities[0]; expect(entity.polyline.material.color.getValue()).toEqual( import__69.GeoJsonDataSource.stroke ); expect(entity.polyline.width.getValue()).toEqual( import__69.GeoJsonDataSource.strokeWidth ); entity = entities[1]; expect(entity.polygon.material.color.getValue()).toEqual( import__69.GeoJsonDataSource.fill ); expect(entity.polygon.outlineColor.getValue()).toEqual( import__69.GeoJsonDataSource.stroke ); expect(entity.polygon.outlineWidth.getValue()).toEqual( import__69.GeoJsonDataSource.strokeWidth ); entity = entities[2]; const expectedImage = dataSource._pinBuilder.fromMakiIconId( import__69.GeoJsonDataSource.markerSymbol, import__69.GeoJsonDataSource.markerColor, import__69.GeoJsonDataSource.markerSize ); expect(entity.billboard.image.getValue()).toEqual(expectedImage); }); }); it("Generates description", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(topoJson).then(function() { const entityCollection = dataSource.entities; const entities = entityCollection.values; const polygon2 = entities[0]; expect(polygon2.description).toBeDefined(); }); }); it("Works with geometrycollection", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(geometryCollection).then(function() { const entityCollection = dataSource.entities; let entity = entityCollection.values[0]; expect(entity.properties).toBe(geometryCollection.properties); expect(entity.position.getValue(time2)).toEqual( coordinatesToCartesian(geometryCollection.geometries[0].coordinates) ); expect(entity.billboard).toBeDefined(); entity = entityCollection.values[1]; expect(entity.properties).toBe(geometryCollection.properties); expect(entity.polyline.positions.getValue(time2)).toEqual( coordinatesArrayToCartesian( geometryCollection.geometries[1].coordinates ) ); }); }); it("Works with named crs", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(pointNamedCrs).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.position.getValue(time2)).toEqual( coordinatesToCartesian(point.coordinates) ); }); }); it("Works with named crs OGC:1.3:CRS84", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(pointNamedCrsOgc).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.position.getValue(time2)).toEqual( coordinatesToCartesian(point.coordinates) ); }); }); it("Works with named crs EPSG::4326", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(pointNamedCrsEpsg).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.position.getValue(time2)).toEqual( coordinatesToCartesian(point.coordinates) ); }); }); it("Works with link crs href", function() { const projectedPosition = new import__69.Cartesian3(1, 2, 3); import__69.GeoJsonDataSource.crsLinkHrefs[pointCrsLinkHref.crs.properties.href] = function(properties) { expect(properties).toBe(pointCrsLinkHref.crs.properties); return Promise.resolve(properties.href).then(function(href) { return function(coordinate) { expect(coordinate).toBe(pointCrsLinkHref.coordinates); return projectedPosition; }; }); }; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(pointCrsLinkHref).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.position.getValue(time2)).toEqual(projectedPosition); }); }); it("Works with EPSG crs", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(pointCrsEpsg).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.position.getValue(time2)).toEqual( coordinatesToCartesian(point.coordinates) ); }); }); it("Works with polyline using simplestyle", function() { const geoJson = { type: "Feature", geometry: { type: "LineString", coordinates: [ [100, 0], [101, 1] ] }, properties: { title: "textMarker", description: "My description", stroke: "#aabbcc", "stroke-opacity": 0.5, "stroke-width": 5 } }; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(geoJson).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.name).toEqual(geoJson.properties.title); expect(entity.description.getValue(time2)).toEqual( geoJson.properties.description ); const expectedColor = import__69.Color.fromCssColorString(geoJson.properties.stroke); expectedColor.alpha = geoJson.properties["stroke-opacity"]; expect(entity.polyline.material.color.getValue(time2)).toEqual( expectedColor ); expect(entity.polyline.width.getValue(time2)).toEqual( geoJson.properties["stroke-width"] ); }); }); it("Works with polyline using null simplestyle values", function() { const geoJson = { type: "Feature", geometry: { type: "LineString", coordinates: [ [100, 0], [101, 1] ] }, properties: { title: null, description: null, stroke: null, "stroke-opacity": null, "stroke-width": null } }; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(geoJson).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.name).toBeUndefined(); expect(entity.description).toBeUndefined(); expect(entity.polyline.material.color.getValue(time2)).toEqual( import__69.GeoJsonDataSource.stroke ); expect(entity.polyline.width.getValue(time2)).toEqual( import__69.GeoJsonDataSource.strokeWidth ); }); }); it("Works with polyline using null simplestyle values but with opacity", function() { const geoJson = { type: "Feature", geometry: { type: "LineString", coordinates: [ [100, 0], [101, 1] ] }, properties: { title: null, description: null, stroke: null, "stroke-opacity": 0.42, "stroke-width": null } }; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(geoJson).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.name).toBeUndefined(); expect(entity.description).toBeUndefined(); const expectedMaterialColor = import__69.GeoJsonDataSource.stroke.clone(); expectedMaterialColor.alpha = 0.42; expect(entity.polyline.material.color.getValue(time2)).toEqual( expectedMaterialColor ); expect(entity.polyline.width.getValue(time2)).toEqual( import__69.GeoJsonDataSource.strokeWidth ); }); }); it("Works with polygon using simplestyle", function() { const geoJson = { type: "Feature", geometry: { type: "Polygon", coordinates: [ [ [100, 0], [101, 0], [101, 1], [100, 1], [100, 0] ] ] }, properties: { title: "textMarker", description: "My description", stroke: "#aabbcc", "stroke-opacity": 0.5, "stroke-width": 5, fill: "#ccaabb", "fill-opacity": 0.25 } }; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(geoJson).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.name).toEqual(geoJson.properties.title); expect(entity.description.getValue(time2)).toEqual( geoJson.properties.description ); const expectedFill = import__69.Color.fromCssColorString(geoJson.properties.fill); expectedFill.alpha = geoJson.properties["fill-opacity"]; const expectedOutlineColor = import__69.Color.fromCssColorString( geoJson.properties.stroke ); expectedOutlineColor.alpha = geoJson.properties["stroke-opacity"]; expect(entity.polygon.material.color.getValue(time2)).toEqual( expectedFill ); expect(entity.polygon.outline.getValue(time2)).toEqual(true); expect(entity.polygon.outlineWidth.getValue(time2)).toEqual(5); expect(entity.polygon.outlineColor.getValue(time2)).toEqual( expectedOutlineColor ); }); }); it("Works with polygon using null simplestyle", function() { const geoJson = { type: "Feature", geometry: { type: "Polygon", coordinates: [ [ [100, 0], [101, 0], [101, 1], [100, 1], [100, 0] ] ] }, properties: { title: null, description: null, stroke: null, "stroke-opacity": null, "stroke-width": null, fill: null, "fill-opacity": null } }; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(geoJson).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.name).toBeUndefined(); expect(entity.description).toBeUndefined(); expect(entity.polygon.material.color.getValue(time2)).toEqual( import__69.GeoJsonDataSource.fill ); expect(entity.polygon.outline.getValue(time2)).toEqual(true); expect(entity.polygon.outlineWidth.getValue(time2)).toEqual( import__69.GeoJsonDataSource.strokeWidth ); expect(entity.polygon.outlineColor.getValue(time2)).toEqual( import__69.GeoJsonDataSource.stroke ); }); }); it("Works with polygons using null simplestyle but with an opacity", function() { const geoJson = { type: "Feature", geometry: { type: "Polygon", coordinates: [ [ [100, 0], [101, 0], [101, 1], [100, 1], [100, 0] ] ] }, properties: { title: null, description: null, stroke: null, "stroke-opacity": 0.42, "stroke-width": null, fill: null, "fill-opacity": 0.42 } }; const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(geoJson).then(function() { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.name).toBeUndefined(); expect(entity.description).toBeUndefined(); const expectedFill = import__69.GeoJsonDataSource.fill.clone(); expectedFill.alpha = geoJson.properties["fill-opacity"]; expect(entity.polygon.material.color.getValue(time2)).toEqual( expectedFill ); const expectedOutlineColor = import__69.GeoJsonDataSource.stroke.clone(); expectedOutlineColor.alpha = 0.42; expect(entity.polygon.outline.getValue(time2)).toEqual(true); expect(entity.polygon.outlineWidth.getValue(time2)).toEqual( import__69.GeoJsonDataSource.strokeWidth ); expect(entity.polygon.outlineColor.getValue(time2)).toEqual( expectedOutlineColor ); }); }); it("load works with a URL", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load("Data/test.geojson").then(function() { expect(dataSource.name).toEqual("test.geojson"); }); }); it("Fails when encountering unknown geometry", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(featureUnknownGeometry).then(function() { fail("should not be called"); }).catch(function() { }); }); it("Fails with undefined geometry", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(featureUndefinedGeometry).then(function() { fail("should not be called"); }).catch(function() { }); }); it("Fails with unknown geomeetry in geometryCollection", function() { const dataSource = new import__69.GeoJsonDataSource(); return dataSource.load(geometryCollectionUnknownType).then(function() { fail("should not be called"); }).catch(function() { }); }); it("load throws with undefined geoJson", function() { const dataSource = new import__69.GeoJsonDataSource(); expect(function() { dataSource.load(void 0); }).toThrowDeveloperError(); }); it("rejects unknown geometry", function() { return import__69.GeoJsonDataSource.load(unknownGeometry).then(function() { fail("should not be called"); }).catch(function(error) { expect(error).toBeInstanceOf(import__69.RuntimeError); expect(error.message).toContain( "Unsupported GeoJSON object type: TimeyWimey" ); }); }); it("rejects invalid url", function() { return import__69.GeoJsonDataSource.load("invalid.geojson").then(function() { fail("should not be called"); }).catch(function(error) { expect(error.statusCode).toBe(404); }); }); it("rejects null CRS", function() { const featureWithNullCrs = { type: "Feature", geometry: point, crs: null }; return import__69.GeoJsonDataSource.load(featureWithNullCrs).then(function(dataSource) { expect(dataSource.entities.values.length).toBe(0); }); }); it("rejects unknown CRS", function() { const featureWithUnknownCrsType = { type: "Feature", geometry: point, crs: { type: "potato", properties: {} } }; return import__69.GeoJsonDataSource.load(featureWithUnknownCrsType).then(function() { fail("should not be called"); }).catch(function(error) { expect(error).toBeInstanceOf(import__69.RuntimeError); expect(error.message).toContain("Unknown crs type: potato"); }); }); it("rejects undefined CRS properties", function() { const featureWithUndefinedCrsProperty = { type: "Feature", geometry: point, crs: { type: "name" } }; return import__69.GeoJsonDataSource.load(featureWithUndefinedCrsProperty).then(function() { fail("should not be called"); }).catch(function(error) { expect(error).toBeInstanceOf(import__69.RuntimeError); expect(error.message).toContain("crs.properties is undefined."); }); }); it("rejects unknown CRS name", function() { const featureWithUnknownCrsType = { type: "Feature", geometry: point, crs: { type: "name", properties: { name: "failMe" } } }; return import__69.GeoJsonDataSource.load(featureWithUnknownCrsType).then(function() { fail("should not be called"); }).catch(function(error) { expect(error).toBeInstanceOf(import__69.RuntimeError); expect(error.message).toContain("Unknown crs name: failMe"); }); }); it("rejects unknown CRS link", function() { const featureWithUnknownCrsType = { type: "Feature", geometry: point, crs: { type: "link", properties: { href: "failMe", type: "failMeTwice" } } }; return import__69.GeoJsonDataSource.load(featureWithUnknownCrsType).then(function() { fail("should not be called"); }).catch(function(error) { expect(error).toBeInstanceOf(import__69.RuntimeError); expect(error.message).toContain( 'Unable to resolve crs link: {"href":"failMe","type":"failMeTwice"}' ); }); }); it("load rejects loading non json file", function() { const dataSource = new import__69.GeoJsonDataSource(); const spy = jasmine.createSpy("errorEvent"); dataSource.errorEvent.addEventListener(spy); return dataSource.load("Data/Images/Blue.png").then(function() { fail("should not be called"); }).catch(function() { expect(spy).toHaveBeenCalledWith(dataSource, jasmine.any(Error)); }); }); it("load raises loading event", function() { const dataSource = new import__69.GeoJsonDataSource(); const spy = jasmine.createSpy("loadingEvent"); dataSource.loadingEvent.addEventListener(spy); const promise = dataSource.load("Data/test.geojson"); expect(spy).toHaveBeenCalledWith(dataSource, true); expect(dataSource.isLoading).toBe(true); return promise.then(function() { expect(spy).toHaveBeenCalledWith(dataSource, false); expect(dataSource.isLoading).toBe(false); }); }); }); // packages/engine/Specs/DataSources/GeometryUpdaterSetSpec.js var import__70 = __toESM(require_Cesium(), 1); describe("GeometryUpdaterSet", () => { let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); it("has expected defaults", () => { const updaterSet = new import__70.GeometryUpdaterSet(new import__70.Entity(), scene2); expect(updaterSet.updaters.length).toEqual(10); expect(updaterSet.updaters[0]).toBeInstanceOf(import__70.BoxGeometryUpdater); expect(updaterSet.updaters[1]).toBeInstanceOf(import__70.CylinderGeometryUpdater); expect(updaterSet.updaters[2]).toBeInstanceOf(import__70.CorridorGeometryUpdater); expect(updaterSet.updaters[3]).toBeInstanceOf(import__70.EllipseGeometryUpdater); expect(updaterSet.updaters[4]).toBeInstanceOf(import__70.EllipsoidGeometryUpdater); expect(updaterSet.updaters[5]).toBeInstanceOf(import__70.PlaneGeometryUpdater); expect(updaterSet.updaters[6]).toBeInstanceOf(import__70.PolygonGeometryUpdater); expect(updaterSet.updaters[7]).toBeInstanceOf( import__70.PolylineVolumeGeometryUpdater ); expect(updaterSet.updaters[8]).toBeInstanceOf(import__70.RectangleGeometryUpdater); expect(updaterSet.updaters[9]).toBeInstanceOf(import__70.WallGeometryUpdater); }); it("registers new updater", () => { function FakeUpdater() { } FakeUpdater.prototype.geometryChanged = new import__70.Event(); import__70.GeometryUpdaterSet.registerUpdater(FakeUpdater); const updaterSet = new import__70.GeometryUpdaterSet(new import__70.Entity(), scene2); expect(updaterSet.updaters.length).toEqual(11); expect(updaterSet.updaters[10]).toBeInstanceOf(FakeUpdater); import__70.GeometryUpdaterSet.unregisterUpdater(FakeUpdater); const updaterSet2 = new import__70.GeometryUpdaterSet(new import__70.Entity(), scene2); expect(updaterSet2.updaters.length).withContext("length after unregister").toEqual(10); }); }); // packages/engine/Specs/DataSources/GeometryUpdaterSpec.js var import__71 = __toESM(require_Cesium(), 1); describe("DataSources/GeometryUpdater", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); it("Constructor throws if no Entity supplied", function() { expect(function() { return new import__71.GeometryUpdater({ entity: void 0, scene: scene2, geometryOptions: {}, geometryPropertyName: "box", observedPropertyNames: ["availability", "box"] }); }).toThrowDeveloperError(); }); it("Constructor throws if no scene supplied", function() { expect(function() { return new import__71.GeometryUpdater({ entity: new import__71.Entity(), scene: void 0, geometryOptions: {}, geometryPropertyName: "box", observedPropertyNames: ["availability", "box"] }); }).toThrowDeveloperError(); }); it("Constructor throws if no geometryOptions supplied", function() { expect(function() { return new import__71.GeometryUpdater({ entity: new import__71.Entity(), scene: scene2, geometryOptions: void 0, geometryPropertyName: "box", observedPropertyNames: ["availability", "box"] }); }).toThrowDeveloperError(); }); it("Constructor throws if no geometryPropertyName supplied", function() { expect(function() { return new import__71.GeometryUpdater({ entity: new import__71.Entity(), scene: scene2, geometryOptions: {}, geometryPropertyName: void 0, observedPropertyNames: ["availability", "box"] }); }).toThrowDeveloperError(); }); it("Constructor throws if no observedPropertyNames supplied", function() { expect(function() { return new import__71.GeometryUpdater({ entity: new import__71.Entity(), scene: scene2, geometryOptions: {}, geometryPropertyName: "box", observedPropertyNames: void 0 }); }).toThrowDeveloperError(); }); it("createDynamicUpdater throws if not dynamic", function() { const updater = new import__71.GeometryUpdater({ entity: new import__71.Entity(), scene: scene2, geometryOptions: {}, geometryPropertyName: "box", observedPropertyNames: ["availability", "box"] }); expect(function() { return updater.createDynamicUpdater( new import__71.PrimitiveCollection(), new import__71.PrimitiveCollection() ); }).toThrowDeveloperError(); }); it("createDynamicUpdater throws if primitives undefined", function() { const updater = new import__71.GeometryUpdater({ entity: new import__71.Entity(), scene: scene2, geometryOptions: {}, geometryPropertyName: "box", observedPropertyNames: ["availability", "box"] }); updater._dynamic = true; expect(function() { return updater.createDynamicUpdater(void 0, new import__71.PrimitiveCollection()); }).toThrowDeveloperError(); }); it("createDynamicUpdater throws if groundPrimitives undefined", function() { const updater = new import__71.GeometryUpdater({ entity: new import__71.Entity(), scene: scene2, geometryOptions: {}, geometryPropertyName: "box", observedPropertyNames: ["availability", "box"] }); updater._dynamic = true; expect(function() { return updater.createDynamicUpdater(new import__71.PrimitiveCollection(), void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/GeometryVisualizerSpec.js var import__72 = __toESM(require_Cesium(), 1); describe( "DataSources/GeometryVisualizer", function() { const time2 = import__72.JulianDate.now(); let scene2; beforeAll(function() { scene2 = createScene_default(); return import__72.GroundPrimitive.initializeTerrainHeights(); }); afterAll(function() { scene2.destroyForSpecs(); import__72.GroundPrimitive._initialized = false; import__72.GroundPrimitive._initPromise = void 0; import__72.ApproximateTerrainHeights._initPromise = void 0; import__72.ApproximateTerrainHeights._terrainHeights = void 0; }); function visualizerUpdated(visualizer) { return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = visualizer.update(time2); scene2.render(time2); return isUpdated; }); } function visualizerEmpty(visualizer) { return pollToPromise_default(function() { scene2.initializeFrame(); expect(visualizer.update(time2)).toBe(true); scene2.render(time2); return scene2.primitives.length === 0 && scene2.groundPrimitives.length === 0; }); } it("Can create and destroy", function() { const objects = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, objects, scene2.primitives, scene2.groundPrimitives ); expect(visualizer.update(time2)).toBe(true); expect(scene2.primitives.length).toBe(0); expect(visualizer.isDestroyed()).toBe(false); visualizer.destroy(); expect(visualizer.isDestroyed()).toBe(true); }); it("Creates and removes static color open geometry", function() { const objects = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, objects, scene2.primitives, scene2.groundPrimitives ); const ellipse = new import__72.EllipseGraphics(); ellipse.semiMajorAxis = new import__72.ConstantProperty(2); ellipse.semiMinorAxis = new import__72.ConstantProperty(1); ellipse.material = new import__72.ColorMaterialProperty(); ellipse.height = new import__72.ConstantProperty(0); const entity = new import__72.Entity(); entity.position = new import__72.ConstantPositionProperty( new import__72.Cartesian3(1234, 5678, 9101112) ); entity.ellipse = ellipse; objects.add(entity); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__72.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toEqual( import__72.ColorGeometryInstanceAttribute.toValue(import__72.Color.WHITE) ); expect(primitive.appearance).toBeInstanceOf(import__72.PerInstanceColorAppearance); expect(primitive.appearance.closed).toBe(true); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); }); it("Creates and removes static material open geometry", function() { const objects = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, objects, scene2.primitives, scene2.groundPrimitives ); const ellipse = new import__72.EllipseGraphics(); ellipse.semiMajorAxis = new import__72.ConstantProperty(2); ellipse.semiMinorAxis = new import__72.ConstantProperty(1); ellipse.material = new import__72.GridMaterialProperty(); ellipse.height = new import__72.ConstantProperty(1); const entity = new import__72.Entity(); entity.position = new import__72.ConstantPositionProperty( new import__72.Cartesian3(1234, 5678, 9101112) ); entity.ellipse = ellipse; objects.add(entity); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__72.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toBeUndefined(); expect(primitive.appearance).toBeInstanceOf(import__72.MaterialAppearance); expect(primitive.appearance.closed).toBe(false); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); }); it("Creates and removes static color closed geometry", function() { const objects = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, objects, scene2.primitives, scene2.groundPrimitives ); const ellipse = new import__72.EllipseGraphics(); ellipse.semiMajorAxis = new import__72.ConstantProperty(2); ellipse.semiMinorAxis = new import__72.ConstantProperty(1); ellipse.material = new import__72.ColorMaterialProperty(); ellipse.extrudedHeight = new import__72.ConstantProperty(1e3); const entity = new import__72.Entity(); entity.position = new import__72.ConstantPositionProperty( new import__72.Cartesian3(1234, 5678, 9101112) ); entity.ellipse = ellipse; objects.add(entity); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__72.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toEqual( import__72.ColorGeometryInstanceAttribute.toValue(import__72.Color.WHITE) ); expect(primitive.appearance).toBeInstanceOf(import__72.PerInstanceColorAppearance); expect(primitive.appearance.closed).toBe(true); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); }); it("Creates and removes static material closed geometry", function() { const objects = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, objects, scene2.primitives, scene2.groundPrimitives ); const ellipse = new import__72.EllipseGraphics(); ellipse.semiMajorAxis = new import__72.ConstantProperty(2); ellipse.semiMinorAxis = new import__72.ConstantProperty(1); ellipse.material = new import__72.GridMaterialProperty(); ellipse.extrudedHeight = new import__72.ConstantProperty(1e3); const entity = new import__72.Entity(); entity.position = new import__72.ConstantPositionProperty( new import__72.Cartesian3(1234, 5678, 9101112) ); entity.ellipse = ellipse; objects.add(entity); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__72.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toBeUndefined(); expect(primitive.appearance).toBeInstanceOf(import__72.MaterialAppearance); expect(primitive.appearance.closed).toBe(true); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); }); it("Creates and removes static outline geometry", function() { const objects = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, objects, scene2.primitives, scene2.groundPrimitives ); const ellipse = new import__72.EllipseGraphics(); ellipse.semiMajorAxis = new import__72.ConstantProperty(2); ellipse.semiMinorAxis = new import__72.ConstantProperty(1); ellipse.outline = new import__72.ConstantProperty(true); ellipse.outlineColor = new import__72.ConstantProperty(import__72.Color.BLUE); ellipse.fill = new import__72.ConstantProperty(false); const entity = new import__72.Entity(); entity.position = new import__72.ConstantPositionProperty( new import__72.Cartesian3(1234, 5678, 9101112) ); entity.ellipse = ellipse; objects.add(entity); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__72.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toEqual( import__72.ColorGeometryInstanceAttribute.toValue(import__72.Color.BLUE) ); expect(primitive.appearance).toBeInstanceOf(import__72.PerInstanceColorAppearance); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); }); function createAndRemoveGeometryWithShadows(shadows) { const objects = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, objects, scene2.primitives, scene2.groundPrimitives ); const ellipse = new import__72.EllipseGraphics(); ellipse.semiMajorAxis = new import__72.ConstantProperty(2); ellipse.semiMinorAxis = new import__72.ConstantProperty(1); ellipse.material = new import__72.ColorMaterialProperty(); ellipse.extrudedHeight = new import__72.ConstantProperty(1e3); ellipse.shadows = new import__72.ConstantProperty(shadows); const entity = new import__72.Entity(); entity.position = new import__72.ConstantPositionProperty( new import__72.Cartesian3(1234, 5678, 9101112) ); entity.ellipse = ellipse; objects.add(entity); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); expect(primitive.shadows).toBe(shadows); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); } it("Creates and removes geometry with shadows disabled", function() { return createAndRemoveGeometryWithShadows(import__72.ShadowMode.DISABLED); }); it("Creates and removes geometry with shadows enabled", function() { return createAndRemoveGeometryWithShadows(import__72.ShadowMode.ENABLED); }); it("Creates and removes geometry with shadow casting only", function() { return createAndRemoveGeometryWithShadows(import__72.ShadowMode.CAST_ONLY); }); it("Creates and removes geometry with shadow receiving only", function() { return createAndRemoveGeometryWithShadows(import__72.ShadowMode.RECEIVE_ONLY); }); function createAndRemoveGeometryWithClassificationType(type) { const objects = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, objects, scene2.primitives, scene2.groundPrimitives ); const ellipse = new import__72.EllipseGraphics(); ellipse.semiMajorAxis = new import__72.ConstantProperty(2); ellipse.semiMinorAxis = new import__72.ConstantProperty(1); ellipse.material = new import__72.ColorMaterialProperty(); ellipse.classificationType = new import__72.ConstantProperty(type); const entity = new import__72.Entity(); entity.position = new import__72.ConstantPositionProperty( new import__72.Cartesian3(1234, 5678, 9101112) ); entity.ellipse = ellipse; objects.add(entity); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.groundPrimitives.get(0); expect(primitive.classificationType).toBe(type); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); } it("Creates and removes geometry classifying terrain", function() { return createAndRemoveGeometryWithClassificationType( import__72.ClassificationType.TERRAIN ); }); it("Creates and removes geometry classifying 3D Tiles", function() { return createAndRemoveGeometryWithClassificationType( import__72.ClassificationType.CESIUM_3D_TILE ); }); it("Creates and removes geometry classifying both terrain and 3D Tiles", function() { return createAndRemoveGeometryWithClassificationType( import__72.ClassificationType.BOTH ); }); it("Correctly handles geometry changing batches", function() { const objects = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, objects, scene2.primitives, scene2.groundPrimitives ); const ellipse = new import__72.EllipseGraphics(); ellipse.semiMajorAxis = new import__72.ConstantProperty(2); ellipse.semiMinorAxis = new import__72.ConstantProperty(1); ellipse.material = new import__72.ColorMaterialProperty(); ellipse.height = new import__72.ConstantProperty(0); const entity = new import__72.Entity(); entity.position = new import__72.ConstantPositionProperty( new import__72.Cartesian3(1234, 5678, 9101112) ); entity.ellipse = ellipse; objects.add(entity); return visualizerUpdated(visualizer).then(function() { let primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__72.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toEqual( import__72.ColorGeometryInstanceAttribute.toValue(import__72.Color.WHITE) ); expect(primitive.appearance).toBeInstanceOf(import__72.PerInstanceColorAppearance); ellipse.material = new import__72.GridMaterialProperty(); return visualizerUpdated(visualizer).then(function() { primitive = scene2.primitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__72.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toBeUndefined(); expect(primitive.appearance).toBeInstanceOf(import__72.MaterialAppearance); objects.remove(entity); scene2.initializeFrame(); expect(visualizer.update(time2)).toBe(true); scene2.render(time2); expect(scene2.primitives.length).toBe(0); visualizer.destroy(); }); }); }); it("Correctly handles modifying translucent outline color", function() { const entities = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, entities, scene2.primitives, scene2.groundPrimitives ); let color = import__72.Color.BLUE.withAlpha(0.5); const entity = entities.add({ position: new import__72.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, fill: false, outline: true, outlineColor: color } }); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.color).toEqual( import__72.ColorGeometryInstanceAttribute.toValue(color) ); color = import__72.Color.RED.withAlpha(0.5); entity.ellipse.outlineColor.setValue(color); return visualizerUpdated(visualizer); }).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.color).toEqual( import__72.ColorGeometryInstanceAttribute.toValue(color) ); entities.remove(entity); visualizer.destroy(); }); }); it("Creates and removes dynamic geometry", function() { const objects = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, objects, scene2.primitives, scene2.groundPrimitives ); const ellipse = new import__72.EllipseGraphics(); ellipse.semiMajorAxis = new import__72.SampledProperty(Number); ellipse.semiMajorAxis.addSample(time2, 2); ellipse.semiMinorAxis = new import__72.ConstantProperty(1); ellipse.extrudedHeight = new import__72.ConstantProperty(1e3); ellipse.material = new import__72.ColorMaterialProperty(); const entity = new import__72.Entity(); entity.position = new import__72.ConstantPositionProperty( new import__72.Cartesian3(1234, 5678, 9101112) ); entity.ellipse = ellipse; objects.add(entity); scene2.initializeFrame(); expect(visualizer.update(time2)).toBe(true); scene2.render(time2); objects.remove(entity); scene2.initializeFrame(); expect(visualizer.update(time2)).toBe(true); scene2.render(time2); expect(scene2.primitives.length).toBe(0); visualizer.destroy(); }); it("Creates and removes dynamic geometry on terrain ", function() { const objects = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, objects, scene2.primitives, scene2.groundPrimitives ); const ellipse = new import__72.EllipseGraphics(); ellipse.semiMajorAxis = new import__72.SampledProperty(Number); ellipse.semiMajorAxis.addSample(time2, 2); ellipse.semiMinorAxis = new import__72.ConstantProperty(1); ellipse.material = new import__72.ColorMaterialProperty(); const entity = new import__72.Entity(); entity.position = new import__72.ConstantPositionProperty( new import__72.Cartesian3(1234, 5678, 9101112) ); entity.ellipse = ellipse; objects.add(entity); scene2.initializeFrame(); expect(visualizer.update(time2)).toBe(true); scene2.render(time2); objects.remove(entity); scene2.initializeFrame(); expect(visualizer.update(time2)).toBe(true); scene2.render(time2); expect(scene2.primitives.length).toBe(0); visualizer.destroy(); }); it("Constructor throws without scene", function() { const objects = new import__72.EntityCollection(); expect(function() { return new import__72.GeometryVisualizer( void 0, objects, scene2.primitives, scene2.groundPrimitives ); }).toThrowDeveloperError(); }); it("Constructor throws without entityCollection", function() { expect(function() { return new import__72.GeometryVisualizer( scene2, void 0, scene2.primitives, scene2.groundPrimitives ); }).toThrowDeveloperError(); }); it("Update throws without time parameter", function() { const visualizer = new import__72.GeometryVisualizer( scene2, new import__72.EntityCollection(), scene2.primitives, scene2.groundPrimitives ); expect(function() { visualizer.update(void 0); }).toThrowDeveloperError(); }); it("removes the listener from the entity collection when destroyed", function() { const entityCollection = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, entityCollection, scene2.primitives, scene2.groundPrimitives ); expect(entityCollection.collectionChanged.numberOfListeners).toEqual(1); visualizer.destroy(); expect(entityCollection.collectionChanged.numberOfListeners).toEqual(0); }); it("calls destroy on all updaterSets", function() { const entityCollection = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, entityCollection, scene2.primitives, scene2.groundPrimitives ); const destroySpy = jasmine.createSpy("destroy"); visualizer._updaterSets.set("test", { destroy: destroySpy }); expect(visualizer._updaterSets.values.length).toBe(1); visualizer.destroy(); expect(destroySpy).toHaveBeenCalled(); expect(visualizer._updaterSets.values.length).toBe(0); }); it("Computes dynamic geometry bounding sphere.", function() { const entityCollection = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, entityCollection, scene2.primitives, scene2.groundPrimitives ); const ellipse = new import__72.EllipseGraphics(); ellipse.semiMajorAxis = new import__72.ConstantProperty(2); ellipse.semiMinorAxis = new import__72.ConstantProperty(1); ellipse.height = new import__72.ConstantProperty(0); const entity = new import__72.Entity(); entity.position = import__72.Cartesian3.fromDegrees(0, 0, 0); entity.ellipse = ellipse; entityCollection.add(entity); let state2; const result = new import__72.BoundingSphere(); return pollToPromise_default(function() { scene2.initializeFrame(); scene2.render(); visualizer.update(time2); state2 = visualizer.getBoundingSphere(entity, result); return state2 !== import__72.BoundingSphereState.PENDING; }).then(function() { const primitive = scene2.primitives.get(0); expect(state2).toBe(import__72.BoundingSphereState.DONE); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(result).toEqual( import__72.BoundingSphere.transform( attributes.boundingSphere, primitive.modelMatrix, new import__72.BoundingSphere() ) ); visualizer.destroy(); }); }); it("Compute dynamic geometry bounding sphere throws without entity.", function() { const entityCollection = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, entityCollection, scene2.primitives, scene2.groundPrimitives ); const result = new import__72.BoundingSphere(); expect(function() { visualizer.getBoundingSphere(void 0, result); }).toThrowDeveloperError(); visualizer.destroy(); }); it("Compute dynamic geometry bounding sphere throws without result.", function() { const entityCollection = new import__72.EntityCollection(); const entity = new import__72.Entity(); entityCollection.add(entity); const visualizer = new import__72.GeometryVisualizer( scene2, entityCollection, scene2.primitives, scene2.groundPrimitives ); expect(function() { visualizer.getBoundingSphere(entity, void 0); }).toThrowDeveloperError(); visualizer.destroy(); }); it("Can remove and entity and then add a new new instance with the same id.", function() { const objects = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, objects, scene2.primitives, scene2.groundPrimitives ); const entity = new import__72.Entity({ id: "test", position: import__72.Cartesian3.fromDegrees(0, 0, 0), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material: import__72.Color.ORANGE, height: 0 } }); objects.add(entity); return visualizerUpdated(visualizer).then(function() { objects.remove(entity); const entity2 = new import__72.Entity({ id: "test", position: import__72.Cartesian3.fromDegrees(0, 0, 0), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material: import__72.Color.BLUE, height: 0 } }); objects.add(entity2); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity2); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__72.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toEqual( import__72.ColorGeometryInstanceAttribute.toValue(import__72.Color.BLUE) ); expect(primitive.appearance).toBeInstanceOf( import__72.PerInstanceColorAppearance ); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); }); }); it("Sets static geometry primitive show attribute when using dynamic fill color", function() { const entities = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, entities, scene2.primitives, scene2.groundPrimitives ); const entity = entities.add({ position: new import__72.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material: new import__72.ColorMaterialProperty( createDynamicProperty_default(import__72.Color.BLUE) ), height: 0 } }); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__72.ShowGeometryInstanceAttribute.toValue(true) ); entity.show = false; return visualizerUpdated(visualizer); }).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__72.ShowGeometryInstanceAttribute.toValue(false) ); entities.remove(entity); visualizer.destroy(); }); }); it("Sets static geometry primitive show attribute when using dynamic outline color", function() { const entities = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, entities, scene2.primitives, scene2.groundPrimitives ); const entity = entities.add({ position: new import__72.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, fill: false, outline: true, outlineColor: createDynamicProperty_default(import__72.Color.BLUE) } }); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__72.ShowGeometryInstanceAttribute.toValue(true) ); entity.show = false; return visualizerUpdated(visualizer); }).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__72.ShowGeometryInstanceAttribute.toValue(false) ); entities.remove(entity); visualizer.destroy(); }); }); it("Sets static geometry primitive show attribute when using dynamic fill material", function() { const entities = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, entities, scene2.primitives, scene2.groundPrimitives ); const entity = entities.add({ position: new import__72.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material: new import__72.GridMaterialProperty({ color: createDynamicProperty_default(import__72.Color.BLUE) }), height: 0 } }); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__72.ShowGeometryInstanceAttribute.toValue(true) ); entity.show = false; return visualizerUpdated(visualizer); }).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__72.ShowGeometryInstanceAttribute.toValue(false) ); entities.remove(entity); visualizer.destroy(); }); }); it("batches ground entities by material if ground entity materials is supported", function() { if (!import__72.GroundPrimitive.isSupported(scene2) || !import__72.GroundPrimitive.supportsMaterials(scene2)) { return; } const entities = new import__72.EntityCollection(); const visualizer = new import__72.GeometryVisualizer( scene2, entities, scene2.primitives, scene2.groundPrimitives ); const blueColor = import__72.Color.BLUE.withAlpha(0.5); entities.add({ position: import__72.Cartesian3.fromDegrees(1, 2), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material: blueColor, classificationType: import__72.ClassificationType.TERRAIN } }); return visualizerUpdated(visualizer).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); entities.add({ position: import__72.Cartesian3.fromDegrees(12, 34), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material: blueColor, classificationType: import__72.ClassificationType.TERRAIN } }); return visualizerUpdated(visualizer); }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); entities.add({ position: import__72.Cartesian3.fromDegrees(45, 67), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material: import__72.Color.BLUE.withAlpha(0.6), classificationType: import__72.ClassificationType.TERRAIN } }); return visualizerUpdated(visualizer); }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); entities.add({ position: import__72.Cartesian3.fromDegrees(-1, -2), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material: "./Data/Images/White.png", classificationType: import__72.ClassificationType.TERRAIN } }); return visualizerUpdated(visualizer); }).then(function() { expect(scene2.groundPrimitives.length).toEqual(2); entities.add({ position: import__72.Cartesian3.fromDegrees(-12, -34), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material: "./Data/Images/White.png", classificationType: import__72.ClassificationType.CESIUM_3D_TILE } }); return visualizerUpdated(visualizer); }).then(function() { expect(scene2.groundPrimitives.length).toEqual(3); entities.removeAll(); visualizer.destroy(); }); }); it("registers new updater", () => { function FakeUpdater() { } FakeUpdater.prototype.geometryChanged = new import__72.Event(); const spy = spyOn(import__72.GeometryUpdaterSet, "registerUpdater"); import__72.GeometryUpdaterSet.registerUpdater(FakeUpdater); expect(spy).toHaveBeenCalledOnceWith(FakeUpdater); }); it("unregisters custom updaters", () => { function FakeUpdater() { } FakeUpdater.prototype.geometryChanged = new import__72.Event(); const spy = spyOn(import__72.GeometryUpdaterSet, "unregisterUpdater"); import__72.GeometryUpdaterSet.unregisterUpdater(FakeUpdater); expect(spy).toHaveBeenCalledOnceWith(FakeUpdater); }); }, "WebGL" ); // packages/engine/Specs/DataSources/GpxDataSourceSpec.js var import__73 = __toESM(require_Cesium(), 1); describe("DataSources/GpxDataSource", function() { const parser = new DOMParser(); it("default constructor has expected values", function() { const dataSource = new import__73.GpxDataSource(); expect(dataSource.name).toBeUndefined(); expect(dataSource.clock).toBeUndefined(); expect(dataSource.entities).toBeInstanceOf(import__73.EntityCollection); expect(dataSource.isLoading).toBe(false); expect(dataSource.changedEvent).toBeInstanceOf(import__73.Event); expect(dataSource.errorEvent).toBeInstanceOf(import__73.Event); expect(dataSource.loadingEvent).toBeInstanceOf(import__73.Event); expect(dataSource.show).toBe(true); }); it("load throws with undefined GPX", function() { const dataSource = new import__73.GpxDataSource(); expect(function() { dataSource.load(void 0); }).toThrowDeveloperError(); }); it("load works with a GPX URL", function() { const dataSource = new import__73.GpxDataSource(); return dataSource.load("Data/GPX/simple.gpx").then(function(source) { expect(source).toBe(dataSource); expect(source.entities.values.length).toEqual(1); }); }); it("load rejects nonexistent URL", function() { return import__73.GpxDataSource.load("test.invalid").catch(function(e) { expect(e).toBeInstanceOf(import__73.RequestErrorEvent); }); }); it("load rejects loading non-GPX URL", function() { return import__73.GpxDataSource.load("Data/Images/Blue.png").catch(function(e) { expect(e).toBeInstanceOf(import__73.RuntimeError); }); }); it("sets DataSource creator and version from gpx", function() { const dataSource = new import__73.GpxDataSource(); const gpx = ' '; return dataSource.load(parser.parseFromString(gpx, "text/xml")).then(function() { expect(dataSource.version).toEqual("1.1"); expect(dataSource.creator).toEqual("Test"); }); }); it("sets DataSource name from metadata", function() { const dataSource = new import__73.GpxDataSource(); const gpx = ' File Name '; return dataSource.load(parser.parseFromString(gpx, "text/xml")).then(function() { expect(dataSource.name).toEqual("File Name"); }); }); it("sets DataSource metadata object correctly", function() { const dataSource = new import__73.GpxDataSource(); const gpx = ' The name The desc The keyword '; return dataSource.load(parser.parseFromString(gpx, "text/xml")).then(function() { const metadata = dataSource.metadata; expect(metadata).toBeDefined(); expect(metadata.name).toEqual("The name"); expect(metadata.desc).toEqual("The desc"); expect(metadata.time).toEqual("The time"); expect(metadata.keywords).toEqual("The keyword"); }); }); it("Metadata: handles personType, emailType and linkType", function() { const dataSource = new import__73.GpxDataSource(); const gpx = ' The name user email.com A website text/html '; return dataSource.load(parser.parseFromString(gpx, "text/xml")).then(function() { const metadata = dataSource.metadata; expect(metadata).toBeDefined(); const person = metadata.author; expect(person).toBeDefined(); expect(person.name).toEqual("The name"); expect(person.email).toBeDefined(); expect(person.email).toEqual("user@email.com"); expect(person.link).toBeDefined(); expect(person.link.href).toEqual("www.a.com"); expect(person.link.text).toEqual("A website"); expect(person.link.mimeType).toEqual("text/html"); }); }); it("Metadata: handles copyrightType", function() { const dataSource = new import__73.GpxDataSource(); const gpx = ' 2015 The license '; return dataSource.load(parser.parseFromString(gpx, "text/xml")).then(function() { const metadata = dataSource.metadata; expect(metadata).toBeDefined(); const copyright = metadata.copyright; expect(copyright).toBeDefined(); expect(copyright.author).toEqual("The author"); expect(copyright.year).toEqual("2015"); expect(copyright.license).toEqual("The license"); }); }); it("Metadata: handles boundsType", function() { const dataSource = new import__73.GpxDataSource(); const gpx = ' 1 2 3 4 '; return dataSource.load(parser.parseFromString(gpx, "text/xml")).then(function() { const metadata = dataSource.metadata; expect(metadata).toBeDefined(); const bounds = metadata.bounds; expect(bounds).toBeDefined(); expect(bounds.minLat).toEqual(1); expect(bounds.maxLat).toEqual(2); expect(bounds.minLon).toEqual(3); expect(bounds.maxLon).toEqual(4); }); }); it("raises changed event when the name changes", function() { let gpx = ' NameInGpx '; const dataSource = new import__73.GpxDataSource(); const spy = jasmine.createSpy("changedEvent"); dataSource.changedEvent.addEventListener(spy); return dataSource.load(parser.parseFromString(gpx, "text/xml")).then(function() { expect(spy).toHaveBeenCalledWith(dataSource); spy.calls.reset(); return dataSource.load(parser.parseFromString(gpx, "text/xml")).then(function() { expect(spy).not.toHaveBeenCalled(); gpx = gpx.replace("NameInGpx", "newName"); spy.calls.reset(); return dataSource.load(parser.parseFromString(gpx, "text/xml")).then(function() { expect(spy).toHaveBeenCalledWith(dataSource); }); }); }); }); it("raises loadingEvent event at start and end of load", function() { const dataSource = new import__73.GpxDataSource(); const spy = jasmine.createSpy("loadingEvent"); dataSource.loadingEvent.addEventListener(spy); const promise = dataSource.load("Data/GPX/simple.gpx"); expect(spy).toHaveBeenCalledWith(dataSource, true); spy.calls.reset(); return promise.then(function() { expect(spy).toHaveBeenCalledWith(dataSource, false); }); }); it("Waypoint: sets name", function() { const gpx = ' Test '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.name).toBe("Test"); expect(entity.label).toBeDefined(); expect(entity.label.text.getValue()).toBe("Test"); } ); }); it("Waypoint: throws with invalid coordinates", function() { const gpx = ' '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).catch( function(e) { expect(e).toBeInstanceOf(import__73.DeveloperError); } ); }); it("Waypoint: throws when no coordinates are given", function() { const gpx = ' '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).catch( function(e) { expect(e).toBeInstanceOf(import__73.DeveloperError); } ); }); it("Waypoint: handles simple waypoint", function() { const gpx = ' Position 1 '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); expect(entities[0].position.getValue(import__73.Iso8601.MINIMUM_VALUE)).toEqual( import__73.Cartesian3.fromDegrees(38.737125, -9.139242, void 0) ); expect(entities[0].name).toEqual("Position 1"); } ); }); it("Waypoint: uses default billboard style", function() { const BILLBOARD_SIZE = 32; const gpx = ' Position 1 '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const entities = dataSource.entities.values; expect(entities[0].billboard.height.getValue()).toEqual(BILLBOARD_SIZE); expect(entities[0].billboard.width.getValue()).toEqual(BILLBOARD_SIZE); expect(entities[0].billboard.verticalOrigin.getValue()).toEqual( import__73.VerticalOrigin.BOTTOM ); expect(entities[0].billboard.heightReference).toBeUndefined(); } ); }); it("Waypoint: uses clampToGround billboards", function() { const gpx = ' Position 1 '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml"), { clampToGround: true }).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities[0].billboard.heightReference.getValue()).toEqual( import__73.HeightReference.CLAMP_TO_GROUND ); }); }); it("Waypoint: uses custom image for billboard", function() { const gpx = ' Position 1 '; const image = document.createElement("img"); image.name = "wpt"; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml"), { clampToGround: true, waypointImage: image }).then(function(dataSource) { const entities = dataSource.entities.values; const image2 = entities[0].billboard.image; expect(image2.getValue().name).toEqual("wpt"); }); }); it("Waypoint: handles simple waypoint with elevation", function() { const gpx = ' 3 Position 1 '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); expect(entities[0].position.getValue(import__73.Iso8601.MINIMUM_VALUE)).toEqual( import__73.Cartesian3.fromDegrees(1, 2, 3) ); } ); }); it("Waypoint: handles multiple waypoints", function() { const gpx = ' Position 1 Position 2 Position 3 '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(3); expect(entities[0].position.getValue(import__73.Iso8601.MINIMUM_VALUE)).toEqual( import__73.Cartesian3.fromDegrees(1, 2, void 0) ); expect(entities[1].position.getValue(import__73.Iso8601.MINIMUM_VALUE)).toEqual( import__73.Cartesian3.fromDegrees(3, 4, void 0) ); expect(entities[2].position.getValue(import__73.Iso8601.MINIMUM_VALUE)).toEqual( import__73.Cartesian3.fromDegrees(5, 6, void 0) ); } ); }); it("Description: handles desc", function() { const gpx = ' The Description '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const entity = dataSource.entities.values[0]; const element = document.createElement("div"); element.innerHTML = entity.description.getValue(); const div = element.firstChild; expect(div.style["word-wrap"]).toEqual("break-word"); expect(div.style["background-color"]).toEqual("rgb(255, 255, 255)"); expect(div.style.color).toEqual("rgb(0, 0, 0)"); expect(div.textContent).toEqual("Description: The Description"); } ); }); it("Description: handles time", function() { const gpx = ' '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const entity = dataSource.entities.values[0]; const element = document.createElement("div"); element.innerHTML = entity.description.getValue(); const div = element.firstChild; expect(div.style["word-wrap"]).toEqual("break-word"); expect(div.style["background-color"]).toEqual("rgb(255, 255, 255)"); expect(div.style.color).toEqual("rgb(0, 0, 0)"); expect(div.textContent).toEqual("Time: 2015-08-17T00:06Z"); } ); }); it("Description: handles comment", function() { const gpx = ' The comment '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const entity = dataSource.entities.values[0]; const element = document.createElement("div"); element.innerHTML = entity.description.getValue(); const div = element.firstChild; expect(div.style["word-wrap"]).toEqual("break-word"); expect(div.style["background-color"]).toEqual("rgb(255, 255, 255)"); expect(div.style.color).toEqual("rgb(0, 0, 0)"); expect(div.textContent).toEqual("Comment: The comment"); } ); }); it("Description: handles source", function() { const gpx = ' The source '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const entity = dataSource.entities.values[0]; const element = document.createElement("div"); element.innerHTML = entity.description.getValue(); const div = element.firstChild; expect(div.style["word-wrap"]).toEqual("break-word"); expect(div.style["background-color"]).toEqual("rgb(255, 255, 255)"); expect(div.style.color).toEqual("rgb(0, 0, 0)"); expect(div.textContent).toEqual("Source: The source"); } ); }); it("Description: handles gps number", function() { const gpx = ' The number '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const entity = dataSource.entities.values[0]; const element = document.createElement("div"); element.innerHTML = entity.description.getValue(); const div = element.firstChild; expect(div.style["word-wrap"]).toEqual("break-word"); expect(div.style["background-color"]).toEqual("rgb(255, 255, 255)"); expect(div.style.color).toEqual("rgb(0, 0, 0)"); expect(div.textContent).toEqual("GPS track/route number: The number"); } ); }); it("Description: handles type", function() { const gpx = ' The type '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const entity = dataSource.entities.values[0]; const element = document.createElement("div"); element.innerHTML = entity.description.getValue(); const div = element.firstChild; expect(div.style["word-wrap"]).toEqual("break-word"); expect(div.style["background-color"]).toEqual("rgb(255, 255, 255)"); expect(div.style.color).toEqual("rgb(0, 0, 0)"); expect(div.textContent).toEqual("Type: The type"); } ); }); it("Description: handles multiple fields", function() { const gpx = ' The comment The description The type '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const entity = dataSource.entities.values[0]; const element = document.createElement("div"); element.innerHTML = entity.description.getValue(); const div = element.firstChild; expect(div.style["word-wrap"]).toEqual("break-word"); expect(div.style["background-color"]).toEqual("rgb(255, 255, 255)"); expect(div.style.color).toEqual("rgb(0, 0, 0)"); expect(div.textContent).toEqual( "Comment: The commentDescription: The descriptionType: The type" ); } ); }); it("Description: handles route description", function() { const gpx = ' The comment The description The type 1 Position 1 1 Position 2 1 Position 3 1 Position 4 '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const entity = dataSource.entities.values[0]; const element = document.createElement("div"); element.innerHTML = entity.description.getValue(); const div = element.firstChild; expect(div.style["word-wrap"]).toEqual("break-word"); expect(div.style["background-color"]).toEqual("rgb(255, 255, 255)"); expect(div.style.color).toEqual("rgb(0, 0, 0)"); expect(div.textContent).toEqual( "Comment: The commentDescription: The descriptionType: The type" ); } ); }); it("Route: handles simple route", function() { const gpx = ' Test Route 1 Position 1 1 Position 2 1 Position 3 1 Position 4 '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(5); expect(entities[1].position.getValue(import__73.Iso8601.MINIMUM_VALUE)).toEqual( import__73.Cartesian3.fromDegrees(1, 2, 1) ); expect(entities[2].position.getValue(import__73.Iso8601.MINIMUM_VALUE)).toEqual( import__73.Cartesian3.fromDegrees(3, 4, 1) ); expect(entities[3].position.getValue(import__73.Iso8601.MINIMUM_VALUE)).toEqual( import__73.Cartesian3.fromDegrees(5, 6, 1) ); expect(entities[4].position.getValue(import__73.Iso8601.MINIMUM_VALUE)).toEqual( import__73.Cartesian3.fromDegrees(7, 8, 1) ); } ); }); it("Track: handles simple track", function() { const gpx = ' Test Track 1.0 Position 1 1.0 Position 2 '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); const entity = entities[0]; expect(entity.path).toBeUndefined(); expect(entity.polyline).toBeDefined(); const positions = entity.polyline.positions.getValue( import__73.Iso8601.MINIMUM_VALUE ); expect(positions).toEqual([ import__73.Cartesian3.fromDegrees(1, 2, 1), import__73.Cartesian3.fromDegrees(3, 4, 1) ]); } ); }); it("Track: uses default polyline style", function() { const gpx = ' Test Track 1.0 Position 1 1.0 Position 2 '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); const entity = entities[0]; expect(entity.path).toBeUndefined(); expect(entity.polyline).toBeDefined(); expect(entity.polyline.width.getValue()).toEqual(4); expect(entity.polyline.material.getValue()).toBeDefined(); expect(entity.polyline.material.color.getValue()).toEqual(import__73.Color.RED); expect(entity.polyline.material.outlineWidth.getValue()).toEqual(2); expect(entity.polyline.material.outlineColor.getValue()).toEqual( import__73.Color.BLACK ); } ); }); it("Track: uses custom polyline color for tracks", function() { const gpx = ' Test Track 1.0 Position 1 1.0 Position 2 '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml"), { trackColor: import__73.Color.BLUE }).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); const entity = entities[0]; expect(entity.polyline.material.color.getValue()).toEqual(import__73.Color.BLUE); expect(entity.polyline.clampToGround).toBeUndefined(); }); }); it("Track: uses custom polyline color for routes", function() { const gpx = ' 0.0 Position 1 0.0 Position 2 0.0 Position 3 0.0 Position 4 '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml"), { routeColor: import__73.Color.BLUE }).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(5); const entity = entities[0]; expect(entity.polyline.material.color.getValue()).toEqual(import__73.Color.BLUE); expect(entity.polyline.clampToGround).toBeUndefined(); }); }); it("Track: uses clampToGround polylines", function() { const gpx = ' Test Track 1.0 Position 1 1.0 Position 2 '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml"), { clampToGround: true }).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); const entity = entities[0]; expect(entity.polyline.clampToGround.getValue()).toEqual(true); }); }); it("Track: handles time-dynamic track", function() { const gpx = ' Test Track 1.0 Position 1 1.0 Position 2 1.0 Position 3 '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const time1 = import__73.JulianDate.fromIso8601("2000-01-01T00:00:00Z"); const time2 = import__73.JulianDate.fromIso8601("2000-01-01T00:00:01Z"); const time3 = import__73.JulianDate.fromIso8601("2000-01-01T00:00:02Z"); const entity = dataSource.entities.values[0]; expect(entity.position.getValue(time1)).toEqual( import__73.Cartesian3.fromDegrees(1, 2, 1) ); expect(entity.position.getValue(time2)).toEqual( import__73.Cartesian3.fromDegrees(3, 4, 1) ); expect(entity.position.getValue(time3)).toEqual( import__73.Cartesian3.fromDegrees(5, 6, 1) ); expect(entity.polyline).toBeDefined(); expect(entity.availability.start).toEqual(time1); expect(entity.availability.stop).toEqual(time3); } ); }); it("Track: time-dynamic uses default path style", function() { const gpx = ' Test Track 1.0 Position 1 1.0 Position 2 1.0 Position 3 '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml")).then( function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); const entity = entities[0]; expect(entity.polyline).toBeDefined(); expect(entity.polyline.width.getValue()).toEqual(4); expect(entity.polyline.material.getValue()).toBeDefined(); expect(entity.polyline.material.color.getValue()).toEqual(import__73.Color.RED); expect(entity.polyline.material.outlineWidth.getValue()).toEqual(2); expect(entity.polyline.material.outlineColor.getValue()).toEqual( import__73.Color.BLACK ); } ); }); it("Track: time-dynamic track uses clampToGround", function() { const gpx = ' Test Track 1.0 Position 1 1.0 Position 2 1.0 Position 3 '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml"), { clampToGround: true }).then(function(dataSource) { const entities = dataSource.entities.values; const entity = entities[0]; expect(entity.polyline).toBeDefined(); expect(entity.polyline.clampToGround.getValue()).toEqual(true); }); }); it("update returns true", function() { const gpx = ' Test Track 1.0 Position 1 1.0 Position 2 '; return import__73.GpxDataSource.load(parser.parseFromString(gpx, "text/xml"), { clampToGround: true }).then(function(dataSource) { expect(dataSource.update()).toBe(true); }); }); }); // packages/engine/Specs/DataSources/GridMaterialPropertySpec.js var import__74 = __toESM(require_Cesium(), 1); describe("DataSources/GridMaterialProperty", function() { it("constructor provides the expected defaults", function() { const property = new import__74.GridMaterialProperty(); expect(property.color).toBeUndefined(); expect(property.cellAlpha).toBeUndefined(); expect(property.lineCount).toBeUndefined(); expect(property.lineThickness).toBeUndefined(); expect(property.lineOffset).toBeUndefined(); expect(property.getType()).toEqual("Grid"); const result = property.getValue(); expect(result.color).toEqual(import__74.Color.WHITE); expect(result.cellAlpha).toEqual(0.1); expect(result.lineCount).toEqual(new import__74.Cartesian2(8, 8)); expect(result.lineThickness).toEqual(new import__74.Cartesian2(1, 1)); expect(result.lineOffset).toEqual(new import__74.Cartesian2(0, 0)); }); it("constructor sets options and allows raw assignment", function() { const options = { color: import__74.Color.RED, cellAlpha: 1, lineCount: new import__74.Cartesian2(2, 3), lineThickness: new import__74.Cartesian2(4, 5), lineOffset: new import__74.Cartesian2(6, 7) }; const property = new import__74.GridMaterialProperty(options); expect(property.color).toBeInstanceOf(import__74.ConstantProperty); expect(property.cellAlpha).toBeInstanceOf(import__74.ConstantProperty); expect(property.lineCount).toBeInstanceOf(import__74.ConstantProperty); expect(property.lineThickness).toBeInstanceOf(import__74.ConstantProperty); expect(property.lineOffset).toBeInstanceOf(import__74.ConstantProperty); expect(property.color.getValue()).toEqual(options.color); expect(property.cellAlpha.getValue()).toEqual(options.cellAlpha); expect(property.lineCount.getValue()).toEqual(options.lineCount); expect(property.lineThickness.getValue()).toEqual(options.lineThickness); expect(property.lineOffset.getValue()).toEqual(options.lineOffset); }); it("works with constant values", function() { const property = new import__74.GridMaterialProperty(); property.color = new import__74.ConstantProperty(import__74.Color.RED); property.cellAlpha = new import__74.ConstantProperty(1); property.lineCount = new import__74.ConstantProperty(new import__74.Cartesian2(3.4, 5)); property.lineThickness = new import__74.ConstantProperty(new import__74.Cartesian2(2, 3)); property.lineOffset = new import__74.ConstantProperty(new import__74.Cartesian2(0.7, 0.8)); const result = property.getValue(import__74.JulianDate.now()); expect(result.color).toEqual(import__74.Color.RED); expect(result.cellAlpha).toEqual(1); expect(result.lineCount).toEqual(new import__74.Cartesian2(3.4, 5)); expect(result.lineThickness).toEqual(new import__74.Cartesian2(2, 3)); expect(result.lineOffset).toEqual(new import__74.Cartesian2(0.7, 0.8)); }); it("works with dynamic values", function() { const property = new import__74.GridMaterialProperty(); property.color = new import__74.TimeIntervalCollectionProperty(); property.cellAlpha = new import__74.TimeIntervalCollectionProperty(); property.lineCount = new import__74.TimeIntervalCollectionProperty(); property.lineThickness = new import__74.TimeIntervalCollectionProperty(); property.lineOffset = new import__74.TimeIntervalCollectionProperty(); const start = new import__74.JulianDate(1, 0); const stop = new import__74.JulianDate(2, 0); property.color.intervals.addInterval( new import__74.TimeInterval({ start, stop, data: import__74.Color.BLUE }) ); property.cellAlpha.intervals.addInterval( new import__74.TimeInterval({ start, stop, data: 1 }) ); property.lineCount.intervals.addInterval( new import__74.TimeInterval({ start, stop, data: new import__74.Cartesian2(3.4, 5) }) ); property.lineThickness.intervals.addInterval( new import__74.TimeInterval({ start, stop, data: new import__74.Cartesian2(2, 3) }) ); property.lineOffset.intervals.addInterval( new import__74.TimeInterval({ start, stop, data: new import__74.Cartesian2(0.7, 0.8) }) ); const result = property.getValue(start); expect(result.color).toEqual(import__74.Color.BLUE); expect(result.cellAlpha).toEqual(1); expect(result.lineCount).toEqual(new import__74.Cartesian2(3.4, 5)); expect(result.lineThickness).toEqual(new import__74.Cartesian2(2, 3)); expect(result.lineOffset).toEqual(new import__74.Cartesian2(0.7, 0.8)); }); it("works with a result parameter", function() { const property = new import__74.GridMaterialProperty(); property.color = new import__74.ConstantProperty(import__74.Color.RED); property.cellAlpha = new import__74.ConstantProperty(1); property.lineCount = new import__74.ConstantProperty(new import__74.Cartesian2(3.4, 5)); property.lineThickness = new import__74.ConstantProperty(new import__74.Cartesian2(2, 3)); property.lineOffset = new import__74.ConstantProperty(new import__74.Cartesian2(0.7, 0.8)); const result = {}; const returnedResult = property.getValue(import__74.JulianDate.now(), result); expect(result).toBe(returnedResult); expect(result.color).toEqual(import__74.Color.RED); expect(result.cellAlpha).toEqual(1); expect(result.lineCount).toEqual(new import__74.Cartesian2(3.4, 5)); expect(result.lineThickness).toEqual(new import__74.Cartesian2(2, 3)); expect(result.lineOffset).toEqual(new import__74.Cartesian2(0.7, 0.8)); }); it("equals works", function() { const left = new import__74.GridMaterialProperty(); left.color = new import__74.ConstantProperty(import__74.Color.RED); left.cellAlpha = new import__74.ConstantProperty(1); left.lineCount = new import__74.ConstantProperty(new import__74.Cartesian2(3.4, 5)); left.lineThickness = new import__74.ConstantProperty(new import__74.Cartesian2(2, 3)); left.lineOffset = new import__74.ConstantProperty(new import__74.Cartesian2(0.7, 0.8)); const right = new import__74.GridMaterialProperty(); right.color = new import__74.ConstantProperty(import__74.Color.RED); right.cellAlpha = new import__74.ConstantProperty(1); right.lineCount = new import__74.ConstantProperty(new import__74.Cartesian2(3.4, 5)); right.lineThickness = new import__74.ConstantProperty(new import__74.Cartesian2(2, 3)); right.lineOffset = new import__74.ConstantProperty(new import__74.Cartesian2(0.7, 0.8)); expect(left.equals(right)).toEqual(true); right.color = new import__74.ConstantProperty(import__74.Color.BLUE); expect(left.equals(right)).toEqual(false); right.color = left.color; right.cellAlpha = new import__74.ConstantProperty(0.5); expect(left.equals(right)).toEqual(false); right.cellAlpha = left.cellAlpha; right.lineCount = new import__74.ConstantProperty(new import__74.Cartesian2(4, 5)); expect(left.equals(right)).toEqual(false); right.lineCount = left.lineCount; right.lineThickness = new import__74.ConstantProperty(new import__74.Cartesian2(3, 2)); expect(left.equals(right)).toEqual(false); right.lineThickness = left.lineThickness; right.lineOffset = new import__74.ConstantProperty(new import__74.Cartesian2(0.8, 0.7)); expect(left.equals(right)).toEqual(false); right.lineOffset = left.lineOffset; expect(left.equals(right)).toEqual(true); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__74.GridMaterialProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); let oldValue = property.color; property.color = new import__74.ConstantProperty(import__74.Color.WHITE); expect(listener).toHaveBeenCalledWith( property, "color", property.color, oldValue ); listener.calls.reset(); property.color.setValue(import__74.Color.BLACK); expect(listener).toHaveBeenCalledWith( property, "color", property.color, property.color ); listener.calls.reset(); property.color = property.color; expect(listener.calls.count()).toEqual(0); listener.calls.reset(); oldValue = property.cellAlpha; property.cellAlpha = new import__74.ConstantProperty(0); expect(listener).toHaveBeenCalledWith( property, "cellAlpha", property.cellAlpha, oldValue ); listener.calls.reset(); property.cellAlpha.setValue(1); expect(listener).toHaveBeenCalledWith( property, "cellAlpha", property.cellAlpha, property.cellAlpha ); listener.calls.reset(); property.cellAlpha = property.cellAlpha; expect(listener.calls.count()).toEqual(0); listener.calls.reset(); oldValue = property.lineCount; property.lineCount = new import__74.ConstantProperty(5); expect(listener).toHaveBeenCalledWith( property, "lineCount", property.lineCount, oldValue ); listener.calls.reset(); property.lineCount.setValue(10); expect(listener).toHaveBeenCalledWith( property, "lineCount", property.lineCount, property.lineCount ); listener.calls.reset(); property.lineCount = property.lineCount; expect(listener.calls.count()).toEqual(0); listener.calls.reset(); oldValue = property.lineThickness; property.lineThickness = new import__74.ConstantProperty(5); expect(listener).toHaveBeenCalledWith( property, "lineThickness", property.lineThickness, oldValue ); listener.calls.reset(); property.lineThickness.setValue(10); expect(listener).toHaveBeenCalledWith( property, "lineThickness", property.lineThickness, property.lineThickness ); listener.calls.reset(); oldValue = property.lineOffset; property.lineOffset = new import__74.ConstantProperty(5); expect(listener).toHaveBeenCalledWith( property, "lineOffset", property.lineOffset, oldValue ); listener.calls.reset(); property.lineOffset.setValue(10); expect(listener).toHaveBeenCalledWith( property, "lineOffset", property.lineOffset, property.lineOffset ); listener.calls.reset(); property.lineOffset = property.lineOffset; expect(listener.calls.count()).toEqual(0); }); it("isConstant is only true when all properties are constant or undefined", function() { const property = new import__74.GridMaterialProperty(); expect(property.isConstant).toBe(true); property.color = void 0; property.cellAlpha = void 0; property.lineCount = void 0; property.lineThickness = void 0; property.lineOffset = void 0; expect(property.isConstant).toBe(true); property.color = new import__74.SampledProperty(import__74.Color); property.color.addSample(import__74.JulianDate.now(), import__74.Color.WHITE); expect(property.isConstant).toBe(false); property.color = void 0; expect(property.isConstant).toBe(true); property.cellAlpha = new import__74.SampledProperty(Number); property.cellAlpha.addSample(import__74.JulianDate.now(), 0); expect(property.isConstant).toBe(false); property.cellAlpha = void 0; expect(property.isConstant).toBe(true); property.lineCount = new import__74.SampledProperty(Number); property.lineCount.addSample(import__74.JulianDate.now(), 1); expect(property.isConstant).toBe(false); property.lineCount = void 0; expect(property.isConstant).toBe(true); property.lineThickness = new import__74.SampledProperty(Number); property.lineThickness.addSample(import__74.JulianDate.now(), 1); expect(property.isConstant).toBe(false); property.lineThickness = void 0; expect(property.isConstant).toBe(true); property.lineOffset = new import__74.SampledProperty(Number); property.lineOffset.addSample(import__74.JulianDate.now(), 1); expect(property.isConstant).toBe(false); }); }); // packages/engine/Specs/DataSources/GroundGeometryUpdaterSpec.js var import__75 = __toESM(require_Cesium(), 1); describe("DataSources/GroundGeometryUpdater", function() { beforeAll(function() { return import__75.ApproximateTerrainHeights.initialize(); }); afterAll(function() { import__75.ApproximateTerrainHeights._initPromise = void 0; import__75.ApproximateTerrainHeights._terrainHeights = void 0; }); it("getGeometryHeight works for for height reference NONE and RELATIVE_TO_GROUND", function() { const expected = 30; const height = expected; let heightReference = import__75.HeightReference.NONE; expect( import__75.GroundGeometryUpdater.getGeometryHeight(height, heightReference) ).toEqual(expected); heightReference = import__75.HeightReference.RELATIVE_TO_GROUND; expect( import__75.GroundGeometryUpdater.getGeometryHeight(height, heightReference) ).toEqual(expected); }); it("getGeometryHeight works for for height reference CLAMP_TO_GROUND", function() { const height = 50; const heightReference = import__75.HeightReference.CLAMP_TO_GROUND; expect( import__75.GroundGeometryUpdater.getGeometryHeight(height, heightReference) ).toEqual(0); }); it("getGeometryExtrudedHeight works for for height reference NONE and RELATIVE_TO_GROUND", function() { const expected = 30; const height = expected; let heightReference = import__75.HeightReference.NONE; expect( import__75.GroundGeometryUpdater.getGeometryExtrudedHeight(height, heightReference) ).toEqual(expected); heightReference = import__75.HeightReference.RELATIVE_TO_GROUND; expect( import__75.GroundGeometryUpdater.getGeometryExtrudedHeight(height, heightReference) ).toEqual(expected); }); it("getGeometryExtrudedHeight works for for height reference CLAMP_TO_GROUND", function() { const height = 50; const heightReference = import__75.HeightReference.CLAMP_TO_GROUND; expect( import__75.GroundGeometryUpdater.getGeometryExtrudedHeight(height, heightReference) ).toEqual(import__75.GroundGeometryUpdater.CLAMP_TO_GROUND); }); it("computeGeometryOffsetAttribute works", function() { const height = 50; const extrudedHeight = 30; let heightReference; let extrudedHeightReference; let result = import__75.GroundGeometryUpdater.computeGeometryOffsetAttribute( height, heightReference, extrudedHeight, extrudedHeightReference ); expect(result).toBeUndefined(); heightReference = import__75.HeightReference.NONE; extrudedHeightReference = import__75.HeightReference.NONE; result = import__75.GroundGeometryUpdater.computeGeometryOffsetAttribute( height, heightReference, extrudedHeight, extrudedHeightReference ); expect(result).toBeUndefined(); heightReference = import__75.HeightReference.NONE; extrudedHeightReference = import__75.HeightReference.CLAMP_TO_GROUND; result = import__75.GroundGeometryUpdater.computeGeometryOffsetAttribute( height, heightReference, extrudedHeight, extrudedHeightReference ); expect(result).toBeUndefined(); heightReference = import__75.HeightReference.NONE; extrudedHeightReference = import__75.HeightReference.RELATIVE_TO_GROUND; result = import__75.GroundGeometryUpdater.computeGeometryOffsetAttribute( height, heightReference, extrudedHeight, extrudedHeightReference ); expect(result).toBe(import__75.GeometryOffsetAttribute.TOP); heightReference = import__75.HeightReference.CLAMP_TO_GROUND; extrudedHeightReference = import__75.HeightReference.NONE; result = import__75.GroundGeometryUpdater.computeGeometryOffsetAttribute( height, heightReference, extrudedHeight, extrudedHeightReference ); expect(result).toBe(import__75.GeometryOffsetAttribute.TOP); heightReference = import__75.HeightReference.CLAMP_TO_GROUND; extrudedHeightReference = import__75.HeightReference.CLAMP_TO_GROUND; result = import__75.GroundGeometryUpdater.computeGeometryOffsetAttribute( height, heightReference, extrudedHeight, extrudedHeightReference ); expect(result).toBe(import__75.GeometryOffsetAttribute.TOP); heightReference = import__75.HeightReference.CLAMP_TO_GROUND; extrudedHeightReference = import__75.HeightReference.RELATIVE_TO_GROUND; result = import__75.GroundGeometryUpdater.computeGeometryOffsetAttribute( height, heightReference, extrudedHeight, extrudedHeightReference ); expect(result).toBe(import__75.GeometryOffsetAttribute.ALL); heightReference = import__75.HeightReference.RELATIVE_TO_GROUND; extrudedHeightReference = import__75.HeightReference.NONE; result = import__75.GroundGeometryUpdater.computeGeometryOffsetAttribute( height, heightReference, extrudedHeight, extrudedHeightReference ); expect(result).toBe(import__75.GeometryOffsetAttribute.TOP); heightReference = import__75.HeightReference.RELATIVE_TO_GROUND; extrudedHeightReference = import__75.HeightReference.CLAMP_TO_GROUND; result = import__75.GroundGeometryUpdater.computeGeometryOffsetAttribute( height, heightReference, extrudedHeight, extrudedHeightReference ); expect(result).toBe(import__75.GeometryOffsetAttribute.TOP); heightReference = import__75.HeightReference.RELATIVE_TO_GROUND; extrudedHeightReference = import__75.HeightReference.RELATIVE_TO_GROUND; result = import__75.GroundGeometryUpdater.computeGeometryOffsetAttribute( height, heightReference, extrudedHeight, extrudedHeightReference ); expect(result).toBe(import__75.GeometryOffsetAttribute.ALL); result = import__75.GroundGeometryUpdater.computeGeometryOffsetAttribute( void 0, heightReference, void 0, extrudedHeightReference ); expect(result).toBeUndefined(); }); it("Overridden version of destroy is called", function() { const options = { scene: { frameState: { context: { depthTexture: true } } }, entity: {}, geometryOptions: {}, geometryPropertyName: "", observedPropertyNames: [] }; const groundGeometryUpdater = new import__75.GroundGeometryUpdater(options); const destroySpy = jasmine.createSpy("destroy"); groundGeometryUpdater._terrainOffsetProperty = { destroy: destroySpy }; groundGeometryUpdater.destroy(); expect(destroySpy).toHaveBeenCalled(); expect(groundGeometryUpdater._terrainOffsetProperty).toBeUndefined(); expect(groundGeometryUpdater.isDestroyed()).toBe(true); }); }); // packages/engine/Specs/DataSources/ImageMaterialPropertySpec.js var import__76 = __toESM(require_Cesium(), 1); describe("DataSources/ImageMaterialProperty", function() { it("constructor provides the expected defaults", function() { const property = new import__76.ImageMaterialProperty(); expect(property.getType()).toEqual("Image"); const result = property.getValue(); expect(result.image).toBeUndefined(); expect(result.repeat).toEqual(new import__76.Cartesian2(1, 1)); expect(result.color).toEqual(import__76.Color.WHITE); }); it("constructor sets options and allows raw assignment", function() { const options = { image: "test.invalid", repeat: new import__76.Cartesian2(1, 2), color: import__76.Color.RED.withAlpha(0.5), transparent: true }; const property = new import__76.ImageMaterialProperty(options); expect(property.image).toBeInstanceOf(import__76.ConstantProperty); expect(property.repeat).toBeInstanceOf(import__76.ConstantProperty); expect(property.color).toBeInstanceOf(import__76.ConstantProperty); expect(property.transparent).toBeInstanceOf(import__76.ConstantProperty); expect(property.image.getValue()).toEqual(options.image); expect(property.repeat.getValue()).toEqual(options.repeat); expect(property.color.getValue()).toEqual(options.color); expect(property.transparent.getValue()).toEqual(options.transparent); }); it("works with constant values", function() { const property = new import__76.ImageMaterialProperty(); property.image = new import__76.ConstantProperty("http://test.invalid/image.png"); property.repeat = new import__76.ConstantProperty(new import__76.Cartesian2(2, 3)); const result = property.getValue(import__76.JulianDate.now()); expect(result.image).toEqual("http://test.invalid/image.png"); expect(result.repeat).toEqual(new import__76.Cartesian2(2, 3)); }); it("works with dynamic values", function() { const property = new import__76.ImageMaterialProperty(); property.image = new import__76.TimeIntervalCollectionProperty(); property.repeat = new import__76.TimeIntervalCollectionProperty(); const start = new import__76.JulianDate(1, 0); const stop = new import__76.JulianDate(2, 0); property.image.intervals.addInterval( new import__76.TimeInterval({ start, stop, data: "http://test.invalid/image.png" }) ); property.repeat.intervals.addInterval( new import__76.TimeInterval({ start, stop, data: new import__76.Cartesian2(2, 3) }) ); const result = property.getValue(start); expect(result.image).toEqual("http://test.invalid/image.png"); expect(result.repeat).toEqual(new import__76.Cartesian2(2, 3)); }); it("works with a result parameter", function() { const property = new import__76.ImageMaterialProperty(); property.image = new import__76.ConstantProperty("http://test.invalid/image.png"); property.repeat = new import__76.ConstantProperty(new import__76.Cartesian2(2, 3)); const result = {}; const returnedResult = property.getValue(import__76.JulianDate.now(), result); expect(result).toBe(returnedResult); expect(result.image).toEqual("http://test.invalid/image.png"); expect(result.repeat).toEqual(new import__76.Cartesian2(2, 3)); }); it("equals works", function() { const left = new import__76.ImageMaterialProperty(); left.image = new import__76.ConstantProperty("http://test.invalid/image.png"); left.repeat = new import__76.ConstantProperty(new import__76.Cartesian2(2, 3)); const right = new import__76.ImageMaterialProperty(); right.image = new import__76.ConstantProperty("http://test.invalid/image.png"); right.repeat = new import__76.ConstantProperty(new import__76.Cartesian2(2, 3)); expect(left.equals(right)).toEqual(true); right.image = new import__76.ConstantProperty("http://test.invalid/image2.png"); expect(left.equals(right)).toEqual(false); right.image = left.image; right.repeat = new import__76.ConstantProperty(new import__76.Cartesian2(3, 2)); expect(left.equals(right)).toEqual(false); right.repeat = left.repeat; expect(left.equals(right)).toEqual(true); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__76.ImageMaterialProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); let oldValue = property.image; property.image = new import__76.ConstantProperty("http://test.invalid/image.png"); expect(listener).toHaveBeenCalledWith( property, "image", property.image, oldValue ); listener.calls.reset(); property.image.setValue("http://test.invalid/image2.png"); expect(listener).toHaveBeenCalledWith( property, "image", property.image, property.image ); listener.calls.reset(); property.image = property.image; expect(listener.calls.count()).toEqual(0); listener.calls.reset(); oldValue = property.repeat; property.repeat = new import__76.ConstantProperty(new import__76.Cartesian2(1.5, 1.5)); expect(listener).toHaveBeenCalledWith( property, "repeat", property.repeat, oldValue ); listener.calls.reset(); property.repeat.setValue(new import__76.Cartesian2(1, 1)); expect(listener).toHaveBeenCalledWith( property, "repeat", property.repeat, property.repeat ); listener.calls.reset(); property.repeat = property.repeat; expect(listener.calls.count()).toEqual(0); }); it("isConstant is only true when all properties are constant or undefined", function() { const property = new import__76.ImageMaterialProperty(); expect(property.isConstant).toBe(true); property.image = void 0; property.repeat = void 0; expect(property.isConstant).toBe(true); const start = new import__76.JulianDate(1, 0); const stop = new import__76.JulianDate(2, 0); property.image = new import__76.TimeIntervalCollectionProperty(); property.image.intervals.addInterval( new import__76.TimeInterval({ start, stop, data: "http://test.invalid/image.png" }) ); expect(property.isConstant).toBe(false); property.image = void 0; expect(property.isConstant).toBe(true); property.repeat = new import__76.TimeIntervalCollectionProperty(); property.repeat.intervals.addInterval( new import__76.TimeInterval({ start, stop, data: new import__76.Cartesian2(2, 3) }) ); expect(property.isConstant).toBe(false); }); }); // packages/engine/Specs/DataSources/KmlDataSourceSpec.js var import__77 = __toESM(require_Cesium(), 1); var import__78 = __toESM(require_Cesium(), 1); describe("DataSources/KmlDataSource", function() { const parser = new DOMParser(); const image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAMAAAAoyzS7AAADAFBMVEUAAP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADHM2paAAAAGHRFWHRTb2Z0d2FyZQBQYWludC5ORVQgdjMuMzap5+IlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg=="; const uberStyle = ' '; const uberLineColor = import__77.Color.fromBytes(170, 170, 170, 170); const uberLineWidth = 2; const uberPolyColor = import__77.Color.fromBytes(204, 204, 204, 204); const uberPolyFill = false; const uberPolyOutline = false; const uberIconColor = import__77.Color.fromBytes(221, 221, 221, 221); const uberIconScale = 3; const uberIconHeading = import__78.Math.toRadians(-45); const uberIconHotspot = new import__77.Cartesian2(45, -42); const uberIconHref = import__77.Resource.DEFAULT.getDerivedResource({ url: "test.png" }).url; const uberLabelColor = import__77.Color.fromBytes(238, 238, 238, 238); const uberLabelScale = 4; const expectedRefreshLinkHref = import__77.Resource.DEFAULT.getDerivedResource({ url: "./Data/KML/refresh.kml" }).url; const screenOverlayContainer = document.createElement("div"); const uberCamera = { positionWC: new import__77.Cartesian3(0, 0, 0), directionWC: new import__77.Cartesian3(0, 0, 1), upWC: new import__77.Cartesian3(0, 1, 0), pitch: 0, heading: 0, frustum: new import__77.PerspectiveFrustum(), computeViewRectangle: function() { return import__77.Rectangle.MAX_VALUE; }, pickEllipsoid: function() { return void 0; } }; const uberCanvas = { clientWidth: 512, clientHeight: 512 }; const options = { credit: "This is my credit", screenOverlayContainer }; uberCamera.frustum.fov = import__78.Math.PI_OVER_FOUR; uberCamera.frustum.aspectRatio = 1; beforeEach(function() { uberCamera.positionWC.x = 0; }); it("default constructor has expected values", function() { const dataSource = new import__77.KmlDataSource(options); expect(dataSource.name).toBeUndefined(); expect(dataSource.clock).toBeUndefined(); expect(dataSource.entities).toBeInstanceOf(import__77.EntityCollection); expect(dataSource.isLoading).toBe(false); expect(dataSource.changedEvent).toBeInstanceOf(import__77.Event); expect(dataSource.errorEvent).toBeInstanceOf(import__77.Event); expect(dataSource.loadingEvent).toBeInstanceOf(import__77.Event); expect(dataSource.unsupportedNodeEvent).toBeInstanceOf(import__77.Event); expect(dataSource.show).toBe(true); expect(dataSource.credit).toBeInstanceOf(import__77.Credit); }); it("setting name raises changed event", function() { const dataSource = new import__77.KmlDataSource(options); const spy = jasmine.createSpy("changedEvent"); dataSource.changedEvent.addEventListener(spy); const newName = "garfield"; dataSource.name = newName; expect(dataSource.name).toEqual(newName); expect(spy.calls.count()).toEqual(1); expect(spy).toHaveBeenCalledWith(dataSource); }); it("show sets underlying entity collection show.", function() { const dataSource = new import__77.KmlDataSource(options); dataSource.show = false; expect(dataSource.show).toBe(false); expect(dataSource.show).toEqual(dataSource.entities.show); dataSource.show = true; expect(dataSource.show).toBe(true); expect(dataSource.show).toEqual(dataSource.entities.show); }); it("load throws with undefined KML", function() { const dataSource = new import__77.KmlDataSource(options); expect(function() { dataSource.load(void 0); }).toThrowDeveloperError(); }); it("load works with a KMZ file", function() { const dataSource = new import__77.KmlDataSource(options); return import__77.Resource.fetchBlob("Data/KML/simple.kmz").then(function(blob) { return dataSource.load(blob); }).then(function(source) { expect(source).toBe(dataSource); expect(source.entities.values.length).toEqual(1); }); }); it("load rejects loading non-KMZ file", function() { const dataSource = new import__77.KmlDataSource(options); const spy = jasmine.createSpy("errorEvent"); dataSource.errorEvent.addEventListener(spy); return import__77.Resource.fetchBlob("Data/Images/Blue.png").then(function(blob) { return dataSource.load(blob); }).catch(function(e) { expect(e).toBeInstanceOf(import__77.RuntimeError); expect(spy).toHaveBeenCalled(); }); }); it("load rejects KMZ file with no KML contained", function() { return import__77.Resource.fetchBlob("Data/KML/empty.kmz").then(function(blob) { return import__77.KmlDataSource.load(blob, options); }).catch(function(e) { expect(e).toBeInstanceOf(import__77.RuntimeError); expect(e.message).toEqual("KMZ file does not contain a KML document."); }); }); it("load works with a KML URL", function() { const dataSource = new import__77.KmlDataSource(options); return dataSource.load("Data/KML/simple.kml", options).then(function(source) { expect(source).toBe(dataSource); expect(source.entities.values.length).toEqual(1); }); }); it("load works with a KML Resource", function() { const dataSource = new import__77.KmlDataSource(options); const resource = new import__77.Resource({ url: "Data/KML/simple.kml" }); return dataSource.load(resource, options).then(function(source) { expect(source).toBe(dataSource); expect(source.entities.values.length).toEqual(1); }); }); it("load works with a KMZ URL", function() { const dataSource = new import__77.KmlDataSource(options); return dataSource.load("Data/KML/simple.kmz").then(function(source) { expect(source).toBe(dataSource); expect(source.entities.values.length).toEqual(1); }); }); it("load works with a KMZ URL with Windows-style paths", function() { const dataSource = new import__77.KmlDataSource(options); return dataSource.load("Data/KML/backslash.kmz").then(function(source) { expect(source).toBe(dataSource); expect( (0, import__77.isDataUri)(source.entities.values[0]._billboard._image._value.url) ).toBe(true); }); }); it("load works with a KMZ Resource", function() { const dataSource = new import__77.KmlDataSource(options); const resource = new import__77.Resource({ url: "Data/KML/simple.kmz" }); return dataSource.load(resource).then(function(source) { expect(source).toBe(dataSource); expect(source.entities.values.length).toEqual(1); }); }); it("load does deferred loading", function() { const kml = ' '; jasmine.clock().install(); jasmine.clock().mockDate(/* @__PURE__ */ new Date()); spyOn(import__77.KmlDataSource, "_getTimestamp").and.callFake(function() { return Date.now(); }); const OrigDeferredLoading = import__77.KmlDataSource._DeferredLoading; let deferredLoading; spyOn(import__77.KmlDataSource, "_DeferredLoading").and.callFake(function(datasource) { deferredLoading = new OrigDeferredLoading(datasource); const process = deferredLoading._process.bind(deferredLoading); spyOn(deferredLoading, "_process").and.callFake(function(isFirst) { jasmine.clock().tick(1001); return process(isFirst); }); const giveUpTime = deferredLoading._giveUpTime.bind(deferredLoading); spyOn(deferredLoading, "_giveUpTime").and.callFake(function() { giveUpTime(); jasmine.clock().tick(1); }); return deferredLoading; }); const dataSource = new import__77.KmlDataSource(options); return dataSource.load(parser.parseFromString(kml, "text/xml"), options).then(function(source) { expect(deferredLoading._process.calls.count()).toEqual(3); jasmine.clock().uninstall(); }); }); it("load inserts missing namespace declaration into kml", function() { const dataSource = new import__77.KmlDataSource(options); return dataSource.load("Data/KML/undeclaredNamespaces.kml").then(function(source) { expect(source).toBe(dataSource); expect(source.entities.values.length).toEqual(1); }); }); it("load inserts missing namespace declaration into kmz", function() { const dataSource = new import__77.KmlDataSource(options); return dataSource.load("Data/KML/undeclaredNamespaces.kmz").then(function(source) { expect(source).toBe(dataSource); expect(source.entities.values.length).toEqual(1); }); }); it("load deletes duplicate namespace declaration in kml", function() { const datasource = new import__77.KmlDataSource(options); return datasource.load("Data/KML/duplicateNamespace.kml").then(function(source) { expect(source).toBe(datasource); expect(source.entities.values.length).toEqual(1); }); }); it("load deletes duplicate namespace declaration in kmz", function() { const dataSource = new import__77.KmlDataSource(options); return dataSource.load("Data/KML/duplicateNamespace.kmz").then(function(source) { expect(source).toBe(dataSource); expect(source.entities.values.length).toEqual(1); }); }); it("load rejects nonexistent URL", function() { return import__77.KmlDataSource.load("test.invalid", options).catch(function(e) { expect(e).toBeInstanceOf(import__77.RequestErrorEvent); }); }); it("load rejects loading non-KML URL", function() { return import__77.KmlDataSource.load("Data/Images/Blue.png", options).catch(function(e) { expect(e).toBeInstanceOf(import__77.RuntimeError); }); }); it("load rejects valid KMZ zip URL with no KML contained", function() { return import__77.KmlDataSource.load("Data/KML/empty.kmz", options).catch(function(e) { expect(e).toBeInstanceOf(import__77.RuntimeError); expect(e.message).toEqual("KMZ file does not contain a KML document."); }); }); it("if load contains tag with no image included, no image is added", function() { const dataSource = new import__77.KmlDataSource(options); return import__77.Resource.fetchBlob("Data/KML/simpleNoIcon.kml").then(function(blob) { return dataSource.load(blob); }).then(function(source) { expect(source.entities); expect(source.entities.values.length).toEqual(1); expect(source.entities._entities._array.length).toEqual(1); expect( source.entities._entities._array[0]._billboard._image ).toBeUndefined(); }); }); it("if load does not contain icon #testStyle '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); expect(entities[0].billboard.scale.getValue()).toEqual(3); }); }); it("Styles: supports local styles with styleUrl missing #", function() { const kml = ' testStyle '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); expect(entities[0].billboard.scale.getValue()).toEqual(3); }); }); it("Styles: supports external styles with styleUrl", function() { const kml = ' Data/KML/externalStyle.kml#testStyle '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities[0].billboard.scale.getValue()).toEqual(3); }); }); it("Styles: supports external style maps with styleUrl", function() { const kml = ' Data/KML/externalStyle.kml#testStyleMap '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities[0].billboard.scale.getValue()).toEqual(3); }); }); it("Styles: inline styles take precedance over shared styles", function() { const kml = ' #testStyle '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); const billboard = entities[0].billboard; expect(billboard.scale.getValue()).toEqual(2); expect(billboard.rotation.getValue()).toEqual(import__78.Math.toRadians(-4)); expect(billboard.image.getValue().url).toEqual("http://test.invalid/"); }); }); it("Styles: colorMode random", function() { import__78.Math.setRandomNumberSeed(0); const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const generatedColor = dataSource.entities.values[0].billboard.color.getValue(); expect(generatedColor.red).toBeLessThan(1); expect(generatedColor.green).toBeLessThan(1); expect(generatedColor.blue).toBeLessThan(1); expect(generatedColor.alpha).toEqual(0.8); }); }); it("Styles: colorMode random black", function() { import__78.Math.setRandomNumberSeed(0); const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const generatedColor = dataSource.entities.values[0].billboard.color.getValue(); expect(generatedColor.red).toEqual(0); expect(generatedColor.green).toEqual(0); expect(generatedColor.blue).toEqual(0); expect(generatedColor.alpha).toEqual(0.8); }); }); it("Styles: empty color", function() { import__78.Math.setRandomNumberSeed(0); const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.entities.values[0].billboard.color).toBeUndefined(); }); }); it("Styles: Applies expected styles to Point geometry", function() { const kml = ` ${uberStyle} TheName absolute 1,2,3 `; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.label).toBeDefined(); expect(entity.label.text.getValue()).toEqual("TheName"); expect(entity.label.fillColor.getValue()).toEqual(uberLabelColor); expect(entity.label.scale.getValue()).toEqual(uberLabelScale); expect(entity.billboard.color.getValue()).toEqual(uberIconColor); expect(entity.billboard.scale.getValue()).toEqual(uberIconScale); expect(entity.billboard.rotation.getValue()).toEqual(uberIconHeading); expect(entity.billboard.image.getValue().url).toEqual(uberIconHref); expect(entity.billboard.pixelOffset.getValue()).toEqual(uberIconHotspot); expect(entity.polyline).toBeUndefined(); }); }); it("Styles: Applies expected styles to extruded Point geometry", function() { const kml = ` ${uberStyle} TheName 1 absolute 1,2,3 `; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.label.text.getValue()).toEqual("TheName"); expect(entity.label.fillColor.getValue()).toEqual(uberLabelColor); expect(entity.label.scale.getValue()).toEqual(uberLabelScale); expect(entity.billboard.color.getValue()).toEqual(uberIconColor); expect(entity.billboard.scale.getValue()).toEqual(uberIconScale); expect(entity.billboard.rotation.getValue()).toEqual(uberIconHeading); expect(entity.billboard.image.getValue().url).toEqual(uberIconHref); expect(entity.billboard.pixelOffset.getValue()).toEqual(uberIconHotspot); expect(entity.polyline.material).toBeInstanceOf(import__77.ColorMaterialProperty); expect(entity.polyline.material.color.getValue()).toEqual(uberLineColor); expect(entity.polyline.width.getValue()).toEqual(uberLineWidth); }); }); it("Styles: Applies expected styles to LineString geometry", function() { const kml = ` ${uberStyle} TheName 1,2,3 4,5,6 `; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polyline.material).toBeInstanceOf(import__77.ColorMaterialProperty); expect(entity.polyline.material.color.getValue()).toEqual(uberLineColor); expect(entity.polyline.width.getValue()).toEqual(uberLineWidth); expect(entity.label).toBeUndefined(); expect(entity.wall).toBeUndefined(); }); }); it("Styles: Applies expected styles to extruded LineString geometry", function() { const kml = ` ${uberStyle} TheName 1 absolute 1,2,3 4,5,6 `; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.wall.material).toBeInstanceOf(import__77.ColorMaterialProperty); expect(entity.wall.material.color.getValue()).toEqual(uberPolyColor); expect(entity.wall.fill.getValue()).toEqual(uberPolyFill); expect(entity.wall.outline.getValue()).toEqual(true); expect(entity.wall.outlineColor.getValue()).toEqual(uberLineColor); expect(entity.wall.outlineWidth.getValue()).toEqual(uberLineWidth); expect(entity.polyline).toBeUndefined(); expect(entity.label).toBeUndefined(); }); }); it("Styles: Applies expected styles to Polygon geometry", function() { const kml = ` ${uberStyle} 1 absolute 1,2,3 4,5,6 7,8,9 `; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon.material).toBeInstanceOf(import__77.ColorMaterialProperty); expect(entity.polygon.material.color.getValue()).toEqual(uberPolyColor); expect(entity.polygon.fill.getValue()).toEqual(uberPolyFill); expect(entity.polygon.outline.getValue()).toEqual(uberPolyOutline); expect(entity.polygon.outlineColor.getValue()).toEqual(uberLineColor); expect(entity.polygon.outlineWidth.getValue()).toEqual(uberLineWidth); expect(entity.label).toBeUndefined(); }); }); it("Styles: Applies expected styles to gx:Track geometry", function() { const kml = ` ${uberStyle} TheName absolute 2000-01-01T00:00:02Z 7 8 9 `; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.label).toBeDefined(); expect(entity.label.text.getValue()).toEqual("TheName"); expect(entity.label.fillColor.getValue()).toEqual(uberLabelColor); expect(entity.label.scale.getValue()).toEqual(uberLabelScale); expect(entity.billboard.color.getValue()).toEqual(uberIconColor); expect(entity.billboard.scale.getValue()).toEqual(uberIconScale); expect(entity.billboard.rotation.getValue()).toEqual(uberIconHeading); expect(entity.billboard.image.getValue().url).toEqual(uberIconHref); expect(entity.billboard.pixelOffset.getValue()).toEqual(uberIconHotspot); expect(entity.path).toBeDefined(); expect(entity.path.material).toBeInstanceOf(import__77.ColorMaterialProperty); expect(entity.path.material.color.getValue()).toEqual(uberLineColor); expect(entity.path.width.getValue()).toEqual(uberLineWidth); expect(entity.path.leadTime.getValue()).toEqual(0); expect(entity.path.trailTime).toBeUndefined(); expect(entity.polyline).toBeUndefined(); }); }); it("Styles: Applies expected styles to extruded gx:Track geometry", function() { const kml = ` ${uberStyle} TheName 1 absolute 2000-01-01T00:00:02Z 7 8 9 `; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.label.text.getValue()).toEqual("TheName"); expect(entity.label.fillColor.getValue()).toEqual(uberLabelColor); expect(entity.label.scale.getValue()).toEqual(uberLabelScale); expect(entity.billboard.color.getValue()).toEqual(uberIconColor); expect(entity.billboard.scale.getValue()).toEqual(uberIconScale); expect(entity.billboard.rotation.getValue()).toEqual(uberIconHeading); expect(entity.billboard.image.getValue().url).toEqual(uberIconHref); expect(entity.billboard.pixelOffset.getValue()).toEqual(uberIconHotspot); expect(entity.path).toBeDefined(); expect(entity.path.material).toBeInstanceOf(import__77.ColorMaterialProperty); expect(entity.path.material.color.getValue()).toEqual(uberLineColor); expect(entity.path.width.getValue()).toEqual(uberLineWidth); expect(entity.path.leadTime.getValue()).toEqual(0); expect(entity.path.trailTime).toBeUndefined(); expect(entity.polyline.material).toBeInstanceOf(import__77.ColorMaterialProperty); expect(entity.polyline.material.color.getValue()).toEqual(uberLineColor); expect(entity.polyline.width.getValue()).toEqual(uberLineWidth); }); }); it("Styles: Applies expected styles to gx:MultiTrack geometry", function() { const kml = ` ${uberStyle} TheName absolute 2000-01-01T00:00:02Z 7 8 9 `; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.label).toBeDefined(); expect(entity.label.text.getValue()).toEqual("TheName"); expect(entity.label.fillColor.getValue()).toEqual(uberLabelColor); expect(entity.label.scale.getValue()).toEqual(uberLabelScale); expect(entity.billboard.color.getValue()).toEqual(uberIconColor); expect(entity.billboard.scale.getValue()).toEqual(uberIconScale); expect(entity.billboard.rotation.getValue()).toEqual(uberIconHeading); expect(entity.billboard.image.getValue().url).toEqual(uberIconHref); expect(entity.billboard.pixelOffset.getValue()).toEqual(uberIconHotspot); expect(entity.path).toBeDefined(); expect(entity.path.material).toBeInstanceOf(import__77.ColorMaterialProperty); expect(entity.path.material.color.getValue()).toEqual(uberLineColor); expect(entity.path.width.getValue()).toEqual(uberLineWidth); expect(entity.path.leadTime.getValue()).toEqual(0); expect(entity.path.trailTime).toBeUndefined(); expect(entity.polyline).toBeUndefined(); }); }); it("Styles: Applies expected styles to extruded gx:MultiTrack geometry", function() { const kml = ` ${uberStyle} TheName 1 absolute 2000-01-01T00:00:02Z 7 8 9 `; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.label.text.getValue()).toEqual("TheName"); expect(entity.label.fillColor.getValue()).toEqual(uberLabelColor); expect(entity.label.scale.getValue()).toEqual(uberLabelScale); expect(entity.billboard.color.getValue()).toEqual(uberIconColor); expect(entity.billboard.scale.getValue()).toEqual(uberIconScale); expect(entity.billboard.rotation.getValue()).toEqual(uberIconHeading); expect(entity.billboard.image.getValue().url).toEqual(uberIconHref); expect(entity.billboard.pixelOffset.getValue()).toEqual(uberIconHotspot); expect(entity.path).toBeDefined(); expect(entity.path.material).toBeInstanceOf(import__77.ColorMaterialProperty); expect(entity.path.material.color.getValue()).toEqual(uberLineColor); expect(entity.path.width.getValue()).toEqual(uberLineWidth); expect(entity.path.leadTime.getValue()).toEqual(0); expect(entity.path.trailTime).toBeUndefined(); expect(entity.polyline.material).toBeInstanceOf(import__77.ColorMaterialProperty); expect(entity.polyline.material.color.getValue()).toEqual(uberLineColor); expect(entity.polyline.width.getValue()).toEqual(uberLineWidth); }); }); it("Styles: Applies local StyleMap", function() { const kml = ' normal '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.billboard.scale.getValue()).toBe(2); }); }); it("Styles: Applies normal styleUrl StyleMap", function() { const kml = ' normal #styleMapExample '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.billboard.scale.getValue()).toBe(2); }); }); it("Styles: Applies normal StyleMap containing styleUrl", function() { const kml = ' normal #normalStyle #styleMapExample '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.billboard.scale.getValue()).toBe(2); }); }); it("Styles: Applies normal StyleMap containing styleUrl without #", function() { const kml = ' normal normalStyle #styleMapExample '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.billboard.scale.getValue()).toBe(2); }); }); it("IconStyle: handles empty element", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities[0].billboard).toBeDefined(); }); }); it("IconStyle: Sets billboard image absolute path", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; const billboard = entities[0].billboard; expect(billboard.image.getValue().url).toEqual( "http://test.invalid/image.png" ); }); }); it("IconStyle: Sets billboard with root:// Url", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; const billboard = entities[0].billboard; expect(billboard.image.getValue().url).toEqual( "https://maps.google.com/mapfiles/kml/pal3/icon56.png" ); }); }); it("IconStyle: Sets billboard image relative path", function() { const kml = ' '; return import__77.KmlDataSource.load(parser.parseFromString(kml, "text/xml"), { sourceUri: "http://test.invalid" }).then(function(dataSource) { const entities = dataSource.entities.values; const billboard = entities[0].billboard; expect(billboard.image.getValue().url).toEqual( "http://test.invalid/image.png" ); }); }); it("IconStyle: Sets billboard image inside KMZ", function() { return import__77.KmlDataSource.load("Data/KML/simple.kmz", options).then(function(dataSource) { const entities = dataSource.entities.values; const billboard = entities[0].billboard; expect(billboard.image.getValue().url).toEqual(image); }); }); it("IconStyle: Sets billboard image with subregion", function() { const kml = ' '; const expectedIconHref = import__77.Resource.DEFAULT.getDerivedResource({ url: "whiteShapes.png" }).url; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const billboard = dataSource.entities.values[0].billboard; expect(billboard.image.getValue().url).toEqual(expectedIconHref); expect(billboard.imageSubRegion.getValue()).toEqual( new import__77.BoundingRectangle(49, 43, 18, 18) ); }); }); it("IconStyle: Sets billboard image with hotSpot fractions", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const billboard = dataSource.entities.values[0].billboard; expect(billboard.pixelOffset.getValue()).toEqual(new import__77.Cartesian2(8, 8)); }); }); it("IconStyle: Sets billboard image with hotSpot pixels", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const billboard = dataSource.entities.values[0].billboard; expect(billboard.pixelOffset.getValue()).toEqual(new import__77.Cartesian2(15, -14)); }); }); it("IconStyle: Sets billboard image with hotSpot insetPixels", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const billboard = dataSource.entities.values[0].billboard; expect(billboard.pixelOffset.getValue()).toEqual(new import__77.Cartesian2(-15, 14)); }); }); it("IconStyle: Sets color", function() { const color = import__77.Color.fromBytes(204, 221, 238, 255); const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities[0].billboard.color.getValue()).toEqual(color); }); }); it("IconStyle: Sets scale", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities[0].billboard.scale.getValue()).toEqual(2.2); }); }); it("IconStyle: Sets heading", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities[0].billboard.rotation.getValue()).toEqual( import__78.Math.toRadians(-4) ); expect(entities[0].billboard.alignedAxis.getValue()).toEqual( import__77.Cartesian3.UNIT_Z ); }); }); it("BalloonStyle: specify all properties", function() { const kml = ' The Name The Description
The Address
The Snippet The Property The Value
'; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; const element = document.createElement("div"); element.innerHTML = entity.description.getValue(); const div = element.firstChild; expect(div.style["word-wrap"]).toEqual("break-word"); expect(div.style["background-color"]).toEqual("rgba(102, 68, 34, 0)"); expect(div.style.color).toEqual("rgba(0, 34, 68, 0.4)"); expect(div.textContent).toEqual( "The Name The Description The Address The Snippet The ID The Property The Value $[prop2/displayName] $[prop2]" ); }); }); it("BalloonStyle: entity replacement removes missing values", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; const element = document.createElement("div"); element.innerHTML = entity.description.getValue(); const div = element.firstChild; expect(div.textContent).toEqual(" "); }); }); it("BalloonStyle: description without BalloonStyle", function() { const kml = ' The Description '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; const element = document.createElement("div"); element.innerHTML = entity.description.getValue(); const div = element.firstChild; expect(div.style["word-wrap"]).toEqual("break-word"); expect(div.style["background-color"]).toEqual("rgb(255, 255, 255)"); expect(div.style.color).toEqual("rgb(0, 0, 0)"); expect(div.textContent).toEqual("The Description"); }); }); it("BalloonStyle: creates table from ExtendedData", function() { const kml = ' Property 1 1 2 Property 3 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; const element = document.createElement("div"); element.innerHTML = entity.description.getValue(); const div = element.firstChild; expect(div.style["word-wrap"]).toEqual("break-word"); expect(div.style["background-color"]).toEqual("rgb(255, 255, 255)"); expect(div.style.color).toEqual("rgb(0, 0, 0)"); const table = div.firstChild; expect(table.localName).toEqual("table"); expect(table.rows.length).toBe(3); expect(table.rows[0].cells.length).toEqual(2); expect(table.rows[1].cells.length).toEqual(2); expect(table.rows[2].cells.length).toEqual(2); expect(table.rows[0].cells[0].textContent).toEqual("Property 1"); expect(table.rows[1].cells[0].textContent).toEqual("prop2"); expect(table.rows[2].cells[0].textContent).toEqual("Property 3"); expect(table.rows[0].cells[1].textContent).toEqual("1"); expect(table.rows[1].cells[1].textContent).toEqual("2"); expect(table.rows[2].cells[1].textContent).toEqual(""); }); }); it("BalloonStyle: does not create a description for empty ExtendedData", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.description).toBeUndefined(); }); }); it("BalloonStyle: description creates links from text", function() { const kml = ' http://cesiumjs.org '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; const element = document.createElement("div"); element.innerHTML = entity.description.getValue(); const a = element.firstChild.firstChild; expect(a.localName).toEqual("a"); expect(a.getAttribute("href")).toEqual("http://cesiumjs.org/"); expect(a.getAttribute("target")).toEqual("_blank"); }); }); it("BalloonStyle: relative description paths absolute to sourceUri", function() { const kml = ' ]]> '; return import__77.KmlDataSource.load(parser.parseFromString(kml, "text/xml"), { sourceUri: "http://test.invalid" }).then(function(dataSource) { const entity = dataSource.entities.values[0]; const element = document.createElement("div"); element.innerHTML = entity.description.getValue(); const a = element.firstChild.firstChild; expect(a.localName).toEqual("img"); expect(a.getAttribute("src")).toEqual("http://test.invalid/foo/bar.png"); }); }); it("BalloonStyle: description retargets existing links to _blank", function() { const kml = ' Homepage]]> '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; const element = document.createElement("div"); element.innerHTML = entity.description.getValue(); const a = element.firstChild.firstChild; expect(a.localName).toEqual("a"); expect(a.textContent).toEqual("Homepage"); expect(a.getAttribute("href")).toEqual("http://cesiumjs.org/"); expect(a.getAttribute("target")).toEqual("_blank"); }); }); it("BalloonStyle: description does not create links from non-explicit urls", function() { const kml = ' states.id google.com '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; const element = document.createElement("div"); element.innerHTML = entity.description.getValue(); const div = element.firstChild; expect(div.innerHTML).toEqual("states.id google.com"); }); }); it("BalloonStyle: description is rewritten for embedded kmz links and images", function() { return import__77.KmlDataSource.load("Data/KML/simple.kmz", options).then(function(dataSource) { const entity = dataSource.entities.values[0]; const description = entity.description.getValue(); const div = document.createElement("div"); div.innerHTML = description; expect(div.textContent).toEqual("image.png image.png"); const children = div.firstChild.querySelectorAll("*"); expect(children.length).toEqual(2); const link = children[0]; expect(link.localName).toEqual("a"); expect(link.getAttribute("href")).toEqual(image); expect(link.getAttribute("download")).toEqual("image.png"); const img = children[1]; expect(img.localName).toEqual("img"); expect(img.src).toEqual(image); }); }); it("LabelStyle: Sets defaults", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; const label = entities[0].label; expect(label).toBeDefined(); expect(label.text).toBeUndefined(); expect(label.fillColor).toBeUndefined(); expect(label.outlineColor).toBeUndefined(); expect(label.outlineWidth).toBeUndefined(); expect(label.show).toBeUndefined(); expect(label.scale).toBeUndefined(); expect(label.verticalOrigin).toBeUndefined(); expect(label.eyeOffset).toBeUndefined(); expect(label.pixelOffsetScaleByDistance).toBeUndefined(); expect(label.text).toBeUndefined(); expect(label.fillColor).toBeUndefined(); expect(label.outlineColor).toBeUndefined(); expect(label.outlineWidth).toBeUndefined(); expect(label.show).toBeUndefined(); expect(label.scale).toBeUndefined(); expect(label.verticalOrigin).toBeUndefined(); expect(label.eyeOffset).toBeUndefined(); expect(label.pixelOffsetScaleByDistance).toBeUndefined(); expect(label.font.getValue()).toEqual("16px sans-serif"); expect(label.style.getValue()).toEqual(import__77.LabelStyle.FILL_AND_OUTLINE); expect(label.horizontalOrigin.getValue()).toEqual(import__77.HorizontalOrigin.LEFT); expect(label.pixelOffset.getValue()).toEqual(new import__77.Cartesian2(17, 0)); expect(label.translucencyByDistance.getValue()).toEqual( new import__77.NearFarScalar(3e6, 1, 5e6, 0) ); }); }); it("LabelStyle: Sets color", function() { const color = import__77.Color.fromBytes(204, 221, 238, 255); const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities[0].label.fillColor.getValue()).toEqual(color); }); }); it("LabelStyle: Sets scale", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities[0].label.pixelOffset.getValue()).toEqual( new import__77.Cartesian2(33, 0) ); }); }); it("LabelStyle: Sets pixelOffset when billboard scaled", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities[0].label.pixelOffset.getValue()).toEqual( new import__77.Cartesian3(3 * 16 + 1, 0) ); }); }); it("LabelStyle: Sets pixelOffset when billboard scaled", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities[0].label.pixelOffset).toBeUndefined(); expect(entities[0].label.horizontalOrigin).toBeUndefined(); }); }); it("LineStyle: Sets defaults", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; const polyline = entities[0].polyline; expect(polyline).toBeDefined(); expect(polyline.positions).toBeUndefined(); expect(polyline.arcType).toBeUndefined(); expect(polyline.width).toBeUndefined(); expect(polyline.show).toBeUndefined(); expect(polyline.material).toBeUndefined(); expect(polyline.granularity).toBeUndefined(); }); }); it("LineStyle: Sets color", function() { const color = import__77.Color.fromBytes(204, 221, 238, 255); const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; const polyline = entities[0].polyline; expect(polyline.material).toBeInstanceOf(import__77.ColorMaterialProperty); expect(polyline.material.color.getValue()).toEqual(color); }); }); it("LineStyle: Sets width", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; const polyline = entities[0].polyline; expect(polyline.width.getValue()).toEqual(2.75); }); }); it("PolyStyle: Sets defaults", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; const polygon = entities[0].polygon; expect(polygon).toBeDefined(); expect(polygon.hierarchy).toBeUndefined(); expect(polygon.height).toBeUndefined(); expect(polygon.extrudedHeight).toBeUndefined(); expect(polygon.show).toBeUndefined(); expect(polygon.fill).toBeUndefined(); expect(polygon.material).toBeUndefined(); expect(polygon.outlineWidth).toBeUndefined(); expect(polygon.stRotation).toBeUndefined(); expect(polygon.granularity).toBeUndefined(); expect(polygon.perPositionHeight).toBeUndefined(); expect(polygon.outline.getValue()).toBe(true); expect(polygon.outlineColor.getValue()).toEqual(import__77.Color.WHITE); }); }); it("PolyStyle: Sets color", function() { const color = import__77.Color.fromBytes(204, 221, 238, 255); const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; const polygon = entities[0].polygon; expect(polygon.material).toBeInstanceOf(import__77.ColorMaterialProperty); expect(polygon.material.color.getValue()).toEqual(color); }); }); it("PolyStyle: Sets fill", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; const polygon = entities[0].polygon; expect(polygon.fill.getValue()).toEqual(false); }); }); it("PolyStyle: Sets outline", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; const polygon = entities[0].polygon; expect(polygon.outline.getValue()).toEqual(false); }); }); it("Folder: sets parent property", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities; const folder = entities.getById("parent"); const placemark = entities.getById("child"); expect(entities.values.length).toBe(2); expect(folder).toBeDefined(); expect(placemark.parent).toBe(folder); }); }); it("Folder: timespan for folder", function() { const kml = ' 2000-01-01 2000-01-03 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const start = import__77.JulianDate.fromIso8601("2000-01-01"); const stop = import__77.JulianDate.fromIso8601("2000-01-03"); const entities = dataSource.entities.values; expect(entities.length).toBe(2); const interval = entities[0].availability; expect(interval.start).toEqual(start); expect(interval.stop).toEqual(stop); expect(entities[0].availability).toEqual(entities[1].availability); }); }); it("Folder: timespan for folder and feature", function() { const kml = ' 2000-01-02 2000-01-03 2000-01-01 2000-01-04 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const startFolder = import__77.JulianDate.fromIso8601("2000-01-01"); const stopFolder = import__77.JulianDate.fromIso8601("2000-01-04"); const startFeature = import__77.JulianDate.fromIso8601("2000-01-02"); const stopFeature = import__77.JulianDate.fromIso8601("2000-01-03"); const entities = dataSource.entities.values; expect(entities.length).toBe(2); let interval = entities[0].availability; expect(interval.start).toEqual(startFolder); expect(interval.stop).toEqual(stopFolder); interval = entities[1].availability; expect(interval.start).toEqual(startFeature); expect(interval.stop).toEqual(stopFeature); }); }); it("Folder: timestamp for folder", function() { const kml = ' 2000-01-03 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const start = import__77.JulianDate.fromIso8601("2000-01-03"); const entities = dataSource.entities.values; expect(entities.length).toBe(2); const interval = entities[0].availability; expect(interval.start).toEqual(start); expect(interval.stop).toEqual(import__77.Iso8601.MAXIMUM_VALUE); expect(entities[0].availability).toEqual(entities[1].availability); }); }); it("Folder: timestamp for folder and feature", function() { const kml = ' 2000-01-04 2000-01-05 2000-01-03 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const startFolder = import__77.JulianDate.fromIso8601("2000-01-03"); const startFeature = import__77.JulianDate.fromIso8601("2000-01-04"); const stopFeature = import__77.JulianDate.fromIso8601("2000-01-05"); const entities = dataSource.entities.values; expect(entities.length).toBe(2); let interval = entities[0].availability; expect(interval.start).toEqual(startFolder); expect(interval.stop).toEqual(import__77.Iso8601.MAXIMUM_VALUE); interval = entities[1].availability; expect(interval.start).toEqual(startFeature); expect(interval.stop).toEqual(stopFeature); }); }); it("Geometry Point: handles empty Point", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); expect(entities[0].position.getValue(import__77.Iso8601.MINIMUM_VALUE)).toEqual( import__77.Cartesian3.fromDegrees(0, 0, 0) ); expect(entities[0].polyline).toBeUndefined(); }); }); it("Geometry Point: handles invalid coordinates", function() { const kml = ' absolute 1,2,3,4 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); expect(entities[0].position.getValue(import__77.Iso8601.MINIMUM_VALUE)).toEqual( import__77.Cartesian3.fromDegrees(1, 2, 3) ); expect(entities[0].polyline).toBeUndefined(); }); }); it("Geometry Point: handles empty coordinates", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); expect(entities[0].position.getValue(import__77.Iso8601.MINIMUM_VALUE)).toEqual( import__77.Cartesian3.fromDegrees(0, 0, 0) ); expect(entities[0].polyline).toBeUndefined(); }); }); it("Geometry Point: sets heightReference to clampToGround", function() { const kml = ' 1,2,3 '; return import__77.KmlDataSource.load(parser.parseFromString(kml, "text/xml"), { clampToGround: true }).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); expect( entities[0].billboard.heightReference.getValue(import__77.Iso8601.MINIMUM_VALUE) ).toEqual(import__77.HeightReference.CLAMP_TO_GROUND); expect(entities[0].polyline).toBeUndefined(); }); }); it("Geometry Point: sets position altitudeMode absolute", function() { const kml = ' absolute 1,2,3 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); expect(entities[0].position.getValue(import__77.Iso8601.MINIMUM_VALUE)).toEqual( import__77.Cartesian3.fromDegrees(1, 2, 3) ); expect(entities[0].billboard.pixelOffset).toBeUndefined(); expect(entities[0].polyline).toBeUndefined(); }); }); it("Geometry Point: sets position altitudeMode relativeToGround", function() { const kml = ' relativeToGround 1,2,3 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); expect(entities[0].position.getValue(import__77.Iso8601.MINIMUM_VALUE)).toEqual( import__77.Cartesian3.fromDegrees(1, 2, 3) ); expect(entities[0].billboard.pixelOffset).toBeUndefined(); expect(entities[0].polyline).toBeUndefined(); }); }); it("Geometry Point: does not extrude when altitudeMode is clampToGround", function() { const kml = ' clampToGround 1,2 1 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); expect(entities[0].position.getValue(import__77.Iso8601.MINIMUM_VALUE)).toEqual( import__77.Cartesian3.fromDegrees(1, 2, 0) ); expect(entities[0].billboard.pixelOffset).toBeUndefined(); expect(entities[0].polyline).toBeUndefined(); }); }); it("Geometry Point: does not extrude when gx:altitudeMode is clampToSeaFloor", function() { const kml = ' clampToSeaFloor 1,2 1 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); expect(entities[0].position.getValue(import__77.Iso8601.MINIMUM_VALUE)).toEqual( import__77.Cartesian3.fromDegrees(1, 2) ); expect(entities[0].polyline).toBeUndefined(); }); }); it("Geometry Point: extrudes when altitudeMode is relativeToGround", function() { const kml = ' relativeToGround 1,2,3 1 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); expect(entities[0].position.getValue(import__77.Iso8601.MINIMUM_VALUE)).toEqual( import__77.Cartesian3.fromDegrees(1, 2, 3) ); expect(entities[0].polyline).toBeDefined(); const positions = entities[0].polyline.positions.getValue( import__77.Iso8601.MINIMUM_VALUE ); expect(positions).toEqualEpsilon( [import__77.Cartesian3.fromDegrees(1, 2, 3), import__77.Cartesian3.fromDegrees(1, 2, 0)], import__78.Math.EPSILON13 ); }); }); it("Geometry Point: extrudes when gx:altitudeMode is relativeToSeaFloor", function() { const kml = ' relativeToSeaFloor 1,2,3 1 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); expect(entities[0].position.getValue(import__77.Iso8601.MINIMUM_VALUE)).toEqual( import__77.Cartesian3.fromDegrees(1, 2, 3) ); expect(entities[0].polyline).toBeDefined(); const positions = entities[0].polyline.positions.getValue( import__77.Iso8601.MINIMUM_VALUE ); expect(positions).toEqualEpsilon( [import__77.Cartesian3.fromDegrees(1, 2, 3), import__77.Cartesian3.fromDegrees(1, 2, 0)], import__78.Math.EPSILON13 ); }); }); it("Geometry Point: extrudes when altitudeMode is absolute", function() { const kml = ' absolute 1,2,3 1 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); expect(entities[0].position.getValue(import__77.Iso8601.MINIMUM_VALUE)).toEqual( import__77.Cartesian3.fromDegrees(1, 2, 3) ); expect(entities[0].polyline).toBeDefined(); const positions = entities[0].polyline.positions.getValue( import__77.Iso8601.MINIMUM_VALUE ); expect(positions).toEqualEpsilon( [import__77.Cartesian3.fromDegrees(1, 2, 3), import__77.Cartesian3.fromDegrees(1, 2, 0)], import__78.Math.EPSILON13 ); }); }); it("Geometry Point: correctly converts coordinates using earth ellipsoid", function() { const kml = ' 24.070617695061806,87.90173269295278,0 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); expect( entities[0].position.getValue(import__77.Iso8601.MINIMUM_VALUE) ).toEqualEpsilon( new import__77.Cartesian3(213935.5635247161, 95566.36983235707, 6352461425213023e-9), import__78.Math.EPSILON13 ); }); }); it("Geometry Point: correctly converts coordinates using moon ellipsoid", function() { const kml = ' 24.070617695061806,87.90173269295278,0 '; const moonOptions = (0, import__77.combine)(options, { ellipsoid: import__77.Ellipsoid.MOON }); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), moonOptions ).then(function(moonDataSource) { const entities = moonDataSource.entities.values; expect(entities.length).toEqual(1); expect( entities[0].position.getValue(import__77.Iso8601.MINIMUM_VALUE) ).toEqualEpsilon( new import__77.Cartesian3(58080.7702560248, 25945.04756005268, 1.7362350758562544e6), import__78.Math.EPSILON13 ); }); }); it("Geometry Polygon: handles empty coordinates", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon.hierarchy).toBeUndefined(); }); }); it("Geometry Polygon: without holes", function() { const kml = ' 1,2,3 4,5,6 7,8,9 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; const coordinates = [ import__77.Cartesian3.fromDegrees(1, 2, 3), import__77.Cartesian3.fromDegrees(4, 5, 6), import__77.Cartesian3.fromDegrees(7, 8, 9) ]; expect(entity.polygon.hierarchy.getValue().positions).toEqual( coordinates ); }); }); it("Geometry Polygon: with holes", function() { const kml = ' 1,2,3 4,5,6 7,8,9 1.1,2.1,3.1 4.1,5.1,6.1 7.1,8.1,9.1 1.2,2.2,3.2 4.2,5.2,6.2 7.2,8.2,9.2 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; const coordinates = [ import__77.Cartesian3.fromDegrees(1, 2, 3), import__77.Cartesian3.fromDegrees(4, 5, 6), import__77.Cartesian3.fromDegrees(7, 8, 9) ]; const holeCoordinates = [ import__77.Cartesian3.fromDegrees(1.1, 2.1, 3.1), import__77.Cartesian3.fromDegrees(4.1, 5.1, 6.1), import__77.Cartesian3.fromDegrees(7.1, 8.1, 9.1) ]; const holeCoordinates2 = [ import__77.Cartesian3.fromDegrees(1.2, 2.2, 3.2), import__77.Cartesian3.fromDegrees(4.2, 5.2, 6.2), import__77.Cartesian3.fromDegrees(7.2, 8.2, 9.2) ]; const hierarchy = entity.polygon.hierarchy.getValue(); expect(hierarchy.positions).toEqual(coordinates); expect(hierarchy.holes.length).toEqual(2); expect(hierarchy.holes[0].positions).toEqual(holeCoordinates); expect(hierarchy.holes[0].holes).toEqual([]); expect(hierarchy.holes[1].positions).toEqual(holeCoordinates2); expect(hierarchy.holes[1].holes).toEqual([]); }); }); it("Geometry Polygon: altitudeMode relativeToGround and can extrude", function() { const kml = ' relativeToGround 1 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon.perPositionHeight.getValue()).toEqual(true); expect(entity.polygon.extrudedHeight.getValue()).toEqual(0); }); }); it("Geometry Polygon: altitudeMode absolute and can extrude", function() { const kml = ' absolute 1 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon.perPositionHeight.getValue()).toEqual(true); expect(entity.polygon.extrudedHeight.getValue()).toEqual(0); }); }); it("Geometry Polygon: altitudeMode clampToGround and cannot extrude", function() { const kml = ' clampToGround 1 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon.perPositionHeight).toBeUndefined(); expect(entity.polygon.extrudedHeight).toBeUndefined(); }); }); it("Geometry Polygon: gx:altitudeMode relativeToSeaFloor and can extrude", function() { const kml = ' relativeToSeaFloor 1 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon.perPositionHeight.getValue()).toEqual(true); expect(entity.polygon.extrudedHeight.getValue()).toEqual(0); }); }); it("Geometry Polygon: gx:altitudeMode clampToSeaFloor and can extrude", function() { const kml = ' clampToSeaFloor 1 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon.perPositionHeight).toBeUndefined(); expect(entity.polygon.extrudedHeight).toBeUndefined(); }); }); it("Geometry Polygon: When loaded with the Ellipsoid.MOON, the coordinates should be on the lunar ellipsoid, otherwise on Earth.", function() { const kml = ' 24.070617695061806,87.90173269295278,0 49.598705282838125,87.04553528415659,0 34.373553362965566,86.015550572534,0 14.570663006937881,86.60174704052636,0 24.070617695061806,87.90173269295278,0 '; const moonOptions = (0, import__77.combine)(options, { ellipsoid: import__77.Ellipsoid.MOON }); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), moonOptions ).then(function(moonDataSource) { const entity = moonDataSource.entities.values[0]; const moonPoint = entity.polygon.hierarchy.getValue().positions[0]; expect(moonPoint).toEqualEpsilon( new import__77.Cartesian3(58080.7702560248, 25945.04756005268, 1.7362350758562544e6), import__78.Math.EPSILON13 ); }); }); it("Geometry Polygon: When loaded with the default ellipsoid, the coordinates should be on Earth.", function() { const kml = ' 24.070617695061806,87.90173269295278,0 49.598705282838125,87.04553528415659,0 34.373553362965566,86.015550572534,0 14.570663006937881,86.60174704052636,0 24.070617695061806,87.90173269295278,0 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; const earthPoint = entity.polygon.hierarchy.getValue().positions[0]; expect(earthPoint).toEqualEpsilon( new import__77.Cartesian3(213935.5635247161, 95566.36983235707, 6352461425213023e-9), import__78.Math.EPSILON13 ); }); }); it("Geometry LineString: handles empty element", function() { const kml = ' '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); const entity = entities[0]; expect(entity.wall).toBeUndefined(); expect(entity.polyline).toBeDefined(); expect(entity.polyline.arcType.getValue()).toEqual(import__77.ArcType.NONE); }); }); it("Geometry LineString: sets positions (clampToGround default)", function() { const kml = ' 1,2,3 4,5,6 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); const entity = entities[0]; expect(entity.wall).toBeUndefined(); expect(entity.polyline).toBeDefined(); const positions = entity.polyline.positions.getValue( import__77.Iso8601.MINIMUM_VALUE ); expect(positions).toEqualEpsilon( [import__77.Cartesian3.fromDegrees(1, 2), import__77.Cartesian3.fromDegrees(4, 5)], import__78.Math.EPSILON10 ); expect(entity.polyline.arcType.getValue()).toEqual(import__77.ArcType.NONE); }); }); it("Geometry LineString: sets wall positions when extruded", function() { const kml = ' absolute 1 1,2,3 4,5,6 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); const entity = entities[0]; expect(entity.polyline).toBeUndefined(); expect(entity.wall).toBeDefined(); const positions = entity.wall.positions.getValue(import__77.Iso8601.MINIMUM_VALUE); expect(positions).toEqualEpsilon( [import__77.Cartesian3.fromDegrees(1, 2, 3), import__77.Cartesian3.fromDegrees(4, 5, 6)], import__78.Math.EPSILON10 ); }); }); it("Geometry LineString: sets positions altitudeMode clampToGround, cannot extrude, can tessellate", function() { const kml = ' clampToGround 1 1 1,2,3 4,5,6 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); const entity = entities[0]; expect(entity.polyline.arcType).toBeUndefined(); const positions = entity.polyline.positions.getValue( import__77.Iso8601.MINIMUM_VALUE ); expect(positions).toEqualEpsilon( [import__77.Cartesian3.fromDegrees(1, 2), import__77.Cartesian3.fromDegrees(4, 5)], import__78.Math.EPSILON10 ); }); }); it("Geometry LineString: sets positions altitudeMode gx:clampToSeaFloor, cannot extrude, can tessellate", function() { const kml = ' clampToSeaFloor 1 1 1,2,3 4,5,6 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); const entity = entities[0]; expect(entity.polyline.arcType).toBeUndefined(); const positions = entity.polyline.positions.getValue( import__77.Iso8601.MINIMUM_VALUE ); expect(positions).toEqualEpsilon( [import__77.Cartesian3.fromDegrees(1, 2), import__77.Cartesian3.fromDegrees(4, 5)], import__78.Math.EPSILON10 ); }); }); it("Geometry LineString: sets positions altitudeMode gx:relativeToSeaFloor, can extrude, cannot tessellate", function() { const kml = ' relativeToSeaFloor 1 1 1,2,3 4,5,6 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); const entity = entities[0]; expect(entity.polyline).toBeUndefined(true); expect(entity.wall).toBeDefined(); const positions = entity.wall.positions.getValue(import__77.Iso8601.MINIMUM_VALUE); expect(positions).toEqualEpsilon( [import__77.Cartesian3.fromDegrees(1, 2, 3), import__77.Cartesian3.fromDegrees(4, 5, 6)], import__78.Math.EPSILON10 ); }); }); it("Geometry LineString: sets positions altitudeMode relativeToGround, can extrude, cannot tessellate", function() { const kml = ' relativeToGround 1 1 1,2,3 4,5,6 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); const entity = entities[0]; expect(entity.polyline).toBeUndefined(); expect(entity.wall).toBeDefined(); const positions = entity.wall.positions.getValue(import__77.Iso8601.MINIMUM_VALUE); expect(positions).toEqualEpsilon( [import__77.Cartesian3.fromDegrees(1, 2, 3), import__77.Cartesian3.fromDegrees(4, 5, 6)], import__78.Math.EPSILON10 ); }); }); it("Geometry LineString: sets positions altitudeMode absolute, can extrude, cannot tessellate", function() { const kml = ' absolute 1 1 1,2,3 4,5,6 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(1); const entity = entities[0]; expect(entity.polyline).toBeUndefined(); expect(entity.wall).toBeDefined(); const positions = entity.wall.positions.getValue(import__77.Iso8601.MINIMUM_VALUE); expect(positions).toEqualEpsilon( [import__77.Cartesian3.fromDegrees(1, 2, 3), import__77.Cartesian3.fromDegrees(4, 5, 6)], import__78.Math.EPSILON10 ); }); }); it("Geometry gx:Track: sets position and availability", function() { const kml = ' 2000-01-01T00:00:00Z 1 2 3 2000-01-01T00:00:01Z 4 5 6 2000-01-01T00:00:02Z 7 8 9 '; return import__77.KmlDataSource.load(parser.parseFromString(kml, "text/xml"), { clampToGround: true }).then(function(dataSource) { const time1 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:00Z"); const time2 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:01Z"); const time3 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:02Z"); const entity = dataSource.entities.values[0]; expect(entity.position.getValue(time1)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(1, 2, 3), import__78.Math.EPSILON12 ); expect(entity.position.getValue(time2)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(4, 5, 6), import__78.Math.EPSILON12 ); expect(entity.position.getValue(time3)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(7, 8, 9), import__78.Math.EPSILON12 ); expect(entity.billboard.heightReference.getValue(time1)).toEqual( import__77.HeightReference.CLAMP_TO_GROUND ); expect(entity.billboard.heightReference.getValue(time2)).toEqual( import__77.HeightReference.CLAMP_TO_GROUND ); expect(entity.billboard.heightReference.getValue(time3)).toEqual( import__77.HeightReference.CLAMP_TO_GROUND ); expect(entity.polyline).toBeUndefined(); expect(entity.availability.start).toEqual(time1); expect(entity.availability.stop).toEqual(time3); }); }); it("Geometry gx:Track: sets position clampToGround, cannot extrude", function() { const kml = ' clampToGround 1 2000-01-01T00:00:00Z 1 2 3 2000-01-01T00:00:01Z 4 5 6 2000-01-01T00:00:02Z 7 8 9 '; return import__77.KmlDataSource.load(parser.parseFromString(kml, "text/xml"), { clampToGround: true }).then(function(dataSource) { const time1 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:00Z"); const time2 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:01Z"); const time3 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:02Z"); const entity = dataSource.entities.values[0]; expect(entity.position.getValue(time1)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(1, 2, 3), import__78.Math.EPSILON12 ); expect(entity.position.getValue(time2)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(4, 5, 6), import__78.Math.EPSILON12 ); expect(entity.position.getValue(time3)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(7, 8, 9), import__78.Math.EPSILON12 ); expect(entity.billboard.heightReference.getValue(time1)).toEqual( import__77.HeightReference.CLAMP_TO_GROUND ); expect(entity.billboard.heightReference.getValue(time2)).toEqual( import__77.HeightReference.CLAMP_TO_GROUND ); expect(entity.billboard.heightReference.getValue(time3)).toEqual( import__77.HeightReference.CLAMP_TO_GROUND ); expect(entity.polyline).toBeUndefined(); }); }); it("Geometry gx:Track: sets position altitudeMode absolute, can extrude", function() { const kml = ' absolute 1 2000-01-01T00:00:00Z 1 2 3 2000-01-01T00:00:01Z 4 5 6 2000-01-01T00:00:02Z 7 8 9 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const time1 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:00Z"); const time2 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:01Z"); const time3 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:02Z"); const entity = dataSource.entities.values[0]; expect(entity.position.getValue(time1)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(1, 2, 3), import__78.Math.EPSILON12 ); expect(entity.position.getValue(time2)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(4, 5, 6), import__78.Math.EPSILON12 ); expect(entity.position.getValue(time3)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(7, 8, 9), import__78.Math.EPSILON12 ); expect(entity.polyline.positions.getValue(time1)).toEqualEpsilon( [import__77.Cartesian3.fromDegrees(1, 2, 3), import__77.Cartesian3.fromDegrees(1, 2)], import__78.Math.EPSILON12 ); expect(entity.polyline.positions.getValue(time2)).toEqualEpsilon( [import__77.Cartesian3.fromDegrees(4, 5, 6), import__77.Cartesian3.fromDegrees(4, 5)], import__78.Math.EPSILON12 ); expect(entity.polyline.positions.getValue(time3)).toEqualEpsilon( [import__77.Cartesian3.fromDegrees(7, 8, 9), import__77.Cartesian3.fromDegrees(7, 8)], import__78.Math.EPSILON12 ); }); }); it("Geometry gx:Track: sets position altitudeMode relativeToGround, can extrude", function() { const kml = ' relativeToGround 1 2000-01-01T00:00:00Z 1 2 3 2000-01-01T00:00:01Z 4 5 6 2000-01-01T00:00:02Z 7 8 9 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const time1 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:00Z"); const time2 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:01Z"); const time3 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:02Z"); const entity = dataSource.entities.values[0]; expect(entity.position.getValue(time1)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(1, 2, 3), import__78.Math.EPSILON12 ); expect(entity.position.getValue(time2)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(4, 5, 6), import__78.Math.EPSILON12 ); expect(entity.position.getValue(time3)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(7, 8, 9), import__78.Math.EPSILON12 ); expect(entity.polyline.positions.getValue(time1)).toEqualEpsilon( [import__77.Cartesian3.fromDegrees(1, 2, 3), import__77.Cartesian3.fromDegrees(1, 2)], import__78.Math.EPSILON12 ); expect(entity.polyline.positions.getValue(time2)).toEqualEpsilon( [import__77.Cartesian3.fromDegrees(4, 5, 6), import__77.Cartesian3.fromDegrees(4, 5)], import__78.Math.EPSILON12 ); expect(entity.polyline.positions.getValue(time3)).toEqualEpsilon( [import__77.Cartesian3.fromDegrees(7, 8, 9), import__77.Cartesian3.fromDegrees(7, 8)], import__78.Math.EPSILON12 ); }); }); it("Geometry gx:Track: sets position and availability when missing values", function() { const kml = ' 2000-01-01T00:00:00Z 1 2 3 2000-01-01T00:00:01Z 4 5 6 2000-01-01T00:00:02Z '; return import__77.KmlDataSource.load(parser.parseFromString(kml, "text/xml"), { clampToGround: true }).then(function(dataSource) { const time1 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:00Z"); const time2 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:01Z"); const time3 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:02Z"); const entity = dataSource.entities.values[0]; expect(entity.position.getValue(time1)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(1, 2, 3), import__78.Math.EPSILON12 ); expect(entity.position.getValue(time2)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(4, 5, 6), import__78.Math.EPSILON12 ); expect(entity.position.getValue(time3)).toBeUndefined(); expect(entity.billboard.heightReference.getValue(time1)).toEqual( import__77.HeightReference.CLAMP_TO_GROUND ); expect(entity.billboard.heightReference.getValue(time2)).toEqual( import__77.HeightReference.CLAMP_TO_GROUND ); expect(entity.billboard.heightReference.getValue(time3)).toEqual( import__77.HeightReference.CLAMP_TO_GROUND ); expect(entity.availability.start).toEqual(time1); expect(entity.availability.stop).toEqual(time2); }); }); it("Geometry gx:MultiTrack: sets position and availability without interpolate", function() { const kml = ' 2000-01-01T00:00:00Z 1 2 3 2000-01-01T00:00:01Z 4 5 6 2000-01-01T00:00:02Z 6 5 4 2000-01-01T00:00:03Z 3 2 1 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const time1 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:00Z"); const time2 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:01Z"); const time3 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:02Z"); const time4 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:03Z"); const entity = dataSource.entities.values[0]; expect(entity.availability.length).toEqual(2); expect(entity.availability.get(0).start).toEqual(time1); expect(entity.availability.get(0).stop).toEqual(time2); expect(entity.availability.get(1).start).toEqual(time3); expect(entity.availability.get(1).stop).toEqual(time4); expect(entity.position.getValue(time1)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(1, 2), import__78.Math.EPSILON12 ); expect(entity.position.getValue(time2)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(4, 5), import__78.Math.EPSILON12 ); expect(entity.position.getValue(time3)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(6, 5), import__78.Math.EPSILON12 ); expect(entity.position.getValue(time4)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(3, 2), import__78.Math.EPSILON12 ); }); }); it("Geometry gx:MultiTrack: sets position and availability with interpolate", function() { const kml = ' 1 2000-01-01T00:00:00Z 1 2 3 2000-01-01T00:00:01Z 4 5 6 2000-01-01T00:00:02Z 6 5 4 2000-01-01T00:00:03Z 3 2 1 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const time1 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:00Z"); const time2 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:01Z"); const time3 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:02Z"); const time4 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:03Z"); const entity = dataSource.entities.values[0]; expect(entity.availability.length).toEqual(1); expect(entity.availability.get(0).start).toEqual(time1); expect(entity.availability.get(0).stop).toEqual(time4); expect(entity.position.getValue(time1)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(1, 2), import__78.Math.EPSILON12 ); expect(entity.position.getValue(time2)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(4, 5), import__78.Math.EPSILON12 ); expect(entity.position.getValue(time3)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(6, 5), import__78.Math.EPSILON12 ); expect(entity.position.getValue(time4)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(3, 2), import__78.Math.EPSILON12 ); }); }); it("Geometry gx:MultiTrack: sets position and availability altitudeMode absolute, extrude, with interpolate", function() { const kml = ' 1 absolute 1 2000-01-01T00:00:00Z 1 2 3 2000-01-01T00:00:01Z 4 5 6 absolute 1 2000-01-01T00:00:02Z 6 5 4 2000-01-01T00:00:03Z 3 2 1 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const time1 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:00Z"); const time2 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:01Z"); const time3 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:02Z"); const time4 = import__77.JulianDate.fromIso8601("2000-01-01T00:00:03Z"); const entity = dataSource.entities.values[0]; expect(entity.availability.length).toEqual(1); expect(entity.availability.get(0).start).toEqual(time1); expect(entity.availability.get(0).stop).toEqual(time4); expect(entity.position.getValue(time1)).toEqual( import__77.Cartesian3.fromDegrees(1, 2, 3) ); expect(entity.position.getValue(time2)).toEqual( import__77.Cartesian3.fromDegrees(4, 5, 6) ); expect(entity.position.getValue(time3)).toEqual( import__77.Cartesian3.fromDegrees(6, 5, 4) ); expect(entity.position.getValue(time4)).toEqual( import__77.Cartesian3.fromDegrees(3, 2, 1) ); }); }); it("Geometry MultiGeometry: sets expected properties", function() { const kml = ' TheName TheDescription 1,2 3,4 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities; expect(entities.values.length).toEqual(3); const multi = entities.getById("testID"); expect(multi).toBeDefined(); const point1 = entities.getById("testIDpoint1"); expect(point1).toBeDefined(); expect(point1.parent).toBe(multi); expect(point1.name).toBe(multi.name); expect(point1.description).toBe(multi.description); expect(point1.kml).toBe(multi.kml); expect(point1.position.getValue(import__77.Iso8601.MINIMUM_VALUE)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(1, 2), import__78.Math.EPSILON13 ); const point2 = entities.getById("testIDpoint2"); expect(point2).toBeDefined(); expect(point2.parent).toBe(multi); expect(point2.name).toBe(multi.name); expect(point2.description).toBe(multi.description); expect(point2.kml).toBe(multi.kml); expect(point2.position.getValue(import__77.Iso8601.MINIMUM_VALUE)).toEqualEpsilon( import__77.Cartesian3.fromDegrees(3, 4), import__78.Math.EPSILON13 ); }); }); it("NetworkLink: Loads data", function() { return import__77.KmlDataSource.load("Data/KML/networkLink.kml", options).then( function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(2); expect(entities[0].id).toEqual("link"); expect(entities[1].parent).toBe(entities[0]); } ); }); it("NetworkLink: onInterval", function() { const kml = ' ./Data/KML/refresh.kml onInterval 1 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(3); const link1 = entities[0]; const folder1 = entities[1]; const placemark1 = entities[2]; expect(link1.id).toEqual("link"); expect(folder1.parent).toBe(link1); expect(placemark1.parent).toBe(folder1); const spy = jasmine.createSpy("refreshEvent"); dataSource.refreshEvent.addEventListener(spy); return pollToPromise_default(function() { dataSource.update(0); return spy.calls.count() > 0; }).then(function() { expect(spy).toHaveBeenCalledWith(dataSource, expectedRefreshLinkHref); expect(entities.length).toEqual(3); const link2 = entities[0]; const folder2 = entities[1]; const placemark2 = entities[2]; expect(link2.id).toEqual("link"); expect(folder2.parent).toBe(link2); expect(placemark2.parent).toBe(folder2); expect(link2).toEqual(link2); expect(folder2).not.toEqual(folder1); expect(placemark2).not.toEqual(placemark1); }); }); }); it("NetworkLink: onExpire", function() { const kml = ' ./Data/KML/refresh.kml onExpire '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(3); const link1 = entities[0]; const folder1 = entities[1]; const placemark1 = entities[2]; expect(link1.id).toEqual("link"); expect(folder1.parent).toBe(link1); expect(placemark1.parent).toBe(folder1); const spy = jasmine.createSpy("refreshEvent"); dataSource.refreshEvent.addEventListener(spy); dataSource.update(0); return pollToPromise_default(function() { return spy.calls.count() > 0; }).then(function() { expect(spy).toHaveBeenCalledWith(dataSource, expectedRefreshLinkHref); expect(entities.length).toEqual(3); const link2 = entities[0]; const folder2 = entities[1]; const placemark2 = entities[2]; expect(link2.id).toEqual("link"); expect(folder2.parent).toBe(link2); expect(placemark2.parent).toBe(folder2); expect(link2).toEqual(link2); expect(folder2).not.toEqual(folder1); expect(placemark2).not.toEqual(placemark1); }); }); }); it("NetworkLink: onStop", function() { const kml = ' ./Data/KML/refresh.kml onStop '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), Object.assign({ canvas: uberCanvas, camera: uberCamera, options }) ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(3); const link1 = entities[0]; const folder1 = entities[1]; const placemark1 = entities[2]; expect(link1.id).toEqual("link"); expect(folder1.parent).toBe(link1); expect(placemark1.parent).toBe(folder1); const spy = jasmine.createSpy("refreshEvent"); dataSource.refreshEvent.addEventListener(spy); uberCamera.positionWC.x = 1; dataSource.update(0); return pollToPromise_default(function() { return spy.calls.count() > 0; }).then(function() { expect(spy).toHaveBeenCalledWith( dataSource, `${expectedRefreshLinkHref}?BBOX=-180%2C-90%2C180%2C90` ); expect(entities.length).toEqual(3); const link2 = entities[0]; const folder2 = entities[1]; const placemark2 = entities[2]; expect(link2.id).toEqual("link"); expect(folder2.parent).toBe(link2); expect(placemark2.parent).toBe(folder2); expect(link2).toEqual(link2); expect(folder2).not.toEqual(folder1); expect(placemark2).not.toEqual(placemark1); }); }); }); it("NetworkLink: Url is correct on initial load", function() { const kml = ' ./Data/KML/refresh.kml '; const requestNetworkLink = (0, import__77.defer)(); spyOn(import__77.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { requestNetworkLink.resolve(url); deferred.reject(); }); import__77.KmlDataSource.load(parser.parseFromString(kml, "text/xml"), options); return requestNetworkLink.promise.then(function(url) { expect(url).toEqual(expectedRefreshLinkHref); }); }); it("NetworkLink can accept invalid but common URL tag instead of Link", function() { const kml = ' ./Data/KML/refresh.kml '; const requestNetworkLink = (0, import__77.defer)(); spyOn(import__77.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { requestNetworkLink.resolve(url); deferred.reject(); }); import__77.KmlDataSource.load(parser.parseFromString(kml, "text/xml"), options); return requestNetworkLink.promise.then(function(url) { expect(url).toEqual(expectedRefreshLinkHref); }); }); it("NetworkLink: Url is correct on initial load with onStop defaults", function() { const kml = ' ./Data/KML/refresh.kml onStop '; const requestNetworkLink = (0, import__77.defer)(); spyOn(import__77.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { requestNetworkLink.resolve(url); deferred.reject(); }); import__77.KmlDataSource.load(parser.parseFromString(kml, "text/xml"), options); return requestNetworkLink.promise.then(function(url) { expect(url).toEqual( `${expectedRefreshLinkHref}?BBOX=-180%2C-90%2C180%2C90` ); }); }); it("NetworkLink: Url is correct on initial load with httpQuery without a ?", function() { const kml = ' ./Data/KML/refresh.kml onInterval client=[clientName]-v[clientVersion]&v=[kmlVersion]&lang=[language] '; const requestNetworkLink = (0, import__77.defer)(); spyOn(import__77.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { requestNetworkLink.resolve(url); deferred.reject(); }); import__77.KmlDataSource.load(parser.parseFromString(kml, "text/xml"), options); return requestNetworkLink.promise.then(function(url) { expect(url).toEqual( `${expectedRefreshLinkHref}?client=Cesium-v1&v=2.2&lang=English` ); }); }); it("NetworkLink: Url is correct on initial load with httpQuery with a ?", function() { const kml = ' ./Data/KML/refresh.kml onInterval ?client=[clientName]-v[clientVersion]&v=[kmlVersion]&lang=[language] '; const requestNetworkLink = (0, import__77.defer)(); spyOn(import__77.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { requestNetworkLink.resolve(url); deferred.reject(); }); import__77.KmlDataSource.load(parser.parseFromString(kml, "text/xml"), options); return requestNetworkLink.promise.then(function(url) { expect(url).toEqual( `${expectedRefreshLinkHref}?client=Cesium-v1&v=2.2&lang=English` ); }); }); it("NetworkLink: Url is correct on initial load with viewFormat without a ?", function() { const kml = ' ./Data/KML/refresh.kml onInterval BBOX=[bboxWest],[bboxSouth],[bboxEast],[bboxNorth];CAMERA=[lookatLon],[lookatLat],[lookatRange],[lookatTilt],[lookatHeading];VIEW=[horizFov],[vertFov],[horizPixels],[vertPixels],[terrainEnabled] '; const requestNetworkLink = (0, import__77.defer)(); spyOn(import__77.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { requestNetworkLink.resolve(url); deferred.reject(); }); import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), Object.assign({ camera: uberCamera, canvas: uberCanvas }, options) ); return requestNetworkLink.promise.then(function(url) { expect(url).toEqual( `${expectedRefreshLinkHref}?BBOX=-180%2C-90%2C180%2C90&CAMERA=0%2C0%2C6378137%2C0%2C0&VIEW=45%2C45%2C512%2C512%2C1` ); }); }); it("NetworkLink: Url is correct on initial load with viewFormat with a ?", function() { const kml = ' ./Data/KML/refresh.kml onInterval ?BBOX=[bboxWest],[bboxSouth],[bboxEast],[bboxNorth];CAMERA=[lookatLon],[lookatLat],[lookatRange],[lookatTilt],[lookatHeading];VIEW=[horizFov],[vertFov],[horizPixels],[vertPixels],[terrainEnabled] '; const requestNetworkLink = (0, import__77.defer)(); spyOn(import__77.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { requestNetworkLink.resolve(url); deferred.reject(); }); const src = new import__77.KmlDataSource(); src.camera = uberCamera; src.canvas = uberCanvas; src.load(parser.parseFromString(kml, "text/xml"), options); return requestNetworkLink.promise.then(function(url) { expect(url).toEqual( `${expectedRefreshLinkHref}?BBOX=-180%2C-90%2C180%2C90&CAMERA=0%2C0%2C6378137%2C0%2C0&VIEW=45%2C45%2C512%2C512%2C1` ); }); }); it("NetworkLink: Url is correct on initial load with viewFormat and httpQuery", function() { const kml = ' ./Data/KML/refresh.kml onInterval vf=1 hq=1 '; const requestNetworkLink = (0, import__77.defer)(); spyOn(import__77.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { requestNetworkLink.resolve(url); deferred.reject(); }); import__77.KmlDataSource.load(parser.parseFromString(kml, "text/xml"), options); return requestNetworkLink.promise.then(function(url) { expect(url).toEqual(`${expectedRefreshLinkHref}?hq=1&vf=1`); }); }); it("NetworkLink: onStop when no globe is in view", function() { const kml = ' ./Data/KML/refresh.kml onStop '; const ourOptions = { camera: { positionWC: new import__77.Cartesian3(0, 0, 0), directionWC: new import__77.Cartesian3(0, 0, 1), upWC: new import__77.Cartesian3(0, 1, 0), pitch: 0, heading: 0, frustum: { aspectRatio: 1, fov: import__78.Math.PI_OVER_FOUR }, computeViewRectangle: function() { return void 0; }, pickEllipsoid: function() { return void 0; } }, canvas: uberCanvas }; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), ourOptions ).then(function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toEqual(3); const link1 = entities[0]; const folder1 = entities[1]; const placemark1 = entities[2]; expect(link1.id).toEqual("link"); expect(folder1.parent).toBe(link1); expect(placemark1.parent).toBe(folder1); const spy = jasmine.createSpy("refreshEvent"); dataSource.refreshEvent.addEventListener(spy); ourOptions.camera.positionWC.x = 1; dataSource.update(0); return pollToPromise_default(function() { return spy.calls.count() > 0; }).then(function() { expect(spy).toHaveBeenCalledWith( dataSource, `${expectedRefreshLinkHref}?BBOX=0%2C0%2C0%2C0` ); expect(entities.length).toEqual(3); const link2 = entities[0]; const folder2 = entities[1]; const placemark2 = entities[2]; expect(link2.id).toEqual("link"); expect(folder2.parent).toBe(link2); expect(placemark2.parent).toBe(folder2); expect(link2).toEqual(link2); expect(folder2).not.toEqual(folder1); expect(placemark2).not.toEqual(placemark1); }); }); }); it("NetworkLink: timespan for network link", function() { const kml = ' ./Data/KML/simple.kml 2000-01-01 2000-01-03 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const start = import__77.JulianDate.fromIso8601("2000-01-01"); const stop = import__77.JulianDate.fromIso8601("2000-01-03"); const entities = dataSource.entities.values; expect(entities.length).toBe(2); const interval = entities[0].availability; expect(interval.start).toEqual(start); expect(interval.stop).toEqual(stop); expect(entities[0].availability).toEqual(entities[1].availability); }); }); it("NetworkLink: timestamp for network link", function() { const kml = ' ./Data/KML/simple.kml 2000-01-03 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const start = import__77.JulianDate.fromIso8601("2000-01-03"); const entities = dataSource.entities.values; expect(entities.length).toBe(2); const interval = entities[0].availability; expect(interval.start).toEqual(start); expect(interval.stop).toEqual(import__77.Iso8601.MAXIMUM_VALUE); expect(entities[0].availability).toEqual(entities[1].availability); }); }); it("NetworkLink: within a kmz file", function() { return import__77.KmlDataSource.load("Data/KML/multilevel.kmz", options).then( function(dataSource) { const entities = dataSource.entities.values; expect(entities.length).toBe(3); expect(entities[1].billboard).not.toBeNull(); expect(entities[1].position.getValue(import__77.Iso8601.MINIMUM_VALUE)).toEqual( import__77.Cartesian3.fromDegrees(1, 2, 3) ); expect(entities[0].parent).toBeUndefined(); expect(entities[2].parent).toBe(entities[0]); expect(entities[1].parent).toBe(entities[2]); } ); }); it("can load a KML file with explicit namespaces", function() { return import__77.KmlDataSource.load("Data/KML/namespaced.kml", options).then( function(dataSource) { expect(dataSource.entities.values.length).toBe(3); } ); }); it("can load styles from a KML file with namespaces", function() { return import__77.KmlDataSource.load("Data/KML/namespaced.kml", options).then( function(dataSource) { console.debug(dataSource.entities.values[2]); const polyline = dataSource.entities.values[2].polyline; const expectedColor = import__77.Color.fromBytes(255, 0, 255, 0); const polylineColor = polyline.material.color.getValue(); expect(polylineColor).toEqual(expectedColor); expect(polyline.width.getValue()).toEqual(10); } ); }); it("Boolean values can use true string", function() { const kml = ' relativeToGround 1 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon.perPositionHeight.getValue()).toEqual(true); }); }); it("Boolean values can use false string", function() { const kml = ' relativeToGround 1 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon.perPositionHeight.getValue()).toEqual(true); }); }); it("Properly finds the root feature node when it is not the first child of the KML node", function() { const kml = ' bob '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.name).toBe("bob"); expect(entity.label).toBeDefined(); expect(entity.label.text.getValue()).toBe("bob"); }); }); it("Has entity collection with link to data source", function() { const dataSource = new import__77.KmlDataSource(options); const entityCollection = dataSource.entities; expect(entityCollection.owner).toEqual(dataSource); }); it("Has entity with link to entity collection", function() { const kml = ' relativeToGround 1 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entityCollection = dataSource.entities; const entity = entityCollection.values[0]; expect(entity.entityCollection).toEqual(entityCollection); }); }); it("GroundOverlay Icon with refreshMode shows warning", function() { const kml = ' http://test.invalid/image.png onInterval '; spyOn(console, "warn").and.callThrough(); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.entities.values.length).toEqual(1); expect(console.warn.calls.count()).toEqual(1); expect(console.warn).toHaveBeenCalledWith( "KML - Unsupported Icon refreshMode: onInterval" ); }); }); it("GroundOverly Icon with viewRefreshMode shows warning", function() { const kml = ' http://test.invalid/image.png onStop '; spyOn(console, "warn").and.callThrough(); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.entities.values.length).toEqual(1); expect(console.warn.calls.count()).toEqual(1); expect(console.warn).toHaveBeenCalledWith( "KML - Unsupported Icon viewRefreshMode: onStop" ); }); }); it("GroundOverly Icon with gx:x, gx:y, gx:w, gx:h shows warning", function() { const kml = ' http://test.invalid/image.png 1 '; spyOn(console, "warn").and.callThrough(); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.entities.values.length).toEqual(1); expect(console.warn.calls.count()).toEqual(1); expect(console.warn).toHaveBeenCalledWith( "KML - gx:x, gx:y, gx:w, gx:h aren't supported for GroundOverlays" ); }); }); it("LineStyle with gx extensions show warnings", function() { const kml = ' 1,2,3 4,5,6 '; spyOn(console, "warn").and.callThrough(); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.entities.values.length).toEqual(1); expect(console.warn.calls.count()).toEqual(4); expect(console.warn.calls.argsFor(0)[0]).toBe( "KML - gx:outerColor is not supported in a LineStyle" ); expect(console.warn.calls.argsFor(1)[0]).toBe( "KML - gx:outerWidth is not supported in a LineStyle" ); expect(console.warn.calls.argsFor(2)[0]).toBe( "KML - gx:physicalWidth is not supported in a LineStyle" ); expect(console.warn.calls.argsFor(3)[0]).toBe( "KML - gx:labelVisibility is not supported in a LineStyle" ); }); }); it("Folder with radioFolder listItemType shows warning", function() { const kml = ' '; spyOn(console, "warn").and.callThrough(); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.entities.values.length).toEqual(1); expect(console.warn.calls.count()).toEqual(1); expect(console.warn).toHaveBeenCalledWith( "KML - Unsupported ListStyle with listItemType: radioFolder" ); }); }); it("StyleMap with highlighted key shows warning", function() { const kml = ' normal highlighted '; spyOn(console, "warn").and.callThrough(); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.entities.values.length).toEqual(1); expect(console.warn.calls.count()).toEqual(1); expect(console.warn).toHaveBeenCalledWith( "KML - Unsupported StyleMap key: highlighted" ); }); }); it("Linestrings with gx:drawOrder shows warning", function() { const kml = ' 1 1,2,3 4,5,6 '; spyOn(console, "warn").and.callThrough(); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.entities.values.length).toEqual(1); expect(console.warn.calls.count()).toEqual(1); expect(console.warn).toHaveBeenCalledWith( "KML - gx:drawOrder is not supported in LineStrings when clampToGround is false" ); }); }); it("gx:Track with gx:angles shows warning)", function() { const kml = ' 2000-01-01T00:00:00Z 1 2 3 4 5 6 '; spyOn(console, "warn").and.callThrough(); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.entities.values.length).toEqual(1); expect(console.warn.calls.count()).toEqual(1); expect(console.warn).toHaveBeenCalledWith( "KML - gx:angles are not supported in gx:Tracks" ); }); }); it("Model geometry shows warning)", function() { const kml = ' '; spyOn(console, "warn").and.callThrough(); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.entities.values.length).toEqual(1); expect(console.warn.calls.count()).toEqual(1); expect(console.warn).toHaveBeenCalledWith( "KML - Unsupported geometry: Model" ); }); }); it("ExtendedData with SchemaData or custom XML show warnings", function() { const kml = ' 1,2,3 4,5,6 '; spyOn(console, "warn").and.callThrough(); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.entities.values.length).toEqual(1); expect(console.warn.calls.count()).toEqual(2); expect(console.warn.calls.argsFor(0)[0]).toBe( "KML - SchemaData is unsupported" ); expect(console.warn.calls.argsFor(1)[0]).toBe( "KML - ExtendedData with xmlns:prefix is unsupported" ); }); }); it("Parse Camera and LookAt on features", function() { const kml = ' 1,2,3 4,5,6 -120 40 100 90 30 1250 '; spyOn(console, "warn").and.callThrough(); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.entities.values.length).toEqual(1); const placemark = dataSource.entities.values[0]; expect(placemark.kml.camera).toBeInstanceOf(import__77.KmlCamera); expect(placemark.kml.lookAt).toBeInstanceOf(import__77.KmlLookAt); expect(placemark.kml.lookAt.position).toEqual( import__77.Cartesian3.fromDegrees(-120, 40, 100) ); expect(placemark.kml.lookAt.headingPitchRange).toEqualEpsilon( new import__77.HeadingPitchRange( import__78.Math.toRadians(90), import__78.Math.toRadians(30 - 90), 1250 ), import__78.Math.EPSILON10 ); }); }); it("Features with a Region shows warning", function() { const kml = ' 1,2,3 4,5,6 '; spyOn(console, "warn").and.callThrough(); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.entities.values.length).toEqual(1); expect(console.warn.calls.count()).toEqual(1); expect(console.warn).toHaveBeenCalledWith( "KML - Placemark Regions are unsupported" ); }); }); it("NetworkLink with a viewRefreshMode=onRegion shows warning", function() { const kml = ' ./Data/KML/simple.kml onRegion '; spyOn(console, "warn").and.callThrough(); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.entities.values.length).toEqual(1); expect(console.warn.calls.count()).toEqual(1); expect(console.warn).toHaveBeenCalledWith( "KML - Unsupported viewRefreshMode: onRegion" ); }); }); it("Tour: reads gx:Tour)", function() { const kml = ' Tour 1 2 3 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.kmlTours.length).toEqual(1); const tour = dataSource.kmlTours[0]; expect(tour).toBeInstanceOf(import__77.KmlTour); expect(tour.name).toEqual("Tour 1"); expect(tour.id).toEqual("id_123"); expect(tour.playlist.length).toEqual(2); expect(tour.playlist[0].duration).toEqual(2); expect(tour.playlist[0]).toBeInstanceOf(import__77.KmlTourWait); expect(tour.playlist[1].duration).toEqual(3); expect(tour.playlist[1]).toBeInstanceOf(import__77.KmlTourFlyTo); }); }); it("Tour: reads LookAt and Camera", function() { const kml = ' 5 bounce 10 20 30 40 50 60 4.1 170.0 -43.0 9700 -10.0 33.5 20 '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.kmlTours.length).toEqual(1); const tour = dataSource.kmlTours[0]; expect(tour.playlist.length).toEqual(2); const flyto1 = tour.playlist[0]; const flyto2 = tour.playlist[1]; expect(flyto1.flyToMode).toEqual("bounce"); expect(flyto1.duration).toEqual(5); expect(flyto1.view).toBeInstanceOf(import__77.KmlLookAt); expect(flyto2.duration).toEqual(4.1); expect(flyto2.view).toBeInstanceOf(import__77.KmlCamera); expect(flyto1.view.position).toBeInstanceOf(import__77.Cartesian3); expect(flyto2.view.position).toBeInstanceOf(import__77.Cartesian3); expect(flyto1.view.headingPitchRange).toBeInstanceOf(import__77.HeadingPitchRange); expect(flyto2.view.headingPitchRoll).toBeInstanceOf(import__77.HeadingPitchRoll); }); }); it("Tour: log KML Tour unsupported nodes", function() { const kml = ' '; spyOn(console, "warn").and.callThrough(); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.kmlTours.length).toEqual(1); expect(dataSource.kmlTours[0].playlist.length).toEqual(0); expect(console.warn).toHaveBeenCalledWith( "KML Tour unsupported node AnimatedUpdate" ); expect(console.warn).toHaveBeenCalledWith( "KML Tour unsupported node TourControl" ); expect(console.warn).toHaveBeenCalledWith( "KML Tour unsupported node SoundCue" ); }); }); it("NetworkLink: onExpire without an expires shows warning", function() { const kml = ' ./Data/KML/simple.kml onExpire '; spyOn(console, "warn").and.callThrough(); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.entities.values.length).toEqual(2); expect(console.warn.calls.count()).toEqual(1); expect(console.warn).toHaveBeenCalledWith( "KML - refreshMode of onExpire requires the NetworkLinkControl to have an expires element" ); }); }); it("NetworkLink: Heading and pitch can be undefined if the camera is in morphing mode", function() { const kml = ' ./Data/KML/simple.kml onExpire '; const camera = createCamera_default({ offset: import__77.Cartesian3.fromDegrees(-110, 30, 1e3) }); import__77.Camera.clone(uberCamera, camera); const kmlOptions = { camera, canvas: uberCanvas }; camera._mode = import__77.SceneMode.MORPHING; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), kmlOptions ).then(function(dataSource) { expect(dataSource.entities.values.length).toEqual(2); }); }); it("when clampToGround is false, height isn't set if the polygon is extrudable", function() { const kml = ' relativeToGround '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon.perPositionHeight.getValue()).toEqual(true); expect(entity.polygon.height).toBeUndefined(); }); }); it("when clampToGround is false, height is set to 0 if polygon isn't extrudable", function() { const kml = ' clampToGround '; return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polygon.perPositionHeight).toBeUndefined(); expect(entity.polygon.height.getValue()).toEqual(0); }); }); it("when a LineString is clamped to ground and tesselated, entity has a polyline geometry and ColorProperty", function() { const kml = ' clampToGround true 1,2,3 4,5,6 '; const clampToGroundOptions = (0, import__77.combine)(options, { clampToGround: true }); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), clampToGroundOptions ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polyline).toBeDefined(); expect(entity.polyline.clampToGround.getValue()).toEqual(true); expect(entity.polyline.material).toBeInstanceOf(import__77.ColorMaterialProperty); }); }); it("when a LineString is clamped to ground and tesselated with z draworder, entity has a polyline geometry and ColorProperty", function() { const kml = ' clampToGround true 1,2,3 4,5,6 2 '; const clampToGroundOptions = (0, import__77.combine)(options, { clampToGround: true }); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), clampToGroundOptions ).then(function(dataSource) { const entity = dataSource.entities.values[0]; expect(entity.polyline).toBeDefined(); expect(entity.polyline.clampToGround.getValue()).toEqual(true); expect(entity.polyline.zIndex.getValue()).toBe(2); }); }); it("correctly uses random colors", function() { const kml = '\n\n\n\n\n\n\n#color2\n\n\n\n\n-89.52101149718367,44.23294548447373,0 -91.98408516538682,47.97512147591338,0 -96.92502046753899,45.42403256080313,0 -89.52101149718367,44.23294548447373,0 \n\n\n\n\n\n\n#color3\n\n\n\n\n-87.93623144974434,37.55775744070508,0 -89.46217805511263,41.26028180023913,0 -96.5546236391081,37.07597093222066,0 -87.93623144974434,37.55775744070508,0 \n\n\n\n\n\n\n#color4\n\n\n\n\n-104.347585776386,32.33288590150301,0 -103.8767557883591,37.6658714706182,0 -109.2704409486033,39.04706243328442,0 -104.347585776386,32.33288590150301,0 \n\n\n\n\n\n\n\n'; import__78.Math.setRandomNumberSeed(0); return import__77.KmlDataSource.load( parser.parseFromString(kml, "text/xml"), options ).then(function(dataSource) { expect(dataSource.entities.values.length).toEqual(4); expect( dataSource.entities.values[2].polygon.material.color.getValue() ).not.toEqual( dataSource.entities.values[3].polygon.material.color.getValue() ); }); }); }); // packages/engine/Specs/DataSources/KmlTourFlyToSpec.js var import__79 = __toESM(require_Cesium(), 1); var import__80 = __toESM(require_Cesium(), 1); describe("DataSources/KmlTourFlyTo", function() { it("generates camera options for KmlLookAt", function() { const position = import__79.Cartesian3.fromDegrees(40, 30, 1e3); const hpr = new import__79.HeadingPitchRange( import__80.Math.toRadians(10), import__80.Math.toRadians(45), 1e4 ); const flyto = new import__79.KmlTourFlyTo(10, "bounce", new import__79.KmlLookAt(position, hpr)); const options = flyto.getCameraOptions(); expect(options.duration).toEqual(10); expect(options.complete).toBeUndefined(); expect(options.easingFunction).toBeUndefined(); expect(options.offset).toBe(hpr); expect(options.destination).toBeUndefined(); expect(options.orientation).toBeUndefined(); }); it("generates camera options for KmlCamera", function() { const position = import__79.Cartesian3.fromDegrees(40, 30, 1e3); const hpr = new import__79.HeadingPitchRoll( import__80.Math.toRadians(10), import__80.Math.toRadians(45), 0 ); const flyto = new import__79.KmlTourFlyTo(10, "bounce", new import__79.KmlCamera(position, hpr)); const options = flyto.getCameraOptions(); expect(options.duration).toEqual(10); expect(options.complete).toBeUndefined(); expect(options.easingFunction).toBeUndefined(); expect(options.offset).toBeUndefined(); expect(options.destination.x).toEqual(position.x); expect(options.destination.y).toEqual(position.y); expect(options.destination.z).toEqual(position.z); expect(options.orientation).toBe(hpr); }); it("adds activeCallback to options", function() { const position = import__79.Cartesian3.fromDegrees(40, 30, 1e3); const hpr = new import__79.HeadingPitchRange( import__80.Math.toRadians(10), import__80.Math.toRadians(45), 1e4 ); const flyto = new import__79.KmlTourFlyTo(10, "bounce", new import__79.KmlLookAt(position, hpr)); flyto.activeCallback = jasmine.createSpy("activeCallback"); const options = flyto.getCameraOptions(); expect(options.complete).toBeDefined(); options.complete(); expect(options.complete).toHaveBeenCalled(); }); it("calls camera flyTo for KmlCamera", function() { const position = import__79.Cartesian3.fromDegrees(40, 30, 1e3); const hpr = new import__79.HeadingPitchRoll( import__80.Math.toRadians(10), import__80.Math.toRadians(45), 0 ); const flyto = new import__79.KmlTourFlyTo( 0.01, "bounce", new import__79.KmlCamera(position, hpr) ); const doneSpy = jasmine.createSpy("cameraDone"); const flyFake = jasmine.createSpy("flyTo").and.callFake(function(options) { if (options.complete) { options.complete(); } }); const fakeCamera = { flyTo: flyFake }; flyto.play(doneSpy, fakeCamera); return pollToPromise_default(function() { return doneSpy.calls.count() > 0; }).then(function() { expect(fakeCamera.flyTo).toHaveBeenCalled(); expect(fakeCamera.flyTo.calls.mostRecent().args[0].destination).toBe( position ); expect(fakeCamera.flyTo.calls.mostRecent().args[0].orientation).toBe(hpr); expect(doneSpy).toHaveBeenCalled(); }); }); it("calls camera flyToBoundingSphere for KmlLookAt", function() { const position = import__79.Cartesian3.fromDegrees(40, 30, 1e3); const hpr = new import__79.HeadingPitchRange( import__80.Math.toRadians(10), import__80.Math.toRadians(45), 1e4 ); const flyto = new import__79.KmlTourFlyTo( 0.01, "bounce", new import__79.KmlLookAt(position, hpr) ); const doneSpy = jasmine.createSpy("cameraDone"); const flyFake = jasmine.createSpy("flyToBoundingSphere").and.callFake(function(sphere, options) { if (options.complete) { options.complete(); } }); const fakeCamera = { flyToBoundingSphere: flyFake }; flyto.play(doneSpy, fakeCamera); return pollToPromise_default(function() { return doneSpy.calls.count() > 0; }).then(function() { expect(fakeCamera.flyToBoundingSphere).toHaveBeenCalled(); expect( fakeCamera.flyToBoundingSphere.calls.mostRecent().args[0].center.x ).toEqual(position.x); expect( fakeCamera.flyToBoundingSphere.calls.mostRecent().args[0].center.y ).toEqual(position.y); expect( fakeCamera.flyToBoundingSphere.calls.mostRecent().args[0].center.z ).toEqual(position.z); expect( fakeCamera.flyToBoundingSphere.calls.mostRecent().args[1].offset ).toBe(hpr); expect(doneSpy).toHaveBeenCalled(); }); }); }); // packages/engine/Specs/DataSources/KmlTourSpec.js var import__81 = __toESM(require_Cesium(), 1); describe("DataSources/KmlTour", function() { function getLookAt() { const position = import__81.Cartesian3.fromDegrees(40, 30, 1e3); const hpr = new import__81.HeadingPitchRange( import__81.Math.toRadians(10), import__81.Math.toRadians(45), 1e4 ); return new import__81.KmlLookAt(position, hpr); } function createMockWidget() { const mockWidget = {}; mockWidget.scene = {}; mockWidget.scene.camera = {}; mockWidget.scene.camera.flyTo = jasmine.createSpy("flyTo").and.callFake(function(options) { if (options.complete) { options.complete(); } }); mockWidget.scene.camera.flyToBoundingSphere = jasmine.createSpy("flyToBoundingSphere").and.callFake(function(boundingSphere, options) { if (options.complete) { options.complete(); } }); return mockWidget; } it("add entries to playlist", function() { const tour = new import__81.KmlTour("test", "test"); const wait = new import__81.KmlTourWait(10); const flyTo = new import__81.KmlTourFlyTo(5, null, getLookAt()); tour.addPlaylistEntry(wait); tour.addPlaylistEntry(flyTo); expect(tour.playlist.length).toEqual(2); expect(tour.playlist[0]).toBe(wait); expect(tour.playlist[1]).toBe(flyTo); }); it("calls entries play", function() { const waitSpy = spyOn(import__81.KmlTourWait.prototype, "play").and.callFake(function(callback) { callback(); }); const flySpy = spyOn(import__81.KmlTourFlyTo.prototype, "play").and.callFake(function(callback) { callback(); }); const tour = new import__81.KmlTour("test", "test"); const wait = new import__81.KmlTourWait(0.1); const flyTo = new import__81.KmlTourFlyTo(0.1, null, getLookAt()); tour.addPlaylistEntry(wait); tour.addPlaylistEntry(flyTo); const mockWidget = createMockWidget(); tour.play(mockWidget); return pollToPromise_default(function() { return waitSpy.calls.count() > 0 && flySpy.calls.count() > 0; }).then(function() { expect(waitSpy).toHaveBeenCalled(); expect(flySpy).toHaveBeenCalled(); }); }); it("calls events", function() { const tour = new import__81.KmlTour("test", "test"); const wait1 = new import__81.KmlTourWait(0.05); const wait2 = new import__81.KmlTourWait(0.02); const tourStart = jasmine.createSpy("TourStart"); const tourEnd = jasmine.createSpy("TourEnd"); const entryStart = jasmine.createSpy("EntryStart"); const entryEnd = jasmine.createSpy("EntryEnd"); tour.addPlaylistEntry(wait1); tour.addPlaylistEntry(wait2); tour.tourStart.addEventListener(tourStart); tour.tourEnd.addEventListener(tourEnd); tour.entryStart.addEventListener(entryStart); tour.entryEnd.addEventListener(entryEnd); tour.play(createMockWidget()); return pollToPromise_default(function() { return tourEnd.calls.count() > 0; }).then(function() { expect(tourStart).toHaveBeenCalled(); expect(entryStart).toHaveBeenCalled(); expect(entryEnd).toHaveBeenCalled(); expect(tourEnd).toHaveBeenCalledWith(false); }); }); it("terminates playback", function() { const tour = new import__81.KmlTour("test", "test"); const wait = new import__81.KmlTourWait(60); const flyTo = new import__81.KmlTourFlyTo(0.1, null, getLookAt()); const tourStart = jasmine.createSpy("TourStart"); const tourEnd = jasmine.createSpy("TourEnd"); const entryStart = jasmine.createSpy("EntryStart"); const entryEnd = jasmine.createSpy("EntryEnd"); tour.addPlaylistEntry(wait); tour.addPlaylistEntry(flyTo); tour.tourStart.addEventListener(tourStart); tour.tourEnd.addEventListener(tourEnd); tour.entryStart.addEventListener(entryStart); tour.entryEnd.addEventListener(entryEnd); const mockWidget = createMockWidget(); tour.play(mockWidget); setTimeout(function() { tour.stop(); expect(tourStart).toHaveBeenCalled(); expect(entryStart).toHaveBeenCalledWith(wait); expect(entryEnd).toHaveBeenCalledWith(wait, true); expect(tourEnd).toHaveBeenCalledWith(true); expect(entryStart.calls.count()).toEqual(1); expect(entryEnd.calls.count()).toEqual(1); expect(tourStart.calls.count()).toEqual(1); expect(tourEnd.calls.count()).toEqual(1); expect(mockWidget.scene.camera.flyTo.calls.count()).toEqual(0); expect(mockWidget.scene.camera.flyToBoundingSphere.calls.count()).toEqual( 0 ); }, 5); }); }); // packages/engine/Specs/DataSources/LabelGraphicsSpec.js var import__82 = __toESM(require_Cesium(), 1); describe("DataSources/LabelGraphics", function() { it("creates expected instance from raw assignment and construction", function() { const options = { text: "0", font: "1", style: import__82.LabelStyle.FILL, fillColor: import__82.Color.RED, outlineColor: import__82.Color.BLUE, outlineWidth: 2, horizontalOrigin: import__82.HorizontalOrigin.LEFT, verticalOrigin: import__82.VerticalOrigin.BOTTOM, eyeOffset: new import__82.Cartesian3(3, 4, 5), pixelOffset: new import__82.Cartesian2(6, 7), scale: 8, show: true, translucencyByDistance: new import__82.NearFarScalar(9, 10, 11, 12), pixelOffsetScaleByDistance: new import__82.NearFarScalar(13, 14, 15, 16), scaleByDistance: new import__82.NearFarScalar(17, 18, 19, 20), distanceDisplayCondition: new import__82.DistanceDisplayCondition(10, 100), disableDepthTestDistance: 10 }; const label = new import__82.LabelGraphics(options); expect(label.text).toBeInstanceOf(import__82.ConstantProperty); expect(label.font).toBeInstanceOf(import__82.ConstantProperty); expect(label.style).toBeInstanceOf(import__82.ConstantProperty); expect(label.fillColor).toBeInstanceOf(import__82.ConstantProperty); expect(label.outlineColor).toBeInstanceOf(import__82.ConstantProperty); expect(label.outlineWidth).toBeInstanceOf(import__82.ConstantProperty); expect(label.horizontalOrigin).toBeInstanceOf(import__82.ConstantProperty); expect(label.verticalOrigin).toBeInstanceOf(import__82.ConstantProperty); expect(label.eyeOffset).toBeInstanceOf(import__82.ConstantProperty); expect(label.scale).toBeInstanceOf(import__82.ConstantProperty); expect(label.show).toBeInstanceOf(import__82.ConstantProperty); expect(label.translucencyByDistance).toBeInstanceOf(import__82.ConstantProperty); expect(label.pixelOffsetScaleByDistance).toBeInstanceOf(import__82.ConstantProperty); expect(label.scaleByDistance).toBeInstanceOf(import__82.ConstantProperty); expect(label.distanceDisplayCondition).toBeInstanceOf(import__82.ConstantProperty); expect(label.disableDepthTestDistance).toBeInstanceOf(import__82.ConstantProperty); expect(label.text.getValue()).toEqual(options.text); expect(label.font.getValue()).toEqual(options.font); expect(label.style.getValue()).toEqual(options.style); expect(label.fillColor.getValue()).toEqual(options.fillColor); expect(label.outlineColor.getValue()).toEqual(options.outlineColor); expect(label.outlineWidth.getValue()).toEqual(options.outlineWidth); expect(label.horizontalOrigin.getValue()).toEqual(options.horizontalOrigin); expect(label.verticalOrigin.getValue()).toEqual(options.verticalOrigin); expect(label.eyeOffset.getValue()).toEqual(options.eyeOffset); expect(label.scale.getValue()).toEqual(options.scale); expect(label.show.getValue()).toEqual(options.show); expect(label.translucencyByDistance.getValue()).toEqual( options.translucencyByDistance ); expect(label.pixelOffsetScaleByDistance.getValue()).toEqual( options.pixelOffsetScaleByDistance ); expect(label.scaleByDistance.getValue()).toEqual(options.scaleByDistance); expect(label.distanceDisplayCondition.getValue()).toEqual( options.distanceDisplayCondition ); expect(label.disableDepthTestDistance.getValue()).toEqual( options.disableDepthTestDistance ); }); it("merge assigns unassigned properties", function() { const source = new import__82.LabelGraphics(); source.text = new import__82.ConstantProperty("not it"); source.font = new import__82.ConstantProperty("arial"); source.style = new import__82.ConstantProperty(import__82.LabelStyle.FILL); source.fillColor = new import__82.ConstantProperty(import__82.Color.BLACK); source.outlineColor = new import__82.ConstantProperty(import__82.Color.BLUE); source.outlineWidth = new import__82.ConstantProperty(5); source.horizontalOrigin = new import__82.ConstantProperty(import__82.HorizontalOrigin.LEFT); source.verticalOrigin = new import__82.ConstantProperty(import__82.VerticalOrigin.BOTTOM); source.eyeOffset = new import__82.ConstantProperty(import__82.Cartesian3.UNIT_Y); source.pixelOffset = new import__82.ConstantProperty(import__82.Cartesian2.UNIT_X); source.scale = new import__82.ConstantProperty(1); source.show = new import__82.ConstantProperty(false); source.translucencyByDistance = new import__82.ConstantProperty(new import__82.NearFarScalar()); source.pixelOffsetScaleByDistance = new import__82.ConstantProperty( new import__82.NearFarScalar(1, 0, 3e9, 0) ); source.scaleByDistance = new import__82.ConstantProperty( new import__82.NearFarScalar(1, 0, 3e9, 0) ); source.distanceDisplayCondition = new import__82.ConstantProperty( new import__82.DistanceDisplayCondition(10, 100) ); source.disableDepthTestDistance = new import__82.ConstantProperty(10); const target = new import__82.LabelGraphics(); target.merge(source); expect(target.text).toBe(source.text); expect(target.font).toBe(source.font); expect(target.style).toBe(source.style); expect(target.fillColor).toBe(source.fillColor); expect(target.outlineColor).toBe(source.outlineColor); expect(target.outlineWidth).toBe(source.outlineWidth); expect(target.horizontalOrigin).toBe(source.horizontalOrigin); expect(target.verticalOrigin).toBe(source.verticalOrigin); expect(target.eyeOffset).toBe(source.eyeOffset); expect(target.pixelOffset).toBe(source.pixelOffset); expect(target.scale).toBe(source.scale); expect(target.show).toBe(source.show); expect(target.translucencyByDistance).toBe(source.translucencyByDistance); expect(target.pixelOffsetScaleByDistance).toBe( source.pixelOffsetScaleByDistance ); expect(target.scaleByDistance).toBe(source.scaleByDistance); expect(target.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(target.disableDepthTestDistance).toBe( source.disableDepthTestDistance ); }); it("merge does not assign assigned properties", function() { const source = new import__82.LabelGraphics(); source.text = new import__82.ConstantProperty("not it"); source.font = new import__82.ConstantProperty("arial"); source.style = new import__82.ConstantProperty(import__82.LabelStyle.FILL); source.fillColor = new import__82.ConstantProperty(import__82.Color.BLACK); source.outlineColor = new import__82.ConstantProperty(import__82.Color.BLUE); source.outlineWidth = new import__82.ConstantProperty(5); source.horizontalOrigin = new import__82.ConstantProperty(import__82.HorizontalOrigin.LEFT); source.verticalOrigin = new import__82.ConstantProperty(import__82.VerticalOrigin.BOTTOM); source.eyeOffset = new import__82.ConstantProperty(import__82.Cartesian3.UNIT_Y); source.pixelOffset = new import__82.ConstantProperty(import__82.Cartesian2.UNIT_X); source.scale = new import__82.ConstantProperty(1); source.show = new import__82.ConstantProperty(false); source.translucencyByDistance = new import__82.ConstantProperty(new import__82.NearFarScalar()); source.pixelOffsetScaleByDistance = new import__82.ConstantProperty( new import__82.NearFarScalar(1, 0, 3e9, 0) ); source.scaleByDistance = new import__82.ConstantProperty( new import__82.NearFarScalar(1, 0, 3e9, 0) ); source.distanceDisplayCondition = new import__82.ConstantProperty( new import__82.DistanceDisplayCondition(10, 100) ); source.disableDepthTestDistance = new import__82.ConstantProperty(10); const text = new import__82.ConstantProperty("my text"); const font = new import__82.ConstantProperty("10px serif"); const style = new import__82.ConstantProperty(import__82.LabelStyle.OUTLINE); const fillColor = new import__82.ConstantProperty(import__82.Color.RED); const outlineColor = new import__82.ConstantProperty(import__82.Color.WHITE); const outlineWidth = new import__82.ConstantProperty(4); const horizontalOrigin = new import__82.ConstantProperty(import__82.HorizontalOrigin.RIGHT); const verticalOrigin = new import__82.ConstantProperty(import__82.VerticalOrigin.TOP); const eyeOffset = new import__82.ConstantProperty(import__82.Cartesian3.UNIT_Z); const pixelOffset = new import__82.ConstantProperty(import__82.Cartesian2.UNIT_Y); const scale = new import__82.ConstantProperty(2); const show = new import__82.ConstantProperty(true); const translucencyByDistance = new import__82.ConstantProperty(new import__82.NearFarScalar()); const pixelOffsetScaleByDistance = new import__82.ConstantProperty( new import__82.NearFarScalar() ); const scaleByDistance = new import__82.ConstantProperty(new import__82.NearFarScalar()); const distanceDisplayCondition = new import__82.ConstantProperty( new import__82.DistanceDisplayCondition() ); const disableDepthTestDistance = new import__82.ConstantProperty(20); const target = new import__82.LabelGraphics(); target.text = text; target.font = font; target.style = style; target.fillColor = fillColor; target.outlineColor = outlineColor; target.outlineWidth = outlineWidth; target.horizontalOrigin = horizontalOrigin; target.verticalOrigin = verticalOrigin; target.eyeOffset = eyeOffset; target.pixelOffset = pixelOffset; target.scale = scale; target.show = show; target.translucencyByDistance = translucencyByDistance; target.pixelOffsetScaleByDistance = pixelOffsetScaleByDistance; target.scaleByDistance = scaleByDistance; target.distanceDisplayCondition = distanceDisplayCondition; target.disableDepthTestDistance = disableDepthTestDistance; target.merge(source); expect(target.text).toBe(text); expect(target.font).toBe(font); expect(target.style).toBe(style); expect(target.fillColor).toBe(fillColor); expect(target.outlineColor).toBe(outlineColor); expect(target.outlineWidth).toBe(outlineWidth); expect(target.horizontalOrigin).toBe(horizontalOrigin); expect(target.verticalOrigin).toBe(verticalOrigin); expect(target.eyeOffset).toBe(eyeOffset); expect(target.pixelOffset).toBe(pixelOffset); expect(target.scale).toBe(scale); expect(target.show).toBe(show); expect(target.translucencyByDistance).toBe(translucencyByDistance); expect(target.pixelOffsetScaleByDistance).toBe(pixelOffsetScaleByDistance); expect(target.scaleByDistance).toBe(scaleByDistance); expect(target.distanceDisplayCondition).toBe(distanceDisplayCondition); expect(target.disableDepthTestDistance).toBe(disableDepthTestDistance); }); it("clone works", function() { const source = new import__82.LabelGraphics(); source.text = new import__82.ConstantProperty("not it"); source.font = new import__82.ConstantProperty("arial"); source.style = new import__82.ConstantProperty(import__82.LabelStyle.FILL); source.fillColor = new import__82.ConstantProperty(import__82.Color.BLACK); source.outlineColor = new import__82.ConstantProperty(import__82.Color.BLUE); source.outlineWidth = new import__82.ConstantProperty(5); source.horizontalOrigin = new import__82.ConstantProperty(import__82.HorizontalOrigin.LEFT); source.verticalOrigin = new import__82.ConstantProperty(import__82.VerticalOrigin.BOTTOM); source.eyeOffset = new import__82.ConstantProperty(import__82.Cartesian3.UNIT_Y); source.pixelOffset = new import__82.ConstantProperty(import__82.Cartesian2.UNIT_X); source.scale = new import__82.ConstantProperty(1); source.show = new import__82.ConstantProperty(false); source.translucencyByDistance = new import__82.ConstantProperty(new import__82.NearFarScalar()); source.pixelOffsetScaleByDistance = new import__82.ConstantProperty( new import__82.NearFarScalar(1, 0, 3e9, 0) ); source.scaleByDistance = new import__82.ConstantProperty( new import__82.NearFarScalar(1, 0, 3e9, 0) ); source.distanceDisplayCondition = new import__82.ConstantProperty( new import__82.DistanceDisplayCondition(10, 100) ); source.disableDepthTestDistance = new import__82.ConstantProperty(10); const result = source.clone(); expect(result.text).toBe(source.text); expect(result.font).toBe(source.font); expect(result.style).toBe(source.style); expect(result.fillColor).toBe(source.fillColor); expect(result.outlineColor).toBe(source.outlineColor); expect(result.outlineWidth).toBe(source.outlineWidth); expect(result.horizontalOrigin).toBe(source.horizontalOrigin); expect(result.verticalOrigin).toBe(source.verticalOrigin); expect(result.eyeOffset).toBe(source.eyeOffset); expect(result.pixelOffset).toBe(source.pixelOffset); expect(result.scale).toBe(source.scale); expect(result.show).toBe(source.show); expect(result.translucencyByDistance).toBe(source.translucencyByDistance); expect(result.pixelOffsetScaleByDistance).toBe( source.pixelOffsetScaleByDistance ); expect(result.scaleByDistance).toBe(source.scaleByDistance); expect(result.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(result.disableDepthTestDistance).toBe( source.disableDepthTestDistance ); }); it("merge throws if source undefined", function() { const target = new import__82.LabelGraphics(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/LabelVisualizerSpec.js var import__83 = __toESM(require_Cesium(), 1); describe( "DataSources/LabelVisualizer", function() { let scene2; let entityCluster; let visualizer; beforeAll(function() { scene2 = createScene_default(); scene2.globe = createGlobe_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { entityCluster = new import__83.EntityCluster(); entityCluster._initialize(scene2); }); afterEach(function() { if ((0, import__83.defined)(visualizer)) { visualizer = visualizer.destroy(); } entityCluster.destroy(); }); it("constructor throws if no scene is passed.", function() { expect(function() { return new import__83.LabelVisualizer(); }).toThrowDeveloperError(); }); it("update throws if no time specified.", function() { const entityCollection = new import__83.EntityCollection(); visualizer = new import__83.LabelVisualizer(entityCluster, entityCollection); expect(function() { visualizer.update(); }).toThrowDeveloperError(); }); it("isDestroy returns false until destroyed.", function() { const entityCollection = new import__83.EntityCollection(); visualizer = new import__83.LabelVisualizer(entityCluster, entityCollection); expect(visualizer.isDestroyed()).toEqual(false); visualizer.destroy(); expect(visualizer.isDestroyed()).toEqual(true); visualizer = void 0; }); it("removes the listener from the entity collection when destroyed", function() { const entityCollection = new import__83.EntityCollection(); visualizer = new import__83.LabelVisualizer(entityCluster, entityCollection); expect(entityCollection.collectionChanged.numberOfListeners).toEqual(1); visualizer.destroy(); expect(entityCollection.collectionChanged.numberOfListeners).toEqual(0); visualizer = void 0; }); it("object with no label does not create a label.", function() { const entityCollection = new import__83.EntityCollection(); visualizer = new import__83.LabelVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__83.ConstantProperty( new import__83.Cartesian3(1234, 5678, 9101112) ); visualizer.update(import__83.JulianDate.now()); expect(scene2.primitives.get(0)).toBeUndefined(); }); it("object with no position does not create a label.", function() { const entityCollection = new import__83.EntityCollection(); visualizer = new import__83.LabelVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); const label = testObject.label = new import__83.LabelGraphics(); label.show = new import__83.ConstantProperty(true); label.text = new import__83.ConstantProperty("lorum ipsum"); visualizer.update(import__83.JulianDate.now()); expect(scene2.primitives.get(0)).toBeUndefined(); }); it("object with no text does not create a label.", function() { const entityCollection = new import__83.EntityCollection(); visualizer = new import__83.LabelVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__83.ConstantProperty( new import__83.Cartesian3(1234, 5678, 9101112) ); const label = testObject.label = new import__83.LabelGraphics(); label.show = new import__83.ConstantProperty(true); visualizer.update(import__83.JulianDate.now()); expect(scene2.primitives.get(0)).toBeUndefined(); }); it("A LabelGraphics causes a label to be created and updated.", function() { const entityCollection = new import__83.EntityCollection(); visualizer = new import__83.LabelVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); const time2 = import__83.JulianDate.now(); const label = testObject.label = new import__83.LabelGraphics(); testObject.position = new import__83.ConstantProperty( new import__83.Cartesian3(1234, 5678, 9101112) ); label.text = new import__83.ConstantProperty("a"); label.font = new import__83.ConstantProperty("sans serif"); label.style = new import__83.ConstantProperty(import__83.LabelStyle.FILL); label.fillColor = new import__83.ConstantProperty(new import__83.Color(0.5, 0.8, 0.6, 0.7)); label.outlineColor = new import__83.ConstantProperty(new import__83.Color(0.4, 0.3, 0.2, 0.1)); label.outlineWidth = new import__83.ConstantProperty(4.5); label.horizontalOrigin = new import__83.ConstantProperty(import__83.HorizontalOrigin.RIGHT); label.verticalOrigin = new import__83.ConstantProperty(import__83.VerticalOrigin.TOP); label.eyeOffset = new import__83.ConstantProperty(new import__83.Cartesian3(1, 2, 3)); label.pixelOffset = new import__83.ConstantProperty(new import__83.Cartesian2(3, 2)); label.scale = new import__83.ConstantProperty(12.5); label.show = new import__83.ConstantProperty(true); label.translucencyByDistance = new import__83.ConstantProperty(new import__83.NearFarScalar()); label.pixelOffsetScaleByDistance = new import__83.ConstantProperty( new import__83.NearFarScalar() ); label.scaleByDistance = new import__83.ConstantProperty(new import__83.NearFarScalar()); label.distanceDisplayCondition = new import__83.ConstantProperty( new import__83.DistanceDisplayCondition() ); label.disableDepthTestDistance = new import__83.ConstantProperty(10); visualizer.update(time2); const labelCollection = entityCluster._labelCollection; expect(labelCollection.length).toEqual(1); const l = labelCollection.get(0); visualizer.update(time2); expect(l.position).toEqual(testObject.position.getValue(time2)); expect(l.text).toEqual(testObject.label.text.getValue(time2)); expect(l.font).toEqual(testObject.label.font.getValue(time2)); expect(l.style).toEqual(testObject.label.style.getValue(time2)); expect(l.fillColor).toEqual(testObject.label.fillColor.getValue(time2)); expect(l.outlineColor).toEqual( testObject.label.outlineColor.getValue(time2) ); expect(l.outlineWidth).toEqual( testObject.label.outlineWidth.getValue(time2) ); expect(l.horizontalOrigin).toEqual( testObject.label.horizontalOrigin.getValue(time2) ); expect(l.verticalOrigin).toEqual( testObject.label.verticalOrigin.getValue(time2) ); expect(l.eyeOffset).toEqual(testObject.label.eyeOffset.getValue(time2)); expect(l.pixelOffset).toEqual( testObject.label.pixelOffset.getValue(time2) ); expect(l.scale).toEqual(testObject.label.scale.getValue(time2)); expect(l.show).toEqual(testObject.label.show.getValue(time2)); expect(l.translucencyByDistance).toEqual( testObject.label.translucencyByDistance.getValue(time2) ); expect(l.pixelOffsetScaleByDistance).toEqual( testObject.label.pixelOffsetScaleByDistance.getValue(time2) ); expect(l.scaleByDistance).toEqual( testObject.label.scaleByDistance.getValue(time2) ); expect(l.distanceDisplayCondition).toEqual( testObject.label.distanceDisplayCondition.getValue(time2) ); expect(l.disableDepthTestDistance).toEqual( testObject.label.disableDepthTestDistance.getValue(time2) ); testObject.position = new import__83.ConstantProperty( new import__83.Cartesian3(5678, 1234, 1293434) ); label.text = new import__83.ConstantProperty("b"); label.font = new import__83.ConstantProperty("serif"); label.style = new import__83.ConstantProperty(import__83.LabelStyle.FILL_AND_OUTLINE); label.fillColor = new import__83.ConstantProperty(new import__83.Color(0.1, 0.2, 0.3, 0.4)); label.outlineColor = new import__83.ConstantProperty(new import__83.Color(0.8, 0.7, 0.6, 0.5)); label.outlineWidth = new import__83.ConstantProperty(0.5); label.horizontalOrigin = new import__83.ConstantProperty(import__83.HorizontalOrigin.CENTER); label.verticalOrigin = new import__83.ConstantProperty(import__83.VerticalOrigin.BOTTOM); label.eyeOffset = new import__83.ConstantProperty(new import__83.Cartesian3(3, 1, 2)); label.pixelOffset = new import__83.ConstantProperty(new import__83.Cartesian2(2, 3)); label.scale = new import__83.ConstantProperty(2.5); label.show = new import__83.ConstantProperty(true); label.translucencyByDistance = new import__83.ConstantProperty(new import__83.NearFarScalar()); label.pixelOffsetScaleByDistance = new import__83.ConstantProperty( new import__83.NearFarScalar() ); label.scaleByDistance = new import__83.ConstantProperty(new import__83.NearFarScalar()); label.distanceDisplayCondition = new import__83.ConstantProperty( new import__83.DistanceDisplayCondition() ); label.disableDepthTestDistance = new import__83.ConstantProperty(20); visualizer.update(time2); expect(l.position).toEqual(testObject.position.getValue(time2)); expect(l.text).toEqual(testObject.label.text.getValue(time2)); expect(l.font).toEqual(testObject.label.font.getValue(time2)); expect(l.style).toEqual(testObject.label.style.getValue(time2)); expect(l.fillColor).toEqual(testObject.label.fillColor.getValue(time2)); expect(l.outlineColor).toEqual( testObject.label.outlineColor.getValue(time2) ); expect(l.outlineWidth).toEqual( testObject.label.outlineWidth.getValue(time2) ); expect(l.horizontalOrigin).toEqual( testObject.label.horizontalOrigin.getValue(time2) ); expect(l.verticalOrigin).toEqual( testObject.label.verticalOrigin.getValue(time2) ); expect(l.eyeOffset).toEqual(testObject.label.eyeOffset.getValue(time2)); expect(l.pixelOffset).toEqual( testObject.label.pixelOffset.getValue(time2) ); expect(l.scale).toEqual(testObject.label.scale.getValue(time2)); expect(l.show).toEqual(testObject.label.show.getValue(time2)); expect(l.translucencyByDistance).toEqual( testObject.label.translucencyByDistance.getValue(time2) ); expect(l.pixelOffsetScaleByDistance).toEqual( testObject.label.pixelOffsetScaleByDistance.getValue(time2) ); expect(l.scaleByDistance).toEqual( testObject.label.scaleByDistance.getValue(time2) ); expect(l.distanceDisplayCondition).toEqual( testObject.label.distanceDisplayCondition.getValue(time2) ); expect(l.disableDepthTestDistance).toEqual( testObject.label.disableDepthTestDistance.getValue(time2) ); label.show = new import__83.ConstantProperty(false); visualizer.update(time2); }); it("Reuses primitives when hiding one and showing another", function() { const time2 = import__83.JulianDate.now(); const entityCollection = new import__83.EntityCollection(); visualizer = new import__83.LabelVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__83.ConstantProperty( new import__83.Cartesian3(1234, 5678, 9101112) ); testObject.label = new import__83.LabelGraphics(); testObject.label.text = new import__83.ConstantProperty("a"); testObject.label.show = new import__83.ConstantProperty(true); visualizer.update(time2); const labelCollection = entityCluster._labelCollection; expect(labelCollection.length).toEqual(1); testObject.label.show = new import__83.ConstantProperty(false); visualizer.update(time2); expect(labelCollection.length).toEqual(1); const testObject2 = entityCollection.getOrCreateEntity("test2"); testObject2.position = new import__83.ConstantProperty( new import__83.Cartesian3(1234, 5678, 9101112) ); testObject2.label = new import__83.LabelGraphics(); testObject2.label.text = new import__83.ConstantProperty("b"); testObject2.label.show = new import__83.ConstantProperty(true); visualizer.update(time2); expect(labelCollection.length).toEqual(1); }); it("clear hides labels.", function() { const entityCollection = new import__83.EntityCollection(); visualizer = new import__83.LabelVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); const time2 = import__83.JulianDate.now(); const label = testObject.label = new import__83.LabelGraphics(); testObject.position = new import__83.ConstantProperty( new import__83.Cartesian3(1234, 5678, 9101112) ); label.show = new import__83.ConstantProperty(true); label.text = new import__83.ConstantProperty("lorum ipsum"); visualizer.update(time2); const labelCollection = entityCluster._labelCollection; expect(labelCollection.length).toEqual(1); const l = labelCollection.get(0); expect(l.show).toEqual(true); entityCollection.removeAll(); visualizer.update(time2); expect(l.show).toEqual(false); expect(l.id).toBeUndefined(); }); it("Visualizer sets entity property.", function() { const entityCollection = new import__83.EntityCollection(); visualizer = new import__83.LabelVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); const time2 = import__83.JulianDate.now(); const label = testObject.label = new import__83.LabelGraphics(); testObject.position = new import__83.ConstantProperty( new import__83.Cartesian3(1234, 5678, 9101112) ); label.show = new import__83.ConstantProperty(true); label.text = new import__83.ConstantProperty("lorum ipsum"); visualizer.update(time2); const labelCollection = entityCluster._labelCollection; expect(labelCollection.length).toEqual(1); const l = labelCollection.get(0); expect(l.id).toEqual(testObject); }); it("Computes bounding sphere.", function() { const entityCollection = new import__83.EntityCollection(); visualizer = new import__83.LabelVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); const time2 = import__83.JulianDate.now(); const label = testObject.label = new import__83.LabelGraphics(); testObject.position = new import__83.ConstantProperty( new import__83.Cartesian3(1234, 5678, 9101112) ); label.show = new import__83.ConstantProperty(true); label.text = new import__83.ConstantProperty("lorum ipsum"); visualizer.update(time2); const result = new import__83.BoundingSphere(); const state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__83.BoundingSphereState.DONE); expect(result.center).toEqual(testObject.position.getValue()); expect(result.radius).toEqual(0); }); it("Fails bounding sphere for entity without billboard.", function() { const entityCollection = new import__83.EntityCollection(); const testObject = entityCollection.getOrCreateEntity("test"); visualizer = new import__83.LabelVisualizer(entityCluster, entityCollection); visualizer.update(import__83.JulianDate.now()); const result = new import__83.BoundingSphere(); const state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__83.BoundingSphereState.FAILED); }); it("Compute bounding sphere throws without entity.", function() { const entityCollection = new import__83.EntityCollection(); visualizer = new import__83.LabelVisualizer(entityCluster, entityCollection); const result = new import__83.BoundingSphere(); expect(function() { visualizer.getBoundingSphere(void 0, result); }).toThrowDeveloperError(); }); it("Compute bounding sphere throws without result.", function() { const entityCollection = new import__83.EntityCollection(); const testObject = entityCollection.getOrCreateEntity("test"); visualizer = new import__83.LabelVisualizer(entityCluster, entityCollection); expect(function() { visualizer.getBoundingSphere(testObject, void 0); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/DataSources/ModelGraphicsSpec.js var import__84 = __toESM(require_Cesium(), 1); describe("DataSources/ModelGraphics", function() { it("creates expected instance from raw assignment and construction", function() { const options = { uri: "0", scale: 1, show: false, minimumPixelSize: 2, maximumScale: 200, incrementallyLoadTextures: false, runAnimations: false, clampAnimations: false, shadows: import__84.ShadowMode.DISABLED, heightReference: import__84.HeightReference.CLAMP_TO_GROUND, distanceDisplayCondition: new import__84.DistanceDisplayCondition(), silhouetteColor: new import__84.Color(1, 0, 0, 1), silhouetteSize: 3, color: new import__84.Color(0, 1, 0, 0.2), colorBlendMode: import__84.ColorBlendMode.HIGHLIGHT, colorBlendAmount: 0.5, clippingPlanes: new import__84.ClippingPlaneCollection(), customShader: new import__84.CustomShader(), imageBasedLightingFactor: new import__84.Cartesian2(0.5, 0.5), lightColor: new import__84.Color(1, 1, 0, 1), nodeTransformations: { node1: { translation: import__84.Cartesian3.UNIT_Y, rotation: new import__84.Quaternion(0.5, 0.5, 0.5, 0.5), scale: import__84.Cartesian3.UNIT_X } }, articulations: { "articulation1 stage1": 45 } }; const model = new import__84.ModelGraphics(options); expect(model.uri).toBeInstanceOf(import__84.ConstantProperty); expect(model.scale).toBeInstanceOf(import__84.ConstantProperty); expect(model.show).toBeInstanceOf(import__84.ConstantProperty); expect(model.minimumPixelSize).toBeInstanceOf(import__84.ConstantProperty); expect(model.maximumScale).toBeInstanceOf(import__84.ConstantProperty); expect(model.incrementallyLoadTextures).toBeInstanceOf(import__84.ConstantProperty); expect(model.shadows).toBeInstanceOf(import__84.ConstantProperty); expect(model.heightReference).toBeInstanceOf(import__84.ConstantProperty); expect(model.distanceDisplayCondition).toBeInstanceOf(import__84.ConstantProperty); expect(model.silhouetteColor).toBeInstanceOf(import__84.ConstantProperty); expect(model.silhouetteSize).toBeInstanceOf(import__84.ConstantProperty); expect(model.color).toBeInstanceOf(import__84.ConstantProperty); expect(model.colorBlendMode).toBeInstanceOf(import__84.ConstantProperty); expect(model.colorBlendAmount).toBeInstanceOf(import__84.ConstantProperty); expect(model.clippingPlanes).toBeInstanceOf(import__84.ConstantProperty); expect(model.customShader).toBeInstanceOf(import__84.ConstantProperty); expect(model.imageBasedLightingFactor).toBeInstanceOf(import__84.ConstantProperty); expect(model.lightColor).toBeInstanceOf(import__84.ConstantProperty); expect(model.runAnimations).toBeInstanceOf(import__84.ConstantProperty); expect(model.clampAnimations).toBeInstanceOf(import__84.ConstantProperty); expect(model.nodeTransformations).toBeInstanceOf(import__84.PropertyBag); expect(model.articulations).toBeInstanceOf(import__84.PropertyBag); expect(model.uri.getValue()).toEqual(options.uri); expect(model.scale.getValue()).toEqual(options.scale); expect(model.show.getValue()).toEqual(options.show); expect(model.minimumPixelSize.getValue()).toEqual(options.minimumPixelSize); expect(model.maximumScale.getValue()).toEqual(options.maximumScale); expect(model.incrementallyLoadTextures.getValue()).toEqual( options.incrementallyLoadTextures ); expect(model.shadows.getValue()).toEqual(options.shadows); expect(model.heightReference.getValue()).toEqual(options.heightReference); expect(model.distanceDisplayCondition.getValue()).toEqual( options.distanceDisplayCondition ); expect(model.silhouetteColor.getValue()).toEqual(options.silhouetteColor); expect(model.silhouetteSize.getValue()).toEqual(options.silhouetteSize); expect(model.color.getValue()).toEqual(options.color); expect(model.colorBlendMode.getValue()).toEqual(options.colorBlendMode); expect(model.colorBlendAmount.getValue()).toEqual(options.colorBlendAmount); expect(model.clippingPlanes.getValue().planes).toEqual( options.clippingPlanes.planes ); expect(model.customShader.getValue()).toEqual(options.customShader); expect(model.imageBasedLightingFactor.getValue()).toEqual( options.imageBasedLightingFactor ); expect(model.lightColor.getValue()).toEqual(options.lightColor); expect(model.runAnimations.getValue()).toEqual(options.runAnimations); expect(model.clampAnimations.getValue()).toEqual(options.clampAnimations); let actualNodeTransformations = model.nodeTransformations.getValue( new import__84.JulianDate() ); let expectedNodeTransformations = options.nodeTransformations; actualNodeTransformations = JSON.parse( JSON.stringify(actualNodeTransformations) ); expectedNodeTransformations = JSON.parse( JSON.stringify(expectedNodeTransformations) ); expect(actualNodeTransformations).toEqual(expectedNodeTransformations); let actualArticulations = model.articulations.getValue(new import__84.JulianDate()); let expectedArticulations = options.articulations; actualArticulations = JSON.parse(JSON.stringify(actualArticulations)); expectedArticulations = JSON.parse(JSON.stringify(expectedArticulations)); expect(actualArticulations).toEqual(expectedArticulations); }); it("merge assigns unassigned properties", function() { const source = new import__84.ModelGraphics(); source.uri = new import__84.ConstantProperty(""); source.show = new import__84.ConstantProperty(true); source.scale = new import__84.ConstantProperty(1); source.minimumPixelSize = new import__84.ConstantProperty(2); source.maximumScale = new import__84.ConstantProperty(200); source.incrementallyLoadTextures = new import__84.ConstantProperty(true); source.shadows = new import__84.ConstantProperty(import__84.ShadowMode.ENABLED); source.heightReference = new import__84.ConstantProperty( import__84.HeightReference.CLAMP_TO_GROUND ); source.distanceDisplayCondition = new import__84.ConstantProperty( new import__84.DistanceDisplayCondition() ); source.silhouetteColor = new import__84.ConstantProperty( new import__84.Color(1, 0, 0, 1) ); source.silhouetteSize = new import__84.ConstantProperty(3); source.color = new import__84.ConstantProperty(new import__84.Color(0, 1, 0, 0.2)); source.colorBlendMode = new import__84.ConstantProperty(import__84.ColorBlendMode.HIGHLIGHT); source.colorBlendAmount = new import__84.ConstantProperty(0.5); source.clippingPlanes = new import__84.ConstantProperty(new import__84.ClippingPlaneCollection()); source.customShader = new import__84.ConstantProperty(new import__84.CustomShader()); source.imageBasedLightingFactor = new import__84.ConstantProperty( new import__84.Cartesian2(0.5, 0.5) ); source.lightColor = new import__84.ConstantProperty(new import__84.Color(1, 1, 0, 1)); source.runAnimations = new import__84.ConstantProperty(true); source.clampAnimations = new import__84.ConstantProperty(true); source.nodeTransformations = { node1: new import__84.NodeTransformationProperty({ translation: import__84.Cartesian3.UNIT_Y, rotation: new import__84.Quaternion(0.5, 0.5, 0.5, 0.5), scale: import__84.Cartesian3.UNIT_X }), node2: new import__84.NodeTransformationProperty({ scale: import__84.Cartesian3.UNIT_Z }) }; source.articulations = { "a1 s1": 10, "a2 s2": 20 }; const target = new import__84.ModelGraphics(); target.merge(source); expect(target.uri).toBe(source.uri); expect(target.show).toBe(source.show); expect(target.scale).toBe(source.scale); expect(target.minimumPixelSize).toBe(source.minimumPixelSize); expect(target.maximumScale).toBe(source.maximumScale); expect(target.incrementallyLoadTextures).toBe( source.incrementallyLoadTextures ); expect(target.shadows).toBe(source.shadows); expect(target.heightReference).toBe(source.heightReference); expect(target.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(target.silhouetteColor).toEqual(source.silhouetteColor); expect(target.silhouetteSize).toEqual(source.silhouetteSize); expect(target.color).toBe(source.color); expect(target.colorBlendMode).toBe(source.colorBlendMode); expect(target.colorBlendAmount).toBe(source.colorBlendAmount); expect(target.clippingPlanes).toBe(source.clippingPlanes); expect(target.customShader).toBe(source.customShader); expect(target.imageBasedLightingFactor).toBe( source.imageBasedLightingFactor ); expect(target.lightColor).toBe(source.lightColor); expect(target.runAnimations).toBe(source.runAnimations); expect(target.clampAnimations).toBe(source.clampAnimations); expect(target.nodeTransformations).toEqual(source.nodeTransformations); expect(target.articulations).toEqual(source.articulations); }); it("merge does not assign assigned properties", function() { const source = new import__84.ModelGraphics(); source.uri = new import__84.ConstantProperty(""); source.show = new import__84.ConstantProperty(true); source.scale = new import__84.ConstantProperty(1); source.minimumPixelSize = new import__84.ConstantProperty(2); source.maximumScale = new import__84.ConstantProperty(200); source.incrementallyLoadTextures = new import__84.ConstantProperty(true); source.shadows = new import__84.ConstantProperty(import__84.ShadowMode.ENABLED); source.heightReference = new import__84.ConstantProperty( import__84.HeightReference.CLAMP_TO_GROUND ); source.distanceDisplayCondition = new import__84.ConstantProperty( new import__84.DistanceDisplayCondition() ); source.silhouetteColor = new import__84.ConstantProperty(new import__84.Color()); source.silhouetteSize = new import__84.ConstantProperty(1); source.color = new import__84.ConstantProperty(new import__84.Color(0, 1, 0, 0.2)); source.colorBlendMode = new import__84.ConstantProperty(import__84.ColorBlendMode.HIGHLIGHT); source.colorBlendAmount = new import__84.ConstantProperty(0.5); source.clippingPlanes = new import__84.ConstantProperty(new import__84.ClippingPlaneCollection()); source.customShader = new import__84.ConstantProperty(new import__84.CustomShader()); source.imageBasedLightingFactor = new import__84.ConstantProperty( new import__84.Cartesian2(0.5, 0.5) ); source.lightColor = new import__84.ConstantProperty(new import__84.Color(1, 1, 0, 1)); source.runAnimations = new import__84.ConstantProperty(true); source.clampAnimations = new import__84.ConstantProperty(true); source.nodeTransformations = { transform: new import__84.NodeTransformationProperty() }; source.articulations = { "a1 s1": 10, "a2 s2": 20 }; const uri = new import__84.ConstantProperty(""); const show = new import__84.ConstantProperty(true); const scale = new import__84.ConstantProperty(1); const minimumPixelSize = new import__84.ConstantProperty(2); const maximumScale = new import__84.ConstantProperty(200); const incrementallyLoadTextures = new import__84.ConstantProperty(true); const shadows = new import__84.ConstantProperty(import__84.ShadowMode.ENABLED); const heightReference = new import__84.ConstantProperty( import__84.HeightReference.CLAMP_TO_GROUND ); const distanceDisplayCondition = new import__84.ConstantProperty( new import__84.DistanceDisplayCondition() ); const silhouetteColor = new import__84.ConstantProperty(new import__84.Color()); const silhouetteSize = new import__84.ConstantProperty(1); const color = new import__84.ConstantProperty(new import__84.Color(0, 1, 0, 0.2)); const colorBlendMode = new import__84.ConstantProperty(import__84.ColorBlendMode.HIGHLIGHT); const colorBlendAmount = new import__84.ConstantProperty(0.5); const clippingPlanes = new import__84.ConstantProperty(new import__84.ClippingPlaneCollection()); const customShader = new import__84.ConstantProperty(new import__84.CustomShader()); const imageBasedLightingFactor = new import__84.ConstantProperty( new import__84.Cartesian2(0.5, 0.5) ); const lightColor = new import__84.ConstantProperty(new import__84.Color(1, 1, 0, 1)); const runAnimations = new import__84.ConstantProperty(true); const clampAnimations = new import__84.ConstantProperty(true); const nodeTransformations = new import__84.PropertyBag({ transform: new import__84.NodeTransformationProperty() }); const articulations = new import__84.PropertyBag({ "a1 s1": 10, "a2 s2": 20 }); const target = new import__84.ModelGraphics(); target.uri = uri; target.show = show; target.scale = scale; target.minimumPixelSize = minimumPixelSize; target.maximumScale = maximumScale; target.incrementallyLoadTextures = incrementallyLoadTextures; target.shadows = shadows; target.heightReference = heightReference; target.distanceDisplayCondition = distanceDisplayCondition; target.silhouetteColor = silhouetteColor; target.silhouetteSize = silhouetteSize; target.color = color; target.colorBlendMode = colorBlendMode; target.colorBlendAmount = colorBlendAmount; target.clippingPlanes = clippingPlanes; target.customShader = customShader; target.imageBasedLightingFactor = imageBasedLightingFactor; target.lightColor = lightColor; target.runAnimations = runAnimations; target.clampAnimations = clampAnimations; target.nodeTransformations = nodeTransformations; target.articulations = articulations; target.merge(source); expect(target.uri).toBe(uri); expect(target.show).toBe(show); expect(target.scale).toBe(scale); expect(target.minimumPixelSize).toBe(minimumPixelSize); expect(target.maximumScale).toBe(maximumScale); expect(target.incrementallyLoadTextures).toBe(incrementallyLoadTextures); expect(target.shadows).toBe(shadows); expect(target.heightReference).toBe(heightReference); expect(target.distanceDisplayCondition).toBe(distanceDisplayCondition); expect(target.silhouetteColor).toBe(silhouetteColor); expect(target.silhouetteSize).toBe(silhouetteSize); expect(target.color).toBe(color); expect(target.colorBlendMode).toBe(colorBlendMode); expect(target.colorBlendAmount).toBe(colorBlendAmount); expect(target.clippingPlanes).toBe(clippingPlanes); expect(target.customShader).toBe(customShader); expect(target.imageBasedLightingFactor).toBe(imageBasedLightingFactor); expect(target.lightColor).toBe(lightColor); expect(target.runAnimations).toBe(runAnimations); expect(target.clampAnimations).toBe(clampAnimations); expect(target.nodeTransformations).toBe(nodeTransformations); expect(target.articulations).toBe(articulations); }); it("clone works", function() { const source = new import__84.ModelGraphics(); source.uri = new import__84.ConstantProperty(""); source.show = new import__84.ConstantProperty(true); source.scale = new import__84.ConstantProperty(1); source.minimumPixelSize = new import__84.ConstantProperty(2); source.maximumScale = new import__84.ConstantProperty(200); source.incrementallyLoadTextures = new import__84.ConstantProperty(true); source.shadows = new import__84.ConstantProperty(import__84.ShadowMode.ENABLED); source.heightReference = new import__84.ConstantProperty( import__84.HeightReference.CLAMP_TO_GROUND ); source.distanceDisplayCondition = new import__84.ConstantProperty( new import__84.DistanceDisplayCondition() ); source.silhouetteColor = new import__84.ConstantProperty(new import__84.Color()); source.silhouetteSize = new import__84.ConstantProperty(2); source.color = new import__84.ConstantProperty(new import__84.Color(0, 1, 0, 0.2)); source.colorBlendMode = new import__84.ConstantProperty(import__84.ColorBlendMode.HIGHLIGHT); source.colorBlendAmount = new import__84.ConstantProperty(0.5); source.clippingPlanes = new import__84.ConstantProperty(new import__84.ClippingPlaneCollection()); source.customShader = new import__84.ConstantProperty(new import__84.CustomShader()); source.imageBasedLightingFactor = new import__84.ConstantProperty( new import__84.Cartesian2(0.5, 0.5) ); source.lightColor = new import__84.ConstantProperty(new import__84.Color(1, 1, 0, 1)); source.runAnimations = new import__84.ConstantProperty(true); source.clampAnimations = new import__84.ConstantProperty(true); source.nodeTransformations = { node1: new import__84.NodeTransformationProperty(), node2: new import__84.NodeTransformationProperty() }; source.articulations = { "a1 s1": 10, "a2 s2": 20 }; const result = source.clone(); expect(result.uri).toBe(source.uri); expect(result.show).toBe(source.show); expect(result.scale).toBe(source.scale); expect(result.minimumPixelSize).toBe(source.minimumPixelSize); expect(result.maximumScale).toBe(source.maximumScale); expect(result.incrementallyLoadTextures).toBe( source.incrementallyLoadTextures ); expect(result.shadows).toBe(source.shadows); expect(result.heightReference).toBe(source.heightReference); expect(result.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(result.silhouetteColor).toEqual(source.silhouetteColor); expect(result.silhouetteSize).toEqual(source.silhouetteSize); expect(result.color).toBe(source.color); expect(result.colorBlendMode).toBe(source.colorBlendMode); expect(result.colorBlendAmount).toBe(source.colorBlendAmount); expect(result.clippingPlanes).toBe(source.clippingPlanes); expect(result.customShader).toBe(source.customShader); expect(result.imageBasedLightingFactor).toBe( source.imageBasedLightingFactor ); expect(result.lightColor).toBe(source.lightColor); expect(result.runAnimations).toBe(source.runAnimations); expect(result.clampAnimations).toBe(source.clampAnimations); expect(result.nodeTransformations).toEqual(source.nodeTransformations); expect(result.articulations).toEqual(source.articulations); }); it("merge throws if source undefined", function() { const target = new import__84.ModelGraphics(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/ModelVisualizerSpec.js var import__85 = __toESM(require_Cesium(), 1); describe( "DataSources/ModelVisualizer", function() { const boxUrl = "./Data/Models/glTF-2.0/BoxTextured/glTF/BoxTextured.gltf"; const boxArticulationsUrl = "./Data/Models/glTF-2.0/BoxArticulations/glTF/BoxArticulations.gltf"; let scene2; let entityCollection; let visualizer; beforeAll(function() { scene2 = createScene_default(); }); beforeEach(function() { scene2.globe = new import__85.Globe(); entityCollection = new import__85.EntityCollection(); visualizer = new import__85.ModelVisualizer(scene2, entityCollection); }); afterEach(function() { visualizer = visualizer && visualizer.destroy(); entityCollection.removeAll(); scene2.primitives.removeAll(); }); afterAll(function() { scene2.destroyForSpecs(); }); it("constructor throws if no scene is passed", function() { expect(function() { return new import__85.ModelVisualizer(void 0, entityCollection); }).toThrowDeveloperError(); }); it("constructor throws if no entityCollection is passed", function() { expect(function() { return new import__85.ModelVisualizer(scene2, void 0); }).toThrowDeveloperError(); }); it("update throws if no time specified", function() { expect(function() { visualizer.update(); }).toThrowDeveloperError(); }); it("isDestroy returns false until destroyed", function() { expect(visualizer.isDestroyed()).toEqual(false); visualizer.destroy(); expect(visualizer.isDestroyed()).toEqual(true); visualizer = void 0; }); it("removes the listener from the entity collection when destroyed", function() { expect(entityCollection.collectionChanged.numberOfListeners).toEqual(1); visualizer.destroy(); expect(entityCollection.collectionChanged.numberOfListeners).toEqual(0); visualizer = void 0; }); it("object with no model does not create one", function() { const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__85.ConstantProperty( new import__85.Cartesian3(1234, 5678, 9101112) ); visualizer.update(import__85.JulianDate.now()); expect(scene2.primitives.length).toEqual(0); }); it("object with no position does not create a model", function() { const testObject = entityCollection.getOrCreateEntity("test"); const model = testObject.model = new import__85.ModelGraphics(); model.uri = new import__85.ConstantProperty(boxUrl); visualizer.update(import__85.JulianDate.now()); expect(scene2.primitives.length).toEqual(0); }); it("creates and updates a primitive from ModelGraphics", async function() { const time2 = import__85.JulianDate.now(); const model = new import__85.ModelGraphics(); model.show = new import__85.ConstantProperty(true); model.scale = new import__85.ConstantProperty(2); model.minimumPixelSize = new import__85.ConstantProperty(24); model.uri = new import__85.ConstantProperty(boxArticulationsUrl); model.distanceDisplayCondition = new import__85.ConstantProperty( new import__85.DistanceDisplayCondition(10, 100) ); const translation = new import__85.Cartesian3(1, 2, 3); const rotation = new import__85.Quaternion(0, 0.707, 0, 0.707); const scale = new import__85.Cartesian3(2, 2, 2); const nodeTransforms = { Root: new import__85.NodeTransformationProperty({ translation: new import__85.ConstantProperty(translation), rotation: new import__85.ConstantProperty(rotation), scale: new import__85.ConstantProperty(scale) }) }; model.nodeTransformations = nodeTransforms; const clippingPlanes = new import__85.ClippingPlaneCollection({ planes: [new import__85.ClippingPlane(import__85.Cartesian3.UNIT_X, 0)] }); model.clippingPlanes = new import__85.ConstantProperty(clippingPlanes); const customShader = new import__85.CustomShader(); model.customShader = new import__85.ConstantProperty(customShader); model.imageBasedLightingFactor = new import__85.ConstantProperty( new import__85.Cartesian2(0.5, 0.5) ); model.lightColor = new import__85.ConstantProperty(new import__85.Color(1, 1, 0, 1)); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__85.ConstantPositionProperty( import__85.Cartesian3.fromDegrees(1, 2, 3) ); testObject.model = model; visualizer.update(time2); let primitive; await pollToPromise_default(function() { primitive = scene2.primitives.get(0); return (0, import__85.defined)(primitive); }); visualizer.update(time2); expect(primitive.show).toEqual(true); expect(primitive.scale).toEqual(2); expect(primitive.minimumPixelSize).toEqual(24); expect(primitive.modelMatrix).toEqual( import__85.Transforms.eastNorthUpToFixedFrame( import__85.Cartesian3.fromDegrees(1, 2, 3), scene2.globe.ellipsoid ) ); expect(primitive.distanceDisplayCondition).toEqual( new import__85.DistanceDisplayCondition(10, 100) ); expect(primitive.clippingPlanes._planes.length).toEqual( clippingPlanes._planes.length ); expect( import__85.Cartesian3.equals( primitive.clippingPlanes._planes[0].normal, clippingPlanes._planes[0].normal ) ).toBe(true); expect(primitive.clippingPlanes._planes[0].distance).toEqual( clippingPlanes._planes[0].distance ); expect(primitive.customShader).toEqual(customShader); expect(primitive.imageBasedLighting.imageBasedLightingFactor).toEqual( new import__85.Cartesian2(0.5, 0.5) ); expect(primitive.lightColor).toEqual(new import__85.Cartesian3(1, 1, 0)); await pollToPromise_default(function() { scene2.render(); return primitive.ready; }); visualizer.update(time2); const node = primitive.getNode("Root"); expect(node).toBeDefined(); const transformationMatrix = import__85.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); import__85.Matrix4.multiplyTransformation( node.originalMatrix, transformationMatrix, transformationMatrix ); expect(node.matrix).toEqual(transformationMatrix); }); it("can apply model articulations", async function() { const time2 = import__85.JulianDate.now(); const model = new import__85.ModelGraphics(); model.uri = new import__85.ConstantProperty(boxArticulationsUrl); const articulations = { "SampleArticulation MoveX": 1, "SampleArticulation MoveY": 2, "SampleArticulation MoveZ": 3, "SampleArticulation Yaw": 4, "SampleArticulation Pitch": 5, "SampleArticulation Roll": 6, "SampleArticulation Size": 0.9, "SampleArticulation SizeX": 0.8, "SampleArticulation SizeY": 0.7, "SampleArticulation SizeZ": 0.6 }; model.articulations = articulations; const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__85.ConstantPositionProperty( import__85.Cartesian3.fromDegrees(1, 2, 3) ); testObject.model = model; visualizer.update(time2); let primitive; await pollToPromise_default(function() { primitive = scene2.primitives.get(0); return (0, import__85.defined)(primitive); }); await pollToPromise_default(function() { scene2.render(); return primitive.ready; }); visualizer.update(time2); const node = primitive.getNode("Root"); const expected = [ 0.7147690483240505, -0.04340611926232735, -0.0749741046529782, 0, -0.06188330295778636, 0.05906797312763484, -0.6241645867602773, 0, 0.03752515582279579, 0.5366347296529127, 0.04706410108373541, 0, 1, 3, -2, 1 ]; expect(node.matrix).toEqualEpsilon(expected, import__85.Math.EPSILON14); }); it("creates a primitive from ModelGraphics with a Resource", async function() { const time2 = import__85.JulianDate.now(); const model = new import__85.ModelGraphics(); model.show = new import__85.ConstantProperty(true); model.uri = new import__85.ConstantProperty( new import__85.Resource({ url: boxArticulationsUrl }) ); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__85.ConstantPositionProperty( import__85.Cartesian3.fromDegrees(1, 2, 3) ); testObject.model = model; visualizer.update(time2); let primitive; await pollToPromise_default(function() { primitive = scene2.primitives.get(0); return (0, import__85.defined)(primitive); }); await pollToPromise_default(function() { scene2.render(); return primitive.ready; }); visualizer.update(time2); const node = primitive.getNode("Root"); expect(node).toBeDefined(); }); it("removes primitives on Entity removal", async function() { const model = new import__85.ModelGraphics(); model.uri = new import__85.ConstantProperty(boxUrl); const time2 = import__85.JulianDate.now(); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__85.ConstantProperty( new import__85.Cartesian3(5678, 1234, 1101112) ); testObject.model = model; visualizer.update(time2); let primitive; await pollToPromise_default(function() { primitive = scene2.primitives.get(0); return (0, import__85.defined)(primitive); }); visualizer.update(time2); entityCollection.removeAll(); visualizer.update(time2); expect(scene2.primitives.length).toEqual(0); }); it("sets id property", async function() { const time2 = import__85.JulianDate.now(); const testObject = entityCollection.getOrCreateEntity("test"); const model = new import__85.ModelGraphics(); testObject.model = model; testObject.position = new import__85.ConstantProperty( new import__85.Cartesian3(5678, 1234, 1101112) ); model.uri = new import__85.ConstantProperty(boxUrl); visualizer.update(time2); let primitive; await pollToPromise_default(function() { primitive = scene2.primitives.get(0); return (0, import__85.defined)(primitive); }); expect(primitive.id).toEqual(testObject); }); it("computes bounding sphere", async function() { const time2 = import__85.JulianDate.now(); const testObject = entityCollection.getOrCreateEntity("test"); const model = new import__85.ModelGraphics(); testObject.model = model; testObject.position = new import__85.ConstantProperty( new import__85.Cartesian3(5678, 1234, 1101112) ); model.uri = new import__85.ConstantProperty(boxUrl); visualizer.update(time2); let primitive; await pollToPromise_default(function() { primitive = scene2.primitives.get(0); return (0, import__85.defined)(primitive); }); const result = new import__85.BoundingSphere(); let state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__85.BoundingSphereState.PENDING); await pollToPromise_default(function() { scene2.render(); visualizer.update(time2); state2 = visualizer.getBoundingSphere(testObject, result); return state2 !== import__85.BoundingSphereState.PENDING; }); expect(state2).toBe(import__85.BoundingSphereState.DONE); const expected = import__85.BoundingSphere.clone( primitive.boundingSphere, new import__85.BoundingSphere() ); expect(result).toEqual(expected); }); it("computes bounding sphere with height reference clamp to terrain", async function() { const position = import__85.Cartesian3.fromDegrees(149.515332, -34.984799); const tileset = new import__85.Cesium3DTileset({ enableCollision: true }); scene2.primitives.add(tileset); const time2 = import__85.JulianDate.now(); const testObject = entityCollection.getOrCreateEntity("test"); const model = new import__85.ModelGraphics({ heightReference: import__85.HeightReference.CLAMP_TO_TERRAIN }); testObject.model = model; testObject.position = new import__85.ConstantProperty(position); model.uri = new import__85.ConstantProperty(boxUrl); visualizer.update(time2); const result = new import__85.BoundingSphere(); let state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__85.BoundingSphereState.PENDING); spyOn(scene2.globe, "getHeight").and.returnValue(10); spyOn(tileset, "getHeight").and.returnValue(20); await pollToPromise_default(function() { scene2.renderForSpecs(); visualizer.update(time2); state2 = visualizer.getBoundingSphere(testObject, result); return state2 !== import__85.BoundingSphereState.PENDING; }); expect(state2).toBe(import__85.BoundingSphereState.DONE); const modelData = visualizer._modelHash[testObject.id]; expect(modelData.clampedBoundingSphere).toBeUndefined(); const expectedCenter = import__85.Cartographic.fromCartesian(position); expectedCenter.height = 10; expect(result.center).toEqualEpsilon( import__85.Cartographic.toCartesian(expectedCenter), import__85.Math.EPSILON8 ); }); it("computes bounding sphere with height reference relative to terrain", async function() { const heightOffset = 1e3; const position = import__85.Cartesian3.fromDegrees( 149.515332, -34.984799, heightOffset ); const tileset = new import__85.Cesium3DTileset({ enableCollision: true }); scene2.primitives.add(tileset); const time2 = import__85.JulianDate.now(); const testObject = entityCollection.getOrCreateEntity("test"); const model = new import__85.ModelGraphics({ heightReference: import__85.HeightReference.RELATIVE_TO_TERRAIN }); testObject.model = model; testObject.position = new import__85.ConstantProperty(position); model.uri = new import__85.ConstantProperty(boxUrl); visualizer.update(time2); const result = new import__85.BoundingSphere(); let state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__85.BoundingSphereState.PENDING); spyOn(scene2.globe, "getHeight").and.returnValue(10); spyOn(tileset, "getHeight").and.returnValue(20); await pollToPromise_default(function() { scene2.renderForSpecs(); visualizer.update(time2); state2 = visualizer.getBoundingSphere(testObject, result); return state2 !== import__85.BoundingSphereState.PENDING; }); expect(state2).toBe(import__85.BoundingSphereState.DONE); const modelData = visualizer._modelHash[testObject.id]; expect(modelData.clampedBoundingSphere).toBeUndefined(); const expectedCenter = import__85.Cartographic.fromCartesian(position); expectedCenter.height = heightOffset + 10; expect(result.center).toEqualEpsilon( import__85.Cartographic.toCartesian(expectedCenter), import__85.Math.EPSILON8 ); }); it("computes bounding sphere with height reference clamp to 3D Tiles", async function() { const position = import__85.Cartesian3.fromDegrees(149.515332, -34.984799); const tileset = new import__85.Cesium3DTileset({ enableCollision: true }); scene2.primitives.add(tileset); const time2 = import__85.JulianDate.now(); const testObject = entityCollection.getOrCreateEntity("test"); const model = new import__85.ModelGraphics({ heightReference: import__85.HeightReference.CLAMP_TO_3D_TILE }); testObject.model = model; testObject.position = new import__85.ConstantProperty(position); model.uri = new import__85.ConstantProperty(boxUrl); visualizer.update(time2); const result = new import__85.BoundingSphere(); let state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__85.BoundingSphereState.PENDING); spyOn(scene2.globe, "getHeight").and.returnValue(20); spyOn(tileset, "getHeight").and.returnValue(10); await pollToPromise_default(function() { scene2.renderForSpecs(); visualizer.update(time2); state2 = visualizer.getBoundingSphere(testObject, result); return state2 !== import__85.BoundingSphereState.PENDING; }); expect(state2).toBe(import__85.BoundingSphereState.DONE); const modelData = visualizer._modelHash[testObject.id]; expect(modelData.clampedBoundingSphere).toBeUndefined(); const expectedCenter = import__85.Cartographic.fromCartesian(position); expectedCenter.height = 10; expect(result.center).toEqualEpsilon( import__85.Cartographic.toCartesian(expectedCenter), import__85.Math.EPSILON8 ); }); it("computes bounding sphere with height reference relative to 3D Tiles", async function() { const heightOffset = 1e3; const position = import__85.Cartesian3.fromDegrees( 149.515332, -34.984799, heightOffset ); const tileset = new import__85.Cesium3DTileset({ enableCollision: true }); scene2.primitives.add(tileset); const time2 = import__85.JulianDate.now(); const testObject = entityCollection.getOrCreateEntity("test"); const model = new import__85.ModelGraphics({ heightReference: import__85.HeightReference.RELATIVE_TO_3D_TILE }); testObject.model = model; testObject.position = new import__85.ConstantProperty(position); model.uri = new import__85.ConstantProperty(boxUrl); visualizer.update(time2); const result = new import__85.BoundingSphere(); let state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__85.BoundingSphereState.PENDING); spyOn(scene2.globe, "getHeight").and.returnValue(20); spyOn(tileset, "getHeight").and.returnValue(10); await pollToPromise_default(function() { scene2.renderForSpecs(); visualizer.update(time2); state2 = visualizer.getBoundingSphere(testObject, result); return state2 !== import__85.BoundingSphereState.PENDING; }); expect(state2).toBe(import__85.BoundingSphereState.DONE); const modelData = visualizer._modelHash[testObject.id]; expect(modelData.clampedBoundingSphere).toBeUndefined(); const expectedCenter = import__85.Cartographic.fromCartesian(position); expectedCenter.height = heightOffset + 10; expect(result.center).toEqualEpsilon( import__85.Cartographic.toCartesian(expectedCenter), import__85.Math.EPSILON8 ); }); it("computes bounding sphere with height reference clamp to ground", async function() { const position = import__85.Cartesian3.fromDegrees(149.515332, -34.984799); const tileset = new import__85.Cesium3DTileset({ enableCollision: true }); scene2.primitives.add(tileset); const time2 = import__85.JulianDate.now(); const testObject = entityCollection.getOrCreateEntity("test"); const model = new import__85.ModelGraphics({ heightReference: import__85.HeightReference.CLAMP_TO_GROUND }); testObject.model = model; testObject.position = new import__85.ConstantProperty(position); model.uri = new import__85.ConstantProperty(boxUrl); visualizer.update(time2); const result = new import__85.BoundingSphere(); let state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__85.BoundingSphereState.PENDING); spyOn(scene2.globe, "getHeight").and.returnValue(10); spyOn(tileset, "getHeight").and.returnValue(20); await pollToPromise_default(function() { scene2.renderForSpecs(); visualizer.update(time2); state2 = visualizer.getBoundingSphere(testObject, result); return state2 !== import__85.BoundingSphereState.PENDING; }); expect(state2).toBe(import__85.BoundingSphereState.DONE); const modelData = visualizer._modelHash[testObject.id]; expect(modelData.clampedBoundingSphere).toBeUndefined(); const expectedCenter = import__85.Cartographic.fromCartesian(position); expectedCenter.height = 20; expect(result.center).toEqualEpsilon( import__85.Cartographic.toCartesian(expectedCenter), import__85.Math.EPSILON8 ); }); it("computes bounding sphere with height reference relative to ground", async function() { const heightOffset = 1e3; const position = import__85.Cartesian3.fromDegrees( 149.515332, -34.984799, heightOffset ); const tileset = new import__85.Cesium3DTileset({ enableCollision: true }); scene2.primitives.add(tileset); const time2 = import__85.JulianDate.now(); const testObject = entityCollection.getOrCreateEntity("test"); const model = new import__85.ModelGraphics({ heightReference: import__85.HeightReference.RELATIVE_TO_GROUND }); testObject.model = model; testObject.position = new import__85.ConstantProperty(position); model.uri = new import__85.ConstantProperty(boxUrl); visualizer.update(time2); const result = new import__85.BoundingSphere(); let state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__85.BoundingSphereState.PENDING); spyOn(scene2.globe, "getHeight").and.returnValue(10); spyOn(tileset, "getHeight").and.returnValue(20); await pollToPromise_default(function() { scene2.renderForSpecs(); visualizer.update(time2); state2 = visualizer.getBoundingSphere(testObject, result); return state2 !== import__85.BoundingSphereState.PENDING; }); expect(state2).toBe(import__85.BoundingSphereState.DONE); const modelData = visualizer._modelHash[testObject.id]; expect(modelData.clampedBoundingSphere).toBeUndefined(); const expectedCenter = import__85.Cartographic.fromCartesian(position); expectedCenter.height = heightOffset + 20; expect(result.center).toEqualEpsilon( import__85.Cartographic.toCartesian(expectedCenter), import__85.Math.EPSILON8 ); }); it("computes bounding sphere where globe is undefined", async function() { scene2.globe = void 0; const time2 = import__85.JulianDate.now(); const testObject = entityCollection.getOrCreateEntity("test"); const model = new import__85.ModelGraphics(); testObject.model = model; testObject.position = new import__85.ConstantProperty( new import__85.Cartesian3(5678, 1234, 1101112) ); model.uri = new import__85.ConstantProperty(boxUrl); visualizer.update(time2); let primitive; await pollToPromise_default(function() { primitive = scene2.primitives.get(0); return (0, import__85.defined)(primitive); }); const result = new import__85.BoundingSphere(); let state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__85.BoundingSphereState.PENDING); await pollToPromise_default(function() { scene2.render(); visualizer.update(time2); state2 = visualizer.getBoundingSphere(testObject, result); return state2 !== import__85.BoundingSphereState.PENDING; }); expect(state2).toBe(import__85.BoundingSphereState.DONE); const expected = import__85.BoundingSphere.clone( primitive.boundingSphere, new import__85.BoundingSphere() ); expect(result).toEqual(expected); }); it("fails bounding sphere for entity without ModelGraphics", function() { const testObject = entityCollection.getOrCreateEntity("test"); visualizer.update(import__85.JulianDate.now()); const result = new import__85.BoundingSphere(); const state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__85.BoundingSphereState.FAILED); }); it("fails bounding sphere when model fails to load", async function() { const time2 = import__85.JulianDate.now(); const testObject = entityCollection.getOrCreateEntity("test"); const model = new import__85.ModelGraphics(); testObject.model = model; testObject.position = new import__85.ConstantProperty( new import__85.Cartesian3(5678, 1234, 1101112) ); model.uri = new import__85.ConstantProperty("/path/to/incorrect/file"); visualizer.update(time2); const result = new import__85.BoundingSphere(); let state2 = visualizer.getBoundingSphere(testObject, result); await pollToPromise_default(function() { scene2.render(); visualizer.update(time2); state2 = visualizer.getBoundingSphere(testObject, result); return state2 !== import__85.BoundingSphereState.PENDING; }); expect(state2).toBe(import__85.BoundingSphereState.FAILED); }); it("compute bounding sphere throws without entity", function() { const result = new import__85.BoundingSphere(); expect(function() { visualizer.getBoundingSphere(void 0, result); }).toThrowDeveloperError(); }); it("compute bounding sphere throws without result", function() { const testObject = entityCollection.getOrCreateEntity("test"); expect(function() { visualizer.getBoundingSphere(testObject, void 0); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/DataSources/NodeTransformationPropertySpec.js var import__86 = __toESM(require_Cesium(), 1); describe("DataSources/NodeTransformationProperty", function() { it("default constructor sets expected values", function() { const property = new import__86.NodeTransformationProperty(); expect(property.isConstant).toBe(true); expect(property.translation).toBeUndefined(); expect(property.rotation).toBeUndefined(); expect(property.scale).toBeUndefined(); const result = property.getValue(); expect(result.translation).toEqual(import__86.Cartesian3.ZERO); expect(result.rotation).toEqual(import__86.Quaternion.IDENTITY); expect(result.scale).toEqual(new import__86.Cartesian3(1, 1, 1)); }); it("constructor sets options and allows raw assignment", function() { const options = { translation: import__86.Cartesian3.UNIT_Y, rotation: new import__86.Quaternion(0.5, 0.5, 0.5, 0.5), scale: import__86.Cartesian3.UNIT_X }; const property = new import__86.NodeTransformationProperty(options); expect(property.translation).toBeInstanceOf(import__86.ConstantProperty); expect(property.rotation).toBeInstanceOf(import__86.ConstantProperty); expect(property.scale).toBeInstanceOf(import__86.ConstantProperty); expect(property.translation.getValue()).toEqual(options.translation); expect(property.rotation.getValue()).toEqual(options.rotation); expect(property.scale.getValue()).toEqual(options.scale); }); it("works with constant values", function() { const property = new import__86.NodeTransformationProperty(); property.translation = new import__86.ConstantProperty(import__86.Cartesian3.UNIT_Y); property.rotation = new import__86.ConstantProperty( new import__86.Quaternion(0.5, 0.5, 0.5, 0.5) ); property.scale = new import__86.ConstantProperty(import__86.Cartesian3.UNIT_X); const result = property.getValue(import__86.JulianDate.now()); expect(result.translation).toEqual(import__86.Cartesian3.UNIT_Y); expect(result.rotation).toEqual(new import__86.Quaternion(0.5, 0.5, 0.5, 0.5)); expect(result.scale).toEqual(import__86.Cartesian3.UNIT_X); }); it("works with dynamic values", function() { const property = new import__86.NodeTransformationProperty(); property.translation = new import__86.TimeIntervalCollectionProperty(); property.rotation = new import__86.TimeIntervalCollectionProperty(); property.scale = new import__86.TimeIntervalCollectionProperty(); const start = new import__86.JulianDate(1, 0); const stop = new import__86.JulianDate(2, 0); property.translation.intervals.addInterval( new import__86.TimeInterval({ start, stop, data: import__86.Cartesian3.UNIT_Y }) ); property.rotation.intervals.addInterval( new import__86.TimeInterval({ start, stop, data: new import__86.Quaternion(0.5, 0.5, 0.5, 0.5) }) ); property.scale.intervals.addInterval( new import__86.TimeInterval({ start, stop, data: import__86.Cartesian3.UNIT_X }) ); expect(property.isConstant).toBe(false); const result = property.getValue(start); expect(result.translation).toEqual(import__86.Cartesian3.UNIT_Y); expect(result.rotation).toEqual(new import__86.Quaternion(0.5, 0.5, 0.5, 0.5)); expect(result.scale).toEqual(import__86.Cartesian3.UNIT_X); }); it("works with a result parameter", function() { const property = new import__86.NodeTransformationProperty(); property.translation = new import__86.ConstantProperty(import__86.Cartesian3.UNIT_Y); property.rotation = new import__86.ConstantProperty( new import__86.Quaternion(0.5, 0.5, 0.5, 0.5) ); property.scale = new import__86.ConstantProperty(import__86.Cartesian3.UNIT_X); const translation = new import__86.Cartesian3(); const rotation = new import__86.Quaternion(); const scale = new import__86.Cartesian3(); const result = { translation, rotation, scale }; const returnedResult = property.getValue(import__86.JulianDate.now(), result); expect(returnedResult).toBe(result); expect(returnedResult.translation).toBe(translation); expect(returnedResult.translation).toEqual(import__86.Cartesian3.UNIT_Y); expect(returnedResult.rotation).toBe(rotation); expect(returnedResult.rotation).toEqual(new import__86.Quaternion(0.5, 0.5, 0.5, 0.5)); expect(returnedResult.scale).toBe(scale); expect(returnedResult.scale).toEqual(import__86.Cartesian3.UNIT_X); }); it("equals works", function() { const left = new import__86.NodeTransformationProperty(); left.translation = new import__86.ConstantProperty(import__86.Cartesian3.UNIT_Y); left.rotation = new import__86.ConstantProperty(new import__86.Quaternion(0.5, 0.5, 0.5, 0.5)); left.scale = new import__86.ConstantProperty(import__86.Cartesian3.UNIT_X); const right = new import__86.NodeTransformationProperty(); right.translation = new import__86.ConstantProperty(import__86.Cartesian3.UNIT_Y); right.rotation = new import__86.ConstantProperty(new import__86.Quaternion(0.5, 0.5, 0.5, 0.5)); right.scale = new import__86.ConstantProperty(import__86.Cartesian3.UNIT_X); expect(left.equals(right)).toEqual(true); right.scale = new import__86.ConstantProperty(import__86.Cartesian3.ZERO); expect(left.equals(right)).toEqual(false); right.scale = new import__86.ConstantProperty(import__86.Cartesian3.UNIT_X); right.translation = new import__86.ConstantProperty(import__86.Cartesian3.ZERO); expect(left.equals(right)).toEqual(false); right.translation = new import__86.ConstantProperty(import__86.Cartesian3.UNIT_Y); right.rotation = new import__86.ConstantProperty(import__86.Quaternion.ZERO); expect(left.equals(right)).toEqual(false); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__86.NodeTransformationProperty(); testDefinitionChanged_default( property, "rotation", import__86.Cartesian3.UNIT_X, import__86.Cartesian3.ZERO ); testDefinitionChanged_default( property, "translation", new import__86.Quaternion(0.5, 0.5, 0.5, 0.5), import__86.Quaternion.ZERO ); testDefinitionChanged_default( property, "scale", import__86.Cartesian3.UNIT_X, import__86.Cartesian3.ZERO ); }); }); // packages/engine/Specs/DataSources/PathGraphicsSpec.js var import__87 = __toESM(require_Cesium(), 1); describe("DataSources/PathGraphics", function() { it("creates expected instance from raw assignment and construction", function() { const options = { material: import__87.Color.RED, width: 1, show: false, leadTime: 2, trailTime: 3, resolution: 4, distanceDisplayCondition: new import__87.DistanceDisplayCondition(10, 20) }; const path = new import__87.PathGraphics(options); expect(path.material).toBeInstanceOf(import__87.ColorMaterialProperty); expect(path.width).toBeInstanceOf(import__87.ConstantProperty); expect(path.show).toBeInstanceOf(import__87.ConstantProperty); expect(path.leadTime).toBeInstanceOf(import__87.ConstantProperty); expect(path.trailTime).toBeInstanceOf(import__87.ConstantProperty); expect(path.resolution).toBeInstanceOf(import__87.ConstantProperty); expect(path.distanceDisplayCondition).toBeInstanceOf(import__87.ConstantProperty); expect(path.material.color.getValue()).toEqual(options.material); expect(path.width.getValue()).toEqual(options.width); expect(path.show.getValue()).toEqual(options.show); expect(path.leadTime.getValue()).toEqual(options.leadTime); expect(path.trailTime.getValue()).toEqual(options.trailTime); expect(path.resolution.getValue()).toEqual(options.resolution); expect(path.distanceDisplayCondition.getValue()).toEqual( options.distanceDisplayCondition ); }); it("merge assigns unassigned properties", function() { const source = new import__87.PathGraphics(); source.material = new import__87.ColorMaterialProperty(); source.width = new import__87.ConstantProperty(1); source.show = new import__87.ConstantProperty(true); source.leadTime = new import__87.ConstantProperty(1); source.trailTime = new import__87.ConstantProperty(1); source.resolution = new import__87.ConstantProperty(1); source.distanceDisplayCondition = new import__87.ConstantProperty( new import__87.DistanceDisplayCondition(10, 20) ); const target = new import__87.PathGraphics(); target.merge(source); expect(target.material).toBe(source.material); expect(target.width).toBe(source.width); expect(target.show).toBe(source.show); expect(target.leadTime).toBe(source.leadTime); expect(target.trailTime).toBe(source.trailTime); expect(target.resolution).toBe(source.resolution); expect(target.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); }); it("merge does not assign assigned properties", function() { const source = new import__87.PathGraphics(); source.material = new import__87.ColorMaterialProperty(); source.width = new import__87.ConstantProperty(1); source.show = new import__87.ConstantProperty(true); source.leadTime = new import__87.ConstantProperty(1); source.trailTime = new import__87.ConstantProperty(1); source.resolution = new import__87.ConstantProperty(1); source.distanceDisplayCondition = new import__87.ConstantProperty( new import__87.DistanceDisplayCondition() ); const color = new import__87.ColorMaterialProperty(); const width = new import__87.ConstantProperty(1); const show = new import__87.ConstantProperty(true); const leadTime = new import__87.ConstantProperty(1); const trailTime = new import__87.ConstantProperty(1); const resolution = new import__87.ConstantProperty(1); const distanceDisplayCondition = new import__87.ConstantProperty( new import__87.DistanceDisplayCondition() ); const target = new import__87.PathGraphics(); target.material = color; target.width = width; target.show = show; target.leadTime = leadTime; target.trailTime = trailTime; target.resolution = resolution; target.distanceDisplayCondition = distanceDisplayCondition; target.merge(source); expect(target.material).toBe(color); expect(target.width).toBe(width); expect(target.show).toBe(show); expect(target.leadTime).toBe(leadTime); expect(target.trailTime).toBe(trailTime); expect(target.resolution).toBe(resolution); expect(target.distanceDisplayCondition).toBe(distanceDisplayCondition); }); it("clone works", function() { const source = new import__87.PathGraphics(); source.material = new import__87.ColorMaterialProperty(); source.width = new import__87.ConstantProperty(1); source.show = new import__87.ConstantProperty(true); source.leadTime = new import__87.ConstantProperty(1); source.trailTime = new import__87.ConstantProperty(1); source.resolution = new import__87.ConstantProperty(1); source.distanceDisplayCondition = new import__87.ConstantProperty( new import__87.DistanceDisplayCondition() ); const result = source.clone(); expect(result.material).toBe(source.material); expect(result.width).toBe(source.width); expect(result.show).toBe(source.show); expect(result.leadTime).toBe(source.leadTime); expect(result.trailTime).toBe(source.trailTime); expect(result.resolution).toBe(source.resolution); expect(result.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); }); it("merge throws if source undefined", function() { const target = new import__87.PathGraphics(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/PathVisualizerSpec.js var import__88 = __toESM(require_Cesium(), 1); describe( "DataSources/PathVisualizer", function() { let scene2; let visualizer; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { visualizer = visualizer && visualizer.destroy(); }); it("constructor throws if no scene is passed.", function() { expect(function() { return new import__88.PathVisualizer(); }).toThrowDeveloperError(); }); it("update throws if no time specified.", function() { const entityCollection = new import__88.EntityCollection(); visualizer = new import__88.PathVisualizer(scene2, entityCollection); expect(function() { visualizer.update(); }).toThrowDeveloperError(); }); it("isDestroy returns false until destroyed.", function() { const entityCollection = new import__88.EntityCollection(); visualizer = new import__88.PathVisualizer(scene2, entityCollection); expect(visualizer.isDestroyed()).toEqual(false); visualizer.destroy(); expect(visualizer.isDestroyed()).toEqual(true); visualizer = void 0; }); it("removes the listener from the entity collection when destroyed", function() { const entityCollection = new import__88.EntityCollection(); const visualizer2 = new import__88.PathVisualizer(scene2, entityCollection); expect(entityCollection.collectionChanged.numberOfListeners).toEqual(1); visualizer2.destroy(); expect(entityCollection.collectionChanged.numberOfListeners).toEqual(0); }); it("object with no path does not create one.", function() { const entityCollection = new import__88.EntityCollection(); visualizer = new import__88.PathVisualizer(scene2, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__88.ConstantProperty([ new import__88.Cartesian3(1234, 5678, 9101112), new import__88.Cartesian3(5678, 1234, 1101112) ]); visualizer.update(import__88.JulianDate.now()); expect(scene2.primitives.length).toEqual(0); }); it("object with no position does not create a polyline.", function() { const entityCollection = new import__88.EntityCollection(); visualizer = new import__88.PathVisualizer(scene2, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); const path = testObject.path = new import__88.PathGraphics(); path.show = new import__88.ConstantProperty(true); visualizer.update(import__88.JulianDate.now()); expect(scene2.primitives.length).toEqual(0); }); it("adding and removing an entity path without rendering does not crash.", function() { const times = [new import__88.JulianDate(0, 0), new import__88.JulianDate(1, 0)]; const positions = [ new import__88.Cartesian3(1234, 5678, 9101112), new import__88.Cartesian3(5678, 1234, 1101112) ]; const entityCollection = new import__88.EntityCollection(); visualizer = new import__88.PathVisualizer(scene2, entityCollection); const position = new import__88.SampledPositionProperty(); position.addSamples(times, positions); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = position; testObject.path = new import__88.PathGraphics(); entityCollection.remove(testObject); }); it("A PathGraphics causes a primitive to be created and updated.", function() { const times = [new import__88.JulianDate(0, 0), new import__88.JulianDate(1, 0)]; const updateTime = new import__88.JulianDate(0.5, 0); const positions = [ new import__88.Cartesian3(1234, 5678, 9101112), new import__88.Cartesian3(5678, 1234, 1101112) ]; const entityCollection = new import__88.EntityCollection(); visualizer = new import__88.PathVisualizer(scene2, entityCollection); expect(scene2.primitives.length).toEqual(0); const testObject = entityCollection.getOrCreateEntity("test"); const position = new import__88.SampledPositionProperty(); testObject.position = position; position.addSamples(times, positions); const path = testObject.path = new import__88.PathGraphics(); path.show = new import__88.ConstantProperty(true); path.material = new import__88.PolylineOutlineMaterialProperty(); path.material.color = new import__88.ConstantProperty(new import__88.Color(0.8, 0.7, 0.6, 0.5)); path.material.outlineColor = new import__88.ConstantProperty( new import__88.Color(0.1, 0.2, 0.3, 0.4) ); path.material.outlineWidth = new import__88.ConstantProperty(2.5); path.width = new import__88.ConstantProperty(12.5); path.distanceDisplayCondition = new import__88.ConstantProperty( new import__88.DistanceDisplayCondition(10, 20) ); path.leadTime = new import__88.ConstantProperty(25); path.trailTime = new import__88.ConstantProperty(10); visualizer.update(updateTime); expect(scene2.primitives.length).toEqual(1); const polylineCollection = scene2.primitives.get(0); const primitive = polylineCollection.get(0); expect(primitive.positions[0]).toEqual( testObject.position.getValue( import__88.JulianDate.addSeconds( updateTime, -path.trailTime.getValue(), new import__88.JulianDate() ) ) ); expect(primitive.positions[1]).toEqual( testObject.position.getValue(updateTime) ); expect(primitive.positions[2]).toEqual( testObject.position.getValue( import__88.JulianDate.addSeconds( updateTime, path.leadTime.getValue(), new import__88.JulianDate() ) ) ); expect(primitive.show).toEqual(testObject.path.show.getValue(updateTime)); expect(primitive.width).toEqual( testObject.path.width.getValue(updateTime) ); expect(primitive.distanceDisplayCondition).toEqual( testObject.path.distanceDisplayCondition.getValue(updateTime) ); const material = primitive.material; expect(material.uniforms.color).toEqual( testObject.path.material.color.getValue(updateTime) ); expect(material.uniforms.outlineColor).toEqual( testObject.path.material.outlineColor.getValue(updateTime) ); expect(material.uniforms.outlineWidth).toEqual( testObject.path.material.outlineWidth.getValue(updateTime) ); path.show = new import__88.ConstantProperty(false); visualizer.update(updateTime); expect(primitive.show).toEqual(testObject.path.show.getValue(updateTime)); }); it("creates primitives when an entity is already in the collection.", function() { const times = [new import__88.JulianDate(0, 0), new import__88.JulianDate(1, 0)]; const updateTime = new import__88.JulianDate(0.5, 0); const positions = [ new import__88.Cartesian3(1234, 5678, 9101112), new import__88.Cartesian3(5678, 1234, 1101112) ]; const entityCollection = new import__88.EntityCollection(); const testObject = entityCollection.getOrCreateEntity("test"); const position = new import__88.SampledPositionProperty(); testObject.position = position; position.addSamples(times, positions); const path = testObject.path = new import__88.PathGraphics(); path.show = new import__88.ConstantProperty(true); path.material = new import__88.PolylineOutlineMaterialProperty(); path.material.color = new import__88.ConstantProperty(new import__88.Color(0.8, 0.7, 0.6, 0.5)); path.material.outlineColor = new import__88.ConstantProperty( new import__88.Color(0.1, 0.2, 0.3, 0.4) ); path.material.outlineWidth = new import__88.ConstantProperty(2.5); path.width = new import__88.ConstantProperty(12.5); path.leadTime = new import__88.ConstantProperty(25); path.trailTime = new import__88.ConstantProperty(10); visualizer = new import__88.PathVisualizer(scene2, entityCollection); expect(scene2.primitives.length).toEqual(0); visualizer.update(updateTime); expect(scene2.primitives.length).toEqual(1); }); it("A custom material can be used.", function() { const times = [new import__88.JulianDate(0, 0), new import__88.JulianDate(1, 0)]; const updateTime = new import__88.JulianDate(0.5, 0); const positions = [ new import__88.Cartesian3(1234, 5678, 9101112), new import__88.Cartesian3(5678, 1234, 1101112) ]; const entityCollection = new import__88.EntityCollection(); visualizer = new import__88.PathVisualizer(scene2, entityCollection); expect(scene2.primitives.length).toEqual(0); const testObject = entityCollection.getOrCreateEntity("test"); const position = new import__88.SampledPositionProperty(); testObject.position = position; position.addSamples(times, positions); const path = testObject.path = new import__88.PathGraphics(); path.show = new import__88.ConstantProperty(true); path.material = new import__88.PolylineGlowMaterialProperty(); path.material.color = new import__88.ConstantProperty(new import__88.Color(0.8, 0.7, 0.6, 0.5)); path.material.glowPower = new import__88.ConstantProperty(0.2); path.material.taperPower = new import__88.ConstantProperty(0.15); path.width = new import__88.ConstantProperty(12.5); path.leadTime = new import__88.ConstantProperty(25); path.trailTime = new import__88.ConstantProperty(10); visualizer.update(updateTime); expect(scene2.primitives.length).toEqual(1); const polylineCollection = scene2.primitives.get(0); const primitive = polylineCollection.get(0); const material = primitive.material; expect(material.uniforms.color).toEqual( testObject.path.material.color.getValue(updateTime) ); expect(material.uniforms.glowPower).toEqual( testObject.path.material.glowPower.getValue(updateTime) ); expect(material.uniforms.taperPower).toEqual( testObject.path.material.taperPower.getValue(updateTime) ); }); it("Reuses primitives when hiding one and showing another", function() { const times = [new import__88.JulianDate(0, 0), new import__88.JulianDate(1, 0)]; const time2 = new import__88.JulianDate(0.5, 0); const positions = [ new import__88.Cartesian3(1234, 5678, 9101112), new import__88.Cartesian3(5678, 1234, 1101112) ]; const entityCollection = new import__88.EntityCollection(); visualizer = new import__88.PathVisualizer(scene2, entityCollection); let position = new import__88.SampledPositionProperty(); position.addSamples(times, positions); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = position; testObject.path = new import__88.PathGraphics(); testObject.path.show = new import__88.ConstantProperty(true); testObject.path.leadTime = new import__88.ConstantProperty(25); testObject.path.trailTime = new import__88.ConstantProperty(10); visualizer.update(time2); const polylineCollection = scene2.primitives.get(0); expect(polylineCollection.length).toEqual(1); testObject.path.show = new import__88.ConstantProperty(false); visualizer.update(time2); expect(polylineCollection.length).toEqual(1); position = new import__88.SampledPositionProperty(); position.addSamples(times, positions); const testObject2 = entityCollection.getOrCreateEntity("test2"); testObject2.position = position; testObject2.path = new import__88.PathGraphics(); testObject2.path.show = new import__88.ConstantProperty(true); testObject2.path.leadTime = new import__88.ConstantProperty(25); testObject2.path.trailTime = new import__88.ConstantProperty(10); visualizer.update(time2); expect(polylineCollection.length).toEqual(1); }); it("Switches from inertial to fixed paths in 2D", function() { const times = [new import__88.JulianDate(0, 0), new import__88.JulianDate(1, 0)]; const time2 = new import__88.JulianDate(0.5, 0); const positions = [ new import__88.Cartesian3(1234, 5678, 9101112), new import__88.Cartesian3(5678, 1234, 1101112) ]; const position = new import__88.SampledPositionProperty(import__88.ReferenceFrame.INERTIAL); position.addSamples(times, positions); const entityCollection = new import__88.EntityCollection(); visualizer = new import__88.PathVisualizer(scene2, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = position; testObject.path = new import__88.PathGraphics(); testObject.path.leadTime = new import__88.ConstantProperty(25); testObject.path.trailTime = new import__88.ConstantProperty(10); visualizer.update(time2); expect(scene2.primitives.length).toEqual(1); const inertialPolylineCollection = scene2.primitives.get(0); expect(inertialPolylineCollection.length).toEqual(1); expect(inertialPolylineCollection.modelMatrix).not.toEqual( import__88.Matrix4.IDENTITY ); const inertialLine = inertialPolylineCollection.get(0); expect(inertialLine.show).toEqual(true); scene2.mode = import__88.SceneMode.SCENE2D; visualizer.update(time2); expect(scene2.primitives.length).toEqual(2); const fixedPolylineCollection = scene2.primitives.get(1); expect(inertialLine.show).toEqual(false); expect(fixedPolylineCollection.length).toEqual(1); expect(fixedPolylineCollection.modelMatrix).toEqual(import__88.Matrix4.IDENTITY); const fixedLine = fixedPolylineCollection.get(0); expect(fixedLine.show).toEqual(true); }); it("clear hides primitives.", function() { const times = [new import__88.JulianDate(0, 0), new import__88.JulianDate(1, 0)]; const updateTime = new import__88.JulianDate(0.5, 0); const positions = [ new import__88.Cartesian3(1234, 5678, 9101112), new import__88.Cartesian3(5678, 1234, 1101112) ]; const entityCollection = new import__88.EntityCollection(); visualizer = new import__88.PathVisualizer(scene2, entityCollection); expect(scene2.primitives.length).toEqual(0); const testObject = entityCollection.getOrCreateEntity("test"); const position = new import__88.SampledPositionProperty(); testObject.position = position; position.addSamples(times, positions); const path = testObject.path = new import__88.PathGraphics(); path.show = new import__88.ConstantProperty(true); path.color = new import__88.ConstantProperty(new import__88.Color(0.8, 0.7, 0.6, 0.5)); path.width = new import__88.ConstantProperty(12.5); path.outlineColor = new import__88.ConstantProperty(new import__88.Color(0.1, 0.2, 0.3, 0.4)); path.outlineWidth = new import__88.ConstantProperty(2.5); path.leadTime = new import__88.ConstantProperty(25); path.trailTime = new import__88.ConstantProperty(10); visualizer.update(updateTime); expect(scene2.primitives.length).toEqual(1); const polylineCollection = scene2.primitives.get(0); const primitive = polylineCollection.get(0); visualizer.update(updateTime); entityCollection.removeAll(); expect(primitive.show).toEqual(false); expect(primitive.id).toBeUndefined(); }); it("Visualizer sets entity property.", function() { const times = [new import__88.JulianDate(0, 0), new import__88.JulianDate(1, 0)]; const updateTime = new import__88.JulianDate(0.5, 0); const positions = [ new import__88.Cartesian3(1234, 5678, 9101112), new import__88.Cartesian3(5678, 1234, 1101112) ]; const entityCollection = new import__88.EntityCollection(); visualizer = new import__88.PathVisualizer(scene2, entityCollection); expect(scene2.primitives.length).toEqual(0); const testObject = entityCollection.getOrCreateEntity("test"); const position = new import__88.SampledPositionProperty(); testObject.position = position; position.addSamples(times, positions); const path = testObject.path = new import__88.PathGraphics(); path.show = new import__88.ConstantProperty(true); path.color = new import__88.ConstantProperty(new import__88.Color(0.8, 0.7, 0.6, 0.5)); path.width = new import__88.ConstantProperty(12.5); path.outlineColor = new import__88.ConstantProperty(new import__88.Color(0.1, 0.2, 0.3, 0.4)); path.outlineWidth = new import__88.ConstantProperty(2.5); path.leadTime = new import__88.ConstantProperty(25); path.trailTime = new import__88.ConstantProperty(10); visualizer.update(updateTime); const polylineCollection = scene2.primitives.get(0); const primitive = polylineCollection.get(0); expect(primitive.id).toEqual(testObject); }); it("Visualizer destroys primitives when all items are removed.", function() { const times = [new import__88.JulianDate(0, 0), new import__88.JulianDate(1, 0)]; const updateTime = new import__88.JulianDate(0.5, 0); const positions = [ new import__88.Cartesian3(1234, 5678, 9101112), new import__88.Cartesian3(5678, 1234, 1101112) ]; const entityCollection = new import__88.EntityCollection(); visualizer = new import__88.PathVisualizer(scene2, entityCollection); expect(scene2.primitives.length).toEqual(0); const testObject = entityCollection.getOrCreateEntity("test"); const position = new import__88.SampledPositionProperty(); testObject.position = position; position.addSamples(times, positions); const path = testObject.path = new import__88.PathGraphics(); path.show = new import__88.ConstantProperty(true); path.color = new import__88.ConstantProperty(new import__88.Color(0.8, 0.7, 0.6, 0.5)); path.width = new import__88.ConstantProperty(12.5); path.outlineColor = new import__88.ConstantProperty(new import__88.Color(0.1, 0.2, 0.3, 0.4)); path.outlineWidth = new import__88.ConstantProperty(2.5); path.leadTime = new import__88.ConstantProperty(25); path.trailTime = new import__88.ConstantProperty(10); visualizer.update(updateTime); expect(scene2.primitives.length).toEqual(1); entityCollection.removeAll(); visualizer.update(updateTime); expect(scene2.primitives.length).toEqual(0); }); it("subSample works for constant properties", function() { const property = new import__88.ConstantPositionProperty( new import__88.Cartesian3(1e3, 2e3, 3e3) ); const start = new import__88.JulianDate(0, 0); const stop = new import__88.JulianDate(1, 0); const updateTime = new import__88.JulianDate(1, 43200); const referenceFrame = import__88.ReferenceFrame.FIXED; const maximumStep = 10; const result = import__88.PathVisualizer._subSample( property, start, stop, updateTime, referenceFrame, maximumStep ); expect(result).toEqual([property._value]); }); it("subSample works for reference properties", function() { const property = new import__88.ConstantPositionProperty( new import__88.Cartesian3(1e3, 2e3, 3e3) ); const start = new import__88.JulianDate(0, 0); const stop = new import__88.JulianDate(1, 0); const updateTime = new import__88.JulianDate(1, 43200); const referenceFrame = import__88.ReferenceFrame.FIXED; const maximumStep = 10; const entities = new import__88.EntityCollection(); const targetEntity = entities.getOrCreateEntity("target"); targetEntity.position = property; const referenceProperty = new import__88.ReferenceProperty(entities, "target", [ "position" ]); const result = import__88.PathVisualizer._subSample( referenceProperty, start, stop, updateTime, referenceFrame, maximumStep ); expect(result).toEqual([property._value]); }); it("subSample works for sampled properties", function() { const property = new import__88.SampledPositionProperty(); const start = new import__88.JulianDate(0, 0); const stop = new import__88.JulianDate(1, 0); property.addSample(start, new import__88.Cartesian3(0, 0, 0)); property.addSample(stop, new import__88.Cartesian3(0, 0, 100)); let updateTime = new import__88.JulianDate(0, 43200); const referenceFrame = import__88.ReferenceFrame.FIXED; let maximumStep = 86400; const result = []; import__88.PathVisualizer._subSample( property, start, stop, updateTime, referenceFrame, maximumStep, result ); expect(result).toEqual([ property.getValue(start), property.getValue(updateTime), property.getValue(stop) ]); maximumStep = 28800; let expectedStep = 28800; import__88.PathVisualizer._subSample( property, start, stop, updateTime, referenceFrame, maximumStep, result ); expect(result).toEqual([ property.getValue(start), property.getValue( import__88.JulianDate.addSeconds(start, expectedStep, new import__88.JulianDate()) ), property.getValue(updateTime), property.getValue( import__88.JulianDate.addSeconds(start, expectedStep * 2, new import__88.JulianDate()) ), property.getValue(stop) ]); maximumStep = 43201; expectedStep = 43200; updateTime = new import__88.JulianDate(0, 64800); import__88.PathVisualizer._subSample( property, start, stop, updateTime, referenceFrame, maximumStep, result ); expect(result).toEqual([ property.getValue(start), property.getValue( import__88.JulianDate.addSeconds(start, expectedStep, new import__88.JulianDate()) ), property.getValue(updateTime), property.getValue(stop) ]); maximumStep = 43199; expectedStep = 28800; updateTime = new import__88.JulianDate(0, 21600); import__88.PathVisualizer._subSample( property, start, stop, updateTime, referenceFrame, maximumStep, result ); expect(result).toEqual([ property.getValue(start), property.getValue(updateTime), property.getValue( import__88.JulianDate.addSeconds(start, expectedStep, new import__88.JulianDate()) ), property.getValue( import__88.JulianDate.addSeconds(start, expectedStep * 2, new import__88.JulianDate()) ), property.getValue(stop) ]); }); it("subSample works for interval properties", function() { const t1 = new import__88.JulianDate(0, 0); const t2 = new import__88.JulianDate(1, 0); const t3 = new import__88.JulianDate(2, 0); const t4 = new import__88.JulianDate(3, 0); const property = new import__88.TimeIntervalCollectionPositionProperty(); property.intervals.addInterval( new import__88.TimeInterval({ start: t1, stop: t2, data: new import__88.Cartesian3(0, 0, 1) }) ); property.intervals.addInterval( new import__88.TimeInterval({ start: t2, stop: t3, isStartIncluded: false, isStopIncluded: false, data: new import__88.Cartesian3(0, 0, 2) }) ); property.intervals.addInterval( new import__88.TimeInterval({ start: t3, stop: t4, data: new import__88.Cartesian3(0, 0, 3) }) ); const updateTime = new import__88.JulianDate(1, 43200); const referenceFrame = import__88.ReferenceFrame.FIXED; const maximumStep = 10; const result = []; import__88.PathVisualizer._subSample( property, t1, t4, updateTime, referenceFrame, maximumStep, result ); expect(result).toEqual([ new import__88.Cartesian3(0, 0, 1), new import__88.Cartesian3(0, 0, 2), new import__88.Cartesian3(0, 0, 3) ]); import__88.PathVisualizer._subSample( property, t2, t3, updateTime, referenceFrame, maximumStep, result ); expect(result).toEqual([ new import__88.Cartesian3(0, 0, 1), new import__88.Cartesian3(0, 0, 2), new import__88.Cartesian3(0, 0, 3) ]); import__88.PathVisualizer._subSample( property, t1, t2, updateTime, referenceFrame, maximumStep, result ); expect(result).toEqual([new import__88.Cartesian3(0, 0, 1)]); import__88.PathVisualizer._subSample( property, t3, t4, updateTime, referenceFrame, maximumStep, result ); expect(result).toEqual([new import__88.Cartesian3(0, 0, 3)]); }); function CustomPositionProperty(innerProperty) { this.SampledProperty = innerProperty; this.isConstant = innerProperty.isConstant; this.definitionChanged = innerProperty.definitionChanged; this.referenceFrame = innerProperty.referenceFrame; this.getValue = function(time2, result) { return innerProperty.getValue(time2, result); }; this.getValueInReferenceFrame = function(time2, referenceFrame, result) { return innerProperty.getValueInReferenceFrame( time2, referenceFrame, result ); }; this.equals = function(other) { return innerProperty.equals(other); }; } it("subSample works for custom properties", function() { const t1 = new import__88.JulianDate(0, 0); const t2 = new import__88.JulianDate(1, 0); const t3 = new import__88.JulianDate(2, 0); const t4 = new import__88.JulianDate(3, 0); const updateTime = new import__88.JulianDate(1, 1); const sampledProperty = new import__88.SampledPositionProperty(); sampledProperty.addSample(t1, new import__88.Cartesian3(0, 0, 1)); sampledProperty.addSample(t2, new import__88.Cartesian3(0, 0, 2)); sampledProperty.addSample(t3, new import__88.Cartesian3(0, 0, 3)); sampledProperty.addSample(t4, new import__88.Cartesian3(0, 0, 4)); const property = new CustomPositionProperty(sampledProperty); const referenceFrame = import__88.ReferenceFrame.FIXED; const maximumStep = 43200; const result = []; import__88.PathVisualizer._subSample( property, t1, t4, updateTime, referenceFrame, maximumStep, result ); expect(result).toEqual([ sampledProperty.getValue(t1), sampledProperty.getValue( import__88.JulianDate.addSeconds(t1, maximumStep, new import__88.JulianDate()) ), sampledProperty.getValue( import__88.JulianDate.addSeconds(t1, maximumStep * 2, new import__88.JulianDate()) ), sampledProperty.getValue(updateTime), sampledProperty.getValue( import__88.JulianDate.addSeconds(t1, maximumStep * 3, new import__88.JulianDate()) ), sampledProperty.getValue( import__88.JulianDate.addSeconds(t1, maximumStep * 4, new import__88.JulianDate()) ), sampledProperty.getValue( import__88.JulianDate.addSeconds(t1, maximumStep * 5, new import__88.JulianDate()) ), sampledProperty.getValue( import__88.JulianDate.addSeconds(t1, maximumStep * 6, new import__88.JulianDate()) ) ]); }); function createCompositeTest(useReferenceProperty) { const t1 = new import__88.JulianDate(0, 0); const t2 = new import__88.JulianDate(1, 0); const t3 = new import__88.JulianDate(2, 0); const t4 = new import__88.JulianDate(3, 0); const t5 = new import__88.JulianDate(4, 0); const t6 = new import__88.JulianDate(5, 0); const constantProperty = new import__88.ConstantPositionProperty( new import__88.Cartesian3(0, 0, 1) ); const intervalProperty = new import__88.TimeIntervalCollectionPositionProperty(); intervalProperty.intervals.addInterval( new import__88.TimeInterval({ start: t1, stop: t2, data: new import__88.Cartesian3(0, 0, 1) }) ); intervalProperty.intervals.addInterval( new import__88.TimeInterval({ start: t2, stop: t3, isStartIncluded: false, isStopIncluded: false, data: new import__88.Cartesian3(0, 0, 2) }) ); intervalProperty.intervals.addInterval( new import__88.TimeInterval({ start: t1, stop: t2, data: new import__88.Cartesian3(0, 0, 3) }) ); const sampledProperty = new import__88.SampledPositionProperty(); sampledProperty.addSample(t1, new import__88.Cartesian3(0, 0, 1)); sampledProperty.addSample(t2, new import__88.Cartesian3(0, 0, 2)); sampledProperty.addSample(t3, new import__88.Cartesian3(0, 0, 3)); sampledProperty.addSample(t4, new import__88.Cartesian3(0, 0, 4)); const entities = new import__88.EntityCollection(); const targetEntity = entities.getOrCreateEntity("target"); targetEntity.position = new import__88.ConstantPositionProperty( new import__88.Cartesian3(0, 0, 5) ); const referenceProperty = new import__88.ReferenceProperty(entities, "target", [ "position" ]); const scaledProperty = new import__88.ScaledPositionProperty(referenceProperty); const property = new import__88.CompositePositionProperty(); property.intervals.addInterval( new import__88.TimeInterval({ start: t1, stop: t2, data: intervalProperty }) ); property.intervals.addInterval( new import__88.TimeInterval({ start: t2, stop: t3, isStartIncluded: false, isStopIncluded: false, data: constantProperty }) ); property.intervals.addInterval( new import__88.TimeInterval({ start: t3, stop: t4, data: sampledProperty }) ); property.intervals.addInterval( new import__88.TimeInterval({ start: t4, stop: t5, isStartIncluded: false, isStopIncluded: true, data: referenceProperty }) ); property.intervals.addInterval( new import__88.TimeInterval({ start: t5, stop: t6, isStartIncluded: false, isStopIncluded: true, data: scaledProperty }) ); const updateTime = new import__88.JulianDate(0, 0); const referenceFrame = import__88.ReferenceFrame.FIXED; const maximumStep = 43200; const result = []; let propertyToTest = property; if (useReferenceProperty) { const testReference = entities.getOrCreateEntity("testReference"); testReference.position = property; propertyToTest = new import__88.ReferenceProperty(entities, "testReference", [ "position" ]); } import__88.PathVisualizer._subSample( propertyToTest, t1, t6, updateTime, referenceFrame, maximumStep, result ); expect(result).toEqual([ intervalProperty.intervals.get(0).data, constantProperty.getValue(t1), sampledProperty.getValue(t3), sampledProperty.getValue( import__88.JulianDate.addSeconds(t3, maximumStep, new import__88.JulianDate()) ), sampledProperty.getValue(t4), targetEntity.position.getValue(t5), scaledProperty.getValue(t6) ]); } it("subSample works for composite properties", function() { createCompositeTest(false); }); it("subSample works for composite properties wrapped in reference properties", function() { createCompositeTest(true); }); }, "WebGL" ); // packages/engine/Specs/DataSources/PlaneGeometryUpdaterSpec.js var import__89 = __toESM(require_Cesium(), 1); describe( "DataSources/PlaneGeometryUpdater", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); function createBasicPlane() { const planeGraphics = new import__89.PlaneGraphics(); planeGraphics.plane = new import__89.ConstantProperty( new import__89.Plane(import__89.Cartesian3.UNIT_X, 0) ); planeGraphics.dimensions = new import__89.ConstantProperty(new import__89.Cartesian2(1, 2)); const entity = new import__89.Entity(); entity.position = new import__89.ConstantPositionProperty( import__89.Cartesian3.fromDegrees(0, 0, 0) ); entity.plane = planeGraphics; return entity; } function createDynamicPlane() { const entity = createBasicPlane(); entity.plane.plane = createDynamicProperty_default( new import__89.Plane(import__89.Cartesian3.UNIT_X, 0) ); entity.plane.dimensions = createDynamicProperty_default(new import__89.Cartesian2(1, 2)); return entity; } it("A time-varying plane causes geometry to be dynamic", function() { const entity = createBasicPlane(); const updater = new import__89.PlaneGeometryUpdater(entity, scene2); entity.plane.plane = createDynamicProperty_default(); updater._onEntityPropertyChanged(entity, "plane"); expect(updater.isDynamic).toBe(true); }); it("A time-varying dimensions causes geometry to be dynamic", function() { const entity = createBasicPlane(); const updater = new import__89.PlaneGeometryUpdater(entity, scene2); entity.plane.dimensions = createDynamicProperty_default(); updater._onEntityPropertyChanged(entity, "plane"); expect(updater.isDynamic).toBe(true); }); it("dynamic updater sets properties", function() { const entity = createDynamicPlane(); const updater = new import__89.PlaneGeometryUpdater(entity, scene2); const dynamicUpdater = updater.createDynamicUpdater( new import__89.PrimitiveCollection(), new import__89.PrimitiveCollection() ); dynamicUpdater.update(import__89.JulianDate.now()); const options = dynamicUpdater._options; expect(options.plane).toEqual(entity.plane.plane.getValue()); expect(options.dimensions).toEqual(entity.plane.dimensions.getValue()); }); it("geometryChanged event is raised when expected", function() { const entity = createBasicPlane(); const updater = new import__89.PlaneGeometryUpdater(entity, scene2); const listener = jasmine.createSpy("listener"); updater.geometryChanged.addEventListener(listener); entity.plane.dimensions = new import__89.ConstantProperty(); updater._onEntityPropertyChanged(entity, "plane"); expect(listener.calls.count()).toEqual(1); entity.availability = new import__89.TimeIntervalCollection(); updater._onEntityPropertyChanged(entity, "availability"); expect(listener.calls.count()).toEqual(2); entity.plane.dimensions = void 0; updater._onEntityPropertyChanged(entity, "plane"); expect(listener.calls.count()).toEqual(3); entity.plane.height = void 0; updater._onEntityPropertyChanged(entity, "plane"); entity.viewFrom = new import__89.ConstantProperty(import__89.Cartesian3.UNIT_X); updater._onEntityPropertyChanged(entity, "viewFrom"); expect(listener.calls.count()).toEqual(3); }); function getScene() { return scene2; } createGeometryUpdaterSpecs_default( import__89.PlaneGeometryUpdater, "plane", createBasicPlane, getScene ); createDynamicGeometryUpdaterSpecs_default( import__89.PlaneGeometryUpdater, "plane", createDynamicPlane, getScene ); }, "WebGL" ); // packages/engine/Specs/DataSources/PlaneGraphicsSpec.js var import__90 = __toESM(require_Cesium(), 1); describe("DataSources/PlaneGraphics", function() { it("creates expected instance from raw assignment and construction", function() { const options = { material: import__90.Color.BLUE, show: true, fill: false, outline: false, outlineColor: import__90.Color.RED, outlineWidth: 1, plane: new import__90.Plane(import__90.Cartesian3.UNIT_X, 0), dimensions: new import__90.Cartesian2(2, 3), shadows: import__90.ShadowMode.DISABLED, distanceDisplayCondition: new import__90.DistanceDisplayCondition(10, 100) }; const plane = new import__90.PlaneGraphics(options); expect(plane.material).toBeInstanceOf(import__90.ColorMaterialProperty); expect(plane.show).toBeInstanceOf(import__90.ConstantProperty); expect(plane.fill).toBeInstanceOf(import__90.ConstantProperty); expect(plane.outline).toBeInstanceOf(import__90.ConstantProperty); expect(plane.outlineColor).toBeInstanceOf(import__90.ConstantProperty); expect(plane.outlineWidth).toBeInstanceOf(import__90.ConstantProperty); expect(plane.plane).toBeInstanceOf(import__90.ConstantProperty); expect(plane.dimensions).toBeInstanceOf(import__90.ConstantProperty); expect(plane.shadows).toBeInstanceOf(import__90.ConstantProperty); expect(plane.distanceDisplayCondition).toBeInstanceOf(import__90.ConstantProperty); expect(plane.material.color.getValue()).toEqual(options.material); expect(plane.show.getValue()).toEqual(options.show); expect(plane.fill.getValue()).toEqual(options.fill); expect(plane.outline.getValue()).toEqual(options.outline); expect(plane.outlineColor.getValue()).toEqual(options.outlineColor); expect(plane.outlineWidth.getValue()).toEqual(options.outlineWidth); expect(plane.plane.getValue()).toEqual(options.plane); expect(plane.dimensions.getValue()).toEqual(options.dimensions); expect(plane.shadows.getValue()).toEqual(options.shadows); expect(plane.distanceDisplayCondition.getValue()).toEqual( options.distanceDisplayCondition ); }); it("merge assigns unassigned properties", function() { const source = new import__90.PlaneGraphics(); source.material = new import__90.ColorMaterialProperty(); source.show = new import__90.ConstantProperty(); source.fill = new import__90.ConstantProperty(); source.outline = new import__90.ConstantProperty(); source.outlineColor = new import__90.ConstantProperty(); source.outlineWidth = new import__90.ConstantProperty(); source.plane = new import__90.ConstantProperty(); source.dimensions = new import__90.ConstantProperty(); source.shadows = new import__90.ConstantProperty(import__90.ShadowMode.ENABLED); source.distanceDisplayCondition = new import__90.ConstantProperty( new import__90.DistanceDisplayCondition(10, 100) ); const target = new import__90.PlaneGraphics(); target.merge(source); expect(target.material).toBe(source.material); expect(target.show).toBe(source.show); expect(target.fill).toBe(source.fill); expect(target.outline).toBe(source.outline); expect(target.outlineColor).toBe(source.outlineColor); expect(target.outlineWidth).toBe(source.outlineWidth); expect(target.plane).toBe(source.plane); expect(target.dimensions).toBe(source.dimensions); expect(target.shadows).toBe(source.shadows); expect(target.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); }); it("merge does not assign assigned properties", function() { const source = new import__90.PlaneGraphics(); const material = new import__90.ColorMaterialProperty(); const show = new import__90.ConstantProperty(); const fill = new import__90.ConstantProperty(); const outline = new import__90.ConstantProperty(); const outlineColor = new import__90.ConstantProperty(); const outlineWidth = new import__90.ConstantProperty(); const plane = new import__90.ConstantProperty(); const dimensions = new import__90.ConstantProperty(); const shadows = new import__90.ConstantProperty(); const distanceDisplayCondition = new import__90.ConstantProperty(); const target = new import__90.PlaneGraphics(); target.material = material; target.show = show; target.fill = fill; target.outline = outline; target.outlineColor = outlineColor; target.outlineWidth = outlineWidth; target.plane = plane; target.dimensions = dimensions; target.shadows = shadows; target.distanceDisplayCondition = distanceDisplayCondition; target.merge(source); expect(target.material).toBe(material); expect(target.show).toBe(show); expect(target.fill).toBe(fill); expect(target.outline).toBe(outline); expect(target.outlineColor).toBe(outlineColor); expect(target.outlineWidth).toBe(outlineWidth); expect(target.plane).toBe(plane); expect(target.dimensions).toBe(dimensions); expect(target.shadows).toBe(shadows); expect(target.distanceDisplayCondition).toBe(distanceDisplayCondition); }); it("clone works", function() { const source = new import__90.PlaneGraphics(); source.material = new import__90.ColorMaterialProperty(); source.show = new import__90.ConstantProperty(); source.fill = new import__90.ConstantProperty(); source.outline = new import__90.ConstantProperty(); source.outlineColor = new import__90.ConstantProperty(); source.outlineWidth = new import__90.ConstantProperty(); source.plane = new import__90.ConstantProperty(); source.dimensions = new import__90.ConstantProperty(); source.shadows = new import__90.ConstantProperty(); source.distanceDisplayCondition = new import__90.ConstantProperty(); const result = source.clone(); expect(result.material).toBe(source.material); expect(result.show).toBe(source.show); expect(result.fill).toBe(source.fill); expect(result.outline).toBe(source.outline); expect(result.outlineColor).toBe(source.outlineColor); expect(result.outlineWidth).toBe(source.outlineWidth); expect(result.plane).toBe(source.plane); expect(result.dimensions).toBe(source.dimensions); expect(result.shadows).toBe(source.shadows); expect(result.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); }); it("merge throws if source undefined", function() { const target = new import__90.PlaneGraphics(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__90.PlaneGraphics(); testMaterialDefinitionChanged_default(property, "material", import__90.Color.RED, import__90.Color.BLUE); testDefinitionChanged_default(property, "show", true, false); testDefinitionChanged_default(property, "fill", false, true); testDefinitionChanged_default(property, "outline", true, false); testDefinitionChanged_default(property, "outlineColor", import__90.Color.RED, import__90.Color.BLUE); testDefinitionChanged_default(property, "outlineWidth", 2, 3); testDefinitionChanged_default( property, "plane", new import__90.Plane(import__90.Cartesian3.UNIT_X, 0), new import__90.Plane(import__90.Cartesian3.UNIT_Z, 1) ); testDefinitionChanged_default( property, "dimensions", new import__90.Cartesian2(0, 0), new import__90.Cartesian2(1, 1) ); testDefinitionChanged_default( property, "shadows", import__90.ShadowMode.ENABLED, import__90.ShadowMode.DISABLED ); testDefinitionChanged_default( property, "distanceDisplayCondition", new import__90.DistanceDisplayCondition(), new import__90.DistanceDisplayCondition(10, 100) ); }); }); // packages/engine/Specs/DataSources/PointGraphicsSpec.js var import__91 = __toESM(require_Cesium(), 1); describe("DataSources/PointGraphics", function() { it("creates expected instance from raw assignment and construction", function() { const options = { color: import__91.Color.RED, pixelSize: 1, outlineColor: import__91.Color.BLUE, outlineWidth: 2, show: false, scaleByDistance: new import__91.NearFarScalar(3, 4, 5, 6), heightReference: import__91.HeightReference.RELATIVE_TO_GROUND, distanceDisplayCondition: new import__91.DistanceDisplayCondition(10, 100), disableDepthTestDistance: 10 }; const point = new import__91.PointGraphics(options); expect(point.color).toBeInstanceOf(import__91.ConstantProperty); expect(point.pixelSize).toBeInstanceOf(import__91.ConstantProperty); expect(point.outlineColor).toBeInstanceOf(import__91.ConstantProperty); expect(point.outlineWidth).toBeInstanceOf(import__91.ConstantProperty); expect(point.show).toBeInstanceOf(import__91.ConstantProperty); expect(point.scaleByDistance).toBeInstanceOf(import__91.ConstantProperty); expect(point.heightReference).toBeInstanceOf(import__91.ConstantProperty); expect(point.distanceDisplayCondition).toBeInstanceOf(import__91.ConstantProperty); expect(point.disableDepthTestDistance).toBeInstanceOf(import__91.ConstantProperty); expect(point.color.getValue()).toEqual(options.color); expect(point.pixelSize.getValue()).toEqual(options.pixelSize); expect(point.outlineColor.getValue()).toEqual(options.outlineColor); expect(point.outlineWidth.getValue()).toEqual(options.outlineWidth); expect(point.show.getValue()).toEqual(options.show); expect(point.scaleByDistance.getValue()).toEqual(options.scaleByDistance); expect(point.heightReference.getValue()).toEqual(options.heightReference); expect(point.distanceDisplayCondition.getValue()).toEqual( options.distanceDisplayCondition ); expect(point.disableDepthTestDistance.getValue()).toEqual( options.disableDepthTestDistance ); }); it("merge assigns unassigned properties", function() { const source = new import__91.PointGraphics(); source.color = new import__91.ConstantProperty(import__91.Color.WHITE); source.pixelSize = new import__91.ConstantProperty(1); source.outlineColor = new import__91.ConstantProperty(import__91.Color.WHITE); source.outlineWidth = new import__91.ConstantProperty(1); source.show = new import__91.ConstantProperty(true); source.scaleByDistance = new import__91.ConstantProperty(new import__91.NearFarScalar()); source.heightReference = new import__91.ConstantProperty( import__91.HeightReference.RELATIVE_TO_GROUND ); source.distanceDisplayCondition = new import__91.ConstantProperty( new import__91.DistanceDisplayCondition(10, 100) ); source.disableDepthTestDistance = new import__91.ConstantProperty(10); const target = new import__91.PointGraphics(); target.merge(source); expect(target.color).toBe(source.color); expect(target.pixelSize).toBe(source.pixelSize); expect(target.outlineColor).toBe(source.outlineColor); expect(target.outlineWidth).toBe(source.outlineWidth); expect(target.show).toBe(source.show); expect(target.scaleByDistance).toBe(source.scaleByDistance); expect(target.heightReference).toBe(source.heightReference); expect(target.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(target.disableDepthTestDistance).toBe( source.disableDepthTestDistance ); }); it("merge does not assign assigned properties", function() { const source = new import__91.PointGraphics(); source.color = new import__91.ConstantProperty(import__91.Color.WHITE); source.pixelSize = new import__91.ConstantProperty(1); source.outlineColor = new import__91.ConstantProperty(import__91.Color.WHITE); source.outlineWidth = new import__91.ConstantProperty(1); source.show = new import__91.ConstantProperty(true); source.scaleByDistance = new import__91.ConstantProperty(new import__91.NearFarScalar()); source.heightReference = new import__91.ConstantProperty( import__91.HeightReference.RELATIVE_TO_GROUND ); source.distanceDisplayCondition = new import__91.ConstantProperty( new import__91.DistanceDisplayCondition(10, 100) ); source.disableDepthTestDistance = new import__91.ConstantProperty(10); const color = new import__91.ConstantProperty(import__91.Color.WHITE); const pixelSize = new import__91.ConstantProperty(1); const outlineColor = new import__91.ConstantProperty(import__91.Color.WHITE); const outlineWidth = new import__91.ConstantProperty(1); const show = new import__91.ConstantProperty(true); const heightReference = new import__91.ConstantProperty( import__91.HeightReference.CLAMP_TO_GROUND ); const distanDisplayCondition = new import__91.ConstantProperty( new import__91.DistanceDisplayCondition(10, 100) ); const disableDepthTestDistance = new import__91.ConstantProperty(20); const target = new import__91.PointGraphics(); target.color = color; target.pixelSize = pixelSize; target.outlineColor = outlineColor; target.outlineWidth = outlineWidth; target.show = show; target.scaleByDistance = show; target.heightReference = heightReference; target.distanceDisplayCondition = distanDisplayCondition; target.disableDepthTestDistance = disableDepthTestDistance; target.merge(source); expect(target.color).toBe(color); expect(target.pixelSize).toBe(pixelSize); expect(target.outlineColor).toBe(outlineColor); expect(target.outlineWidth).toBe(outlineWidth); expect(target.show).toBe(show); expect(target.scaleByDistance).toBe(show); expect(target.heightReference).toBe(heightReference); expect(target.distanceDisplayCondition).toBe(distanDisplayCondition); expect(target.disableDepthTestDistance).toBe(disableDepthTestDistance); }); it("clone works", function() { const source = new import__91.PointGraphics(); source.color = new import__91.ConstantProperty(import__91.Color.WHITE); source.pixelSize = new import__91.ConstantProperty(1); source.outlineColor = new import__91.ConstantProperty(import__91.Color.WHITE); source.outlineWidth = new import__91.ConstantProperty(1); source.show = new import__91.ConstantProperty(true); source.scaleByDistance = new import__91.ConstantProperty(new import__91.NearFarScalar()); source.heightReference = new import__91.ConstantProperty( import__91.HeightReference.RELATIVE_TO_GROUND ); source.distanceDisplayCondition = new import__91.ConstantProperty( new import__91.DistanceDisplayCondition(10, 100) ); source.disableDepthTestDistance = new import__91.ConstantProperty(10); const result = source.clone(); expect(result.color).toBe(source.color); expect(result.pixelSize).toBe(source.pixelSize); expect(result.outlineColor).toBe(source.outlineColor); expect(result.outlineWidth).toBe(source.outlineWidth); expect(result.show).toBe(source.show); expect(result.scaleByDistance).toBe(source.scaleByDistance); expect(result.heightReference).toBe(source.heightReference); expect(result.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(result.disableDepthTestDistance).toBe( source.disableDepthTestDistance ); }); it("merge throws if source undefined", function() { const target = new import__91.PointGraphics(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/PointVisualizerSpec.js var import__92 = __toESM(require_Cesium(), 1); describe( "DataSources/PointVisualizer", function() { let scene2; let entityCluster; let visualizer; beforeAll(function() { scene2 = createScene_default(); scene2.globe = { ellipsoid: import__92.Ellipsoid.WGS84, _surface: {}, imageryLayersUpdatedEvent: new import__92.Event(), terrainProviderChanged: new import__92.Event(), tileLoadProgressEvent: new import__92.Event() }; scene2.globe.getHeight = function() { return 0; }; scene2.globe.destroy = function() { }; scene2.globe._surface.updateHeight = function() { }; Object.defineProperties(scene2.globe, { terrainProvider: { set: function(value) { this.terrainProviderChanged.raiseEvent(value); } } }); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { entityCluster = new import__92.EntityCluster(); entityCluster._initialize(scene2); }); afterEach(function() { if ((0, import__92.defined)(visualizer)) { visualizer = visualizer.destroy(); } entityCluster.destroy(); }); it("constructor throws if no scene is passed.", function() { const entityCollection = new import__92.EntityCollection(); expect(function() { return new import__92.PointVisualizer(void 0, entityCollection); }).toThrowDeveloperError(); }); it("constructor throws if no entityCollection is passed.", function() { expect(function() { return new import__92.PointVisualizer(entityCluster, void 0); }).toThrowDeveloperError(); }); it("update throws if no time specified.", function() { const entityCollection = new import__92.EntityCollection(); visualizer = new import__92.PointVisualizer(entityCluster, entityCollection); expect(function() { visualizer.update(); }).toThrowDeveloperError(); }); it("isDestroy returns false until destroyed.", function() { const entityCollection = new import__92.EntityCollection(); visualizer = new import__92.PointVisualizer(entityCluster, entityCollection); expect(visualizer.isDestroyed()).toEqual(false); visualizer.destroy(); expect(visualizer.isDestroyed()).toEqual(true); visualizer = void 0; }); it("removes the listener from the entity collection when destroyed", function() { const entityCollection = new import__92.EntityCollection(); visualizer = new import__92.PointVisualizer(entityCluster, entityCollection); expect(entityCollection.collectionChanged.numberOfListeners).toEqual(1); visualizer.destroy(); expect(entityCollection.collectionChanged.numberOfListeners).toEqual(0); visualizer = void 0; }); it("object with no point does not create a pointPrimitive.", function() { const entityCollection = new import__92.EntityCollection(); visualizer = new import__92.PointVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__92.ConstantProperty( new import__92.Cartesian3(1234, 5678, 9101112) ); visualizer.update(import__92.JulianDate.now()); expect(scene2.primitives.length).toEqual(0); }); it("object with no position does not create a pointPrimitive.", function() { const entityCollection = new import__92.EntityCollection(); visualizer = new import__92.PointVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); const point = testObject.point = new import__92.PointGraphics(); point.show = new import__92.ConstantProperty(true); visualizer.update(import__92.JulianDate.now()); expect(scene2.primitives.length).toEqual(0); }); it("A PointGraphics causes a PointPrimitive to be created and updated.", function() { const time2 = import__92.JulianDate.now(); const entityCollection = new import__92.EntityCollection(); visualizer = new import__92.PointVisualizer(entityCluster, entityCollection); const entity = entityCollection.add({ position: new import__92.Cartesian3(1234, 5678, 9101112), point: { show: true, color: new import__92.Color(0.1, 0.2, 0.3, 0.4), outlineColor: new import__92.Color(0.5, 0.6, 0.7, 0.8), outlineWidth: 9, pixelSize: 10, scaleByDistance: new import__92.NearFarScalar(11, 12, 13, 14), distanceDisplayCondition: new import__92.DistanceDisplayCondition(10, 100), disableDepthTestDistance: 10 } }); const point = entity.point; visualizer.update(time2); const pointPrimitiveCollection = entityCluster._pointCollection; expect(pointPrimitiveCollection).toBeInstanceOf(import__92.PointPrimitiveCollection); expect(pointPrimitiveCollection.length).toEqual(1); const pointPrimitive = pointPrimitiveCollection.get(0); expect(pointPrimitive.show).toEqual(point.show.getValue(time2)); expect(pointPrimitive.position).toEqual(entity.position.getValue(time2)); expect(pointPrimitive.scaleByDistance).toEqual( point.scaleByDistance.getValue(time2) ); expect(pointPrimitive.color).toEqual(point.color.getValue(time2)); expect(pointPrimitive.outlineColor).toEqual( point.outlineColor.getValue(time2) ); expect(pointPrimitive.outlineWidth).toEqual( point.outlineWidth.getValue(time2) ); expect(pointPrimitive.distanceDisplayCondition).toEqual( point.distanceDisplayCondition.getValue(time2) ); expect(pointPrimitive.disableDepthTestDistance).toEqual( point.disableDepthTestDistance.getValue(time2) ); point.color = new import__92.Color(0.15, 0.16, 0.17, 0.18); point.outlineColor = new import__92.Color(0.19, 0.2, 0.21, 0.22); point.pixelSize = 23; point.outlineWidth = 24; point.scaleByDistance = new import__92.NearFarScalar(25, 26, 27, 28); point.distanceDisplayCondition = new import__92.DistanceDisplayCondition( 1e3, 1e6 ); point.disableDepthTestDistance = 20; visualizer.update(time2); expect(pointPrimitive.show).toEqual(point.show.getValue(time2)); expect(pointPrimitive.position).toEqual(entity.position.getValue(time2)); expect(pointPrimitive.scaleByDistance).toEqual( point.scaleByDistance.getValue(time2) ); expect(pointPrimitive.color).toEqual(point.color.getValue(time2)); expect(pointPrimitive.outlineColor).toEqual( point.outlineColor.getValue(time2) ); expect(pointPrimitive.outlineWidth).toEqual( point.outlineWidth.getValue(time2) ); expect(pointPrimitive.distanceDisplayCondition).toEqual( point.distanceDisplayCondition.getValue(time2) ); expect(pointPrimitive.disableDepthTestDistance).toEqual( point.disableDepthTestDistance.getValue(time2) ); point.show = false; visualizer.update(time2); expect(pointPrimitive.show).toEqual(point.show.getValue(time2)); }); it("A PointGraphics on terrain causes a Billboard to be created and updated.", function() { const time2 = import__92.JulianDate.now(); const entityCollection = new import__92.EntityCollection(); visualizer = new import__92.PointVisualizer(entityCluster, entityCollection); const entity = entityCollection.add({ position: new import__92.Cartesian3(1234, 5678, 9101112), point: { show: true, color: new import__92.Color(0.1, 0.2, 0.3, 0.4), outlineColor: new import__92.Color(0.5, 0.6, 0.7, 0.8), outlineWidth: 9, pixelSize: 10, scaleByDistance: new import__92.NearFarScalar(11, 12, 13, 14), distanceDisplayCondition: new import__92.DistanceDisplayCondition(10, 100), disableDepthTestDistance: 10, heightReference: import__92.HeightReference.CLAMP_TO_GROUND } }); const point = entity.point; visualizer.update(time2); const billboardCollection = entityCluster._billboardCollection; expect(billboardCollection).toBeInstanceOf(import__92.BillboardCollection); expect(billboardCollection.length).toEqual(1); const billboard = billboardCollection.get(0); expect(billboard.show).toEqual(point.show.getValue(time2)); expect(billboard.position).toEqual(entity.position.getValue(time2)); expect(billboard.scaleByDistance).toEqual( point.scaleByDistance.getValue(time2) ); expect(billboard.distanceDisplayCondition).toEqual( point.distanceDisplayCondition.getValue(time2) ); expect(billboard.disableDepthTestDistance).toEqual( point.disableDepthTestDistance.getValue(time2) ); point.color = new import__92.Color(0.15, 0.16, 0.17, 0.18); point.outlineColor = new import__92.Color(0.19, 0.2, 0.21, 0.22); point.pixelSize = 23; point.outlineWidth = 24; point.scaleByDistance = new import__92.NearFarScalar(25, 26, 27, 28); point.distanceDisplayCondition = new import__92.DistanceDisplayCondition( 1e3, 1e6 ); point.disableDepthTestDistance = 20; visualizer.update(time2); expect(billboard.show).toEqual(point.show.getValue(time2)); expect(billboard.position).toEqual(entity.position.getValue(time2)); expect(billboard.scaleByDistance).toEqual( point.scaleByDistance.getValue(time2) ); expect(billboard.distanceDisplayCondition).toEqual( point.distanceDisplayCondition.getValue(time2) ); expect(billboard.disableDepthTestDistance).toEqual( point.disableDepthTestDistance.getValue(time2) ); point.show = false; visualizer.update(time2); expect(billboard.show).toEqual(point.show.getValue(time2)); }); it("Reuses primitives when hiding one and showing another", function() { const time2 = import__92.JulianDate.now(); const entityCollection = new import__92.EntityCollection(); visualizer = new import__92.PointVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); testObject.position = new import__92.ConstantProperty( new import__92.Cartesian3(1234, 5678, 9101112) ); testObject.point = new import__92.PointGraphics(); testObject.point.show = new import__92.ConstantProperty(true); visualizer.update(time2); const pointPrimitiveCollection = entityCluster._pointCollection; expect(pointPrimitiveCollection.length).toEqual(1); testObject.point.show = new import__92.ConstantProperty(false); visualizer.update(time2); expect(pointPrimitiveCollection.length).toEqual(1); const testObject2 = entityCollection.getOrCreateEntity("test2"); testObject2.position = new import__92.ConstantProperty( new import__92.Cartesian3(1234, 5678, 9101112) ); testObject2.point = new import__92.PointGraphics(); testObject2.point.show = new import__92.ConstantProperty(true); visualizer.update(time2); expect(pointPrimitiveCollection.length).toEqual(1); }); it("clear hides pointPrimitives.", function() { const entityCollection = new import__92.EntityCollection(); visualizer = new import__92.PointVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); const time2 = import__92.JulianDate.now(); testObject.position = new import__92.ConstantProperty( new import__92.Cartesian3(1234, 5678, 9101112) ); const point = testObject.point = new import__92.PointGraphics(); point.show = new import__92.ConstantProperty(true); visualizer.update(time2); const pointPrimitiveCollection = entityCluster._pointCollection; expect(pointPrimitiveCollection.length).toEqual(1); const bb = pointPrimitiveCollection.get(0); visualizer.update(time2); entityCollection.removeAll(); expect(bb.show).toEqual(false); expect(bb.id).toBeUndefined(); }); it("Visualizer sets entity property.", function() { const entityCollection = new import__92.EntityCollection(); visualizer = new import__92.PointVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); const time2 = import__92.JulianDate.now(); const point = testObject.point = new import__92.PointGraphics(); testObject.position = new import__92.ConstantProperty( new import__92.Cartesian3(1234, 5678, 9101112) ); point.show = new import__92.ConstantProperty(true); visualizer.update(time2); const pointPrimitiveCollection = entityCluster._pointCollection; expect(pointPrimitiveCollection.length).toEqual(1); const bb = pointPrimitiveCollection.get(0); expect(bb.id).toEqual(testObject); }); it("Computes bounding sphere.", function() { const entityCollection = new import__92.EntityCollection(); visualizer = new import__92.PointVisualizer(entityCluster, entityCollection); const testObject = entityCollection.getOrCreateEntity("test"); const time2 = import__92.JulianDate.now(); const point = testObject.point = new import__92.PointGraphics(); testObject.position = new import__92.ConstantProperty( new import__92.Cartesian3(1234, 5678, 9101112) ); point.show = new import__92.ConstantProperty(true); visualizer.update(time2); const result = new import__92.BoundingSphere(); const state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__92.BoundingSphereState.DONE); expect(result.center).toEqual(testObject.position.getValue()); expect(result.radius).toEqual(0); }); it("Fails bounding sphere for entity without pointPrimitive.", function() { const entityCollection = new import__92.EntityCollection(); const testObject = entityCollection.getOrCreateEntity("test"); visualizer = new import__92.PointVisualizer(entityCluster, entityCollection); visualizer.update(import__92.JulianDate.now()); const result = new import__92.BoundingSphere(); const state2 = visualizer.getBoundingSphere(testObject, result); expect(state2).toBe(import__92.BoundingSphereState.FAILED); }); it("Compute bounding sphere throws without entity.", function() { const entityCollection = new import__92.EntityCollection(); visualizer = new import__92.PointVisualizer(entityCluster, entityCollection); const result = new import__92.BoundingSphere(); expect(function() { visualizer.getBoundingSphere(void 0, result); }).toThrowDeveloperError(); }); it("Compute bounding sphere throws without result.", function() { const entityCollection = new import__92.EntityCollection(); const testObject = entityCollection.getOrCreateEntity("test"); visualizer = new import__92.PointVisualizer(entityCluster, entityCollection); expect(function() { visualizer.getBoundingSphere(testObject, void 0); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/DataSources/PolygonGeometryUpdaterSpec.js var import__93 = __toESM(require_Cesium(), 1); var import__94 = __toESM(require_Cesium(), 1); describe( "DataSources/PolygonGeometryUpdater", function() { let scene2; let time2; let groundPrimitiveSupported; beforeAll(function() { scene2 = createScene_default(); time2 = import__93.JulianDate.now(); groundPrimitiveSupported = import__93.GroundPrimitive.isSupported(scene2); return import__93.ApproximateTerrainHeights.initialize(); }); afterAll(function() { scene2.destroyForSpecs(); import__93.ApproximateTerrainHeights._initPromise = void 0; import__93.ApproximateTerrainHeights._terrainHeights = void 0; }); function createBasicPolygon() { const polygon = new import__93.PolygonGraphics(); polygon.hierarchy = new import__93.ConstantProperty( new import__93.PolygonHierarchy( import__93.Cartesian3.fromRadiansArray([-1, -1, 1, -1, 1, 1, -1, 1]) ) ); polygon.height = new import__93.ConstantProperty(0); const entity = new import__93.Entity(); entity.polygon = polygon; return entity; } function createVerticalPolygon() { const polygon = new import__93.PolygonGraphics(); polygon.hierarchy = new import__93.ConstantProperty( new import__93.PolygonHierarchy( import__93.Cartesian3.fromDegreesArrayHeights([ -1, 1, 0, -2, 1, 0, -2, 1, 0 ]) ) ); polygon.perPositionHeight = true; const entity = new import__93.Entity(); entity.polygon = polygon; return entity; } function createDynamicPolygon() { const entity = createBasicPolygon(); entity.polygon.extrudedHeight = createDynamicProperty_default(2); return entity; } function createBasicPolygonWithoutHeight() { const polygon = new import__93.PolygonGraphics(); polygon.hierarchy = new import__93.ConstantProperty( new import__93.PolygonHierarchy( import__93.Cartesian3.fromRadiansArray([0, 0, 1, 0, 1, 1, 0, 1]) ) ); const entity = new import__93.Entity(); entity.polygon = polygon; return entity; } function createDynamicPolygonWithoutHeight() { const entity = createBasicPolygonWithoutHeight(); entity.polygon.granularity = createDynamicProperty_default(1); return entity; } it("Properly computes isClosed", function() { const entity = createBasicPolygon(); entity.polygon.perPositionHeight = true; const updater = new import__93.PolygonGeometryUpdater(entity, scene2); expect(updater.isClosed).toBe(false); entity.polygon.perPositionHeight = false; updater._onEntityPropertyChanged(entity, "polygon"); expect(updater.isClosed).toBe(true); entity.polygon.height = 1e3; updater._onEntityPropertyChanged(entity, "polygon"); expect(updater.isClosed).toBe(false); entity.polygon.extrudedHeight = 1e3; updater._onEntityPropertyChanged(entity, "polygon"); expect(updater.isClosed).toBe(false); entity.polygon.extrudedHeight = 100; updater._onEntityPropertyChanged(entity, "polygon"); expect(updater.isClosed).toBe(true); entity.polygon.closeTop = false; updater._onEntityPropertyChanged(entity, "polygon"); expect(updater.isClosed).toBe(false); entity.polygon.closeTop = true; entity.polygon.closeBottom = false; updater._onEntityPropertyChanged(entity, "polygon"); expect(updater.isClosed).toBe(false); }); it("A time-varying positions causes geometry to be dynamic", function() { const entity = createBasicPolygon(); const updater = new import__93.PolygonGeometryUpdater(entity, scene2); const point1 = new import__93.SampledPositionProperty(); point1.addSample(time2, new import__93.Cartesian3()); const point2 = new import__93.SampledPositionProperty(); point2.addSample(time2, new import__93.Cartesian3()); const point3 = new import__93.SampledPositionProperty(); point3.addSample(time2, new import__93.Cartesian3()); entity.polygon.hierarchy = new import__93.PropertyArray(); entity.polygon.hierarchy.setValue([point1, point2, point3]); updater._onEntityPropertyChanged(entity, "polygon"); expect(updater.isDynamic).toBe(true); }); it("A time-varying height causes geometry to be dynamic", function() { const entity = createBasicPolygon(); const updater = new import__93.PolygonGeometryUpdater(entity, scene2); entity.polygon.height = new import__93.SampledProperty(Number); entity.polygon.height.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "polygon"); expect(updater.isDynamic).toBe(true); }); it("A time-varying extrudedHeight causes geometry to be dynamic", function() { const entity = createBasicPolygon(); const updater = new import__93.PolygonGeometryUpdater(entity, scene2); entity.polygon.extrudedHeight = new import__93.SampledProperty(Number); entity.polygon.extrudedHeight.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "polygon"); expect(updater.isDynamic).toBe(true); }); it("A time-varying granularity causes geometry to be dynamic", function() { const entity = createBasicPolygon(); const updater = new import__93.PolygonGeometryUpdater(entity, scene2); entity.polygon.granularity = new import__93.SampledProperty(Number); entity.polygon.granularity.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "polygon"); expect(updater.isDynamic).toBe(true); }); it("A time-varying stRotation causes geometry to be dynamic", function() { const entity = createBasicPolygon(); const updater = new import__93.PolygonGeometryUpdater(entity, scene2); entity.polygon.stRotation = new import__93.SampledProperty(Number); entity.polygon.stRotation.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "polygon"); expect(updater.isDynamic).toBe(true); }); it("A time-varying perPositionHeight causes geometry to be dynamic", function() { const entity = createBasicPolygon(); const updater = new import__93.PolygonGeometryUpdater(entity, scene2); entity.polygon.perPositionHeight = new import__93.SampledProperty(Number); entity.polygon.perPositionHeight.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "polygon"); expect(updater.isDynamic).toBe(true); }); it("A time-varying arcType causes geometry to be dynamic", function() { const entity = createBasicPolygon(); const updater = new import__93.PolygonGeometryUpdater(entity, scene2); entity.polygon.arcType = new import__93.SampledProperty(Number); entity.polygon.arcType.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "polygon"); expect(updater.isDynamic).toBe(true); }); it("Creates geometry with expected properties", function() { const options = { height: 431, extrudedHeight: 123, granularity: 0.97, stRotation: 12, perPositionHeight: false, closeTop: true, closeBottom: false, arcType: import__93.ArcType.GEODESIC, textureCoordinates: [[0.5, 0.3]] }; const entity = createBasicPolygon(); const polygon = entity.polygon; polygon.outline = true; polygon.perPositionHeight = new import__93.ConstantProperty( options.perPositionHeight ); polygon.closeTop = new import__93.ConstantProperty(options.closeTop); polygon.closeBottom = new import__93.ConstantProperty(options.closeBottom); polygon.stRotation = new import__93.ConstantProperty(options.stRotation); polygon.height = new import__93.ConstantProperty(options.height); polygon.extrudedHeight = new import__93.ConstantProperty(options.extrudedHeight); polygon.granularity = new import__93.ConstantProperty(options.granularity); polygon.arcType = new import__93.ConstantProperty(options.arcType); polygon.textureCoordinates = new import__93.ConstantProperty( options.textureCoordinates ); const updater = new import__93.PolygonGeometryUpdater(entity, scene2); let instance; let geometry; instance = updater.createFillGeometryInstance(time2); geometry = instance.geometry; expect(geometry).toBeInstanceOf(import__93.PolygonGeometry); expect(geometry._stRotation).toEqual(options.stRotation); expect(geometry._height).toEqual(options.height); expect(geometry._granularity).toEqual(options.granularity); expect(geometry._extrudedHeight).toEqual(options.extrudedHeight); expect(geometry._closeTop).toEqual(options.closeTop); expect(geometry._closeBottom).toEqual(options.closeBottom); expect(geometry._arcType).toEqual(options.arcType); expect(geometry._textureCoordinates).toEqual(options.textureCoordinates); expect(geometry._offsetAttribute).toBeUndefined(); instance = updater.createOutlineGeometryInstance(time2); geometry = instance.geometry; expect(geometry).toBeInstanceOf(import__93.PolygonOutlineGeometry); expect(geometry._height).toEqual(options.height); expect(geometry._granularity).toEqual(options.granularity); expect(geometry._extrudedHeight).toEqual(options.extrudedHeight); expect(geometry._perPositionHeight).toEqual(options.perPositionHeight); expect(geometry._offsetAttribute).toBeUndefined(); }); it("Creates coplanar polygon", function() { const stRotation = 12; const textureCoordinates = [0.3, 0.4]; const entity = createVerticalPolygon(); const polygon = entity.polygon; polygon.outline = true; polygon.stRotation = new import__93.ConstantProperty(stRotation); polygon.textureCoordinates = new import__93.ConstantProperty(textureCoordinates); const updater = new import__93.PolygonGeometryUpdater(entity, scene2); let instance; let geometry; instance = updater.createFillGeometryInstance(time2); geometry = instance.geometry; expect(geometry).toBeInstanceOf(import__93.CoplanarPolygonGeometry); expect(geometry._stRotation).toEqual(stRotation); expect(geometry._textureCoordinates).toEqual(textureCoordinates); instance = updater.createOutlineGeometryInstance(time2); geometry = instance.geometry; expect(geometry).toBeInstanceOf(import__93.CoplanarPolygonOutlineGeometry); }); it("Checks that a polygon with per position heights isn't on terrain", function() { const entity = createBasicPolygon(); entity.polygon.height = void 0; entity.polygon.perPositionHeight = new import__93.ConstantProperty(true); const updater = new import__93.PolygonGeometryUpdater(entity, scene2); expect(updater.onTerrain).toBe(false); }); it("Checks that a polygon without per position heights is on terrain", function() { const entity = createBasicPolygon(); entity.polygon.height = void 0; entity.polygon.perPositionHeight = new import__93.ConstantProperty(false); const updater = new import__93.PolygonGeometryUpdater(entity, scene2); if (groundPrimitiveSupported) { expect(updater.onTerrain).toBe(true); } else { expect(updater.onTerrain).toBe(false); } }); it("Checks that a polygon without per position heights does not use a height reference", function() { const entity = createBasicPolygon(); const graphics = entity.polygon; graphics.perPositionHeight = new import__93.ConstantProperty(true); graphics.outline = true; graphics.outlineColor = import__93.Color.BLACK; graphics.height = void 0; graphics.extrudedHeight = void 0; const updater = new import__93.PolygonGeometryUpdater(entity, scene2); let instance; graphics.heightReference = new import__93.ConstantProperty( import__93.HeightReference.RELATIVE_TO_GROUND ); graphics.extrudedHeightReference = new import__93.ConstantProperty( import__93.HeightReference.RELATIVE_TO_GROUND ); updater._onEntityPropertyChanged(entity, "polygon"); instance = updater.createFillGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); instance = updater.createOutlineGeometryInstance(time2); expect(instance.geometry._offsetAttribute).toBeUndefined(); }); it("dynamic updater sets properties", function() { const polygon = new import__93.PolygonGraphics(); polygon.hierarchy = createDynamicProperty_default( new import__93.PolygonHierarchy( import__93.Cartesian3.fromRadiansArray([0, 0, 1, 0, 1, 1, 0, 1]) ) ); polygon.height = createDynamicProperty_default(3); polygon.extrudedHeight = createDynamicProperty_default(2); polygon.perPositionHeight = createDynamicProperty_default(false); polygon.granularity = createDynamicProperty_default(2); polygon.stRotation = createDynamicProperty_default(1); polygon.textureCoordinates = createDynamicProperty_default({ positions: [ new import__93.Cartesian2(0.5, 1), new import__93.Cartesian2(0, 0.5), new import__93.Cartesian2(0.5, 0), new import__93.Cartesian2(1, 0.5) ] }); polygon.closeTop = createDynamicProperty_default(false); polygon.closeBottom = createDynamicProperty_default(false); polygon.arcType = createDynamicProperty_default(import__93.ArcType.RHUMB); const entity = new import__93.Entity(); entity.polygon = polygon; const updater = new import__93.PolygonGeometryUpdater(entity, scene2); const dynamicUpdater = updater.createDynamicUpdater( new import__93.PrimitiveCollection(), new import__93.PrimitiveCollection() ); dynamicUpdater.update(time2); const options = dynamicUpdater._options; expect(options.id).toEqual(entity); expect(options.polygonHierarchy).toEqual(polygon.hierarchy.getValue()); expect(options.height).toEqual(polygon.height.getValue()); expect(options.extrudedHeight).toEqual(polygon.extrudedHeight.getValue()); expect(options.perPositionHeight).toEqual( polygon.perPositionHeight.getValue() ); expect(options.granularity).toEqual(polygon.granularity.getValue()); expect(options.stRotation).toEqual(polygon.stRotation.getValue()); expect(options.textureCoordinates).toEqual( polygon.textureCoordinates.getValue() ); expect(options.closeTop).toEqual(polygon.closeTop.getValue()); expect(options.closeBottom).toEqual(polygon.closeBottom.getValue()); expect(options.arcType).toEqual(polygon.arcType.getValue()); expect(options.offsetAttribute).toBeUndefined(); }); it("geometryChanged event is raised when expected", function() { const entity = createBasicPolygon(); const updater = new import__93.PolygonGeometryUpdater(entity, scene2); const listener = jasmine.createSpy("listener"); updater.geometryChanged.addEventListener(listener); entity.polygon.hierarchy = new import__93.ConstantProperty([]); updater._onEntityPropertyChanged(entity, "polygon"); expect(listener.calls.count()).toEqual(1); entity.polygon.height = new import__93.ConstantProperty(82); updater._onEntityPropertyChanged(entity, "polygon"); expect(listener.calls.count()).toEqual(2); entity.availability = new import__93.TimeIntervalCollection(); updater._onEntityPropertyChanged(entity, "availability"); expect(listener.calls.count()).toEqual(3); entity.polygon.hierarchy = void 0; updater._onEntityPropertyChanged(entity, "polygon"); expect(listener.calls.count()).toEqual(4); entity.polygon.height = void 0; updater._onEntityPropertyChanged(entity, "polygon"); entity.viewFrom = new import__93.ConstantProperty(import__93.Cartesian3.UNIT_X); updater._onEntityPropertyChanged(entity, "viewFrom"); expect(listener.calls.count()).toEqual(4); }); it("perPositionHeight is true sets onTerrain to false", function() { const entity = createBasicPolygonWithoutHeight(); entity.polygon.fill = true; entity.polygon.perPositionHeight = true; const updater = new import__93.PolygonGeometryUpdater(entity, scene2); expect(updater.onTerrain).toBe(false); }); it("computes center", function() { const entity = createBasicPolygon(); const updater = new import__93.PolygonGeometryUpdater(entity, scene2); let result = updater._computeCenter(time2); result = import__93.Ellipsoid.WGS84.scaleToGeodeticSurface(result, result); expect(result).toEqualEpsilon( import__93.Cartesian3.fromDegrees(0, 0), import__94.Math.EPSILON10 ); }); function getScene() { return scene2; } createGeometryUpdaterSpecs_default( import__93.PolygonGeometryUpdater, "polygon", createBasicPolygon, getScene ); createDynamicGeometryUpdaterSpecs_default( import__93.PolygonGeometryUpdater, "polygon", createDynamicPolygon, getScene ); createGeometryUpdaterGroundGeometrySpecs_default( import__93.PolygonGeometryUpdater, "polygon", createBasicPolygonWithoutHeight, createDynamicPolygonWithoutHeight, getScene ); }, "WebGL" ); // packages/engine/Specs/DataSources/PolygonGraphicsSpec.js var import__95 = __toESM(require_Cesium(), 1); describe("DataSources/PolygonGraphics", function() { it("creates expected instance from raw assignment and construction", function() { const options = { material: import__95.Color.BLUE, show: true, hierarchy: new import__95.PolygonHierarchy(), height: 2, extrudedHeight: 3, granularity: 4, stRotation: 5, perPositionHeight: false, fill: false, outline: false, outlineColor: import__95.Color.RED, outlineWidth: 7, closeTop: true, closeBottom: true, shadows: import__95.ShadowMode.DISABLED, distanceDisplayCondition: new import__95.DistanceDisplayCondition(), classificationType: import__95.ClassificationType.TERRAIN, arcType: import__95.ArcType.GEODESIC, zIndex: 22, textureCoordinates: [] }; const polygon = new import__95.PolygonGraphics(options); expect(polygon.material).toBeInstanceOf(import__95.ColorMaterialProperty); expect(polygon.show).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.hierarchy).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.height).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.extrudedHeight).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.granularity).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.stRotation).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.perPositionHeight).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.fill).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.outline).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.outlineColor).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.outlineWidth).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.closeTop).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.closeBottom).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.shadows).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.distanceDisplayCondition).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.classificationType).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.arcType).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.zIndex).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.textureCoordinates).toBeInstanceOf(import__95.ConstantProperty); expect(polygon.material.color.getValue()).toEqual(options.material); expect(polygon.show.getValue()).toEqual(options.show); expect(polygon.hierarchy.getValue()).toEqual(options.hierarchy); expect(polygon.height.getValue()).toEqual(options.height); expect(polygon.extrudedHeight.getValue()).toEqual(options.extrudedHeight); expect(polygon.granularity.getValue()).toEqual(options.granularity); expect(polygon.stRotation.getValue()).toEqual(options.stRotation); expect(polygon.perPositionHeight.getValue()).toEqual( options.perPositionHeight ); expect(polygon.fill.getValue()).toEqual(options.fill); expect(polygon.outline.getValue()).toEqual(options.outline); expect(polygon.outlineColor.getValue()).toEqual(options.outlineColor); expect(polygon.outlineWidth.getValue()).toEqual(options.outlineWidth); expect(polygon.closeTop.getValue()).toEqual(options.closeTop); expect(polygon.closeBottom.getValue()).toEqual(options.closeBottom); expect(polygon.shadows.getValue()).toEqual(options.shadows); expect(polygon.distanceDisplayCondition.getValue()).toEqual( options.distanceDisplayCondition ); expect(polygon.classificationType.getValue()).toEqual( options.classificationType ); expect(polygon.arcType.getValue()).toEqual(options.arcType); expect(polygon.zIndex.getValue()).toEqual(22); expect(polygon.textureCoordinates.getValue()).toEqual( options.textureCoordinates ); }); it("merge assigns unassigned properties", function() { const source = new import__95.PolygonGraphics(); source.material = new import__95.ColorMaterialProperty(); source.hierarchy = new import__95.ConstantProperty(); source.show = new import__95.ConstantProperty(); source.height = new import__95.ConstantProperty(); source.extrudedHeight = new import__95.ConstantProperty(); source.granularity = new import__95.ConstantProperty(); source.stRotation = new import__95.ConstantProperty(); source.fill = new import__95.ConstantProperty(); source.outline = new import__95.ConstantProperty(); source.outlineColor = new import__95.ConstantProperty(); source.outlineWidth = new import__95.ConstantProperty(); source.perPositionHeight = new import__95.ConstantProperty(); source.closeTop = new import__95.ConstantProperty(); source.closeBottom = new import__95.ConstantProperty(); source.shadows = new import__95.ConstantProperty(import__95.ShadowMode.ENABLED); source.distanceDisplayCondition = new import__95.ConstantProperty( new import__95.DistanceDisplayCondition() ); source.classificationType = new import__95.ConstantProperty( import__95.ClassificationType.TERRAIN ); source.arcType = new import__95.ConstantProperty(import__95.ArcType.RHUMB); source.zIndex = new import__95.ConstantProperty(30); source.textureCoordinates = new import__95.ConstantProperty(); const target = new import__95.PolygonGraphics(); target.merge(source); expect(target.material).toBe(source.material); expect(target.hierarchy).toBe(source.hierarchy); expect(target.show).toBe(source.show); expect(target.height).toBe(source.height); expect(target.extrudedHeight).toBe(source.extrudedHeight); expect(target.granularity).toBe(source.granularity); expect(target.stRotation).toBe(source.stRotation); expect(target.fill).toBe(source.fill); expect(target.outline).toBe(source.outline); expect(target.outlineColor).toBe(source.outlineColor); expect(target.outlineWidth).toBe(source.outlineWidth); expect(target.perPositionHeight).toBe(source.perPositionHeight); expect(target.closeTop).toBe(source.closeTop); expect(target.closeBottom).toBe(source.closeBottom); expect(target.shadows).toBe(source.shadows); expect(target.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(target.classificationType).toBe(source.classificationType); expect(target.arcType).toBe(source.arcType); expect(target.zIndex).toBe(source.zIndex); expect(target.textureCoordinates).toBe(source.textureCoordinates); }); it("merge does not assign assigned properties", function() { const source = new import__95.PolygonGraphics(); const material = new import__95.ColorMaterialProperty(); const positions = new import__95.ConstantProperty(); const show = new import__95.ConstantProperty(); const height = new import__95.ConstantProperty(); const extrudedHeight = new import__95.ConstantProperty(); const granularity = new import__95.ConstantProperty(); const stRotation = new import__95.ConstantProperty(); const fill = new import__95.ConstantProperty(); const outline = new import__95.ConstantProperty(); const outlineColor = new import__95.ConstantProperty(); const outlineWidth = new import__95.ConstantProperty(); const perPositionHeight = new import__95.ConstantProperty(); const closeTop = new import__95.ConstantProperty(); const closeBottom = new import__95.ConstantProperty(); const shadows = new import__95.ConstantProperty(); const distanceDisplayCondition = new import__95.ConstantProperty(); const classificationType = new import__95.ConstantProperty(); const arcType = new import__95.ConstantProperty(); const zIndex = new import__95.ConstantProperty(); const textureCoordinates = new import__95.ConstantProperty(); const target = new import__95.PolygonGraphics(); target.material = material; target.hierarchy = positions; target.show = show; target.height = height; target.extrudedHeight = extrudedHeight; target.granularity = granularity; target.stRotation = stRotation; target.fill = fill; target.outline = outline; target.outlineColor = outlineColor; target.outlineWidth = outlineWidth; target.perPositionHeight = perPositionHeight; target.closeTop = closeTop; target.closeBottom = closeBottom; target.shadows = shadows; target.distanceDisplayCondition = distanceDisplayCondition; target.classificationType = classificationType; target.arcType = arcType; target.zIndex = zIndex; target.textureCoordinates = textureCoordinates; target.merge(source); expect(target.material).toBe(material); expect(target.hierarchy).toBe(positions); expect(target.show).toBe(show); expect(target.height).toBe(height); expect(target.extrudedHeight).toBe(extrudedHeight); expect(target.granularity).toBe(granularity); expect(target.stRotation).toBe(stRotation); expect(target.fill).toBe(fill); expect(target.outline).toBe(outline); expect(target.outlineColor).toBe(outlineColor); expect(target.outlineWidth).toBe(outlineWidth); expect(target.perPositionHeight).toBe(perPositionHeight); expect(target.closeTop).toBe(closeTop); expect(target.closeBottom).toBe(closeBottom); expect(target.shadows).toBe(shadows); expect(target.distanceDisplayCondition).toBe(distanceDisplayCondition); expect(target.classificationType).toBe(classificationType); expect(target.arcType).toBe(arcType); expect(target.zIndex).toBe(zIndex); expect(target.textureCoordinates).toBe(textureCoordinates); }); it("clone works", function() { const source = new import__95.PolygonGraphics(); source.material = new import__95.ColorMaterialProperty(); source.hierarchy = new import__95.ConstantProperty(); source.show = new import__95.ConstantProperty(); source.height = new import__95.ConstantProperty(); source.extrudedHeight = new import__95.ConstantProperty(); source.granularity = new import__95.ConstantProperty(); source.stRotation = new import__95.ConstantProperty(); source.fill = new import__95.ConstantProperty(); source.outline = new import__95.ConstantProperty(); source.outlineColor = new import__95.ConstantProperty(); source.outlineWidth = new import__95.ConstantProperty(); source.perPositionHeight = new import__95.ConstantProperty(); source.closeTop = new import__95.ConstantProperty(); source.closeBottom = new import__95.ConstantProperty(); source.shadows = new import__95.ConstantProperty(); source.distanceDisplayCondition = new import__95.ConstantProperty(); source.classificationType = new import__95.ConstantProperty(); source.arcType = new import__95.ConstantProperty(); source.zIndex = new import__95.ConstantProperty(); source.textureCoordinates = new import__95.ConstantProperty(); const result = source.clone(); expect(result.material).toBe(source.material); expect(result.hierarchy).toBe(source.hierarchy); expect(result.show).toBe(source.show); expect(result.height).toBe(source.height); expect(result.extrudedHeight).toBe(source.extrudedHeight); expect(result.granularity).toBe(source.granularity); expect(result.stRotation).toBe(source.stRotation); expect(result.fill).toBe(source.fill); expect(result.outline).toBe(source.outline); expect(result.outlineColor).toBe(source.outlineColor); expect(result.outlineWidth).toBe(source.outlineWidth); expect(result.perPositionHeight).toBe(source.perPositionHeight); expect(result.closeTop).toBe(source.closeTop); expect(result.closeBottom).toBe(source.closeBottom); expect(result.shadows).toBe(source.shadows); expect(result.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(result.classificationType).toBe(source.classificationType); expect(result.arcType).toBe(source.arcType); expect(result.zIndex).toBe(source.zIndex); expect(result.textureCoordinates).toBe(source.textureCoordinates); }); it("merge throws if source undefined", function() { const target = new import__95.PolygonGraphics(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__95.PolygonGraphics(); testMaterialDefinitionChanged_default(property, "material", import__95.Color.RED, import__95.Color.BLUE); testDefinitionChanged_default(property, "hierarchy", [0], [1]); testDefinitionChanged_default(property, "show", true, false); testDefinitionChanged_default(property, "height", 3, 4); testDefinitionChanged_default(property, "extrudedHeight", 4, 3); testDefinitionChanged_default(property, "granularity", 1, 2); testDefinitionChanged_default(property, "stRotation", 5, 6); testDefinitionChanged_default(property, "fill", false, true); testDefinitionChanged_default(property, "outline", true, false); testDefinitionChanged_default(property, "outlineColor", import__95.Color.RED, import__95.Color.BLUE); testDefinitionChanged_default(property, "outlineWidth", 2, 3); testDefinitionChanged_default(property, "perPositionHeight", false, true); testDefinitionChanged_default(property, "closeTop", true, false); testDefinitionChanged_default(property, "closeBottom", true, false); testDefinitionChanged_default( property, "shadows", import__95.ShadowMode.ENABLED, import__95.ShadowMode.DISABLED ); testDefinitionChanged_default( property, "distanceDisplayCondition", new import__95.DistanceDisplayCondition(), new import__95.DistanceDisplayCondition(10, 100) ); testDefinitionChanged_default( property, "classificationType", import__95.ClassificationType.TERRAIN, import__95.ClassificationType.BOTH ); testDefinitionChanged_default(property, "arcType", import__95.ArcType.GEODESIC, import__95.ArcType.RHUMB); testDefinitionChanged_default(property, "zIndex", 54, 3); testDefinitionChanged_default(property, "textureCoordinates", [0], [1]); }); it("converts an array of positions to a PolygonHierarchy", function() { const positions = [ new import__95.Cartesian3(1, 2, 3), new import__95.Cartesian3(4, 5, 6), new import__95.Cartesian3(7, 8, 9) ]; let graphics = new import__95.PolygonGraphics({ hierarchy: positions }); expect(graphics.hierarchy).toBeInstanceOf(import__95.ConstantProperty); let hierarchy = graphics.hierarchy.getValue(); expect(hierarchy).toBeInstanceOf(import__95.PolygonHierarchy); expect(hierarchy.positions).toEqual(positions); graphics = new import__95.PolygonGraphics(); graphics.hierarchy = positions; expect(graphics.hierarchy).toBeInstanceOf(import__95.ConstantProperty); hierarchy = graphics.hierarchy.getValue(); expect(hierarchy).toBeInstanceOf(import__95.PolygonHierarchy); expect(hierarchy.positions).toEqual(positions); }); }); // packages/engine/Specs/DataSources/PolylineArrowMaterialPropertySpec.js var import__96 = __toESM(require_Cesium(), 1); describe("DataSources/PolylineArrowMaterialProperty", function() { it("constructor provides the expected defaults", function() { let property = new import__96.PolylineArrowMaterialProperty(); expect(property.color).toBeUndefined(); expect(property.getType()).toEqual("PolylineArrow"); expect(property.isConstant).toBe(true); const result = property.getValue(); expect(result.color).toEqual(import__96.Color.WHITE); const colorProperty = new import__96.ConstantProperty(import__96.Color.BLUE); property = new import__96.PolylineArrowMaterialProperty(colorProperty); expect(property.color).toBe(colorProperty); property = new import__96.PolylineArrowMaterialProperty(import__96.Color.BLUE); expect(property.color).toBeInstanceOf(import__96.ConstantProperty); expect(property.color.getValue()).toEqual(import__96.Color.BLUE); }); it("works with constant values", function() { const property = new import__96.PolylineArrowMaterialProperty(); property.color = new import__96.ConstantProperty(import__96.Color.RED); const result = property.getValue(import__96.JulianDate.now()); expect(result.color).toEqual(import__96.Color.RED); }); it("works with dynamic values", function() { const property = new import__96.PolylineArrowMaterialProperty(); property.color = new import__96.TimeIntervalCollectionProperty(); const start = new import__96.JulianDate(1, 0); const stop = new import__96.JulianDate(2, 0); property.color.intervals.addInterval( new import__96.TimeInterval({ start, stop, data: import__96.Color.BLUE }) ); expect(property.isConstant).toBe(false); const result = property.getValue(start); expect(result.color).toEqual(import__96.Color.BLUE); }); it("works with a result parameter", function() { const property = new import__96.PolylineArrowMaterialProperty(); property.color = new import__96.ConstantProperty(import__96.Color.RED); const result = { color: import__96.Color.BLUE.clone() }; const returnedResult = property.getValue(import__96.JulianDate.now(), result); expect(returnedResult).toBe(result); expect(result.color).toEqual(import__96.Color.RED); }); it("equals works", function() { const left = new import__96.PolylineArrowMaterialProperty(); left.color = new import__96.ConstantProperty(import__96.Color.WHITE); const right = new import__96.PolylineArrowMaterialProperty(); right.color = new import__96.ConstantProperty(import__96.Color.WHITE); expect(left.equals(right)).toEqual(true); right.color = new import__96.ConstantProperty(import__96.Color.BLACK); expect(left.equals(right)).toEqual(false); }); it("raises definitionChanged when a color property is assigned or modified", function() { const property = new import__96.PolylineArrowMaterialProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); const oldValue = property.color; property.color = new import__96.ConstantProperty(import__96.Color.WHITE); expect(listener).toHaveBeenCalledWith( property, "color", property.color, oldValue ); listener.calls.reset(); property.color.setValue(import__96.Color.BLACK); expect(listener).toHaveBeenCalledWith( property, "color", property.color, property.color ); listener.calls.reset(); property.color = property.color; expect(listener.calls.count()).toEqual(0); }); }); // packages/engine/Specs/DataSources/PolylineDashMaterialPropertySpec.js var import__97 = __toESM(require_Cesium(), 1); describe("DataSources/PolylineDashMaterialProperty", function() { it("constructor provides the expected defaults", function() { const property = new import__97.PolylineDashMaterialProperty(); expect(property.getType()).toEqual("PolylineDash"); const result = property.getValue(); expect(result.color).toEqual(import__97.Color.WHITE); expect(result.gapColor).toEqual(import__97.Color.TRANSPARENT); expect(result.dashLength).toEqual(16); expect(result.dashPattern).toEqual(255); }); it("constructor sets options and allows raw assignment", function() { const options = { color: import__97.Color.RED, gapColor: import__97.Color.YELLOW, dashLength: 10, dashPattern: 7 }; const property = new import__97.PolylineDashMaterialProperty(options); expect(property.color).toBeInstanceOf(import__97.ConstantProperty); expect(property.gapColor).toBeInstanceOf(import__97.ConstantProperty); expect(property.dashLength).toBeInstanceOf(import__97.ConstantProperty); expect(property.dashPattern).toBeInstanceOf(import__97.ConstantProperty); expect(property.color.getValue()).toEqual(options.color); expect(property.gapColor.getValue()).toEqual(options.gapColor); expect(property.dashLength.getValue()).toEqual(options.dashLength); expect(property.dashPattern.getValue()).toEqual(options.dashPattern); }); it("works with constant values", function() { const property = new import__97.PolylineDashMaterialProperty(); property.color = new import__97.ConstantProperty(import__97.Color.RED); property.gapColor = new import__97.ConstantProperty(import__97.Color.YELLOW); property.dashLength = new import__97.ConstantProperty(10); property.dashPattern = new import__97.ConstantProperty(7); const result = property.getValue(import__97.JulianDate.now()); expect(result.color).toEqual(import__97.Color.RED); expect(result.gapColor).toEqual(import__97.Color.YELLOW); expect(result.dashLength).toEqual(10); expect(result.dashPattern).toEqual(7); }); it("works with dynamic values", function() { const property = new import__97.PolylineDashMaterialProperty(); property.color = new import__97.TimeIntervalCollectionProperty(); property.gapColor = new import__97.TimeIntervalCollectionProperty(); property.dashLength = new import__97.TimeIntervalCollectionProperty(); property.dashPattern = new import__97.TimeIntervalCollectionProperty(); const start = new import__97.JulianDate(1, 0); const stop = new import__97.JulianDate(2, 0); property.color.intervals.addInterval( new import__97.TimeInterval({ start, stop, data: import__97.Color.BLUE }) ); property.gapColor.intervals.addInterval( new import__97.TimeInterval({ start, stop, data: import__97.Color.YELLOW }) ); property.dashLength.intervals.addInterval( new import__97.TimeInterval({ start, stop, data: 10 }) ); property.dashPattern.intervals.addInterval( new import__97.TimeInterval({ start, stop, data: 11 }) ); const result = property.getValue(start); expect(result.color).toEqual(import__97.Color.BLUE); expect(result.gapColor).toEqual(import__97.Color.YELLOW); expect(result.dashLength).toEqual(10); expect(result.dashPattern).toEqual(11); }); it("works with a result parameter", function() { const property = new import__97.PolylineDashMaterialProperty(); property.color = new import__97.ConstantProperty(import__97.Color.RED); property.gapColor = new import__97.ConstantProperty(import__97.Color.YELLOW); property.dashLength = new import__97.ConstantProperty(10); property.dashPattern = new import__97.ConstantProperty(11); const result = { color: import__97.Color.YELLOW.clone(), gapColor: import__97.Color.RED.clone(), dashLength: 1, dashPattern: 2 }; const returnedResult = property.getValue(import__97.JulianDate.now(), result); expect(returnedResult).toBe(result); expect(result.color).toEqual(import__97.Color.RED); expect(result.gapColor).toEqual(import__97.Color.YELLOW); expect(result.dashLength).toEqual(10); expect(result.dashPattern).toEqual(11); }); it("equals works", function() { const left = new import__97.PolylineDashMaterialProperty(); left.color = new import__97.ConstantProperty(import__97.Color.WHITE); left.gapColor = new import__97.ConstantProperty(import__97.Color.YELLOW); left.dashLength = new import__97.ConstantProperty(5); left.dashPattern = new import__97.ConstantProperty(7); const right = new import__97.PolylineDashMaterialProperty(); right.color = new import__97.ConstantProperty(import__97.Color.WHITE); right.gapColor = new import__97.ConstantProperty(import__97.Color.YELLOW); right.dashLength = new import__97.ConstantProperty(5); right.dashPattern = new import__97.ConstantProperty(7); expect(left.equals(right)).toEqual(true); right.color = new import__97.ConstantProperty(import__97.Color.RED); expect(left.equals(right)).toEqual(false); right.color = left.color; right.dashLength = new import__97.ConstantProperty(3); expect(left.equals(right)).toEqual(false); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__97.PolylineDashMaterialProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); let oldValue = property.color; property.color = new import__97.ConstantProperty(import__97.Color.RED); expect(listener).toHaveBeenCalledWith( property, "color", property.color, oldValue ); listener.calls.reset(); property.color.setValue(import__97.Color.YELLOW); expect(listener).toHaveBeenCalledWith( property, "color", property.color, property.color ); listener.calls.reset(); property.color = property.color; expect(listener.calls.count()).toEqual(0); listener.calls.reset(); oldValue = property.gapColor; property.gapColor = new import__97.ConstantProperty(import__97.Color.RED); expect(listener).toHaveBeenCalledWith( property, "gapColor", property.gapColor, oldValue ); listener.calls.reset(); property.gapColor.setValue(import__97.Color.YELLOW); expect(listener).toHaveBeenCalledWith( property, "gapColor", property.gapColor, property.gapColor ); listener.calls.reset(); property.gapColor = property.gapColor; expect(listener.calls.count()).toEqual(0); listener.calls.reset(); oldValue = property.dashLength; property.dashLength = new import__97.ConstantProperty(3); expect(listener).toHaveBeenCalledWith( property, "dashLength", property.dashLength, oldValue ); listener.calls.reset(); property.dashLength.setValue(2); expect(listener).toHaveBeenCalledWith( property, "dashLength", property.dashLength, property.dashLength ); listener.calls.reset(); property.dashLength = property.dashLength; expect(listener.calls.count()).toEqual(0); oldValue = property.dashPattern; property.dashPattern = new import__97.ConstantProperty(3); expect(listener).toHaveBeenCalledWith( property, "dashPattern", property.dashPattern, oldValue ); listener.calls.reset(); property.dashPattern.setValue(2); expect(listener).toHaveBeenCalledWith( property, "dashPattern", property.dashPattern, property.dashPattern ); listener.calls.reset(); property.dashPattern = property.dashPattern; expect(listener.calls.count()).toEqual(0); }); it("isConstant is only true when all properties are constant or undefined", function() { const property = new import__97.PolylineDashMaterialProperty(); expect(property.isConstant).toBe(true); property.color = void 0; property.gapColor = void 0; property.dashLength = void 0; property.dashPattern = void 0; expect(property.isConstant).toBe(true); const start = new import__97.JulianDate(1, 0); const stop = new import__97.JulianDate(2, 0); property.color = new import__97.TimeIntervalCollectionProperty(); property.color.intervals.addInterval( new import__97.TimeInterval({ start, stop, data: import__97.Color.RED }) ); expect(property.isConstant).toBe(false); property.color = void 0; expect(property.isConstant).toBe(true); property.gapColor = new import__97.TimeIntervalCollectionProperty(); property.gapColor.intervals.addInterval( new import__97.TimeInterval({ start, stop, data: import__97.Color.RED }) ); expect(property.isConstant).toBe(false); property.gapColor = void 0; expect(property.isConstant).toBe(true); property.dashLength = new import__97.TimeIntervalCollectionProperty(); property.dashLength.intervals.addInterval( new import__97.TimeInterval({ start, stop, data: 3 }) ); expect(property.isConstant).toBe(false); property.dashLength = void 0; expect(property.isConstant).toBe(true); property.dashPattern = new import__97.TimeIntervalCollectionProperty(); property.dashPattern.intervals.addInterval( new import__97.TimeInterval({ start, stop, data: 3 }) ); expect(property.isConstant).toBe(false); }); }); // packages/engine/Specs/DataSources/PolylineGeometryUpdaterSpec.js var import__98 = __toESM(require_Cesium(), 1); describe( "DataSources/PolylineGeometryUpdater", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); scene2.globe = new import__98.Globe(); return import__98.GroundPolylinePrimitive.initializeTerrainHeights(); }); afterAll(function() { scene2.destroyForSpecs(); import__98.GroundPolylinePrimitive._initPromise = void 0; import__98.GroundPolylinePrimitive._initialized = false; import__98.ApproximateTerrainHeights._initPromise = void 0; import__98.ApproximateTerrainHeights._terrainHeights = void 0; }); const time2 = import__98.JulianDate.now(); const basicPositions = import__98.Cartesian3.fromRadiansArray([ 0, 0, 1, 0, 1, 1, 0, 1 ]); function createBasicPolyline() { const polyline = new import__98.PolylineGraphics(); polyline.positions = new import__98.ConstantProperty(basicPositions); const entity = new import__98.Entity(); entity.polyline = polyline; return entity; } it("Constructor sets expected defaults", function() { const entity = new import__98.Entity(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); expect(updater.isDestroyed()).toBe(false); expect(updater.entity).toBe(entity); expect(updater.isClosed).toBe(false); expect(updater.fillEnabled).toBe(false); expect(updater.fillMaterialProperty).toBe(void 0); expect(updater.depthFailMaterialProperty).toBe(void 0); expect(updater.outlineEnabled).toBe(false); expect(updater.hasConstantFill).toBe(true); expect(updater.hasConstantOutline).toBe(true); expect(updater.outlineColorProperty).toBe(void 0); expect(updater.shadowsProperty).toBe(void 0); expect(updater.distanceDisplayConditionProperty).toBe(void 0); expect(updater.isDynamic).toBe(false); expect(updater.clampToGround).toBe(false); expect(updater.arcType).toBe(void 0); expect(updater.zIndex).toBe(0); expect(updater.isOutlineVisible(time2)).toBe(false); expect(updater.isFilled(time2)).toBe(false); updater.destroy(); expect(updater.isDestroyed()).toBe(true); }); it("No geometry available when polyline is undefined ", function() { const entity = createBasicPolyline(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); entity.polyline = void 0; expect(updater.fillEnabled).toBe(false); expect(updater.outlineEnabled).toBe(false); expect(updater.isDynamic).toBe(false); }); it("No geometry available when not shown.", function() { const entity = createBasicPolyline(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); entity.polyline.show = new import__98.ConstantProperty(false); expect(updater.fillEnabled).toBe(false); expect(updater.outlineEnabled).toBe(false); expect(updater.isDynamic).toBe(false); }); it("Values correct when using default graphics", function() { const entity = createBasicPolyline(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); expect(updater.isClosed).toBe(false); expect(updater.fillEnabled).toBe(true); expect(updater.fillMaterialProperty).toEqual( new import__98.ColorMaterialProperty(import__98.Color.WHITE) ); expect(updater.depthFailMaterialProperty).toBe(void 0); expect(updater.outlineEnabled).toBe(false); expect(updater.hasConstantFill).toBe(true); expect(updater.hasConstantOutline).toBe(true); expect(updater.outlineColorProperty).toBe(void 0); expect(updater.shadowsProperty).toEqual( new import__98.ConstantProperty(import__98.ShadowMode.DISABLED) ); expect(updater.distanceDisplayConditionProperty).toEqual( new import__98.ConstantProperty(new import__98.DistanceDisplayCondition()) ); expect(updater.isDynamic).toBe(false); expect(updater.clampToGround).toBe(false); expect(updater.arcType).toBe(void 0); expect(updater.zIndex).toEqual(new import__98.ConstantProperty(0)); }); it("Polyline material is correctly exposed.", function() { const entity = createBasicPolyline(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); entity.polyline.material = new import__98.ColorMaterialProperty(); expect(updater.fillMaterialProperty).toBe(entity.polyline.material); }); it("Polyline depth fail material is correctly exposed.", function() { const entity = createBasicPolyline(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); entity.polyline.depthFailMaterial = new import__98.ColorMaterialProperty(); expect(updater.depthFailMaterialProperty).toBe( entity.polyline.depthFailMaterial ); }); it("A time-varying positions causes geometry to be dynamic", function() { const entity = createBasicPolyline(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); const point1 = new import__98.SampledPositionProperty(); point1.addSample(time2, new import__98.Cartesian3()); const point2 = new import__98.SampledPositionProperty(); point2.addSample(time2, new import__98.Cartesian3()); const point3 = new import__98.SampledPositionProperty(); point3.addSample(time2, new import__98.Cartesian3()); entity.polyline.positions = new import__98.PropertyArray(); entity.polyline.positions.setValue([point1, point2, point3]); expect(updater.isDynamic).toBe(true); }); it("A time-varying width causes geometry to be dynamic", function() { const entity = createBasicPolyline(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); entity.polyline.width = new import__98.SampledProperty(Number); entity.polyline.width.addSample(time2, 1); expect(updater.isDynamic).toBe(true); }); it("A time-varying arcType causes geometry to be dynamic", function() { const arcType = new import__98.TimeIntervalCollectionProperty(); arcType.intervals.addInterval( new import__98.TimeInterval({ start: new import__98.JulianDate(0, 0), stop: new import__98.JulianDate(10, 0), data: import__98.ArcType.NONE }) ); const entity = createBasicPolyline(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); entity.polyline.arcType = arcType; expect(updater.isDynamic).toBe(true); }); it("A time-varying granularity causes geometry to be dynamic", function() { const entity = createBasicPolyline(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); entity.polyline.granularity = new import__98.SampledProperty(Number); entity.polyline.granularity.addSample(time2, 1); expect(updater.isDynamic).toBe(true); }); it("A time-varying clampToGround causes geometry to be dynamic", function() { const entity = createBasicPolyline(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); entity.polyline.clampToGround = new import__98.SampledProperty(Number); entity.polyline.clampToGround.addSample(time2, true); expect(updater.isDynamic).toBe(true); }); it("A time-varying arcType causes geometry to be dynamic", function() { const entity = createBasicPolyline(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); entity.polyline.arcType = new import__98.SampledProperty(Number); entity.polyline.arcType.addSample(time2, 1); expect(updater.isDynamic).toBe(true); }); it("A time-varying zIndex causes geometry to be dynamic", function() { const entity = createBasicPolyline(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); entity.polyline.zIndex = new import__98.SampledProperty(Number); entity.polyline.zIndex.addSample(time2, 1); expect(updater.isDynamic).toBe(true); }); function validateGeometryInstance(options) { const entity = createBasicPolyline(); const clampToGround = options.clampToGround; const polyline = entity.polyline; polyline.show = new import__98.ConstantProperty(options.show); polyline.material = options.material; polyline.depthFailMaterial = options.depthFailMaterial; polyline.width = new import__98.ConstantProperty(options.width); polyline.granularity = new import__98.ConstantProperty(options.granularity); polyline.distanceDisplayCondition = options.distanceDisplayCondition; polyline.clampToGround = new import__98.ConstantProperty(clampToGround); polyline.arcType = new import__98.ConstantProperty(options.arcType); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); const instance = updater.createFillGeometryInstance(time2); const geometry = instance.geometry; const attributes = instance.attributes; if (clampToGround) { expect(geometry.width).toEqual(options.width); } else { expect(geometry._width).toEqual(options.width); if ((0, import__98.defined)(options.arcType)) { expect(geometry._arcType).toEqual(options.arcType); } expect(geometry._granularity).toEqual(options.granularity); if (options.depthFailMaterial && options.depthFailMaterial instanceof import__98.ColorMaterialProperty) { expect(attributes.depthFailColor.value).toEqual( import__98.ColorGeometryInstanceAttribute.toValue( options.depthFailMaterial.color.getValue(time2) ) ); } else { expect(attributes.depthFailColor).toBeUndefined(); } } if (options.material instanceof import__98.ColorMaterialProperty) { expect(attributes.color.value).toEqual( import__98.ColorGeometryInstanceAttribute.toValue( options.material.color.getValue(time2) ) ); } else { expect(attributes.color).toBeUndefined(); } expect(attributes.show.value).toEqual( import__98.ShowGeometryInstanceAttribute.toValue(options.show) ); if (options.distanceDisplayCondition) { expect(attributes.distanceDisplayCondition.value).toEqual( import__98.DistanceDisplayConditionGeometryInstanceAttribute.toValue( options.distanceDisplayCondition ) ); } } it("Creates expected per-color geometry", function() { validateGeometryInstance({ show: true, material: new import__98.ColorMaterialProperty(import__98.Color.RED), width: 3, clampToGround: false, granularity: 1, arcType: import__98.ArcType.NONE }); if (!import__98.Entity.supportsPolylinesOnTerrain(scene2)) { return; } validateGeometryInstance({ show: true, material: new import__98.ColorMaterialProperty(import__98.Color.RED), width: 3, clampToGround: true, granularity: 1, arcType: import__98.ArcType.GEODESIC }); }); it("Creates expected per-color geometry with color depth fail appearance", function() { validateGeometryInstance({ show: true, material: new import__98.ColorMaterialProperty(import__98.Color.RED), depthFailMaterial: new import__98.ColorMaterialProperty(import__98.Color.BLUE), width: 3, clampToGround: false, granularity: 1, arcType: import__98.ArcType.GEODESIC }); }); it("Creates expected per-color geometry with material depth fail appearance", function() { validateGeometryInstance({ show: true, material: new import__98.ColorMaterialProperty(import__98.Color.RED), depthFailMaterial: new import__98.GridMaterialProperty(), width: 3, clampToGround: false, granularity: 1, arcType: import__98.ArcType.RHUMB }); }); it("Creates expected per-material geometry", function() { validateGeometryInstance({ show: true, material: new import__98.GridMaterialProperty(), width: 4, clampToGround: false, granularity: 0.5, arcType: import__98.ArcType.GEODESIC }); if (!import__98.Entity.supportsPolylinesOnTerrain(scene2)) { return; } validateGeometryInstance({ show: true, material: new import__98.GridMaterialProperty(), width: 4, clampToGround: true, granularity: 0.5, arcType: import__98.ArcType.GEODESIC }); }); it("Creates expected per-material geometry with color depth fail appearance", function() { validateGeometryInstance({ show: true, material: new import__98.GridMaterialProperty(), depthFailMaterial: new import__98.ColorMaterialProperty(import__98.Color.BLUE), width: 4, clampToGround: false, granularity: 0.5 }); }); it("Creates expected per-material geometry with color depth fail appearance", function() { validateGeometryInstance({ show: true, material: new import__98.GridMaterialProperty(), depthFailMaterial: new import__98.GridMaterialProperty(), width: 4, clampToGround: false, granularity: 0.5 }); }); it("Creates expected distance display condition geometry", function() { validateGeometryInstance({ show: true, material: new import__98.ColorMaterialProperty(import__98.Color.RED), width: 3, clampToGround: false, granularity: 1, distanceDisplayCondition: new import__98.DistanceDisplayCondition(10, 100) }); if (!import__98.Entity.supportsPolylinesOnTerrain(scene2)) { return; } validateGeometryInstance({ show: true, material: new import__98.ColorMaterialProperty(import__98.Color.RED), width: 3, clampToGround: true, granularity: 1, distanceDisplayCondition: new import__98.DistanceDisplayCondition(10, 100) }); }); it("Attributes have expected values at creation time", function() { const time1 = new import__98.JulianDate(0, 0); const time22 = new import__98.JulianDate(10, 0); const time3 = new import__98.JulianDate(20, 0); const show = new import__98.TimeIntervalCollectionProperty(); show.intervals.addInterval( new import__98.TimeInterval({ start: time1, stop: time22, data: false }) ); show.intervals.addInterval( new import__98.TimeInterval({ start: time22, stop: time3, isStartIncluded: false, data: true }) ); const colorMaterial = new import__98.ColorMaterialProperty(); colorMaterial.color = new import__98.SampledProperty(import__98.Color); colorMaterial.color.addSample(time2, import__98.Color.YELLOW); colorMaterial.color.addSample(time22, import__98.Color.BLUE); colorMaterial.color.addSample(time3, import__98.Color.RED); const entity = createBasicPolyline(); entity.polyline.show = show; entity.polyline.material = colorMaterial; const updater = new import__98.PolylineGeometryUpdater(entity, scene2); const instance = updater.createFillGeometryInstance(time22); const attributes = instance.attributes; expect(attributes.color.value).toEqual( import__98.ColorGeometryInstanceAttribute.toValue( colorMaterial.color.getValue(time22) ) ); expect(attributes.show.value).toEqual( import__98.ShowGeometryInstanceAttribute.toValue(show.getValue(time22)) ); }); it("createFillGeometryInstance obeys Entity.show is false.", function() { const entity = createBasicPolyline(); entity.show = false; entity.polyline.fill = true; const updater = new import__98.PolylineGeometryUpdater(entity, scene2); const instance = updater.createFillGeometryInstance(new import__98.JulianDate()); const attributes = instance.attributes; expect(attributes.show.value).toEqual( import__98.ShowGeometryInstanceAttribute.toValue(false) ); }); it("dynamic updater sets properties", function() { const entity = new import__98.Entity(); const polyline = new import__98.PolylineGraphics(); entity.polyline = polyline; const time3 = new import__98.JulianDate(0, 0); const time22 = new import__98.JulianDate(10, 0); const time32 = new import__98.JulianDate(20, 0); const width = new import__98.SampledProperty(Number); width.addSample(time3, 1); width.addSample(time22, 2); width.addSample(time32, 3); polyline.show = new import__98.ConstantProperty(true); polyline.width = width; polyline.positions = new import__98.ConstantProperty([ import__98.Cartesian3.fromDegrees(0, 0, 0), import__98.Cartesian3.fromDegrees(0, 1, 0) ]); polyline.material = new import__98.ColorMaterialProperty(import__98.Color.RED); polyline.granularity = new import__98.ConstantProperty(1e-3); polyline.arcType = new import__98.ConstantProperty(import__98.ArcType.NONE); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); const primitives = scene2.primitives; expect(primitives.length).toBe(0); const dynamicUpdater = updater.createDynamicUpdater( primitives, scene2.groundPrimitives ); expect(dynamicUpdater.isDestroyed()).toBe(false); dynamicUpdater.update(time22); expect(primitives.length).toBe(1); const polylineCollection = primitives.get(0); const primitive = polylineCollection.get(0); expect(primitive.show).toEqual(true); expect(primitive.width).toEqual(2); expect(primitive.material.type).toEqual("Color"); expect(primitive.material.uniforms.color).toEqual(import__98.Color.RED); expect(primitive.positions.length).toEqual(2); polyline.arcType = new import__98.ConstantProperty(import__98.ArcType.GEODESIC); dynamicUpdater.update(time32); expect(primitive.width).toEqual(3); expect(primitive.positions.length).toBeGreaterThan(2); dynamicUpdater.destroy(); expect(primitives.length).toBe(0); expect(scene2.groundPrimitives.length).toBe(0); updater.destroy(); }); it("clampToGround can be dynamic", function() { if (!import__98.Entity.supportsPolylinesOnTerrain(scene2)) { return; } const entity = new import__98.Entity(); const polyline = new import__98.PolylineGraphics(); entity.polyline = polyline; const time3 = new import__98.JulianDate(0, 0); let isClampedToGround = true; const clampToGround = new import__98.CallbackProperty(function() { return isClampedToGround; }, false); polyline.show = new import__98.ConstantProperty(true); polyline.width = new import__98.ConstantProperty(1); polyline.positions = new import__98.ConstantProperty([ import__98.Cartesian3.fromDegrees(0, 0, 0), import__98.Cartesian3.fromDegrees(0, 1, 0) ]); polyline.material = new import__98.ColorMaterialProperty(import__98.Color.RED); polyline.granularity = new import__98.ConstantProperty(1e-3); polyline.clampToGround = clampToGround; const updater = new import__98.PolylineGeometryUpdater(entity, scene2); const groundPrimitives = scene2.groundPrimitives; expect(groundPrimitives.length).toBe(0); const dynamicUpdater = updater.createDynamicUpdater( scene2.primitives, groundPrimitives ); expect(dynamicUpdater.isDestroyed()).toBe(false); expect(groundPrimitives.length).toBe(0); dynamicUpdater.update(time3); expect(groundPrimitives.length).toBe(1); const primitive = groundPrimitives.get(0); expect(primitive.show).toEqual(true); isClampedToGround = false; dynamicUpdater.update(time3); dynamicUpdater.destroy(); expect(scene2.primitives.length).toBe(0); expect(groundPrimitives.length).toBe(0); updater.destroy(); }); it("arcType can be dynamic", function() { const entity = new import__98.Entity(); const polyline = new import__98.PolylineGraphics(); entity.polyline = polyline; const time3 = new import__98.JulianDate(0, 0); let arcTypeVar = import__98.ArcType.GEODESIC; const arcType = new import__98.CallbackProperty(function() { return arcTypeVar; }, false); polyline.show = new import__98.ConstantProperty(true); polyline.width = new import__98.ConstantProperty(1); polyline.positions = new import__98.ConstantProperty([ import__98.Cartesian3.fromDegrees(0, 0, 0), import__98.Cartesian3.fromDegrees(0, 1, 0) ]); polyline.material = new import__98.ColorMaterialProperty(import__98.Color.RED); polyline.granularity = new import__98.ConstantProperty(1e-3); polyline.clampToGround = new import__98.ConstantProperty(false); polyline.arcType = arcType; const updater = new import__98.PolylineGeometryUpdater(entity, scene2); const primitives = scene2.primitives; expect(primitives.length).toBe(0); const dynamicUpdater = updater.createDynamicUpdater( primitives, scene2.groundPrimitives ); expect(dynamicUpdater.isDestroyed()).toBe(false); expect(primitives.length).toBe(0); dynamicUpdater.update(time3); expect(primitives.length).toBe(1); const polylineCollection = primitives.get(0); const polylineObject = polylineCollection.get(0); expect(polylineObject.show).toEqual(true); const geodesicPolylinePositionsLength = polylineObject.positions.length; arcTypeVar = import__98.ArcType.NONE; dynamicUpdater.update(time3); expect(polylineObject.positions.length).not.toEqual( geodesicPolylinePositionsLength ); dynamicUpdater.destroy(); expect(scene2.primitives.length).toBe(0); expect(primitives.length).toBe(0); updater.destroy(); }); it("geometryChanged event is raised when expected", function() { const entity = createBasicPolyline(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); const listener = jasmine.createSpy("listener"); updater.geometryChanged.addEventListener(listener); entity.polyline.positions = new import__98.ConstantProperty( import__98.Cartesian3.fromRadiansArray([0, 0, 1, 0]) ); expect(listener.calls.count()).toEqual(1); entity.polyline.width = new import__98.ConstantProperty(82); expect(listener.calls.count()).toEqual(2); entity.availability = new import__98.TimeIntervalCollection(); expect(listener.calls.count()).toEqual(3); entity.polyline.positions = void 0; expect(listener.calls.count()).toEqual(4); entity.polyline.width = void 0; entity.viewFrom = new import__98.ConstantProperty(import__98.Cartesian3.UNIT_X); expect(listener.calls.count()).toEqual(4); }); it("createFillGeometryInstance throws if object is not shown", function() { const entity = new import__98.Entity(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); expect(function() { return updater.createFillGeometryInstance(time2); }).toThrowDeveloperError(); }); it("createFillGeometryInstance throws if no time provided", function() { const entity = createBasicPolyline(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); expect(function() { return updater.createFillGeometryInstance(void 0); }).toThrowDeveloperError(); }); it("createOutlineGeometryInstance throws", function() { const entity = new import__98.Entity(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); expect(function() { return updater.createOutlineGeometryInstance(); }).toThrowDeveloperError(); }); it("createDynamicUpdater throws if not dynamic", function() { const entity = createBasicPolyline(); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); expect(function() { return updater.createDynamicUpdater( scene2.primitives, scene2.groundPrimitives ); }).toThrowDeveloperError(); updater.destroy(); }); it("createDynamicUpdater throws if primitives undefined", function() { const entity = createBasicPolyline(); entity.polyline.width = new import__98.SampledProperty(Number); entity.polyline.width.addSample(time2, 4); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); expect(updater.isDynamic).toBe(true); expect(function() { return updater.createDynamicUpdater(void 0, scene2.groundPrimitives); }).toThrowDeveloperError(); updater.destroy(); }); it("createDynamicUpdater throws if groundPrimitives undefined", function() { const entity = createBasicPolyline(); entity.polyline.width = new import__98.SampledProperty(Number); entity.polyline.width.addSample(time2, 4); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); expect(updater.isDynamic).toBe(true); expect(function() { return updater.createDynamicUpdater(scene2.primitives); }).toThrowDeveloperError(); updater.destroy(); }); it("dynamicUpdater.update throws if no time specified", function() { const entity = createBasicPolyline(); entity.polyline.width = new import__98.SampledProperty(Number); entity.polyline.width.addSample(time2, 4); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); const dynamicUpdater = updater.createDynamicUpdater( scene2.primitives, scene2.groundPrimitives ); expect(function() { dynamicUpdater.update(void 0); }).toThrowDeveloperError(); dynamicUpdater.destroy(); updater.destroy(); }); it("Constructor throws if no entity supplied", function() { expect(function() { return new import__98.PolylineGeometryUpdater(void 0, scene2); }).toThrowDeveloperError(); }); it("Constructor throws if no scene supplied", function() { const entity = new import__98.Entity(); expect(function() { return new import__98.PolylineGeometryUpdater(entity, void 0); }).toThrowDeveloperError(); }); it("Computes dynamic geometry bounding sphere for fill.", function() { const entity = createBasicPolyline(); entity.polyline.width = createDynamicProperty_default(1); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); const dynamicUpdater = updater.createDynamicUpdater( scene2.primitives, scene2.groundPrimitives ); dynamicUpdater.update(time2); const result = new import__98.BoundingSphere(0); const state2 = dynamicUpdater.getBoundingSphere(result); expect(state2).toBe(import__98.BoundingSphereState.DONE); const primitive = scene2.primitives.get(0); const line = primitive.get(0); expect(result).toEqual(import__98.BoundingSphere.fromPoints(line.positions)); dynamicUpdater.destroy(); updater.destroy(); expect(scene2.primitives.length).toBe(0); expect(scene2.groundPrimitives.length).toBe(0); }); it("Computes dynamic geometry bounding sphere on terrain.", function() { if (!import__98.Entity.supportsPolylinesOnTerrain(scene2)) { return; } const entity = createBasicPolyline(); entity.polyline.width = createDynamicProperty_default(1); entity.polyline.clampToGround = true; const updater = new import__98.PolylineGeometryUpdater(entity, scene2); const dynamicUpdater = updater.createDynamicUpdater( scene2.primitives, scene2.groundPrimitives ); dynamicUpdater.update(time2); const result = new import__98.BoundingSphere(0); let state2 = dynamicUpdater.getBoundingSphere(result); expect(state2).toBe(import__98.BoundingSphereState.PENDING); return pollToPromise_default(function() { scene2.initializeFrame(); scene2.render(); state2 = dynamicUpdater.getBoundingSphere(result); return state2 !== import__98.BoundingSphereState.PENDING; }).then(function() { const primitive = scene2.groundPrimitives.get(0); expect(state2).toBe(import__98.BoundingSphereState.DONE); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(result).toEqual(attributes.boundingSphere); dynamicUpdater.destroy(); updater.destroy(); expect(scene2.primitives.length).toBe(0); expect(scene2.groundPrimitives.length).toBe(0); }); }); it("Fails dynamic geometry bounding sphere for entity without billboard.", function() { const entity = createBasicPolyline(); entity.polyline.width = createDynamicProperty_default(1); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); const dynamicUpdater = updater.createDynamicUpdater( scene2.primitives, scene2.groundPrimitives ); const result = new import__98.BoundingSphere(); const state2 = dynamicUpdater.getBoundingSphere(result); expect(state2).toBe(import__98.BoundingSphereState.FAILED); dynamicUpdater.destroy(); updater.destroy(); expect(scene2.primitives.length).toBe(0); expect(scene2.groundPrimitives.length).toBe(0); }); it("Compute dynamic geometry bounding sphere throws without result.", function() { const entity = createBasicPolyline(); entity.polyline.width = createDynamicProperty_default(1); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); const dynamicUpdater = updater.createDynamicUpdater( scene2.primitives, scene2.groundPrimitives ); expect(function() { dynamicUpdater.getBoundingSphere(void 0); }).toThrowDeveloperError(); dynamicUpdater.destroy(); updater.destroy(); expect(scene2.primitives.length).toBe(0); expect(scene2.groundPrimitives.length).toBe(0); }); it("calls generateCartesianRhumbArc for RHUMB arcType", function() { const entity = createBasicPolyline(); entity.polyline.width = createDynamicProperty_default(1); entity.polyline.arcType = import__98.ArcType.RHUMB; const updater = new import__98.PolylineGeometryUpdater(entity, scene2); const dynamicUpdater = updater.createDynamicUpdater( scene2.primitives, scene2.groundPrimitives ); spyOn(import__98.PolylinePipeline, "generateCartesianRhumbArc").and.callThrough(); dynamicUpdater.update(time2); expect(import__98.PolylinePipeline.generateCartesianRhumbArc).toHaveBeenCalled(); dynamicUpdater.destroy(); updater.destroy(); expect(scene2.primitives.length).toBe(0); expect(scene2.groundPrimitives.length).toBe(0); }); it("arcType GEODESIC with undefined globe does not call generateCartesianArc", function() { if (!import__98.Entity.supportsPolylinesOnTerrain(scene2)) { return; } const entity = createBasicPolyline(); entity.polyline.width = createDynamicProperty_default(1); scene2.globe = void 0; const updater = new import__98.PolylineGeometryUpdater(entity, scene2); const dynamicUpdater = updater.createDynamicUpdater( scene2.primitives, scene2.groundPrimitives ); spyOn(import__98.PolylinePipeline, "generateCartesianArc").and.callThrough(); dynamicUpdater.update(time2); expect(import__98.PolylinePipeline.generateCartesianArc).not.toHaveBeenCalled(); dynamicUpdater.destroy(); updater.destroy(); expect(scene2.primitives.length).toBe(0); expect(scene2.groundPrimitives.length).toBe(0); scene2.globe = new import__98.Globe(); }); it("clampToGround true without support for polylines on terrain does not generate GroundPolylineGeometry", function() { spyOn(import__98.Entity, "supportsPolylinesOnTerrain").and.callFake(function() { return false; }); const entity = createBasicPolyline(); const polyline = entity.polyline; polyline.show = new import__98.ConstantProperty(true); polyline.clampToGround = new import__98.ConstantProperty(true); const updater = new import__98.PolylineGeometryUpdater(entity, scene2); expect(updater.clampToGround).toBe(false); const instance = updater.createFillGeometryInstance(time2); expect(instance.geometry).not.toBeInstanceOf(import__98.GroundPolylineGeometry); updater.destroy(); }); }, "WebGL" ); // packages/engine/Specs/DataSources/PolylineGlowMaterialPropertySpec.js var import__99 = __toESM(require_Cesium(), 1); describe("DataSources/PolylineGlowMaterialProperty", function() { it("constructor provides the expected defaults", function() { const property = new import__99.PolylineGlowMaterialProperty(); expect(property.getType()).toEqual("PolylineGlow"); expect(property.isConstant).toBe(true); expect(property.color).toBeUndefined(); expect(property.glowPower).toBeUndefined(); expect(property.taperPower).toBeUndefined(); const result = property.getValue(); expect(result.color).toEqual(import__99.Color.WHITE); expect(result.glowPower).toEqual(0.25); expect(result.taperPower).toEqual(1); }); it("constructor sets options and allows raw assignment", function() { const options = { color: import__99.Color.RED, glowPower: 1, taperPower: 0.5 }; const property = new import__99.PolylineGlowMaterialProperty(options); expect(property.color).toBeInstanceOf(import__99.ConstantProperty); expect(property.glowPower).toBeInstanceOf(import__99.ConstantProperty); expect(property.taperPower).toBeInstanceOf(import__99.ConstantProperty); expect(property.color.getValue()).toEqual(options.color); expect(property.glowPower.getValue()).toEqual(options.glowPower); expect(property.taperPower.getValue()).toEqual(options.taperPower); }); it("works with constant values", function() { const property = new import__99.PolylineGlowMaterialProperty(); property.color = new import__99.ConstantProperty(import__99.Color.RED); property.glowPower = new import__99.ConstantProperty(0.75); property.taperPower = new import__99.ConstantProperty(0.85); const result = property.getValue(import__99.JulianDate.now()); expect(result.color).toEqual(import__99.Color.RED); expect(result.glowPower).toEqual(0.75); expect(result.taperPower).toEqual(0.85); }); it("works with dynamic values", function() { const property = new import__99.PolylineGlowMaterialProperty(); property.color = new import__99.TimeIntervalCollectionProperty(); property.glowPower = new import__99.TimeIntervalCollectionProperty(); property.taperPower = new import__99.TimeIntervalCollectionProperty(); const start = new import__99.JulianDate(1, 0); const stop = new import__99.JulianDate(2, 0); property.color.intervals.addInterval( new import__99.TimeInterval({ start, stop, data: import__99.Color.BLUE }) ); property.glowPower.intervals.addInterval( new import__99.TimeInterval({ start, stop, data: 0.65 }) ); property.taperPower.intervals.addInterval( new import__99.TimeInterval({ start, stop, data: 0.55 }) ); expect(property.isConstant).toBe(false); const result = property.getValue(start); expect(result.color).toEqual(import__99.Color.BLUE); expect(result.glowPower).toEqual(0.65); expect(result.taperPower).toEqual(0.55); }); it("works with a result parameter", function() { const property = new import__99.PolylineGlowMaterialProperty(); property.color = new import__99.ConstantProperty(import__99.Color.RED); property.glowPower = new import__99.ConstantProperty(0.43); property.taperPower = new import__99.ConstantProperty(0.33); const result = { color: import__99.Color.BLUE.clone(), glowPower: 0.12, taperPower: 0.13 }; const returnedResult = property.getValue(import__99.JulianDate.now(), result); expect(returnedResult).toBe(result); expect(result.color).toEqual(import__99.Color.RED); expect(result.glowPower).toEqual(0.43); expect(result.taperPower).toEqual(0.33); }); it("equals works", function() { const left = new import__99.PolylineGlowMaterialProperty(); left.color = new import__99.ConstantProperty(import__99.Color.WHITE); left.glowPower = new import__99.ConstantProperty(0.15); left.taperPower = new import__99.ConstantProperty(0.18); const right = new import__99.PolylineGlowMaterialProperty(); right.color = new import__99.ConstantProperty(import__99.Color.WHITE); right.glowPower = new import__99.ConstantProperty(0.15); right.taperPower = new import__99.ConstantProperty(0.18); expect(left.equals(right)).toEqual(true); right.color = new import__99.ConstantProperty(import__99.Color.BLACK); expect(left.equals(right)).toEqual(false); right.color = new import__99.ConstantProperty(import__99.Color.WHITE); right.glowPower = new import__99.ConstantProperty(0.25); expect(left.equals(right)).toEqual(false); right.glowPower = new import__99.ConstantProperty(0.15); right.taperPower = new import__99.ConstantProperty(0.19); expect(left.equals(right)).toEqual(false); }); it("raises definitionChanged when a color property is assigned or modified", function() { const property = new import__99.PolylineGlowMaterialProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); const oldValue = property.color; property.color = new import__99.ConstantProperty(import__99.Color.WHITE); expect(listener).toHaveBeenCalledWith( property, "color", property.color, oldValue ); listener.calls.reset(); property.color.setValue(import__99.Color.BLACK); expect(listener).toHaveBeenCalledWith( property, "color", property.color, property.color ); listener.calls.reset(); property.color = property.color; expect(listener.calls.count()).toEqual(0); }); it("raises definitionChanged when glow property is assigned or modified", function() { const property = new import__99.PolylineGlowMaterialProperty(); testDefinitionChanged_default(property, "color", import__99.Color.RED, import__99.Color.BLUE); testDefinitionChanged_default(property, "glowPower", 0.25, 0.54); testDefinitionChanged_default(property, "taperPower", 1, 0.44); }); }); // packages/engine/Specs/DataSources/PolylineGraphicsSpec.js var import__100 = __toESM(require_Cesium(), 1); describe("DataSources/PolylineGraphics", function() { it("creates expected instance from raw assignment and construction", function() { const options = { material: import__100.Color.BLUE, depthFailMaterial: import__100.Color.RED, positions: [], show: true, width: 1, clampToGround: true, granularity: 2, shadows: import__100.ShadowMode.DISABLED, distanceDisplayCondition: new import__100.DistanceDisplayCondition(), classificationType: import__100.ClassificationType.TERRAIN, arcType: import__100.ArcType.GEODESIC, zIndex: 0 }; const polyline = new import__100.PolylineGraphics(options); expect(polyline.material).toBeInstanceOf(import__100.ColorMaterialProperty); expect(polyline.depthFailMaterial).toBeInstanceOf(import__100.ColorMaterialProperty); expect(polyline.positions).toBeInstanceOf(import__100.ConstantProperty); expect(polyline.show).toBeInstanceOf(import__100.ConstantProperty); expect(polyline.width).toBeInstanceOf(import__100.ConstantProperty); expect(polyline.clampToGround).toBeInstanceOf(import__100.ConstantProperty); expect(polyline.granularity).toBeInstanceOf(import__100.ConstantProperty); expect(polyline.shadows).toBeInstanceOf(import__100.ConstantProperty); expect(polyline.distanceDisplayCondition).toBeInstanceOf(import__100.ConstantProperty); expect(polyline.classificationType).toBeInstanceOf(import__100.ConstantProperty); expect(polyline.arcType).toBeInstanceOf(import__100.ConstantProperty); expect(polyline.zIndex).toBeInstanceOf(import__100.ConstantProperty); expect(polyline.material.color.getValue()).toEqual(options.material); expect(polyline.depthFailMaterial.color.getValue()).toEqual( options.depthFailMaterial ); expect(polyline.positions.getValue()).toEqual(options.positions); expect(polyline.show.getValue()).toEqual(options.show); expect(polyline.width.getValue()).toEqual(options.width); expect(polyline.clampToGround.getValue()).toEqual(options.clampToGround); expect(polyline.granularity.getValue()).toEqual(options.granularity); expect(polyline.shadows.getValue()).toEqual(options.shadows); expect(polyline.distanceDisplayCondition.getValue()).toEqual( options.distanceDisplayCondition ); expect(polyline.classificationType.getValue()).toEqual( options.classificationType ); expect(polyline.arcType.getValue()).toEqual(options.arcType); expect(polyline.zIndex.getValue()).toEqual(options.zIndex); }); it("merge assigns unassigned properties", function() { const source = new import__100.PolylineGraphics(); source.material = new import__100.ColorMaterialProperty(); source.depthFailMaterial = new import__100.ColorMaterialProperty(); source.positions = new import__100.ConstantProperty(); source.width = new import__100.ConstantProperty(); source.show = new import__100.ConstantProperty(); source.clampToGround = new import__100.ConstantProperty(); source.granularity = new import__100.ConstantProperty(); source.shadows = new import__100.ConstantProperty(import__100.ShadowMode.ENABLED); source.distanceDisplayCondition = new import__100.ConstantProperty( new import__100.DistanceDisplayCondition() ); source.classificationType = new import__100.ConstantProperty( import__100.ClassificationType.TERRAIN ); source.arcType = new import__100.ConstantProperty(import__100.ArcType.GEODESIC); source.zIndex = new import__100.ConstantProperty(); const target = new import__100.PolylineGraphics(); target.merge(source); expect(target.material).toBe(source.material); expect(target.depthFailMaterial).toBe(source.depthFailMaterial); expect(target.positions).toBe(source.positions); expect(target.width).toBe(source.width); expect(target.show).toBe(source.show); expect(target.clampToGround).toBe(source.clampToGround); expect(target.granularity).toBe(source.granularity); expect(target.shadows).toBe(source.shadows); expect(target.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(target.classificationType).toBe(source.classificationType); expect(target.arcType).toBe(source.arcType); expect(target.zIndex).toBe(source.zIndex); }); it("merge does not assign assigned properties", function() { const source = new import__100.PolylineGraphics(); source.material = new import__100.ColorMaterialProperty(); source.depthFailMaterial = new import__100.ColorMaterialProperty(); source.positions = new import__100.ConstantProperty(); source.width = new import__100.ConstantProperty(); source.show = new import__100.ConstantProperty(); source.clampToGround = new import__100.ConstantProperty(); source.granularity = new import__100.ConstantProperty(); source.shadows = new import__100.ConstantProperty(); source.distanceDisplayCondition = new import__100.ConstantProperty(); source.classificationType = new import__100.ConstantProperty(); source.arcType = new import__100.ConstantProperty(); source.zIndex = new import__100.ConstantProperty(); const color = new import__100.ColorMaterialProperty(); const depthFailColor = new import__100.ColorMaterialProperty(); const positions = new import__100.ConstantProperty(); const width = new import__100.ConstantProperty(); const show = new import__100.ConstantProperty(); const clampToGround = new import__100.ConstantProperty(); const granularity = new import__100.ConstantProperty(); const shadows = new import__100.ConstantProperty(); const distanceDisplayCondition = new import__100.ConstantProperty(); const classificationType = new import__100.ConstantProperty(); const arcType = new import__100.ConstantProperty(); const zIndex = new import__100.ConstantProperty(); const target = new import__100.PolylineGraphics(); target.material = color; target.depthFailMaterial = depthFailColor; target.positions = positions; target.width = width; target.show = show; target.clampToGround = clampToGround; target.granularity = granularity; target.shadows = shadows; target.distanceDisplayCondition = distanceDisplayCondition; target.classificationType = classificationType; target.arcType = arcType; target.zIndex = zIndex; target.merge(source); expect(target.material).toBe(color); expect(target.depthFailMaterial).toBe(depthFailColor); expect(target.positions).toBe(positions); expect(target.width).toBe(width); expect(target.show).toBe(show); expect(target.clampToGround).toBe(clampToGround); expect(target.granularity).toBe(granularity); expect(target.shadows).toBe(shadows); expect(target.distanceDisplayCondition).toBe(distanceDisplayCondition); expect(target.classificationType).toBe(classificationType); expect(target.arcType).toBe(arcType); expect(target.zIndex).toBe(zIndex); }); it("clone works", function() { const source = new import__100.PolylineGraphics(); source.material = new import__100.ColorMaterialProperty(); source.depthFailMaterial = new import__100.ColorMaterialProperty(); source.width = new import__100.ConstantProperty(); source.positions = new import__100.ConstantProperty(); source.show = new import__100.ConstantProperty(); source.clampToGround = new import__100.ConstantProperty(); source.granularity = new import__100.ConstantProperty(); source.shadows = new import__100.ConstantProperty(); source.distanceDisplayCondition = new import__100.ConstantProperty(); source.classificationType = new import__100.ConstantProperty(); source.arcType = new import__100.ConstantProperty(); source.zIndex = new import__100.ConstantProperty(); const result = source.clone(); expect(result.material).toBe(source.material); expect(result.depthFailMaterial).toBe(source.depthFailMaterial); expect(result.positions).toBe(source.positions); expect(result.width).toBe(source.width); expect(result.show).toBe(source.show); expect(result.clampToGround).toBe(source.clampToGround); expect(result.granularity).toBe(source.granularity); expect(result.shadows).toBe(source.shadows); expect(result.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(result.classificationType).toBe(source.classificationType); expect(result.arcType).toBe(source.arcType); expect(result.zIndex).toBe(source.zIndex); }); it("merge throws if source undefined", function() { const target = new import__100.PolylineGraphics(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__100.PolylineGraphics(); testMaterialDefinitionChanged_default(property, "material", import__100.Color.RED, import__100.Color.BLUE); testMaterialDefinitionChanged_default( property, "depthFailMaterial", import__100.Color.RED, import__100.Color.BLUE ); testDefinitionChanged_default(property, "show", true, false); testDefinitionChanged_default(property, "positions", [], []); testDefinitionChanged_default(property, "width", 3, 4); testDefinitionChanged_default(property, "clampToGround", false, true); testDefinitionChanged_default(property, "granularity", 2, 1); testDefinitionChanged_default( property, "shadows", import__100.ShadowMode.ENABLED, import__100.ShadowMode.DISABLED ); testDefinitionChanged_default( property, "distanceDisplayCondition", new import__100.DistanceDisplayCondition(), new import__100.DistanceDisplayCondition(10, 20) ); testDefinitionChanged_default( property, "classificationType", import__100.ClassificationType.TERRAIN ); testDefinitionChanged_default(property, "arcType", import__100.ArcType.GEODESIC, import__100.ArcType.RHUMB); testDefinitionChanged_default(property, "zIndex", 20, 5); }); }); // packages/engine/Specs/DataSources/PolylineOutlineMaterialPropertySpec.js var import__101 = __toESM(require_Cesium(), 1); describe("DataSources/PolylineOutlineMaterialProperty", function() { it("constructor provides the expected defaults", function() { const property = new import__101.PolylineOutlineMaterialProperty(); expect(property.getType()).toEqual("PolylineOutline"); const result = property.getValue(); expect(result.color).toEqual(import__101.Color.WHITE); expect(result.outlineColor).toEqual(import__101.Color.BLACK); expect(result.outlineWidth).toEqual(1); }); it("constructor sets options and allows raw assignment", function() { const options = { color: import__101.Color.RED, outlineColor: import__101.Color.BLUE, outlineWidth: 5 }; const property = new import__101.PolylineOutlineMaterialProperty(options); expect(property.color).toBeInstanceOf(import__101.ConstantProperty); expect(property.outlineColor).toBeInstanceOf(import__101.ConstantProperty); expect(property.outlineWidth).toBeInstanceOf(import__101.ConstantProperty); expect(property.color.getValue()).toEqual(options.color); expect(property.outlineColor.getValue()).toEqual(options.outlineColor); expect(property.outlineWidth.getValue()).toEqual(options.outlineWidth); }); it("works with constant values", function() { const property = new import__101.PolylineOutlineMaterialProperty(); property.color = new import__101.ConstantProperty(import__101.Color.RED); property.outlineColor = new import__101.ConstantProperty(import__101.Color.BLUE); const result = property.getValue(import__101.JulianDate.now()); expect(result.color).toEqual(import__101.Color.RED); expect(result.outlineColor).toEqual(import__101.Color.BLUE); }); it("works with dynamic values", function() { const property = new import__101.PolylineOutlineMaterialProperty(); property.color = new import__101.TimeIntervalCollectionProperty(); property.outlineColor = new import__101.TimeIntervalCollectionProperty(); const start = new import__101.JulianDate(1, 0); const stop = new import__101.JulianDate(2, 0); property.color.intervals.addInterval( new import__101.TimeInterval({ start, stop, data: import__101.Color.BLUE }) ); property.outlineColor.intervals.addInterval( new import__101.TimeInterval({ start, stop, data: import__101.Color.RED }) ); const result = property.getValue(start); expect(result.color).toEqual(import__101.Color.BLUE); expect(result.outlineColor).toEqual(import__101.Color.RED); }); it("works with a result parameter", function() { const property = new import__101.PolylineOutlineMaterialProperty(); property.color = new import__101.ConstantProperty(import__101.Color.RED); property.outlineColor = new import__101.ConstantProperty(import__101.Color.BLUE); const result = { color: import__101.Color.YELLOW.clone(), outlineColor: import__101.Color.BROWN.clone() }; const returnedResult = property.getValue(import__101.JulianDate.now(), result); expect(returnedResult).toBe(result); expect(result.color).toEqual(import__101.Color.RED); expect(result.outlineColor).toEqual(import__101.Color.BLUE); }); it("equals works", function() { const left = new import__101.PolylineOutlineMaterialProperty(); left.color = new import__101.ConstantProperty(import__101.Color.WHITE); left.outlineColor = new import__101.ConstantProperty(import__101.Color.BLACK); left.outlineWidth = new import__101.ConstantProperty(5); const right = new import__101.PolylineOutlineMaterialProperty(); right.color = new import__101.ConstantProperty(import__101.Color.WHITE); right.outlineColor = new import__101.ConstantProperty(import__101.Color.BLACK); right.outlineWidth = new import__101.ConstantProperty(5); expect(left.equals(right)).toEqual(true); right.color = new import__101.ConstantProperty(import__101.Color.RED); expect(left.equals(right)).toEqual(false); right.color = left.color; right.outlineColor = new import__101.ConstantProperty(import__101.Color.BLUE); expect(left.equals(right)).toEqual(false); right.outlineColor = left.outlineColor; right.outlineWidth = new import__101.ConstantProperty(6); expect(left.equals(right)).toEqual(false); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__101.PolylineOutlineMaterialProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); let oldValue = property.color; property.color = new import__101.ConstantProperty(import__101.Color.RED); expect(listener).toHaveBeenCalledWith( property, "color", property.color, oldValue ); listener.calls.reset(); property.color.setValue(import__101.Color.YELLOW); expect(listener).toHaveBeenCalledWith( property, "color", property.color, property.color ); listener.calls.reset(); property.color = property.color; expect(listener.calls.count()).toEqual(0); listener.calls.reset(); oldValue = property.outlineColor; property.outlineColor = new import__101.ConstantProperty(import__101.Color.BLUE); expect(listener).toHaveBeenCalledWith( property, "outlineColor", property.outlineColor, oldValue ); listener.calls.reset(); property.outlineColor.setValue(import__101.Color.GREEN); expect(listener).toHaveBeenCalledWith( property, "outlineColor", property.outlineColor, property.outlineColor ); listener.calls.reset(); property.outlineColor = property.outlineColor; expect(listener.calls.count()).toEqual(0); oldValue = property.outlineWidth; property.outlineWidth = new import__101.ConstantProperty(2.5); expect(listener).toHaveBeenCalledWith( property, "outlineWidth", property.outlineWidth, oldValue ); listener.calls.reset(); property.outlineWidth.setValue(1.5); expect(listener).toHaveBeenCalledWith( property, "outlineWidth", property.outlineWidth, property.outlineWidth ); listener.calls.reset(); property.outlineWidth = property.outlineWidth; expect(listener.calls.count()).toEqual(0); }); it("isConstant is only true when all properties are constant or undefined", function() { const property = new import__101.PolylineOutlineMaterialProperty(); expect(property.isConstant).toBe(true); property.color = void 0; property.outlineColor = void 0; property.outlineWidth = void 0; expect(property.isConstant).toBe(true); const start = new import__101.JulianDate(1, 0); const stop = new import__101.JulianDate(2, 0); property.color = new import__101.TimeIntervalCollectionProperty(); property.color.intervals.addInterval( new import__101.TimeInterval({ start, stop, data: import__101.Color.RED }) ); expect(property.isConstant).toBe(false); property.color = void 0; expect(property.isConstant).toBe(true); property.outlineColor = new import__101.TimeIntervalCollectionProperty(); property.outlineColor.intervals.addInterval( new import__101.TimeInterval({ start, stop, data: import__101.Color.BLUE }) ); expect(property.isConstant).toBe(false); property.outlineColor = void 0; expect(property.isConstant).toBe(true); property.outlineWidth = new import__101.TimeIntervalCollectionProperty(); property.outlineWidth.intervals.addInterval( new import__101.TimeInterval({ start, stop, data: 2 }) ); expect(property.isConstant).toBe(false); }); }); // packages/engine/Specs/DataSources/PolylineVisualizerSpec.js var import__102 = __toESM(require_Cesium(), 1); describe( "DataSources/PolylineVisualizer", function() { const time2 = import__102.JulianDate.now(); let scene2; beforeAll(function() { scene2 = createScene_default(); return import__102.ApproximateTerrainHeights.initialize(); }); afterAll(function() { scene2.destroyForSpecs(); import__102.ApproximateTerrainHeights._initPromise = void 0; import__102.ApproximateTerrainHeights._terrainHeights = void 0; }); function visualizerUpdated(visualizer) { return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = visualizer.update(time2); scene2.render(time2); return isUpdated; }); } function visualizerEmpty(visualizer) { return pollToPromise_default(function() { scene2.initializeFrame(); expect(visualizer.update(time2)).toBe(true); scene2.render(time2); return scene2.primitives.length === 0 && scene2.groundPrimitives.length === 0; }); } it("Can create and destroy", function() { const objects = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, objects); expect(visualizer.update(time2)).toBe(true); expect(scene2.primitives.length).toBe(0); expect(visualizer.isDestroyed()).toBe(false); visualizer.destroy(); expect(visualizer.isDestroyed()).toBe(true); }); it("Creates and removes static color polyline", function() { const objects = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, objects); const polyline = new import__102.PolylineGraphics(); polyline.positions = new import__102.ConstantProperty([ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ]); polyline.material = new import__102.ColorMaterialProperty(); const entity = new import__102.Entity(); entity.polyline = polyline; objects.add(entity); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__102.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toEqual( import__102.ColorGeometryInstanceAttribute.toValue(import__102.Color.WHITE) ); expect(primitive.appearance).toBeInstanceOf(import__102.PolylineColorAppearance); expect(primitive.appearance.closed).toBe(false); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); }); it("Creates and removes static material polyline", function() { const objects = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, objects); const polyline = new import__102.PolylineGraphics(); polyline.positions = new import__102.ConstantProperty([ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ]); polyline.material = new import__102.PolylineArrowMaterialProperty(); const entity = new import__102.Entity(); entity.polyline = polyline; objects.add(entity); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__102.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toBeUndefined(); expect(primitive.appearance).toBeInstanceOf(import__102.PolylineMaterialAppearance); expect(primitive.appearance.closed).toBe(false); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); }); it("Creates and removes static polylines on terrain", function() { if (!import__102.Entity.supportsPolylinesOnTerrain(scene2)) { return; } const objects = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, objects); const polyline = new import__102.PolylineGraphics(); polyline.positions = new import__102.ConstantProperty([ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ]); polyline.material = new import__102.ColorMaterialProperty(); polyline.clampToGround = new import__102.ConstantProperty(true); const entity = new import__102.Entity(); entity.polyline = polyline; objects.add(entity); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.groundPrimitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__102.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toEqual( import__102.ColorGeometryInstanceAttribute.toValue(import__102.Color.WHITE) ); expect(primitive.appearance).toBeInstanceOf(import__102.PolylineColorAppearance); expect(primitive.appearance.closed).toBe(false); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); }); function createAndRemoveGeometryWithShadows(shadows) { const objects = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, objects); const polyline = new import__102.PolylineGraphics(); polyline.positions = new import__102.ConstantProperty([ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ]); polyline.material = new import__102.ColorMaterialProperty(); polyline.shadows = new import__102.ConstantProperty(shadows); const entity = new import__102.Entity(); entity.polyline = polyline; objects.add(entity); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); expect(primitive.shadows).toBe(shadows); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); } it("Creates and removes geometry with shadows disabled", function() { return createAndRemoveGeometryWithShadows(import__102.ShadowMode.DISABLED); }); it("Creates and removes geometry with shadows enabled", function() { return createAndRemoveGeometryWithShadows(import__102.ShadowMode.ENABLED); }); it("Creates and removes geometry with shadow casting only", function() { return createAndRemoveGeometryWithShadows(import__102.ShadowMode.CAST_ONLY); }); it("Creates and removes geometry with shadow receiving only", function() { return createAndRemoveGeometryWithShadows(import__102.ShadowMode.RECEIVE_ONLY); }); it("Creates and removes static color material and static color depth fail material", function() { const objects = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, objects); const polyline = new import__102.PolylineGraphics(); polyline.positions = new import__102.ConstantProperty([ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ]); polyline.material = new import__102.ColorMaterialProperty(); polyline.depthFailMaterial = new import__102.ColorMaterialProperty(); const entity = new import__102.Entity(); entity.position = new import__102.ConstantPositionProperty( new import__102.Cartesian3(1234, 5678, 9101112) ); entity.polyline = polyline; objects.add(entity); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__102.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toEqual( import__102.ColorGeometryInstanceAttribute.toValue(import__102.Color.WHITE) ); expect(attributes.depthFailColor).toEqual( import__102.ColorGeometryInstanceAttribute.toValue(import__102.Color.WHITE) ); expect(primitive.appearance).toBeInstanceOf(import__102.PolylineColorAppearance); expect(primitive.depthFailAppearance).toBeInstanceOf( import__102.PolylineColorAppearance ); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); }); it("Creates and removes static color material and static depth fail material", function() { const objects = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, objects); const polyline = new import__102.PolylineGraphics(); polyline.positions = new import__102.ConstantProperty([ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ]); polyline.material = new import__102.ColorMaterialProperty(); polyline.depthFailMaterial = new import__102.PolylineArrowMaterialProperty(); const entity = new import__102.Entity(); entity.position = new import__102.ConstantPositionProperty( new import__102.Cartesian3(1234, 5678, 9101112) ); entity.polyline = polyline; objects.add(entity); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__102.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toEqual( import__102.ColorGeometryInstanceAttribute.toValue(import__102.Color.WHITE) ); expect(attributes.depthFailColor).toBeUndefined(); expect(primitive.appearance).toBeInstanceOf(import__102.PolylineColorAppearance); expect(primitive.depthFailAppearance).toBeInstanceOf( import__102.PolylineMaterialAppearance ); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); }); it("Creates and removes static material and static depth fail material", function() { const objects = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, objects); const polyline = new import__102.PolylineGraphics(); polyline.positions = new import__102.ConstantProperty([ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ]); polyline.material = new import__102.PolylineArrowMaterialProperty(); polyline.depthFailMaterial = new import__102.PolylineArrowMaterialProperty(); const entity = new import__102.Entity(); entity.position = new import__102.ConstantPositionProperty( new import__102.Cartesian3(1234, 5678, 9101112) ); entity.polyline = polyline; objects.add(entity); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__102.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toBeUndefined(); expect(attributes.depthFailColor).toBeUndefined(); expect(primitive.appearance).toBeInstanceOf(import__102.PolylineMaterialAppearance); expect(primitive.depthFailAppearance).toBeInstanceOf( import__102.PolylineMaterialAppearance ); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); }); it("Creates and removes static material and static color depth fail material", function() { const objects = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, objects); const polyline = new import__102.PolylineGraphics(); polyline.positions = new import__102.ConstantProperty([ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ]); polyline.material = new import__102.PolylineArrowMaterialProperty(); polyline.depthFailMaterial = new import__102.ColorMaterialProperty(); const entity = new import__102.Entity(); entity.position = new import__102.ConstantPositionProperty( new import__102.Cartesian3(1234, 5678, 9101112) ); entity.polyline = polyline; objects.add(entity); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__102.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toBeUndefined(); expect(attributes.depthFailColor).toEqual( import__102.ColorGeometryInstanceAttribute.toValue(import__102.Color.WHITE) ); expect(primitive.appearance).toBeInstanceOf(import__102.PolylineMaterialAppearance); expect(primitive.depthFailAppearance).toBeInstanceOf( import__102.PolylineColorAppearance ); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); }); function createAndRemoveGeometryWithClassificationType(classificationType) { if (!import__102.Entity.supportsPolylinesOnTerrain(scene2)) { return; } const objects = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, objects); const polyline = new import__102.PolylineGraphics(); polyline.positions = new import__102.ConstantProperty([ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ]); polyline.material = new import__102.ColorMaterialProperty(); polyline.classificationType = new import__102.ConstantProperty(classificationType); polyline.clampToGround = true; const entity = new import__102.Entity(); entity.polyline = polyline; objects.add(entity); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.groundPrimitives.get(0); expect(primitive.classificationType).toBe(classificationType); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); } it("Creates and removes geometry classifying terrain", function() { return createAndRemoveGeometryWithClassificationType( import__102.ClassificationType.TERRAIN ); }); it("Creates and removes geometry classifying 3D Tiles", function() { return createAndRemoveGeometryWithClassificationType( import__102.ClassificationType.CESIUM_3D_TILE ); }); it("Creates and removes geometry classifying both terrain and 3D Tiles", function() { return createAndRemoveGeometryWithClassificationType( import__102.ClassificationType.BOTH ); }); it("Correctly handles geometry changing batches", function() { const objects = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, objects); const polyline = new import__102.PolylineGraphics(); polyline.positions = new import__102.ConstantProperty([ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ]); polyline.material = new import__102.ColorMaterialProperty(); const entity = new import__102.Entity(); entity.polyline = polyline; objects.add(entity); return visualizerUpdated(visualizer).then(function() { let primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__102.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toEqual( import__102.ColorGeometryInstanceAttribute.toValue(import__102.Color.WHITE) ); expect(primitive.appearance).toBeInstanceOf(import__102.PolylineColorAppearance); polyline.material = new import__102.PolylineArrowMaterialProperty(); return visualizerUpdated(visualizer).then(function() { primitive = scene2.primitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__102.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toBeUndefined(); expect(primitive.appearance).toBeInstanceOf( import__102.PolylineMaterialAppearance ); objects.remove(entity); scene2.initializeFrame(); expect(visualizer.update(time2)).toBe(true); scene2.render(time2); expect(scene2.primitives.length).toBe(0); visualizer.destroy(); }); }); }); it("Creates and removes dynamic polyline", function() { const objects = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, objects); const polyline = new import__102.PolylineGraphics(); polyline.positions = new import__102.CallbackProperty(function() { return [ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ]; }, false); polyline.material = new import__102.ColorMaterialProperty(); const entity = new import__102.Entity(); entity.polyline = polyline; objects.add(entity); scene2.initializeFrame(); expect(visualizer.update(time2)).toBe(true); scene2.render(time2); objects.remove(entity); scene2.initializeFrame(); expect(visualizer.update(time2)).toBe(true); scene2.render(time2); expect(scene2.primitives.length).toBe(0); visualizer.destroy(); }); it("Constructor throws without scene", function() { const objects = new import__102.EntityCollection(); expect(function() { return new import__102.PolylineVisualizer(void 0, objects); }).toThrowDeveloperError(); }); it("Update throws without time parameter", function() { const visualizer = new import__102.PolylineVisualizer(scene2, new import__102.EntityCollection()); expect(function() { visualizer.update(void 0); }).toThrowDeveloperError(); }); it("removes the listener from the entity collection when destroyed", function() { const entityCollection = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, entityCollection); expect(entityCollection.collectionChanged.numberOfListeners).toEqual(1); visualizer.destroy(); expect(entityCollection.collectionChanged.numberOfListeners).toEqual(0); }); it("Computes dynamic geometry bounding sphere.", function() { const entityCollection = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, entityCollection); const polyline = new import__102.PolylineGraphics(); polyline.positions = new import__102.ConstantProperty([ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ]); polyline.material = new import__102.PolylineArrowMaterialProperty(); const entity = new import__102.Entity(); entity.polyline = polyline; entityCollection.add(entity); let state2; const result = new import__102.BoundingSphere(); return pollToPromise_default(function() { scene2.initializeFrame(); scene2.render(); visualizer.update(time2); state2 = visualizer.getBoundingSphere(entity, result); return state2 !== import__102.BoundingSphereState.PENDING; }).then(function() { const primitive = scene2.primitives.get(0); expect(state2).toBe(import__102.BoundingSphereState.DONE); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(result).toEqual( import__102.BoundingSphere.transform( attributes.boundingSphere, primitive.modelMatrix, new import__102.BoundingSphere() ) ); visualizer.destroy(); }); }); it("Compute dynamic geometry bounding sphere throws without entity.", function() { const entityCollection = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, entityCollection); const result = new import__102.BoundingSphere(); expect(function() { visualizer.getBoundingSphere(void 0, result); }).toThrowDeveloperError(); visualizer.destroy(); }); it("Compute dynamic geometry bounding sphere throws without result.", function() { const entityCollection = new import__102.EntityCollection(); const entity = new import__102.Entity(); entityCollection.add(entity); const visualizer = new import__102.PolylineVisualizer(scene2, entityCollection); expect(function() { visualizer.getBoundingSphere(entity, void 0); }).toThrowDeveloperError(); visualizer.destroy(); }); it("Can remove an entity and then add a new instance with the same id.", function() { const objects = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, objects); const entity = new import__102.Entity({ id: "test", polyline: { positions: [ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ], material: import__102.Color.ORANGE } }); objects.add(entity); return visualizerUpdated(visualizer).then(function() { objects.remove(entity); const entity2 = new import__102.Entity({ id: "test", position: import__102.Cartesian3.fromDegrees(0, 0, 0), polyline: { positions: [ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ], material: import__102.Color.BLUE } }); objects.add(entity2); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity2); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__102.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toEqual( import__102.ColorGeometryInstanceAttribute.toValue(import__102.Color.BLUE) ); expect(primitive.appearance).toBeInstanceOf(import__102.PolylineColorAppearance); objects.remove(entity); return visualizerEmpty(visualizer).then(function() { visualizer.destroy(); }); }); }); }); it("Sets static geometry primitive show attribute when using dynamic fill color", function() { const entities = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, entities); const entity = entities.add({ polyline: { positions: [ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ], material: new import__102.ColorMaterialProperty( createDynamicProperty_default(import__102.Color.BLUE) ) } }); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__102.ShowGeometryInstanceAttribute.toValue(true) ); entity.show = false; return visualizerUpdated(visualizer); }).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__102.ShowGeometryInstanceAttribute.toValue(false) ); entities.remove(entity); visualizer.destroy(); }); }); it("Sets static geometry primitive show attribute when using dynamic fill material", function() { const entities = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, entities); const entity = entities.add({ position: new import__102.Cartesian3(1234, 5678, 9101112), polyline: { positions: [ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ], material: new import__102.PolylineArrowMaterialProperty( createDynamicProperty_default(import__102.Color.BLUE) ) } }); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__102.ShowGeometryInstanceAttribute.toValue(true) ); entity.show = false; return visualizerUpdated(visualizer); }).then(function() { const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__102.ShowGeometryInstanceAttribute.toValue(false) ); entities.remove(entity); visualizer.destroy(); }); }); it("Sets static geometry primitive show attribute when clamped to ground", function() { if (!import__102.Entity.supportsPolylinesOnTerrain(scene2)) { return; } const objects = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, objects); const polyline = new import__102.PolylineGraphics(); polyline.positions = new import__102.ConstantProperty([ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ]); polyline.material = new import__102.ColorMaterialProperty(); polyline.clampToGround = new import__102.ConstantProperty(true); const entity = new import__102.Entity(); entity.polyline = polyline; objects.add(entity); return visualizerUpdated(visualizer).then(function() { const primitive = scene2.groundPrimitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes).toBeDefined(); expect(attributes.show).toEqual( import__102.ShowGeometryInstanceAttribute.toValue(true) ); expect(attributes.color).toEqual( import__102.ColorGeometryInstanceAttribute.toValue(import__102.Color.WHITE) ); expect(primitive.appearance).toBeInstanceOf(import__102.PolylineColorAppearance); expect(primitive.appearance.closed).toBe(false); entity.polyline.show = false; return visualizerUpdated(visualizer); }).then(function() { expect(scene2.primitives.length).toEqual(0); objects.remove(entity); visualizer.destroy(); }); }); it("batches ground poylines by material if ground polylines are supported", function() { if (!import__102.Entity.supportsPolylinesOnTerrain(scene2)) { return; } const entities = new import__102.EntityCollection(); const visualizer = new import__102.PolylineVisualizer(scene2, entities); const blueColor = import__102.Color.BLUE.withAlpha(0.5); const redColor = import__102.Color.RED.withAlpha(0.5); const positions = [ import__102.Cartesian3.fromDegrees(0, 0), import__102.Cartesian3.fromDegrees(0, 1e-6) ]; entities.add({ polyline: { positions, material: blueColor, classificationType: import__102.ClassificationType.TERRAIN, clampToGround: true } }); return visualizerUpdated(visualizer).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); entities.add({ polyline: { positions, material: blueColor, classificationType: import__102.ClassificationType.TERRAIN, clampToGround: true } }); return visualizerUpdated(visualizer); }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); entities.add({ polyline: { positions, material: redColor, classificationType: import__102.ClassificationType.TERRAIN, clampToGround: true } }); return visualizerUpdated(visualizer); }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); entities.add({ polyline: { positions, material: new import__102.PolylineArrowMaterialProperty(), classificationType: import__102.ClassificationType.TERRAIN, clampToGround: true } }); return visualizerUpdated(visualizer); }).then(function() { expect(scene2.groundPrimitives.length).toEqual(2); entities.add({ polyline: { positions, material: new import__102.PolylineArrowMaterialProperty(), classificationType: import__102.ClassificationType.CESIUM_3D_TILE, clampToGround: true } }); return visualizerUpdated(visualizer); }).then(function() { expect(scene2.groundPrimitives.length).toEqual(3); entities.removeAll(); visualizer.destroy(); }); }); }, "WebGL" ); // packages/engine/Specs/DataSources/PolylineVolumeGeometryUpdaterSpec.js var import__103 = __toESM(require_Cesium(), 1); describe( "DataSources/PolylineVolumeGeometryUpdater", function() { let scene2; let time2; beforeAll(function() { scene2 = createScene_default(); time2 = import__103.JulianDate.now(); }); afterAll(function() { scene2.destroyForSpecs(); }); const shape = [ new import__103.Cartesian2(-1, -1), new import__103.Cartesian2(1, -1), new import__103.Cartesian2(1, 1), new import__103.Cartesian2(1, -1) ]; function createBasicPolylineVolume() { const polylineVolume = new import__103.PolylineVolumeGraphics(); polylineVolume.positions = new import__103.ConstantProperty( import__103.Cartesian3.fromDegreesArray([0, 0, 1, 0, 1, 1, 0, 1]) ); polylineVolume.shape = new import__103.ConstantProperty(shape); const entity = new import__103.Entity(); entity.polylineVolume = polylineVolume; return entity; } function createDynamicPolylineVolume() { const entity = createBasicPolylineVolume(); entity.polylineVolume.shape = createDynamicProperty_default(shape); return entity; } it("A time-varying positions causes geometry to be dynamic", function() { const entity = createBasicPolylineVolume(); const updater = new import__103.PolylineVolumeGeometryUpdater(entity, scene2); entity.polylineVolume.positions = createDynamicProperty_default( import__103.Cartesian3.fromRadiansArray([0, 0, 1, 0, 1, 1, 0, 1]) ); updater._onEntityPropertyChanged(entity, "polylineVolume"); expect(updater.isDynamic).toBe(true); }); it("A time-varying shape causes geometry to be dynamic", function() { const entity = createBasicPolylineVolume(); const updater = new import__103.PolylineVolumeGeometryUpdater(entity, scene2); entity.polylineVolume.shape = createDynamicProperty_default(shape); updater._onEntityPropertyChanged(entity, "polylineVolume"); expect(updater.isDynamic).toBe(true); }); it("A time-varying granularity causes geometry to be dynamic", function() { const entity = createBasicPolylineVolume(); const updater = new import__103.PolylineVolumeGeometryUpdater(entity, scene2); entity.polylineVolume.granularity = createDynamicProperty_default(1); updater._onEntityPropertyChanged(entity, "polylineVolume"); expect(updater.isDynamic).toBe(true); }); it("A time-varying cornerType causes geometry to be dynamic", function() { const entity = createBasicPolylineVolume(); const updater = new import__103.PolylineVolumeGeometryUpdater(entity, scene2); entity.polylineVolume.cornerType = new import__103.TimeIntervalCollectionProperty(); entity.polylineVolume.cornerType.intervals.addInterval( new import__103.TimeInterval({ start: import__103.JulianDate.now(), stop: import__103.JulianDate.now(), data: import__103.CornerType.ROUNDED }) ); updater._onEntityPropertyChanged(entity, "polylineVolume"); expect(updater.isDynamic).toBe(true); }); it("Creates geometry with expected properties", function() { const options = { shape, granularity: 0.97, cornerType: import__103.CornerType.MITERED }; const entity = createBasicPolylineVolume(); const polylineVolume = entity.polylineVolume; polylineVolume.outline = true; polylineVolume.cornerType = new import__103.ConstantProperty(options.cornerType); polylineVolume.shape = new import__103.ConstantProperty(options.shape); polylineVolume.granularity = new import__103.ConstantProperty(options.granularity); const updater = new import__103.PolylineVolumeGeometryUpdater(entity, scene2); let instance; let geometry; instance = updater.createFillGeometryInstance(time2); geometry = instance.geometry; expect(geometry._shape).toEqual(options.shape); expect(geometry._granularity).toEqual(options.granularity); instance = updater.createOutlineGeometryInstance(time2); geometry = instance.geometry; expect(geometry._shape).toEqual(options.shape); expect(geometry._granularity).toEqual(options.granularity); expect(geometry._cornerType).toEqual(options.cornerType); }); it("dynamic updater sets properties", function() { const polylineVolume = new import__103.PolylineVolumeGraphics(); polylineVolume.positions = createDynamicProperty_default( import__103.Cartesian3.fromRadiansArray([0, 0, 1, 0, 1, 1, 0, 1]) ); polylineVolume.show = createDynamicProperty_default(true); polylineVolume.shape = createDynamicProperty_default(shape); polylineVolume.outline = createDynamicProperty_default(true); polylineVolume.fill = createDynamicProperty_default(true); polylineVolume.granularity = createDynamicProperty_default(2); polylineVolume.cornerType = createDynamicProperty_default(import__103.CornerType.MITERED); const entity = new import__103.Entity(); entity.polylineVolume = polylineVolume; const updater = new import__103.PolylineVolumeGeometryUpdater(entity, scene2); const dynamicUpdater = updater.createDynamicUpdater( new import__103.PrimitiveCollection(), new import__103.PrimitiveCollection() ); dynamicUpdater.update(time2); const options = dynamicUpdater._options; expect(options.id).toEqual(entity); expect(options.polylinePositions).toEqual( polylineVolume.positions.getValue() ); expect(options.shapePositions).toEqual(polylineVolume.shape.getValue()); expect(options.granularity).toEqual( polylineVolume.granularity.getValue() ); expect(options.cornerType).toEqual(polylineVolume.cornerType.getValue()); }); it("geometryChanged event is raised when expected", function() { const entity = createBasicPolylineVolume(); const updater = new import__103.PolylineVolumeGeometryUpdater(entity, scene2); const listener = jasmine.createSpy("listener"); updater.geometryChanged.addEventListener(listener); entity.polylineVolume.positions = new import__103.ConstantProperty([]); updater._onEntityPropertyChanged(entity, "polylineVolume"); expect(listener.calls.count()).toEqual(1); entity.polylineVolume.shape = new import__103.ConstantProperty(shape); updater._onEntityPropertyChanged(entity, "polylineVolume"); expect(listener.calls.count()).toEqual(2); entity.availability = new import__103.TimeIntervalCollection(); updater._onEntityPropertyChanged(entity, "availability"); expect(listener.calls.count()).toEqual(3); entity.polylineVolume.positions = void 0; updater._onEntityPropertyChanged(entity, "polylineVolume"); expect(listener.calls.count()).toEqual(4); entity.polylineVolume.shape = void 0; updater._onEntityPropertyChanged(entity, "polylineVolume"); entity.viewFrom = new import__103.ConstantProperty(import__103.Cartesian3.UNIT_X); updater._onEntityPropertyChanged(entity, "viewFrom"); expect(listener.calls.count()).toEqual(4); }); function getScene() { return scene2; } createGeometryUpdaterSpecs_default( import__103.PolylineVolumeGeometryUpdater, "polylineVolume", createBasicPolylineVolume, getScene ); createDynamicGeometryUpdaterSpecs_default( import__103.PolylineVolumeGeometryUpdater, "polylineVolume", createDynamicPolylineVolume, getScene ); }, "WebGL" ); // packages/engine/Specs/DataSources/PolylineVolumeGraphicsSpec.js var import__104 = __toESM(require_Cesium(), 1); describe("DataSources/PolylineVolumeGraphics", function() { it("creates expected instance from raw assignment and construction", function() { const options = { material: import__104.Color.BLUE, positions: [], shape: [], show: true, granularity: 1, fill: false, outline: false, outlineColor: import__104.Color.RED, outlineWidth: 2, cornerType: import__104.CornerType.BEVELED, shadows: import__104.ShadowMode.DISABLED, distanceDisplayCondition: new import__104.DistanceDisplayCondition() }; const polylineVolume = new import__104.PolylineVolumeGraphics(options); expect(polylineVolume.material).toBeInstanceOf(import__104.ColorMaterialProperty); expect(polylineVolume.positions).toBeInstanceOf(import__104.ConstantProperty); expect(polylineVolume.show).toBeInstanceOf(import__104.ConstantProperty); expect(polylineVolume.shape).toBeInstanceOf(import__104.ConstantProperty); expect(polylineVolume.granularity).toBeInstanceOf(import__104.ConstantProperty); expect(polylineVolume.fill).toBeInstanceOf(import__104.ConstantProperty); expect(polylineVolume.outline).toBeInstanceOf(import__104.ConstantProperty); expect(polylineVolume.outlineColor).toBeInstanceOf(import__104.ConstantProperty); expect(polylineVolume.outlineWidth).toBeInstanceOf(import__104.ConstantProperty); expect(polylineVolume.cornerType).toBeInstanceOf(import__104.ConstantProperty); expect(polylineVolume.shadows).toBeInstanceOf(import__104.ConstantProperty); expect(polylineVolume.distanceDisplayCondition).toBeInstanceOf( import__104.ConstantProperty ); expect(polylineVolume.material.color.getValue()).toEqual(options.material); expect(polylineVolume.positions.getValue()).toEqual(options.positions); expect(polylineVolume.show.getValue()).toEqual(options.show); expect(polylineVolume.shape.getValue()).toEqual(options.shape); expect(polylineVolume.granularity.getValue()).toEqual(options.granularity); expect(polylineVolume.fill.getValue()).toEqual(options.fill); expect(polylineVolume.outline.getValue()).toEqual(options.outline); expect(polylineVolume.outlineColor.getValue()).toEqual( options.outlineColor ); expect(polylineVolume.outlineWidth.getValue()).toEqual( options.outlineWidth ); expect(polylineVolume.cornerType.getValue()).toEqual(options.cornerType); expect(polylineVolume.shadows.getValue()).toEqual(options.shadows); expect(polylineVolume.distanceDisplayCondition.getValue()).toEqual( options.distanceDisplayCondition ); }); it("merge assigns unassigned properties", function() { const source = new import__104.PolylineVolumeGraphics(); source.material = new import__104.ColorMaterialProperty(); source.positions = new import__104.ConstantProperty(); source.show = new import__104.ConstantProperty(); source.shape = new import__104.ConstantProperty(); source.granularity = new import__104.ConstantProperty(); source.fill = new import__104.ConstantProperty(); source.outline = new import__104.ConstantProperty(); source.outlineColor = new import__104.ConstantProperty(); source.outlineWidth = new import__104.ConstantProperty(); source.cornerType = new import__104.ConstantProperty(); source.shadows = new import__104.ConstantProperty(import__104.ShadowMode.ENABLED); source.distanceDisplayCondition = new import__104.ConstantProperty( new import__104.DistanceDisplayCondition() ); const target = new import__104.PolylineVolumeGraphics(); target.merge(source); expect(target.material).toBe(source.material); expect(target.positions).toBe(source.positions); expect(target.show).toBe(source.show); expect(target.shape).toBe(source.shape); expect(target.granularity).toBe(source.granularity); expect(target.fill).toBe(source.fill); expect(target.outline).toBe(source.outline); expect(target.outlineColor).toBe(source.outlineColor); expect(target.outlineWidth).toBe(source.outlineWidth); expect(target.cornerType).toBe(source.cornerType); expect(target.shadows).toBe(source.shadows); expect(target.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); }); it("merge does not assign assigned properties", function() { const source = new import__104.PolylineVolumeGraphics(); const material = new import__104.ColorMaterialProperty(); const positions = new import__104.ConstantProperty(); const show = new import__104.ConstantProperty(); const shape = new import__104.ConstantProperty(); const granularity = new import__104.ConstantProperty(); const fill = new import__104.ConstantProperty(); const outline = new import__104.ConstantProperty(); const outlineColor = new import__104.ConstantProperty(); const outlineWidth = new import__104.ConstantProperty(); const cornerType = new import__104.ConstantProperty(); const shadows = new import__104.ConstantProperty(); const distanceDisplayCondition = new import__104.ConstantProperty(); const target = new import__104.PolylineVolumeGraphics(); target.material = material; target.positions = positions; target.show = show; target.shape = shape; target.granularity = granularity; target.fill = fill; target.outline = outline; target.outlineColor = outlineColor; target.outlineWidth = outlineWidth; target.cornerType = cornerType; target.shadows = shadows; target.distanceDisplayCondition = distanceDisplayCondition; target.merge(source); expect(target.material).toBe(material); expect(target.positions).toBe(positions); expect(target.show).toBe(show); expect(target.shape).toBe(shape); expect(target.granularity).toBe(granularity); expect(target.fill).toBe(fill); expect(target.outline).toBe(outline); expect(target.outlineColor).toBe(outlineColor); expect(target.outlineWidth).toBe(outlineWidth); expect(target.cornerType).toBe(cornerType); expect(target.shadows).toBe(shadows); expect(target.distanceDisplayCondition).toBe(distanceDisplayCondition); }); it("clone works", function() { const source = new import__104.PolylineVolumeGraphics(); source.material = new import__104.ColorMaterialProperty(); source.positions = new import__104.ConstantProperty(); source.show = new import__104.ConstantProperty(); source.shape = new import__104.ConstantProperty(); source.granularity = new import__104.ConstantProperty(); source.fill = new import__104.ConstantProperty(); source.outline = new import__104.ConstantProperty(); source.outlineColor = new import__104.ConstantProperty(); source.outlineWidth = new import__104.ConstantProperty(); source.cornerType = new import__104.ConstantProperty(); source.shadows = new import__104.ConstantProperty(); source.distanceDisplayCondition = new import__104.ConstantProperty(); const result = source.clone(); expect(result.material).toBe(source.material); expect(result.positions).toBe(source.positions); expect(result.show).toBe(source.show); expect(result.shape).toBe(source.shape); expect(result.granularity).toBe(source.granularity); expect(result.fill).toBe(source.fill); expect(result.outline).toBe(source.outline); expect(result.outlineColor).toBe(source.outlineColor); expect(result.outlineWidth).toBe(source.outlineWidth); expect(result.cornerType).toBe(source.cornerType); expect(result.shadows).toBe(source.shadows); expect(result.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); }); it("merge throws if source undefined", function() { const target = new import__104.PolylineVolumeGraphics(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__104.PolylineVolumeGraphics(); testMaterialDefinitionChanged_default(property, "material", import__104.Color.RED, import__104.Color.BLUE); testDefinitionChanged_default(property, "positions", [], []); testDefinitionChanged_default(property, "shape", [], []); testDefinitionChanged_default(property, "show", true, false); testDefinitionChanged_default(property, "granularity", 1, 2); testDefinitionChanged_default(property, "fill", false, true); testDefinitionChanged_default(property, "outline", true, false); testDefinitionChanged_default(property, "outlineColor", import__104.Color.RED, import__104.Color.BLUE); testDefinitionChanged_default(property, "outlineWidth", 2, 3); testDefinitionChanged_default( property, "cornerType", import__104.CornerType.BEVELED, import__104.CornerType.MITERED ); testDefinitionChanged_default( property, "shadows", import__104.ShadowMode.ENABLED, import__104.ShadowMode.DISABLED ); testDefinitionChanged_default( property, "distanceDisplayCondition", new import__104.DistanceDisplayCondition(), new import__104.DistanceDisplayCondition(10, 100) ); }); }); // packages/engine/Specs/DataSources/PositionPropertyArraySpec.js var import__105 = __toESM(require_Cesium(), 1); describe("DataSources/PositionPropertyArray", function() { const time2 = import__105.JulianDate.now(); it("default constructor sets expected values", function() { const property = new import__105.PositionPropertyArray(); expect(property.isConstant).toBe(true); expect(property.getValue(time2)).toBeUndefined(); }); it("constructor sets expected values", function() { const expected = [import__105.Cartesian3.UNIT_X, import__105.Cartesian3.UNIT_Z]; const value = [ new import__105.ConstantPositionProperty(import__105.Cartesian3.UNIT_X), new import__105.ConstantPositionProperty(import__105.Cartesian3.UNIT_Z) ]; const property = new import__105.PositionPropertyArray(value); expect(property.getValue(time2)).toEqual(expected); }); it("setValue raises definitionChanged event", function() { const property = new import__105.PositionPropertyArray(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.setValue([]); expect(listener).toHaveBeenCalledWith(property); }); it("changing array member raises definitionChanged event", function() { const property = new import__105.PositionPropertyArray(); const item = new import__105.ConstantPositionProperty(import__105.Cartesian3.UNIT_X); property.setValue([item]); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); item.setValue(import__105.Cartesian3.UNIT_Z); expect(listener).toHaveBeenCalledWith(property); }); it("works with result parameter", function() { const expected = [import__105.Cartesian3.UNIT_X, import__105.Cartesian3.UNIT_Z]; const expectedResult = []; const value = [ new import__105.ConstantPositionProperty(import__105.Cartesian3.UNIT_X), new import__105.ConstantPositionProperty(import__105.Cartesian3.UNIT_Z) ]; const property = new import__105.PositionPropertyArray(value); const result = property.getValue(time2, expectedResult); expect(result).toEqual(expected); expect(result).toBe(expectedResult); }); it("works with reference frame parameter", function() { const value = [ new import__105.ConstantPositionProperty(import__105.Cartesian3.UNIT_X, import__105.ReferenceFrame.INERTIAL), new import__105.ConstantPositionProperty(import__105.Cartesian3.UNIT_Z, import__105.ReferenceFrame.FIXED) ]; const expected = [ value[0].getValueInReferenceFrame(time2, import__105.ReferenceFrame.INERTIAL), value[1].getValueInReferenceFrame(time2, import__105.ReferenceFrame.INERTIAL) ]; const property = new import__105.PositionPropertyArray(value); const result = property.getValueInReferenceFrame( time2, import__105.ReferenceFrame.INERTIAL ); expect(result).toEqual(expected); }); it("works with undefined value", function() { const property = new import__105.PositionPropertyArray(); property.setValue(void 0); expect(property.getValue(time2)).toBeUndefined(); }); it("works with undefined propertyvalue", function() { const property = new import__105.PositionPropertyArray(); property.setValue([new import__105.ConstantPositionProperty()]); expect(property.getValue(time2)).toEqual([]); }); it("works with empty array", function() { const property = new import__105.PositionPropertyArray(); property.setValue([]); expect(property.getValue(time2)).toEqual([]); }); it("equals works", function() { let left = new import__105.PositionPropertyArray([ new import__105.ConstantPositionProperty(import__105.Cartesian3.UNIT_X) ]); let right = new import__105.PositionPropertyArray([ new import__105.ConstantPositionProperty(import__105.Cartesian3.UNIT_X) ]); expect(left.equals(right)).toEqual(true); right = new import__105.PositionPropertyArray([ new import__105.ConstantPositionProperty(import__105.Cartesian3.UNIT_Z) ]); expect(left.equals(right)).toEqual(false); left = new import__105.PositionPropertyArray(); right = new import__105.PositionPropertyArray(); expect(left.equals(right)).toEqual(true); }); it("isConstant is true only if all members are constant", function() { const property = new import__105.PositionPropertyArray(); property.setValue([new import__105.ConstantPositionProperty(import__105.Cartesian3.UNIT_X)]); expect(property.isConstant).toBe(true); const sampledProperty = new import__105.SampledPositionProperty(); sampledProperty.addSample(time2, import__105.Cartesian3.UNIT_X); property.setValue([ new import__105.ConstantPositionProperty(import__105.Cartesian3.UNIT_Z), sampledProperty ]); expect(property.isConstant).toBe(false); }); }); // packages/engine/Specs/DataSources/PropertyArraySpec.js var import__106 = __toESM(require_Cesium(), 1); describe("DataSources/PropertyArray", function() { const time2 = import__106.JulianDate.now(); it("default constructor sets expected values", function() { const property = new import__106.PropertyArray(); expect(property.isConstant).toBe(true); expect(property.getValue(time2)).toBeUndefined(); }); it("constructor sets expected values", function() { const expected = [1, 2]; const value = [new import__106.ConstantProperty(1), new import__106.ConstantProperty(2)]; const property = new import__106.PropertyArray(value); expect(property.getValue(time2)).toEqual(expected); }); it("setValue raises definitionChanged event", function() { const property = new import__106.PropertyArray(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.setValue([]); expect(listener).toHaveBeenCalledWith(property); }); it("changing array member raises definitionChanged event", function() { const property = new import__106.PropertyArray(); const item = new import__106.ConstantProperty(1); property.setValue([item]); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); item.setValue(2); expect(listener).toHaveBeenCalledWith(property); }); it("works with result parameter", function() { const expected = [1, 2]; const expectedResult = []; const value = [new import__106.ConstantProperty(1), new import__106.ConstantProperty(2)]; const property = new import__106.PropertyArray(value); const result = property.getValue(time2, expectedResult); expect(result).toEqual(expected); expect(result).toBe(expectedResult); }); it("works with undefined value", function() { const property = new import__106.PropertyArray(); property.setValue(void 0); expect(property.getValue(time2)).toBeUndefined(); }); it("ignores undefined property values", function() { const property = new import__106.PropertyArray(); property.setValue([new import__106.ConstantProperty()]); expect(property.getValue(time2)).toEqual([]); }); it("works with empty array", function() { const property = new import__106.PropertyArray(); property.setValue([]); expect(property.getValue(time2)).toEqual([]); }); it("equals works", function() { let left = new import__106.PropertyArray([new import__106.ConstantProperty(1)]); let right = new import__106.PropertyArray([new import__106.ConstantProperty(1)]); expect(left.equals(right)).toEqual(true); right = new import__106.PropertyArray([new import__106.ConstantProperty(2)]); expect(left.equals(right)).toEqual(false); left = new import__106.PropertyArray(); right = new import__106.PropertyArray(); expect(left.equals(right)).toEqual(true); }); it("isConstant is true only if all members are constant", function() { const property = new import__106.PropertyArray(); property.setValue([new import__106.ConstantProperty(2)]); expect(property.isConstant).toBe(true); const sampledProperty = new import__106.SampledProperty(Number); sampledProperty.addSample(time2, 1); property.setValue([new import__106.ConstantProperty(2), sampledProperty]); expect(property.isConstant).toBe(false); }); }); // packages/engine/Specs/DataSources/PropertyBagSpec.js var import__107 = __toESM(require_Cesium(), 1); describe("DataSources/PropertyBag", function() { const time2 = import__107.JulianDate.now(); it("sets correct values when constructed with no arguments", function() { const property = new import__107.PropertyBag(); expect(property.isConstant).toBe(true); expect(property.getValue(time2)).toEqual({}); }); it("sets correct values when constructed with arguments", function() { const property = new import__107.PropertyBag({ a: new import__107.ConstantProperty(1), b: new import__107.ConstantProperty(2) }); expect(property.propertyNames).toContain("a"); expect(property.a).toBeDefined(); expect(property.a).toBeInstanceOf(import__107.ConstantProperty); expect(property.hasProperty("a")).toEqual(true); expect(property.propertyNames).toContain("b"); expect(property.b).toBeDefined(); expect(property.b).toBeInstanceOf(import__107.ConstantProperty); expect(property.hasProperty("b")).toEqual(true); expect(property.getValue(time2)).toEqual({ a: 1, b: 2 }); }); it("works with result parameter", function() { const property = new import__107.PropertyBag({ a: new import__107.ConstantProperty(1), b: new import__107.ConstantProperty(2) }); const expectedResult = { a: -1 }; const result = property.getValue(time2, expectedResult); expect(result).toEqual({ a: 1, b: 2 }); expect(result).toBe(expectedResult); }); it("leaves extra properties in result object in place", function() { const property = new import__107.PropertyBag({ a: new import__107.ConstantProperty(1) }); const expectedResult = { q: -1 }; const result = property.getValue(time2, expectedResult); expect(result).toEqual({ a: 1, q: -1 }); expect(result).toBe(expectedResult); }); it("converts raw values to properties when constructed", function() { const property = new import__107.PropertyBag({ a: 1, b: 2 }); expect(property.propertyNames).toContain("a"); expect(property.a).toBeInstanceOf(import__107.ConstantProperty); expect(property.propertyNames).toContain("b"); expect(property.b).toBeInstanceOf(import__107.ConstantProperty); expect(property.getValue(time2)).toEqual({ a: 1, b: 2 }); }); function FakeProperty(v) { this.v = v; } FakeProperty.prototype.getValue = function() { return this.v; }; function createFakeProperty(v) { return new FakeProperty(v); } it("uses the provided function to convert raw values to properties when constructed", function() { const property = new import__107.PropertyBag( { a: 1, b: 2 }, createFakeProperty ); expect(property.propertyNames).toContain("a"); expect(property.a).toBeDefined(); expect(property.a).toBeInstanceOf(FakeProperty); expect(property.propertyNames).toContain("b"); expect(property.b).toBeDefined(); expect(property.b).toBeInstanceOf(FakeProperty); expect(property.getValue(time2)).toEqual({ a: 1, b: 2 }); }); it("returns correct results from hasProperty", function() { const property = new import__107.PropertyBag(); expect(property.hasProperty("a")).toEqual(false); property.addProperty("a"); expect(property.hasProperty("a")).toEqual(true); }); it("allows adding a property without a value", function() { const property = new import__107.PropertyBag(); property.addProperty("a"); expect(property.propertyNames).toEqual(["a"]); expect(property.a).toBeUndefined(); expect(property.hasProperty("a")).toEqual(true); expect(property.getValue(time2)).toEqual({ a: void 0 }); }); it("allows adding a property with a value", function() { const property = new import__107.PropertyBag(); property.addProperty("a", new import__107.ConstantProperty(1)); expect(property.propertyNames).toEqual(["a"]); expect(property.a).toBeInstanceOf(import__107.ConstantProperty); expect(property.getValue(time2)).toEqual({ a: 1 }); }); it("uses the provided function to convert raw values to properties when added with a value", function() { const property = new import__107.PropertyBag(); property.addProperty("a", 1, createFakeProperty); expect(property.propertyNames).toEqual(["a"]); expect(property.a).toBeInstanceOf(FakeProperty); expect(property.getValue(time2)).toEqual({ a: 1 }); }); it("uses the provided function to convert raw values to properties when added without a value", function() { const property = new import__107.PropertyBag(); property.addProperty("a", void 0, createFakeProperty); expect(property.propertyNames).toEqual(["a"]); expect(property.a).toBeUndefined(); property.a = 1; expect(property.a).toBeInstanceOf(FakeProperty); expect(property.getValue(time2)).toEqual({ a: 1 }); }); it("allows removing a property that was previously added", function() { const property = new import__107.PropertyBag(); property.addProperty("a", new import__107.ConstantProperty(1)); expect(property.hasProperty("a")).toEqual(true); property.removeProperty("a"); expect(property.propertyNames).toEqual([]); expect(property.a).toBeUndefined(); expect(property.hasProperty("a")).toEqual(false); expect(property.getValue(time2)).toEqual({}); }); it("throws when removing a property that was not added", function() { const property = new import__107.PropertyBag(); expect(function() { property.removeProperty("a"); }).toThrowDeveloperError(); }); it("raises definitionChanged event when addProperty is called", function() { const property = new import__107.PropertyBag(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.addProperty("a"); expect(listener).toHaveBeenCalledWith(property); }); it("raises definitionChanged event when properties are changed", function() { const property = new import__107.PropertyBag(); property.addProperty("a"); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); const a = new import__107.ConstantProperty(1); property.a = a; expect(listener).toHaveBeenCalledWith(property, "a", a, void 0); }); it("requires propertyName in addProperty", function() { const property = new import__107.PropertyBag(); expect(function() { property.addProperty(); }).toThrowDeveloperError(); }); it("requires propertyName in removeProperty", function() { const property = new import__107.PropertyBag(); expect(function() { property.removeProperty(); }).toThrowDeveloperError(); }); it("has working equals function", function() { let left = new import__107.PropertyBag({ a: new import__107.ConstantProperty(1) }); let right = new import__107.PropertyBag({ a: new import__107.ConstantProperty(1) }); expect(left.equals(right)).toEqual(true); right.addProperty("c"); expect(left.equals(right)).toEqual(false); right = new import__107.PropertyBag({ a: new import__107.ConstantProperty(2) }); expect(left.equals(right)).toEqual(false); right = new import__107.PropertyBag({ b: new import__107.ConstantProperty(1) }); expect(left.equals(right)).toEqual(false); right = new import__107.PropertyBag(); expect(left.equals(right)).toEqual(false); left = new import__107.PropertyBag(); right = new import__107.PropertyBag(); expect(left.equals(right)).toEqual(true); }); it("returns true from isConstant only if all members are constant", function() { const property = new import__107.PropertyBag(); property.addProperty("a", new import__107.ConstantProperty(2)); expect(property.isConstant).toBe(true); const sampledProperty = new import__107.SampledProperty(Number); sampledProperty.addSample(time2, 1); property.addProperty("b", sampledProperty); expect(property.isConstant).toBe(false); }); }); // packages/engine/Specs/DataSources/RectangleGeometryUpdaterSpec.js var import__108 = __toESM(require_Cesium(), 1); var import__109 = __toESM(require_Cesium(), 1); describe( "DataSources/RectangleGeometryUpdater", function() { let time2; let scene2; beforeAll(function() { scene2 = createScene_default(); time2 = new import__108.JulianDate(0, 0); return import__108.ApproximateTerrainHeights.initialize(); }); afterAll(function() { scene2.destroyForSpecs(); import__108.ApproximateTerrainHeights._initPromise = void 0; import__108.ApproximateTerrainHeights._terrainHeights = void 0; }); function createBasicRectangle() { const rectangle = new import__108.RectangleGraphics(); const entity = new import__108.Entity(); entity.rectangle = rectangle; entity.rectangle.coordinates = new import__108.ConstantProperty( new import__108.Rectangle(-1, -1, 1, 1) ); entity.rectangle.height = new import__108.ConstantProperty(0); return entity; } function createDynamicRectangle() { const entity = createBasicRectangle(); entity.rectangle.extrudedHeight = createDynamicProperty_default(2); return entity; } function createBasicRectangleWithoutHeight() { const rectangle = new import__108.RectangleGraphics(); const entity = new import__108.Entity(); entity.rectangle = rectangle; entity.rectangle.coordinates = new import__108.ConstantProperty( new import__108.Rectangle(0, 0, 1, 1) ); return entity; } function createDynamicRectangleWithoutHeight() { const entity = createBasicRectangleWithoutHeight(); entity.rectangle.rotation = createDynamicProperty_default(2); return entity; } it("Properly detects closed geometry.", function() { const entity = createBasicRectangle(); const updater = new import__108.RectangleGeometryUpdater(entity, scene2); entity.rectangle.extrudedHeight = new import__108.ConstantProperty(1e3); updater._onEntityPropertyChanged(entity, "rectangle"); expect(updater.isClosed).toBe(true); }); it("A time-varying coordinates causes geometry to be dynamic", function() { const entity = createBasicRectangle(); const updater = new import__108.RectangleGeometryUpdater(entity, scene2); entity.rectangle.coordinates = new import__108.SampledProperty(import__108.Rectangle); entity.rectangle.coordinates.addSample(import__108.JulianDate.now(), new import__108.Rectangle()); updater._onEntityPropertyChanged(entity, "rectangle"); expect(updater.isDynamic).toBe(true); }); it("A time-varying height causes geometry to be dynamic", function() { const entity = createBasicRectangle(); const updater = new import__108.RectangleGeometryUpdater(entity, scene2); entity.rectangle.height = new import__108.SampledProperty(Number); entity.rectangle.height.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "rectangle"); expect(updater.isDynamic).toBe(true); }); it("A time-varying extrudedHeight causes geometry to be dynamic", function() { const entity = createBasicRectangle(); const updater = new import__108.RectangleGeometryUpdater(entity, scene2); entity.rectangle.extrudedHeight = new import__108.SampledProperty(Number); entity.rectangle.extrudedHeight.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "rectangle"); expect(updater.isDynamic).toBe(true); }); it("A time-varying granularity causes geometry to be dynamic", function() { const entity = createBasicRectangle(); const updater = new import__108.RectangleGeometryUpdater(entity, scene2); entity.rectangle.granularity = new import__108.SampledProperty(Number); entity.rectangle.granularity.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "rectangle"); expect(updater.isDynamic).toBe(true); }); it("A time-varying stRotation causes geometry to be dynamic", function() { const entity = createBasicRectangle(); const updater = new import__108.RectangleGeometryUpdater(entity, scene2); entity.rectangle.stRotation = new import__108.SampledProperty(Number); entity.rectangle.stRotation.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "rectangle"); expect(updater.isDynamic).toBe(true); }); it("Creates geometry with expected properties", function() { const options = { height: 431, extrudedHeight: 123, granularity: 0.97, rotation: 1, stRotation: 12 }; const entity = createBasicRectangle(); const rectangle = entity.rectangle; rectangle.outline = true; rectangle.rotation = new import__108.ConstantProperty(options.rotation); rectangle.stRotation = new import__108.ConstantProperty(options.stRotation); rectangle.height = new import__108.ConstantProperty(options.height); rectangle.extrudedHeight = new import__108.ConstantProperty(options.extrudedHeight); rectangle.granularity = new import__108.ConstantProperty(options.granularity); const updater = new import__108.RectangleGeometryUpdater(entity, scene2); let instance; let geometry; instance = updater.createFillGeometryInstance(time2); geometry = instance.geometry; expect(geometry._rotation).toEqual(options.rotation); expect(geometry._stRotation).toEqual(options.stRotation); expect(geometry._surfaceHeight).toEqual(options.height); expect(geometry._granularity).toEqual(options.granularity); expect(geometry._extrudedHeight).toEqual(options.extrudedHeight); expect(geometry._offsetAttribute).toBeUndefined(); instance = updater.createOutlineGeometryInstance(time2); geometry = instance.geometry; expect(geometry._surfaceHeight).toEqual(options.height); expect(geometry._granularity).toEqual(options.granularity); expect(geometry._extrudedHeight).toEqual(options.extrudedHeight); expect(geometry._offsetAttribute).toBeUndefined(); }); it("dynamic updater sets properties", function() { const rectangle = new import__108.RectangleGraphics(); rectangle.coordinates = createDynamicProperty_default(new import__108.Rectangle(0, 0, 1, 1)); rectangle.show = createDynamicProperty_default(true); rectangle.height = createDynamicProperty_default(3); rectangle.extrudedHeight = createDynamicProperty_default(2); rectangle.outline = createDynamicProperty_default(true); rectangle.fill = createDynamicProperty_default(true); rectangle.granularity = createDynamicProperty_default(2); rectangle.stRotation = createDynamicProperty_default(1); const entity = new import__108.Entity(); entity.rectangle = rectangle; const updater = new import__108.RectangleGeometryUpdater(entity, scene2); const dynamicUpdater = updater.createDynamicUpdater( new import__108.PrimitiveCollection(), new import__108.PrimitiveCollection() ); dynamicUpdater.update(time2); const options = dynamicUpdater._options; expect(options.id).toEqual(entity); expect(options.rectangle).toEqual(rectangle.coordinates.getValue()); expect(options.height).toEqual(rectangle.height.getValue()); expect(options.extrudedHeight).toEqual( rectangle.extrudedHeight.getValue() ); expect(options.granularity).toEqual(rectangle.granularity.getValue()); expect(options.stRotation).toEqual(rectangle.stRotation.getValue()); expect(options.offsetAttribute).toBeUndefined(); }); it("geometryChanged event is raised when expected", function() { const entity = createBasicRectangle(); const updater = new import__108.RectangleGeometryUpdater(entity, scene2); const listener = jasmine.createSpy("listener"); updater.geometryChanged.addEventListener(listener); entity.rectangle.height = new import__108.ConstantProperty(82); updater._onEntityPropertyChanged(entity, "rectangle"); expect(listener.calls.count()).toEqual(1); entity.availability = new import__108.TimeIntervalCollection(); updater._onEntityPropertyChanged(entity, "availability"); expect(listener.calls.count()).toEqual(2); entity.rectangle.coordinates = void 0; updater._onEntityPropertyChanged(entity, "rectangle"); expect(listener.calls.count()).toEqual(3); entity.rectangle.height = void 0; updater._onEntityPropertyChanged(entity, "rectangle"); entity.viewFrom = new import__108.ConstantProperty(import__108.Cartesian3.UNIT_X); updater._onEntityPropertyChanged(entity, "viewFrom"); expect(listener.calls.count()).toEqual(3); }); it("computes center", function() { const entity = createBasicRectangle(); const updater = new import__108.RectangleGeometryUpdater(entity, scene2); expect(updater._computeCenter(time2)).toEqualEpsilon( import__108.Cartesian3.fromDegrees(0, 0), import__109.Math.EPSILON10 ); }); function getScene() { return scene2; } createGeometryUpdaterSpecs_default( import__108.RectangleGeometryUpdater, "rectangle", createBasicRectangle, getScene ); createDynamicGeometryUpdaterSpecs_default( import__108.RectangleGeometryUpdater, "rectangle", createDynamicRectangle, getScene ); createGeometryUpdaterGroundGeometrySpecs_default( import__108.RectangleGeometryUpdater, "rectangle", createBasicRectangleWithoutHeight, createDynamicRectangleWithoutHeight, getScene ); }, "WebGL" ); // packages/engine/Specs/DataSources/RectangleGraphicsSpec.js var import__110 = __toESM(require_Cesium(), 1); describe("DataSources/RectangleGraphics", function() { it("creates expected instance from raw assignment and construction", function() { const options = { material: import__110.Color.BLUE, show: true, coordinates: new import__110.Rectangle(0.1, 0.2, 0.3, 0.4), height: 5, extrudedHeight: 6, granularity: 7, rotation: 8, stRotation: 9, fill: false, outline: false, outlineColor: import__110.Color.RED, outlineWidth: 10, shadows: import__110.ShadowMode.DISABLED, distanceDisplayCondition: new import__110.DistanceDisplayCondition(), classificationType: import__110.ClassificationType.TERRAIN, zIndex: 5 }; const rectangle = new import__110.RectangleGraphics(options); expect(rectangle.material).toBeInstanceOf(import__110.ColorMaterialProperty); expect(rectangle.show).toBeInstanceOf(import__110.ConstantProperty); expect(rectangle.coordinates).toBeInstanceOf(import__110.ConstantProperty); expect(rectangle.height).toBeInstanceOf(import__110.ConstantProperty); expect(rectangle.extrudedHeight).toBeInstanceOf(import__110.ConstantProperty); expect(rectangle.granularity).toBeInstanceOf(import__110.ConstantProperty); expect(rectangle.rotation).toBeInstanceOf(import__110.ConstantProperty); expect(rectangle.stRotation).toBeInstanceOf(import__110.ConstantProperty); expect(rectangle.fill).toBeInstanceOf(import__110.ConstantProperty); expect(rectangle.outline).toBeInstanceOf(import__110.ConstantProperty); expect(rectangle.outlineColor).toBeInstanceOf(import__110.ConstantProperty); expect(rectangle.outlineWidth).toBeInstanceOf(import__110.ConstantProperty); expect(rectangle.shadows).toBeInstanceOf(import__110.ConstantProperty); expect(rectangle.distanceDisplayCondition).toBeInstanceOf(import__110.ConstantProperty); expect(rectangle.classificationType).toBeInstanceOf(import__110.ConstantProperty); expect(rectangle.zIndex).toBeInstanceOf(import__110.ConstantProperty); expect(rectangle.material.color.getValue()).toEqual(options.material); expect(rectangle.show.getValue()).toEqual(options.show); expect(rectangle.coordinates.getValue()).toEqual(options.coordinates); expect(rectangle.height.getValue()).toEqual(options.height); expect(rectangle.extrudedHeight.getValue()).toEqual(options.extrudedHeight); expect(rectangle.granularity.getValue()).toEqual(options.granularity); expect(rectangle.rotation.getValue()).toEqual(options.rotation); expect(rectangle.stRotation.getValue()).toEqual(options.stRotation); expect(rectangle.fill.getValue()).toEqual(options.fill); expect(rectangle.outline.getValue()).toEqual(options.outline); expect(rectangle.outlineColor.getValue()).toEqual(options.outlineColor); expect(rectangle.outlineWidth.getValue()).toEqual(options.outlineWidth); expect(rectangle.shadows.getValue()).toEqual(options.shadows); expect(rectangle.distanceDisplayCondition.getValue()).toEqual( options.distanceDisplayCondition ); expect(rectangle.classificationType.getValue()).toEqual( options.classificationType ); expect(rectangle.zIndex.getValue()).toEqual(options.zIndex); }); it("merge assigns unassigned properties", function() { const source = new import__110.RectangleGraphics(); source.material = new import__110.ColorMaterialProperty(); source.show = new import__110.ConstantProperty(); source.coordinates = new import__110.ConstantProperty(); source.height = new import__110.ConstantProperty(); source.extrudedHeight = new import__110.ConstantProperty(); source.granularity = new import__110.ConstantProperty(); source.stRotation = new import__110.ConstantProperty(); source.rotation = new import__110.ConstantProperty(); source.fill = new import__110.ConstantProperty(); source.outline = new import__110.ConstantProperty(); source.outlineColor = new import__110.ConstantProperty(); source.outlineWidth = new import__110.ConstantProperty(); source.shadows = new import__110.ConstantProperty(import__110.ShadowMode.ENABLED); source.distanceDisplayCondition = new import__110.ConstantProperty(); source.classificationType = new import__110.ConstantProperty(); source.zIndex = new import__110.ConstantProperty(); const target = new import__110.RectangleGraphics(); target.merge(source); expect(target.material).toBe(source.material); expect(target.show).toBe(source.show); expect(target.coordinates).toBe(source.coordinates); expect(target.height).toBe(source.height); expect(target.extrudedHeight).toBe(source.extrudedHeight); expect(target.granularity).toBe(source.granularity); expect(target.stRotation).toBe(source.stRotation); expect(target.rotation).toBe(source.rotation); expect(target.fill).toBe(source.fill); expect(target.outline).toBe(source.outline); expect(target.outlineColor).toBe(source.outlineColor); expect(target.outlineWidth).toBe(source.outlineWidth); expect(target.shadows).toBe(source.shadows); expect(target.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(target.classificationType).toBe(source.classificationType); expect(target.zIndex).toBe(source.zIndex); }); it("merge does not assign assigned properties", function() { const source = new import__110.RectangleGraphics(); const material = new import__110.ColorMaterialProperty(); const show = new import__110.ConstantProperty(); const coordinates = new import__110.ConstantProperty(); const height = new import__110.ConstantProperty(); const extrudedHeight = new import__110.ConstantProperty(); const granularity = new import__110.ConstantProperty(); const stRotation = new import__110.ConstantProperty(); const rotation = new import__110.ConstantProperty(); const fill = new import__110.ConstantProperty(); const outline = new import__110.ConstantProperty(); const outlineColor = new import__110.ConstantProperty(); const outlineWidth = new import__110.ConstantProperty(); const shadows = new import__110.ConstantProperty(); const distanceDisplayCondition = new import__110.ConstantProperty(); const classificationType = new import__110.ConstantProperty(); const zIndex = new import__110.ConstantProperty(); const target = new import__110.RectangleGraphics(); target.material = material; target.show = show; target.coordinates = coordinates; target.height = height; target.extrudedHeight = extrudedHeight; target.granularity = granularity; target.stRotation = stRotation; target.rotation = rotation; target.fill = fill; target.outline = outline; target.outlineColor = outlineColor; target.outlineWidth = outlineWidth; target.shadows = shadows; target.distanceDisplayCondition = distanceDisplayCondition; target.classificationType = classificationType; target.zIndex = zIndex; target.merge(source); expect(target.material).toBe(material); expect(target.show).toBe(show); expect(target.coordinates).toBe(coordinates); expect(target.height).toBe(height); expect(target.extrudedHeight).toBe(extrudedHeight); expect(target.granularity).toBe(granularity); expect(target.stRotation).toBe(stRotation); expect(target.rotation).toBe(rotation); expect(target.fill).toBe(fill); expect(target.outline).toBe(outline); expect(target.outlineColor).toBe(outlineColor); expect(target.outlineWidth).toBe(outlineWidth); expect(target.shadows).toBe(shadows); expect(target.distanceDisplayCondition).toBe(distanceDisplayCondition); expect(target.classificationType).toBe(classificationType); expect(target.zIndex).toBe(zIndex); }); it("clone works", function() { const source = new import__110.RectangleGraphics(); source.material = new import__110.ColorMaterialProperty(); source.show = new import__110.ConstantProperty(); source.coordinates = new import__110.ConstantProperty(); source.height = new import__110.ConstantProperty(); source.extrudedHeight = new import__110.ConstantProperty(); source.granularity = new import__110.ConstantProperty(); source.stRotation = new import__110.ConstantProperty(); source.rotation = new import__110.ConstantProperty(); source.fill = new import__110.ConstantProperty(); source.outline = new import__110.ConstantProperty(); source.outlineColor = new import__110.ConstantProperty(); source.outlineWidth = new import__110.ConstantProperty(); source.shadows = new import__110.ConstantProperty(); source.distanceDisplayCondition = new import__110.ConstantProperty(); source.classificationType = new import__110.ConstantProperty(); source.zIndex = new import__110.ConstantProperty(); const result = source.clone(); expect(result.material).toBe(source.material); expect(result.show).toBe(source.show); expect(result.coordinates).toBe(source.coordinates); expect(result.height).toBe(source.height); expect(result.extrudedHeight).toBe(source.extrudedHeight); expect(result.granularity).toBe(source.granularity); expect(result.stRotation).toBe(source.stRotation); expect(result.rotation).toBe(source.rotation); expect(result.fill).toBe(source.fill); expect(result.outline).toBe(source.outline); expect(result.outlineColor).toBe(source.outlineColor); expect(result.outlineWidth).toBe(source.outlineWidth); expect(result.shadows).toBe(source.shadows); expect(result.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); expect(result.classificationType).toBe(source.classificationType); expect(result.zIndex).toBe(source.zIndex); }); it("merge throws if source undefined", function() { const target = new import__110.RectangleGraphics(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__110.RectangleGraphics(); testMaterialDefinitionChanged_default(property, "material", import__110.Color.RED, import__110.Color.BLUE); testDefinitionChanged_default(property, "show", true, false); testDefinitionChanged_default( property, "coordinates", new import__110.Rectangle(0, 0, 0.1, 0.1), new import__110.Rectangle(0, 0, 1, 1) ); testDefinitionChanged_default(property, "height", 2, 5); testDefinitionChanged_default(property, "extrudedHeight", 3, 4); testDefinitionChanged_default(property, "granularity", 3, 4); testDefinitionChanged_default(property, "stRotation", 3, 4); testDefinitionChanged_default(property, "rotation", 3, 4); testDefinitionChanged_default(property, "fill", false, true); testDefinitionChanged_default(property, "outline", true, false); testDefinitionChanged_default(property, "outlineColor", import__110.Color.RED, import__110.Color.BLUE); testDefinitionChanged_default(property, "outlineWidth", 2, 3); testDefinitionChanged_default( property, "shadows", import__110.ShadowMode.ENABLED, import__110.ShadowMode.DISABLED ); testDefinitionChanged_default( property, "distanceDisplayCondition", new import__110.DistanceDisplayCondition(), new import__110.DistanceDisplayCondition(10, 100) ); testDefinitionChanged_default( property, "classificationType", import__110.ClassificationType.TERRAIN, import__110.ClassificationType.BOTH ); testDefinitionChanged_default(property, "zIndex", 20, 5); }); }); // packages/engine/Specs/DataSources/ReferencePropertySpec.js var import__111 = __toESM(require_Cesium(), 1); describe("DataSources/ReferenceProperty", function() { const time2 = import__111.JulianDate.now(); it("constructor sets expected values", function() { const collection = new import__111.EntityCollection(); const objectId = "testId"; const propertyNames = ["foo", "bar", "baz"]; const property = new import__111.ReferenceProperty(collection, objectId, propertyNames); expect(property.targetCollection).toBe(collection); expect(property.targetId).toEqual(objectId); expect(property.targetPropertyNames).toEqual(propertyNames); }); it("fromString sets expected values", function() { const collection = new import__111.EntityCollection(); const objectId = "testId"; const propertyNames = ["foo", "bar", "baz"]; const property = import__111.ReferenceProperty.fromString( collection, "testId#foo.bar.baz" ); expect(property.targetCollection).toBe(collection); expect(property.targetId).toEqual(objectId); expect(property.targetPropertyNames).toEqual(propertyNames); }); it("fromString works with escaped values", function() { const collection = new import__111.EntityCollection(); const objectId = "#identif\\#ier."; const propertyNames = ["propertyName", ".abc\\", "def"]; const property = import__111.ReferenceProperty.fromString( collection, "\\#identif\\\\\\#ier\\.#propertyName.\\.abc\\\\.def" ); expect(property.targetCollection).toBe(collection); expect(property.targetId).toEqual(objectId); expect(property.targetPropertyNames).toEqual(propertyNames); }); it("properly tracks resolved property", function() { const testObject = new import__111.Entity({ id: "testId" }); testObject.billboard = new import__111.BillboardGraphics(); testObject.billboard.scale = new import__111.ConstantProperty(5); const collection = new import__111.EntityCollection(); collection.add(testObject); const property = import__111.ReferenceProperty.fromString( collection, "testId#billboard.scale" ); expect(property.referenceFrame).toBeUndefined(); expect(property.isConstant).toEqual(true); expect(property.resolvedProperty).toBe(testObject.billboard.scale); expect(property.getValue(time2)).toEqual(5); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); testObject.billboard.scale.setValue(6); expect(listener).toHaveBeenCalledWith(property); expect(property.isConstant).toEqual(true); expect(property.getValue(time2)).toEqual(6); listener.calls.reset(); testObject.billboard.scale = new import__111.ConstantProperty(7); expect(listener).toHaveBeenCalledWith(property); expect(property.isConstant).toEqual(true); expect(property.getValue(time2)).toEqual(7); listener.calls.reset(); testObject.billboard = new import__111.BillboardGraphics(); testObject.billboard.scale = new import__111.ConstantProperty(8); expect(listener).toHaveBeenCalledWith(property); expect(property.isConstant).toEqual(true); expect(property.getValue(time2)).toEqual(8); listener.calls.reset(); collection.remove(testObject); expect(listener).not.toHaveBeenCalled(); expect(property.isConstant).toEqual(true); expect(property.getValue(time2)).toBeUndefined(); listener.calls.reset(); const testObject2 = new import__111.Entity({ id: "testId" }); testObject2.billboard = new import__111.BillboardGraphics(); testObject2.billboard.scale = new import__111.ConstantProperty(9); collection.add(testObject2); expect(listener).toHaveBeenCalledWith(property); expect(property.isConstant).toEqual(true); expect(property.getValue(time2)).toEqual(9); testObject2.billboard.scale = void 0; expect(listener).toHaveBeenCalledWith(property); expect(property.isConstant).toEqual(true); expect(property.getValue(time2)).toBeUndefined(); testObject2.billboard.scale = new import__111.ConstantProperty(10); expect(listener).toHaveBeenCalledWith(property); expect(property.isConstant).toEqual(true); expect(property.getValue(time2)).toEqual(10); }); it("works with position properties", function() { const testObject = new import__111.Entity({ id: "testId" }); testObject.position = new import__111.ConstantPositionProperty( new import__111.Cartesian3(1, 2, 3), import__111.ReferenceFrame.FIXED ); const collection = new import__111.EntityCollection(); collection.add(testObject); let property = import__111.ReferenceProperty.fromString(collection, "testId#position"); expect(property.isConstant).toEqual(true); expect(property.referenceFrame).toEqual(import__111.ReferenceFrame.FIXED); expect(property.getValue(time2)).toEqual(testObject.position.getValue(time2)); expect( property.getValueInReferenceFrame(time2, import__111.ReferenceFrame.INERTIAL) ).toEqual( testObject.position.getValueInReferenceFrame( time2, import__111.ReferenceFrame.INERTIAL ) ); property = import__111.ReferenceProperty.fromString(collection, "nonExistent#position"); expect(property.isConstant).toEqual(true); expect(property.referenceFrame).toBeUndefined(); expect(property.getValue(time2)).toBeUndefined(); expect( property.getValueInReferenceFrame(time2, import__111.ReferenceFrame.INERTIAL) ).toBeUndefined(); }); it("works with material properties", function() { const testObject = new import__111.Entity({ id: "testId" }); testObject.addProperty("testMaterial"); testObject.testMaterial = new import__111.ColorMaterialProperty(import__111.Color.WHITE); const collection = new import__111.EntityCollection(); collection.add(testObject); let property = import__111.ReferenceProperty.fromString( collection, "testId#testMaterial" ); expect(property.isConstant).toEqual(true); expect(property.getType(time2)).toEqual( testObject.testMaterial.getType(time2) ); expect(property.getValue(time2)).toEqual( testObject.testMaterial.getValue(time2) ); property = import__111.ReferenceProperty.fromString( collection, "nonExistent#testMaterial" ); expect(property.isConstant).toEqual(true); expect(property.referenceFrame).toBeUndefined(); expect(property.getType(time2)).toBeUndefined(); expect(property.getValue(time2)).toBeUndefined(); }); it("equals works", function() { const entityCollection = new import__111.EntityCollection(); const left = import__111.ReferenceProperty.fromString( entityCollection, "objectId#foo.bar" ); let right = import__111.ReferenceProperty.fromString( entityCollection, "objectId#foo.bar" ); expect(left.equals(right)).toEqual(true); right = import__111.ReferenceProperty.fromString( new import__111.EntityCollection(), "objectId#foo.bar" ); expect(left.equals(right)).toEqual(false); right = import__111.ReferenceProperty.fromString( entityCollection, "otherObjectId#foo.bar" ); expect(left.equals(right)).toEqual(false); right = import__111.ReferenceProperty.fromString(entityCollection, "objectId#foo"); expect(left.equals(right)).toEqual(false); right = import__111.ReferenceProperty.fromString(entityCollection, "objectId#foo.baz"); expect(left.equals(right)).toEqual(false); }); it("does not raise definition changed when target entity has not changed.", function() { const testObject = new import__111.Entity({ id: "testId" }); testObject.billboard = new import__111.BillboardGraphics(); testObject.billboard.scale = new import__111.ConstantProperty(5); const otherObject = new import__111.Entity({ id: "other" }); const collection = new import__111.EntityCollection(); collection.add(testObject); collection.add(otherObject); const property = import__111.ReferenceProperty.fromString( collection, "testId#billboard.scale" ); expect(property.resolvedProperty).toBe(testObject.billboard.scale); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); collection.remove(otherObject); expect(listener).not.toHaveBeenCalled(); collection.remove(testObject); expect(listener).not.toHaveBeenCalled(); }); it("attaches to a target entity created later", function() { const collection = new import__111.EntityCollection(); const property = import__111.ReferenceProperty.fromString( collection, "testId#billboard.scale" ); expect(property.resolvedProperty).toBeUndefined(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); const otherObject = new import__111.Entity({ id: "other" }); collection.add(otherObject); expect(listener).not.toHaveBeenCalled(); expect(property.resolvedProperty).toBeUndefined(); const testObject = new import__111.Entity({ id: "testId" }); testObject.billboard = new import__111.BillboardGraphics(); testObject.billboard.scale = new import__111.ConstantProperty(5); collection.add(testObject); expect(listener).toHaveBeenCalledWith(property); expect(property.resolvedProperty).toBe(testObject.billboard.scale); }); it("constructor throws with undefined targetCollection", function() { expect(function() { return new import__111.ReferenceProperty(void 0, "objectid", ["property"]); }).toThrowDeveloperError(); }); it("constructor throws with undefined targetId", function() { expect(function() { return new import__111.ReferenceProperty(new import__111.EntityCollection(), void 0, [ "property" ]); }).toThrowDeveloperError(); }); it("constructor throws with undefined targetPropertyNames", function() { expect(function() { return new import__111.ReferenceProperty( new import__111.EntityCollection(), "objectId", void 0 ); }).toThrowDeveloperError(); }); it("constructor throws with empty targetPropertyNames", function() { expect(function() { return new import__111.ReferenceProperty(new import__111.EntityCollection(), "objectId", []); }).toThrowDeveloperError(); }); it("constructor throws with empty targetId", function() { expect(function() { return new import__111.ReferenceProperty(new import__111.EntityCollection(), "", ["property"]); }).toThrowDeveloperError(); }); it("fromString throws with undefined targetCollection", function() { expect(function() { return import__111.ReferenceProperty.fromString(void 0, "objectid#property"); }).toThrowDeveloperError(); }); it("fromString throws with undefined referenceString", function() { expect(function() { return import__111.ReferenceProperty.fromString(new import__111.EntityCollection(), void 0); }).toThrowDeveloperError(); }); it("fromString throws with invalid referenceString", function() { expect(function() { return import__111.ReferenceProperty.fromString(new import__111.EntityCollection(), "foo"); }).toThrowDeveloperError(); expect(function() { return import__111.ReferenceProperty.fromString(new import__111.EntityCollection(), "foo#"); }).toThrowDeveloperError(); expect(function() { return import__111.ReferenceProperty.fromString(new import__111.EntityCollection(), "#bar"); }).toThrowDeveloperError(); }); it("getValue returns undefined if target entity can not be resolved", function() { const collection = new import__111.EntityCollection(); const property = import__111.ReferenceProperty.fromString(collection, "testId#foo.bar"); expect(property.getValue(time2)).toBeUndefined(); }); it("getValue returns undefined if target property can not be resolved", function() { const collection = new import__111.EntityCollection(); const testObject = new import__111.Entity({ id: "testId" }); collection.add(testObject); const property = import__111.ReferenceProperty.fromString( collection, "testId#billboard" ); expect(property.getValue(time2)).toBeUndefined(); }); it("getValue returns undefined if sub-property of target property can not be resolved", function() { const collection = new import__111.EntityCollection(); const testObject = new import__111.Entity({ id: "testId" }); testObject.billboard = new import__111.BillboardGraphics(); collection.add(testObject); const property = import__111.ReferenceProperty.fromString( collection, "testId#billboard.foo" ); expect(property.getValue(time2)).toBeUndefined(); }); }); // packages/engine/Specs/DataSources/RotationSpec.js var import__112 = __toESM(require_Cesium(), 1); var import__113 = __toESM(require_Cesium(), 1); // Specs/createPackableSpecs.js var import_engine16 = __toESM(require_Cesium(), 1); function createPackableSpecs(packable, instance, packedInstance, namePrefix) { namePrefix = (0, import_engine16.defaultValue)(namePrefix, ""); it(`${namePrefix} can pack`, function() { const packedArray = []; const returnArray = packable.pack(instance, packedArray); expect(returnArray).toBe(packedArray); const packedLength = (0, import_engine16.defined)(packable.packedLength) ? packable.packedLength : instance.packedLength; expect(packedArray.length).toEqual(packedLength); expect(packedArray).toEqualEpsilon(packedInstance, import_engine16.Math.EPSILON15); }); it(`${namePrefix} can roundtrip`, function() { const packedArray = []; packable.pack(instance, packedArray); const result = packable.unpack(packedArray); expect(instance).toEqual(result); }); it(`${namePrefix} can unpack`, function() { const result = packable.unpack(packedInstance); expect(result).toEqual(instance); }); it(`${namePrefix} can pack with startingIndex`, function() { const packedArray = [0]; const expected = packedArray.concat(packedInstance); packable.pack(instance, packedArray, 1); expect(packedArray).toEqualEpsilon(expected, import_engine16.Math.EPSILON15); }); it(`${namePrefix} can unpack with startingIndex`, function() { const packedArray = [0].concat(packedInstance); const result = packable.unpack(packedArray, 1); expect(instance).toEqual(result); }); it(`${namePrefix} pack throws with undefined value`, function() { const array = []; expect(function() { packable.pack(void 0, array); }).toThrowDeveloperError(); }); it(`${namePrefix} pack throws with undefined array`, function() { expect(function() { packable.pack(instance, void 0); }).toThrowDeveloperError(); }); it(`${namePrefix} unpack throws with undefined array`, function() { expect(function() { packable.unpack(void 0); }).toThrowDeveloperError(); }); if (typeof packable.convertPackedArrayForInterpolation === "function") { it(`${namePrefix} packs and unpacks for interpolation.`, function() { const packedForInterpolation = []; packable.convertPackedArrayForInterpolation( packedInstance, 0, 0, packedForInterpolation ); const value = packable.unpackInterpolationResult( packedForInterpolation, packedInstance, 0, 0 ); const result = packable.unpack(packedInstance); expect(value).toEqual(result); }); it(`${namePrefix} convertPackedArrayForInterpolation throws without array.`, function() { expect(function() { packable.convertPackedArrayForInterpolation(void 0); }).toThrowDeveloperError(); }); it(`${namePrefix} unpackInterpolationResult throws without packed array.`, function() { expect(function() { packable.unpackInterpolationResult(void 0, []); }).toThrowDeveloperError(); }); it(`${namePrefix} unpackInterpolationResult throws without source array.`, function() { expect(function() { packable.unpackInterpolationResult([], void 0); }).toThrowDeveloperError(); }); } } var createPackableSpecs_default = createPackableSpecs; // packages/engine/Specs/DataSources/RotationSpec.js describe("DataSources/Rotation", function() { it("Interpolates towards the closest angle.", function() { const time1 = import__112.JulianDate.fromIso8601("2010-05-07T00:00:00"); const time2 = import__112.JulianDate.fromIso8601("2010-05-07T00:01:00"); const time3 = import__112.JulianDate.fromIso8601("2010-05-07T00:02:00"); const time4 = import__112.JulianDate.fromIso8601("2010-05-07T00:03:00"); const time5 = import__112.JulianDate.fromIso8601("2010-05-07T00:04:00"); const property = new import__112.SampledProperty(import__112.Rotation); property.addSample(time1, 0); property.addSample(time3, import__113.Math.toRadians(350)); property.addSample(time5, import__113.Math.toRadians(10)); expect(property.getValue(time2)).toEqual(import__113.Math.toRadians(355)); expect(property.getValue(time4)).toEqual(0); }); createPackableSpecs_default(import__112.Rotation, 1, [1]); }); // packages/engine/Specs/DataSources/SampledPositionPropertySpec.js var import__114 = __toESM(require_Cesium(), 1); describe("DataSources/SampledPositionProperty", function() { it("constructor sets expected defaults", function() { const property = new import__114.SampledPositionProperty(); expect(property.referenceFrame).toEqual(import__114.ReferenceFrame.FIXED); expect(property.interpolationDegree).toEqual(1); expect(property.interpolationAlgorithm).toEqual(import__114.LinearApproximation); expect(property.numberOfDerivatives).toEqual(0); expect(property.forwardExtrapolationType).toEqual(import__114.ExtrapolationType.NONE); expect(property.forwardExtrapolationDuration).toEqual(0); expect(property.backwardExtrapolationType).toEqual(import__114.ExtrapolationType.NONE); expect(property.backwardExtrapolationDuration).toEqual(0); }); it("constructor sets expected values", function() { const property = new import__114.SampledPositionProperty(import__114.ReferenceFrame.INERTIAL, 1); expect(property.referenceFrame).toEqual(import__114.ReferenceFrame.INERTIAL); expect(property.interpolationDegree).toEqual(1); expect(property.interpolationAlgorithm).toEqual(import__114.LinearApproximation); expect(property.numberOfDerivatives).toEqual(1); expect(property.forwardExtrapolationType).toEqual(import__114.ExtrapolationType.NONE); expect(property.forwardExtrapolationDuration).toEqual(0); expect(property.backwardExtrapolationType).toEqual(import__114.ExtrapolationType.NONE); expect(property.backwardExtrapolationDuration).toEqual(0); }); it("getValue works without a result parameter", function() { const time2 = import__114.JulianDate.now(); const value = new import__114.Cartesian3(1, 2, 3); const property = new import__114.SampledPositionProperty(); property.addSample(time2, value); const result = property.getValue(time2); expect(result).not.toBe(value); expect(result).toEqual(value); }); it("getValue works with a result parameter", function() { const time2 = import__114.JulianDate.now(); const value = new import__114.Cartesian3(1, 2, 3); const property = new import__114.SampledPositionProperty(); property.addSample(time2, value); const expected = new import__114.Cartesian3(); const result = property.getValue(time2, expected); expect(result).toBe(expected); expect(expected).toEqual(value); }); it("getValue returns in fixed frame", function() { const time2 = import__114.JulianDate.now(); const valueInertial = new import__114.Cartesian3(1, 2, 3); const valueFixed = import__114.PositionProperty.convertToReferenceFrame( time2, valueInertial, import__114.ReferenceFrame.INERTIAL, import__114.ReferenceFrame.FIXED ); const property = new import__114.SampledPositionProperty(import__114.ReferenceFrame.INERTIAL); property.addSample(time2, valueInertial); const result = property.getValue(time2); expect(result).toEqual(valueFixed); }); it("getValueInReferenceFrame works without a result parameter", function() { const time2 = import__114.JulianDate.now(); const value = new import__114.Cartesian3(1, 2, 3); const property = new import__114.SampledPositionProperty(); property.addSample(time2, value); const result = property.getValueInReferenceFrame( time2, import__114.ReferenceFrame.INERTIAL ); expect(result).not.toBe(value); expect(result).toEqual( import__114.PositionProperty.convertToReferenceFrame( time2, value, import__114.ReferenceFrame.FIXED, import__114.ReferenceFrame.INERTIAL ) ); }); it("getValueInReferenceFrame works with a result parameter", function() { const time2 = import__114.JulianDate.now(); const value = new import__114.Cartesian3(1, 2, 3); const property = new import__114.SampledPositionProperty(import__114.ReferenceFrame.INERTIAL); property.addSample(time2, value); const expected = new import__114.Cartesian3(); const result = property.getValueInReferenceFrame( time2, import__114.ReferenceFrame.FIXED, expected ); expect(result).toBe(expected); expect(expected).toEqual( import__114.PositionProperty.convertToReferenceFrame( time2, value, import__114.ReferenceFrame.INERTIAL, import__114.ReferenceFrame.FIXED ) ); }); it("addSamplesPackedArray works", function() { const data = [0, 7, 8, 9, 1, 8, 9, 10, 2, 9, 10, 11]; const epoch = new import__114.JulianDate(0, 0); const property = new import__114.SampledPositionProperty(); property.addSamplesPackedArray(data, epoch); expect(property.getValue(epoch)).toEqual(new import__114.Cartesian3(7, 8, 9)); expect(property.getValue(new import__114.JulianDate(0, 0.5))).toEqual( new import__114.Cartesian3(7.5, 8.5, 9.5) ); }); it("addSample works", function() { const times = [ new import__114.JulianDate(0, 0), new import__114.JulianDate(1, 0), new import__114.JulianDate(2, 0) ]; const values = [ new import__114.Cartesian3(7, 8, 9), new import__114.Cartesian3(8, 9, 10), new import__114.Cartesian3(9, 10, 11) ]; const property = new import__114.SampledPositionProperty(); property.addSample(times[0], values[0]); property.addSample(times[1], values[1]); property.addSample(times[2], values[2]); expect(property.getValue(times[0])).toEqual(values[0]); expect(property.getValue(times[1])).toEqual(values[1]); expect(property.getValue(times[2])).toEqual(values[2]); expect(property.getValue(new import__114.JulianDate(0.5, 0))).toEqual( new import__114.Cartesian3(7.5, 8.5, 9.5) ); }); it("addSamples works", function() { const times = [ new import__114.JulianDate(0, 0), new import__114.JulianDate(1, 0), new import__114.JulianDate(2, 0) ]; const values = [ new import__114.Cartesian3(7, 8, 9), new import__114.Cartesian3(8, 9, 10), new import__114.Cartesian3(9, 10, 11) ]; const property = new import__114.SampledPositionProperty(); property.addSamples(times, values); expect(property.getValue(times[0])).toEqual(values[0]); expect(property.getValue(times[1])).toEqual(values[1]); expect(property.getValue(times[2])).toEqual(values[2]); expect(property.getValue(new import__114.JulianDate(0.5, 0))).toEqual( new import__114.Cartesian3(7.5, 8.5, 9.5) ); }); it("can remove a sample at a date", function() { const times = [ new import__114.JulianDate(0, 0), new import__114.JulianDate(1, 0), new import__114.JulianDate(2, 0) ]; const values = [ new import__114.Cartesian3(7, 8, 9), new import__114.Cartesian3(18, 19, 110), new import__114.Cartesian3(9, 10, 11) ]; const property = new import__114.SampledPositionProperty(); property.addSamples(times, values); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); let result = property.removeSample(new import__114.JulianDate(4, 0)); expect(result).toEqual(false); result = property.removeSample(times[1]); expect(listener).toHaveBeenCalledWith(property); expect(property.getValue(times[0])).toEqual(values[0]); expect(result).toEqual(true); expect(property.getValue(times[1])).toEqual(new import__114.Cartesian3(8, 9, 10)); expect(property.getValue(times[2])).toEqual(values[2]); }); it("can remove samples for a time interval", function() { const times = [ new import__114.JulianDate(0, 0), new import__114.JulianDate(1, 0), new import__114.JulianDate(2, 0), new import__114.JulianDate(3, 0) ]; const values = [ new import__114.Cartesian3(7, 8, 9), new import__114.Cartesian3(18, 19, 110), new import__114.Cartesian3(19, 20, 110), new import__114.Cartesian3(10, 11, 12) ]; const property = new import__114.SampledPositionProperty(); property.addSamples(times, values); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.removeSamples( new import__114.TimeInterval({ start: times[1], stop: times[2] }) ); expect(listener).toHaveBeenCalledWith(property); expect(property.getValue(times[0])).toEqual(values[0]); expect(property.getValue(times[1])).toEqual(new import__114.Cartesian3(8, 9, 10)); expect(property.getValue(times[2])).toEqual(new import__114.Cartesian3(9, 10, 11)); expect(property.getValue(times[3])).toEqual(values[3]); }); it("addSamplesPackedArray works with derivatives", function() { const data = [ 0, 7, 8, 9, 1, 0, 0, 1, 8, 9, 10, 0, 1, 0, 2, 9, 10, 11, 0, 0, 1 ]; const epoch = new import__114.JulianDate(0, 0); const property = new import__114.SampledPositionProperty(import__114.ReferenceFrame.FIXED, 1); property.addSamplesPackedArray(data, epoch); expect(property.getValue(epoch)).toEqual(new import__114.Cartesian3(7, 8, 9)); expect(property.getValue(new import__114.JulianDate(0, 0.5))).toEqual( new import__114.Cartesian3(7.5, 8.5, 9.5) ); }); it("addSample works with derivatives", function() { const times = [ new import__114.JulianDate(0, 0), new import__114.JulianDate(1, 0), new import__114.JulianDate(2, 0) ]; const positions = [ new import__114.Cartesian3(7, 8, 9), new import__114.Cartesian3(8, 9, 10), new import__114.Cartesian3(9, 10, 11) ]; const velocities = [ [new import__114.Cartesian3(0, 0, 1)], [new import__114.Cartesian3(0, 1, 0)], [new import__114.Cartesian3(1, 0, 0)] ]; const property = new import__114.SampledPositionProperty(import__114.ReferenceFrame.FIXED, 1); property.addSample(times[0], positions[0], velocities[0]); property.addSample(times[1], positions[1], velocities[1]); property.addSample(times[2], positions[2], velocities[2]); expect(property.getValue(times[0])).toEqual(positions[0]); expect(property.getValue(times[1])).toEqual(positions[1]); expect(property.getValue(times[2])).toEqual(positions[2]); expect(property.getValue(new import__114.JulianDate(0.5, 0))).toEqual( new import__114.Cartesian3(7.5, 8.5, 9.5) ); }); it("addSamples works with derivatives", function() { const times = [ new import__114.JulianDate(0, 0), new import__114.JulianDate(1, 0), new import__114.JulianDate(2, 0) ]; const positions = [ new import__114.Cartesian3(7, 8, 9), new import__114.Cartesian3(8, 9, 10), new import__114.Cartesian3(9, 10, 11) ]; const velocities = [ [new import__114.Cartesian3(0, 0, 1)], [new import__114.Cartesian3(0, 1, 0)], [new import__114.Cartesian3(1, 0, 0)] ]; const property = new import__114.SampledPositionProperty(import__114.ReferenceFrame.FIXED, 1); property.addSamples(times, positions, velocities); expect(property.getValue(times[0])).toEqual(positions[0]); expect(property.getValue(times[1])).toEqual(positions[1]); expect(property.getValue(times[2])).toEqual(positions[2]); expect(property.getValue(new import__114.JulianDate(0.5, 0))).toEqual( new import__114.Cartesian3(7.5, 8.5, 9.5) ); }); it("addSample throws when derivative is undefined but expected", function() { const property = new import__114.SampledPositionProperty(import__114.ReferenceFrame.FIXED, 1); expect(function() { property.addSample( new import__114.JulianDate(0, 0), new import__114.Cartesian3(7, 8, 9), void 0 ); }).toThrowDeveloperError(); }); it("addSamples throws when derivative is undefined but expected", function() { const times = [ new import__114.JulianDate(0, 0), new import__114.JulianDate(1, 0), new import__114.JulianDate(2, 0) ]; const positions = [ new import__114.Cartesian3(7, 8, 9), new import__114.Cartesian3(8, 9, 10), new import__114.Cartesian3(9, 10, 11) ]; const property = new import__114.SampledPositionProperty(import__114.ReferenceFrame.FIXED, 1); expect(function() { property.addSamples(times, positions, void 0); }).toThrowDeveloperError(); }); it("addSamples throws when derivative is not the correct length", function() { const times = [ new import__114.JulianDate(0, 0), new import__114.JulianDate(1, 0), new import__114.JulianDate(2, 0) ]; const positions = [ new import__114.Cartesian3(7, 8, 9), new import__114.Cartesian3(8, 9, 10), new import__114.Cartesian3(9, 10, 11) ]; const velocities = [[new import__114.Cartesian3(7, 8, 9)], [new import__114.Cartesian3(8, 9, 10)]]; const property = new import__114.SampledPositionProperty(import__114.ReferenceFrame.FIXED, 1); expect(function() { property.addSamples(times, positions, velocities); }).toThrowDeveloperError(); }); it("can set interpolationAlgorithm and degree", function() { const data = [0, 7, 8, 9, 1, 8, 9, 10, 2, 9, 10, 11]; const epoch = new import__114.JulianDate(0, 0); let timesCalled = 0; const MockInterpolation = { type: "Mock", getRequiredDataPoints: function(degree) { return 3; }, interpolateOrderZero: function(x, xTable, yTable, yStride, result) { expect(x).toEqual(1); expect(xTable.length).toEqual(3); expect(xTable[0]).toBe(-2); expect(xTable[1]).toBe(-1); expect(xTable[2]).toBe(0); expect(yTable.length).toEqual(9); expect(yTable[0]).toBe(7); expect(yTable[1]).toBe(8); expect(yTable[2]).toBe(9); expect(yTable[3]).toBe(8); expect(yTable[4]).toBe(9); expect(yTable[5]).toBe(10); expect(yTable[6]).toBe(9); expect(yTable[7]).toBe(10); expect(yTable[8]).toBe(11); expect(yStride).toEqual(3); expect(result.length).toEqual(3); result[0] = 2; result[1] = 3; result[2] = 4; timesCalled++; return result; } }; const property = new import__114.SampledPositionProperty(); property.forwardExtrapolationType = import__114.ExtrapolationType.EXTRAPOLATE; property.addSamplesPackedArray(data, epoch); property.setInterpolationOptions({ interpolationDegree: 2, interpolationAlgorithm: MockInterpolation }); expect(property.getValue(epoch)).toEqual(new import__114.Cartesian3(7, 8, 9)); expect(property.getValue(new import__114.JulianDate(0, 3))).toEqual( new import__114.Cartesian3(2, 3, 4) ); expect(timesCalled).toEqual(1); }); it("Returns undefined if trying to interpolate with less than enough samples.", function() { const value = new import__114.Cartesian3(1, 2, 3); const time2 = new import__114.JulianDate(0, 0); const property = new import__114.SampledPositionProperty(); property.addSample(time2, value); expect(property.getValue(time2)).toEqual(value); expect( property.getValue(import__114.JulianDate.addSeconds(time2, 4, new import__114.JulianDate())) ).toBeUndefined(); }); it("throws with no time parameter", function() { const property = new import__114.SampledPositionProperty(); expect(function() { property.getValue(void 0); }).toThrowDeveloperError(); }); it("throws with no reference frame parameter", function() { const property = new import__114.SampledPositionProperty(); const time2 = import__114.JulianDate.now(); expect(function() { property.getValueInReferenceFrame(time2, void 0); }).toThrowDeveloperError(); }); it("equals works when interpolators differ", function() { const left = new import__114.SampledPositionProperty(); const right = new import__114.SampledPositionProperty(); expect(left.equals(right)).toEqual(true); right.setInterpolationOptions({ interpolationAlgorithm: import__114.LagrangePolynomialApproximation }); expect(left.equals(right)).toEqual(false); }); it("equals works when interpolator degree differ", function() { const left = new import__114.SampledPositionProperty(); left.setInterpolationOptions({ interpolationDegree: 2, interpolationAlgorithm: import__114.LagrangePolynomialApproximation }); const right = new import__114.SampledPositionProperty(); right.setInterpolationOptions({ interpolationDegree: 2, interpolationAlgorithm: import__114.LagrangePolynomialApproximation }); expect(left.equals(right)).toEqual(true); right.setInterpolationOptions({ interpolationDegree: 3, interpolationAlgorithm: import__114.LagrangePolynomialApproximation }); expect(left.equals(right)).toEqual(false); }); it("equals works when reference frames differ", function() { const left = new import__114.SampledPositionProperty(import__114.ReferenceFrame.FIXED); const right = new import__114.SampledPositionProperty(import__114.ReferenceFrame.INERTIAL); expect(left.equals(right)).toEqual(false); }); it("equals works when samples differ", function() { const left = new import__114.SampledPositionProperty(); const right = new import__114.SampledPositionProperty(); expect(left.equals(right)).toEqual(true); const time2 = import__114.JulianDate.now(); const value = new import__114.Cartesian3(1, 2, 3); left.addSample(time2, value); expect(left.equals(right)).toEqual(false); right.addSample(time2, value); expect(left.equals(right)).toEqual(true); }); it("raises definitionChanged when extrapolation options change", function() { const property = new import__114.SampledPositionProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.forwardExtrapolationType = import__114.ExtrapolationType.EXTRAPOLATE; expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.forwardExtrapolationDuration = 1; expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.backwardExtrapolationType = import__114.ExtrapolationType.HOLD; expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.backwardExtrapolationDuration = 1; expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.forwardExtrapolationType = import__114.ExtrapolationType.EXTRAPOLATE; expect(listener).not.toHaveBeenCalled(); property.forwardExtrapolationDuration = 1; expect(listener).not.toHaveBeenCalled(); property.backwardExtrapolationType = import__114.ExtrapolationType.HOLD; expect(listener).not.toHaveBeenCalled(); property.backwardExtrapolationDuration = 1; expect(listener).not.toHaveBeenCalled(); }); }); // packages/engine/Specs/DataSources/SampledPropertySpec.js var import__115 = __toESM(require_Cesium(), 1); var import__116 = __toESM(require_Cesium(), 1); describe("DataSources/SampledProperty", function() { it("constructor sets expected defaults", function() { let property = new import__115.SampledProperty(import__115.Cartesian3); expect(property.interpolationDegree).toEqual(1); expect(property.interpolationAlgorithm).toEqual(import__115.LinearApproximation); expect(property.isConstant).toEqual(true); expect(property.type).toBe(import__115.Cartesian3); expect(property.derivativeTypes).toBeUndefined(); expect(property.forwardExtrapolationType).toEqual(import__115.ExtrapolationType.NONE); expect(property.forwardExtrapolationDuration).toEqual(0); expect(property.backwardExtrapolationType).toEqual(import__115.ExtrapolationType.NONE); expect(property.backwardExtrapolationDuration).toEqual(0); const derivatives2 = [import__115.Cartesian3, import__115.Cartesian3]; property = new import__115.SampledProperty(import__115.Quaternion, derivatives2); expect(property.interpolationDegree).toEqual(1); expect(property.interpolationAlgorithm).toEqual(import__115.LinearApproximation); expect(property.isConstant).toEqual(true); expect(property.type).toBe(import__115.Quaternion); expect(property.derivativeTypes).toBe(derivatives2); expect(property.forwardExtrapolationType).toEqual(import__115.ExtrapolationType.NONE); expect(property.forwardExtrapolationDuration).toEqual(0); expect(property.backwardExtrapolationType).toEqual(import__115.ExtrapolationType.NONE); expect(property.backwardExtrapolationDuration).toEqual(0); }); it("isConstant works", function() { const property = new import__115.SampledProperty(Number); expect(property.isConstant).toEqual(true); property.addSample(new import__115.JulianDate(0, 0), 1); expect(property.isConstant).toEqual(false); }); it("addSamplesPackedArray works", function() { const data = [0, 7, 1, 8, 2, 9]; const epoch2 = new import__115.JulianDate(0, 0); const property = new import__115.SampledProperty(Number); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.addSamplesPackedArray(data, epoch2); expect(listener).toHaveBeenCalledWith(property); expect(property.getValue(epoch2)).toEqual(7); expect(property.getValue(new import__115.JulianDate(0, 0.5))).toEqual(7.5); }); it("addSample works", function() { const times2 = [ new import__115.JulianDate(0, 0), new import__115.JulianDate(1, 0), new import__115.JulianDate(2, 0) ]; const values = [7, 8, 9]; const property = new import__115.SampledProperty(Number); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.addSample(times2[0], values[0]); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.addSample(times2[1], values[1]); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.addSample(times2[2], values[2]); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); expect(property.getValue(times2[0])).toEqual(values[0]); expect(property.getValue(times2[1])).toEqual(values[1]); expect(property.getValue(times2[2])).toEqual(values[2]); expect(property.getValue(new import__115.JulianDate(0.5, 0))).toEqual(7.5); }); it("addSamples works", function() { const times2 = [ new import__115.JulianDate(0, 0), new import__115.JulianDate(1, 0), new import__115.JulianDate(2, 0) ]; const values = [7, 8, 9]; const property = new import__115.SampledProperty(Number); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.addSamples(times2, values); expect(listener).toHaveBeenCalledWith(property); expect(property.getValue(times2[0])).toEqual(values[0]); expect(property.getValue(times2[1])).toEqual(values[1]); expect(property.getValue(times2[2])).toEqual(values[2]); expect(property.getValue(new import__115.JulianDate(0.5, 0))).toEqual(7.5); }); it("can remove a sample at a date", function() { const times2 = [ new import__115.JulianDate(0, 0), new import__115.JulianDate(1, 0), new import__115.JulianDate(2, 0) ]; const values = [1, 8, 3]; const property = new import__115.SampledProperty(Number); property.addSamples(times2, values); expect(property.getValue(times2[0])).toEqual(values[0]); expect(property.getValue(times2[1])).toEqual(values[1]); expect(property.getValue(times2[2])).toEqual(values[2]); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); let result = property.removeSample(new import__115.JulianDate(4, 0)); expect(result).toEqual(false); result = property.removeSample(times2[1]); expect(listener).toHaveBeenCalledWith(property); expect(result).toEqual(true); expect(property._times.length).toEqual(2); expect(property._values.length).toEqual(2); expect(property.getValue(times2[0])).toEqual(values[0]); expect(property.getValue(times2[1])).toEqual((values[0] + values[2]) / 2); expect(property.getValue(times2[2])).toEqual(values[2]); }); function arraySubset(array, startIndex, count) { array = array.slice(); array.splice(startIndex, count); return array; } it("can remove samples for a time interval", function() { const times2 = [ new import__115.JulianDate(0, 0), new import__115.JulianDate(1, 0), new import__115.JulianDate(2, 0), new import__115.JulianDate(3, 0), new import__115.JulianDate(4, 0) ]; const values = [1, 8, 13, 1, 3]; function createProperty() { const property2 = new import__115.SampledProperty(Number); property2.addSamples(times2, values); expect(property2.getValue(times2[0])).toEqual(values[0]); expect(property2.getValue(times2[1])).toEqual(values[1]); expect(property2.getValue(times2[2])).toEqual(values[2]); expect(property2.getValue(times2[3])).toEqual(values[3]); expect(property2.getValue(times2[4])).toEqual(values[4]); return property2; } let property = createProperty(); let listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.removeSamples( new import__115.TimeInterval({ start: times2[1], stop: times2[3] }) ); expect(listener).toHaveBeenCalledWith(property); expect(property._times.length).toEqual(2); expect(property._values.length).toEqual(2); expect(property._times).toEqual(arraySubset(times2, 1, 3)); expect(property._values).toEqual(arraySubset(values, 1, 3)); expect(property.getValue(times2[0])).toEqual(values[0]); expect(property.getValue(times2[2])).toEqual((values[0] + values[4]) / 2); expect(property.getValue(times2[4])).toEqual(values[4]); property = createProperty(); listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.removeSamples( new import__115.TimeInterval({ start: import__115.JulianDate.addSeconds(times2[1], 4, new import__115.JulianDate()), stop: times2[3] }) ); expect(listener).toHaveBeenCalledWith(property); expect(property._times.length).toEqual(3); expect(property._values.length).toEqual(3); expect(property._times).toEqual(arraySubset(times2, 2, 2)); expect(property._values).toEqual(arraySubset(values, 2, 2)); property = createProperty(); listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.removeSamples( new import__115.TimeInterval({ start: import__115.JulianDate.addSeconds(times2[1], 4, new import__115.JulianDate()), stop: import__115.JulianDate.addSeconds(times2[3], -4, new import__115.JulianDate()) }) ); expect(listener).toHaveBeenCalledWith(property); expect(property._times.length).toEqual(4); expect(property._values.length).toEqual(4); expect(property._times).toEqual(arraySubset(times2, 2, 1)); expect(property._values).toEqual(arraySubset(values, 2, 1)); }); it("can remove samples for a time interval with start or stop not included", function() { const times2 = [ new import__115.JulianDate(0, 0), new import__115.JulianDate(1, 0), new import__115.JulianDate(2, 0), new import__115.JulianDate(3, 0), new import__115.JulianDate(4, 0) ]; const values = [1, 8, 13, 1, 3]; function createProperty() { const property2 = new import__115.SampledProperty(Number); property2.addSamples(times2, values); expect(property2.getValue(times2[0])).toEqual(values[0]); expect(property2.getValue(times2[1])).toEqual(values[1]); expect(property2.getValue(times2[2])).toEqual(values[2]); expect(property2.getValue(times2[3])).toEqual(values[3]); expect(property2.getValue(times2[4])).toEqual(values[4]); return property2; } let property = createProperty(); let listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.removeSamples( new import__115.TimeInterval({ start: times2[1], stop: times2[3], isStartIncluded: false, isStopIncluded: true }) ); expect(listener).toHaveBeenCalledWith(property); expect(property._times).toEqual(arraySubset(times2, 2, 2)); expect(property._values).toEqual(arraySubset(values, 2, 2)); property = createProperty(); listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.removeSamples( new import__115.TimeInterval({ start: times2[1], stop: times2[3], isStartIncluded: true, isStopIncluded: false }) ); expect(listener).toHaveBeenCalledWith(property); expect(property._times).toEqual(arraySubset(times2, 1, 2)); expect(property._values).toEqual(arraySubset(values, 1, 2)); property = createProperty(); listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.removeSamples( new import__115.TimeInterval({ start: times2[1], stop: times2[3], isStartIncluded: false, isStopIncluded: false }) ); expect(listener).toHaveBeenCalledWith(property); expect(property._times).toEqual(arraySubset(times2, 2, 1)); expect(property._values).toEqual(arraySubset(values, 2, 1)); }); it("works with PackableForInterpolation", function() { function CustomType(value) { this.x = value; } CustomType.packedLength = 1; CustomType.packedInterpolationLength = 2; CustomType.pack = function(value, array, startingIndex) { array[startingIndex] = value.x; }; CustomType.unpack = function(array, startingIndex, result) { return array[startingIndex]; }; CustomType.convertPackedArrayForInterpolation = function(packedArray, startingIndex, lastIndex, result) { for (let i = 0, len = lastIndex - startingIndex + 1; i < len; i++) { const offset = i * 2; result[offset] = packedArray[i] * 0.5; result[offset + 1] = packedArray[i] * 0.5; } }; CustomType.unpackInterpolationResult = function(array, sourceArray, firstIndex, lastIndex, result) { if (!(0, import__115.defined)(result)) { result = new CustomType(); } result.x = array[0] + array[1]; return result; }; const times2 = [ new import__115.JulianDate(0, 0), new import__115.JulianDate(1, 0), new import__115.JulianDate(2, 0) ]; const values = [new CustomType(0), new CustomType(2), new CustomType(4)]; const property = new import__115.SampledProperty(CustomType); property.addSample(times2[0], values[0]); property.addSample(times2[1], values[1]); property.addSample(times2[2], values[2]); expect(property.getValue(new import__115.JulianDate(0.5, 0)).x).toEqual(1); }); it("can set interpolationAlgorithm and degree", function() { const data = [0, 7, 2, 9, 4, 11]; const epoch2 = new import__115.JulianDate(0, 0); let timesCalled = 0; const MockInterpolation = { type: "Mock", getRequiredDataPoints: function(degree) { return 3; }, interpolateOrderZero: function(x, xTable, yTable, yStride, result) { expect(x).toEqual(-1); expect(xTable.length).toEqual(3); expect(xTable[0]).toBe(-4); expect(xTable[1]).toBe(-2); expect(xTable[2]).toBe(0); expect(yTable.length).toEqual(3); expect(yTable[0]).toBe(7); expect(yTable[1]).toBe(9); expect(yTable[2]).toBe(11); expect(yStride).toEqual(1); expect(result.length).toEqual(1); result[0] = 2; timesCalled++; return result; } }; const property = new import__115.SampledProperty(Number); property.forwardExtrapolationType = import__115.ExtrapolationType.EXTRAPOLATE; property.addSamplesPackedArray(data, epoch2); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); expect(property.getValue(epoch2)).toEqual(7); expect(property.getValue(new import__115.JulianDate(0, 1))).toEqual(8); property.setInterpolationOptions({ interpolationAlgorithm: MockInterpolation, interpolationDegree: 2 }); expect(listener).toHaveBeenCalledWith(property); expect(property.getValue(epoch2)).toEqual(7); expect(property.getValue(new import__115.JulianDate(0, 3))).toEqual(2); expect(timesCalled).toEqual(1); }); it("Returns undefined if trying to interpolate with less than enough samples.", function() { const value = 7; const time2 = new import__115.JulianDate(0, 0); const property = new import__115.SampledProperty(Number); property.addSample(time2, value); expect(property.getValue(time2)).toEqual(value); expect( property.getValue(import__115.JulianDate.addSeconds(time2, 4, new import__115.JulianDate())) ).toBeUndefined(); }); it("Allows empty options object without failing", function() { const property = new import__115.SampledProperty(Number); const interpolationAlgorithm = property.interpolationAlgorithm; const interpolationDegree = property.interpolationDegree; property.setInterpolationOptions({}); expect(property.interpolationAlgorithm).toEqual(interpolationAlgorithm); expect(property.interpolationDegree).toEqual(interpolationDegree); }); it("mergeNewSamples works with huge data sets.", function() { const times2 = []; const values = []; const epoch2 = import__115.JulianDate.now(); const data = []; const expectedTimes = []; const expectedValues = []; for (let i = 0; i < 2e5; i++) { data.push(i); data.push(i); expectedTimes.push(import__115.JulianDate.addSeconds(epoch2, i, new import__115.JulianDate())); expectedValues.push(i); } import__115.SampledProperty._mergeNewSamples(epoch2, times2, values, data, 1); expect(times2).toEqual(expectedTimes, import__115.JulianDate.compare); expect(values).toEqual(expectedValues); }); it("mergeNewSamples works for sorted non-intersecting data.", function() { const times2 = []; const values = []; const epoch2 = import__115.JulianDate.now(); const newData = [0, "a", 1, "b", 2, "c"]; const newData2 = [3, "d", 4, "e", 5, "f"]; const expectedTimes = [ import__115.JulianDate.addSeconds(epoch2, 0, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 1, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 2, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 3, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 4, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 5, new import__115.JulianDate()) ]; const expectedValues = ["a", "b", "c", "d", "e", "f"]; import__115.SampledProperty._mergeNewSamples(epoch2, times2, values, newData, 1); import__115.SampledProperty._mergeNewSamples(epoch2, times2, values, newData2, 1); expect(times2).toEqual(expectedTimes, import__115.JulianDate.compare); expect(values).toEqual(expectedValues); }); it("mergeNewSamples works for ISO8601 dates", function() { const times2 = []; const values = []; const epoch2 = import__115.JulianDate.fromIso8601("2010-01-01T12:00:00"); const newData = [ "2010-01-01T12:00:00", "a", "2010-01-01T12:00:01", "b", "2010-01-01T12:00:02", "c" ]; const newData2 = [ "2010-01-01T12:00:03", "d", "2010-01-01T12:00:04", "e", "2010-01-01T12:00:05", "f" ]; const expectedTimes = [ import__115.JulianDate.addSeconds(epoch2, 0, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 1, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 2, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 3, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 4, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 5, new import__115.JulianDate()) ]; const expectedValues = ["a", "b", "c", "d", "e", "f"]; import__115.SampledProperty._mergeNewSamples(void 0, times2, values, newData, 1); import__115.SampledProperty._mergeNewSamples(void 0, times2, values, newData2, 1); expect(times2).toEqual(expectedTimes, import__115.JulianDate.compare); expect(values).toEqual(expectedValues); }); it("mergeNewSamples works for elements of size 2.", function() { const times2 = []; const values = []; const epoch2 = import__115.JulianDate.now(); const newData = [1, "b", "b", 4, "e", "e", 0, "a", "a"]; const newData2 = [2, "c", "c", 3, "d", "d"]; const expectedTimes = [ import__115.JulianDate.addSeconds(epoch2, 0, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 1, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 2, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 3, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 4, new import__115.JulianDate()) ]; const expectedValues = ["a", "a", "b", "b", "c", "c", "d", "d", "e", "e"]; import__115.SampledProperty._mergeNewSamples(epoch2, times2, values, newData, 2); import__115.SampledProperty._mergeNewSamples(epoch2, times2, values, newData2, 2); expect(times2).toEqual(expectedTimes, import__115.JulianDate.compare); expect(values).toEqual(expectedValues); }); it("mergeNewSamples works for unsorted intersecting data.", function() { const times2 = []; const values = []; const epoch2 = import__115.JulianDate.now(); const newData = [1, "b", 4, "e", 0, "a"]; const newData2 = [5, "f", 2, "c", 3, "d"]; const expectedTimes = [ import__115.JulianDate.addSeconds(epoch2, 0, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 1, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 2, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 3, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 4, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 5, new import__115.JulianDate()) ]; const expectedValues = ["a", "b", "c", "d", "e", "f"]; import__115.SampledProperty._mergeNewSamples(epoch2, times2, values, newData, 1); import__115.SampledProperty._mergeNewSamples(epoch2, times2, values, newData2, 1); expect(times2).toEqual(expectedTimes, import__115.JulianDate.compare); expect(values).toEqual(expectedValues); }); it("mergeNewSamples works for data with repeated values.", function() { const times2 = []; const values = []; const epoch2 = import__115.JulianDate.now(); const newData = [0, "a", 1, "b", 1, "c", 0, "d", 4, "e", 5, "f"]; const expectedTimes = [ import__115.JulianDate.addSeconds(epoch2, 0, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 1, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 4, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch2, 5, new import__115.JulianDate()) ]; const expectedValues = ["d", "c", "e", "f"]; import__115.SampledProperty._mergeNewSamples(epoch2, times2, values, newData, 1); expect(times2).toEqual(expectedTimes, import__115.JulianDate.compare); expect(values).toEqual(expectedValues); }); const interwovenData = [ { epoch: import__115.JulianDate.fromIso8601("20130205T150405.704999999999927Z"), values: [ 0, 1, 120, 2, 240, 3, 360, 4, 480, 6, 600, 8, 720, 10, 840, 12, 960, 14, 1080, 16 ] }, { epoch: import__115.JulianDate.fromIso8601("20130205T151151.60499999999956Z"), values: [ 0, 5, 120, 7, 240, 9, 360, 11, 480, 13, 600, 15, 720, 17, 840, 18, 960, 19, 1080, 20 ] } ]; it("mergeNewSamples works with interwoven data", function() { const times2 = []; const values = []; import__115.SampledProperty._mergeNewSamples( interwovenData[0].epoch, times2, values, interwovenData[0].values, 1 ); import__115.SampledProperty._mergeNewSamples( interwovenData[1].epoch, times2, values, interwovenData[1].values, 1 ); for (let i = 0; i < values.length; i++) { expect(values[i]).toBe(i + 1); } }); it("constructor throws without type parameter.", function() { expect(function() { return new import__115.SampledProperty(void 0); }).toThrowDeveloperError(); }); it("equals works when interpolators differ", function() { const left = new import__115.SampledProperty(Number); const right = new import__115.SampledProperty(Number); expect(left.equals(right)).toEqual(true); right.setInterpolationOptions({ interpolationAlgorithm: import__115.LagrangePolynomialApproximation }); expect(left.equals(right)).toEqual(false); }); it("equals works when interpolator degree differ", function() { const left = new import__115.SampledProperty(Number); left.setInterpolationOptions({ interpolationDegree: 2, interpolationAlgorithm: import__115.LagrangePolynomialApproximation }); const right = new import__115.SampledProperty(Number); right.setInterpolationOptions({ interpolationDegree: 2, interpolationAlgorithm: import__115.LagrangePolynomialApproximation }); expect(left.equals(right)).toEqual(true); right.setInterpolationOptions({ interpolationDegree: 3, interpolationAlgorithm: import__115.LagrangePolynomialApproximation }); expect(left.equals(right)).toEqual(false); }); it("equals works when samples differ", function() { const left = new import__115.SampledProperty(Number); const right = new import__115.SampledProperty(Number); expect(left.equals(right)).toEqual(true); const time2 = import__115.JulianDate.now(); left.addSample(time2, 5); expect(left.equals(right)).toEqual(false); right.addSample(time2, 5); expect(left.equals(right)).toEqual(true); }); it("equals works when samples differ with quaternion", function() { const left = new import__115.SampledProperty(import__115.Quaternion); const right = new import__115.SampledProperty(import__115.Quaternion); expect(left.equals(right)).toEqual(true); const time2 = import__115.JulianDate.now(); left.addSample(time2, new import__115.Quaternion(1, 2, 3, 4)); right.addSample(time2, new import__115.Quaternion(1, 2, 3, 5)); expect(left.equals(right)).toEqual(false); }); it("equals works when derivatives differ", function() { let left = new import__115.SampledProperty(Number, [Number]); let right = new import__115.SampledProperty(Number); expect(left.equals(right)).toEqual(false); left = new import__115.SampledProperty(Number, [Number]); right = new import__115.SampledProperty(Number, [Number]); expect(left.equals(right)).toEqual(true); left = new import__115.SampledProperty(Number, [Number]); right = new import__115.SampledProperty(Number, [Number, Number]); expect(left.equals(right)).toEqual(false); left = new import__115.SampledProperty(import__115.Cartesian3, [import__115.Cartesian3, Number]); right = new import__115.SampledProperty(import__115.Cartesian3, [Number, Number]); expect(left.equals(right)).toEqual(false); }); const epoch = import__115.JulianDate.fromIso8601("2014-01-01T00:00:00"); it("addSample works with multiple derivatives", function() { const results = [ 0, -3.39969163485071, 0.912945250727628, -6.17439797860995, 0.745113160479349, -1.63963048028446, -0.304810621102217, 4.83619040459681, -0.993888653923375, 169.448966391543 ]; const property = new import__115.SampledProperty(Number, [Number, Number]); property.forwardExtrapolationType = import__115.ExtrapolationType.EXTRAPOLATE; property.setInterpolationOptions({ interpolationAlgorithm: import__115.HermitePolynomialApproximation, interpolationDegree: 1 }); for (let x = 0; x < 100; x += 20) { property.addSample( import__115.JulianDate.addSeconds(epoch, x, new import__115.JulianDate()), Math.sin(x), [Math.cos(x), -Math.sin(x)] ); } let resultIndex = 0; for (let i = 0; i < 100; i += 10) { const result = property.getValue( import__115.JulianDate.addSeconds(epoch, i, new import__115.JulianDate()) ); expect(result).toEqualEpsilon( results[resultIndex++], import__116.Math.EPSILON12 ); } }); const times = [ import__115.JulianDate.addSeconds(epoch, 0, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch, 60, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch, 120, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch, 180, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch, 240, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch, 300, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch, 360, new import__115.JulianDate()), import__115.JulianDate.addSeconds(epoch, 420, new import__115.JulianDate()) ]; const positions = [ new import__115.Cartesian3(13378137, 0, 1), new import__115.Cartesian3(133741283576279e-7, 327475.593690065, 2), new import__115.Cartesian3(133621048328212e-7, 654754.936954423, 3), new import__115.Cartesian3(133420736310691e-7, 981641.896976832, 4), new import__115.Cartesian3(133140467567223e-7, 130794057608951e-8, 5), new import__115.Cartesian3(13278041005799e-6, 163345542917117e-8, 6), new import__115.Cartesian3(132340779559193e-7, 195799138083385e-8, 7), new import__115.Cartesian3(13182183953374e-6, 228135394232816e-8, 8) ]; const derivatives = [ [new import__115.Cartesian3(0, 5458.47176691947, 0)], [new import__115.Cartesian3(-133.614738921601, 5456.83618333919, 0)], [new import__115.Cartesian3(-267.149404854867, 5451.93041277513, 0)], [new import__115.Cartesian3(-400.523972797808, 5443.75739517027, 0)], [new import__115.Cartesian3(-533.658513692378, 5432.32202847183, 0)], [new import__115.Cartesian3(-666.473242324565, 5417.63116569613, 0)], [new import__115.Cartesian3(-798.888565138278, 5399.69361082164, 0)], [new import__115.Cartesian3(-930.82512793439, 5378.52011351288, 0)] ]; const order0Results = [ new import__115.Cartesian3(13378137, 0, 1), new import__115.Cartesian3(13376800785876e-6, 109158.531230022, 1.33333333333333), new import__115.Cartesian3(133754645717519e-7, 218317.062460043, 1.66666666666667), new import__115.Cartesian3(133741283576279e-7, 327475.593690065, 2), new import__115.Cartesian3(133701205160257e-7, 436568.708111518, 2.33333333333333), new import__115.Cartesian3(133661126744234e-7, 545661.82253297, 2.66666666666667), new import__115.Cartesian3(133621048328212e-7, 654754.936954423, 3), new import__115.Cartesian3(133554277655705e-7, 763717.256961893, 3.33333333333333), new import__115.Cartesian3(133487506983198e-7, 872679.576969362, 3.66666666666667), new import__115.Cartesian3(133420736310691e-7, 981641.896976832, 4), new import__115.Cartesian3(133327313396202e-7, 109040812334772e-8, 4.33333333333333), new import__115.Cartesian3(133233890481712e-7, 119917434971862e-8, 4.66666666666667), new import__115.Cartesian3(133140467567223e-7, 130794057608951e-8, 5), new import__115.Cartesian3(133020448397479e-7, 141644552711673e-8, 5.33333333333333), new import__115.Cartesian3(132900429227734e-7, 152495047814395e-8, 5.66666666666667), new import__115.Cartesian3(13278041005799e-6, 163345542917117e-8, 6), new import__115.Cartesian3(132633866558391e-7, 17416340797254e-7, 6.33333333333333), new import__115.Cartesian3(132487323058792e-7, 184981273027962e-8, 6.66666666666667), new import__115.Cartesian3(132340779559193e-7, 195799138083385e-8, 7), new import__115.Cartesian3(132167799550709e-7, 206577890133195e-8, 7.33333333333333), new import__115.Cartesian3(131994819542224e-7, 217356642183006e-8, 7.66666666666667), new import__115.Cartesian3(13182183953374e-6, 228135394232816e-8, 8) ]; const order1Results = [ new import__115.Cartesian3(13378137, 0, 1), new import__115.Cartesian3(133776915656321e-7, 109168.223625571, 1.25925925925926), new import__115.Cartesian3(133763553218481e-7, 218329.177845564, 1.74074074074074), new import__115.Cartesian3(133741283576279e-7, 327475.593690065, 2), new import__115.Cartesian3(133710107916129e-7, 436600.202479654, 2.25925925925926), new import__115.Cartesian3(133670028610487e-7, 545695.738439022, 2.74074074074074), new import__115.Cartesian3(133621048328212e-7, 654754.936954423, 3), new import__115.Cartesian3(133563170034622e-7, 763770.534428588, 3.25925925925926), new import__115.Cartesian3(133496397880007e-7, 872735.273070732, 3.74074074074074), new import__115.Cartesian3(133420736310691e-7, 981641.896976832, 4), new import__115.Cartesian3(133336190069115e-7, 109048315198472e-8, 4.25925925925926), new import__115.Cartesian3(133242765080919e-7, 11992517926376e-7, 4.74074074074074), new import__115.Cartesian3(133140467567223e-7, 130794057608951e-8, 5), new import__115.Cartesian3(133029304044753e-7, 141654226196067e-8, 5.25925925925926), new import__115.Cartesian3(132909282210945e-7, 152504962147035e-8, 5.74074074074074), new import__115.Cartesian3(13278041005799e-6, 163345542917117e-8, 6), new import__115.Cartesian3(13264269587299e-6, 174175246280477e-8, 6.25925925925926), new import__115.Cartesian3(132496149120568e-7, 184993351459858e-8, 6.74074074074074), new import__115.Cartesian3(132340779559193e-7, 195799138083385e-8, 7), new import__115.Cartesian3(132176597241379e-7, 206591886170184e-8, 7.25925925925926), new import__115.Cartesian3(13200361339326e-6, 217370877475762e-8, 7.74074074074074), new import__115.Cartesian3(13182183953374e-6, 228135394232816e-8, 8) ]; it("addSample works with derivatives", function() { const property = new import__115.SampledProperty(import__115.Cartesian3, [import__115.Cartesian3]); property.setInterpolationOptions({ interpolationAlgorithm: import__115.HermitePolynomialApproximation, interpolationDegree: 1 }); for (let x = 0; x < times.length; x++) { property.addSample(times[x], positions[x], derivatives[x]); } let resultIndex = 0; for (let i = 0; i < 420; i += 20) { const result = property.getValue( import__115.JulianDate.addSeconds(epoch, i, new import__115.JulianDate()) ); expect(result).toEqualEpsilon( order1Results[resultIndex++], import__116.Math.EPSILON7 ); } }); it("addSample works without derivatives", function() { const property = new import__115.SampledProperty(import__115.Cartesian3); property.setInterpolationOptions({ interpolationAlgorithm: import__115.HermitePolynomialApproximation, interpolationDegree: 1 }); for (let x = 0; x < times.length; x++) { property.addSample(times[x], positions[x]); } let resultIndex = 0; for (let i = 0; i < 420; i += 20) { const result = property.getValue( import__115.JulianDate.addSeconds(epoch, i, new import__115.JulianDate()) ); expect(result).toEqualEpsilon( order0Results[resultIndex++], import__116.Math.EPSILON7 ); } }); it("addSamples works with derivatives", function() { const property = new import__115.SampledProperty(import__115.Cartesian3, [import__115.Cartesian3]); property.setInterpolationOptions({ interpolationAlgorithm: import__115.HermitePolynomialApproximation, interpolationDegree: 1 }); property.addSamples(times, positions, derivatives); let resultIndex = 0; for (let i = 0; i < 420; i += 20) { const result = property.getValue( import__115.JulianDate.addSeconds(epoch, i, new import__115.JulianDate()) ); expect(result).toEqualEpsilon( order1Results[resultIndex++], import__116.Math.EPSILON7 ); } }); it("addSamples works without derivatives", function() { const property = new import__115.SampledProperty(import__115.Cartesian3); property.setInterpolationOptions({ interpolationAlgorithm: import__115.HermitePolynomialApproximation, interpolationDegree: 1 }); property.addSamples(times, positions); let resultIndex = 0; for (let i = 0; i < 420; i += 20) { const result = property.getValue( import__115.JulianDate.addSeconds(epoch, i, new import__115.JulianDate()) ); expect(result).toEqualEpsilon( order0Results[resultIndex++], import__116.Math.EPSILON7 ); } }); it("addSamplesPackedArray works with derivatives", function() { const property = new import__115.SampledProperty(import__115.Cartesian3, [import__115.Cartesian3]); property.setInterpolationOptions({ interpolationAlgorithm: import__115.HermitePolynomialApproximation, interpolationDegree: 1 }); const data = []; for (let x = 0; x < times.length; x++) { data.push(times[x]); import__115.Cartesian3.pack(positions[x], data, data.length); import__115.Cartesian3.pack(derivatives[x][0], data, data.length); } property.addSamplesPackedArray(data); let resultIndex = 0; for (let i = 0; i < 420; i += 20) { const result = property.getValue( import__115.JulianDate.addSeconds(epoch, i, new import__115.JulianDate()) ); expect(result).toEqualEpsilon( order1Results[resultIndex++], import__116.Math.EPSILON7 ); } }); it("addSamplesPackedArray works without derivatives", function() { const property = new import__115.SampledProperty(import__115.Cartesian3); property.setInterpolationOptions({ interpolationAlgorithm: import__115.HermitePolynomialApproximation, interpolationDegree: 1 }); const data = []; for (let x = 0; x < times.length; x++) { data.push(times[x]); import__115.Cartesian3.pack(positions[x], data, data.length); } property.addSamplesPackedArray(data); let resultIndex = 0; for (let i = 0; i < 420; i += 20) { const result = property.getValue( import__115.JulianDate.addSeconds(epoch, i, new import__115.JulianDate()) ); expect(result).toEqualEpsilon( order0Results[resultIndex++], import__116.Math.EPSILON7 ); } }); it("obeys extrapolation options", function() { const property = new import__115.SampledProperty(Number); const time0 = new import__115.JulianDate(0, 0.99); const time1 = new import__115.JulianDate(0, 1); const time2 = new import__115.JulianDate(0, 2); const time3 = new import__115.JulianDate(0, 3); const time4 = new import__115.JulianDate(0, 4); const time5 = new import__115.JulianDate(0, 4.01); property.addSample(time2, 1); property.addSample(time3, 2); expect(property.getValue(time0)).toBeUndefined(); expect(property.getValue(time1)).toBeUndefined(); expect(property.getValue(time2)).toBe(1); expect(property.getValue(time3)).toBe(2); expect(property.getValue(time4)).toBeUndefined(); expect(property.getValue(time5)).toBeUndefined(); property.forwardExtrapolationType = import__115.ExtrapolationType.HOLD; property.forwardExtrapolationDuration = 1; property.backwardExtrapolationType = import__115.ExtrapolationType.NONE; property.backwardExtrapolationDuration = 1; expect(property.getValue(time1)).toBeUndefined(); expect(property.getValue(time2)).toBe(1); expect(property.getValue(time3)).toBe(2); expect(property.getValue(time4)).toBe(2); expect(property.getValue(time5)).toBeUndefined(); property.forwardExtrapolationType = import__115.ExtrapolationType.EXTRAPOLATE; property.forwardExtrapolationDuration = 1; property.backwardExtrapolationType = import__115.ExtrapolationType.NONE; property.backwardExtrapolationDuration = 1; expect(property.getValue(time1)).toBeUndefined(); expect(property.getValue(time2)).toBe(1); expect(property.getValue(time3)).toBe(2); expect(property.getValue(time4)).toBe(3); expect(property.getValue(time5)).toBeUndefined(); property.forwardExtrapolationType = import__115.ExtrapolationType.NONE; property.forwardExtrapolationDuration = 1; property.backwardExtrapolationType = import__115.ExtrapolationType.HOLD; property.backwardExtrapolationDuration = 1; expect(property.getValue(time0)).toBeUndefined(); expect(property.getValue(time1)).toBe(1); expect(property.getValue(time2)).toBe(1); expect(property.getValue(time3)).toBe(2); expect(property.getValue(time4)).toBeUndefined(); property.forwardExtrapolationType = import__115.ExtrapolationType.NONE; property.forwardExtrapolationDuration = 1; property.backwardExtrapolationType = import__115.ExtrapolationType.EXTRAPOLATE; property.backwardExtrapolationDuration = 1; expect(property.getValue(time0)).toBeUndefined(); expect(property.getValue(time1)).toBe(0); expect(property.getValue(time2)).toBe(1); expect(property.getValue(time3)).toBe(2); expect(property.getValue(time4)).toBeUndefined(); }); it("getValue returns undefined for empty extrapolated property", function() { const sampledPosition = new import__115.SampledProperty(import__115.Cartesian3); sampledPosition.backwardExtrapolationType = import__115.ExtrapolationType.HOLD; sampledPosition.forwardExtrapolationType = import__115.ExtrapolationType.HOLD; const result = sampledPosition.getValue(import__115.JulianDate.now()); expect(result).toBeUndefined(); }); it("raises definitionChanged when extrapolation options change", function() { const property = new import__115.SampledProperty(Number); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.forwardExtrapolationType = import__115.ExtrapolationType.EXTRAPOLATE; expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.forwardExtrapolationDuration = 1; expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.backwardExtrapolationType = import__115.ExtrapolationType.HOLD; expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.backwardExtrapolationDuration = 1; expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.forwardExtrapolationType = import__115.ExtrapolationType.EXTRAPOLATE; expect(listener).not.toHaveBeenCalled(); property.forwardExtrapolationDuration = 1; expect(listener).not.toHaveBeenCalled(); property.backwardExtrapolationType = import__115.ExtrapolationType.HOLD; expect(listener).not.toHaveBeenCalled(); property.backwardExtrapolationDuration = 1; expect(listener).not.toHaveBeenCalled(); }); }); // packages/engine/Specs/DataSources/StaticGeometryColorBatchSpec.js var import__117 = __toESM(require_Cesium(), 1); var import__118 = __toESM(require_Cesium(), 1); describe("DataSources/StaticGeometryColorBatch", function() { const time2 = import__117.JulianDate.now(); let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); it("updates color attribute after rebuilding geometry primitive", function() { const batch = new import__117.StaticGeometryColorBatch( scene2.primitives, import__117.PerInstanceColorAppearance, void 0, false, import__117.ShadowMode.DISABLED ); const entity = new import__117.Entity({ position: new import__117.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, show: new import__117.CallbackProperty(function() { return true; }, false), material: import__117.Color.RED, height: 0 } }); const updater = new import__117.EllipseGeometryUpdater(entity, scene2); batch.add(time2, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.color).toEqual([255, 0, 0, 255]); entity.ellipse.material = import__117.Color.GREEN; updater._onEntityPropertyChanged(entity, "ellipse"); batch.remove(updater); batch.add(time2, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive2 = scene2.primitives.get(0); const attributes2 = primitive2.getGeometryInstanceAttributes(entity); expect(attributes2.color).toEqual([0, 128, 0, 255]); batch.removeAllPrimitives(); }); }); }); it("updates with sampled color out of range", function() { const validTime = import__117.JulianDate.fromIso8601("2018-02-14T04:10:00+1100"); const outOfRangeTime = import__117.JulianDate.fromIso8601("2018-02-14T04:20:00+1100"); const color = new import__117.TimeIntervalCollectionProperty(); color.intervals.addInterval( import__117.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100", data: import__117.Color.RED }) ); const entity = new import__117.Entity({ availability: new import__117.TimeIntervalCollection([ import__117.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100" }) ]), position: new import__117.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, extrudedHeight: 20, material: new import__117.ColorMaterialProperty(color) } }); const batch = new import__117.StaticGeometryColorBatch( scene2.primitives, import__117.PerInstanceColorAppearance, void 0, false, import__117.ShadowMode.DISABLED ); const updater = new import__117.EllipseGeometryUpdater(entity, scene2); batch.add(validTime, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(validTime); scene2.render(validTime); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); let primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.color).toEqual([255, 0, 0, 255]); batch.update(outOfRangeTime); scene2.render(outOfRangeTime); primitive = scene2.primitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.color).toEqual([255, 255, 255, 255]); batch.removeAllPrimitives(); }); }); it("updates with sampled distance display condition out of range", function() { const validTime = import__117.JulianDate.fromIso8601("2018-02-14T04:10:00+1100"); const outOfRangeTime = import__117.JulianDate.fromIso8601("2018-02-14T04:20:00+1100"); const ddc = new import__117.TimeIntervalCollectionProperty(); ddc.intervals.addInterval( import__117.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100", data: new import__117.DistanceDisplayCondition(1, 2) }) ); const entity = new import__117.Entity({ availability: new import__117.TimeIntervalCollection([ import__117.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100" }) ]), position: new import__117.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, extrudedHeight: 20, material: import__117.Color.RED, distanceDisplayCondition: ddc } }); const batch = new import__117.StaticGeometryColorBatch( scene2.primitives, import__117.PerInstanceColorAppearance, void 0, false, import__117.ShadowMode.DISABLED ); const updater = new import__117.EllipseGeometryUpdater(entity, scene2); batch.add(validTime, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(validTime); scene2.render(validTime); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); let primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.distanceDisplayCondition).toEqualEpsilon( [1, 2], import__118.Math.EPSILON6 ); batch.update(outOfRangeTime); scene2.render(outOfRangeTime); primitive = scene2.primitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.distanceDisplayCondition).toEqual([0, Infinity]); batch.removeAllPrimitives(); }); }); it("updates with sampled show out of range", function() { const validTime = import__117.JulianDate.fromIso8601("2018-02-14T04:10:00+1100"); const outOfRangeTime = import__117.JulianDate.fromIso8601("2018-02-14T04:20:00+1100"); const show = new import__117.TimeIntervalCollectionProperty(); show.intervals.addInterval( import__117.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100", data: true }) ); const entity = new import__117.Entity({ availability: new import__117.TimeIntervalCollection([ import__117.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100" }) ]), position: new import__117.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, extrudedHeight: 20, show } }); const batch = new import__117.StaticGeometryColorBatch( scene2.primitives, import__117.PerInstanceColorAppearance, void 0, false, import__117.ShadowMode.DISABLED ); const updater = new import__117.EllipseGeometryUpdater(entity, scene2); batch.add(validTime, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(validTime); scene2.render(validTime); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); let primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.show).toEqual([1]); batch.update(outOfRangeTime); scene2.render(outOfRangeTime); primitive = scene2.primitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.show).toEqual([0]); batch.removeAllPrimitives(); }); }); it("updates color attribute after rebuilding polyline primitive", function() { const batch = new import__117.StaticGeometryColorBatch( scene2.primitives, import__117.PolylineColorAppearance, void 0, false, import__117.ShadowMode.DISABLED ); const entity = new import__117.Entity({ polyline: { positions: [ import__117.Cartesian3.fromDegrees(0, 0), import__117.Cartesian3.fromDegrees(0, 1) ], material: import__117.Color.RED } }); const updater = new import__117.PolylineGeometryUpdater(entity, scene2); batch.add(time2, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.color).toEqual([255, 0, 0, 255]); entity.polyline.material = import__117.Color.GREEN; batch.remove(updater); batch.add(time2, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive2 = scene2.primitives.get(0); const attributes2 = primitive2.getGeometryInstanceAttributes(entity); expect(attributes2.color).toEqual([0, 128, 0, 255]); batch.removeAllPrimitives(); }); }); }); it("updates with sampled depth fail color out of range", function() { const validTime = import__117.JulianDate.fromIso8601("2018-02-14T04:10:00+1100"); const color = new import__117.TimeIntervalCollectionProperty(); color.intervals.addInterval( import__117.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100", data: import__117.Color.RED }) ); const entity = new import__117.Entity({ availability: new import__117.TimeIntervalCollection([ import__117.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100" }) ]), polyline: { positions: [ import__117.Cartesian3.fromDegrees(0, 0), import__117.Cartesian3.fromDegrees(0, 1) ], material: import__117.Color.BLUE, depthFailMaterial: new import__117.ColorMaterialProperty(color) } }); const batch = new import__117.StaticGeometryColorBatch( scene2.primitives, import__117.PolylineColorAppearance, import__117.PolylineColorAppearance, false, import__117.ShadowMode.DISABLED ); const updater = new import__117.PolylineGeometryUpdater(entity, scene2); batch.add(validTime, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(validTime); scene2.render(validTime); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); let primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.depthFailColor).toEqual([255, 0, 0, 255]); batch.update(time2); scene2.render(time2); primitive = scene2.primitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.depthFailColor).toEqual([255, 255, 255, 255]); batch.removeAllPrimitives(); }); }); it("shows only one primitive while rebuilding primitive", function() { const batch = new import__117.StaticGeometryColorBatch( scene2.primitives, import__117.PerInstanceColorAppearance, void 0, false, import__117.ShadowMode.DISABLED ); function buildEntity() { return new import__117.Entity({ position: new import__117.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material: import__117.Color.RED.withAlpha(0.5), height: 0 } }); } function renderScene() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; } const entity1 = buildEntity(); const entity2 = buildEntity(); const updater1 = new import__117.EllipseGeometryUpdater(entity1, scene2); const updater2 = new import__117.EllipseGeometryUpdater(entity2, scene2); batch.add(time2, updater1); return pollToPromise_default(renderScene).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); expect(primitive.show).toBeTruthy(); }).then(function() { batch.add(time2, updater2); }).then(function() { return pollToPromise_default(function() { renderScene(); return scene2.primitives.length === 2; }); }).then(function() { let showCount = 0; expect(scene2.primitives.length).toEqual(2); showCount += !!scene2.primitives.get(0).show; showCount += !!scene2.primitives.get(1).show; expect(showCount).toEqual(1); }).then(function() { return pollToPromise_default(renderScene); }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); expect(primitive.show).toBeTruthy(); batch.removeAllPrimitives(); }); }); it("has correct show attribute after rebuilding primitive", function() { const batch = new import__117.StaticGeometryColorBatch( scene2.primitives, import__117.PerInstanceColorAppearance, void 0, false, import__117.ShadowMode.DISABLED ); function buildEntity() { return new import__117.Entity({ position: new import__117.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material: import__117.Color.RED.withAlpha(0.5), height: 0 } }); } function renderScene() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; } const entity1 = buildEntity(); const updater1 = new import__117.EllipseGeometryUpdater(entity1, scene2); batch.add(time2, updater1); const entity2 = buildEntity(); const updater2 = new import__117.EllipseGeometryUpdater(entity2, scene2); return pollToPromise_default(renderScene).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([1]); entity1.show = false; updater1._onEntityPropertyChanged(entity1, "isShowing"); return pollToPromise_default(renderScene); }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([0]); batch.add(time2, updater2); return pollToPromise_default(renderScene); }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([0]); attributes = primitive.getGeometryInstanceAttributes(entity2); expect(attributes.show).toEqual([1]); batch.removeAllPrimitives(); }); }); }); // packages/engine/Specs/DataSources/StaticGeometryPerMaterialBatchSpec.js var import__119 = __toESM(require_Cesium(), 1); var import__120 = __toESM(require_Cesium(), 1); describe("DataSources/StaticGeometryPerMaterialBatch", function() { const time2 = import__119.JulianDate.now(); let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); it("handles shared material being invalidated with geometry", function() { const batch = new import__119.StaticGeometryPerMaterialBatch( scene2.primitives, import__119.MaterialAppearance, void 0, false, import__119.ShadowMode.DISABLED ); const ellipse = new import__119.EllipseGraphics(); ellipse.semiMajorAxis = new import__119.ConstantProperty(2); ellipse.semiMinorAxis = new import__119.ConstantProperty(1); ellipse.material = new import__119.GridMaterialProperty(); const entity = new import__119.Entity(); entity.position = new import__119.ConstantPositionProperty( new import__119.Cartesian3(1234, 5678, 9101112) ); entity.ellipse = ellipse; const ellipse2 = new import__119.EllipseGraphics(); ellipse2.semiMajorAxis = new import__119.ConstantProperty(3); ellipse2.semiMinorAxis = new import__119.ConstantProperty(2); ellipse2.material = new import__119.GridMaterialProperty(); const entity2 = new import__119.Entity(); entity2.position = new import__119.ConstantPositionProperty( new import__119.Cartesian3(1234, 5678, 9101112) ); entity2.ellipse = ellipse2; const updater = new import__119.EllipseGeometryUpdater(entity, scene2); const updater2 = new import__119.EllipseGeometryUpdater(entity2, scene2); batch.add(time2, updater); batch.add(time2, updater2); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); ellipse.material.cellAlpha = new import__119.ConstantProperty(0.5); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(2); batch.removeAllPrimitives(); }); }); }); it("updates with sampled distance display condition out of range", function() { const validTime = import__119.JulianDate.fromIso8601("2018-02-14T04:10:00+1100"); const outOfRangeTime = import__119.JulianDate.fromIso8601("2018-02-14T04:20:00+1100"); const ddc = new import__119.TimeIntervalCollectionProperty(); ddc.intervals.addInterval( import__119.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100", data: new import__119.DistanceDisplayCondition(1, 2) }) ); const entity = new import__119.Entity({ availability: new import__119.TimeIntervalCollection([ import__119.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100" }) ]), position: new import__119.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, extrudedHeight: 20, material: new import__119.GridMaterialProperty(), distanceDisplayCondition: ddc } }); const batch = new import__119.StaticGeometryPerMaterialBatch( scene2.primitives, import__119.MaterialAppearance, void 0, false, import__119.ShadowMode.DISABLED ); const updater = new import__119.EllipseGeometryUpdater(entity, scene2); batch.add(validTime, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(validTime); scene2.render(validTime); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); let primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.distanceDisplayCondition).toEqualEpsilon( [1, 2], import__120.Math.EPSILON6 ); batch.update(outOfRangeTime); scene2.render(outOfRangeTime); primitive = scene2.primitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.distanceDisplayCondition).toEqual([0, Infinity]); batch.removeAllPrimitives(); }); }); it("updates with sampled show out of range", function() { const validTime = import__119.JulianDate.fromIso8601("2018-02-14T04:10:00+1100"); const outOfRangeTime = import__119.JulianDate.fromIso8601("2018-02-14T04:20:00+1100"); const show = new import__119.TimeIntervalCollectionProperty(); show.intervals.addInterval( import__119.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100", data: true }) ); const entity = new import__119.Entity({ availability: new import__119.TimeIntervalCollection([ import__119.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100" }) ]), position: new import__119.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, extrudedHeight: 20, material: new import__119.GridMaterialProperty(), show } }); const batch = new import__119.StaticGeometryPerMaterialBatch( scene2.primitives, import__119.MaterialAppearance, void 0, false, import__119.ShadowMode.DISABLED ); const updater = new import__119.EllipseGeometryUpdater(entity, scene2); batch.add(validTime, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(validTime); scene2.render(validTime); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); let primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.show).toEqual([1]); batch.update(outOfRangeTime); scene2.render(outOfRangeTime); primitive = scene2.primitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.show).toEqual([0]); batch.removeAllPrimitives(); }); }); it("handles shared material being invalidated for polyline", function() { const batch = new import__119.StaticGeometryPerMaterialBatch( scene2.primitives, import__119.PolylineMaterialAppearance, void 0, false, import__119.ShadowMode.DISABLED ); const polyline = new import__119.PolylineGraphics(); polyline.positions = new import__119.ConstantProperty([ import__119.Cartesian3.fromDegrees(0, 0), import__119.Cartesian3.fromDegrees(0, 1) ]); polyline.material = new import__119.PolylineArrowMaterialProperty(); const entity = new import__119.Entity(); entity.polyline = polyline; const polyline2 = new import__119.PolylineGraphics(); polyline2.positions = new import__119.ConstantProperty([ import__119.Cartesian3.fromDegrees(0, 0), import__119.Cartesian3.fromDegrees(0, 1) ]); polyline2.material = new import__119.PolylineArrowMaterialProperty(); const entity2 = new import__119.Entity(); entity2.polyline = polyline2; const updater = new import__119.PolylineGeometryUpdater(entity, scene2); const updater2 = new import__119.PolylineGeometryUpdater(entity2, scene2); batch.add(time2, updater); batch.add(time2, updater2); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); polyline.material.color = new import__119.ConstantProperty(import__119.Color.RED); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(2); batch.removeAllPrimitives(); }); }); }); it("updates with sampled depth fail color out of range", function() { const validTime = import__119.JulianDate.fromIso8601("2018-02-14T04:10:00+1100"); const color = new import__119.TimeIntervalCollectionProperty(); color.intervals.addInterval( import__119.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100", data: import__119.Color.RED }) ); const entity = new import__119.Entity({ availability: new import__119.TimeIntervalCollection([ import__119.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100" }) ]), polyline: { positions: [ import__119.Cartesian3.fromDegrees(0, 0), import__119.Cartesian3.fromDegrees(0, 1) ], material: new import__119.PolylineArrowMaterialProperty(), depthFailMaterial: new import__119.ColorMaterialProperty(color) } }); const batch = new import__119.StaticGeometryPerMaterialBatch( scene2.primitives, import__119.PolylineMaterialAppearance, import__119.PolylineColorAppearance, false, import__119.ShadowMode.DISABLED ); const updater = new import__119.PolylineGeometryUpdater(entity, scene2); batch.add(validTime, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(validTime); scene2.render(validTime); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); let primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.depthFailColor).toEqual([255, 0, 0, 255]); batch.update(time2); scene2.render(time2); primitive = scene2.primitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.depthFailColor).toEqual([255, 255, 255, 255]); batch.removeAllPrimitives(); }); }); it("shows only one primitive while rebuilding primitive", function() { const batch = new import__119.StaticGeometryPerMaterialBatch( scene2.primitives, import__119.MaterialAppearance, void 0, false, import__119.ShadowMode.DISABLED ); function buildEntity() { const material = new import__119.GridMaterialProperty({ color: import__119.Color.YELLOW, cellAlpha: 0.3, lineCount: new import__119.Cartesian2(8, 8), lineThickness: new import__119.Cartesian2(2, 2) }); return new import__119.Entity({ position: new import__119.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, height: 0, material } }); } function renderScene() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; } const entity1 = buildEntity(); const entity2 = buildEntity(); const updater1 = new import__119.EllipseGeometryUpdater(entity1, scene2); const updater2 = new import__119.EllipseGeometryUpdater(entity2, scene2); batch.add(time2, updater1); return pollToPromise_default(renderScene).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); expect(primitive.show).toBeTruthy(); }).then(function() { batch.add(time2, updater2); }).then(function() { return pollToPromise_default(function() { renderScene(); return scene2.primitives.length === 2; }); }).then(function() { let showCount = 0; expect(scene2.primitives.length).toEqual(2); showCount += !!scene2.primitives.get(0).show; showCount += !!scene2.primitives.get(1).show; expect(showCount).toEqual(1); }).then(function() { return pollToPromise_default(renderScene); }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); expect(primitive.show).toBeTruthy(); batch.removeAllPrimitives(); }); }); it("removes all updaters", function() { const batch = new import__119.StaticGeometryPerMaterialBatch( scene2.primitives, import__119.MaterialAppearance, void 0, false, import__119.ShadowMode.DISABLED ); function buildEntity(MaterialProperty) { const material = new MaterialProperty({ evenColor: import__119.Color.YELLOW, oddColor: import__119.Color.BLUE }); return new import__119.Entity({ position: new import__119.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, height: 0, material } }); } function renderScene() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; } const entity1 = buildEntity(import__119.StripeMaterialProperty); const entity2 = buildEntity(import__119.CheckerboardMaterialProperty); const entity3 = buildEntity(import__119.StripeMaterialProperty); const entity4 = buildEntity(import__119.CheckerboardMaterialProperty); const updater1 = new import__119.EllipseGeometryUpdater(entity1, scene2); const updater2 = new import__119.EllipseGeometryUpdater(entity2, scene2); const updater3 = new import__119.EllipseGeometryUpdater(entity3, scene2); const updater4 = new import__119.EllipseGeometryUpdater(entity4, scene2); const emptyUpdater = new import__119.BoxGeometryUpdater(entity1, scene2); batch.add(time2, updater1); batch.add(time2, updater2); batch.add(time2, updater3); batch.add(time2, updater4); return pollToPromise_default(renderScene).then(function() { expect(scene2.primitives.length).toEqual(2); }).then(function() { batch.remove(updater1); batch.remove(updater2); batch.remove(emptyUpdater); batch.remove(updater3); batch.remove(updater4); return pollToPromise_default(renderScene); }).then(function() { expect(scene2.primitives.length).toEqual(0); batch.removeAllPrimitives(); }); }); it("has correct show attribute after rebuilding primitive", function() { const batch = new import__119.StaticGeometryPerMaterialBatch( scene2.primitives, import__119.MaterialAppearance, void 0, false, import__119.ShadowMode.DISABLED ); function buildEntity() { const material = new import__119.GridMaterialProperty({ color: import__119.Color.YELLOW, cellAlpha: 0.3, lineCount: new import__119.Cartesian2(8, 8), lineThickness: new import__119.Cartesian2(2, 2) }); return new import__119.Entity({ position: new import__119.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, height: 0, material } }); } function renderScene() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; } const entity1 = buildEntity(); const updater1 = new import__119.EllipseGeometryUpdater(entity1, scene2); batch.add(time2, updater1); const entity2 = buildEntity(); const updater2 = new import__119.EllipseGeometryUpdater(entity2, scene2); return pollToPromise_default(renderScene).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([1]); entity1.show = false; updater1._onEntityPropertyChanged(entity1, "isShowing"); return pollToPromise_default(renderScene); }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([0]); batch.add(time2, updater2); return pollToPromise_default(renderScene); }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([0]); attributes = primitive.getGeometryInstanceAttributes(entity2); expect(attributes.show).toEqual([1]); batch.removeAllPrimitives(); }); }); }); // packages/engine/Specs/DataSources/StaticGroundGeometryColorBatchSpec.js var import__121 = __toESM(require_Cesium(), 1); var import__122 = __toESM(require_Cesium(), 1); describe("DataSources/StaticGroundGeometryColorBatch", function() { const time2 = import__121.JulianDate.now(); let scene2; beforeAll(function() { scene2 = createScene_default(); return import__121.GroundPrimitive.initializeTerrainHeights(); }); afterAll(function() { scene2.destroyForSpecs(); import__121.GroundPrimitive._initialized = false; import__121.GroundPrimitive._initPromise = void 0; import__121.ApproximateTerrainHeights._initPromise = void 0; import__121.ApproximateTerrainHeights._terrainHeights = void 0; }); it("updates color attribute after rebuilding primitive", function() { if (!import__121.GroundPrimitive.isSupported(scene2)) { return; } const batch = new import__121.StaticGroundGeometryColorBatch( scene2.groundPrimitives, import__121.ClassificationType.BOTH ); const entity = new import__121.Entity({ position: new import__121.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, show: new import__121.CallbackProperty(function() { return true; }, false), material: import__121.Color.RED } }); const updater = new import__121.EllipseGeometryUpdater(entity, scene2); batch.add(time2, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); const primitive = scene2.groundPrimitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); const red = [255, 0, 0, 255]; expect(attributes.color).toEqual(red); expect(batch._batches.length).toEqual(1); entity.ellipse.material = import__121.Color.GREEN; updater._onEntityPropertyChanged(entity, "ellipse"); batch.remove(updater); batch.add(time2, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); const primitive2 = scene2.groundPrimitives.get(0); const attributes2 = primitive2.getGeometryInstanceAttributes(entity); const green = [0, 128, 0, 255]; expect(attributes2.color).toEqual(green); expect(batch._batches.length).toEqual(1); batch.removeAllPrimitives(); }); }); }); it("batches overlapping geometry separately", function() { if (!import__121.GroundPrimitive.isSupported(scene2)) { return; } const batch = new import__121.StaticGroundGeometryColorBatch( scene2.groundPrimitives, import__121.ClassificationType.BOTH ); const entity = new import__121.Entity({ position: new import__121.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, show: new import__121.CallbackProperty(function() { return true; }, false), material: import__121.Color.RED } }); const entity2 = new import__121.Entity({ position: new import__121.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, show: new import__121.CallbackProperty(function() { return true; }, false), material: import__121.Color.RED } }); const updater = new import__121.EllipseGeometryUpdater(entity, scene2); batch.add(time2, updater); const updater2 = new import__121.EllipseGeometryUpdater(entity2, scene2); batch.add(time2, updater2); expect(batch._batches.length).toEqual(2); }); it("updates with sampled distance display condition out of range", function() { const validTime = import__121.JulianDate.fromIso8601("2018-02-14T04:10:00+1100"); const outOfRangeTime = import__121.JulianDate.fromIso8601("2018-02-14T04:20:00+1100"); const ddc = new import__121.TimeIntervalCollectionProperty(); ddc.intervals.addInterval( import__121.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100", data: new import__121.DistanceDisplayCondition(1, 2) }) ); const entity = new import__121.Entity({ availability: new import__121.TimeIntervalCollection([ import__121.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100" }) ]), position: new import__121.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material: import__121.Color.RED, distanceDisplayCondition: ddc } }); const batch = new import__121.StaticGroundGeometryColorBatch( scene2.groundPrimitives, import__121.ClassificationType.BOTH ); const updater = new import__121.EllipseGeometryUpdater(entity, scene2); batch.add(validTime, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(validTime); scene2.render(validTime); return isUpdated; }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); let primitive = scene2.groundPrimitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.distanceDisplayCondition).toEqualEpsilon( [1, 2], import__122.Math.EPSILON6 ); batch.update(outOfRangeTime); scene2.render(outOfRangeTime); primitive = scene2.groundPrimitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.distanceDisplayCondition).toEqual([0, Infinity]); batch.removeAllPrimitives(); }); }); it("updates with sampled show out of range", function() { const validTime = import__121.JulianDate.fromIso8601("2018-02-14T04:10:00+1100"); const outOfRangeTime = import__121.JulianDate.fromIso8601("2018-02-14T04:20:00+1100"); const show = new import__121.TimeIntervalCollectionProperty(); show.intervals.addInterval( import__121.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100", data: true }) ); const entity = new import__121.Entity({ availability: new import__121.TimeIntervalCollection([ import__121.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100" }) ]), position: new import__121.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material: import__121.Color.RED, show } }); const batch = new import__121.StaticGroundGeometryColorBatch( scene2.groundPrimitives, import__121.ClassificationType.BOTH ); const updater = new import__121.EllipseGeometryUpdater(entity, scene2); batch.add(validTime, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(validTime); scene2.render(validTime); return isUpdated; }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); let primitive = scene2.groundPrimitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.show).toEqual([1]); batch.update(outOfRangeTime); scene2.render(outOfRangeTime); primitive = scene2.groundPrimitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.show).toEqual([0]); batch.removeAllPrimitives(); }); }); it("shows only one primitive while rebuilding primitive", function() { if (!import__121.GroundPrimitive.isSupported(scene2)) { return; } const batch = new import__121.StaticGroundGeometryColorBatch( scene2.groundPrimitives, import__121.ClassificationType.BOTH ); function renderScene() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; } const entity1 = new import__121.Entity({ position: new import__121.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 0.2, semiMinorAxis: 0.1, outline: true, outlineColor: import__121.Color.RED.withAlpha(0.5) } }); const entity2 = new import__121.Entity({ position: new import__121.Cartesian3(1234, 4678, 9101112), ellipse: { semiMajorAxis: 0.2, semiMinorAxis: 0.1, outline: true, outlineColor: import__121.Color.RED.withAlpha(0.5) } }); const updater1 = new import__121.EllipseGeometryUpdater(entity1, scene2); const updater2 = new import__121.EllipseGeometryUpdater(entity2, scene2); batch.add(time2, updater1); return pollToPromise_default(renderScene).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); const primitive = scene2.groundPrimitives.get(0); expect(primitive.show).toBeTruthy(); }).then(function() { batch.add(time2, updater2); }).then(function() { return pollToPromise_default(function() { renderScene(); return scene2.groundPrimitives.length === 2; }); }).then(function() { let showCount = 0; expect(scene2.groundPrimitives.length).toEqual(2); showCount += !!scene2.groundPrimitives.get(0).show; showCount += !!scene2.groundPrimitives.get(1).show; expect(showCount).toEqual(1); }).then(function() { return pollToPromise_default(renderScene); }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); const primitive = scene2.groundPrimitives.get(0); expect(primitive.show).toBeTruthy(); batch.removeAllPrimitives(); }); }); it("has correct show attribute after rebuilding primitive", function() { if (!import__121.GroundPrimitive.isSupported(scene2)) { return; } const batch = new import__121.StaticGroundGeometryColorBatch( scene2.groundPrimitives, import__121.ClassificationType.BOTH ); function renderScene() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; } const entity1 = new import__121.Entity({ position: new import__121.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 0.2, semiMinorAxis: 0.1, outline: true, outlineColor: import__121.Color.RED.withAlpha(0.5) } }); const updater1 = new import__121.EllipseGeometryUpdater(entity1, scene2); batch.add(time2, updater1); const entity2 = new import__121.Entity({ position: new import__121.Cartesian3(1234, 4678, 9101112), ellipse: { semiMajorAxis: 0.2, semiMinorAxis: 0.1, outline: true, outlineColor: import__121.Color.RED.withAlpha(0.5) } }); const updater2 = new import__121.EllipseGeometryUpdater(entity2, scene2); return pollToPromise_default(renderScene).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); const primitive = scene2.groundPrimitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([1]); entity1.show = false; updater1._onEntityPropertyChanged(entity1, "isShowing"); return pollToPromise_default(renderScene); }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); const primitive = scene2.groundPrimitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([0]); batch.add(time2, updater2); return pollToPromise_default(renderScene); }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); const primitive = scene2.groundPrimitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([0]); attributes = primitive.getGeometryInstanceAttributes(entity2); expect(attributes.show).toEqual([1]); batch.removeAllPrimitives(); }); }); }); // packages/engine/Specs/DataSources/StaticGroundGeometryPerMaterialBatchSpec.js var import__123 = __toESM(require_Cesium(), 1); var import__124 = __toESM(require_Cesium(), 1); describe("DataSources/StaticGroundGeometryPerMaterialBatch", function() { const time2 = import__123.JulianDate.now(); let scene2; beforeAll(function() { scene2 = createScene_default(); return import__123.GroundPrimitive.initializeTerrainHeights(); }); afterAll(function() { scene2.destroyForSpecs(); import__123.GroundPrimitive._initialized = false; import__123.GroundPrimitive._initPromise = void 0; import__123.ApproximateTerrainHeights._initPromise = void 0; import__123.ApproximateTerrainHeights._terrainHeights = void 0; }); it("handles shared material being invalidated with geometry", function() { if (!import__123.GroundPrimitive.isSupported(scene2) || !import__123.GroundPrimitive.supportsMaterials(scene2)) { return; } const batch = new import__123.StaticGroundGeometryPerMaterialBatch( scene2.primitives, import__123.ClassificationType.BOTH, import__123.MaterialAppearance ); const ellipse = new import__123.EllipseGraphics(); ellipse.semiMajorAxis = new import__123.ConstantProperty(2); ellipse.semiMinorAxis = new import__123.ConstantProperty(1); ellipse.material = new import__123.GridMaterialProperty(); const entity = new import__123.Entity({ position: new import__123.Cartesian3(1234, 5678, 9101112), ellipse }); const ellipse2 = new import__123.EllipseGraphics(); ellipse2.semiMajorAxis = new import__123.ConstantProperty(3); ellipse2.semiMinorAxis = new import__123.ConstantProperty(2); ellipse2.material = new import__123.GridMaterialProperty(); const entity2 = new import__123.Entity({ position: new import__123.Cartesian3(123, 456, 789), ellipse: ellipse2 }); const updater = new import__123.EllipseGeometryUpdater(entity, scene2); const updater2 = new import__123.EllipseGeometryUpdater(entity2, scene2); batch.add(time2, updater); batch.add(time2, updater2); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); ellipse.material.cellAlpha = new import__123.ConstantProperty(0.5); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }); }).then(function() { expect(scene2.primitives.length).toEqual(2); batch.removeAllPrimitives(); }); }); it("updates with sampled distance display condition out of range", function() { if (!import__123.GroundPrimitive.isSupported(scene2) || !import__123.GroundPrimitive.supportsMaterials(scene2)) { return; } const validTime = import__123.JulianDate.fromIso8601("2018-02-14T04:10:00+1100"); const outOfRangeTime = import__123.JulianDate.fromIso8601("2018-02-14T04:20:00+1100"); const ddc = new import__123.TimeIntervalCollectionProperty(); ddc.intervals.addInterval( import__123.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100", data: new import__123.DistanceDisplayCondition(1, 2) }) ); const entity = new import__123.Entity({ availability: new import__123.TimeIntervalCollection([ import__123.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100" }) ]), position: new import__123.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material: new import__123.GridMaterialProperty(), distanceDisplayCondition: ddc } }); const batch = new import__123.StaticGroundGeometryPerMaterialBatch( scene2.primitives, import__123.ClassificationType.BOTH, import__123.MaterialAppearance ); const updater = new import__123.EllipseGeometryUpdater(entity, scene2); batch.add(validTime, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(validTime); scene2.render(validTime); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); let primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.distanceDisplayCondition).toEqualEpsilon( [1, 2], import__124.Math.EPSILON6 ); batch.update(outOfRangeTime); scene2.render(outOfRangeTime); primitive = scene2.primitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.distanceDisplayCondition).toEqual([0, Infinity]); batch.removeAllPrimitives(); }); }); it("updates with sampled show out of range", function() { if (!import__123.GroundPrimitive.isSupported(scene2) || !import__123.GroundPrimitive.supportsMaterials(scene2)) { return; } const validTime = import__123.JulianDate.fromIso8601("2018-02-14T04:10:00+1100"); const outOfRangeTime = import__123.JulianDate.fromIso8601("2018-02-14T04:20:00+1100"); const show = new import__123.TimeIntervalCollectionProperty(); show.intervals.addInterval( import__123.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100", data: true }) ); const entity = new import__123.Entity({ availability: new import__123.TimeIntervalCollection([ import__123.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100" }) ]), position: new import__123.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material: new import__123.GridMaterialProperty(), show } }); const batch = new import__123.StaticGroundGeometryPerMaterialBatch( scene2.primitives, import__123.ClassificationType.BOTH, import__123.MaterialAppearance ); const updater = new import__123.EllipseGeometryUpdater(entity, scene2); batch.add(validTime, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(validTime); scene2.render(validTime); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); let primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.show).toEqual([1]); batch.update(outOfRangeTime); scene2.render(outOfRangeTime); primitive = scene2.primitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.show).toEqual([0]); batch.removeAllPrimitives(); }); }); it("shows only one primitive while rebuilding primitive", function() { if (!import__123.GroundPrimitive.isSupported(scene2) || !import__123.GroundPrimitive.supportsMaterials(scene2)) { return; } const batch = new import__123.StaticGroundGeometryPerMaterialBatch( scene2.primitives, import__123.ClassificationType.BOTH, import__123.MaterialAppearance ); function buildEntity(x, y, z) { const material = new import__123.GridMaterialProperty({ color: import__123.Color.YELLOW, cellAlpha: 0.3, lineCount: new import__123.Cartesian2(8, 8), lineThickness: new import__123.Cartesian2(2, 2) }); return new import__123.Entity({ position: new import__123.Cartesian3(x, y, z), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material } }); } function renderScene() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; } const entity1 = buildEntity(1234, 5678, 9101112); const entity2 = buildEntity(123, 456, 789); const updater1 = new import__123.EllipseGeometryUpdater(entity1, scene2); const updater2 = new import__123.EllipseGeometryUpdater(entity2, scene2); batch.add(time2, updater1); return pollToPromise_default(renderScene).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); expect(primitive.show).toBeTruthy(); }).then(function() { batch.add(time2, updater2); }).then(function() { return pollToPromise_default(function() { renderScene(); return scene2.primitives.length === 2; }); }).then(function() { let showCount = 0; expect(scene2.primitives.length).toEqual(2); showCount += !!scene2.primitives.get(0).show; showCount += !!scene2.primitives.get(1).show; expect(showCount).toEqual(1); }).then(function() { return pollToPromise_default(renderScene); }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); expect(primitive.show).toBeTruthy(); batch.removeAllPrimitives(); }); }); it("batches overlapping entities with the same material separately", function() { if (!import__123.GroundPrimitive.isSupported(scene2) || !import__123.GroundPrimitive.supportsMaterials(scene2)) { return; } const batch = new import__123.StaticGroundGeometryPerMaterialBatch( scene2.primitives, import__123.ClassificationType.BOTH, import__123.MaterialAppearance ); const ellipse = new import__123.EllipseGraphics(); ellipse.semiMajorAxis = new import__123.ConstantProperty(2); ellipse.semiMinorAxis = new import__123.ConstantProperty(1); ellipse.material = new import__123.GridMaterialProperty(); const entity = new import__123.Entity({ position: new import__123.Cartesian3(1234, 5678, 9101112), ellipse }); const ellipse2 = new import__123.EllipseGraphics(); ellipse2.semiMajorAxis = new import__123.ConstantProperty(3); ellipse2.semiMinorAxis = new import__123.ConstantProperty(2); ellipse2.material = new import__123.GridMaterialProperty(); const entity2 = new import__123.Entity({ position: new import__123.Cartesian3(1234, 5678, 9101112), ellipse: ellipse2 }); const updater = new import__123.EllipseGeometryUpdater(entity, scene2); const updater2 = new import__123.EllipseGeometryUpdater(entity2, scene2); batch.add(time2, updater); batch.add(time2, updater2); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(2); batch.removeAllPrimitives(); }); }); it("batches nonoverlapping entities that both use color materials", function() { if (!import__123.GroundPrimitive.isSupported(scene2) || !import__123.GroundPrimitive.supportsMaterials(scene2)) { return; } const batch = new import__123.StaticGroundGeometryPerMaterialBatch( scene2.primitives, import__123.ClassificationType.BOTH, import__123.MaterialAppearance ); const entity = new import__123.Entity({ position: new import__123.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material: import__123.Color.RED } }); const entity2 = new import__123.Entity({ position: new import__123.Cartesian3(123, 456, 789), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material: import__123.Color.BLUE } }); const updater = new import__123.EllipseGeometryUpdater(entity, scene2); const updater2 = new import__123.EllipseGeometryUpdater(entity2, scene2); batch.add(time2, updater); batch.add(time2, updater2); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); batch.removeAllPrimitives(); }); }); it("has correct show attribute after rebuilding primitive", function() { if (!import__123.GroundPrimitive.isSupported(scene2)) { return; } if (!import__123.GroundPrimitive.isSupported(scene2) || !import__123.GroundPrimitive.supportsMaterials(scene2)) { return; } const batch = new import__123.StaticGroundGeometryPerMaterialBatch( scene2.primitives, import__123.ClassificationType.BOTH, import__123.MaterialAppearance ); function buildEntity(x, y, z) { const material = new import__123.GridMaterialProperty({ color: import__123.Color.YELLOW, cellAlpha: 0.3, lineCount: new import__123.Cartesian2(8, 8), lineThickness: new import__123.Cartesian2(2, 2) }); return new import__123.Entity({ position: new import__123.Cartesian3(x, y, z), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, material } }); } function renderScene() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; } const entity1 = buildEntity(1234, 5678, 9101112); const updater1 = new import__123.EllipseGeometryUpdater(entity1, scene2); batch.add(time2, updater1); const entity2 = buildEntity(123, 456, 789); const updater2 = new import__123.EllipseGeometryUpdater(entity2, scene2); return pollToPromise_default(renderScene).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([1]); entity1.show = false; updater1._onEntityPropertyChanged(entity1, "isShowing"); return pollToPromise_default(renderScene); }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([0]); batch.add(time2, updater2); return pollToPromise_default(renderScene); }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([0]); attributes = primitive.getGeometryInstanceAttributes(entity2); expect(attributes.show).toEqual([1]); batch.removeAllPrimitives(); }); }); }); // packages/engine/Specs/DataSources/StaticGroundPolylinePerMaterialBatchSpec.js var import__125 = __toESM(require_Cesium(), 1); var import__126 = __toESM(require_Cesium(), 1); describe("DataSources/StaticGroundPolylinePerMaterialBatch", function() { const time2 = import__125.JulianDate.now(); let batch; let scene2; beforeAll(function() { scene2 = createScene_default(); return import__125.GroundPolylinePrimitive.initializeTerrainHeights(); }); afterAll(function() { scene2.destroyForSpecs(); import__125.GroundPolylinePrimitive._initPromise = void 0; import__125.GroundPolylinePrimitive._initialized = false; import__125.ApproximateTerrainHeights._initPromise = void 0; import__125.ApproximateTerrainHeights._terrainHeights = void 0; }); afterEach(function() { if ((0, import__125.defined)(batch)) { batch.removeAllPrimitives(); batch = void 0; } }); function createGroundPolyline() { const polyline = new import__125.PolylineGraphics(); polyline.clampToGround = new import__125.ConstantProperty(true); polyline.positions = new import__125.ConstantProperty( import__125.Cartesian3.fromDegreesArray([0, 0, 0.1, 0, 0.1, 0.1, 0, 0.1]) ); return polyline; } it("handles shared material being invalidated with geometry", function() { if (!import__125.GroundPolylinePrimitive.isSupported(scene2)) { return; } batch = new import__125.StaticGroundPolylinePerMaterialBatch( scene2.groundPrimitives, import__125.ClassificationType.BOTH, false ); const polyline1 = createGroundPolyline(); polyline1.material = new import__125.PolylineOutlineMaterialProperty(); const entity = new import__125.Entity({ polyline: polyline1 }); const polyline2 = createGroundPolyline(); polyline2.material = new import__125.PolylineOutlineMaterialProperty(); const entity2 = new import__125.Entity({ polyline: polyline2 }); const updater = new import__125.PolylineGeometryUpdater(entity, scene2); const updater2 = new import__125.PolylineGeometryUpdater(entity2, scene2); batch.add(time2, updater); batch.add(time2, updater2); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); polyline1.material.outlineWidth = new import__125.ConstantProperty(0.5); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.groundPrimitives.length).toEqual(2); batch.removeAllPrimitives(); }); }); }); it("updates with sampled color out of range", function() { if (!import__125.GroundPolylinePrimitive.isSupported(scene2)) { return; } const validTime = import__125.JulianDate.fromIso8601("2018-02-14T04:10:00+1100"); const color = new import__125.TimeIntervalCollectionProperty(); color.intervals.addInterval( import__125.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100", data: import__125.Color.RED }) ); const polyline = createGroundPolyline(); polyline.material = new import__125.ColorMaterialProperty(color); const entity = new import__125.Entity({ availability: new import__125.TimeIntervalCollection([ import__125.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100" }) ]), polyline }); batch = new import__125.StaticGroundPolylinePerMaterialBatch( scene2.groundPrimitives, import__125.ClassificationType.BOTH, false ); const updater = new import__125.PolylineGeometryUpdater(entity, scene2); batch.add(validTime, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(validTime); scene2.render(validTime); return isUpdated; }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); let primitive = scene2.groundPrimitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.color).toEqual([255, 0, 0, 255]); batch.update(time2); scene2.render(time2); primitive = scene2.groundPrimitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.color).toEqual([255, 255, 255, 255]); batch.removeAllPrimitives(); }); }); it("updates with sampled distance display condition out of range", function() { if (!import__125.GroundPolylinePrimitive.isSupported(scene2)) { return; } const validTime = import__125.JulianDate.fromIso8601("2018-02-14T04:10:00+1100"); const outOfRangeTime = import__125.JulianDate.fromIso8601("2018-02-14T04:20:00+1100"); const ddc = new import__125.TimeIntervalCollectionProperty(); ddc.intervals.addInterval( import__125.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100", data: new import__125.DistanceDisplayCondition(1, 2) }) ); const polyline = createGroundPolyline(); polyline.distanceDisplayCondition = ddc; const entity = new import__125.Entity({ availability: new import__125.TimeIntervalCollection([ import__125.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100" }) ]), polyline }); batch = new import__125.StaticGroundPolylinePerMaterialBatch( scene2.groundPrimitives, import__125.ClassificationType.BOTH, false ); const updater = new import__125.PolylineGeometryUpdater(entity, scene2); batch.add(validTime, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(validTime); scene2.render(validTime); return isUpdated; }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); let primitive = scene2.groundPrimitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.distanceDisplayCondition).toEqualEpsilon( [1, 2], import__126.Math.EPSILON6 ); batch.update(outOfRangeTime); scene2.render(outOfRangeTime); primitive = scene2.groundPrimitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.distanceDisplayCondition).toEqual([0, Infinity]); batch.removeAllPrimitives(); }); }); it("updates with sampled color out of range", function() { if (!import__125.GroundPolylinePrimitive.isSupported(scene2)) { return; } const validTime = import__125.JulianDate.fromIso8601("2018-02-14T04:10:00+1100"); const outOfRangeTime = import__125.JulianDate.fromIso8601("2018-02-14T04:20:00+1100"); const show = new import__125.TimeIntervalCollectionProperty(); show.intervals.addInterval( import__125.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100", data: true }) ); const polyline = createGroundPolyline(); polyline.show = show; const entity = new import__125.Entity({ availability: new import__125.TimeIntervalCollection([ import__125.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100" }) ]), polyline }); batch = new import__125.StaticGroundPolylinePerMaterialBatch( scene2.groundPrimitives, false ); const updater = new import__125.PolylineGeometryUpdater(entity, scene2); batch.add(validTime, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(validTime); scene2.render(validTime); return isUpdated; }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); let primitive = scene2.groundPrimitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.show).toEqual([1]); batch.update(outOfRangeTime); scene2.render(outOfRangeTime); primitive = scene2.groundPrimitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.show).toEqual([0]); batch.removeAllPrimitives(); }); }); it("shows only one primitive while rebuilding primitive", function() { if (!import__125.GroundPolylinePrimitive.isSupported(scene2)) { return; } batch = new import__125.StaticGroundPolylinePerMaterialBatch( scene2.groundPrimitives, import__125.ClassificationType.BOTH, false ); function buildEntity() { const polyline = createGroundPolyline(); polyline.material = new import__125.PolylineOutlineMaterialProperty({ color: import__125.Color.ORANGE, outlineWidth: 2, outlineColor: import__125.Color.BLACK }); return new import__125.Entity({ polyline }); } function renderScene() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; } const entity1 = buildEntity(); const entity2 = buildEntity(); const updater1 = new import__125.PolylineGeometryUpdater(entity1, scene2); const updater2 = new import__125.PolylineGeometryUpdater(entity2, scene2); batch.add(time2, updater1); return pollToPromise_default(renderScene).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); const primitive = scene2.groundPrimitives.get(0); expect(primitive.show).toBeTruthy(); }).then(function() { batch.add(time2, updater2); }).then(function() { return pollToPromise_default(function() { renderScene(); return scene2.groundPrimitives.length === 2; }); }).then(function() { let showCount = 0; expect(scene2.groundPrimitives.length).toEqual(2); showCount += !!scene2.groundPrimitives.get(0).show; showCount += !!scene2.groundPrimitives.get(1).show; expect(showCount).toEqual(1); }).then(function() { return pollToPromise_default(renderScene); }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); const primitive = scene2.groundPrimitives.get(0); expect(primitive.show).toBeTruthy(); batch.removeAllPrimitives(); }); }); it("batches entities that both use color materials", function() { if (!import__125.GroundPolylinePrimitive.isSupported(scene2)) { return; } batch = new import__125.StaticGroundPolylinePerMaterialBatch( scene2.groundPrimitives, import__125.ClassificationType.BOTH, false ); const polyline1 = createGroundPolyline(); polyline1.material = import__125.Color.RED; const entity = new import__125.Entity({ polyline: polyline1 }); const polyline2 = createGroundPolyline(); polyline2.material = import__125.Color.RED; const entity2 = new import__125.Entity({ polyline: polyline2 }); const updater = new import__125.PolylineGeometryUpdater(entity, scene2); const updater2 = new import__125.PolylineGeometryUpdater(entity2, scene2); batch.add(time2, updater); batch.add(time2, updater2); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); batch.removeAllPrimitives(); }); }); it("batches entities with the same material but different Z indices separately", function() { if (!import__125.GroundPolylinePrimitive.isSupported(scene2)) { return; } batch = new import__125.StaticGroundPolylinePerMaterialBatch( scene2.groundPrimitives, import__125.ClassificationType.BOTH, false ); const polyline1 = createGroundPolyline(); polyline1.material = new import__125.PolylineOutlineMaterialProperty(); polyline1.zIndex = 0; const entity = new import__125.Entity({ polyline: polyline1 }); const polyline2 = createGroundPolyline(); polyline2.material = new import__125.PolylineOutlineMaterialProperty(); polyline2.zIndex = 1; const entity2 = new import__125.Entity({ polyline: polyline2 }); const updater = new import__125.PolylineGeometryUpdater(entity, scene2); const updater2 = new import__125.PolylineGeometryUpdater(entity2, scene2); batch.add(time2, updater); batch.add(time2, updater2); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.groundPrimitives.length).toEqual(2); batch.removeAllPrimitives(); }); }); it("removes entities", function() { if (!import__125.GroundPolylinePrimitive.isSupported(scene2)) { return; } batch = new import__125.StaticGroundPolylinePerMaterialBatch( scene2.groundPrimitives, import__125.ClassificationType.BOTH, false ); const polyline1 = createGroundPolyline(); polyline1.material = new import__125.PolylineOutlineMaterialProperty(); const entity = new import__125.Entity({ polyline: polyline1 }); const updater = new import__125.PolylineGeometryUpdater(entity, scene2); batch.add(time2, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); batch.remove(updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }); }).then(function() { expect(scene2.groundPrimitives.length).toEqual(0); batch.removeAllPrimitives(); }); }); it("gets bounding spheres", function() { if (!import__125.GroundPolylinePrimitive.isSupported(scene2)) { return; } const resultSphere = new import__125.BoundingSphere(); batch = new import__125.StaticGroundPolylinePerMaterialBatch( scene2.groundPrimitives, import__125.ClassificationType.BOTH, false ); const polyline1 = createGroundPolyline(); polyline1.material = new import__125.PolylineOutlineMaterialProperty(); const entity = new import__125.Entity({ polyline: polyline1 }); const updater = new import__125.PolylineGeometryUpdater(entity, scene2); let state2 = batch.getBoundingSphere(updater, resultSphere); expect(state2).toEqual(import__125.BoundingSphereState.FAILED); batch.add(time2, updater); batch.update(time2); state2 = batch.getBoundingSphere(updater, resultSphere); expect(state2).toEqual(import__125.BoundingSphereState.PENDING); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); state2 = batch.getBoundingSphere(updater, resultSphere); expect(state2).toEqual(import__125.BoundingSphereState.DONE); batch.removeAllPrimitives(); }); }); it("has correct show attribute after rebuilding primitive", function() { if (!import__125.GroundPolylinePrimitive.isSupported(scene2)) { return; } batch = new import__125.StaticGroundPolylinePerMaterialBatch( scene2.groundPrimitives, import__125.ClassificationType.BOTH, false ); function buildEntity() { const polyline = createGroundPolyline(); polyline.material = new import__125.PolylineOutlineMaterialProperty({ color: import__125.Color.ORANGE, outlineWidth: 2, outlineColor: import__125.Color.BLACK }); return new import__125.Entity({ polyline }); } function renderScene() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; } const entity1 = buildEntity(); const updater1 = new import__125.PolylineGeometryUpdater(entity1, scene2); batch.add(time2, updater1); const entity2 = buildEntity(); const updater2 = new import__125.PolylineGeometryUpdater(entity2, scene2); return pollToPromise_default(renderScene).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); const primitive = scene2.groundPrimitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([1]); entity1.show = false; updater1._onEntityPropertyChanged(entity1, "isShowing"); return pollToPromise_default(renderScene); }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); const primitive = scene2.groundPrimitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([0]); batch.add(time2, updater2); return pollToPromise_default(renderScene); }).then(function() { expect(scene2.groundPrimitives.length).toEqual(1); const primitive = scene2.groundPrimitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([0]); attributes = primitive.getGeometryInstanceAttributes(entity2); expect(attributes.show).toEqual([1]); batch.removeAllPrimitives(); }); }); }); // packages/engine/Specs/DataSources/StaticOutlineGeometryBatchSpec.js var import__127 = __toESM(require_Cesium(), 1); var import__128 = __toESM(require_Cesium(), 1); describe("DataSources/StaticOutlineGeometryBatch", function() { const time2 = import__127.JulianDate.now(); let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); it("updates color attribute after rebuilding primitive", function() { const batch = new import__127.StaticOutlineGeometryBatch( scene2.primitives, scene2, false, import__127.ShadowMode.DISABLED ); const entity = new import__127.Entity({ position: new import__127.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, show: new import__127.CallbackProperty(function() { return true; }, false), outline: true, outlineColor: import__127.Color.RED, height: 0 } }); const updater = new import__127.EllipseGeometryUpdater(entity, scene2); batch.add(time2, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.color).toEqual([255, 0, 0, 255]); entity.ellipse.outlineColor = import__127.Color.GREEN; updater._onEntityPropertyChanged(entity, "ellipse"); batch.remove(updater); batch.add(time2, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive2 = scene2.primitives.get(0); const attributes2 = primitive2.getGeometryInstanceAttributes(entity); expect(attributes2.color).toEqual([0, 128, 0, 255]); batch.removeAllPrimitives(); }); }); }); it("updates with sampled color out of range", function() { const validTime = import__127.JulianDate.fromIso8601("2018-02-14T04:10:00+1100"); const outOfRangeTime = import__127.JulianDate.fromIso8601("2018-02-14T04:20:00+1100"); const color = new import__127.TimeIntervalCollectionProperty(); color.intervals.addInterval( import__127.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100", data: import__127.Color.RED }) ); const entity = new import__127.Entity({ availability: new import__127.TimeIntervalCollection([ import__127.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100" }) ]), position: new import__127.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, extrudedHeight: 20, outline: true, outlineColor: color } }); const batch = new import__127.StaticOutlineGeometryBatch( scene2.primitives, scene2, false, import__127.ShadowMode.DISABLED ); const updater = new import__127.EllipseGeometryUpdater(entity, scene2); batch.add(validTime, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(validTime); scene2.render(validTime); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); let primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.color).toEqual([255, 0, 0, 255]); batch.update(outOfRangeTime); scene2.render(outOfRangeTime); primitive = scene2.primitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.color).toEqual([255, 255, 255, 255]); batch.removeAllPrimitives(); }); }); it("updates with sampled distance display condition out of range", function() { const validTime = import__127.JulianDate.fromIso8601("2018-02-14T04:10:00+1100"); const outOfRangeTime = import__127.JulianDate.fromIso8601("2018-02-14T04:20:00+1100"); const ddc = new import__127.TimeIntervalCollectionProperty(); ddc.intervals.addInterval( import__127.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100", data: new import__127.DistanceDisplayCondition(1, 2) }) ); const entity = new import__127.Entity({ availability: new import__127.TimeIntervalCollection([ import__127.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100" }) ]), position: new import__127.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, extrudedHeight: 20, outline: true, outlineColor: import__127.Color.RED, distanceDisplayCondition: ddc } }); const batch = new import__127.StaticOutlineGeometryBatch( scene2.primitives, scene2, false, import__127.ShadowMode.DISABLED ); const updater = new import__127.EllipseGeometryUpdater(entity, scene2); batch.add(validTime, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(validTime); scene2.render(validTime); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); let primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.distanceDisplayCondition).toEqualEpsilon( [1, 2], import__128.Math.EPSILON6 ); batch.update(outOfRangeTime); scene2.render(outOfRangeTime); primitive = scene2.primitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.distanceDisplayCondition).toEqual([0, Infinity]); batch.removeAllPrimitives(); }); }); it("updates with sampled show out of range", function() { const validTime = import__127.JulianDate.fromIso8601("2018-02-14T04:10:00+1100"); const outOfRangeTime = import__127.JulianDate.fromIso8601("2018-02-14T04:20:00+1100"); const show = new import__127.TimeIntervalCollectionProperty(); show.intervals.addInterval( import__127.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:15:00+1100", data: true }) ); const entity = new import__127.Entity({ availability: new import__127.TimeIntervalCollection([ import__127.TimeInterval.fromIso8601({ iso8601: "2018-02-14T04:00:00+1100/2018-02-14T04:30:00+1100" }) ]), position: new import__127.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, extrudedHeight: 20, outline: true, show } }); const batch = new import__127.StaticOutlineGeometryBatch( scene2.primitives, scene2, false, import__127.ShadowMode.DISABLED ); const updater = new import__127.EllipseGeometryUpdater(entity, scene2); batch.add(validTime, updater); return pollToPromise_default(function() { scene2.initializeFrame(); const isUpdated = batch.update(validTime); scene2.render(validTime); return isUpdated; }).then(function() { expect(scene2.primitives.length).toEqual(1); let primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.show).toEqual([1]); batch.update(outOfRangeTime); scene2.render(outOfRangeTime); primitive = scene2.primitives.get(0); attributes = primitive.getGeometryInstanceAttributes(entity); expect(attributes.show).toEqual([0]); batch.removeAllPrimitives(); }); }); it("shows only one primitive while rebuilding primitive", function() { const batch = new import__127.StaticOutlineGeometryBatch( scene2.primitives, scene2, false, import__127.ShadowMode.DISABLED ); function buildEntity() { return new import__127.Entity({ position: new import__127.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, height: 0, outline: true, outlineColor: import__127.Color.RED.withAlpha(0.5) } }); } function renderScene() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; } const entity1 = buildEntity(); const entity2 = buildEntity(); const updater1 = new import__127.EllipseGeometryUpdater(entity1, scene2); const updater2 = new import__127.EllipseGeometryUpdater(entity2, scene2); batch.add(time2, updater1); return pollToPromise_default(renderScene).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); expect(primitive.show).toBeTruthy(); }).then(function() { batch.add(time2, updater2); }).then(function() { return pollToPromise_default(function() { renderScene(); return scene2.primitives.length === 2; }); }).then(function() { let showCount = 0; expect(scene2.primitives.length).toEqual(2); showCount += !!scene2.primitives.get(0).show; showCount += !!scene2.primitives.get(1).show; expect(showCount).toEqual(1); }).then(function() { return pollToPromise_default(renderScene); }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); expect(primitive.show).toBeTruthy(); batch.removeAllPrimitives(); }); }); it("has correct show attribute after rebuilding primitive", function() { const batch = new import__127.StaticOutlineGeometryBatch( scene2.primitives, scene2, false, import__127.ShadowMode.DISABLED ); function buildEntity() { return new import__127.Entity({ position: new import__127.Cartesian3(1234, 5678, 9101112), ellipse: { semiMajorAxis: 2, semiMinorAxis: 1, height: 0, outline: true, outlineColor: import__127.Color.RED.withAlpha(0.5) } }); } function renderScene() { scene2.initializeFrame(); const isUpdated = batch.update(time2); scene2.render(time2); return isUpdated; } const entity1 = buildEntity(); const updater1 = new import__127.EllipseGeometryUpdater(entity1, scene2); batch.add(time2, updater1); const entity2 = buildEntity(); const updater2 = new import__127.EllipseGeometryUpdater(entity2, scene2); return pollToPromise_default(renderScene).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([1]); entity1.show = false; updater1._onEntityPropertyChanged(entity1, "isShowing"); return pollToPromise_default(renderScene); }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); const attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([0]); batch.add(time2, updater2); return pollToPromise_default(renderScene); }).then(function() { expect(scene2.primitives.length).toEqual(1); const primitive = scene2.primitives.get(0); let attributes = primitive.getGeometryInstanceAttributes(entity1); expect(attributes.show).toEqual([0]); attributes = primitive.getGeometryInstanceAttributes(entity2); expect(attributes.show).toEqual([1]); batch.removeAllPrimitives(); }); }); }); // packages/engine/Specs/DataSources/StripeMaterialPropertySpec.js var import__129 = __toESM(require_Cesium(), 1); describe("DataSources/StripeMaterialProperty", function() { it("constructor provides the expected defaults", function() { const property = new import__129.StripeMaterialProperty(); expect(property.getType()).toEqual("Stripe"); expect(property.isConstant).toBe(true); expect(property.orientation).toBeUndefined(); expect(property.evenColor).toBeUndefined(); expect(property.oddColor).toBeUndefined(); expect(property.offset).toBeUndefined(); expect(property.repeat).toBeUndefined(); const result = property.getValue(); expect(result.horizontal).toEqual(true); expect(result.evenColor).toEqual(import__129.Color.WHITE); expect(result.oddColor).toEqual(import__129.Color.BLACK); expect(result.offset).toEqual(0); expect(result.repeat).toEqual(1); }); it("constructor sets options and allows raw assignment", function() { const options = { orientation: import__129.StripeOrientation.VERTICAL, evenColor: import__129.Color.RED, oddColor: import__129.Color.BLUE, offset: 1, repeat: 2 }; const property = new import__129.StripeMaterialProperty(options); expect(property.orientation).toBeInstanceOf(import__129.ConstantProperty); expect(property.evenColor).toBeInstanceOf(import__129.ConstantProperty); expect(property.oddColor).toBeInstanceOf(import__129.ConstantProperty); expect(property.offset).toBeInstanceOf(import__129.ConstantProperty); expect(property.repeat).toBeInstanceOf(import__129.ConstantProperty); expect(property.orientation.getValue()).toEqual(options.orientation); expect(property.evenColor.getValue()).toEqual(options.evenColor); expect(property.oddColor.getValue()).toEqual(options.oddColor); expect(property.offset.getValue()).toEqual(options.offset); expect(property.repeat.getValue()).toEqual(options.repeat); }); it("works with constant values", function() { const property = new import__129.StripeMaterialProperty(); property.orientation = new import__129.ConstantProperty(import__129.StripeOrientation.VERTICAL); property.evenColor = new import__129.ConstantProperty(import__129.Color.RED); property.oddColor = new import__129.ConstantProperty(import__129.Color.BLUE); property.offset = new import__129.ConstantProperty(10); property.repeat = new import__129.ConstantProperty(20); const result = property.getValue(import__129.JulianDate.now()); expect(result.horizontal).toEqual(false); expect(result.evenColor).toEqual(import__129.Color.RED); expect(result.oddColor).toEqual(import__129.Color.BLUE); expect(result.offset).toEqual(10); expect(result.repeat).toEqual(20); }); it("works with dynamic values", function() { const property = new import__129.StripeMaterialProperty(); property.orientation = new import__129.TimeIntervalCollectionProperty(); property.evenColor = new import__129.TimeIntervalCollectionProperty(); property.oddColor = new import__129.TimeIntervalCollectionProperty(); property.offset = new import__129.TimeIntervalCollectionProperty(); property.repeat = new import__129.TimeIntervalCollectionProperty(); const start = new import__129.JulianDate(1, 0); const stop = new import__129.JulianDate(2, 0); property.orientation.intervals.addInterval( new import__129.TimeInterval({ start, stop, data: false }) ); property.evenColor.intervals.addInterval( new import__129.TimeInterval({ start, stop, data: import__129.Color.RED }) ); property.oddColor.intervals.addInterval( new import__129.TimeInterval({ start, stop, data: import__129.Color.BLUE }) ); property.offset.intervals.addInterval( new import__129.TimeInterval({ start, stop, data: 10 }) ); property.repeat.intervals.addInterval( new import__129.TimeInterval({ start, stop, data: 20 }) ); expect(property.isConstant).toBe(false); const result = property.getValue(start); expect(result.horizontal).toEqual(false); expect(result.evenColor).toEqual(import__129.Color.RED); expect(result.oddColor).toEqual(import__129.Color.BLUE); expect(result.offset).toEqual(10); expect(result.repeat).toEqual(20); }); it("works with a result parameter", function() { const property = new import__129.StripeMaterialProperty(); property.orientation = new import__129.ConstantProperty(import__129.StripeOrientation.VERTICAL); property.evenColor = new import__129.ConstantProperty(import__129.Color.RED); property.oddColor = new import__129.ConstantProperty(import__129.Color.BLUE); property.offset = new import__129.ConstantProperty(10); property.repeat = new import__129.ConstantProperty(20); const result = { horizontal: true, evenColor: import__129.Color.YELLOW.clone(), oddColor: import__129.Color.YELLOW.clone(), offset: 3, repeat: 4 }; const returnedResult = property.getValue(import__129.JulianDate.now(), result); expect(returnedResult).toBe(result); expect(result.horizontal).toEqual(false); expect(result.evenColor).toEqual(import__129.Color.RED); expect(result.oddColor).toEqual(import__129.Color.BLUE); expect(result.offset).toEqual(10); expect(result.repeat).toEqual(20); }); it("equals works", function() { const left = new import__129.StripeMaterialProperty(); left.orientation = new import__129.ConstantProperty(import__129.StripeOrientation.VERTICAL); left.evenColor = new import__129.ConstantProperty(import__129.Color.RED); left.oddColor = new import__129.ConstantProperty(import__129.Color.BLUE); left.offset = new import__129.ConstantProperty(10); left.repeat = new import__129.ConstantProperty(20); const right = new import__129.StripeMaterialProperty(); right.orientation = new import__129.ConstantProperty(import__129.StripeOrientation.VERTICAL); right.evenColor = new import__129.ConstantProperty(import__129.Color.RED); right.oddColor = new import__129.ConstantProperty(import__129.Color.BLUE); right.offset = new import__129.ConstantProperty(10); right.repeat = new import__129.ConstantProperty(20); expect(left.equals(right)).toEqual(true); right.orientation = new import__129.ConstantProperty(import__129.StripeOrientation.HORIZONTAL); expect(left.equals(right)).toEqual(false); right.orientation = new import__129.ConstantProperty(import__129.StripeOrientation.VERTICAL); right.evenColor = new import__129.ConstantProperty(import__129.Color.BLACK); expect(left.equals(right)).toEqual(false); right.evenColor = new import__129.ConstantProperty(import__129.Color.RED); right.oddColor = new import__129.ConstantProperty(import__129.Color.BLACK); expect(left.equals(right)).toEqual(false); right.oddColor = new import__129.ConstantProperty(import__129.Color.BLUE); right.offset = new import__129.ConstantProperty(1); expect(left.equals(right)).toEqual(false); right.offset = new import__129.ConstantProperty(10); right.repeat = new import__129.ConstantProperty(2); expect(left.equals(right)).toEqual(false); right.repeat = new import__129.ConstantProperty(20); expect(left.equals(right)).toEqual(true); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__129.StripeMaterialProperty(); testDefinitionChanged_default(property, "orientation", false, true); testDefinitionChanged_default(property, "evenColor", import__129.Color.RED, import__129.Color.BLUE); testDefinitionChanged_default(property, "oddColor", import__129.Color.RED, import__129.Color.BLUE); testDefinitionChanged_default(property, "offset", 2, 5); testDefinitionChanged_default(property, "repeat", 3, 4); }); }); // packages/engine/Specs/DataSources/TerrainOffsetPropertySpec.js var import__130 = __toESM(require_Cesium(), 1); describe("DataSources/TerrainOffsetProperty", function() { let scene2; const time2 = import__130.JulianDate.now(); beforeAll(function() { scene2 = createScene_default(); scene2.globe = createGlobe_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); it("can construct and destroy", function() { const position = new import__130.CallbackProperty(jasmine.createSpy(), false); const height = new import__130.ConstantProperty(30); const extrudedHeight = new import__130.ConstantProperty(0); const property = new import__130.TerrainOffsetProperty( scene2, position, height, extrudedHeight ); expect(property.isConstant).toBe(false); expect(property.getValue(time2)).toEqual(import__130.Cartesian3.ZERO); property.destroy(); expect(property.isDestroyed()).toBe(true); }); it("throws without scene", function() { const position = new import__130.CallbackProperty(jasmine.createSpy(), false); const height = new import__130.ConstantProperty(30); const extrudedHeight = new import__130.ConstantProperty(0); expect(function() { return new import__130.TerrainOffsetProperty( void 0, position, height, extrudedHeight ); }).toThrowDeveloperError(); }); it("throws without position", function() { const height = new import__130.ConstantProperty(30); const extrudedHeight = new import__130.ConstantProperty(0); expect(function() { return new import__130.TerrainOffsetProperty( scene2, void 0, height, extrudedHeight ); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/TimeIntervalCollectionPositionPropertySpec.js var import__131 = __toESM(require_Cesium(), 1); describe("DataSources/TimeIntervalCollectionPositionProperty", function() { it("default constructor has expected values", function() { const property = new import__131.TimeIntervalCollectionPositionProperty(); expect(property.intervals).toBeInstanceOf(import__131.TimeIntervalCollection); expect(property.getValue(import__131.JulianDate.now())).toBeUndefined(); expect(property.referenceFrame).toBe(import__131.ReferenceFrame.FIXED); }); it("getValue works without a result parameter", function() { const interval1 = new import__131.TimeInterval({ start: new import__131.JulianDate(10, 0), stop: new import__131.JulianDate(12, 0), data: new import__131.Cartesian3(1, 2, 3) }); const interval2 = new import__131.TimeInterval({ start: new import__131.JulianDate(12, 0), stop: new import__131.JulianDate(14, 0), isStartIncluded: false, data: new import__131.Cartesian3(4, 5, 6) }); const property = new import__131.TimeIntervalCollectionPositionProperty(); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); const result1 = property.getValue(interval1.start); expect(result1).not.toBe(interval1.data); expect(result1).toEqual(interval1.data); const result2 = property.getValue(interval2.stop); expect(result2).not.toBe(interval2.data); expect(result2).toEqual(interval2.data); }); it("getValue works with a result parameter", function() { const interval1 = new import__131.TimeInterval({ start: new import__131.JulianDate(10, 0), stop: new import__131.JulianDate(12, 0), data: new import__131.Cartesian3(1, 2, 3) }); const interval2 = new import__131.TimeInterval({ start: new import__131.JulianDate(12, 0), stop: new import__131.JulianDate(14, 0), isStartIncluded: false, data: new import__131.Cartesian3(4, 5, 6) }); const property = new import__131.TimeIntervalCollectionPositionProperty(); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); const expected = new import__131.Cartesian3(); const result1 = property.getValue(interval1.start, expected); expect(result1).toBe(expected); expect(result1).toEqual(interval1.data); const result2 = property.getValue(interval2.stop, expected); expect(result2).toBe(expected); expect(result2).toEqual(interval2.data); }); it("getValue returns in fixed frame", function() { const interval1 = new import__131.TimeInterval({ start: new import__131.JulianDate(10, 0), stop: new import__131.JulianDate(12, 0), data: new import__131.Cartesian3(1, 2, 3) }); const property = new import__131.TimeIntervalCollectionPositionProperty( import__131.ReferenceFrame.INERTIAL ); property.intervals.addInterval(interval1); const valueInertial = new import__131.Cartesian3(1, 2, 3); const valueFixed = import__131.PositionProperty.convertToReferenceFrame( interval1.start, valueInertial, import__131.ReferenceFrame.INERTIAL, import__131.ReferenceFrame.FIXED ); const result = property.getValue(interval1.start); expect(result).toEqual(valueFixed); }); it("getValueInReferenceFrame works with a result parameter", function() { const interval1 = new import__131.TimeInterval({ start: new import__131.JulianDate(10, 0), stop: new import__131.JulianDate(12, 0), data: new import__131.Cartesian3(1, 2, 3) }); const interval2 = new import__131.TimeInterval({ start: new import__131.JulianDate(12, 0), stop: new import__131.JulianDate(14, 0), isStartIncluded: false, data: new import__131.Cartesian3(4, 5, 6) }); const property = new import__131.TimeIntervalCollectionPositionProperty( import__131.ReferenceFrame.FIXED ); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); const valueInertial = import__131.PositionProperty.convertToReferenceFrame( interval1.start, interval1.data, import__131.ReferenceFrame.FIXED, import__131.ReferenceFrame.INERTIAL ); const expected = new import__131.Cartesian3(); const result1 = property.getValueInReferenceFrame( interval1.start, import__131.ReferenceFrame.INERTIAL, expected ); expect(result1).toBe(expected); expect(result1).toEqual(valueInertial); const result2 = property.getValueInReferenceFrame( interval2.stop, import__131.ReferenceFrame.FIXED, expected ); expect(result2).toBe(expected); expect(result2).toEqual(interval2.data); }); it("getValueInReferenceFrame works without a result parameter", function() { const interval1 = new import__131.TimeInterval({ start: new import__131.JulianDate(10, 0), stop: new import__131.JulianDate(12, 0), data: new import__131.Cartesian3(1, 2, 3) }); const interval2 = new import__131.TimeInterval({ start: new import__131.JulianDate(12, 0), stop: new import__131.JulianDate(14, 0), isStartIncluded: false, data: new import__131.Cartesian3(4, 5, 6) }); const property = new import__131.TimeIntervalCollectionPositionProperty( import__131.ReferenceFrame.FIXED ); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); const valueInertial = import__131.PositionProperty.convertToReferenceFrame( interval1.start, interval1.data, import__131.ReferenceFrame.FIXED, import__131.ReferenceFrame.INERTIAL ); const result1 = property.getValueInReferenceFrame( interval1.start, import__131.ReferenceFrame.INERTIAL ); expect(result1).toEqual(valueInertial); const result2 = property.getValueInReferenceFrame( interval2.stop, import__131.ReferenceFrame.FIXED ); expect(result2).toEqual(interval2.data); }); it("returns undefined for valid interval without data", function() { const property = new import__131.TimeIntervalCollectionPositionProperty(); const interval = new import__131.TimeInterval({ start: new import__131.JulianDate(10, 0), stop: new import__131.JulianDate(12, 0) }); property.intervals.addInterval(interval); const result = property.getValue(interval.start); expect(result).toBeUndefined(); }); it("throws with no time parameter", function() { const property = new import__131.TimeIntervalCollectionPositionProperty(); expect(function() { property.getValue(void 0); }).toThrowDeveloperError(); }); it("throws with no reference frame parameter", function() { const property = new import__131.TimeIntervalCollectionPositionProperty(); const time2 = import__131.JulianDate.now(); expect(function() { property.getValueInReferenceFrame(time2, void 0); }).toThrowDeveloperError(); }); it("equals works for differing referenceFrames", function() { const left = new import__131.TimeIntervalCollectionPositionProperty( import__131.ReferenceFrame.FIXED ); let right = new import__131.TimeIntervalCollectionPositionProperty( import__131.ReferenceFrame.INERTIAL ); expect(left.equals(right)).toEqual(false); right = new import__131.TimeIntervalCollectionPositionProperty(import__131.ReferenceFrame.FIXED); expect(left.equals(right)).toEqual(true); }); it("equals works for differing intervals", function() { const interval1 = new import__131.TimeInterval({ start: new import__131.JulianDate(10, 0), stop: new import__131.JulianDate(12, 0), data: new import__131.Cartesian3(1, 2, 3) }); const interval2 = new import__131.TimeInterval({ start: new import__131.JulianDate(12, 0), stop: new import__131.JulianDate(14, 0), isStartIncluded: false, data: new import__131.Cartesian3(4, 5, 6) }); const left = new import__131.TimeIntervalCollectionPositionProperty( import__131.ReferenceFrame.FIXED ); left.intervals.addInterval(interval1); left.intervals.addInterval(interval2); const right = new import__131.TimeIntervalCollectionPositionProperty( import__131.ReferenceFrame.FIXED ); right.intervals.addInterval(interval1); expect(left.equals(right)).toEqual(false); right.intervals.addInterval(interval2); expect(left.equals(right)).toEqual(true); }); it("raises definitionChanged event", function() { const interval = new import__131.TimeInterval({ start: new import__131.JulianDate(10, 0), stop: new import__131.JulianDate(12, 0), data: new import__131.Cartesian3(1, 2, 3) }); const property = new import__131.TimeIntervalCollectionPositionProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.intervals.addInterval(interval); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.intervals.removeInterval(interval); expect(listener).toHaveBeenCalledWith(property); property.intervals.addInterval(interval); listener.calls.reset(); property.intervals.removeAll(); expect(listener).toHaveBeenCalledWith(property); }); }); // packages/engine/Specs/DataSources/TimeIntervalCollectionPropertySpec.js var import__132 = __toESM(require_Cesium(), 1); describe("DataSources/TimeIntervalCollectionProperty", function() { it("default constructor has expected values", function() { const property = new import__132.TimeIntervalCollectionProperty(); expect(property.intervals).toBeInstanceOf(import__132.TimeIntervalCollection); expect(property.getValue(import__132.JulianDate.now())).toBeUndefined(); expect(property.isConstant).toBe(true); }); it("works with basic types", function() { const interval1 = new import__132.TimeInterval({ start: new import__132.JulianDate(10, 0), stop: new import__132.JulianDate(12, 0), data: 5 }); const interval2 = new import__132.TimeInterval({ start: new import__132.JulianDate(12, 0), stop: new import__132.JulianDate(14, 0), isStartIncluded: false, data: 6 }); const property = new import__132.TimeIntervalCollectionProperty(); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); expect(property.getValue(interval1.start)).toBe(interval1.data); expect(property.getValue(interval2.stop)).toBe(interval2.data); expect(property.isConstant).toBe(false); }); it("works with clonable objects", function() { const interval1 = new import__132.TimeInterval({ start: new import__132.JulianDate(10, 0), stop: new import__132.JulianDate(12, 0), data: new import__132.Cartesian3(1, 2, 3) }); const interval2 = new import__132.TimeInterval({ start: new import__132.JulianDate(12, 0), stop: new import__132.JulianDate(14, 0), isStartIncluded: false, data: new import__132.Cartesian3(4, 5, 6) }); const property = new import__132.TimeIntervalCollectionProperty(); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); const result1 = property.getValue(interval1.start); expect(result1).not.toBe(interval1.data); expect(result1).toEqual(interval1.data); const result2 = property.getValue(interval2.stop); expect(result2).not.toBe(interval2.data); expect(result2).toEqual(interval2.data); }); it("works with a result parameter", function() { const interval1 = new import__132.TimeInterval({ start: new import__132.JulianDate(10, 0), stop: new import__132.JulianDate(12, 0), data: new import__132.Cartesian3(1, 2, 3) }); const interval2 = new import__132.TimeInterval({ start: new import__132.JulianDate(12, 0), stop: new import__132.JulianDate(14, 0), isStartIncluded: false, data: new import__132.Cartesian3(4, 5, 6) }); const property = new import__132.TimeIntervalCollectionProperty(); property.intervals.addInterval(interval1); property.intervals.addInterval(interval2); const expected = new import__132.Cartesian3(); const result1 = property.getValue(interval1.start, expected); expect(result1).toBe(expected); expect(result1).toEqual(interval1.data); const result2 = property.getValue(interval2.stop, expected); expect(result2).toBe(expected); expect(result2).toEqual(interval2.data); }); it("throws with no time parameter", function() { const property = new import__132.TimeIntervalCollectionProperty(); expect(function() { property.getValue(void 0); }).toThrowDeveloperError(); }); it("equals works for differing basic type intervals", function() { const interval1 = new import__132.TimeInterval({ start: new import__132.JulianDate(10, 0), stop: new import__132.JulianDate(12, 0), data: 5 }); const interval2 = new import__132.TimeInterval({ start: new import__132.JulianDate(12, 0), stop: new import__132.JulianDate(14, 0), isStartIncluded: false, data: 6 }); const left = new import__132.TimeIntervalCollectionProperty(); left.intervals.addInterval(interval1); left.intervals.addInterval(interval2); const right = new import__132.TimeIntervalCollectionProperty(); right.intervals.addInterval(interval1); expect(left.equals(right)).toEqual(false); right.intervals.addInterval(interval2); expect(left.equals(right)).toEqual(true); }); it("equals works for differing complex type intervals", function() { const interval1 = new import__132.TimeInterval({ start: new import__132.JulianDate(10, 0), stop: new import__132.JulianDate(12, 0), data: new import__132.Cartesian3(1, 2, 3) }); const interval2 = new import__132.TimeInterval({ start: new import__132.JulianDate(12, 0), stop: new import__132.JulianDate(14, 0), isStartIncluded: false, data: new import__132.Cartesian3(4, 5, 6) }); const left = new import__132.TimeIntervalCollectionProperty(); left.intervals.addInterval(interval1); left.intervals.addInterval(interval2); const right = new import__132.TimeIntervalCollectionProperty(); right.intervals.addInterval(interval1); expect(left.equals(right)).toEqual(false); right.intervals.addInterval(interval2); expect(left.equals(right)).toEqual(true); }); it("raises definitionChanged event", function() { const interval = new import__132.TimeInterval({ start: new import__132.JulianDate(10, 0), stop: new import__132.JulianDate(12, 0), data: new import__132.Cartesian3(1, 2, 3) }); const property = new import__132.TimeIntervalCollectionProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.intervals.addInterval(interval); expect(listener).toHaveBeenCalledWith(property); listener.calls.reset(); property.intervals.removeInterval(interval); expect(listener).toHaveBeenCalledWith(property); property.intervals.addInterval(interval); listener.calls.reset(); property.intervals.removeAll(); expect(listener).toHaveBeenCalledWith(property); }); }); // packages/engine/Specs/DataSources/VelocityOrientationPropertySpec.js var import__133 = __toESM(require_Cesium(), 1); describe("DataSources/VelocityOrientationProperty", function() { const time2 = import__133.JulianDate.now(); it("can default construct", function() { const property = new import__133.VelocityOrientationProperty(); expect(property.isConstant).toBe(true); expect(property.definitionChanged).toBeInstanceOf(import__133.Event); expect(property.position).toBeUndefined(); expect(property.ellipsoid).toBe(import__133.Ellipsoid.WGS84); expect(property.getValue(time2)).toBeUndefined(); }); it("can construct with arguments", function() { const position = new import__133.SampledPositionProperty(); const property = new import__133.VelocityOrientationProperty( position, import__133.Ellipsoid.UNIT_SPHERE ); expect(property.isConstant).toBe(true); expect(property.definitionChanged).toBeInstanceOf(import__133.Event); expect(property.position).toBe(position); expect(property.ellipsoid).toBe(import__133.Ellipsoid.UNIT_SPHERE); expect(property.getValue(time2)).toBeUndefined(); }); it("setting position raises definitionChanged event", function() { const property = new import__133.VelocityOrientationProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); const position = new import__133.SampledPositionProperty(); property.position = position; expect(listener).toHaveBeenCalledWith(property); }); it("subscribes/unsubscribes to position definitionChanged and propagates up", function() { const position = new import__133.SampledPositionProperty(); const property = new import__133.VelocityOrientationProperty(position); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); position.definitionChanged.raiseEvent(position); expect(listener).toHaveBeenCalledWith(property); property.position = void 0; listener.calls.reset(); position.definitionChanged.raiseEvent(position); expect(listener.calls.count()).toBe(0); }); it("setting position does not raise definitionChanged event for same data", function() { const position = new import__133.SampledPositionProperty(); const property = new import__133.VelocityOrientationProperty(position); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.position = position; expect(listener.calls.count()).toBe(0); }); it("setting ellipsoid raises definitionChanged event", function() { const property = new import__133.VelocityOrientationProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.ellipsoid = import__133.Ellipsoid.UNIT_SPHERE; expect(listener).toHaveBeenCalledWith(property); }); it("setting ellipsoid does not raise definitionChanged event for same data", function() { const property = new import__133.VelocityOrientationProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.ellipsoid = import__133.Ellipsoid.WGS84; expect(listener.calls.count()).toBe(0); }); it("works without result parameter", function() { const times = [new import__133.JulianDate(0, 0), new import__133.JulianDate(0, 1 / 60)]; const values = [ import__133.Cartesian3.fromDegrees(0, 0, 0), import__133.Cartesian3.fromDegrees(1, 0, 0) ]; const velocity = import__133.Cartesian3.subtract( values[1], values[0], new import__133.Cartesian3() ); import__133.Cartesian3.normalize(velocity, velocity); const position = new import__133.SampledPositionProperty(); position.addSamples(times, values); const property = new import__133.VelocityOrientationProperty(position); let matrix = import__133.Transforms.rotationMatrixFromPositionVelocity( position.getValue(times[0]), velocity ); expect(property.getValue(times[0])).toEqual( import__133.Quaternion.fromRotationMatrix(matrix) ); matrix = import__133.Transforms.rotationMatrixFromPositionVelocity( position.getValue(times[0]), velocity ); expect(property.getValue(times[1])).toEqual( import__133.Quaternion.fromRotationMatrix(matrix) ); }); it("works with result parameter", function() { const times = [new import__133.JulianDate(0, 0), new import__133.JulianDate(0, 1 / 60)]; const values = [ import__133.Cartesian3.fromDegrees(0, 0, 0), import__133.Cartesian3.fromDegrees(1, 0, 0) ]; const velocity = import__133.Cartesian3.subtract( values[1], values[0], new import__133.Cartesian3() ); import__133.Cartesian3.normalize(velocity, velocity); const position = new import__133.SampledPositionProperty(); position.addSamples(times, values); const property = new import__133.VelocityOrientationProperty(position); const expected = new import__133.Cartesian3(); const result = property.getValue(times[0], expected); expect(result).toBe(expected); const matrix = import__133.Transforms.rotationMatrixFromPositionVelocity( position.getValue(times[0]), velocity ); expect(expected).toEqual(import__133.Quaternion.fromRotationMatrix(matrix)); }); it("is undefined at zero velocity", function() { const position = new import__133.CallbackProperty(function() { return import__133.Cartesian3.fromDegrees(0, 0, 0); }, false); const property = new import__133.VelocityOrientationProperty(position); expect(property.getValue(new import__133.JulianDate())).toBeUndefined(); }); it("returns undefined when position value is undefined", function() { const position = new import__133.SampledPositionProperty(); position.addSample(new import__133.JulianDate(1, 0), import__133.Cartesian3.fromDegrees(0, 0, 0)); position.forwardExtrapolationType = import__133.ExtrapolationType.NONE; position.backwardExtrapolationType = import__133.ExtrapolationType.NONE; const property = new import__133.VelocityOrientationProperty(position); const result = property.getValue(new import__133.JulianDate()); expect(result).toBeUndefined(); }); it("returns undefined when position has exactly one value", function() { const position = new import__133.SampledPositionProperty(); position.addSample(new import__133.JulianDate(1, 0), import__133.Cartesian3.fromDegrees(0, 0, 0)); position.forwardExtrapolationType = import__133.ExtrapolationType.NONE; position.backwardExtrapolationType = import__133.ExtrapolationType.NONE; const property = new import__133.VelocityOrientationProperty(position); const result = property.getValue(new import__133.JulianDate(1, 0)); expect(result).toBeUndefined(); }); it("equals works", function() { const position = new import__133.SampledPositionProperty(); const left = new import__133.VelocityOrientationProperty(); const right = new import__133.VelocityOrientationProperty(); expect(left.equals(right)).toBe(true); left.position = position; expect(left.equals(right)).toBe(false); right.position = position; expect(left.equals(right)).toBe(true); left.ellipsoid = import__133.Ellipsoid.UNIT_SPHERE; expect(left.equals(right)).toBe(false); right.ellipsoid = import__133.Ellipsoid.UNIT_SPHERE; expect(left.equals(right)).toBe(true); }); it("getValue throws without time", function() { const property = new import__133.VelocityOrientationProperty(); expect(function() { property.getValue(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/VelocityVectorPropertySpec.js var import__134 = __toESM(require_Cesium(), 1); var import__135 = __toESM(require_Cesium(), 1); describe("DataSources/VelocityVectorProperty", function() { const time2 = import__134.JulianDate.now(); it("can default construct", function() { const property = new import__134.VelocityVectorProperty(); expect(property.isConstant).toBe(true); expect(property.definitionChanged).toBeInstanceOf(import__134.Event); expect(property.position).toBeUndefined(); expect(property.getValue(time2)).toBeUndefined(); expect(property.normalize).toBe(true); }); it("can construct with arguments", function() { const position = new import__134.SampledPositionProperty(); const property = new import__134.VelocityVectorProperty(position, false); expect(property.isConstant).toBe(true); expect(property.definitionChanged).toBeInstanceOf(import__134.Event); expect(property.position).toBe(position); expect(property.getValue(time2)).toEqual(import__134.Cartesian3.ZERO); expect(property.normalize).toBe(false); }); it("raises definitionChanged event when position is set", function() { const property = new import__134.VelocityVectorProperty(); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); const position = new import__134.SampledPositionProperty(); property.position = position; expect(listener).toHaveBeenCalledWith(property); }); it("raises definitionChanged event when normalize changes", function() { const property = new import__134.VelocityVectorProperty(new import__134.SampledPositionProperty()); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.normalize = true; expect(listener.calls.count()).toBe(0); property.normalize = false; expect(listener).toHaveBeenCalledWith(property); }); it("subscribes and unsubscribes to position definitionChanged and propagates up", function() { const position = new import__134.SampledPositionProperty(); const property = new import__134.VelocityVectorProperty(position); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); position.definitionChanged.raiseEvent(position); expect(listener).toHaveBeenCalledWith(property); property.position = void 0; listener.calls.reset(); position.definitionChanged.raiseEvent(position); expect(listener.calls.count()).toBe(0); }); it("does not raise definitionChanged event when position is set to the same instance", function() { const position = new import__134.SampledPositionProperty(); const property = new import__134.VelocityVectorProperty(position); const listener = jasmine.createSpy("listener"); property.definitionChanged.addEventListener(listener); property.position = position; expect(listener.calls.count()).toBe(0); }); it("produces correct normalized value when called without result parameter", function() { const times = [new import__134.JulianDate(0, 0), new import__134.JulianDate(0, 1 / 60)]; const values = [ new import__134.Cartesian3(0, 0, 0), new import__134.Cartesian3(20, 0, 0) ]; const position = new import__134.SampledPositionProperty(); position.addSamples(times, values); const property = new import__134.VelocityVectorProperty(position); const expectedVelocityDirection = new import__134.Cartesian3(1, 0, 0); expect(property.getValue(times[0])).toEqual(expectedVelocityDirection); expect(property.getValue(times[1])).toEqual(expectedVelocityDirection); }); it("produces correct normalized value when called with result parameter", function() { const times = [new import__134.JulianDate(0, 0), new import__134.JulianDate(0, 1 / 60)]; const values = [ new import__134.Cartesian3(0, 0, 0), new import__134.Cartesian3(20, 0, 0) ]; const position = new import__134.SampledPositionProperty(); position.addSamples(times, values); const property = new import__134.VelocityVectorProperty(position); const expectedVelocityDirection = new import__134.Cartesian3(1, 0, 0); const expected = new import__134.Cartesian3(); const result = property.getValue(times[0], expected); expect(result).toBe(expected); expect(result).toEqual(expectedVelocityDirection); }); it("produces correct unnormalized value when called without result parameter", function() { const times = [new import__134.JulianDate(0, 0), new import__134.JulianDate(0, 1)]; const values = [ new import__134.Cartesian3(0, 0, 0), new import__134.Cartesian3(20, 0, 0) ]; const position = new import__134.SampledPositionProperty(); position.addSamples(times, values); const property = new import__134.VelocityVectorProperty(position, false); const expectedVelocity = new import__134.Cartesian3(20, 0, 0); expect(property.getValue(times[0])).toEqualEpsilon( expectedVelocity, import__135.Math.EPSILON13 ); expect(property.getValue(times[1])).toEqualEpsilon( expectedVelocity, import__135.Math.EPSILON13 ); }); it("produces correct unnormalized value when called with result parameter", function() { const times = [new import__134.JulianDate(0, 0), new import__134.JulianDate(0, 1)]; const values = [ new import__134.Cartesian3(0, 0, 0), new import__134.Cartesian3(20, 0, 0) ]; const position = new import__134.SampledPositionProperty(); position.addSamples(times, values); const property = new import__134.VelocityVectorProperty(position, false); const expectedVelocity = new import__134.Cartesian3(20, 0, 0); const expected = new import__134.Cartesian3(); const result = property.getValue(times[0], expected); expect(result).toBe(expected); expect(result).toEqualEpsilon(expectedVelocity, import__135.Math.EPSILON13); }); it("produces normalized value of undefined with constant position", function() { const position = new import__134.ConstantPositionProperty( new import__134.Cartesian3(1, 2, 3) ); const property = new import__134.VelocityVectorProperty(position); expect(property.getValue(new import__134.JulianDate())).toBeUndefined(); }); it("produces unnormalized value of zero with constant position", function() { const position = new import__134.ConstantPositionProperty( new import__134.Cartesian3(1, 2, 3) ); const property = new import__134.VelocityVectorProperty(position, false); expect(property.getValue(new import__134.JulianDate())).toEqual(import__134.Cartesian3.ZERO); }); it("produces normalized value of undefined at zero velocity", function() { const position = new import__134.CallbackProperty(function() { return new import__134.Cartesian3(0, 0, 0); }, false); const property = new import__134.VelocityVectorProperty(position); expect(property.getValue(new import__134.JulianDate())).toBeUndefined(); }); it("produces unnormalized value of zero at zero velocity", function() { const position = new import__134.CallbackProperty(function() { return new import__134.Cartesian3(0, 0, 0); }, false); const property = new import__134.VelocityVectorProperty(position, false); expect(property.getValue(new import__134.JulianDate())).toEqual(import__134.Cartesian3.ZERO); }); it("returns undefined when position value is undefined", function() { const position = new import__134.SampledPositionProperty(); position.addSample(new import__134.JulianDate(1, 0), new import__134.Cartesian3(0, 0, 0)); position.forwardExtrapolationType = import__134.ExtrapolationType.NONE; position.backwardExtrapolationType = import__134.ExtrapolationType.NONE; const property = new import__134.VelocityVectorProperty(position); const result = property.getValue(new import__134.JulianDate()); expect(result).toBeUndefined(); }); it("returns undefined when position has exactly one value", function() { const position = new import__134.SampledPositionProperty(); position.addSample(new import__134.JulianDate(1, 0), new import__134.Cartesian3(0, 0, 0)); position.forwardExtrapolationType = import__134.ExtrapolationType.NONE; position.backwardExtrapolationType = import__134.ExtrapolationType.NONE; const property = new import__134.VelocityVectorProperty(position); const result = property.getValue(new import__134.JulianDate(1, 0)); expect(result).toBeUndefined(); }); it("equals works", function() { const position = new import__134.SampledPositionProperty(); const left = new import__134.VelocityVectorProperty(); const right = new import__134.VelocityVectorProperty(); expect(left.equals(right)).toBe(true); left.position = position; expect(left.equals(right)).toBe(false); right.position = position; expect(left.equals(right)).toBe(true); }); it("getValue throws without time", function() { const property = new import__134.VelocityVectorProperty(); expect(function() { property.getValue(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/WallGeometryUpdaterSpec.js var import__136 = __toESM(require_Cesium(), 1); describe( "DataSources/WallGeometryUpdater", function() { let time2; let time22; let scene2; beforeAll(function() { scene2 = createScene_default(); time2 = new import__136.JulianDate(0, 0); time22 = new import__136.JulianDate(10, 0); }); afterAll(function() { scene2.destroyForSpecs(); }); function createBasicWall() { const wall = new import__136.WallGraphics(); wall.positions = new import__136.ConstantProperty( import__136.Cartesian3.fromRadiansArrayHeights([0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1]) ); const entity = new import__136.Entity(); entity.wall = wall; return entity; } function createDynamicWall() { const entity = createBasicWall(); entity.wall.granularity = createDynamicProperty_default(1); return entity; } it("A time-varying positions causes geometry to be dynamic", function() { const entity = createBasicWall(); const updater = new import__136.WallGeometryUpdater(entity, scene2); const point1 = new import__136.SampledPositionProperty(); point1.addSample(time2, new import__136.Cartesian3()); const point2 = new import__136.SampledPositionProperty(); point2.addSample(time2, new import__136.Cartesian3()); const point3 = new import__136.SampledPositionProperty(); point3.addSample(time2, new import__136.Cartesian3()); entity.wall.positions = new import__136.PropertyArray(); entity.wall.positions.setValue([point1, point2, point3]); updater._onEntityPropertyChanged(entity, "wall"); expect(updater.isDynamic).toBe(true); }); it("A time-varying minimumHeights causes geometry to be dynamic", function() { const entity = createBasicWall(); const updater = new import__136.WallGeometryUpdater(entity, scene2); entity.wall.minimumHeights = new import__136.TimeIntervalCollectionProperty(); entity.wall.minimumHeights.intervals.addInterval( new import__136.TimeInterval({ start: time2, stop: time22, data: [] }) ); updater._onEntityPropertyChanged(entity, "wall"); expect(updater.isDynamic).toBe(true); }); it("A time-varying maximumHeights causes geometry to be dynamic", function() { const entity = createBasicWall(); const updater = new import__136.WallGeometryUpdater(entity, scene2); entity.wall.maximumHeights = new import__136.TimeIntervalCollectionProperty(); entity.wall.maximumHeights.intervals.addInterval( new import__136.TimeInterval({ start: time2, stop: time22, data: [] }) ); updater._onEntityPropertyChanged(entity, "wall"); expect(updater.isDynamic).toBe(true); }); it("A time-varying granularity causes geometry to be dynamic", function() { const entity = createBasicWall(); const updater = new import__136.WallGeometryUpdater(entity, scene2); entity.wall.granularity = new import__136.SampledProperty(Number); entity.wall.granularity.addSample(time2, 1); updater._onEntityPropertyChanged(entity, "wall"); expect(updater.isDynamic).toBe(true); }); it("Creates geometry with expected properties", function() { const options = { minimumHeights: [0, 1, 2, 3], maximumHeights: [4, 5, 6, 7], granularity: 0.97 }; const entity = createBasicWall(); const wall = entity.wall; wall.outline = true; wall.minimumHeights = new import__136.ConstantProperty(options.minimumHeights); wall.maximumHeights = new import__136.ConstantProperty(options.maximumHeights); wall.granularity = new import__136.ConstantProperty(options.granularity); const updater = new import__136.WallGeometryUpdater(entity, scene2); let instance; let geometry; instance = updater.createFillGeometryInstance(time2); geometry = instance.geometry; expect(geometry._granularity).toEqual(options.granularity); expect(geometry._minimumHeights).toEqual(options.minimumHeights); expect(geometry._maximumHeights).toEqual(options.maximumHeights); instance = updater.createOutlineGeometryInstance(time2); geometry = instance.geometry; expect(geometry._granularity).toEqual(options.granularity); expect(geometry._minimumHeights).toEqual(options.minimumHeights); expect(geometry._maximumHeights).toEqual(options.maximumHeights); }); it("dynamic updater sets properties", function() { const wall = new import__136.WallGraphics(); wall.positions = createDynamicProperty_default( import__136.Cartesian3.fromRadiansArray([0, 0, 1, 0, 1, 1, 0, 1]) ); wall.show = createDynamicProperty_default(true); wall.minimumHeights = createDynamicProperty_default([1, 2, 3, 4]); wall.maximumHeights = createDynamicProperty_default([2, 3, 4, 5]); wall.granularity = createDynamicProperty_default(1); wall.fill = createDynamicProperty_default(true); wall.outline = createDynamicProperty_default(true); wall.outlineColor = createDynamicProperty_default(import__136.Color.RED); const entity = new import__136.Entity(); entity.wall = wall; const updater = new import__136.WallGeometryUpdater(entity, scene2); const dynamicUpdater = updater.createDynamicUpdater( new import__136.PrimitiveCollection(), new import__136.PrimitiveCollection() ); dynamicUpdater.update(time2); const options = dynamicUpdater._options; expect(options.id).toEqual(entity); expect(options.positions).toEqual(wall.positions.getValue()); expect(options.minimumHeights).toEqual(wall.minimumHeights.getValue()); expect(options.maximumHeights).toEqual(wall.maximumHeights.getValue()); expect(options.granularity).toEqual(wall.granularity.getValue()); }); it("geometryChanged event is raised when expected", function() { const entity = createBasicWall(); const updater = new import__136.WallGeometryUpdater(entity, scene2); const listener = jasmine.createSpy("listener"); updater.geometryChanged.addEventListener(listener); entity.wall.positions = new import__136.ConstantProperty([]); updater._onEntityPropertyChanged(entity, "wall"); expect(listener.calls.count()).toEqual(1); entity.wall.granularity = new import__136.ConstantProperty(82); updater._onEntityPropertyChanged(entity, "wall"); expect(listener.calls.count()).toEqual(2); entity.availability = new import__136.TimeIntervalCollection(); updater._onEntityPropertyChanged(entity, "availability"); expect(listener.calls.count()).toEqual(3); entity.wall.positions = void 0; updater._onEntityPropertyChanged(entity, "wall"); expect(listener.calls.count()).toEqual(4); entity.wall.granularity = void 0; updater._onEntityPropertyChanged(entity, "wall"); entity.viewFrom = new import__136.ConstantProperty(import__136.Cartesian3.UNIT_X); updater._onEntityPropertyChanged(entity, "viewFrom"); expect(listener.calls.count()).toEqual(4); }); function getScene() { return scene2; } createGeometryUpdaterSpecs_default( import__136.WallGeometryUpdater, "wall", createBasicWall, getScene ); createDynamicGeometryUpdaterSpecs_default( import__136.WallGeometryUpdater, "wall", createDynamicWall, getScene ); }, "WebGL" ); // packages/engine/Specs/DataSources/WallGraphicsSpec.js var import__137 = __toESM(require_Cesium(), 1); describe("DataSources/WallGraphics", function() { it("creates expected instance from raw assignment and construction", function() { const options = { material: import__137.Color.BLUE, positions: [], show: true, granularity: 1, fill: false, outline: false, outlineColor: import__137.Color.RED, outlineWidth: 2, minimumHeights: [3, 4, 5], maximumHeights: [6, 7, 8], shadows: import__137.ShadowMode.DISABLED, distanceDisplayCondition: new import__137.DistanceDisplayCondition() }; const wall = new import__137.WallGraphics(options); expect(wall.material).toBeInstanceOf(import__137.ColorMaterialProperty); expect(wall.positions).toBeInstanceOf(import__137.ConstantProperty); expect(wall.show).toBeInstanceOf(import__137.ConstantProperty); expect(wall.granularity).toBeInstanceOf(import__137.ConstantProperty); expect(wall.granularity).toBeInstanceOf(import__137.ConstantProperty); expect(wall.fill).toBeInstanceOf(import__137.ConstantProperty); expect(wall.outline).toBeInstanceOf(import__137.ConstantProperty); expect(wall.outlineColor).toBeInstanceOf(import__137.ConstantProperty); expect(wall.outlineWidth).toBeInstanceOf(import__137.ConstantProperty); expect(wall.minimumHeights).toBeInstanceOf(import__137.ConstantProperty); expect(wall.maximumHeights).toBeInstanceOf(import__137.ConstantProperty); expect(wall.shadows).toBeInstanceOf(import__137.ConstantProperty); expect(wall.distanceDisplayCondition).toBeInstanceOf(import__137.ConstantProperty); expect(wall.material.color.getValue()).toEqual(options.material); expect(wall.positions.getValue()).toEqual(options.positions); expect(wall.show.getValue()).toEqual(options.show); expect(wall.granularity.getValue()).toEqual(options.granularity); expect(wall.granularity.getValue()).toEqual(options.granularity); expect(wall.fill.getValue()).toEqual(options.fill); expect(wall.outline.getValue()).toEqual(options.outline); expect(wall.outlineColor.getValue()).toEqual(options.outlineColor); expect(wall.outlineWidth.getValue()).toEqual(options.outlineWidth); expect(wall.minimumHeights.getValue()).toEqual(options.minimumHeights); expect(wall.maximumHeights.getValue()).toEqual(options.maximumHeights); expect(wall.shadows.getValue()).toEqual(options.shadows); expect(wall.distanceDisplayCondition.getValue()).toEqual( options.distanceDisplayCondition ); }); it("merge assigns unassigned properties", function() { const source = new import__137.WallGraphics(); source.material = new import__137.ColorMaterialProperty(); source.positions = new import__137.ConstantProperty(); source.show = new import__137.ConstantProperty(); source.granularity = new import__137.ConstantProperty(); source.fill = new import__137.ConstantProperty(); source.outline = new import__137.ConstantProperty(); source.outlineColor = new import__137.ConstantProperty(); source.outlineWidth = new import__137.ConstantProperty(); source.minimumHeights = new import__137.ConstantProperty(); source.maximumHeights = new import__137.ConstantProperty(); source.shadows = new import__137.ConstantProperty(import__137.ShadowMode.ENABLED); source.distanceDisplayCondition = new import__137.ConstantProperty(); const target = new import__137.WallGraphics(); target.merge(source); expect(target.material).toBe(source.material); expect(target.positions).toBe(source.positions); expect(target.show).toBe(source.show); expect(target.granularity).toBe(source.granularity); expect(target.fill).toBe(source.fill); expect(target.outline).toBe(source.outline); expect(target.outlineColor).toBe(source.outlineColor); expect(target.outlineWidth).toBe(source.outlineWidth); expect(target.minimumHeights).toBe(source.minimumHeights); expect(target.maximumHeights).toBe(source.maximumHeights); expect(target.shadows).toBe(source.shadows); expect(target.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); }); it("merge does not assign assigned properties", function() { const source = new import__137.WallGraphics(); const material = new import__137.ColorMaterialProperty(); const positions = new import__137.ColorMaterialProperty(); const show = new import__137.ConstantProperty(); const granularity = new import__137.ConstantProperty(); const fill = new import__137.ConstantProperty(); const outline = new import__137.ConstantProperty(); const outlineColor = new import__137.ConstantProperty(); const outlineWidth = new import__137.ConstantProperty(); const minimumHeights = new import__137.ConstantProperty(); const maximumHeights = new import__137.ConstantProperty(); const shadows = new import__137.ConstantProperty(); const distanceDisplayCondition = new import__137.ConstantProperty(); const target = new import__137.WallGraphics(); target.material = material; target.positions = positions; target.show = show; target.granularity = granularity; target.fill = fill; target.outline = outline; target.outlineColor = outlineColor; target.outlineWidth = outlineWidth; target.minimumHeights = minimumHeights; target.maximumHeights = maximumHeights; target.shadows = shadows; target.distanceDisplayCondition = distanceDisplayCondition; target.merge(source); expect(target.material).toBe(material); expect(target.positions).toBe(positions); expect(target.show).toBe(show); expect(target.granularity).toBe(granularity); expect(target.fill).toBe(fill); expect(target.outline).toBe(outline); expect(target.outlineColor).toBe(outlineColor); expect(target.outlineWidth).toBe(outlineWidth); expect(target.minimumHeights).toBe(minimumHeights); expect(target.maximumHeights).toBe(maximumHeights); expect(target.shadows).toBe(shadows); expect(target.distanceDisplayCondition).toBe(distanceDisplayCondition); }); it("clone works", function() { const source = new import__137.WallGraphics(); source.material = new import__137.ColorMaterialProperty(); source.positions = new import__137.ConstantProperty(); source.show = new import__137.ConstantProperty(); source.granularity = new import__137.ConstantProperty(); source.fill = new import__137.ConstantProperty(); source.outline = new import__137.ConstantProperty(); source.outlineColor = new import__137.ConstantProperty(); source.outlineWidth = new import__137.ConstantProperty(); source.minimumHeights = new import__137.ConstantProperty(); source.maximumHeights = new import__137.ConstantProperty(); source.shadows = new import__137.ConstantProperty(); source.distanceDisplayCondition = new import__137.ConstantProperty(); const result = source.clone(); expect(result.material).toBe(source.material); expect(result.positions).toBe(source.positions); expect(result.show).toBe(source.show); expect(result.granularity).toBe(source.granularity); expect(result.fill).toBe(source.fill); expect(result.outline).toBe(source.outline); expect(result.outlineColor).toBe(source.outlineColor); expect(result.outlineWidth).toBe(source.outlineWidth); expect(result.minimumHeights).toBe(source.minimumHeights); expect(result.maximumHeights).toBe(source.maximumHeights); expect(result.shadows).toBe(source.shadows); expect(result.distanceDisplayCondition).toBe( source.distanceDisplayCondition ); }); it("merge throws if source undefined", function() { const target = new import__137.WallGraphics(); expect(function() { target.merge(void 0); }).toThrowDeveloperError(); }); it("raises definitionChanged when a property is assigned or modified", function() { const property = new import__137.WallGraphics(); testMaterialDefinitionChanged_default(property, "material", import__137.Color.RED, import__137.Color.BLUE); testDefinitionChanged_default(property, "show", true, false); testDefinitionChanged_default(property, "positions", [], []); testDefinitionChanged_default(property, "granularity", 3, 4); testDefinitionChanged_default(property, "fill", false, true); testDefinitionChanged_default(property, "outline", true, false); testDefinitionChanged_default(property, "outlineColor", import__137.Color.RED, import__137.Color.BLUE); testDefinitionChanged_default(property, "outlineWidth", 2, 3); testDefinitionChanged_default(property, "minimumHeights", [0, 1], [2, 3]); testDefinitionChanged_default(property, "maximumHeights", [3, 5], [7, 8]); testDefinitionChanged_default( property, "shadows", import__137.ShadowMode.ENABLED, import__137.ShadowMode.DISABLED ); testDefinitionChanged_default( property, "distanceDisplayCondition", new import__137.DistanceDisplayCondition(), new import__137.DistanceDisplayCondition(10, 100) ); }); }); // packages/engine/Specs/DataSources/createMaterialPropertyDescriptorSpec.js var import__138 = __toESM(require_Cesium(), 1); describe("DataSources/createMaterialPropertyDescriptor", function() { function MockGraphics() { this._definitionChanged = new import__138.Event(); } Object.defineProperties(MockGraphics.prototype, { materialProperty: (0, import__138.createMaterialPropertyDescriptor)("materialProperty") }); it("defaults to undefined", function() { const instance = new MockGraphics(); expect(instance.materialProperty).toBeUndefined(); }); it("creates ImageMaterialProperty from string ", function() { const instance = new MockGraphics(); expect(instance.materialProperty).toBeUndefined(); const value = "test.invalid"; instance.materialProperty = value; expect(instance.materialProperty).toBeInstanceOf(import__138.ImageMaterialProperty); expect(instance.materialProperty.image.getValue()).toEqual(value); }); it("creates ColorMaterialProperty from Color", function() { const instance = new MockGraphics(); expect(instance.materialProperty).toBeUndefined(); const value = import__138.Color.RED; instance.materialProperty = value; expect(instance.materialProperty).toBeInstanceOf(import__138.ColorMaterialProperty); expect(instance.materialProperty.color.getValue()).toEqual(value); }); it("throws if type can not be infered", function() { const instance = new MockGraphics(); expect(function() { instance.materialProperty = {}; }).toThrowDeveloperError(); }); }); // packages/engine/Specs/DataSources/exportKmlSpec.js var import__139 = __toESM(require_Cesium(), 1); var import__140 = __toESM(require_Cesium(), 1); describe("DataSources/exportKml", function() { let kmlDoc; function checkKmlDoc(entities, properties, options) { options = (0, import__139.defaultValue)(options, {}); options.entities = entities; const promise = (0, import__139.exportKml)(options); const kml = kmlDoc.documentElement; const kmlChildNodes = kml.childNodes; expect(kml.localName).toEqual("kml"); expect(kmlChildNodes.length).toBe(1); checkTagWithProperties(kml, properties); return promise; } function checkTagWithProperties(element, properties) { const attributes = properties._; if ((0, import__139.defined)(attributes)) { const elementAttributes = element.attributes; expect(elementAttributes.length).toBe(Object.keys(attributes).length); for (let j = 0; j < elementAttributes.length; ++j) { const nodeAttribute = elementAttributes[j]; const attribute = attributes[nodeAttribute.name]; if (typeof attribute === "string") { expect(nodeAttribute.value).toEqual(attribute); } else if (typeof attribute === "number") { expect(Number(nodeAttribute.value)).toEqualEpsilon( attribute, import__140.Math.EPSILON7 ); } else { fail(); } } } const childNodes = element.childNodes; for (let i = 0; i < childNodes.length; ++i) { const node = childNodes[i]; let property = properties[node.tagName]; expect(property).toBeDefined(); if ((0, import__139.defined)(property.getValue)) { property = property.getValue(import__139.Iso8601.MINIMUM_VALUE); } if (typeof property === "function") { expect(property(node.textContent)).toBe(true); } else if (typeof property === "string") { expect(node.textContent).toEqual(property); } else if (typeof property === "number") { expect(Number(node.textContent)).toEqualEpsilon( property, import__140.Math.EPSILON7 ); } else if (typeof property === "boolean") { expect(Number(node.textContent)).toBe(property ? 1 : 0); } else { checkTagWithProperties(node, property); } } } let counter = 0; const pointPosition = import__139.Cartesian3.fromDegrees(-75.59777, 40.03883, 12); function checkPointCoord(textContent) { const values = textContent.split(/\s*,\s*/); expect(values.length).toBe(3); const cartographic1 = import__139.Cartographic.fromCartesian(pointPosition); const cartographic2 = import__139.Cartographic.fromDegrees( Number(values[0]), Number(values[1]), Number(values[2]) ); return import__139.Cartographic.equalsEpsilon( cartographic1, cartographic2, import__140.Math.EPSILON7 ); } function createEntity(properties) { ++counter; const options = { id: `e${counter}`, name: `entity${counter}`, show: true, description: `This is entity number ${counter}`, position: pointPosition }; if ((0, import__139.defined)(properties)) { for (const propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { options[propertyName] = properties[propertyName]; } } } return new import__139.Entity(options); } function createExpectResult(entity) { return { Document: { Style: { _: { id: "style-1" } }, Placemark: { _: { id: entity.id }, name: entity.name, visibility: entity.show ? 1 : 0, description: entity.description, styleUrl: "#style-1" } } }; } let oldCreateState; beforeAll(function() { oldCreateState = import__139.exportKml._createState; import__139.exportKml._createState = function(options) { const state2 = oldCreateState(options); kmlDoc = state2.kmlDoc; return state2; }; }); afterAll(function() { import__139.exportKml._createState = oldCreateState; }); beforeEach(function() { counter = 0; }); it("Hierarchy", function() { const entity1 = createEntity({ show: false, position: void 0 }); const entity2 = createEntity({ position: void 0, parent: entity1 }); const entity3 = createEntity({ parent: entity2, point: {} }); const entities = new import__139.EntityCollection(); entities.add(entity1); entities.add(entity2); entities.add(entity3); const hierarchy = { Document: { Style: { _: { id: "style-1" }, IconStyle: {} }, Folder: { _: { id: entity1.id }, name: entity1.name, visibility: "0", description: entity1.description, Folder: { _: { id: entity2.id }, name: entity2.name, visibility: true, description: entity2.description, Placemark: { _: { id: entity3.id }, Point: { altitudeMode: "absolute", coordinates: checkPointCoord }, name: entity3.name, visibility: true, description: entity3.description, styleUrl: "#style-1" } } } } }; checkKmlDoc(entities, hierarchy); }); describe("Point Geometry", function() { it("Point with constant position", function() { const entity1 = createEntity({ point: { color: import__139.Color.LINEN, pixelSize: 3, heightReference: import__139.HeightReference.CLAMP_TO_GROUND } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.IconStyle = { color: "ffe6f0fa", colorMode: "normal", scale: 3 / 32 }; expectedResult.Document.Placemark.Point = { altitudeMode: "clampToGround", coordinates: checkPointCoord }; checkKmlDoc(entities, expectedResult); }); it("Point with label", function() { const entity1 = createEntity({ point: { color: import__139.Color.LINEN, pixelSize: 3, heightReference: import__139.HeightReference.CLAMP_TO_GROUND }, label: { text: "Im a label", color: import__139.Color.ORANGE, scale: 2 } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.IconStyle = { color: "ffe6f0fa", colorMode: "normal", scale: 3 / 32 }; expectedResult.Document.Style.LabelStyle = { color: "ff00a5ff", colorMode: "normal", scale: 2 }; expectedResult.Document.Placemark.name = "Im a label"; expectedResult.Document.Placemark.Point = { altitudeMode: "clampToGround", coordinates: checkPointCoord }; checkKmlDoc(entities, expectedResult); }); it("Billboard with constant position", function() { const entity1 = createEntity({ billboard: { image: "http://test.invalid/image.jpg", imageSubRegion: new import__139.BoundingRectangle(12, 0, 24, 36), color: import__139.Color.LINEN, scale: 2, pixelOffset: new import__139.Cartesian2(2, 3), width: 24, height: 36, horizontalOrigin: import__139.HorizontalOrigin.LEFT, verticalOrigin: import__139.VerticalOrigin.BOTTOM, rotation: import__140.Math.toRadians(10), alignedAxis: import__139.Cartesian3.UNIT_Z, heightReference: import__139.HeightReference.CLAMP_TO_GROUND } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.IconStyle = { Icon: { href: "http://test.invalid/image.jpg", x: 12, y: 0, w: 24, h: 36 }, color: "ffe6f0fa", colorMode: "normal", scale: 2, hotSpot: { _: { x: -2 / 2, y: 3 / 2, xunits: "pixels", yunits: "pixels" } }, heading: -10 }; expectedResult.Document.Placemark.Point = { altitudeMode: "clampToGround", coordinates: checkPointCoord }; checkKmlDoc(entities, expectedResult); }); it("Billboard with AlignedAxis not Z", function() { const entity1 = createEntity({ billboard: { rotation: import__140.Math.toRadians(10), alignedAxis: import__139.Cartesian3.UNIT_Y } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.IconStyle = {}; expectedResult.Document.Placemark.Point = { altitudeMode: "absolute", coordinates: checkPointCoord }; checkKmlDoc(entities, expectedResult); }); it("Billboard with 0 degree heading should be 360", function() { const entity1 = createEntity({ billboard: { rotation: import__140.Math.toRadians(0), alignedAxis: import__139.Cartesian3.UNIT_Z } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.IconStyle = { heading: 360 }; expectedResult.Document.Placemark.Point = { altitudeMode: "absolute", coordinates: checkPointCoord }; checkKmlDoc(entities, expectedResult); }); it("Billboard with HotSpot at the center", function() { const entity1 = createEntity({ billboard: { pixelOffset: new import__139.Cartesian2(2, 3), width: 24, height: 36, horizontalOrigin: import__139.HorizontalOrigin.CENTER, verticalOrigin: import__139.VerticalOrigin.CENTER } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.IconStyle = { hotSpot: { _: { x: -(2 - 12), y: 3 + 18, xunits: "pixels", yunits: "pixels" } } }; expectedResult.Document.Placemark.Point = { altitudeMode: "absolute", coordinates: checkPointCoord }; checkKmlDoc(entities, expectedResult); }); it("Billboard with HotSpot at the TopRight", function() { const entity1 = createEntity({ billboard: { pixelOffset: new import__139.Cartesian2(2, 3), width: 24, height: 36, horizontalOrigin: import__139.HorizontalOrigin.RIGHT, verticalOrigin: import__139.VerticalOrigin.TOP } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.IconStyle = { hotSpot: { _: { x: -(2 - 24), y: 3 + 36, xunits: "pixels", yunits: "pixels" } } }; expectedResult.Document.Placemark.Point = { altitudeMode: "absolute", coordinates: checkPointCoord }; checkKmlDoc(entities, expectedResult); }); it("Billboard with a Canvas image", function() { const entity1 = createEntity({ billboard: { image: document.createElement("canvas") } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.IconStyle = { Icon: { href: "texture_1.png" } }; expectedResult.Document.Placemark.Point = { altitudeMode: "absolute", coordinates: checkPointCoord }; return checkKmlDoc(entities, expectedResult).then(function(result) { expect(result.kml).toBeDefined(); expect(Object.keys(result.externalFiles).length).toBe(1); expect(result.externalFiles["texture_1.png"]).toBeDefined(); }); }); it("Billboard with a Canvas image as KMZ", function() { const entity1 = createEntity({ billboard: { image: document.createElement("canvas") } }); const entities = new import__139.EntityCollection(); entities.add(entity1); return (0, import__139.exportKml)({ entities, kmz: true }).then(function(result) { expect(result.kml).toBeUndefined(); expect(result.externalFiles).toBeUndefined(); expect(result.kmz).toBeDefined(); return new Promise((resolve) => { const fileReader = new FileReader(); fileReader.onload = function(event) { expect(new DataView(event.target.result).getUint32(0, false)).toBe( 1347093252 ); resolve(); }; fileReader.readAsArrayBuffer(result.kmz); }); }); }); }); describe("Tracks", function() { const times = [ import__139.JulianDate.fromIso8601("2019-06-17"), import__139.JulianDate.fromIso8601("2019-06-18"), import__139.JulianDate.fromIso8601("2019-06-19") ]; const positions = [ import__139.Cartesian3.fromDegrees(-75.59777, 40.03883, 12), import__139.Cartesian3.fromDegrees(-76.59777, 39.03883, 12), import__139.Cartesian3.fromDegrees(-77.59777, 38.03883, 12) ]; function checkWhen(textContent) { const count = times.length; for (let i = 0; i < count; ++i) { if (textContent === import__139.JulianDate.toIso8601(times[i])) { return true; } } return false; } function checkCoord(textContent) { const values = textContent.split(/\s*,\s*/); expect(values.length).toBe(3); const cartographic1 = new import__139.Cartographic(); const cartographic2 = new import__139.Cartographic(); const count = positions.length; for (let i = 0; i < count; ++i) { import__139.Cartographic.fromCartesian(positions[i], void 0, cartographic1); import__139.Cartographic.fromDegrees( Number(values[0]), Number(values[1]), Number(values[2]), cartographic2 ); if (import__139.Cartographic.equalsEpsilon( cartographic1, cartographic2, import__140.Math.EPSILON7 )) { return true; } } return false; } it("SampledPosition", function() { const position = new import__139.SampledPositionProperty(); position.addSamples(times, positions); const entity1 = createEntity({ position, point: { heightReference: import__139.HeightReference.CLAMP_TO_GROUND } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.IconStyle = {}; expectedResult.Document.Placemark.Track = { altitudeMode: "clampToGround", when: checkWhen, coord: checkCoord }; checkKmlDoc(entities, expectedResult); }); it("CallbackProperty", function() { let index = 0; const position = new import__139.CallbackProperty(function(time2) { expect(index < times.length); expect(import__139.JulianDate.equals(time2, times[index])).toBe(true); return positions[index++]; }, false); const entity1 = createEntity({ position, point: {} }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.IconStyle = {}; expectedResult.Document.Placemark.Track = { altitudeMode: "absolute", when: checkWhen, coord: checkCoord }; checkKmlDoc(entities, expectedResult, { defaultAvailability: new import__139.TimeInterval({ start: times[0], stop: times[2] }), sampleDuration: import__139.JulianDate.secondsDifference(times[1], times[0]) }); }); it("With Model", function() { const position = new import__139.SampledPositionProperty(); position.addSamples(times, positions); const entity1 = createEntity({ position, model: { uri: "http://test.invalid/test" } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Placemark.Track = { altitudeMode: "absolute", when: checkWhen, coord: checkCoord, Model: { Link: { href: "http://test.invalid/test" } } }; const blob = new Blob([new Uint8Array([])], { type: "model/vnd.collada+xml" }); return checkKmlDoc(entities, expectedResult, { modelCallback: function(model, time2, externalFiles) { externalFiles["test.dae"] = blob; return model.uri; } }).then(function(result) { expect(result.externalFiles["test.dae"]).toBe(blob); }); }); it("With Path", function() { const position = new import__139.SampledPositionProperty(); position.addSamples(times, positions); const entity1 = createEntity({ position, point: { heightReference: import__139.HeightReference.CLAMP_TO_GROUND }, path: { width: 2, material: new import__139.ColorMaterialProperty(import__139.Color.GREEN) } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.IconStyle = {}; expectedResult.Document.Style.LineStyle = { color: "ff008000", colorMode: "normal", width: 2 }; expectedResult.Document.Placemark.Track = { altitudeMode: "clampToGround", when: checkWhen, coord: checkCoord }; checkKmlDoc(entities, expectedResult); }); }); describe("Polylines", function() { const positions = [ import__139.Cartesian3.fromDegrees(-1, -1, 12), import__139.Cartesian3.fromDegrees(1, -1, 12), import__139.Cartesian3.fromDegrees(1, 1, 12), import__139.Cartesian3.fromDegrees(-1, 1, 12) ]; function checkCoords(textContent) { const coordinates = textContent.split(" "); expect(coordinates.length).toBe(4); const cartographic1 = new import__139.Cartographic(); const cartographic2 = new import__139.Cartographic(); const count = positions.length; for (let i = 0; i < count; ++i) { import__139.Cartographic.fromCartesian(positions[i], void 0, cartographic1); const values = coordinates[i].split(","); expect(values.length).toBe(3); import__139.Cartographic.fromDegrees( Number(values[0]), Number(values[1]), Number(values[2]), cartographic2 ); if (import__139.Cartographic.equalsEpsilon( cartographic1, cartographic2, import__140.Math.EPSILON7 )) { return true; } } return false; } it("Clamped to ground", function() { const entity1 = createEntity({ polyline: { positions, clampToGround: true, material: new import__139.ColorMaterialProperty(import__139.Color.GREEN), width: 5, zIndex: 2 } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.LineStyle = { color: "ff008000", colorMode: "normal", width: 5 }; expectedResult.Document.Placemark.LineString = { altitudeMode: "clampToGround", coordinates: checkCoords, tessellate: true, drawOrder: 2 }; checkKmlDoc(entities, expectedResult); }); it("Not clamped to ground", function() { const entity1 = createEntity({ polyline: { positions, clampToGround: false, material: new import__139.ColorMaterialProperty(import__139.Color.GREEN), width: 5, zIndex: 2 } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.LineStyle = { color: "ff008000", colorMode: "normal", width: 5 }; expectedResult.Document.Placemark.LineString = { altitudeMode: "absolute", coordinates: checkCoords, drawOrder: 2 }; checkKmlDoc(entities, expectedResult); }); it("With outline", function() { const entity1 = createEntity({ polyline: { positions, clampToGround: false, material: new import__139.PolylineOutlineMaterialProperty({ color: import__139.Color.GREEN, outlineColor: import__139.Color.BLUE, outlineWidth: 2 }), width: 5 } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.LineStyle = { color: "ff008000", colorMode: "normal", width: 5, outerColor: "ffff0000", outerWidth: 2 }; expectedResult.Document.Placemark.LineString = { altitudeMode: "absolute", coordinates: checkCoords }; checkKmlDoc(entities, expectedResult); }); }); describe("Polygons", function() { const positions = [ import__139.Cartesian3.fromDegrees(-1, -1, 12), import__139.Cartesian3.fromDegrees(1, -1, 12), import__139.Cartesian3.fromDegrees(1, 1, 12), import__139.Cartesian3.fromDegrees(-1, 1, 12) ]; function getCheckCoords(height) { return function(textContent) { const coordinates = textContent.split(" "); expect(coordinates.length).toBe(4); const cartographic1 = new import__139.Cartographic(); const cartographic2 = new import__139.Cartographic(); const count = positions.length; for (let i = 0; i < count; ++i) { import__139.Cartographic.fromCartesian(positions[i], void 0, cartographic1); if ((0, import__139.defined)(height)) { cartographic1.height = height; } const values = coordinates[i].split(","); expect(values.length).toBe(3); import__139.Cartographic.fromDegrees( Number(values[0]), Number(values[1]), Number(values[2]), cartographic2 ); if (import__139.Cartographic.equalsEpsilon( cartographic1, cartographic2, import__140.Math.EPSILON7 )) { return true; } } return false; }; } it("Polygon with outline", function() { const entity1 = createEntity({ polygon: { hierarchy: positions, height: 10, perPositionHeight: false, heightReference: import__139.HeightReference.CLAMP_TO_GROUND, extrudedHeight: 0, fill: true, material: new import__139.ColorMaterialProperty(import__139.Color.GREEN), outline: true, outlineWidth: 5, outlineColor: import__139.Color.BLUE, zIndex: 2 } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.PolyStyle = { color: "ff008000", colorMode: "normal", fill: true, outline: true }; expectedResult.Document.Style.LineStyle = { color: "ffff0000", colorMode: "normal", width: 5 }; expectedResult.Document.Placemark.Polygon = { altitudeMode: "clampToGround", outerBoundaryIs: { LinearRing: { coordinates: getCheckCoords(10) } } }; checkKmlDoc(entities, expectedResult); }); it("Polygon with extrusion", function() { const entity1 = createEntity({ polygon: { hierarchy: positions, height: 10, perPositionHeight: false, extrudedHeight: 20 } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.PolyStyle = {}; expectedResult.Document.Placemark.Polygon = { altitudeMode: "absolute", outerBoundaryIs: { LinearRing: { coordinates: getCheckCoords(20) // We use extrudedHeight } }, extrude: true }; checkKmlDoc(entities, expectedResult); }); it("Polygon with extrusion and perPositionHeights", function() { const entity1 = createEntity({ polygon: { hierarchy: positions, height: 10, perPositionHeight: true, extrudedHeight: 20 } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.PolyStyle = {}; expectedResult.Document.Placemark.Polygon = { altitudeMode: "absolute", outerBoundaryIs: { LinearRing: { coordinates: getCheckCoords() // Use per position height } }, extrude: true }; checkKmlDoc(entities, expectedResult); }); it("Polygon with holes", function() { const entity1 = createEntity({ polygon: { hierarchy: new import__139.PolygonHierarchy(positions, [ new import__139.PolygonHierarchy(positions) ]), height: 10 } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.PolyStyle = {}; expectedResult.Document.Placemark.Polygon = { altitudeMode: "absolute", outerBoundaryIs: { LinearRing: { coordinates: getCheckCoords(10) } }, innerBoundaryIs: { LinearRing: { coordinates: getCheckCoords(10) } } }; checkKmlDoc(entities, expectedResult); }); it("Rectangle extruded", function() { const entity1 = createEntity({ rectangle: { coordinates: import__139.Rectangle.fromDegrees(-1, -1, 1, 1), height: 10, perPositionHeight: false, heightReference: import__139.HeightReference.CLAMP_TO_GROUND, extrudedHeight: 20, fill: true, material: new import__139.ColorMaterialProperty(import__139.Color.GREEN), outline: true, outlineWidth: 5, outlineColor: import__139.Color.BLUE, zIndex: 2 } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.PolyStyle = { color: "ff008000", colorMode: "normal", fill: true, outline: true }; expectedResult.Document.Style.LineStyle = { color: "ffff0000", colorMode: "normal", width: 5 }; expectedResult.Document.Placemark.Polygon = { altitudeMode: "clampToGround", outerBoundaryIs: { LinearRing: { coordinates: getCheckCoords(20) } }, extrude: true }; checkKmlDoc(entities, expectedResult); }); it("Rectangle not extruded", function() { const entity1 = createEntity({ rectangle: { coordinates: import__139.Rectangle.fromDegrees(-1, -1, 1, 1), height: 10, heightReference: import__139.HeightReference.CLAMP_TO_GROUND, material: new import__139.ColorMaterialProperty(import__139.Color.GREEN) } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.PolyStyle = { color: "ff008000", colorMode: "normal" }; expectedResult.Document.Placemark.Polygon = { altitudeMode: "clampToGround", outerBoundaryIs: { LinearRing: { coordinates: getCheckCoords(10) } } }; checkKmlDoc(entities, expectedResult); }); }); describe("Models", function() { it("Model with constant position", function() { const entity1 = createEntity({ model: { uri: "http://test.invalid/test.glb", scale: 3, heightReference: import__139.HeightReference.CLAMP_TO_GROUND } }); const entities = new import__139.EntityCollection(); entities.add(entity1); const cartographic = import__139.Cartographic.fromCartesian(pointPosition); const expectedResult = createExpectResult(entity1); expectedResult.Document.Placemark.Model = { altitudeMode: "clampToGround", Location: { longitude: import__140.Math.toDegrees(cartographic.longitude), latitude: import__140.Math.toDegrees(cartographic.latitude), altitude: cartographic.height }, Link: { href: "http://test.invalid/test.dae" }, scale: { x: 3, y: 3, z: 3 } }; checkKmlDoc(entities, expectedResult, { modelCallback: function(model, time2) { return model.uri.getValue(time2).replace(".glb", ".dae"); } }); }); }); describe("GroundOverlays", function() { it("Rectangle", function() { const entity = createEntity({ rectangle: { coordinates: import__139.Rectangle.fromDegrees(-1, -1, 1, 1), height: 10, heightReference: import__139.HeightReference.CLAMP_TO_GROUND, material: new import__139.ImageMaterialProperty({ image: "../images/logo.jpg", color: import__139.Color.GREEN }) } }); const entities = new import__139.EntityCollection(); entities.add(entity); const expectedResult = { Document: { GroundOverlay: { _: { id: entity.id }, name: entity.name, visibility: entity.show ? 1 : 0, description: entity.description, altitude: 10, altitudeMode: "clampToGround", LatLonBox: { north: 1, south: -1, east: 1, west: -1 }, Icon: { href: "../images/logo.jpg" }, color: "ff008000" } } }; checkKmlDoc(entities, expectedResult); }); }); describe("Multigeometry", function() { const positions = [ import__139.Cartesian3.fromDegrees(-1, -1, 12), import__139.Cartesian3.fromDegrees(1, -1, 12), import__139.Cartesian3.fromDegrees(1, 1, 12), import__139.Cartesian3.fromDegrees(-1, 1, 12) ]; function getCheckCoords() { return function(textContent) { const coordinates = textContent.split(" "); expect(coordinates.length).toBe(4); const cartographic1 = new import__139.Cartographic(); const cartographic2 = new import__139.Cartographic(); const count = positions.length; for (let i = 0; i < count; ++i) { import__139.Cartographic.fromCartesian(positions[i], void 0, cartographic1); cartographic1.height = 0; const values = coordinates[i].split(","); expect(values.length).toBe(3); import__139.Cartographic.fromDegrees( Number(values[0]), Number(values[1]), Number(values[2]), cartographic2 ); if (import__139.Cartographic.equalsEpsilon( cartographic1, cartographic2, import__140.Math.EPSILON7 )) { return true; } } return false; }; } it("Polygon and Point", function() { const entity1 = createEntity({ polygon: { hierarchy: positions }, point: {} }); const entities = new import__139.EntityCollection(); entities.add(entity1); const expectedResult = createExpectResult(entity1); expectedResult.Document.Style.IconStyle = {}; expectedResult.Document.Style.PolyStyle = {}; expectedResult.Document.Placemark.MultiGeometry = { Point: { altitudeMode: "absolute", coordinates: checkPointCoord }, Polygon: { altitudeMode: "absolute", outerBoundaryIs: { LinearRing: { coordinates: getCheckCoords() } }, extrude: true } }; checkKmlDoc(entities, expectedResult); }); }); }); // packages/engine/Specs/Core/ApproximateTerrainHeightsSpec.js var import__141 = __toESM(require_Cesium(), 1); describe("Core/ApproximateTerrainHeights", function() { beforeAll(function() { return import__141.ApproximateTerrainHeights.initialize(); }); afterAll(function() { import__141.ApproximateTerrainHeights._initPromise = void 0; import__141.ApproximateTerrainHeights._terrainHeights = void 0; }); it("initializes", function() { return import__141.ApproximateTerrainHeights.initialize().then(function() { expect(import__141.ApproximateTerrainHeights._terrainHeights).toBeDefined(); }); }); it("getMinimumMaximumHeights computes minimum and maximum terrain heights", function() { const result = import__141.ApproximateTerrainHeights.getMinimumMaximumHeights( import__141.Rectangle.fromDegrees(-121, 10, -120, 11) ); expect(result.minimumTerrainHeight).toEqualEpsilon( -5269.86, import__141.Math.EPSILON8 ); expect(result.maximumTerrainHeight).toEqualEpsilon( -28.53, import__141.Math.EPSILON8 ); }); it("getMinimumMaximumHeights throws with no rectangle", function() { expect(function() { return import__141.ApproximateTerrainHeights.getMinimumMaximumHeights(); }).toThrowDeveloperError(); }); it("getMinimumMaximumHeights throws if ApproximateTerrainHeights was not initialized first", function() { const heights = import__141.ApproximateTerrainHeights._terrainHeights; import__141.ApproximateTerrainHeights._terrainHeights = void 0; expect(function() { return import__141.ApproximateTerrainHeights.getMinimumMaximumHeights( import__141.Rectangle.fromDegrees(-121, 10, -120, 11) ); }); import__141.ApproximateTerrainHeights._terrainHeights = heights; }); it("getBoundingSphere computes a bounding sphere", function() { const result = import__141.ApproximateTerrainHeights.getBoundingSphere( import__141.Rectangle.fromDegrees(-121, 10, -120, 11) ); expect(result.center).toEqualEpsilon( new import__141.Cartesian3( -3183013849117281e-9, -5403772559109628e-9, 1.1545815821590829e6 ), import__141.Math.EPSILON8 ); expect(result.radius).toEqualEpsilon( 77884.16321007285, import__141.Math.EPSILON8 ); }); it("getBoundingSphere throws with no rectangle", function() { expect(function() { return import__141.ApproximateTerrainHeights.getBoundingSphere(); }).toThrowDeveloperError(); }); it("getBoundingSphere throws if ApproximateTerrainHeights was not initialized first", function() { const heights = import__141.ApproximateTerrainHeights._terrainHeights; import__141.ApproximateTerrainHeights._terrainHeights = void 0; expect(function() { return import__141.ApproximateTerrainHeights.getBoundingSphere( import__141.Rectangle.fromDegrees(-121, 10, -120, 11) ); }); import__141.ApproximateTerrainHeights._terrainHeights = heights; }); }); // packages/engine/Specs/Core/ArcGISTiledElevationTerrainProviderSpec.js var import__142 = __toESM(require_Cesium(), 1); describe("Core/ArcGISTiledElevationTerrainProvider", function() { const lercTileUrl = "Data/Images/Red16x16.png"; let availability; let metadata; beforeEach(function() { availability = { data: [] }; availability.data.length = 128 * 128; availability.data.fill(1); metadata = { currentVersion: 10.3, serviceDescription: "Test", name: "Test", description: "Test", extent: { xmin: -20037507842788246e-9, ymin: -20037508659999996e-9, xmax: 20037509157211754e-9, ymax: 20037508340000004e-9, spatialReference: { wkid: 102100, latestWkid: 3857 } }, bandCount: 1, copyrightText: "Source: USGS, NGA, NASA, CGIAR, GEBCO,N Robinson,NCEAS,NLS,OS,NMA,Geodatastyrelsen and the GIS User Community", minValues: [-450], maxValues: [8700], capabilities: "Image,Tilemap,Mensuration", tileInfo: { rows: 256, cols: 256, format: "LERC", lods: [ { level: 0, resolution: 156543.03392800014, scale: 591657527591555e-6 }, { level: 1, resolution: 78271.51696399994, scale: 295828763795777e-6 }, { level: 2, resolution: 39135.75848200009, scale: 147914381897889e-6 }, { level: 3, resolution: 19567.87924099992, scale: 73957190948944e-6 }, { level: 4, resolution: 9783.93962049996, scale: 36978595474472e-6 }, { level: 5, resolution: 4891.96981024998, scale: 18489297737236e-6 }, { level: 6, resolution: 2445.98490512499, scale: 9244648868618e-6 }, { level: 7, resolution: 1222.992452562495, scale: 4622324434309e-6 }, { level: 8, resolution: 611.4962262813797, scale: 2311162217155e-6 }, { level: 9, resolution: 305.74811314055756, scale: 1155581108577e-6 }, { level: 10, resolution: 152.87405657041106, scale: 577790.554289 }, { level: 11, resolution: 76.43702828507324, scale: 288895.277144 }, { level: 12, resolution: 38.21851414253662, scale: 144447.638572 }, { level: 13, resolution: 19.10925707126831, scale: 72223.819286 }, { level: 14, resolution: 9.554628535634155, scale: 36111.909643 }, { level: 15, resolution: 4.77731426794937, scale: 18055.954822 }, { level: 16, resolution: 2.388657133974685, scale: 9027.977411 } ] }, spatialReference: { wkid: 3857, latestWkid: 3857 } }; import__142.RequestScheduler.clearForSpecs(); import__142.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { if (url.indexOf("/tile/") !== -1) { import__142.Resource._DefaultImplementations.loadWithXhr( lercTileUrl, responseType, method, data, headers, deferred, overrideMimeType ); return; } if (url.indexOf("/tilemap/") !== -1) { setTimeout(function() { deferred.resolve(JSON.stringify(availability)); }, 1); return; } setTimeout(function() { deferred.resolve(JSON.stringify(metadata)); }, 1); }; }); afterEach(function() { import__142.Resource._Implementations.createImage = import__142.Resource._DefaultImplementations.createImage; import__142.Resource._Implementations.loadWithXhr = import__142.Resource._DefaultImplementations.loadWithXhr; }); function createRequest() { return new import__142.Request({ throttleByServer: true }); } it("conforms to TerrainProvider interface", function() { expect(import__142.ArcGISTiledElevationTerrainProvider).toConformToInterface( import__142.TerrainProvider ); }); it("fromUrl throws without url", async function() { await expectAsync( import__142.ArcGISTiledElevationTerrainProvider.fromUrl() ).toBeRejectedWithDeveloperError( "url is required, actual value was undefined" ); }); it("fromUrl resolves to new ArcGISTiledElevationTerrainProvider", async function() { const provider = await import__142.ArcGISTiledElevationTerrainProvider.fromUrl( "made/up/url" ); expect(provider).toBeInstanceOf(import__142.ArcGISTiledElevationTerrainProvider); }); it("fromUrl with resource resolves to new ArcGISTiledElevationTerrainProvider", async function() { const resource = new import__142.Resource({ url: "made/up/url" }); const provider = await import__142.ArcGISTiledElevationTerrainProvider.fromUrl( resource ); expect(provider).toBeInstanceOf(import__142.ArcGISTiledElevationTerrainProvider); }); it("fromUrl resolves with url promise", async function() { const provider = await import__142.ArcGISTiledElevationTerrainProvider.fromUrl( Promise.resolve("made/up/url") ); expect(provider).toBeInstanceOf(import__142.ArcGISTiledElevationTerrainProvider); }); it("fromUrl rejects if url rejects", async function() { await expectAsync( import__142.ArcGISTiledElevationTerrainProvider.fromUrl( Promise.reject(new Error("my message")) ) ).toBeRejectedWithError("my message"); }); it("has error event", async function() { const provider = await import__142.ArcGISTiledElevationTerrainProvider.fromUrl( "made/up/url" ); expect(provider.errorEvent).toBeDefined(); expect(provider.errorEvent).toBe(provider.errorEvent); }); it("returns reasonable geometric error for various levels", async function() { const provider = await import__142.ArcGISTiledElevationTerrainProvider.fromUrl( "made/up/url" ); expect(provider.getLevelMaximumGeometricError(0)).toBeGreaterThan(0); expect(provider.getLevelMaximumGeometricError(0)).toEqualEpsilon( provider.getLevelMaximumGeometricError(1) * 2, import__142.Math.EPSILON10 ); expect(provider.getLevelMaximumGeometricError(1)).toEqualEpsilon( provider.getLevelMaximumGeometricError(2) * 2, import__142.Math.EPSILON10 ); }); it("logo is undefined if credit is not provided", async function() { delete metadata.copyrightText; const provider = await import__142.ArcGISTiledElevationTerrainProvider.fromUrl( "made/up/url" ); expect(provider.credit).toBeUndefined(); }); it("logo is defined if credit is provided", async function() { const provider = await import__142.ArcGISTiledElevationTerrainProvider.fromUrl( "made/up/url", { credit: "thanks to our awesome made up contributors!" } ); expect(provider.credit).toBeDefined(); }); it("does not have a water mask", async function() { const provider = await import__142.ArcGISTiledElevationTerrainProvider.fromUrl( "made/up/url" ); expect(provider.hasWaterMask).toBe(false); }); it("detects WebMercator tiling scheme", async function() { const baseUrl = "made/up/url"; const terrainProvider = await import__142.ArcGISTiledElevationTerrainProvider.fromUrl( baseUrl ); expect(terrainProvider.tilingScheme).toBeInstanceOf( import__142.WebMercatorTilingScheme ); }); it("detects Geographic tiling scheme", async function() { const baseUrl = "made/up/url"; metadata.spatialReference.latestWkid = 4326; const terrainProvider = await import__142.ArcGISTiledElevationTerrainProvider.fromUrl( baseUrl ); expect(terrainProvider.tilingScheme).toBeInstanceOf(import__142.GeographicTilingScheme); }); it("fromUrl throws if the SRS is not supported", async function() { const baseUrl = "made/up/url"; metadata.spatialReference.latestWkid = 1234; await expectAsync( import__142.ArcGISTiledElevationTerrainProvider.fromUrl(baseUrl) ).toBeRejectedWithError(import__142.RuntimeError, "Invalid spatial reference"); }); it("fromUrl throws if tileInfo missing", async function() { const baseUrl = "made/up/url"; delete metadata.tileInfo; await expectAsync( import__142.ArcGISTiledElevationTerrainProvider.fromUrl(baseUrl) ).toBeRejectedWithError(import__142.RuntimeError, "tileInfo is required"); }); it("checks availability if TileMap capability exists", async function() { const baseUrl = "made/up/url"; const terrainProvider = await import__142.ArcGISTiledElevationTerrainProvider.fromUrl( baseUrl ); expect(terrainProvider._hasAvailability).toBe(true); expect(terrainProvider._tilesAvailable).toBeDefined(); expect(terrainProvider._tilesAvailabilityLoaded).toBeDefined(); }); it("does not check availability if TileMap capability is missing", async function() { const baseUrl = "made/up/url"; metadata.capabilities = "Image,Mensuration"; const terrainProvider = await import__142.ArcGISTiledElevationTerrainProvider.fromUrl( baseUrl ); expect(terrainProvider._hasAvailability).toBe(false); expect(terrainProvider._tilesAvailable).toBeUndefined(); expect(terrainProvider._tilesAvailablityLoaded).toBeUndefined(); }); describe("requestTileGeometry", function() { it("provides HeightmapTerrainData", async function() { const baseUrl = "made/up/url"; const terrainProvider = await import__142.ArcGISTiledElevationTerrainProvider.fromUrl( baseUrl ); const promise = terrainProvider.requestTileGeometry(0, 0, 0); import__142.RequestScheduler.update(); const loadedData = await promise; expect(loadedData).toBeInstanceOf(import__142.HeightmapTerrainData); }); it("returns undefined if too many requests are already in progress", async function() { const baseUrl = "made/up/url"; const deferreds = []; import__142.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { deferreds.push(deferred); }; const terrainProvider = await import__142.ArcGISTiledElevationTerrainProvider.fromUrl( baseUrl ); let promise; let i; for (i = 0; i < import__142.RequestScheduler.maximumRequestsPerServer - 1; ++i) { const request = new import__142.Request({ throttle: true, throttleByServer: true }); promise = terrainProvider.requestTileGeometry(0, 0, 0, request); } import__142.RequestScheduler.update(); expect(promise).toBeDefined(); promise = terrainProvider.requestTileGeometry(0, 0, 0, createRequest()); expect(promise).toBeUndefined(); for (i = 0; i < deferreds.length; ++i) { deferreds[i].resolve(); } await Promise.all( deferreds.map(function(deferred) { return deferred.promise; }) ); }); }); }); // packages/engine/Specs/Core/AssociativeArraySpec.js var import__143 = __toESM(require_Cesium(), 1); describe("Core/AssociativeArray", function() { it("constructor has expected default values", function() { const associativeArray = new import__143.AssociativeArray(); expect(associativeArray.length).toEqual(0); expect(associativeArray.values).toEqual([]); }); it("can manipulate values", function() { const associativeArray = new import__143.AssociativeArray(); expect(associativeArray.contains("key1")).toEqual(false); associativeArray.set("key1", 1); associativeArray.set("key2", 2); associativeArray.set("key3", 3); expect(associativeArray.get("key1")).toEqual(1); expect(associativeArray.get("key2")).toEqual(2); expect(associativeArray.get("key3")).toEqual(3); expect(associativeArray.length).toEqual(3); expect(associativeArray.contains("key1")).toEqual(true); expect(associativeArray.contains("key2")).toEqual(true); expect(associativeArray.contains("key3")).toEqual(true); const values = associativeArray.values; expect(values).toContain(1); expect(values).toContain(2); expect(values).toContain(3); expect(values.length).toEqual(3); associativeArray.set("key2", 4); expect(associativeArray.length).toEqual(3); expect(values).toContain(1); expect(values).not.toContain(2); expect(values).toContain(4); expect(values).toContain(3); expect(values.length).toEqual(3); expect(associativeArray.remove("key1")).toBe(true); expect(associativeArray.get("key1")).toBeUndefined(); expect(associativeArray.contains("key1")).toEqual(false); expect(values).not.toContain(1); expect(values).toContain(4); expect(values).toContain(3); expect(values.length).toEqual(2); expect(associativeArray.remove("key1")).toBe(false); associativeArray.removeAll(); expect(associativeArray.length).toEqual(0); expect(associativeArray.values).toEqual([]); }); it("set throws with undefined key", function() { const associativeArray = new import__143.AssociativeArray(); expect(function() { associativeArray.set(void 0, 1); }).toThrowDeveloperError(); }); it("get throws with undefined key", function() { const associativeArray = new import__143.AssociativeArray(); expect(function() { associativeArray.get(void 0); }).toThrowDeveloperError(); }); it("remove returns false with undefined key", function() { const associativeArray = new import__143.AssociativeArray(); expect(associativeArray.remove(void 0)).toBe(false); }); }); // packages/engine/Specs/Core/AttributeCompressionSpec.js var import__144 = __toESM(require_Cesium(), 1); describe("Core/AttributeCompression", function() { const negativeUnitZ = new import__144.Cartesian3(0, 0, -1); it("oct decode(0, 0)", function() { const result = new import__144.Cartesian3(); import__144.AttributeCompression.octDecode(0, 0, result); expect(result).toEqual(negativeUnitZ); }); it("oct encode(0, 0, -1)", function() { const result = new import__144.Cartesian2(); import__144.AttributeCompression.octEncode(negativeUnitZ, result); expect(result).toEqual(new import__144.Cartesian2(255, 255)); }); it("oct encode(0, 0, 1)", function() { const result = new import__144.Cartesian2(); import__144.AttributeCompression.octEncode(import__144.Cartesian3.UNIT_Z, result); expect(result).toEqual(new import__144.Cartesian2(128, 128)); }); it("oct encode(0, 0, -1) to 4 components", function() { const result = new import__144.Cartesian4(); import__144.AttributeCompression.octEncodeToCartesian4(negativeUnitZ, result); expect(result).toEqual(new import__144.Cartesian4(255, 255, 255, 255)); }); it("oct encode(0, 0, 1) to 4 components", function() { const result = new import__144.Cartesian4(); import__144.AttributeCompression.octEncodeToCartesian4(import__144.Cartesian3.UNIT_Z, result); expect(result).toEqual(new import__144.Cartesian4(128, 0, 128, 0)); }); it("oct extents are equal", function() { const result = new import__144.Cartesian3(); import__144.AttributeCompression.octDecode(0, 0, result); expect(result).toEqual(negativeUnitZ); import__144.AttributeCompression.octDecode(255, 0, result); expect(result).toEqual(negativeUnitZ); import__144.AttributeCompression.octDecode(255, 255, result); expect(result).toEqual(negativeUnitZ); import__144.AttributeCompression.octDecode(255, 0, result); expect(result).toEqual(negativeUnitZ); }); it("throws oct encode vector undefined", function() { let vector; const result = new import__144.Cartesian3(); expect(function() { import__144.AttributeCompression.octEncode(vector, result); }).toThrowDeveloperError(); }); it("throws oct encode result undefined", function() { let result; expect(function() { import__144.AttributeCompression.octEncode(import__144.Cartesian3.UNIT_Z, result); }).toThrowDeveloperError(); }); it("throws oct encode non unit vector", function() { const nonUnitLengthVector = new import__144.Cartesian3(2, 0, 0); const result = new import__144.Cartesian2(); expect(function() { import__144.AttributeCompression.octEncode(nonUnitLengthVector, result); }).toThrowDeveloperError(); }); it("throws oct encode zero length vector", function() { const result = new import__144.Cartesian2(); expect(function() { import__144.AttributeCompression.octEncode(import__144.Cartesian3.ZERO, result); }).toThrowDeveloperError(); }); it("throws oct decode result undefined", function() { let result; expect(function() { import__144.AttributeCompression.octDecode(0, 0, result); }).toThrowDeveloperError(); }); it("throws oct decode x out of bounds", function() { const result = new import__144.Cartesian3(); expect(function() { import__144.AttributeCompression.octDecode(256, 0, result); }).toThrowDeveloperError(); }); it("throws oct decode y out of bounds", function() { const result = new import__144.Cartesian3(); expect(function() { import__144.AttributeCompression.octDecode(0, 256, result); }).toThrowDeveloperError(); }); it("throws 4-component oct decode out of bounds", function() { const result = new import__144.Cartesian3(); expect(function() { import__144.AttributeCompression.octDecodeFromCartesian4( new import__144.Cartesian4(256, 0, 0, 0), result ); }).toThrowDeveloperError(); expect(function() { import__144.AttributeCompression.octDecodeFromCartesian4( new import__144.Cartesian4(0, 256, 0, 0), result ); }).toThrowDeveloperError(); expect(function() { import__144.AttributeCompression.octDecodeFromCartesian4( new import__144.Cartesian4(0, 0, 256, 0), result ); }).toThrowDeveloperError(); expect(function() { import__144.AttributeCompression.octDecodeFromCartesian4( new import__144.Cartesian4(0, 0, 0, 256), result ); }).toThrowDeveloperError(); }); it("oct encoding", function() { const epsilon = import__144.Math.EPSILON1; const encoded = new import__144.Cartesian2(); const result = new import__144.Cartesian3(); let normal = new import__144.Cartesian3(0, 0, 1); import__144.AttributeCompression.octEncode(normal, encoded); expect( import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(0, 0, -1); import__144.AttributeCompression.octEncode(normal, encoded); expect( import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(0, 1, 0); import__144.AttributeCompression.octEncode(normal, encoded); expect( import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(0, -1, 0); import__144.AttributeCompression.octEncode(normal, encoded); expect( import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, 0, 0); import__144.AttributeCompression.octEncode(normal, encoded); expect( import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, 0, 0); import__144.AttributeCompression.octEncode(normal, encoded); expect( import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, 1, 1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncode(normal, encoded); expect( import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, -1, 1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncode(normal, encoded); expect( import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, -1, 1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncode(normal, encoded); expect( import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, 1, 1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncode(normal, encoded); expect( import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, 1, -1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncode(normal, encoded); expect( import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, -1, -1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncode(normal, encoded); expect( import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, 1, -1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncode(normal, encoded); expect( import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, -1, -1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncode(normal, encoded); expect( import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result) ).toEqualEpsilon(normal, epsilon); }); it("oct encoding high precision", function() { const rangeMax = 4294967295; const epsilon = import__144.Math.EPSILON8; const encoded = new import__144.Cartesian2(); const result = new import__144.Cartesian3(); let normal = new import__144.Cartesian3(0, 0, 1); import__144.AttributeCompression.octEncodeInRange(normal, rangeMax, encoded); expect( import__144.AttributeCompression.octDecodeInRange( encoded.x, encoded.y, rangeMax, result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(0, 0, -1); import__144.AttributeCompression.octEncodeInRange(normal, rangeMax, encoded); expect( import__144.AttributeCompression.octDecodeInRange( encoded.x, encoded.y, rangeMax, result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(0, 1, 0); import__144.AttributeCompression.octEncodeInRange(normal, rangeMax, encoded); expect( import__144.AttributeCompression.octDecodeInRange( encoded.x, encoded.y, rangeMax, result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(0, -1, 0); import__144.AttributeCompression.octEncodeInRange(normal, rangeMax, encoded); expect( import__144.AttributeCompression.octDecodeInRange( encoded.x, encoded.y, rangeMax, result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, 0, 0); import__144.AttributeCompression.octEncodeInRange(normal, rangeMax, encoded); expect( import__144.AttributeCompression.octDecodeInRange( encoded.x, encoded.y, rangeMax, result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, 0, 0); import__144.AttributeCompression.octEncodeInRange(normal, rangeMax, encoded); expect( import__144.AttributeCompression.octDecodeInRange( encoded.x, encoded.y, rangeMax, result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, 1, 1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncodeInRange(normal, rangeMax, encoded); expect( import__144.AttributeCompression.octDecodeInRange( encoded.x, encoded.y, rangeMax, result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, -1, 1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncodeInRange(normal, rangeMax, encoded); expect( import__144.AttributeCompression.octDecodeInRange( encoded.x, encoded.y, rangeMax, result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, -1, 1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncodeInRange(normal, rangeMax, encoded); expect( import__144.AttributeCompression.octDecodeInRange( encoded.x, encoded.y, rangeMax, result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, 1, 1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncodeInRange(normal, rangeMax, encoded); expect( import__144.AttributeCompression.octDecodeInRange( encoded.x, encoded.y, rangeMax, result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, 1, -1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncodeInRange(normal, rangeMax, encoded); expect( import__144.AttributeCompression.octDecodeInRange( encoded.x, encoded.y, rangeMax, result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, -1, -1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncodeInRange(normal, rangeMax, encoded); expect( import__144.AttributeCompression.octDecodeInRange( encoded.x, encoded.y, rangeMax, result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, 1, -1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncodeInRange(normal, rangeMax, encoded); expect( import__144.AttributeCompression.octDecodeInRange( encoded.x, encoded.y, rangeMax, result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, -1, -1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncodeInRange(normal, rangeMax, encoded); expect( import__144.AttributeCompression.octDecodeInRange( encoded.x, encoded.y, rangeMax, result ) ).toEqualEpsilon(normal, epsilon); }); it("oct encoding to 4 components", function() { const epsilon = import__144.Math.EPSILON1; const encoded = new import__144.Cartesian4(); const result = new import__144.Cartesian3(); let normal = new import__144.Cartesian3(0, 0, 1); import__144.AttributeCompression.octEncodeToCartesian4(normal, encoded); expect( import__144.AttributeCompression.octDecodeFromCartesian4(encoded, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(0, 0, -1); import__144.AttributeCompression.octEncodeToCartesian4(normal, encoded); expect( import__144.AttributeCompression.octDecodeFromCartesian4(encoded, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(0, 1, 0); import__144.AttributeCompression.octEncodeToCartesian4(normal, encoded); expect( import__144.AttributeCompression.octDecodeFromCartesian4(encoded, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(0, -1, 0); import__144.AttributeCompression.octEncodeToCartesian4(normal, encoded); expect( import__144.AttributeCompression.octDecodeFromCartesian4(encoded, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, 0, 0); import__144.AttributeCompression.octEncodeToCartesian4(normal, encoded); expect( import__144.AttributeCompression.octDecodeFromCartesian4(encoded, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, 0, 0); import__144.AttributeCompression.octEncodeToCartesian4(normal, encoded); expect( import__144.AttributeCompression.octDecodeFromCartesian4(encoded, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, 1, 1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncodeToCartesian4(normal, encoded); expect( import__144.AttributeCompression.octDecodeFromCartesian4(encoded, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, -1, 1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncodeToCartesian4(normal, encoded); expect( import__144.AttributeCompression.octDecodeFromCartesian4(encoded, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, -1, 1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncodeToCartesian4(normal, encoded); expect( import__144.AttributeCompression.octDecodeFromCartesian4(encoded, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, 1, 1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncodeToCartesian4(normal, encoded); expect( import__144.AttributeCompression.octDecodeFromCartesian4(encoded, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, 1, -1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncodeToCartesian4(normal, encoded); expect( import__144.AttributeCompression.octDecodeFromCartesian4(encoded, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, -1, -1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncodeToCartesian4(normal, encoded); expect( import__144.AttributeCompression.octDecodeFromCartesian4(encoded, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, 1, -1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncodeToCartesian4(normal, encoded); expect( import__144.AttributeCompression.octDecodeFromCartesian4(encoded, result) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, -1, -1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncodeToCartesian4(normal, encoded); expect( import__144.AttributeCompression.octDecodeFromCartesian4(encoded, result) ).toEqualEpsilon(normal, epsilon); }); it("octFloat encoding", function() { const epsilon = import__144.Math.EPSILON1; const result = new import__144.Cartesian3(); let normal = new import__144.Cartesian3(0, 0, 1); expect( import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(0, 0, -1); expect( import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(0, 1, 0); expect( import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(0, -1, 0); expect( import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, 0, 0); expect( import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, 0, 0); expect( import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, 1, 1); import__144.Cartesian3.normalize(normal, normal); expect( import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, -1, 1); import__144.Cartesian3.normalize(normal, normal); expect( import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, -1, 1); import__144.Cartesian3.normalize(normal, normal); expect( import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, 1, 1); import__144.Cartesian3.normalize(normal, normal); expect( import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, 1, -1); import__144.Cartesian3.normalize(normal, normal); expect( import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(1, -1, -1); import__144.Cartesian3.normalize(normal, normal); expect( import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, 1, -1); import__144.Cartesian3.normalize(normal, normal); expect( import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result ) ).toEqualEpsilon(normal, epsilon); normal = new import__144.Cartesian3(-1, -1, -1); import__144.Cartesian3.normalize(normal, normal); expect( import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result ) ).toEqualEpsilon(normal, epsilon); }); it("octFloat encoding is equivalent to oct encoding", function() { const encoded = new import__144.Cartesian2(); const result1 = new import__144.Cartesian3(); const result2 = new import__144.Cartesian3(); let normal = new import__144.Cartesian3(0, 0, 1); import__144.AttributeCompression.octEncode(normal, encoded); import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result1); import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result2 ); expect(result1).toEqual(result2); normal = new import__144.Cartesian3(0, 0, -1); import__144.AttributeCompression.octEncode(normal, encoded); import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result1); import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result2 ); expect(result1).toEqual(result2); normal = new import__144.Cartesian3(0, 1, 0); import__144.AttributeCompression.octEncode(normal, encoded); import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result1); import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result2 ); expect(result1).toEqual(result2); normal = new import__144.Cartesian3(0, -1, 0); import__144.AttributeCompression.octEncode(normal, encoded); import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result1); import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result2 ); expect(result1).toEqual(result2); normal = new import__144.Cartesian3(1, 0, 0); import__144.AttributeCompression.octEncode(normal, encoded); import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result1); import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result2 ); expect(result1).toEqual(result2); normal = new import__144.Cartesian3(-1, 0, 0); import__144.AttributeCompression.octEncode(normal, encoded); import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result1); import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result2 ); expect(result1).toEqual(result2); normal = new import__144.Cartesian3(1, 1, 1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncode(normal, encoded); import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result1); import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result2 ); expect(result1).toEqual(result2); normal = new import__144.Cartesian3(1, -1, 1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncode(normal, encoded); import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result1); import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result2 ); expect(result1).toEqual(result2); normal = new import__144.Cartesian3(-1, -1, 1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncode(normal, encoded); import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result1); import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result2 ); expect(result1).toEqual(result2); normal = new import__144.Cartesian3(-1, 1, 1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncode(normal, encoded); import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result1); import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result2 ); expect(result1).toEqual(result2); normal = new import__144.Cartesian3(1, 1, -1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncode(normal, encoded); import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result1); import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result2 ); expect(result1).toEqual(result2); normal = new import__144.Cartesian3(1, -1, -1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncode(normal, encoded); import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result1); import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result2 ); expect(result1).toEqual(result2); normal = new import__144.Cartesian3(-1, 1, -1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncode(normal, encoded); import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result1); import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result2 ); expect(result1).toEqual(result2); normal = new import__144.Cartesian3(-1, -1, -1); import__144.Cartesian3.normalize(normal, normal); import__144.AttributeCompression.octEncode(normal, encoded); import__144.AttributeCompression.octDecode(encoded.x, encoded.y, result1); import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(normal), result2 ); expect(result1).toEqual(result2); }); it("encodeFloat throws without vector", function() { expect(function() { import__144.AttributeCompression.octEncodeFloat(void 0); }).toThrowDeveloperError(); }); it("decodeFloat throws without value", function() { expect(function() { import__144.AttributeCompression.octDecodeFloat(void 0, new import__144.Cartesian3()); }).toThrowDeveloperError(); }); it("decodeFloat throws without result", function() { expect(function() { import__144.AttributeCompression.octDecodeFloat(0, void 0); }).toThrowDeveloperError(); }); it("encode and packFloat is equivalent to oct encoding", function() { const vector = new import__144.Cartesian3(1, 1, 1); import__144.Cartesian3.normalize(vector, vector); const encoded = import__144.AttributeCompression.octEncode(vector, new import__144.Cartesian2()); const encodedFloat = import__144.AttributeCompression.octPackFloat(encoded); expect( import__144.AttributeCompression.octDecodeFloat(encodedFloat, new import__144.Cartesian3()) ).toEqual( import__144.AttributeCompression.octDecode(encoded.x, encoded.y, new import__144.Cartesian3()) ); }); it("packFloat throws without encoded", function() { expect(function() { import__144.AttributeCompression.octPackFloat(void 0); }).toThrowDeveloperError(); }); it("pack is equivalent to oct encoding", function() { const x = import__144.Cartesian3.UNIT_X; const y = import__144.Cartesian3.UNIT_Y; const z = import__144.Cartesian3.UNIT_Z; const packed = import__144.AttributeCompression.octPack(x, y, z, new import__144.Cartesian2()); const decodedX = new import__144.Cartesian3(); const decodedY = new import__144.Cartesian3(); const decodedZ = new import__144.Cartesian3(); import__144.AttributeCompression.octUnpack(packed, decodedX, decodedY, decodedZ); expect(decodedX).toEqual( import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(x), new import__144.Cartesian3() ) ); expect(decodedY).toEqual( import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(y), new import__144.Cartesian3() ) ); expect(decodedZ).toEqual( import__144.AttributeCompression.octDecodeFloat( import__144.AttributeCompression.octEncodeFloat(z), new import__144.Cartesian3() ) ); }); it("pack throws without v1", function() { expect(function() { import__144.AttributeCompression.octPack( void 0, new import__144.Cartesian3(), new import__144.Cartesian3(), new import__144.Cartesian2() ); }).toThrowDeveloperError(); }); it("pack throws without v2", function() { expect(function() { import__144.AttributeCompression.octPack( new import__144.Cartesian3(), void 0, new import__144.Cartesian3(), new import__144.Cartesian2() ); }).toThrowDeveloperError(); }); it("pack throws without v3", function() { expect(function() { import__144.AttributeCompression.octPack( new import__144.Cartesian3(), new import__144.Cartesian3(), void 0, new import__144.Cartesian2() ); }).toThrowDeveloperError(); }); it("pack throws without result", function() { expect(function() { import__144.AttributeCompression.octPack( new import__144.Cartesian3(), new import__144.Cartesian3(), new import__144.Cartesian3(), void 0 ); }).toThrowDeveloperError(); }); it("unpack throws without packed", function() { expect(function() { import__144.AttributeCompression.octUnpack( void 0, new import__144.Cartesian3(), new import__144.Cartesian3(), new import__144.Cartesian3() ); }).toThrowDeveloperError(); }); it("unpack throws without v1", function() { expect(function() { import__144.AttributeCompression.octUnpack( new import__144.Cartesian2(), void 0, new import__144.Cartesian3(), new import__144.Cartesian3() ); }).toThrowDeveloperError(); }); it("unpack throws without v2", function() { expect(function() { import__144.AttributeCompression.octUnpack( new import__144.Cartesian2(), new import__144.Cartesian3(), void 0, new import__144.Cartesian3() ); }).toThrowDeveloperError(); }); it("unpack throws without v3", function() { expect(function() { import__144.AttributeCompression.octUnpack( new import__144.Cartesian2(), new import__144.Cartesian3(), new import__144.Cartesian3(), void 0 ); }).toThrowDeveloperError(); }); it("compresses texture coordinates", function() { const coords = new import__144.Cartesian2(0.5, 0.5); expect( import__144.AttributeCompression.decompressTextureCoordinates( import__144.AttributeCompression.compressTextureCoordinates(coords), new import__144.Cartesian2() ) ).toEqualEpsilon(coords, 1 / 4096); }); it("compress texture coordinates throws without texture coordinates", function() { expect(function() { import__144.AttributeCompression.compressTextureCoordinates(void 0); }).toThrowDeveloperError(); }); it("decompress texture coordinates throws without encoded texture coordinates", function() { expect(function() { import__144.AttributeCompression.decompressTextureCoordinates( void 0, new import__144.Cartesian2() ); }).toThrowDeveloperError(); }); it("decompress texture coordinates throws without result", function() { expect(function() { import__144.AttributeCompression.decompressTextureCoordinates(0, void 0); }).toThrowDeveloperError(); }); it("compresses/decompresses 1.0", function() { const coords = new import__144.Cartesian2(1, 1); expect( import__144.AttributeCompression.decompressTextureCoordinates( import__144.AttributeCompression.compressTextureCoordinates(coords), new import__144.Cartesian2() ) ).toEqual(coords); }); it("compresses/decompresses 0.0", function() { const coords = new import__144.Cartesian2(1, 1); expect( import__144.AttributeCompression.decompressTextureCoordinates( import__144.AttributeCompression.compressTextureCoordinates(coords), new import__144.Cartesian2() ) ).toEqual(coords); }); it("compresses/decompresses 0.5 / 1.0", function() { const coords = new import__144.Cartesian2(0.5, 1); expect( import__144.AttributeCompression.decompressTextureCoordinates( import__144.AttributeCompression.compressTextureCoordinates(coords), new import__144.Cartesian2() ) ).toEqualEpsilon(coords, 1 / 4095); }); it("compresses/decompresses 1.0 / 0.5", function() { const coords = new import__144.Cartesian2(1, 0.5); expect( import__144.AttributeCompression.decompressTextureCoordinates( import__144.AttributeCompression.compressTextureCoordinates(coords), new import__144.Cartesian2() ) ).toEqualEpsilon(coords, 1 / 4095); }); it("compresses/decompresses values very close but not equal to 1.0", function() { const coords = new import__144.Cartesian2(0.99999999999999, 0.99999999999999); expect( import__144.AttributeCompression.decompressTextureCoordinates( import__144.AttributeCompression.compressTextureCoordinates(coords), new import__144.Cartesian2() ) ).toEqualEpsilon(coords, 1 / 4095); }); function zigZag(value) { return (value << 1 ^ value >> 15) & 65535; } const maxShort = 32767; function deltaZigZagEncode(uBuffer, vBuffer, heightBuffer) { const length2 = uBuffer.length; const buffer = new Uint16Array(length2 * ((0, import__144.defined)(heightBuffer) ? 3 : 2)); let lastU = 0; let lastV = 0; let lastHeight = 0; for (let i = 0; i < length2; ++i) { const u = uBuffer[i]; const v = vBuffer[i]; buffer[i] = zigZag(u - lastU); buffer[i + length2] = zigZag(v - lastV); lastU = u; lastV = v; if ((0, import__144.defined)(heightBuffer)) { const height = heightBuffer[i]; buffer[i + length2 * 2] = zigZag(height - lastHeight); lastHeight = height; } } return buffer; } it("decodes delta and ZigZag encoded vertices without height", function() { const length2 = 10; const decodedUBuffer = new Array(length2); const decodedVBuffer = new Array(length2); for (let i = 0; i < length2; ++i) { decodedUBuffer[i] = Math.floor(Math.random() * maxShort); decodedVBuffer[i] = Math.floor(Math.random() * maxShort); } const encoded = deltaZigZagEncode(decodedUBuffer, decodedVBuffer); const uBuffer = new Uint16Array(encoded.buffer, 0, length2); const vBuffer = new Uint16Array( encoded.buffer, length2 * Uint16Array.BYTES_PER_ELEMENT, length2 ); import__144.AttributeCompression.zigZagDeltaDecode(uBuffer, vBuffer); expect(uBuffer).toEqual(decodedUBuffer); expect(vBuffer).toEqual(decodedVBuffer); }); it("decodes delta and ZigZag encoded vertices with height", function() { const length2 = 10; const decodedUBuffer = new Array(length2); const decodedVBuffer = new Array(length2); const decodedHeightBuffer = new Array(length2); for (let i = 0; i < length2; ++i) { decodedUBuffer[i] = Math.floor(Math.random() * maxShort); decodedVBuffer[i] = Math.floor(Math.random() * maxShort); decodedHeightBuffer[i] = Math.floor(Math.random() * maxShort); } const encoded = deltaZigZagEncode( decodedUBuffer, decodedVBuffer, decodedHeightBuffer ); const uBuffer = new Uint16Array(encoded.buffer, 0, length2); const vBuffer = new Uint16Array( encoded.buffer, length2 * Uint16Array.BYTES_PER_ELEMENT, length2 ); const heightBuffer = new Uint16Array( encoded.buffer, 2 * length2 * Uint16Array.BYTES_PER_ELEMENT, length2 ); import__144.AttributeCompression.zigZagDeltaDecode(uBuffer, vBuffer, heightBuffer); expect(uBuffer).toEqual(decodedUBuffer); expect(vBuffer).toEqual(decodedVBuffer); expect(heightBuffer).toEqual(decodedHeightBuffer); }); it("throws when zigZagDeltaDecode has an undefined uBuffer", function() { expect(function() { import__144.AttributeCompression.zigZagDeltaDecode(void 0, new Uint16Array(10)); }).toThrowDeveloperError(); }); it("throws when zigZagDeltaDecode has an undefined vBuffer", function() { expect(function() { import__144.AttributeCompression.zigZagDeltaDecode(new Uint16Array(10), void 0); }).toThrowDeveloperError(); }); it("throws when zigZagDeltaDecode has unequal uBuffer and vBuffer length", function() { expect(function() { import__144.AttributeCompression.zigZagDeltaDecode( new Uint16Array(10), new Uint16Array(11) ); }).toThrowDeveloperError(); }); it("throws when zigZagDeltaDecode has unequal uBuffer, vBuffer, and heightBuffer length", function() { expect(function() { import__144.AttributeCompression.zigZagDeltaDecode( new Uint16Array(10), new Uint16Array(10), new Uint16Array(11) ); }).toThrowDeveloperError(); }); it("throws when dequantize has an undefined typedArray", function() { expect(function() { import__144.AttributeCompression.dequantize( void 0, import__144.ComponentDatatype.UNSIGNED_BYTE, import__144.AttributeType.VEC3, 1 ); }).toThrowDeveloperError(); }); it("throws when dequantize has an undefined componentType", function() { expect(function() { import__144.AttributeCompression.dequantize( new Uint8Array([0, 0, 0, 0]), void 0, import__144.AttributeType.VEC3, 1 ); }).toThrowDeveloperError(); }); it("throws when dequantize has an undefined type", function() { expect(function() { import__144.AttributeCompression.dequantize( new Uint8Array([0, 0, 0, 0]), import__144.ComponentDatatype.UNSIGNED_BYTE, void 0, 1 ); }).toThrowDeveloperError(); }); it("throws when dequantize has an undefined count", function() { expect(function() { import__144.AttributeCompression.dequantize( new Uint8Array([0, 0, 0, 0]), import__144.ComponentDatatype.UNSIGNED_BYTE, import__144.AttributeType.VEC3, void 0 ); }).toThrowDeveloperError(); }); it("dequantize works with BYTE", function() { const input = [-127, -127, -127, 0, 0, 0, 127, 127, 127]; const expected = [-1, -1, -1, 0, 0, 0, 1, 1, 1]; const result = import__144.AttributeCompression.dequantize( new Int8Array(input), import__144.ComponentDatatype.BYTE, import__144.AttributeType.VEC3, 3 ); for (let i = 0; i < input.length; i++) { expect(result[i]).toEqualEpsilon(expected[i], import__144.Math.EPSILON2); } }); it("dequantize works with UNSIGNED_BYTE", function() { const input = [0, 0, 0, 127, 127, 127, 255, 255, 255]; const expected = [0, 0, 0, 0.5, 0.5, 0.5, 1, 1, 1]; const result = import__144.AttributeCompression.dequantize( new Uint8Array(input), import__144.ComponentDatatype.UNSIGNED_BYTE, import__144.AttributeType.VEC3, 3 ); for (let i = 0; i < input.length; i++) { expect(result[i]).toEqualEpsilon(expected[i], import__144.Math.EPSILON2); } }); it("dequantize works with SHORT", function() { const input = [-32767, -32767, -32767, 0, 0, 0, 32767, 32767, 32767]; const expected = [-1, -1, -1, 0, 0, 0, 1, 1, 1]; const result = import__144.AttributeCompression.dequantize( new Int16Array(input), import__144.ComponentDatatype.SHORT, import__144.AttributeType.VEC3, 3 ); for (let i = 0; i < input.length; i++) { expect(result[i]).toEqualEpsilon(expected[i], import__144.Math.EPSILON5); } }); it("dequantize works with UNSIGNED_SHORT", function() { const input = [0, 0, 0, 32767, 32767, 32767, 65535, 65535, 65535]; const expected = [0, 0, 0, 0.5, 0.5, 0.5, 1, 1, 1]; const result = import__144.AttributeCompression.dequantize( new Uint16Array(input), import__144.ComponentDatatype.UNSIGNED_SHORT, import__144.AttributeType.VEC3, 3 ); for (let i = 0; i < input.length; i++) { expect(result[i]).toEqualEpsilon(expected[i], import__144.Math.EPSILON5); } }); it("dequantize works with INT", function() { const input = [ -2147483647, -2147483647, -2147483647, 0, 0, 0, 2147483647, 2147483647, 2147483647 ]; const expected = [-1, -1, -1, 0, 0, 0, 1, 1, 1]; const result = import__144.AttributeCompression.dequantize( new Int32Array(input), import__144.ComponentDatatype.INT, import__144.AttributeType.VEC3, 3 ); for (let i = 0; i < input.length; i++) { expect(result[i]).toEqual(expected[i]); } }); it("dequantize works with UNSIGNED_INT", function() { const input = [ 0, 0, 0, 2147483647, 2147483647, 2147483647, 4294967295, 4294967295, 4294967295 ]; const expected = [0, 0, 0, 0.5, 0.5, 0.5, 1, 1, 1]; const result = import__144.AttributeCompression.dequantize( new Uint32Array(input), import__144.ComponentDatatype.UNSIGNED_INT, import__144.AttributeType.VEC3, 3 ); for (let i = 0; i < input.length; i++) { expect(result[i]).toEqual(expected[i]); } }); it("decodeRGB565 throws without typedArray", function() { expect(function() { return import__144.AttributeCompression.decodeRGB565(); }).toThrowDeveloperError(); }); it("decodeRGB565 throws if arrays are the wrong size", function() { expect(function() { return import__144.AttributeCompression.decodeRGB565( new Uint16Array([0]), new Float32Array(1) ); }).toThrowDeveloperError(); }); it("decodeRGB565 works", function() { const input = new Uint16Array([ 0, //0b00001_000001_00001 2081, //0b10000_100000_01000 33800, //0b11111_111111_11111 65535 ]); const expected = new Float32Array([ 0, 0, 0, 1 / 31, 1 / 63, 1 / 31, 16 / 31, 32 / 63, 8 / 31, 31 / 31, 63 / 63, 31 / 31 ]); const resultLength = input.length * 3; const result = new Float32Array(resultLength); import__144.AttributeCompression.decodeRGB565(input, result); for (let i = 0; i < resultLength; i++) { expect(result[i]).toEqual(expected[i]); } }); it("decodeRGB565 creates a result array if not defined", function() { const result = import__144.AttributeCompression.decodeRGB565(new Uint16Array([0])); expect(result).toEqual(new Float32Array([0, 0, 0])); }); }); // packages/engine/Specs/Core/AxisAlignedBoundingBoxSpec.js var import__145 = __toESM(require_Cesium(), 1); describe("Core/AxisAlignedBoundingBox", function() { const positions = [ new import__145.Cartesian3(3, -1, -3), new import__145.Cartesian3(2, -2, -2), new import__145.Cartesian3(1, -3, -1), new import__145.Cartesian3(0, 0, 0), new import__145.Cartesian3(-1, 1, 1), new import__145.Cartesian3(-2, 2, 2), new import__145.Cartesian3(-3, 3, 3) ]; const positionsMinimum = new import__145.Cartesian3(-3, -3, -3); const positionsMaximum = new import__145.Cartesian3(3, 3, 3); const positionsCenter = new import__145.Cartesian3(0, 0, 0); it("constructor sets expected default values", function() { const box = new import__145.AxisAlignedBoundingBox(); expect(box.minimum).toEqual(import__145.Cartesian3.ZERO); expect(box.maximum).toEqual(import__145.Cartesian3.ZERO); expect(box.center).toEqual(import__145.Cartesian3.ZERO); }); it("constructor sets expected parameter values", function() { const minimum = new import__145.Cartesian3(1, 2, 3); const maximum = new import__145.Cartesian3(4, 5, 6); const center = new import__145.Cartesian3(2.5, 3.5, 4.5); const box = new import__145.AxisAlignedBoundingBox(minimum, maximum, center); expect(box.minimum).toEqual(minimum); expect(box.maximum).toEqual(maximum); expect(box.center).toEqual(center); }); it("constructor computes center if not supplied", function() { const minimum = new import__145.Cartesian3(1, 2, 3); const maximum = new import__145.Cartesian3(4, 5, 6); const expectedCenter = new import__145.Cartesian3(2.5, 3.5, 4.5); const box = new import__145.AxisAlignedBoundingBox(minimum, maximum); expect(box.minimum).toEqual(minimum); expect(box.maximum).toEqual(maximum); expect(box.center).toEqual(expectedCenter); }); it("fromCorners works with a result parameter", function() { const minimum = new import__145.Cartesian3(0, 0, 0); const maximum = new import__145.Cartesian3(1, 1, 1); const expectedCenter = new import__145.Cartesian3(0.5, 0.5, 0.5); const box = new import__145.AxisAlignedBoundingBox(); const result = import__145.AxisAlignedBoundingBox.fromCorners(minimum, maximum, box); expect(result.minimum).toEqual(minimum); expect(result.maximum).toEqual(maximum); expect(result.center).toEqual(expectedCenter); expect(result).toBe(box); }); it("fromCorners works without a result parameter", function() { const minimum = new import__145.Cartesian3(0, 0, 0); const maximum = new import__145.Cartesian3(1, 1, 1); const expectedCenter = new import__145.Cartesian3(0.5, 0.5, 0.5); const box = import__145.AxisAlignedBoundingBox.fromCorners(minimum, maximum); expect(box.minimum).toEqual(minimum); expect(box.maximum).toEqual(maximum); expect(box.center).toEqual(expectedCenter); }); it("fromCorners throws without a minimum", function() { expect(function() { import__145.AxisAlignedBoundingBox.fromCorners(void 0, import__145.Cartesian3.ZERO); }).toThrowDeveloperError(); }); it("fromCorners throws without a maximum", function() { expect(function() { import__145.AxisAlignedBoundingBox.fromCorners(import__145.Cartesian3.ZERO, void 0); }).toThrowDeveloperError(); }); it("fromPoints constructs empty box with undefined positions", function() { const box = import__145.AxisAlignedBoundingBox.fromPoints(void 0); expect(box.minimum).toEqual(import__145.Cartesian3.ZERO); expect(box.maximum).toEqual(import__145.Cartesian3.ZERO); expect(box.center).toEqual(import__145.Cartesian3.ZERO); }); it("fromPoints constructs empty box with empty positions", function() { const box = import__145.AxisAlignedBoundingBox.fromPoints([]); expect(box.minimum).toEqual(import__145.Cartesian3.ZERO); expect(box.maximum).toEqual(import__145.Cartesian3.ZERO); expect(box.center).toEqual(import__145.Cartesian3.ZERO); }); it("fromPoints computes the correct values", function() { const box = import__145.AxisAlignedBoundingBox.fromPoints(positions); expect(box.minimum).toEqual(positionsMinimum); expect(box.maximum).toEqual(positionsMaximum); expect(box.center).toEqual(positionsCenter); }); it("clone without a result parameter", function() { const box = new import__145.AxisAlignedBoundingBox( import__145.Cartesian3.UNIT_Y, import__145.Cartesian3.UNIT_X ); const result = box.clone(); expect(box).not.toBe(result); expect(box).toEqual(result); }); it("clone without a result parameter with box of offset center", function() { const box = new import__145.AxisAlignedBoundingBox( import__145.Cartesian3.UNIT_Y, import__145.Cartesian3.UNIT_X, import__145.Cartesian3.UNIT_Z ); const result = box.clone(); expect(box).not.toBe(result); expect(box).toEqual(result); }); it("clone with a result parameter", function() { const box = new import__145.AxisAlignedBoundingBox( import__145.Cartesian3.UNIT_Y, import__145.Cartesian3.UNIT_X ); const result = new import__145.AxisAlignedBoundingBox( import__145.Cartesian3.ZERO, import__145.Cartesian3.UNIT_Z ); const returnedResult = box.clone(result); expect(result).toBe(returnedResult); expect(box).not.toBe(result); expect(box).toEqual(result); }); it('clone works with "this" result parameter', function() { const box = new import__145.AxisAlignedBoundingBox( import__145.Cartesian3.UNIT_Y, import__145.Cartesian3.UNIT_X ); const returnedResult = box.clone(box); expect(box).toBe(returnedResult); expect(box.minimum).toEqual(import__145.Cartesian3.UNIT_Y); expect(box.maximum).toEqual(import__145.Cartesian3.UNIT_X); }); it("equals works in all cases", function() { const box = new import__145.AxisAlignedBoundingBox( import__145.Cartesian3.UNIT_X, import__145.Cartesian3.UNIT_Y, import__145.Cartesian3.UNIT_Z ); const bogie = new import__145.Cartesian3(2, 3, 4); expect( box.equals( new import__145.AxisAlignedBoundingBox( import__145.Cartesian3.UNIT_X, import__145.Cartesian3.UNIT_Y, import__145.Cartesian3.UNIT_Z ) ) ).toEqual(true); expect( box.equals( new import__145.AxisAlignedBoundingBox(bogie, import__145.Cartesian3.UNIT_Y, import__145.Cartesian3.UNIT_Y) ) ).toEqual(false); expect( box.equals( new import__145.AxisAlignedBoundingBox(import__145.Cartesian3.UNIT_X, bogie, import__145.Cartesian3.UNIT_Z) ) ).toEqual(false); expect( box.equals( new import__145.AxisAlignedBoundingBox(import__145.Cartesian3.UNIT_X, import__145.Cartesian3.UNIT_Y, bogie) ) ).toEqual(false); expect(box.equals(void 0)).toEqual(false); }); it("computes the bounding box for a single position", function() { const box = import__145.AxisAlignedBoundingBox.fromPoints([positions[0]]); expect(box.minimum).toEqual(positions[0]); expect(box.maximum).toEqual(positions[0]); expect(box.center).toEqual(positions[0]); }); it("intersectPlane works with box on the positive side of a plane", function() { const box = new import__145.AxisAlignedBoundingBox( import__145.Cartesian3.negate(import__145.Cartesian3.UNIT_X, new import__145.Cartesian3()), import__145.Cartesian3.ZERO ); const normal = import__145.Cartesian3.negate(import__145.Cartesian3.UNIT_X, new import__145.Cartesian3()); const position = import__145.Cartesian3.UNIT_X; const plane = new import__145.Plane(normal, -import__145.Cartesian3.dot(normal, position)); expect(box.intersectPlane(plane)).toEqual(import__145.Intersect.INSIDE); }); it("intersectPlane works with box on the negative side of a plane", function() { const box = new import__145.AxisAlignedBoundingBox( import__145.Cartesian3.negate(import__145.Cartesian3.UNIT_X, new import__145.Cartesian3()), import__145.Cartesian3.ZERO ); const normal = import__145.Cartesian3.UNIT_X; const position = import__145.Cartesian3.UNIT_X; const plane = new import__145.Plane(normal, -import__145.Cartesian3.dot(normal, position)); expect(box.intersectPlane(plane)).toEqual(import__145.Intersect.OUTSIDE); }); it("intersectPlane works with box intersecting a plane", function() { const box = new import__145.AxisAlignedBoundingBox( import__145.Cartesian3.ZERO, import__145.Cartesian3.multiplyByScalar(import__145.Cartesian3.UNIT_X, 2, new import__145.Cartesian3()) ); const normal = import__145.Cartesian3.UNIT_X; const position = import__145.Cartesian3.UNIT_X; const plane = new import__145.Plane(normal, -import__145.Cartesian3.dot(normal, position)); expect(box.intersectPlane(plane)).toEqual(import__145.Intersect.INTERSECTING); }); it("clone returns undefined with no parameter", function() { expect(import__145.AxisAlignedBoundingBox.clone()).toBeUndefined(); }); it("intersectPlane throws without a box", function() { const plane = new import__145.Plane(import__145.Cartesian3.UNIT_X, 0); expect(function() { import__145.AxisAlignedBoundingBox.intersectPlane(void 0, plane); }).toThrowDeveloperError(); }); it("intersectPlane throws without a plane", function() { const box = new import__145.AxisAlignedBoundingBox(); expect(function() { import__145.AxisAlignedBoundingBox.intersectPlane(box, void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/BingMapsGeocoderServiceSpec.js var import__146 = __toESM(require_Cesium(), 1); describe("Core/BingMapsGeocoderService", function() { afterAll(function() { import__146.Resource._Implementations.loadAndExecuteScript = import__146.Resource._DefaultImplementations.loadAndExecuteScript; }); it("conforms to GeocoderService interface", function() { expect(import__146.BingMapsGeocoderService).toConformToInterface(import__146.GeocoderService); }); it("returns geocoder results", async function() { const query = "some query"; const key = "not_the_real_key;"; const data = { resourceSets: [ { resources: [ { name: "a", bbox: [32, 3, 3, 4] } ] } ] }; import__146.Resource._Implementations.loadAndExecuteScript = function(url, functionName, deferred) { const parsedUrl = new URL(url); expect(parsedUrl.searchParams.get("query")).toEqual(query); expect(parsedUrl.searchParams.get("key")).toEqual(key); expect(parsedUrl.searchParams.get("culture")).toBe(null); deferred.resolve(data); }; const service = new import__146.BingMapsGeocoderService({ key }); const results = await service.geocode(query); expect(results.length).toEqual(1); expect(results[0].displayName).toEqual("a"); expect(results[0].destination).toBeInstanceOf(import__146.Rectangle); }); it("uses supplied culture", async function() { const query = "some query"; const key = "not_the_real_key;"; const data = { resourceSets: [ { resources: [ { name: "a", bbox: [32, 3, 3, 4] } ] } ] }; import__146.Resource._Implementations.loadAndExecuteScript = function(url, functionName, deferred) { const parsedUrl = new URL(url); expect(parsedUrl.searchParams.get("query")).toEqual(query); expect(parsedUrl.searchParams.get("key")).toEqual(key); expect(parsedUrl.searchParams.get("culture")).toEqual("ja"); deferred.resolve(data); }; const service = new import__146.BingMapsGeocoderService({ key, culture: "ja" }); const results = await service.geocode(query); expect(results.length).toEqual(1); expect(results[0].displayName).toEqual("a"); expect(results[0].destination).toBeInstanceOf(import__146.Rectangle); }); it("returns no geocoder results if Bing has no results", async function() { const query = "some query"; const data = { resourceSets: [] }; import__146.Resource._Implementations.loadAndExecuteScript = function(url, functionName, deferred) { deferred.resolve(data); }; const service = new import__146.BingMapsGeocoderService({ key: "" }); const results = await service.geocode(query); expect(results.length).toEqual(0); }); it("returns no geocoder results if Bing has results but no resources", async function() { const query = "some query"; const data = { resourceSets: [ { resources: [] } ] }; import__146.Resource._Implementations.loadAndExecuteScript = function(url, functionName, deferred) { deferred.resolve(data); }; const service = new import__146.BingMapsGeocoderService({ key: "" }); const results = await service.geocode(query); expect(results.length).toEqual(0); }); it("credit returns expected value", async function() { const service = new import__146.BingMapsGeocoderService({ key: "" }); expect(service.credit).toBeInstanceOf(import__146.Credit); expect(service.credit.html).toEqual( `` ); expect(service.credit.showOnScreen).toBe(false); }); }); // packages/engine/Specs/Core/BoundingRectangleSpec.js var import__147 = __toESM(require_Cesium(), 1); describe("Core/BoundingRectangle", function() { it("default constructor sets expected values", function() { const rectangle = new import__147.BoundingRectangle(); expect(rectangle.x).toEqual(0); expect(rectangle.y).toEqual(0); expect(rectangle.width).toEqual(0); expect(rectangle.height).toEqual(0); }); it("constructor sets expected parameters", function() { const rectangle = new import__147.BoundingRectangle(1, 2, 3, 4); expect(rectangle.x).toEqual(1); expect(rectangle.y).toEqual(2); expect(rectangle.width).toEqual(3); expect(rectangle.height).toEqual(4); }); it("clone without a result parameter", function() { const rectangle = new import__147.BoundingRectangle(1, 2, 3, 4); const result = rectangle.clone(); expect(rectangle).not.toBe(result); expect(rectangle).toEqual(result); }); it("clone with a result parameter", function() { const rectangle = new import__147.BoundingRectangle(1, 2, 3, 4); const result = new import__147.BoundingRectangle(6, 7, 8, 9); const returnedResult = rectangle.clone(result); expect(result).not.toBe(rectangle); expect(result).toEqual(rectangle); expect(result).toBe(returnedResult); }); it('clone works with "this" result parameter', function() { const rectangle = new import__147.BoundingRectangle(1, 2, 3, 4); const returnedResult = rectangle.clone(rectangle); expect(rectangle.x).toEqual(1); expect(rectangle.y).toEqual(2); expect(rectangle.width).toEqual(3); expect(rectangle.height).toEqual(4); expect(rectangle).toBe(returnedResult); }); it("equals", function() { const rectangle = new import__147.BoundingRectangle(1, 2, 3, 4); expect(rectangle.equals(new import__147.BoundingRectangle(1, 2, 3, 4))).toEqual( true ); expect(rectangle.equals(new import__147.BoundingRectangle(5, 2, 3, 4))).toEqual( false ); expect(rectangle.equals(new import__147.BoundingRectangle(1, 6, 3, 4))).toEqual( false ); expect(rectangle.equals(new import__147.BoundingRectangle(1, 2, 7, 4))).toEqual( false ); expect(rectangle.equals(new import__147.BoundingRectangle(1, 2, 3, 8))).toEqual( false ); expect(rectangle.equals(void 0)).toEqual(false); }); const positions = [ new import__147.Cartesian2(3, -1), new import__147.Cartesian2(2, -2), new import__147.Cartesian2(1, -3), new import__147.Cartesian2(0, 0), new import__147.Cartesian2(-1, 1), new import__147.Cartesian2(-2, 2), new import__147.Cartesian2(-3, 3) ]; it("create axis aligned bounding rectangle", function() { const rectangle = import__147.BoundingRectangle.fromPoints(positions); expect(rectangle.x).toEqual(-3); expect(rectangle.y).toEqual(-3); expect(rectangle.width).toEqual(6); expect(rectangle.height).toEqual(6); }); it("fromPoints works with a result parameter", function() { const result = new import__147.BoundingRectangle(); const rectangle = import__147.BoundingRectangle.fromPoints(positions, result); expect(rectangle).toBe(result); expect(rectangle.x).toEqual(-3); expect(rectangle.y).toEqual(-3); expect(rectangle.width).toEqual(6); expect(rectangle.height).toEqual(6); }); it("fromPoints creates an empty rectangle with no positions", function() { const rectangle = import__147.BoundingRectangle.fromPoints(); expect(rectangle.x).toEqual(0); expect(rectangle.y).toEqual(0); expect(rectangle.width).toEqual(0); expect(rectangle.height).toEqual(0); }); it("fromRectangle creates an empty rectangle with no rectangle", function() { const rectangle = import__147.BoundingRectangle.fromRectangle(); expect(rectangle.x).toEqual(0); expect(rectangle.y).toEqual(0); expect(rectangle.width).toEqual(0); expect(rectangle.height).toEqual(0); }); it("create a bounding rectangle from a rectangle", function() { const rectangle = import__147.Rectangle.MAX_VALUE; const projection = new import__147.GeographicProjection(import__147.Ellipsoid.UNIT_SPHERE); const expected = new import__147.BoundingRectangle( rectangle.west, rectangle.south, rectangle.east - rectangle.west, rectangle.north - rectangle.south ); expect(import__147.BoundingRectangle.fromRectangle(rectangle, projection)).toEqual( expected ); }); it("fromRectangle works with a result parameter", function() { const rectangle = import__147.Rectangle.MAX_VALUE; const expected = new import__147.BoundingRectangle( rectangle.west, rectangle.south, rectangle.east - rectangle.west, rectangle.north - rectangle.south ); const projection = new import__147.GeographicProjection(import__147.Ellipsoid.UNIT_SPHERE); const result = new import__147.BoundingRectangle(); const returnedResult = import__147.BoundingRectangle.fromRectangle( rectangle, projection, result ); expect(result).toBe(returnedResult); expect(returnedResult).toEqual(expected); }); it("intersect works", function() { const rectangle1 = new import__147.BoundingRectangle(0, 0, 4, 4); const rectangle2 = new import__147.BoundingRectangle(2, 2, 4, 4); const rectangle3 = new import__147.BoundingRectangle(-6, 2, 4, 4); const rectangle4 = new import__147.BoundingRectangle(8, 2, 4, 4); const rectangle5 = new import__147.BoundingRectangle(2, -6, 4, 4); const rectangle6 = new import__147.BoundingRectangle(2, 8, 4, 4); expect(import__147.BoundingRectangle.intersect(rectangle1, rectangle2)).toEqual( import__147.Intersect.INTERSECTING ); expect(import__147.BoundingRectangle.intersect(rectangle1, rectangle3)).toEqual( import__147.Intersect.OUTSIDE ); expect(import__147.BoundingRectangle.intersect(rectangle1, rectangle4)).toEqual( import__147.Intersect.OUTSIDE ); expect(import__147.BoundingRectangle.intersect(rectangle1, rectangle5)).toEqual( import__147.Intersect.OUTSIDE ); expect(import__147.BoundingRectangle.intersect(rectangle1, rectangle6)).toEqual( import__147.Intersect.OUTSIDE ); }); it("union works without a result parameter", function() { const rectangle1 = new import__147.BoundingRectangle(2, 0, 1, 1); const rectangle2 = new import__147.BoundingRectangle(-2, 0, 1, 2); const expected = new import__147.BoundingRectangle(-2, 0, 5, 2); const returnedResult = import__147.BoundingRectangle.union(rectangle1, rectangle2); expect(returnedResult).toEqual(expected); }); it("union works with a result parameter", function() { const rectangle1 = new import__147.BoundingRectangle(2, 0, 1, 1); const rectangle2 = new import__147.BoundingRectangle(-2, 0, 1, 2); const expected = new import__147.BoundingRectangle(-2, 0, 5, 2); const result = new import__147.BoundingRectangle(-1, -1, 10, 10); const returnedResult = import__147.BoundingRectangle.union( rectangle1, rectangle2, result ); expect(result).toBe(returnedResult); expect(returnedResult).toEqual(expected); }); it("expand works if rectangle needs to grow right", function() { const rectangle = new import__147.BoundingRectangle(2, 0, 1, 1); const point = new import__147.Cartesian2(4, 0); const expected = new import__147.BoundingRectangle(2, 0, 2, 1); const result = import__147.BoundingRectangle.expand(rectangle, point); expect(result).toEqual(expected); }); it("expand works if rectangle needs x to grow left", function() { const rectangle = new import__147.BoundingRectangle(2, 0, 1, 1); const point = new import__147.Cartesian2(0, 0); const expected = new import__147.BoundingRectangle(0, 0, 3, 1); const result = import__147.BoundingRectangle.expand(rectangle, point); expect(result).toEqual(expected); }); it("expand works if rectangle needs to grow up", function() { const rectangle = new import__147.BoundingRectangle(2, 0, 1, 1); const point = new import__147.Cartesian2(2, 2); const expected = new import__147.BoundingRectangle(2, 0, 1, 2); const result = import__147.BoundingRectangle.expand(rectangle, point); expect(result).toEqual(expected); }); it("expand works if rectangle needs x to grow down", function() { const rectangle = new import__147.BoundingRectangle(2, 0, 1, 1); const point = new import__147.Cartesian2(2, -1); const expected = new import__147.BoundingRectangle(2, -1, 1, 2); const result = import__147.BoundingRectangle.expand(rectangle, point); expect(result).toEqual(expected); }); it("expand works if rectangle does not need to grow", function() { const rectangle = new import__147.BoundingRectangle(2, 0, 1, 1); const point = new import__147.Cartesian2(2.5, 0.6); const expected = new import__147.BoundingRectangle(2, 0, 1, 1); const result = import__147.BoundingRectangle.expand(rectangle, point); expect(result).toEqual(expected); }); it("expand works with a result parameter", function() { const rectangle = new import__147.BoundingRectangle(2, 0, 1, 1); const point = new import__147.Cartesian2(2, -1); const expected = new import__147.BoundingRectangle(2, -1, 1, 2); const result = new import__147.BoundingRectangle(); const returnedResult = import__147.BoundingRectangle.expand(rectangle, point, result); expect(returnedResult).toBe(returnedResult); expect(result).toEqual(expected); }); it("clone returns undefined with no parameter", function() { expect(import__147.BoundingRectangle.clone()).toBeUndefined(); }); it("union throws with no left parameter", function() { const right = new import__147.BoundingRectangle(1, 2, 3, 4); expect(function() { import__147.BoundingRectangle.union(void 0, right); }).toThrowDeveloperError(); }); it("union throws with no right parameter", function() { const left = new import__147.BoundingRectangle(1, 2, 3, 4); expect(function() { import__147.BoundingRectangle.union(left, void 0); }).toThrowDeveloperError(); }); it("expand throws with no rectangle parameter", function() { const point = new import__147.Cartesian2(); expect(function() { import__147.BoundingRectangle.expand(void 0, point); }).toThrowDeveloperError(); }); it("expand throws with no point parameter", function() { const rectangle = new import__147.BoundingRectangle(1, 2, 3, 4); expect(function() { import__147.BoundingRectangle.expand(rectangle, void 0); }).toThrowDeveloperError(); }); it("intersect throws with no left parameter", function() { const right = new import__147.BoundingRectangle(1, 2, 3, 4); expect(function() { import__147.BoundingRectangle.intersect(void 0, right); }).toThrowDeveloperError(); }); it("intersect throws with no right parameter", function() { const left = new import__147.BoundingRectangle(1, 2, 3, 4); expect(function() { import__147.BoundingRectangle.intersect(left, void 0); }).toThrowDeveloperError(); }); createPackableSpecs_default(import__147.BoundingRectangle, new import__147.BoundingRectangle(1, 2, 3, 4), [ 1, 2, 3, 4 ]); }); // packages/engine/Specs/Core/BoundingSphereSpec.js var import__148 = __toESM(require_Cesium(), 1); describe("Core/BoundingSphere", function() { const positionsRadius = 1; const positionsCenter = new import__148.Cartesian3(10000001, 0, 0); const center = new import__148.Cartesian3(1e7, 0, 0); function getPositions() { return [ import__148.Cartesian3.add(center, new import__148.Cartesian3(1, 0, 0), new import__148.Cartesian3()), import__148.Cartesian3.add(center, new import__148.Cartesian3(2, 0, 0), new import__148.Cartesian3()), import__148.Cartesian3.add(center, new import__148.Cartesian3(0, 0, 0), new import__148.Cartesian3()), import__148.Cartesian3.add(center, new import__148.Cartesian3(1, 1, 0), new import__148.Cartesian3()), import__148.Cartesian3.add(center, new import__148.Cartesian3(1, -1, 0), new import__148.Cartesian3()), import__148.Cartesian3.add(center, new import__148.Cartesian3(1, 0, 1), new import__148.Cartesian3()), import__148.Cartesian3.add(center, new import__148.Cartesian3(1, 0, -1), new import__148.Cartesian3()) ]; } function getPositionsAsFlatArray() { const positions = getPositions(); const result = []; for (let i = 0; i < positions.length; ++i) { result.push(positions[i].x); result.push(positions[i].y); result.push(positions[i].z); } return result; } function getPositionsAsFlatArrayWithStride5() { const positions = getPositions(); const result = []; for (let i = 0; i < positions.length; ++i) { result.push(positions[i].x); result.push(positions[i].y); result.push(positions[i].z); result.push(1.23); result.push(4.56); } return result; } function getPositionsAsEncodedFlatArray() { const positions = getPositions(); const high = []; const low = []; for (let i = 0; i < positions.length; ++i) { const encoded = import__148.EncodedCartesian3.fromCartesian(positions[i]); high.push(encoded.high.x); high.push(encoded.high.y); high.push(encoded.high.z); low.push(encoded.low.x); low.push(encoded.low.y); low.push(encoded.low.z); } return { high, low }; } it("default constructing produces expected values", function() { const sphere = new import__148.BoundingSphere(); expect(sphere.center).toEqual(import__148.Cartesian3.ZERO); expect(sphere.radius).toEqual(0); }); it("constructor sets expected values", function() { const expectedCenter = new import__148.Cartesian3(1, 2, 3); const expectedRadius = 1; const sphere = new import__148.BoundingSphere(expectedCenter, expectedRadius); expect(sphere.center).toEqual(expectedCenter); expect(sphere.radius).toEqual(expectedRadius); }); it("clone without a result parameter", function() { const sphere = new import__148.BoundingSphere(new import__148.Cartesian3(1, 2, 3), 4); const result = sphere.clone(); expect(sphere).not.toBe(result); expect(sphere).toEqual(result); }); it("clone with a result parameter", function() { const sphere = new import__148.BoundingSphere(new import__148.Cartesian3(1, 2, 3), 4); const result = new import__148.BoundingSphere(); const returnedResult = sphere.clone(result); expect(result).not.toBe(sphere); expect(result).toBe(returnedResult); expect(result).toEqual(sphere); }); it('clone works with "this" result parameter', function() { const expectedCenter = new import__148.Cartesian3(1, 2, 3); const expectedRadius = 1; const sphere = new import__148.BoundingSphere(expectedCenter, expectedRadius); const returnedResult = sphere.clone(sphere); expect(sphere).toBe(returnedResult); expect(sphere.center).toEqual(expectedCenter); expect(sphere.radius).toEqual(expectedRadius); }); it("clone clones undefined", function() { expect(import__148.BoundingSphere.clone(void 0)).toBe(void 0); }); it("equals", function() { const sphere = new import__148.BoundingSphere(new import__148.Cartesian3(1, 2, 3), 4); expect( sphere.equals(new import__148.BoundingSphere(new import__148.Cartesian3(1, 2, 3), 4)) ).toEqual(true); expect( sphere.equals(new import__148.BoundingSphere(new import__148.Cartesian3(5, 2, 3), 4)) ).toEqual(false); expect( sphere.equals(new import__148.BoundingSphere(new import__148.Cartesian3(1, 6, 3), 4)) ).toEqual(false); expect( sphere.equals(new import__148.BoundingSphere(new import__148.Cartesian3(1, 2, 7), 4)) ).toEqual(false); expect( sphere.equals(new import__148.BoundingSphere(new import__148.Cartesian3(1, 2, 3), 8)) ).toEqual(false); expect(sphere.equals(void 0)).toEqual(false); }); it("fromPoints without positions returns an empty sphere", function() { const sphere = import__148.BoundingSphere.fromPoints(); expect(sphere.center).toEqual(import__148.Cartesian3.ZERO); expect(sphere.radius).toEqual(0); }); it("fromPoints works with one point", function() { const expectedCenter = new import__148.Cartesian3(1, 2, 3); const sphere = import__148.BoundingSphere.fromPoints([expectedCenter]); expect(sphere.center).toEqual(expectedCenter); expect(sphere.radius).toEqual(0); }); it("fromPoints computes a center from points", function() { const sphere = import__148.BoundingSphere.fromPoints(getPositions()); expect(sphere.center).toEqual(positionsCenter); expect(sphere.radius).toEqual(positionsRadius); }); it("fromPoints contains all points (naive)", function() { const sphere = import__148.BoundingSphere.fromPoints(getPositions()); const radius = sphere.radius; const center2 = sphere.center; const r = new import__148.Cartesian3(radius, radius, radius); const max = import__148.Cartesian3.add(r, center2, new import__148.Cartesian3()); const min = import__148.Cartesian3.subtract(center2, r, new import__148.Cartesian3()); const positions = getPositions(); const numPositions = positions.length; for (let i = 0; i < numPositions; i++) { const currentPos = positions[i]; expect(currentPos.x <= max.x && currentPos.x >= min.x).toEqual(true); expect(currentPos.y <= max.y && currentPos.y >= min.y).toEqual(true); expect(currentPos.z <= max.z && currentPos.z >= min.z).toEqual(true); } }); it("fromPoints contains all points (ritter)", function() { const positions = getPositions(); positions.push( new import__148.Cartesian3(1, 1, 1), new import__148.Cartesian3(2, 2, 2), new import__148.Cartesian3(3, 3, 3) ); const sphere = import__148.BoundingSphere.fromPoints(positions); const radius = sphere.radius; const center2 = sphere.center; const r = new import__148.Cartesian3(radius, radius, radius); const max = import__148.Cartesian3.add(r, center2, new import__148.Cartesian3()); const min = import__148.Cartesian3.subtract(center2, r, new import__148.Cartesian3()); const numPositions = positions.length; for (let i = 0; i < numPositions; i++) { const currentPos = positions[i]; expect(currentPos.x <= max.x && currentPos.x >= min.x).toEqual(true); expect(currentPos.y <= max.y && currentPos.y >= min.y).toEqual(true); expect(currentPos.z <= max.z && currentPos.z >= min.z).toEqual(true); } }); it("fromVertices without positions returns an empty sphere", function() { const sphere = import__148.BoundingSphere.fromVertices(); expect(sphere.center).toEqual(import__148.Cartesian3.ZERO); expect(sphere.radius).toEqual(0); }); it("fromVertices works with one point", function() { const expectedCenter = new import__148.Cartesian3(1, 2, 3); const sphere = import__148.BoundingSphere.fromVertices([ expectedCenter.x, expectedCenter.y, expectedCenter.z ]); expect(sphere.center).toEqual(expectedCenter); expect(sphere.radius).toEqual(0); }); it("fromVertices computes a center from points", function() { const sphere = import__148.BoundingSphere.fromVertices(getPositionsAsFlatArray()); expect(sphere.center).toEqual(positionsCenter); expect(sphere.radius).toEqual(positionsRadius); }); it("fromVertices contains all points (naive)", function() { const sphere = import__148.BoundingSphere.fromVertices(getPositionsAsFlatArray()); const radius = sphere.radius; const center2 = sphere.center; const r = new import__148.Cartesian3(radius, radius, radius); const max = import__148.Cartesian3.add(r, center2, new import__148.Cartesian3()); const min = import__148.Cartesian3.subtract(center2, r, new import__148.Cartesian3()); const positions = getPositions(); const numPositions = positions.length; for (let i = 0; i < numPositions; i++) { const currentPos = positions[i]; expect(currentPos.x <= max.x && currentPos.x >= min.x).toEqual(true); expect(currentPos.y <= max.y && currentPos.y >= min.y).toEqual(true); expect(currentPos.z <= max.z && currentPos.z >= min.z).toEqual(true); } }); it("fromVertices contains all points (ritter)", function() { const positions = getPositionsAsFlatArray(); positions.push(1, 1, 1, 2, 2, 2, 3, 3, 3); const sphere = import__148.BoundingSphere.fromVertices(positions); const radius = sphere.radius; const center2 = sphere.center; const r = new import__148.Cartesian3(radius, radius, radius); const max = import__148.Cartesian3.add(r, center2, new import__148.Cartesian3()); const min = import__148.Cartesian3.subtract(center2, r, new import__148.Cartesian3()); const numElements = positions.length; for (let i = 0; i < numElements; i += 3) { expect(positions[i] <= max.x && positions[i] >= min.x).toEqual(true); expect(positions[i + 1] <= max.y && positions[i + 1] >= min.y).toEqual( true ); expect(positions[i + 2] <= max.z && positions[i + 2] >= min.z).toEqual( true ); } }); it("fromVertices works with a stride of 5", function() { const sphere = import__148.BoundingSphere.fromVertices( getPositionsAsFlatArrayWithStride5(), void 0, 5 ); expect(sphere.center).toEqual(positionsCenter); expect(sphere.radius).toEqual(positionsRadius); }); it("fromVertices works with defined center", function() { const center2 = new import__148.Cartesian3(1, 2, 3); const sphere = import__148.BoundingSphere.fromVertices( getPositionsAsFlatArrayWithStride5(), center2, 5 ); expect(sphere.center).toEqual( import__148.Cartesian3.add(positionsCenter, center2, new import__148.Cartesian3()) ); expect(sphere.radius).toEqual(positionsRadius); }); it("fromVertices requires a stride of at least 3", function() { function callWithStrideOf2() { import__148.BoundingSphere.fromVertices(getPositionsAsFlatArray(), void 0, 2); } expect(callWithStrideOf2).toThrowDeveloperError(); }); it("fromVertices fills result parameter if specified", function() { const center2 = new import__148.Cartesian3(1, 2, 3); const result = new import__148.BoundingSphere(); const sphere = import__148.BoundingSphere.fromVertices( getPositionsAsFlatArrayWithStride5(), center2, 5, result ); expect(sphere).toEqual(result); expect(result.center).toEqual( import__148.Cartesian3.add(positionsCenter, center2, new import__148.Cartesian3()) ); expect(result.radius).toEqual(positionsRadius); }); it("fromEncodedCartesianVertices without positions returns an empty sphere", function() { const sphere = import__148.BoundingSphere.fromEncodedCartesianVertices(); expect(sphere.center).toEqual(import__148.Cartesian3.ZERO); expect(sphere.radius).toEqual(0); }); it("fromEncodedCartesianVertices without positions of different lengths returns an empty sphere", function() { const positions = getPositionsAsEncodedFlatArray(); positions.low.length = positions.low.length - 1; const sphere = import__148.BoundingSphere.fromEncodedCartesianVertices( positions.high, positions.low ); expect(sphere.center).toEqual(import__148.Cartesian3.ZERO); expect(sphere.radius).toEqual(0); }); it("fromEncodedCartesianVertices computes a center from points", function() { const positions = getPositionsAsEncodedFlatArray(); const sphere = import__148.BoundingSphere.fromEncodedCartesianVertices( positions.high, positions.low ); expect(sphere.center).toEqual(positionsCenter); expect(sphere.radius).toEqual(positionsRadius); }); it("fromEncodedCartesianVertices contains all points (naive)", function() { let positions = getPositionsAsEncodedFlatArray(); const sphere = import__148.BoundingSphere.fromEncodedCartesianVertices( positions.high, positions.low ); const radius = sphere.radius; const center2 = sphere.center; const r = new import__148.Cartesian3(radius, radius, radius); const max = import__148.Cartesian3.add(r, center2, new import__148.Cartesian3()); const min = import__148.Cartesian3.subtract(center2, r, new import__148.Cartesian3()); positions = getPositions(); const numPositions = positions.length; for (let i = 0; i < numPositions; i++) { const currentPos = positions[i]; expect(currentPos.x <= max.x && currentPos.x >= min.x).toEqual(true); expect(currentPos.y <= max.y && currentPos.y >= min.y).toEqual(true); expect(currentPos.z <= max.z && currentPos.z >= min.z).toEqual(true); } }); it("fromEncodedCartesianVertices contains all points (ritter)", function() { const positions = getPositionsAsEncodedFlatArray(); const appendedPositions = [ new import__148.Cartesian3(1, 1, 1), new import__148.Cartesian3(2, 2, 2), new import__148.Cartesian3(3, 3, 3) ]; for (let j = 0; j < appendedPositions.length; ++j) { const encoded = import__148.EncodedCartesian3.fromCartesian( import__148.Cartesian3.add(appendedPositions[j], center, new import__148.Cartesian3()) ); positions.high.push(encoded.high.x); positions.high.push(encoded.high.y); positions.high.push(encoded.high.z); positions.low.push(encoded.low.x); positions.low.push(encoded.low.y); positions.low.push(encoded.low.z); } const sphere = import__148.BoundingSphere.fromEncodedCartesianVertices( positions.high, positions.low ); const radius = sphere.radius; const sphereCenter = sphere.center; const r = new import__148.Cartesian3(radius, radius, radius); const max = import__148.Cartesian3.add(r, sphereCenter, new import__148.Cartesian3()); const min = import__148.Cartesian3.subtract(sphereCenter, r, new import__148.Cartesian3()); const numElements = positions.length; for (let i = 0; i < numElements; i += 3) { expect(positions[i] <= max.x && positions[i] >= min.x).toEqual(true); expect(positions[i + 1] <= max.y && positions[i + 1] >= min.y).toEqual( true ); expect(positions[i + 2] <= max.z && positions[i + 2] >= min.z).toEqual( true ); } }); it("fromEncodedCartesianVertices fills result parameter if specified", function() { const positions = getPositionsAsEncodedFlatArray(); const result = new import__148.BoundingSphere(); const sphere = import__148.BoundingSphere.fromEncodedCartesianVertices( positions.high, positions.low, result ); expect(sphere).toEqual(result); expect(result.center).toEqual(positionsCenter); expect(result.radius).toEqual(positionsRadius); }); it("fromRectangle2D creates an empty sphere if no rectangle provided", function() { const sphere = import__148.BoundingSphere.fromRectangle2D(); expect(sphere.center).toEqual(import__148.Cartesian3.ZERO); expect(sphere.radius).toEqual(0); }); it("fromRectangle2D", function() { const rectangle = import__148.Rectangle.MAX_VALUE; const projection = new import__148.GeographicProjection(import__148.Ellipsoid.UNIT_SPHERE); const expected = new import__148.BoundingSphere( import__148.Cartesian3.ZERO, Math.sqrt( rectangle.east * rectangle.east + rectangle.north * rectangle.north ) ); expect(import__148.BoundingSphere.fromRectangle2D(rectangle, projection)).toEqual( expected ); }); it("fromRectangle3D creates an empty sphere if no rectangle provided", function() { const sphere = import__148.BoundingSphere.fromRectangle3D(); expect(sphere.center).toEqual(import__148.Cartesian3.ZERO); expect(sphere.radius).toEqual(0); }); it("fromRectangle3D", function() { const rectangle = import__148.Rectangle.MAX_VALUE; const ellipsoid = import__148.Ellipsoid.WGS84; const expected = new import__148.BoundingSphere( import__148.Cartesian3.ZERO, ellipsoid.maximumRadius ); expect(import__148.BoundingSphere.fromRectangle3D(rectangle, ellipsoid)).toEqual( expected ); }); it("fromRectangle3D with height", function() { const rectangle = new import__148.Rectangle(0.1, -0.3, 0.2, -0.4); const height = 1e5; const ellipsoid = import__148.Ellipsoid.WGS84; const points = import__148.Rectangle.subsample(rectangle, ellipsoid, height); const expected = import__148.BoundingSphere.fromPoints(points); expect( import__148.BoundingSphere.fromRectangle3D(rectangle, ellipsoid, height) ).toEqual(expected); }); it("fromCornerPoints", function() { const sphere = import__148.BoundingSphere.fromCornerPoints( new import__148.Cartesian3(-1, -0, 0), new import__148.Cartesian3(1, 0, 0) ); expect(sphere).toEqual(new import__148.BoundingSphere(import__148.Cartesian3.ZERO, 1)); }); it("fromCornerPoints with a result parameter", function() { const sphere = new import__148.BoundingSphere(); const result = import__148.BoundingSphere.fromCornerPoints( new import__148.Cartesian3(0, -1, 0), new import__148.Cartesian3(0, 1, 0), sphere ); expect(result).toBe(sphere); expect(result).toEqual(new import__148.BoundingSphere(import__148.Cartesian3.ZERO, 1)); }); it("fromCornerPoints throws without corner", function() { expect(function() { import__148.BoundingSphere.fromCornerPoints(); }).toThrowDeveloperError(); }); it("fromCornerPoints throws without oppositeCorner", function() { expect(function() { import__148.BoundingSphere.fromCornerPoints(import__148.Cartesian3.UNIT_X); }).toThrowDeveloperError(); }); it("fromEllipsoid", function() { const ellipsoid = import__148.Ellipsoid.WGS84; const sphere = import__148.BoundingSphere.fromEllipsoid(ellipsoid); expect(sphere.center).toEqual(import__148.Cartesian3.ZERO); expect(sphere.radius).toEqual(ellipsoid.maximumRadius); }); it("fromEllipsoid with a result parameter", function() { const ellipsoid = import__148.Ellipsoid.WGS84; const sphere = new import__148.BoundingSphere(new import__148.Cartesian3(1, 2, 3), 4); const result = import__148.BoundingSphere.fromEllipsoid(ellipsoid, sphere); expect(result).toBe(sphere); expect(result).toEqual( new import__148.BoundingSphere(import__148.Cartesian3.ZERO, ellipsoid.maximumRadius) ); }); it("fromEllipsoid throws without ellipsoid", function() { expect(function() { import__148.BoundingSphere.fromEllipsoid(); }).toThrowDeveloperError(); }); it("fromBoundingSpheres with undefined returns an empty sphere", function() { const sphere = import__148.BoundingSphere.fromBoundingSpheres(); expect(sphere.center).toEqual(import__148.Cartesian3.ZERO); expect(sphere.radius).toEqual(0); }); it("fromBoundingSpheres with empty array returns an empty sphere", function() { const sphere = import__148.BoundingSphere.fromBoundingSpheres([]); expect(sphere.center).toEqual(import__148.Cartesian3.ZERO); expect(sphere.radius).toEqual(0); }); it("fromBoundingSpheres works with 1 sphere", function() { const one = new import__148.BoundingSphere(new import__148.Cartesian3(1, 2, 3), 4); const sphere = import__148.BoundingSphere.fromBoundingSpheres([one]); expect(sphere).toEqual(one); }); it("fromBoundingSpheres works with 2 spheres", function() { const one = new import__148.BoundingSphere(new import__148.Cartesian3(1, 2, 3), 4); const two = new import__148.BoundingSphere(new import__148.Cartesian3(5, 6, 7), 8); const sphere = import__148.BoundingSphere.fromBoundingSpheres([one, two]); expect(sphere).toEqual( import__148.BoundingSphere.union(one, two, new import__148.BoundingSphere()) ); }); it("fromBoundingSpheres works with 3 spheres", function() { const one = new import__148.BoundingSphere(new import__148.Cartesian3(0, 0, 0), 1); const two = new import__148.BoundingSphere(new import__148.Cartesian3(0, 3, 0), 1); const three = new import__148.BoundingSphere(new import__148.Cartesian3(0, 0, 4), 1); const expected = new import__148.BoundingSphere(new import__148.Cartesian3(0, 1.5, 2), 3.5); const sphere = import__148.BoundingSphere.fromBoundingSpheres([one, two, three]); expect(sphere).toEqual(expected); }); it("fromOrientedBoundingBox works with a result", function() { const box = import__148.OrientedBoundingBox.fromPoints(getPositions()); const sphere = new import__148.BoundingSphere(); import__148.BoundingSphere.fromOrientedBoundingBox(box, sphere); expect(sphere.center).toEqual(positionsCenter); expect(sphere.radius).toBeGreaterThan(1.5); expect(sphere.radius).toBeLessThan(2); }); it("fromOrientedBoundingBox works without a result parameter", function() { const box = import__148.OrientedBoundingBox.fromPoints(getPositions()); const sphere = import__148.BoundingSphere.fromOrientedBoundingBox(box); expect(sphere.center).toEqual(positionsCenter); expect(sphere.radius).toBeGreaterThan(1.5); expect(sphere.radius).toBeLessThan(2); }); it("throws from fromOrientedBoundingBox with undefined orientedBoundingBox parameter", function() { expect(function() { import__148.BoundingSphere.fromOrientedBoundingBox(void 0); }).toThrowDeveloperError(); }); it("fromTransformation works with a result parameter", function() { const translation = new import__148.Cartesian3(1, 2, 3); const rotation = import__148.Quaternion.fromAxisAngle(import__148.Cartesian3.UNIT_Z, 0.4); const scale = new import__148.Cartesian3(1, 2, 3); const expectedRadius = 0.5 * import__148.Cartesian3.magnitude(scale); const transformation = import__148.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const sphere = new import__148.BoundingSphere(); const result = import__148.BoundingSphere.fromTransformation(transformation, sphere); expect(result.center).toEqual(translation); expect(result.radius).toEqualEpsilon(expectedRadius, import__148.Math.EPSILON14); expect(result).toBe(sphere); }); it("fromTransformation works without a result parameter", function() { const translation = new import__148.Cartesian3(1, 2, 3); const rotation = import__148.Quaternion.fromAxisAngle(import__148.Cartesian3.UNIT_Z, 0.4); const scale = new import__148.Cartesian3(1, 2, 3); const expectedRadius = 0.5 * import__148.Cartesian3.magnitude(scale); const transformation = import__148.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const sphere = import__148.BoundingSphere.fromTransformation(transformation); expect(sphere.center).toEqual(translation); expect(sphere.radius).toEqualEpsilon(expectedRadius, import__148.Math.EPSILON14); }); it("fromTransformation works with a transformation that has zero scale", function() { const transformation = import__148.Matrix4.fromScale(import__148.Cartesian3.ZERO); const sphere = import__148.BoundingSphere.fromTransformation(transformation); expect(sphere.center).toEqual(import__148.Cartesian3.ZERO); expect(sphere.radius).toEqual(0); }); it("throws from fromTransformation with undefined transformation parameter", function() { expect(function() { import__148.BoundingSphere.fromTransformation(void 0); }).toThrowDeveloperError(); }); it("intersectPlane with sphere on the positive side of a plane", function() { const sphere = new import__148.BoundingSphere(import__148.Cartesian3.ZERO, 0.5); const normal = import__148.Cartesian3.negate(import__148.Cartesian3.UNIT_X, new import__148.Cartesian3()); const position = import__148.Cartesian3.UNIT_X; const plane = new import__148.Plane(normal, -import__148.Cartesian3.dot(normal, position)); expect(sphere.intersectPlane(plane)).toEqual(import__148.Intersect.INSIDE); }); it("intersectPlane with sphere on the negative side of a plane", function() { const sphere = new import__148.BoundingSphere(import__148.Cartesian3.ZERO, 0.5); const normal = import__148.Cartesian3.UNIT_X; const position = import__148.Cartesian3.UNIT_X; const plane = new import__148.Plane(normal, -import__148.Cartesian3.dot(normal, position)); expect(sphere.intersectPlane(plane)).toEqual(import__148.Intersect.OUTSIDE); }); it("intersectPlane with sphere intersecting a plane", function() { const sphere = new import__148.BoundingSphere(import__148.Cartesian3.UNIT_X, 0.5); const normal = import__148.Cartesian3.UNIT_X; const position = import__148.Cartesian3.UNIT_X; const plane = new import__148.Plane(normal, -import__148.Cartesian3.dot(normal, position)); expect(sphere.intersectPlane(plane)).toEqual(import__148.Intersect.INTERSECTING); }); it("expands to contain another sphere", function() { const bs1 = new import__148.BoundingSphere( import__148.Cartesian3.negate(import__148.Cartesian3.UNIT_X, new import__148.Cartesian3()), 1 ); const bs2 = new import__148.BoundingSphere(import__148.Cartesian3.UNIT_X, 1); const expected = new import__148.BoundingSphere(import__148.Cartesian3.ZERO, 2); expect(import__148.BoundingSphere.union(bs1, bs2)).toEqual(expected); }); it("union left sphere encloses right", function() { const bs1 = new import__148.BoundingSphere(import__148.Cartesian3.ZERO, 3); const bs2 = new import__148.BoundingSphere(import__148.Cartesian3.UNIT_X, 1); const union = import__148.BoundingSphere.union(bs1, bs2); expect(union).toEqual(bs1); }); it("union of co-located spheres, right sphere encloses left", function() { const bs1 = new import__148.BoundingSphere(import__148.Cartesian3.UNIT_X, 1); const bs2 = new import__148.BoundingSphere(import__148.Cartesian3.UNIT_X, 2); const union = import__148.BoundingSphere.union(bs1, bs2); expect(union).toEqual(bs2); }); it("union result parameter is a tight fit", function() { const bs1 = new import__148.BoundingSphere( import__148.Cartesian3.multiplyByScalar( import__148.Cartesian3.negate(import__148.Cartesian3.UNIT_X, new import__148.Cartesian3()), 3, new import__148.Cartesian3() ), 3 ); const bs2 = new import__148.BoundingSphere(import__148.Cartesian3.UNIT_X, 1); const expected = new import__148.BoundingSphere( import__148.Cartesian3.multiplyByScalar( import__148.Cartesian3.negate(import__148.Cartesian3.UNIT_X, new import__148.Cartesian3()), 2, new import__148.Cartesian3() ), 4 ); import__148.BoundingSphere.union(bs1, bs2, bs1); expect(bs1).toEqual(expected); }); it("expands to contain another point", function() { const bs = new import__148.BoundingSphere( import__148.Cartesian3.negate(import__148.Cartesian3.UNIT_X, new import__148.Cartesian3()), 1 ); const point = import__148.Cartesian3.UNIT_X; const expected = new import__148.BoundingSphere( import__148.Cartesian3.negate(import__148.Cartesian3.UNIT_X, new import__148.Cartesian3()), 2 ); expect(import__148.BoundingSphere.expand(bs, point)).toEqual(expected); }); it("applies transform", function() { const bs = new import__148.BoundingSphere(import__148.Cartesian3.ZERO, 1); const transform = import__148.Matrix4.fromTranslation(new import__148.Cartesian3(1, 2, 3)); const expected = new import__148.BoundingSphere(new import__148.Cartesian3(1, 2, 3), 1); expect(import__148.BoundingSphere.transform(bs, transform)).toEqual(expected); }); it("applies scale transform", function() { const bs = new import__148.BoundingSphere(import__148.Cartesian3.ZERO, 1); const transform = import__148.Matrix4.fromScale(new import__148.Cartesian3(1, 2, 3)); const expected = new import__148.BoundingSphere(import__148.Cartesian3.ZERO, 3); expect(import__148.BoundingSphere.transform(bs, transform)).toEqual(expected); }); it("applies transform without scale", function() { const bs = new import__148.BoundingSphere(import__148.Cartesian3.ZERO, 1); const transform = import__148.Matrix4.fromTranslation(new import__148.Cartesian3(1, 2, 3)); const expected = new import__148.BoundingSphere(new import__148.Cartesian3(1, 2, 3), 1); expect(import__148.BoundingSphere.transformWithoutScale(bs, transform)).toEqual( expected ); }); it("transformWithoutScale ignores scale", function() { const bs = new import__148.BoundingSphere(import__148.Cartesian3.ZERO, 1); const transform = import__148.Matrix4.fromScale(new import__148.Cartesian3(1, 2, 3)); const expected = new import__148.BoundingSphere(import__148.Cartesian3.ZERO, 1); expect(import__148.BoundingSphere.transformWithoutScale(bs, transform)).toEqual( expected ); }); it("finds distances", function() { const bs = new import__148.BoundingSphere(import__148.Cartesian3.ZERO, 1); const position = new import__148.Cartesian3(-2, 1, 0); const direction = import__148.Cartesian3.UNIT_X; const expected = new import__148.Interval(1, 3); expect( import__148.BoundingSphere.computePlaneDistances(bs, position, direction) ).toEqual(expected); }); it("distance squared to point outside of sphere", function() { const bs = new import__148.BoundingSphere(import__148.Cartesian3.ZERO, 1); const position = new import__148.Cartesian3(-2, 1, 0); const expected = 1.52786405; expect(import__148.BoundingSphere.distanceSquaredTo(bs, position)).toEqualEpsilon( expected, import__148.Math.EPSILON6 ); }); it("distance squared to point inside sphere", function() { const bs = new import__148.BoundingSphere(import__148.Cartesian3.ZERO, 1); const position = new import__148.Cartesian3(-0.5, 0.5, 0); expect(import__148.BoundingSphere.distanceSquaredTo(bs, position)).toEqual(0); }); it("projectTo2D", function() { const positions = getPositions(); const projection = new import__148.GeographicProjection(); const positions2D = []; for (let i = 0; i < positions.length; ++i) { const position = positions[i]; const cartographic = projection.ellipsoid.cartesianToCartographic( position ); positions2D.push(projection.project(cartographic)); } const boundingSphere3D = import__148.BoundingSphere.fromPoints(positions); const boundingSphere2D = import__148.BoundingSphere.projectTo2D( boundingSphere3D, projection ); const actualSphere = import__148.BoundingSphere.fromPoints(positions2D); actualSphere.center = new import__148.Cartesian3( actualSphere.center.z, actualSphere.center.x, actualSphere.center.y ); expect(boundingSphere2D.center).toEqualEpsilon( actualSphere.center, import__148.Math.EPSILON6 ); expect(boundingSphere2D.radius).toBeGreaterThan(actualSphere.radius); }); it("projectTo2D with result parameter", function() { const positions = getPositions(); const projection = new import__148.GeographicProjection(); const sphere = new import__148.BoundingSphere(); const positions2D = []; for (let i = 0; i < positions.length; ++i) { const position = positions[i]; const cartographic = projection.ellipsoid.cartesianToCartographic( position ); positions2D.push(projection.project(cartographic)); } const boundingSphere3D = import__148.BoundingSphere.fromPoints(positions); const boundingSphere2D = import__148.BoundingSphere.projectTo2D( boundingSphere3D, projection, sphere ); const actualSphere = import__148.BoundingSphere.fromPoints(positions2D); actualSphere.center = new import__148.Cartesian3( actualSphere.center.z, actualSphere.center.x, actualSphere.center.y ); expect(boundingSphere2D).toBe(sphere); expect(boundingSphere2D.center).toEqualEpsilon( actualSphere.center, import__148.Math.EPSILON6 ); expect(boundingSphere2D.radius).toBeGreaterThan(actualSphere.radius); }); it("can pack and unpack", function() { const array = []; const boundingSphere = new import__148.BoundingSphere(); boundingSphere.center = new import__148.Cartesian3(1, 2, 3); boundingSphere.radius = 4; import__148.BoundingSphere.pack(boundingSphere, array); expect(array.length).toEqual(import__148.BoundingSphere.packedLength); expect(import__148.BoundingSphere.unpack(array)).toEqual(boundingSphere); }); it("can pack and unpack with offset", function() { const packed = new Array(3); const offset = 3; const boundingSphere = new import__148.BoundingSphere(); boundingSphere.center = new import__148.Cartesian3(1, 2, 3); boundingSphere.radius = 4; import__148.BoundingSphere.pack(boundingSphere, packed, offset); expect(packed.length).toEqual(offset + import__148.BoundingSphere.packedLength); const result = new import__148.BoundingSphere(); const returnedResult = import__148.BoundingSphere.unpack(packed, offset, result); expect(returnedResult).toBe(result); expect(result).toEqual(boundingSphere); }); it("pack throws with undefined boundingSphere", function() { const array = []; expect(function() { import__148.BoundingSphere.pack(void 0, array); }).toThrowDeveloperError(); }); it("pack throws with undefined array", function() { const boundingSphere = new import__148.BoundingSphere(); expect(function() { import__148.BoundingSphere.pack(boundingSphere, void 0); }).toThrowDeveloperError(); }); it("unpack throws with undefined array", function() { expect(function() { import__148.BoundingSphere.unpack(void 0); }).toThrowDeveloperError(); }); it("static projectTo2D throws without sphere", function() { expect(function() { import__148.BoundingSphere.projectTo2D(); }).toThrowDeveloperError(); }); it("clone returns undefined with no parameter", function() { expect(import__148.BoundingSphere.clone()).toBeUndefined(); }); it("union throws with no left parameter", function() { const right = new import__148.BoundingSphere(); expect(function() { import__148.BoundingSphere.union(void 0, right); }).toThrowDeveloperError(); }); it("union throws with no right parameter", function() { const left = new import__148.BoundingSphere(); expect(function() { import__148.BoundingSphere.union(left, void 0); }).toThrowDeveloperError(); }); it("expand throws without a sphere", function() { const plane = new import__148.Cartesian3(); expect(function() { import__148.BoundingSphere.expand(void 0, plane); }).toThrowDeveloperError(); }); it("expand throws without a point", function() { const sphere = new import__148.BoundingSphere(); expect(function() { import__148.BoundingSphere.expand(sphere, void 0); }).toThrowDeveloperError(); }); it("intersectPlane throws without a sphere", function() { const plane = new import__148.Plane(import__148.Cartesian3.UNIT_X, 0); expect(function() { import__148.BoundingSphere.intersectPlane(void 0, plane); }).toThrowDeveloperError(); }); it("intersectPlane throws without a plane", function() { const sphere = new import__148.BoundingSphere(); expect(function() { import__148.BoundingSphere.intersectPlane(sphere, void 0); }).toThrowDeveloperError(); }); it("transform throws without a sphere", function() { expect(function() { import__148.BoundingSphere.transform(); }).toThrowDeveloperError(); }); it("transform throws without a transform", function() { const sphere = new import__148.BoundingSphere(); expect(function() { import__148.BoundingSphere.transform(sphere); }).toThrowDeveloperError(); }); it("distanceSquaredTo throws without a sphere", function() { expect(function() { import__148.BoundingSphere.distanceSquaredTo(); }).toThrowDeveloperError(); }); it("distanceSquaredTo throws without a cartesian", function() { expect(function() { import__148.BoundingSphere.distanceSquaredTo(new import__148.BoundingSphere()); }).toThrowDeveloperError(); }); it("transformWithoutScale throws without a sphere", function() { expect(function() { import__148.BoundingSphere.transformWithoutScale(); }).toThrowDeveloperError(); }); it("transformWithoutScale throws without a transform", function() { const sphere = new import__148.BoundingSphere(); expect(function() { import__148.BoundingSphere.transformWithoutScale(sphere); }).toThrowDeveloperError(); }); it("computePlaneDistances throws without a sphere", function() { expect(function() { import__148.BoundingSphere.computePlaneDistances(); }).toThrowDeveloperError(); }); it("computePlaneDistances throws without a position", function() { expect(function() { import__148.BoundingSphere.computePlaneDistances(new import__148.BoundingSphere()); }).toThrowDeveloperError(); }); it("computePlaneDistances throws without a direction", function() { expect(function() { import__148.BoundingSphere.computePlaneDistances( new import__148.BoundingSphere(), new import__148.Cartesian3() ); }).toThrowDeveloperError(); }); it("isOccluded throws without a sphere", function() { expect(function() { import__148.BoundingSphere.isOccluded(); }).toThrowDeveloperError(); }); it("isOccluded throws without an occluder", function() { expect(function() { import__148.BoundingSphere.isOccluded(new import__148.BoundingSphere()); }).toThrowDeveloperError(); }); function expectBoundingSphereToContainPoint(boundingSphere, point, projection) { const pointInCartesian = projection.project(point); let distanceFromCenter = import__148.Cartesian3.magnitude( import__148.Cartesian3.subtract( pointInCartesian, boundingSphere.center, new import__148.Cartesian3() ) ); distanceFromCenter -= import__148.Math.EPSILON9; expect(distanceFromCenter).toBeLessThanOrEqual(boundingSphere.radius); } it("fromRectangleWithHeights2D includes specified min and max heights", function() { const rectangle = new import__148.Rectangle(0.1, 0.5, 0.2, 0.6); const projection = new import__148.GeographicProjection(); const minHeight = -327; const maxHeight = 2456; const boundingSphere = import__148.BoundingSphere.fromRectangleWithHeights2D( rectangle, projection, minHeight, maxHeight ); let point = import__148.Rectangle.southwest(rectangle).clone(); point.height = minHeight; expectBoundingSphereToContainPoint(boundingSphere, point, projection); point = import__148.Rectangle.southwest(rectangle).clone(); point.height = maxHeight; expectBoundingSphereToContainPoint(boundingSphere, point, projection); point = import__148.Rectangle.northeast(rectangle).clone(); point.height = minHeight; expectBoundingSphereToContainPoint(boundingSphere, point, projection); point = import__148.Rectangle.northeast(rectangle).clone(); point.height = maxHeight; expectBoundingSphereToContainPoint(boundingSphere, point, projection); point = import__148.Rectangle.southeast(rectangle).clone(); point.height = minHeight; expectBoundingSphereToContainPoint(boundingSphere, point, projection); point = import__148.Rectangle.southeast(rectangle).clone(); point.height = maxHeight; expectBoundingSphereToContainPoint(boundingSphere, point, projection); point = import__148.Rectangle.northwest(rectangle).clone(); point.height = minHeight; expectBoundingSphereToContainPoint(boundingSphere, point, projection); point = import__148.Rectangle.northwest(rectangle).clone(); point.height = maxHeight; expectBoundingSphereToContainPoint(boundingSphere, point, projection); point = import__148.Rectangle.center(rectangle).clone(); point.height = minHeight; expectBoundingSphereToContainPoint(boundingSphere, point, projection); point = import__148.Rectangle.center(rectangle).clone(); point.height = maxHeight; expectBoundingSphereToContainPoint(boundingSphere, point, projection); point = new import__148.Cartographic( import__148.Rectangle.center(rectangle).longitude, rectangle.south, minHeight ); expectBoundingSphereToContainPoint(boundingSphere, point, projection); point = new import__148.Cartographic( import__148.Rectangle.center(rectangle).longitude, rectangle.south, maxHeight ); expectBoundingSphereToContainPoint(boundingSphere, point, projection); point = new import__148.Cartographic( import__148.Rectangle.center(rectangle).longitude, rectangle.north, minHeight ); expectBoundingSphereToContainPoint(boundingSphere, point, projection); point = new import__148.Cartographic( import__148.Rectangle.center(rectangle).longitude, rectangle.north, maxHeight ); expectBoundingSphereToContainPoint(boundingSphere, point, projection); point = new import__148.Cartographic( rectangle.west, import__148.Rectangle.center(rectangle).latitude, minHeight ); expectBoundingSphereToContainPoint(boundingSphere, point, projection); point = new import__148.Cartographic( rectangle.west, import__148.Rectangle.center(rectangle).latitude, maxHeight ); expectBoundingSphereToContainPoint(boundingSphere, point, projection); point = new import__148.Cartographic( rectangle.east, import__148.Rectangle.center(rectangle).latitude, minHeight ); expectBoundingSphereToContainPoint(boundingSphere, point, projection); point = new import__148.Cartographic( rectangle.east, import__148.Rectangle.center(rectangle).latitude, maxHeight ); expectBoundingSphereToContainPoint(boundingSphere, point, projection); }); it("computes the volume of a BoundingSphere", function() { const sphere = new import__148.BoundingSphere(new import__148.Cartesian3(), 1); const computedVolume = sphere.volume(); const expectedVolume = 4 / 3 * import__148.Math.PI; expect(computedVolume).toEqualEpsilon(expectedVolume, import__148.Math.EPSILON6); }); createPackableSpecs_default( import__148.BoundingSphere, new import__148.BoundingSphere(new import__148.Cartesian3(1, 2, 3), 4), [1, 2, 3, 4] ); }); // packages/engine/Specs/Core/BoxGeometrySpec.js var import__149 = __toESM(require_Cesium(), 1); describe("Core/BoxGeometry", function() { it("constructor throws without maximum corner", function() { expect(function() { return new import__149.BoxGeometry({ maximum: new import__149.Cartesian3() }); }).toThrowDeveloperError(); }); it("constructor throws without minimum corner", function() { expect(function() { return new import__149.BoxGeometry({ minimum: new import__149.Cartesian3() }); }).toThrowDeveloperError(); }); it("constructor creates optimized number of positions for VertexFormat.POSITIONS_ONLY", function() { const m = import__149.BoxGeometry.createGeometry( new import__149.BoxGeometry({ minimum: new import__149.Cartesian3(-1, -2, -3), maximum: new import__149.Cartesian3(1, 2, 3), vertexFormat: import__149.VertexFormat.POSITION_ONLY }) ); expect(m.attributes.position.values.length).toEqual(8 * 3); expect(m.indices.length).toEqual(12 * 3); }); it("constructor computes all vertex attributes", function() { const minimumCorner = new import__149.Cartesian3(0, 0, 0); const maximumCorner = new import__149.Cartesian3(1, 1, 1); const m = import__149.BoxGeometry.createGeometry( new import__149.BoxGeometry({ minimum: minimumCorner, maximum: maximumCorner, vertexFormat: import__149.VertexFormat.ALL }) ); const numVertices = 24; const numTriangles = 12; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.attributes.normal.values.length).toEqual(numVertices * 3); expect(m.attributes.tangent.values.length).toEqual(numVertices * 3); expect(m.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(m.attributes.st.values.length).toEqual(numVertices * 2); expect(m.indices.length).toEqual(numTriangles * 3); expect(m.boundingSphere.center).toEqual(import__149.Cartesian3.ZERO); expect(m.boundingSphere.radius).toEqual( import__149.Cartesian3.magnitude(maximumCorner) * 0.5 ); }); it("computes offset attribute", function() { const m = import__149.BoxGeometry.createGeometry( new import__149.BoxGeometry({ minimum: new import__149.Cartesian3(-1, -2, -3), maximum: new import__149.Cartesian3(1, 2, 3), vertexFormat: import__149.VertexFormat.POSITION_ONLY, offsetAttribute: import__149.GeometryOffsetAttribute.ALL }) ); const numVertices = 8; expect(m.attributes.position.values.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("fromDimensions throws without dimensions", function() { expect(function() { return import__149.BoxGeometry.fromDimensions(); }).toThrowDeveloperError(); }); it("fromDimensions throws with negative dimensions", function() { expect(function() { return import__149.BoxGeometry.fromDimensions({ dimensions: new import__149.Cartesian3(1, 2, -1) }); }).toThrowDeveloperError(); }); it("fromDimensions", function() { const m = import__149.BoxGeometry.createGeometry( import__149.BoxGeometry.fromDimensions({ dimensions: new import__149.Cartesian3(1, 2, 3), vertexFormat: import__149.VertexFormat.POSITION_ONLY }) ); expect(m.attributes.position.values.length).toEqual(8 * 3); expect(m.indices.length).toEqual(12 * 3); }); it("fromAxisAlignedBoundingBox throws with no boundingBox", function() { expect(function() { return import__149.BoxGeometry.fromAxisAlignedBoundingBox(void 0); }).toThrowDeveloperError(); }); it("fromAxisAlignedBoundingBox", function() { const min = new import__149.Cartesian3(-1, -2, -3); const max = new import__149.Cartesian3(1, 2, 3); const m = import__149.BoxGeometry.fromAxisAlignedBoundingBox( new import__149.AxisAlignedBoundingBox(min, max) ); expect(m._minimum).toEqual(min); expect(m._maximum).toEqual(max); }); it("undefined is returned if min and max are equal", function() { const box = new import__149.BoxGeometry({ vertexFormat: import__149.VertexFormat.POSITION_ONLY, maximum: new import__149.Cartesian3(25e4, 25e4, 25e4), minimum: new import__149.Cartesian3(25e4, 25e4, 25e4) }); const geometry = import__149.BoxGeometry.createGeometry(box); expect(geometry).toBeUndefined(); }); createPackableSpecs_default( import__149.BoxGeometry, new import__149.BoxGeometry({ minimum: new import__149.Cartesian3(1, 2, 3), maximum: new import__149.Cartesian3(4, 5, 6), vertexFormat: import__149.VertexFormat.POSITION_AND_NORMAL }), [1, 2, 3, 4, 5, 6, 1, 1, 0, 0, 0, 0, -1] ); }); // packages/engine/Specs/Core/BoxOutlineGeometrySpec.js var import__150 = __toESM(require_Cesium(), 1); describe("Core/BoxOutlineGeometry", function() { it("constructor throws without maximum corner", function() { expect(function() { return new import__150.BoxOutlineGeometry({ maximum: new import__150.Cartesian3() }); }).toThrowDeveloperError(); }); it("constructor throws without minimum corner", function() { expect(function() { return new import__150.BoxOutlineGeometry({ minimum: new import__150.Cartesian3() }); }).toThrowDeveloperError(); }); it("constructor creates positions", function() { const m = import__150.BoxOutlineGeometry.createGeometry( new import__150.BoxOutlineGeometry({ minimum: new import__150.Cartesian3(-1, -2, -3), maximum: new import__150.Cartesian3(1, 2, 3) }) ); expect(m.attributes.position.values.length).toEqual(8 * 3); expect(m.indices.length).toEqual(12 * 2); }); it("computes offset attribute", function() { const m = import__150.BoxOutlineGeometry.createGeometry( new import__150.BoxOutlineGeometry({ minimum: new import__150.Cartesian3(-1, -2, -3), maximum: new import__150.Cartesian3(1, 2, 3), offsetAttribute: import__150.GeometryOffsetAttribute.ALL }) ); const numVertices = 8; expect(m.attributes.position.values.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("fromDimensions throws without dimensions", function() { expect(function() { return import__150.BoxOutlineGeometry.fromDimensions(); }).toThrowDeveloperError(); }); it("fromDimensions throws with negative dimensions", function() { expect(function() { return import__150.BoxOutlineGeometry.fromDimensions({ dimensions: new import__150.Cartesian3(1, 2, -1) }); }).toThrowDeveloperError(); }); it("fromDimensions", function() { const m = import__150.BoxOutlineGeometry.createGeometry( import__150.BoxOutlineGeometry.fromDimensions({ dimensions: new import__150.Cartesian3(1, 2, 3) }) ); expect(m.attributes.position.values.length).toEqual(8 * 3); expect(m.indices.length).toEqual(12 * 2); }); it("fromAxisAlignedBoundingBox throws with no boundingBox", function() { expect(function() { return import__150.BoxOutlineGeometry.fromAxisAlignedBoundingBox(void 0); }).toThrowDeveloperError(); }); it("fromAxisAlignedBoundingBox", function() { const min = new import__150.Cartesian3(-1, -2, -3); const max = new import__150.Cartesian3(1, 2, 3); const m = import__150.BoxOutlineGeometry.fromAxisAlignedBoundingBox( new import__150.AxisAlignedBoundingBox(min, max) ); expect(m._min).toEqual(min); expect(m._max).toEqual(max); }); it("undefined is returned if min and max are equal", function() { const box = new import__150.BoxOutlineGeometry({ maximum: new import__150.Cartesian3(25e4, 25e4, 25e4), minimum: new import__150.Cartesian3(25e4, 25e4, 25e4) }); const geometry = import__150.BoxOutlineGeometry.createGeometry(box); expect(geometry).toBeUndefined(); }); createPackableSpecs_default( import__150.BoxOutlineGeometry, new import__150.BoxOutlineGeometry({ minimum: new import__150.Cartesian3(1, 2, 3), maximum: new import__150.Cartesian3(4, 5, 6) }), [1, 2, 3, 4, 5, 6, -1] ); }); // packages/engine/Specs/Core/Cartesian2Spec.js var import__151 = __toESM(require_Cesium(), 1); // Specs/createPackableArraySpecs.js var import_engine17 = __toESM(require_Cesium(), 1); function createPackableArraySpecs(packable, unpackedArray, packedArray, stride, namePrefix) { namePrefix = (0, import_engine17.defaultValue)(namePrefix, ""); it(`${namePrefix} can pack`, function() { const actualPackedArray = packable.packArray(unpackedArray); expect(actualPackedArray.length).toEqual(packedArray.length); expect(actualPackedArray).toEqual(packedArray); }); it(`${namePrefix} can roundtrip`, function() { const actualPackedArray = packable.packArray(unpackedArray); const result = packable.unpackArray(actualPackedArray); expect(result).toEqual(unpackedArray); }); it(`${namePrefix} can unpack`, function() { const result = packable.unpackArray(packedArray); expect(result).toEqual(unpackedArray); }); it(`${namePrefix} packArray works with typed arrays`, function() { const typedArray = new Float64Array(packedArray.length); const result = packable.packArray(unpackedArray, typedArray); expect(result).toEqual(new Float64Array(packedArray)); }); it(`${namePrefix} packArray resizes arrays as needed`, function() { const emptyArray = []; let result = packable.packArray(unpackedArray, emptyArray); expect(result).toEqual(packedArray); const largerArray = new Array(packedArray.length + 1).fill(0); result = packable.packArray(unpackedArray, largerArray); expect(result).toEqual(packedArray); }); it(`${namePrefix} packArray throws with undefined array`, function() { expect(function() { packable.packArray(void 0); }).toThrowDeveloperError(); }); it(`${namePrefix} packArray throws for typed arrays of the wrong size`, function() { expect(function() { const tooSmall = new Float64Array(0); packable.packArray(unpackedArray, tooSmall); }).toThrowDeveloperError(); expect(function() { const tooBig = new Float64Array(10); packable.packArray(unpackedArray, tooBig); }).toThrowDeveloperError(); }); it(`${namePrefix} unpackArray works for typed arrays`, function() { const array = packable.unpackArray(new Float64Array(packedArray)); expect(array).toEqual(unpackedArray); }); it(`${namePrefix} unpackArray throws with undefined array`, function() { expect(function() { packable.unpackArray(void 0); }).toThrowDeveloperError(); }); it(`${namePrefix} unpackArray works with a result parameter`, function() { let array = []; let result = packable.unpackArray(packedArray, array); expect(result).toBe(array); expect(result).toEqual(unpackedArray); const PackableClass = packable; array = new Array(unpackedArray.length); for (let i = 0; i < unpackedArray.length; i++) { array[i] = new PackableClass(); } result = packable.unpackArray(packedArray, array); expect(result).toBe(array); expect(result).toEqual(unpackedArray); }); it(`${namePrefix} unpackArray throws with array less than the minimum length`, function() { expect(function() { packable.unpackArray([1]); }).toThrowDeveloperError(); }); it("unpackArray throws with array not multiple of stride", function() { expect(function() { packable.unpackArray(new Array(stride + 1).fill(1)); }).toThrowDeveloperError(); }); } var createPackableArraySpecs_default = createPackableArraySpecs; // packages/engine/Specs/Core/Cartesian2Spec.js describe("Core/Cartesian2", function() { it("construct with default values", function() { const cartesian = new import__151.Cartesian2(); expect(cartesian.x).toEqual(0); expect(cartesian.y).toEqual(0); }); it("construct with only an x value", function() { const cartesian = new import__151.Cartesian2(1); expect(cartesian.x).toEqual(1); expect(cartesian.y).toEqual(0); }); it("construct with all values", function() { const cartesian = new import__151.Cartesian2(1, 2); expect(cartesian.x).toEqual(1); expect(cartesian.y).toEqual(2); }); it("fromArray creates a Cartesian2", function() { let cartesian = new import__151.Cartesian2(); cartesian = import__151.Cartesian2.fromArray([1, 2]); expect(cartesian).toEqual(new import__151.Cartesian2(1, 2)); }); it("fromArray with an offset creates a Cartesian2", function() { let cartesian = new import__151.Cartesian2(); cartesian = import__151.Cartesian2.fromArray([0, 1, 2, 0], 1); expect(cartesian).toEqual(new import__151.Cartesian2(1, 2)); }); it("fromArray throws without values", function() { expect(function() { import__151.Cartesian2.fromArray(); }).toThrowDeveloperError(); }); it("clone with a result parameter", function() { const cartesian = new import__151.Cartesian2(1, 2); const result = new import__151.Cartesian2(); const returnedResult = import__151.Cartesian2.clone(cartesian, result); expect(cartesian).not.toBe(result); expect(result).toBe(returnedResult); expect(cartesian).toEqual(result); }); it("clone works with a result parameter that is an input parameter", function() { const cartesian = new import__151.Cartesian2(1, 2); const returnedResult = import__151.Cartesian2.clone(cartesian, cartesian); expect(cartesian).toBe(returnedResult); }); it("maximumComponent works when X is greater", function() { const cartesian = new import__151.Cartesian2(2, 1); expect(import__151.Cartesian2.maximumComponent(cartesian)).toEqual(cartesian.x); }); it("maximumComponent works when Y is greater", function() { const cartesian = new import__151.Cartesian2(1, 2); expect(import__151.Cartesian2.maximumComponent(cartesian)).toEqual(cartesian.y); }); it("minimumComponent works when X is lesser", function() { const cartesian = new import__151.Cartesian2(1, 2); expect(import__151.Cartesian2.minimumComponent(cartesian)).toEqual(cartesian.x); }); it("minimumComponent works when Y is lesser", function() { const cartesian = new import__151.Cartesian2(2, 1); expect(import__151.Cartesian2.minimumComponent(cartesian)).toEqual(cartesian.y); }); it("minimumByComponent", function() { let first; let second; let expected; const result = new import__151.Cartesian2(); first = new import__151.Cartesian2(2, 0); second = new import__151.Cartesian2(1, 0); expected = new import__151.Cartesian2(1, 0); expect(import__151.Cartesian2.minimumByComponent(first, second, result)).toEqual( expected ); first = new import__151.Cartesian2(1, 0); second = new import__151.Cartesian2(2, 0); expected = new import__151.Cartesian2(1, 0); expect(import__151.Cartesian2.minimumByComponent(first, second, result)).toEqual( expected ); first = new import__151.Cartesian2(2, -15); second = new import__151.Cartesian2(1, -20); expected = new import__151.Cartesian2(1, -20); expect(import__151.Cartesian2.minimumByComponent(first, second, result)).toEqual( expected ); first = new import__151.Cartesian2(2, -20); second = new import__151.Cartesian2(1, -15); expected = new import__151.Cartesian2(1, -20); expect(import__151.Cartesian2.minimumByComponent(first, second, result)).toEqual( expected ); first = new import__151.Cartesian2(2, -15); second = new import__151.Cartesian2(1, -20); expected = new import__151.Cartesian2(1, -20); expect(import__151.Cartesian2.minimumByComponent(first, second, result)).toEqual( expected ); first = new import__151.Cartesian2(2, -15); second = new import__151.Cartesian2(1, -20); expected = new import__151.Cartesian2(1, -20); expect(import__151.Cartesian2.minimumByComponent(first, second, result)).toEqual( expected ); }); it("minimumByComponent with a result parameter", function() { const first = new import__151.Cartesian2(2, 0); const second = new import__151.Cartesian2(1, 0); const expected = new import__151.Cartesian2(1, 0); const result = new import__151.Cartesian2(); const returnedResult = import__151.Cartesian2.minimumByComponent(first, second, result); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expected); }); it("minimumByComponent with a result parameter that is an input parameter", function() { const first = new import__151.Cartesian2(2, 0); const second = new import__151.Cartesian2(1, 0); const expected = new import__151.Cartesian2(1, 0); expect(import__151.Cartesian2.minimumByComponent(first, second, first)).toEqual( expected ); first.x = 1; second.x = 2; expect(import__151.Cartesian2.minimumByComponent(first, second, second)).toEqual( expected ); }); it("minimumByComponent throws without first", function() { expect(function() { import__151.Cartesian2.minimumByComponent(); }).toThrowDeveloperError(); }); it("minimumByComponent throws without second", function() { expect(function() { import__151.Cartesian2.minimumByComponent(new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("minimumByComponent works when first's or second's X is lesser", function() { const first = new import__151.Cartesian2(2, 0); const second = new import__151.Cartesian2(1, 0); const expected = new import__151.Cartesian2(1, 0); expect(import__151.Cartesian2.minimumByComponent(first, second, expected)).toEqual( expected ); second.x = 3; expected.x = 2; expect(import__151.Cartesian2.minimumByComponent(first, second, expected)).toEqual( expected ); }); it("minimumByComponent works when first's or second's Y is lesser", function() { const first = new import__151.Cartesian2(0, 2); const second = new import__151.Cartesian2(0, 1); const expected = new import__151.Cartesian2(0, 1); const result = new import__151.Cartesian2(); expect(import__151.Cartesian2.minimumByComponent(first, second, result)).toEqual( expected ); second.y = 3; expected.y = 2; expect(import__151.Cartesian2.minimumByComponent(first, second, result)).toEqual( expected ); }); it("maximumByComponent", function() { let first; let second; let expected; const result = new import__151.Cartesian2(); first = new import__151.Cartesian2(2, 0); second = new import__151.Cartesian2(1, 0); expected = new import__151.Cartesian2(2, 0); expect(import__151.Cartesian2.maximumByComponent(first, second, result)).toEqual( expected ); first = new import__151.Cartesian2(1, 0); second = new import__151.Cartesian2(2, 0); expected = new import__151.Cartesian2(2, 0); expect(import__151.Cartesian2.maximumByComponent(first, second, result)).toEqual( expected ); first = new import__151.Cartesian2(2, -15); second = new import__151.Cartesian2(1, -20); expected = new import__151.Cartesian2(2, -15); expect(import__151.Cartesian2.maximumByComponent(first, second, result)).toEqual( expected ); first = new import__151.Cartesian2(2, -20); second = new import__151.Cartesian2(1, -15); expected = new import__151.Cartesian2(2, -15); expect(import__151.Cartesian2.maximumByComponent(first, second, result)).toEqual( expected ); first = new import__151.Cartesian2(2, -15); second = new import__151.Cartesian2(1, -20); expected = new import__151.Cartesian2(2, -15); expect(import__151.Cartesian2.maximumByComponent(first, second, result)).toEqual( expected ); first = new import__151.Cartesian2(2, -15); second = new import__151.Cartesian2(1, -20); expected = new import__151.Cartesian2(2, -15); expect(import__151.Cartesian2.maximumByComponent(first, second, result)).toEqual( expected ); }); it("maximumByComponent with a result parameter", function() { const first = new import__151.Cartesian2(2, 0); const second = new import__151.Cartesian2(1, 0); const expected = new import__151.Cartesian2(2, 0); const result = new import__151.Cartesian2(); const returnedResult = import__151.Cartesian2.maximumByComponent(first, second, result); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expected); }); it("maximumByComponent with a result parameter that is an input parameter", function() { const first = new import__151.Cartesian2(2, 0); const second = new import__151.Cartesian2(1, 0); const expected = new import__151.Cartesian2(2, 0); expect(import__151.Cartesian2.maximumByComponent(first, second, first)).toEqual( expected ); first.x = 1; second.x = 2; expect(import__151.Cartesian2.maximumByComponent(first, second, second)).toEqual( expected ); }); it("maximumByComponent throws without first", function() { expect(function() { import__151.Cartesian2.maximumByComponent(); }).toThrowDeveloperError(); }); it("maximumByComponent throws without second", function() { expect(function() { import__151.Cartesian2.maximumByComponent(new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("maximumByComponent works when first's or second's X is greater", function() { const first = new import__151.Cartesian2(2, 0); const second = new import__151.Cartesian2(1, 0); const expected = new import__151.Cartesian2(2, 0); const result = new import__151.Cartesian2(); expect(import__151.Cartesian2.maximumByComponent(first, second, result)).toEqual( expected ); second.x = 3; expected.x = 3; expect(import__151.Cartesian2.maximumByComponent(first, second, result)).toEqual( expected ); }); it("maximumByComponent works when first's or second's Y is greater", function() { const first = new import__151.Cartesian2(0, 2); const second = new import__151.Cartesian2(0, 1); const expected = new import__151.Cartesian2(0, 2); const result = new import__151.Cartesian2(); expect(import__151.Cartesian2.maximumByComponent(first, second, result)).toEqual( expected ); second.y = 3; expected.y = 3; expect(import__151.Cartesian2.maximumByComponent(first, second, result)).toEqual( expected ); }); it("clamp", function() { let value; let min; let max; let expected; const result = new import__151.Cartesian2(); value = new import__151.Cartesian2(-1, 0); min = new import__151.Cartesian2(0, 0); max = new import__151.Cartesian2(1, 1); expected = new import__151.Cartesian2(0, 0); expect(import__151.Cartesian2.clamp(value, min, max, result)).toEqual(expected); value = new import__151.Cartesian2(2, 0); min = new import__151.Cartesian2(0, 0); max = new import__151.Cartesian2(1, 1); expected = new import__151.Cartesian2(1, 0); expect(import__151.Cartesian2.clamp(value, min, max, result)).toEqual(expected); value = new import__151.Cartesian2(0, -1); min = new import__151.Cartesian2(0, 0); max = new import__151.Cartesian2(1, 1); expected = new import__151.Cartesian2(0, 0); expect(import__151.Cartesian2.clamp(value, min, max, result)).toEqual(expected); value = new import__151.Cartesian2(0, 2); min = new import__151.Cartesian2(0, 0); max = new import__151.Cartesian2(1, 1); expected = new import__151.Cartesian2(0, 1); expect(import__151.Cartesian2.clamp(value, min, max, result)).toEqual(expected); value = new import__151.Cartesian2(0, 0); min = new import__151.Cartesian2(0, 0); max = new import__151.Cartesian2(1, 1); expected = new import__151.Cartesian2(0, 0); expect(import__151.Cartesian2.clamp(value, min, max, result)).toEqual(expected); value = new import__151.Cartesian2(0, 0); min = new import__151.Cartesian2(0, 0); max = new import__151.Cartesian2(1, 1); expected = new import__151.Cartesian2(0, 0); expect(import__151.Cartesian2.clamp(value, min, max, result)).toEqual(expected); value = new import__151.Cartesian2(-2, 3); min = new import__151.Cartesian2(0, 0); max = new import__151.Cartesian2(1, 1); expected = new import__151.Cartesian2(0, 1); expect(import__151.Cartesian2.clamp(value, min, max, result)).toEqual(expected); value = new import__151.Cartesian2(0, 0); min = new import__151.Cartesian2(1, 2); max = new import__151.Cartesian2(1, 2); expected = new import__151.Cartesian2(1, 2); expect(import__151.Cartesian2.clamp(value, min, max, result)).toEqual(expected); }); it("clamp with a result parameter", function() { const value = new import__151.Cartesian2(-1, -1); const min = new import__151.Cartesian2(0, 0); const max = new import__151.Cartesian2(1, 1); const expected = new import__151.Cartesian2(0, 0); const result = new import__151.Cartesian2(); const returnedResult = import__151.Cartesian2.clamp(value, min, max, result); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expected); }); it("clamp with a result parameter that is an input parameter", function() { const value = new import__151.Cartesian2(-1, -1); const min = new import__151.Cartesian2(0, 0); const max = new import__151.Cartesian2(1, 1); const expected = new import__151.Cartesian2(0, 0); expect(import__151.Cartesian2.clamp(value, min, max, value)).toEqual(expected); import__151.Cartesian2.fromElements(-1, -1, value); expect(import__151.Cartesian2.clamp(value, min, max, min)).toEqual(expected); import__151.Cartesian2.fromElements(0, 0, value); expect(import__151.Cartesian2.clamp(value, min, max, max)).toEqual(expected); }); it("clamp throws without value", function() { expect(function() { import__151.Cartesian2.clamp(); }).toThrowDeveloperError(); }); it("clamp throws without min", function() { expect(function() { import__151.Cartesian2.clamp(new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("clamp throws without max", function() { expect(function() { import__151.Cartesian2.clamp(new import__151.Cartesian2(), new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("magnitudeSquared", function() { const cartesian = new import__151.Cartesian2(2, 3); expect(import__151.Cartesian2.magnitudeSquared(cartesian)).toEqual(13); }); it("magnitude", function() { const cartesian = new import__151.Cartesian2(2, 3); expect(import__151.Cartesian2.magnitude(cartesian)).toEqual(Math.sqrt(13)); }); it("distance", function() { const distance = import__151.Cartesian2.distance( new import__151.Cartesian2(1, 0), new import__151.Cartesian2(2, 0) ); expect(distance).toEqual(1); }); it("distance throws without left", function() { expect(function() { import__151.Cartesian2.distance(); }).toThrowDeveloperError(); }); it("distance throws without right", function() { expect(function() { import__151.Cartesian2.distance(import__151.Cartesian2.UNIT_X); }).toThrowDeveloperError(); }); it("distanceSquared", function() { const distanceSquared = import__151.Cartesian2.distanceSquared( new import__151.Cartesian2(1, 0), new import__151.Cartesian2(3, 0) ); expect(distanceSquared).toEqual(4); }); it("distanceSquared throws without left", function() { expect(function() { import__151.Cartesian2.distanceSquared(); }).toThrowDeveloperError(); }); it("distanceSquared throws without right", function() { expect(function() { import__151.Cartesian2.distanceSquared(import__151.Cartesian2.UNIT_X); }).toThrowDeveloperError(); }); it("normalize works with a result parameter", function() { const cartesian = new import__151.Cartesian2(2, 0); const expectedResult = new import__151.Cartesian2(1, 0); const result = new import__151.Cartesian2(); const returnedResult = import__151.Cartesian2.normalize(cartesian, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("normalize works with a result parameter that is an input parameter", function() { const cartesian = new import__151.Cartesian2(2, 0); const expectedResult = new import__151.Cartesian2(1, 0); const returnedResult = import__151.Cartesian2.normalize(cartesian, cartesian); expect(cartesian).toBe(returnedResult); expect(cartesian).toEqual(expectedResult); }); it("normalize throws with zero vector", function() { expect(function() { import__151.Cartesian2.normalize(import__151.Cartesian2.ZERO, new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("multiplyComponents works with a result parameter", function() { const left = new import__151.Cartesian2(2, 3); const right = new import__151.Cartesian2(4, 5); const result = new import__151.Cartesian2(); const expectedResult = new import__151.Cartesian2(8, 15); const returnedResult = import__151.Cartesian2.multiplyComponents(left, right, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("multiplyComponents works with a result parameter that is an input parameter", function() { const left = new import__151.Cartesian2(2, 3); const right = new import__151.Cartesian2(4, 5); const expectedResult = new import__151.Cartesian2(8, 15); const returnedResult = import__151.Cartesian2.multiplyComponents(left, right, left); expect(left).toBe(returnedResult); expect(left).toEqual(expectedResult); }); it("divideComponents works with a result parameter", function() { const left = new import__151.Cartesian2(2, 3); const right = new import__151.Cartesian2(4, 5); const result = new import__151.Cartesian2(); const expectedResult = new import__151.Cartesian2(0.5, 0.6); const returnedResult = import__151.Cartesian2.divideComponents(left, right, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("divideComponents works with a result parameter that is an input parameter", function() { const left = new import__151.Cartesian2(2, 3); const right = new import__151.Cartesian2(4, 5); const expectedResult = new import__151.Cartesian2(0.5, 0.6); const returnedResult = import__151.Cartesian2.divideComponents(left, right, left); expect(left).toBe(returnedResult); expect(left).toEqual(expectedResult); }); it("dot", function() { const left = new import__151.Cartesian2(2, 3); const right = new import__151.Cartesian2(4, 5); const expectedResult = 23; const result = import__151.Cartesian2.dot(left, right); expect(result).toEqual(expectedResult); }); it("cross", function() { const left = new import__151.Cartesian2(0, 1); const right = new import__151.Cartesian2(1, 0); const expectedResult = -1; const result = import__151.Cartesian2.cross(left, right); expect(result).toEqual(expectedResult); }); it("add works with a result parameter", function() { const left = new import__151.Cartesian2(2, 3); const right = new import__151.Cartesian2(4, 5); const result = new import__151.Cartesian2(); const expectedResult = new import__151.Cartesian2(6, 8); const returnedResult = import__151.Cartesian2.add(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expectedResult); }); it("add works with a result parameter that is an input parameter", function() { const left = new import__151.Cartesian2(2, 3); const right = new import__151.Cartesian2(4, 5); const expectedResult = new import__151.Cartesian2(6, 8); const returnedResult = import__151.Cartesian2.add(left, right, left); expect(returnedResult).toBe(left); expect(left).toEqual(expectedResult); }); it("subtract works with a result parameter", function() { const left = new import__151.Cartesian2(2, 3); const right = new import__151.Cartesian2(1, 5); const result = new import__151.Cartesian2(); const expectedResult = new import__151.Cartesian2(1, -2); const returnedResult = import__151.Cartesian2.subtract(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expectedResult); }); it("subtract works with this result parameter", function() { const left = new import__151.Cartesian2(2, 3); const right = new import__151.Cartesian2(1, 5); const expectedResult = new import__151.Cartesian2(1, -2); const returnedResult = import__151.Cartesian2.subtract(left, right, left); expect(returnedResult).toBe(left); expect(left).toEqual(expectedResult); }); it("multiplyByScalar with a result parameter", function() { const cartesian = new import__151.Cartesian2(1, 2); const result = new import__151.Cartesian2(); const scalar = 2; const expectedResult = new import__151.Cartesian2(2, 4); const returnedResult = import__151.Cartesian2.multiplyByScalar( cartesian, scalar, result ); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("multiplyByScalar with a result parameter that is an input parameter", function() { const cartesian = new import__151.Cartesian2(1, 2); const scalar = 2; const expectedResult = new import__151.Cartesian2(2, 4); const returnedResult = import__151.Cartesian2.multiplyByScalar( cartesian, scalar, cartesian ); expect(cartesian).toBe(returnedResult); expect(cartesian).toEqual(expectedResult); }); it("divideByScalar with a result parameter", function() { const cartesian = new import__151.Cartesian2(1, 2); const result = new import__151.Cartesian2(); const scalar = 2; const expectedResult = new import__151.Cartesian2(0.5, 1); const returnedResult = import__151.Cartesian2.divideByScalar(cartesian, scalar, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("divideByScalar with a result parameter that is an input parameter", function() { const cartesian = new import__151.Cartesian2(1, 2); const scalar = 2; const expectedResult = new import__151.Cartesian2(0.5, 1); const returnedResult = import__151.Cartesian2.divideByScalar( cartesian, scalar, cartesian ); expect(cartesian).toBe(returnedResult); expect(cartesian).toEqual(expectedResult); }); it("negate with a result parameter", function() { const cartesian = new import__151.Cartesian2(1, -2); const result = new import__151.Cartesian2(); const expectedResult = new import__151.Cartesian2(-1, 2); const returnedResult = import__151.Cartesian2.negate(cartesian, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("negate with a result parameter that is an input parameter", function() { const cartesian = new import__151.Cartesian2(1, -2); const expectedResult = new import__151.Cartesian2(-1, 2); const returnedResult = import__151.Cartesian2.negate(cartesian, cartesian); expect(cartesian).toBe(returnedResult); expect(cartesian).toEqual(expectedResult); }); it("abs with a result parameter", function() { const cartesian = new import__151.Cartesian2(1, -2); const result = new import__151.Cartesian2(); const expectedResult = new import__151.Cartesian2(1, 2); const returnedResult = import__151.Cartesian2.abs(cartesian, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("abs with a result parameter that is an input parameter", function() { const cartesian = new import__151.Cartesian2(1, -2); const expectedResult = new import__151.Cartesian2(1, 2); const returnedResult = import__151.Cartesian2.abs(cartesian, cartesian); expect(cartesian).toBe(returnedResult); expect(cartesian).toEqual(expectedResult); }); it("lerp works with a result parameter", function() { const start = new import__151.Cartesian2(4, 8); const end = new import__151.Cartesian2(8, 20); const t = 0.25; const result = new import__151.Cartesian2(); const expectedResult = new import__151.Cartesian2(5, 11); const returnedResult = import__151.Cartesian2.lerp(start, end, t, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("lerp works with a result parameter that is an input parameter", function() { const start = new import__151.Cartesian2(4, 8); const end = new import__151.Cartesian2(8, 20); const t = 0.25; const expectedResult = new import__151.Cartesian2(5, 11); const returnedResult = import__151.Cartesian2.lerp(start, end, t, start); expect(start).toBe(returnedResult); expect(start).toEqual(expectedResult); }); it("lerp extrapolate forward", function() { const start = new import__151.Cartesian2(4, 8); const end = new import__151.Cartesian2(8, 20); const t = 2; const expectedResult = new import__151.Cartesian2(12, 32); const result = import__151.Cartesian2.lerp(start, end, t, new import__151.Cartesian2()); expect(result).toEqual(expectedResult); }); it("lerp extrapolate backward", function() { const start = new import__151.Cartesian2(4, 8); const end = new import__151.Cartesian2(8, 20); const t = -1; const expectedResult = new import__151.Cartesian2(0, -4); const result = import__151.Cartesian2.lerp(start, end, t, new import__151.Cartesian2()); expect(result).toEqual(expectedResult); }); it("angleBetween works for right angles", function() { const x = import__151.Cartesian2.UNIT_X; const y = import__151.Cartesian2.UNIT_Y; expect(import__151.Cartesian2.angleBetween(x, y)).toEqual(import__151.Math.PI_OVER_TWO); expect(import__151.Cartesian2.angleBetween(y, x)).toEqual(import__151.Math.PI_OVER_TWO); }); it("angleBetween works for acute angles", function() { const x = new import__151.Cartesian2(0, 1); const y = new import__151.Cartesian2(1, 1); expect(import__151.Cartesian2.angleBetween(x, y)).toEqualEpsilon( import__151.Math.PI_OVER_FOUR, import__151.Math.EPSILON14 ); expect(import__151.Cartesian2.angleBetween(y, x)).toEqualEpsilon( import__151.Math.PI_OVER_FOUR, import__151.Math.EPSILON14 ); }); it("angleBetween works for obtuse angles", function() { const x = new import__151.Cartesian2(0, 1); const y = new import__151.Cartesian2(-1, -1); expect(import__151.Cartesian2.angleBetween(x, y)).toEqualEpsilon( import__151.Math.PI * 3 / 4, import__151.Math.EPSILON14 ); expect(import__151.Cartesian2.angleBetween(y, x)).toEqualEpsilon( import__151.Math.PI * 3 / 4, import__151.Math.EPSILON14 ); }); it("angleBetween works for zero angles", function() { const x = import__151.Cartesian2.UNIT_X; expect(import__151.Cartesian2.angleBetween(x, x)).toEqual(0); }); it("most orthogonal angle is x", function() { const v = new import__151.Cartesian2(0, 1); expect(import__151.Cartesian2.mostOrthogonalAxis(v, new import__151.Cartesian2())).toEqual( import__151.Cartesian2.UNIT_X ); }); it("most orthogonal angle is y", function() { const v = new import__151.Cartesian2(1, 0); expect(import__151.Cartesian2.mostOrthogonalAxis(v, new import__151.Cartesian2())).toEqual( import__151.Cartesian2.UNIT_Y ); }); it("equals", function() { const cartesian = new import__151.Cartesian2(1, 2); expect(import__151.Cartesian2.equals(cartesian, new import__151.Cartesian2(1, 2))).toEqual( true ); expect(import__151.Cartesian2.equals(cartesian, new import__151.Cartesian2(2, 2))).toEqual( false ); expect(import__151.Cartesian2.equals(cartesian, new import__151.Cartesian2(2, 1))).toEqual( false ); expect(import__151.Cartesian2.equals(cartesian, void 0)).toEqual(false); }); it("equalsEpsilon", function() { let cartesian = new import__151.Cartesian2(1, 2); expect(cartesian.equalsEpsilon(new import__151.Cartesian2(1, 2), 0)).toEqual( true ); expect(cartesian.equalsEpsilon(new import__151.Cartesian2(1, 2), 1)).toEqual( true ); expect(cartesian.equalsEpsilon(new import__151.Cartesian2(2, 2), 1)).toEqual( true ); expect(cartesian.equalsEpsilon(new import__151.Cartesian2(1, 3), 1)).toEqual( true ); expect( cartesian.equalsEpsilon(new import__151.Cartesian2(1, 3), import__151.Math.EPSILON6) ).toEqual(false); expect(cartesian.equalsEpsilon(void 0, 1)).toEqual(false); cartesian = new import__151.Cartesian2(3e6, 4e6); expect( cartesian.equalsEpsilon(new import__151.Cartesian2(3e6, 4e6), 0) ).toEqual(true); expect( cartesian.equalsEpsilon( new import__151.Cartesian2(3e6, 40000002e-1), import__151.Math.EPSILON7 ) ).toEqual(true); expect( cartesian.equalsEpsilon( new import__151.Cartesian2(30000002e-1, 4e6), import__151.Math.EPSILON7 ) ).toEqual(true); expect( cartesian.equalsEpsilon( new import__151.Cartesian2(30000002e-1, 40000002e-1), import__151.Math.EPSILON7 ) ).toEqual(true); expect( cartesian.equalsEpsilon( new import__151.Cartesian2(30000002e-1, 40000002e-1), import__151.Math.EPSILON9 ) ).toEqual(false); expect(cartesian.equalsEpsilon(void 0, 1)).toEqual(false); expect(import__151.Cartesian2.equalsEpsilon(void 0, cartesian, 1)).toEqual(false); }); it("toString", function() { const cartesian = new import__151.Cartesian2(1.123, 2.345); expect(cartesian.toString()).toEqual("(1.123, 2.345)"); }); it("clone returns undefined with no parameter", function() { expect(import__151.Cartesian2.clone()).toBeUndefined(); }); it("maximumComponent throws with no parameter", function() { expect(function() { import__151.Cartesian2.maximumComponent(); }).toThrowDeveloperError(); }); it("minimumComponent throws with no parameter", function() { expect(function() { import__151.Cartesian2.minimumComponent(); }).toThrowDeveloperError(); }); it("magnitudeSquared throws with no parameter", function() { expect(function() { import__151.Cartesian2.magnitudeSquared(); }).toThrowDeveloperError(); }); it("magnitude throws with no parameter", function() { expect(function() { import__151.Cartesian2.magnitude(); }).toThrowDeveloperError(); }); it("normalize throws with no parameter", function() { expect(function() { import__151.Cartesian2.normalize(); }).toThrowDeveloperError(); }); it("dot throws with no left parameter", function() { expect(function() { import__151.Cartesian2.dot(void 0, new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("dot throws with no right parameter", function() { expect(function() { import__151.Cartesian2.dot(new import__151.Cartesian2(), void 0); }).toThrowDeveloperError(); }); it("multiplyComponents throw with no left parameter", function() { const right = new import__151.Cartesian2(4, 5); expect(function() { import__151.Cartesian2.multiplyComponents(void 0, right); }).toThrowDeveloperError(); }); it("multiplyComponents throw with no right parameter", function() { const left = new import__151.Cartesian2(4, 5); expect(function() { import__151.Cartesian2.multiplyComponents(left, void 0); }).toThrowDeveloperError(); }); it("divideComponents throw with no left parameter", function() { const right = new import__151.Cartesian2(4, 5); expect(function() { import__151.Cartesian2.divideComponents(void 0, right); }).toThrowDeveloperError(); }); it("divideComponents throw with no right parameter", function() { const left = new import__151.Cartesian2(4, 5); expect(function() { import__151.Cartesian2.divideComponents(left, void 0); }).toThrowDeveloperError(); }); it("add throws with no left parameter", function() { expect(function() { import__151.Cartesian2.add(void 0, new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("add throws with no right parameter", function() { expect(function() { import__151.Cartesian2.add(new import__151.Cartesian2(), void 0); }).toThrowDeveloperError(); }); it("subtract throws with no left parameter", function() { expect(function() { import__151.Cartesian2.subtract(void 0, new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("subtract throws with no right parameter", function() { expect(function() { import__151.Cartesian2.subtract(new import__151.Cartesian2(), void 0); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with no cartesian parameter", function() { expect(function() { import__151.Cartesian2.multiplyByScalar(void 0, 2); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with no scalar parameter", function() { expect(function() { import__151.Cartesian2.multiplyByScalar(new import__151.Cartesian2(), void 0); }).toThrowDeveloperError(); }); it("divideByScalar throws with no cartesian parameter", function() { expect(function() { import__151.Cartesian2.divideByScalar(void 0, 2); }).toThrowDeveloperError(); }); it("divideByScalar throws with no scalar parameter", function() { expect(function() { import__151.Cartesian2.divideByScalar(new import__151.Cartesian2(), void 0); }).toThrowDeveloperError(); }); it("negate throws with no cartesian parameter", function() { expect(function() { import__151.Cartesian2.negate(void 0); }).toThrowDeveloperError(); }); it("abs throws with no cartesian parameter", function() { expect(function() { import__151.Cartesian2.abs(void 0); }).toThrowDeveloperError(); }); it("lerp throws with no start parameter", function() { const end = new import__151.Cartesian2(8, 20); const t = 0.25; expect(function() { import__151.Cartesian2.lerp(void 0, end, t); }).toThrowDeveloperError(); }); it("lerp throws with no end parameter", function() { const start = new import__151.Cartesian2(4, 8); const t = 0.25; expect(function() { import__151.Cartesian2.lerp(start, void 0, t); }).toThrowDeveloperError(); }); it("lerp throws with no t parameter", function() { const start = new import__151.Cartesian2(4, 8); const end = new import__151.Cartesian2(8, 20); expect(function() { import__151.Cartesian2.lerp(start, end, void 0); }).toThrowDeveloperError(); }); it("angleBetween throws with no left parameter", function() { const right = new import__151.Cartesian2(8, 20); expect(function() { import__151.Cartesian2.angleBetween(void 0, right); }).toThrowDeveloperError(); }); it("angleBetween throws with no right parameter", function() { const left = new import__151.Cartesian2(4, 8); expect(function() { import__151.Cartesian2.angleBetween(left, void 0); }).toThrowDeveloperError(); }); it("mostOrthogonalAxis throws with no cartesian parameter", function() { expect(function() { import__151.Cartesian2.mostOrthogonalAxis(void 0); }).toThrowDeveloperError(); }); it("fromElements returns a cartesian2 with corrrect coordinates", function() { const cartesian2 = import__151.Cartesian2.fromElements(2, 2); const expectedResult = new import__151.Cartesian2(2, 2); expect(cartesian2).toEqual(expectedResult); }); it("fromElements result param returns cartesian2 with correct coordinates", function() { const cartesian2 = new import__151.Cartesian2(); import__151.Cartesian2.fromElements(2, 2, cartesian2); const expectedResult = new import__151.Cartesian2(2, 2); expect(cartesian2).toEqual(expectedResult); }); it("minimumByComponent throws with no result", function() { expect(function() { import__151.Cartesian2.minimumByComponent(new import__151.Cartesian2(), new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("maximumByComponent throws with no result", function() { expect(function() { import__151.Cartesian2.maximumByComponent(new import__151.Cartesian2(), new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("clamp throws with no result", function() { expect(function() { import__151.Cartesian2.clamp(new import__151.Cartesian2(), new import__151.Cartesian2(), new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("normalize throws with no result", function() { expect(function() { import__151.Cartesian2.normalize(new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("multiplyComponents throws with no result", function() { expect(function() { import__151.Cartesian2.multiplyComponents(new import__151.Cartesian2(), new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("divideComponents throws with no result", function() { expect(function() { import__151.Cartesian2.divideComponents(new import__151.Cartesian2(), new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("add throws with no result", function() { expect(function() { import__151.Cartesian2.add(new import__151.Cartesian2(), new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("subtact throws with no result", function() { expect(function() { import__151.Cartesian2.subtract(new import__151.Cartesian2(), new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with no result", function() { expect(function() { import__151.Cartesian2.multiplyByScalar(new import__151.Cartesian2(), 2); }).toThrowDeveloperError(); }); it("divideByScalar throws with no result", function() { expect(function() { import__151.Cartesian2.divideByScalar(new import__151.Cartesian2(), 2); }).toThrowDeveloperError(); }); it("negate throws with no result", function() { expect(function() { import__151.Cartesian2.negate(new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("abs throws with no result", function() { expect(function() { import__151.Cartesian2.abs(new import__151.Cartesian2()); }).toThrowDeveloperError(); }); it("lerp throws with no result", function() { expect(function() { import__151.Cartesian2.lerp(new import__151.Cartesian2(), new import__151.Cartesian2(), 10); }).toThrowDeveloperError(); }); it("mostOrthogonalAxis throws with no result", function() { expect(function() { import__151.Cartesian2.mostOrthogonalAxis(new import__151.Cartesian2()); }).toThrowDeveloperError(); }); createPackableSpecs_default(import__151.Cartesian2, new import__151.Cartesian2(1, 2), [1, 2]); createPackableArraySpecs_default( import__151.Cartesian2, [new import__151.Cartesian2(1, 2), new import__151.Cartesian2(3, 4)], [1, 2, 3, 4], 2 ); }); // packages/engine/Specs/Core/Cartesian3Spec.js var import__152 = __toESM(require_Cesium(), 1); var import__153 = __toESM(require_Cesium(), 1); describe("Core/Cartesian3", function() { it("construct with default values", function() { const cartesian2 = new import__152.Cartesian3(); expect(cartesian2.x).toEqual(0); expect(cartesian2.y).toEqual(0); expect(cartesian2.z).toEqual(0); }); it("construct with all values", function() { const cartesian2 = new import__152.Cartesian3(1, 2, 3); expect(cartesian2.x).toEqual(1); expect(cartesian2.y).toEqual(2); expect(cartesian2.z).toEqual(3); }); const fortyFiveDegrees = Math.PI / 4; const sixtyDegrees = Math.PI / 3; const cartesian = new import__152.Cartesian3(1, Math.sqrt(3), -2); const spherical = { clock: sixtyDegrees, cone: fortyFiveDegrees + Math.PI / 2, magnitude: Math.sqrt(8) }; it("convert Spherical to an existing Cartesian3 instance", function() { const existing = new import__152.Cartesian3(); expect(cartesian).toEqualEpsilon( import__152.Cartesian3.fromSpherical(spherical, existing), import__153.Math.EPSILON15 ); expect(cartesian).toEqualEpsilon(existing, import__153.Math.EPSILON15); }); it("fromArray with an offset creates a Cartesian3", function() { const cartesian2 = import__152.Cartesian3.fromArray([0, 1, 2, 3, 0], 1); expect(cartesian2).toEqual(new import__152.Cartesian3(1, 2, 3)); }); it("fromArray creates a Cartesian3 with a result parameter", function() { const cartesian2 = new import__152.Cartesian3(); const result = import__152.Cartesian3.fromArray([1, 2, 3], 0, cartesian2); expect(result).toBe(cartesian2); expect(result).toEqual(new import__152.Cartesian3(1, 2, 3)); }); it("fromArray throws without values", function() { expect(function() { import__152.Cartesian3.fromArray(); }).toThrowDeveloperError(); }); it("clone with a result parameter", function() { const cartesian2 = new import__152.Cartesian3(1, 2, 3); const result = new import__152.Cartesian3(); const returnedResult = import__152.Cartesian3.clone(cartesian2, result); expect(cartesian2).not.toBe(result); expect(result).toBe(returnedResult); expect(cartesian2).toEqual(result); }); it("clone works with a result parameter that is an input parameter", function() { const cartesian2 = new import__152.Cartesian3(1, 2, 3); const returnedResult = import__152.Cartesian3.clone(cartesian2, cartesian2); expect(cartesian2).toBe(returnedResult); }); it("maximumComponent works when X is greater", function() { const cartesian2 = new import__152.Cartesian3(2, 1, 0); expect(import__152.Cartesian3.maximumComponent(cartesian2)).toEqual(cartesian2.x); }); it("maximumComponent works when Y is greater", function() { const cartesian2 = new import__152.Cartesian3(1, 2, 0); expect(import__152.Cartesian3.maximumComponent(cartesian2)).toEqual(cartesian2.y); }); it("maximumComponent works when Z is greater", function() { const cartesian2 = new import__152.Cartesian3(1, 2, 3); expect(import__152.Cartesian3.maximumComponent(cartesian2)).toEqual(cartesian2.z); }); it("minimumComponent works when X is lesser", function() { const cartesian2 = new import__152.Cartesian3(1, 2, 3); expect(import__152.Cartesian3.minimumComponent(cartesian2)).toEqual(cartesian2.x); }); it("minimumComponent works when Y is lesser", function() { const cartesian2 = new import__152.Cartesian3(2, 1, 3); expect(import__152.Cartesian3.minimumComponent(cartesian2)).toEqual(cartesian2.y); }); it("minimumComponent works when Z is lesser", function() { const cartesian2 = new import__152.Cartesian3(2, 1, 0); expect(import__152.Cartesian3.minimumComponent(cartesian2)).toEqual(cartesian2.z); }); it("minimumByComponent", function() { let first; let second; let expected; const result = new import__152.Cartesian3(); first = new import__152.Cartesian3(2, 0, 0); second = new import__152.Cartesian3(1, 0, 0); expected = new import__152.Cartesian3(1, 0, 0); expect(import__152.Cartesian3.minimumByComponent(first, second, result)).toEqual( expected ); first = new import__152.Cartesian3(1, 0, 0); second = new import__152.Cartesian3(2, 0, 0); expected = new import__152.Cartesian3(1, 0, 0); expect(import__152.Cartesian3.minimumByComponent(first, second, result)).toEqual( expected ); first = new import__152.Cartesian3(2, -15, 0); second = new import__152.Cartesian3(1, -20, 0); expected = new import__152.Cartesian3(1, -20, 0); expect(import__152.Cartesian3.minimumByComponent(first, second, result)).toEqual( expected ); first = new import__152.Cartesian3(2, -20, 0); second = new import__152.Cartesian3(1, -15, 0); expected = new import__152.Cartesian3(1, -20, 0); expect(import__152.Cartesian3.minimumByComponent(first, second, result)).toEqual( expected ); first = new import__152.Cartesian3(2, -15, 26.4); second = new import__152.Cartesian3(1, -20, 26.5); expected = new import__152.Cartesian3(1, -20, 26.4); expect(import__152.Cartesian3.minimumByComponent(first, second, result)).toEqual( expected ); first = new import__152.Cartesian3(2, -15, 26.5); second = new import__152.Cartesian3(1, -20, 26.4); expected = new import__152.Cartesian3(1, -20, 26.4); expect(import__152.Cartesian3.minimumByComponent(first, second, result)).toEqual( expected ); }); it("minimumByComponent with a result parameter", function() { const first = new import__152.Cartesian3(2, 0, 0); const second = new import__152.Cartesian3(1, 0, 0); const expected = new import__152.Cartesian3(1, 0, 0); const result = new import__152.Cartesian3(); const returnedResult = import__152.Cartesian3.minimumByComponent(first, second, result); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expected); }); it("minimumByComponent with a result parameter that is an input parameter", function() { const first = new import__152.Cartesian3(2, 0, 0); const second = new import__152.Cartesian3(1, 0, 0); const expected = new import__152.Cartesian3(1, 0, 0); expect(import__152.Cartesian3.minimumByComponent(first, second, first)).toEqual( expected ); first.x = 1; second.x = 2; expect(import__152.Cartesian3.minimumByComponent(first, second, second)).toEqual( expected ); }); it("minimumByComponent throws without first", function() { expect(function() { import__152.Cartesian3.minimumByComponent(); }).toThrowDeveloperError(); }); it("minimumByComponent throws without second", function() { expect(function() { import__152.Cartesian3.minimumByComponent(new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("minimumByComponent works when first's or second's X is lesser", function() { const first = new import__152.Cartesian3(2, 0, 0); const second = new import__152.Cartesian3(1, 0, 0); const expected = new import__152.Cartesian3(1, 0, 0); const result = new import__152.Cartesian3(); expect(import__152.Cartesian3.minimumByComponent(first, second, result)).toEqual( expected ); second.x = 3; expected.x = 2; expect(import__152.Cartesian3.minimumByComponent(first, second, result)).toEqual( expected ); }); it("minimumByComponent works when first's or second's Y is lesser", function() { const first = new import__152.Cartesian3(0, 2, 0); const second = new import__152.Cartesian3(0, 1, 0); const expected = new import__152.Cartesian3(0, 1, 0); const result = new import__152.Cartesian3(); expect(import__152.Cartesian3.minimumByComponent(first, second, result)).toEqual( expected ); second.y = 3; expected.y = 2; expect(import__152.Cartesian3.minimumByComponent(first, second, result)).toEqual( expected ); }); it("minimumByComponent works when first's or second's Z is lesser", function() { const first = new import__152.Cartesian3(0, 0, 2); const second = new import__152.Cartesian3(0, 0, 1); const expected = new import__152.Cartesian3(0, 0, 1); const result = new import__152.Cartesian3(); expect(import__152.Cartesian3.minimumByComponent(first, second, result)).toEqual( expected ); second.z = 3; expected.z = 2; expect(import__152.Cartesian3.minimumByComponent(first, second, result)).toEqual( expected ); }); it("maximumByComponent", function() { let first; let second; let expected; const result = new import__152.Cartesian3(); first = new import__152.Cartesian3(2, 0, 0); second = new import__152.Cartesian3(1, 0, 0); expected = new import__152.Cartesian3(2, 0, 0); expect(import__152.Cartesian3.maximumByComponent(first, second, result)).toEqual( expected ); first = new import__152.Cartesian3(1, 0, 0); second = new import__152.Cartesian3(2, 0, 0); expected = new import__152.Cartesian3(2, 0, 0); expect(import__152.Cartesian3.maximumByComponent(first, second, result)).toEqual( expected ); first = new import__152.Cartesian3(2, -15, 0); second = new import__152.Cartesian3(1, -20, 0); expected = new import__152.Cartesian3(2, -15, 0); expect(import__152.Cartesian3.maximumByComponent(first, second, result)).toEqual( expected ); first = new import__152.Cartesian3(2, -20, 0); second = new import__152.Cartesian3(1, -15, 0); expected = new import__152.Cartesian3(2, -15, 0); expect(import__152.Cartesian3.maximumByComponent(first, second, result)).toEqual( expected ); first = new import__152.Cartesian3(2, -15, 26.4); second = new import__152.Cartesian3(1, -20, 26.5); expected = new import__152.Cartesian3(2, -15, 26.5); expect(import__152.Cartesian3.maximumByComponent(first, second, result)).toEqual( expected ); first = new import__152.Cartesian3(2, -15, 26.5); second = new import__152.Cartesian3(1, -20, 26.4); expected = new import__152.Cartesian3(2, -15, 26.5); expect(import__152.Cartesian3.maximumByComponent(first, second, result)).toEqual( expected ); }); it("maximumByComponent with a result parameter", function() { const first = new import__152.Cartesian3(2, 0, 0); const second = new import__152.Cartesian3(1, 0, 0); const expected = new import__152.Cartesian3(2, 0, 0); const result = new import__152.Cartesian3(); const returnedResult = import__152.Cartesian3.maximumByComponent(first, second, result); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expected); }); it("maximumByComponent with a result parameter that is an input parameter", function() { const first = new import__152.Cartesian3(2, 0, 0); const second = new import__152.Cartesian3(1, 0, 0); const expected = new import__152.Cartesian3(2, 0, 0); expect(import__152.Cartesian3.maximumByComponent(first, second, first)).toEqual( expected ); first.x = 1; second.x = 2; expect(import__152.Cartesian3.maximumByComponent(first, second, second)).toEqual( expected ); }); it("maximumByComponent throws without first", function() { expect(function() { import__152.Cartesian3.maximumByComponent(); }).toThrowDeveloperError(); }); it("maximumByComponent throws without second", function() { expect(function() { import__152.Cartesian3.maximumByComponent(new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("maximumByComponent works when first's or second's X is greater", function() { const first = new import__152.Cartesian3(2, 0, 0); const second = new import__152.Cartesian3(1, 0, 0); const expected = new import__152.Cartesian3(2, 0, 0); const result = new import__152.Cartesian3(); expect(import__152.Cartesian3.maximumByComponent(first, second, result)).toEqual( expected ); second.x = 3; expected.x = 3; expect(import__152.Cartesian3.maximumByComponent(first, second, result)).toEqual( expected ); }); it("maximumByComponent works when first's or second's Y is greater", function() { const first = new import__152.Cartesian3(0, 2, 0); const second = new import__152.Cartesian3(0, 1, 0); const expected = new import__152.Cartesian3(0, 2, 0); const result = new import__152.Cartesian3(); expect(import__152.Cartesian3.maximumByComponent(first, second, result)).toEqual( expected ); second.y = 3; expected.y = 3; expect(import__152.Cartesian3.maximumByComponent(first, second, result)).toEqual( expected ); }); it("maximumByComponent works when first's or second's Z is greater", function() { const first = new import__152.Cartesian3(0, 0, 2); const second = new import__152.Cartesian3(0, 0, 1); const expected = new import__152.Cartesian3(0, 0, 2); const result = new import__152.Cartesian3(); expect(import__152.Cartesian3.maximumByComponent(first, second, result)).toEqual( expected ); second.z = 3; expected.z = 3; expect(import__152.Cartesian3.maximumByComponent(first, second, result)).toEqual( expected ); }); it("clamp", function() { let value; let min; let max; let expected; const result = new import__152.Cartesian3(); value = new import__152.Cartesian3(-1, 0, 0); min = new import__152.Cartesian3(0, 0, 0); max = new import__152.Cartesian3(1, 1, 1); expected = new import__152.Cartesian3(0, 0, 0); expect(import__152.Cartesian3.clamp(value, min, max, result)).toEqual(expected); value = new import__152.Cartesian3(2, 0, 0); min = new import__152.Cartesian3(0, 0, 0); max = new import__152.Cartesian3(1, 1, 1); expected = new import__152.Cartesian3(1, 0, 0); expect(import__152.Cartesian3.clamp(value, min, max, result)).toEqual(expected); value = new import__152.Cartesian3(0, -1, 0); min = new import__152.Cartesian3(0, 0, 0); max = new import__152.Cartesian3(1, 1, 1); expected = new import__152.Cartesian3(0, 0, 0); expect(import__152.Cartesian3.clamp(value, min, max, result)).toEqual(expected); value = new import__152.Cartesian3(0, 2, 0); min = new import__152.Cartesian3(0, 0, 0); max = new import__152.Cartesian3(1, 1, 1); expected = new import__152.Cartesian3(0, 1, 0); expect(import__152.Cartesian3.clamp(value, min, max, result)).toEqual(expected); value = new import__152.Cartesian3(0, 0, -1); min = new import__152.Cartesian3(0, 0, 0); max = new import__152.Cartesian3(1, 1, 1); expected = new import__152.Cartesian3(0, 0, 0); expect(import__152.Cartesian3.clamp(value, min, max, result)).toEqual(expected); value = new import__152.Cartesian3(0, 0, 2); min = new import__152.Cartesian3(0, 0, 0); max = new import__152.Cartesian3(1, 1, 1); expected = new import__152.Cartesian3(0, 0, 1); expect(import__152.Cartesian3.clamp(value, min, max, result)).toEqual(expected); value = new import__152.Cartesian3(-2, 3, 4); min = new import__152.Cartesian3(0, 0, 0); max = new import__152.Cartesian3(1, 1, 1); expected = new import__152.Cartesian3(0, 1, 1); expect(import__152.Cartesian3.clamp(value, min, max, result)).toEqual(expected); value = new import__152.Cartesian3(0, 0, 0); min = new import__152.Cartesian3(1, 2, 3); max = new import__152.Cartesian3(1, 2, 3); expected = new import__152.Cartesian3(1, 2, 3); expect(import__152.Cartesian3.clamp(value, min, max, result)).toEqual(expected); }); it("clamp with a result parameter", function() { const value = new import__152.Cartesian3(-1, -1, -1); const min = new import__152.Cartesian3(0, 0, 0); const max = new import__152.Cartesian3(1, 1, 1); const expected = new import__152.Cartesian3(0, 0, 0); const result = new import__152.Cartesian3(); const returnedResult = import__152.Cartesian3.clamp(value, min, max, result); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expected); }); it("clamp with a result parameter that is an input parameter", function() { const value = new import__152.Cartesian3(-1, -1, -1); const min = new import__152.Cartesian3(0, 0, 0); const max = new import__152.Cartesian3(1, 1, 1); const expected = new import__152.Cartesian3(0, 0, 0); expect(import__152.Cartesian3.clamp(value, min, max, value)).toEqual(expected); import__152.Cartesian3.fromElements(-1, -1, -1, value); expect(import__152.Cartesian3.clamp(value, min, max, min)).toEqual(expected); import__152.Cartesian3.fromElements(0, 0, 0, min); expect(import__152.Cartesian3.clamp(value, min, max, max)).toEqual(expected); }); it("clamp throws without value", function() { expect(function() { import__152.Cartesian3.clamp(); }).toThrowDeveloperError(); }); it("clamp throws without min", function() { expect(function() { import__152.Cartesian3.clamp(new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("clamp throws without max", function() { expect(function() { import__152.Cartesian3.clamp(new import__152.Cartesian3(), new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("magnitudeSquared", function() { const cartesian2 = new import__152.Cartesian3(3, 4, 5); expect(import__152.Cartesian3.magnitudeSquared(cartesian2)).toEqual(50); }); it("magnitude", function() { const cartesian2 = new import__152.Cartesian3(3, 4, 5); expect(import__152.Cartesian3.magnitude(cartesian2)).toEqual(Math.sqrt(50)); }); it("distance", function() { const distance = import__152.Cartesian3.distance( new import__152.Cartesian3(1, 0, 0), new import__152.Cartesian3(2, 0, 0) ); expect(distance).toEqual(1); }); it("distance throws without left", function() { expect(function() { import__152.Cartesian3.distance(); }).toThrowDeveloperError(); }); it("distance throws without right", function() { expect(function() { import__152.Cartesian3.distance(import__152.Cartesian3.UNIT_X); }).toThrowDeveloperError(); }); it("distanceSquared", function() { const distanceSquared = import__152.Cartesian3.distanceSquared( new import__152.Cartesian3(1, 0, 0), new import__152.Cartesian3(3, 0, 0) ); expect(distanceSquared).toEqual(4); }); it("distanceSquared throws without left", function() { expect(function() { import__152.Cartesian3.distanceSquared(); }).toThrowDeveloperError(); }); it("distanceSquared throws without right", function() { expect(function() { import__152.Cartesian3.distanceSquared(import__152.Cartesian3.UNIT_X); }).toThrowDeveloperError(); }); it("normalize works with a result parameter", function() { const cartesian2 = new import__152.Cartesian3(2, 0, 0); const expectedResult = new import__152.Cartesian3(1, 0, 0); const result = new import__152.Cartesian3(); const returnedResult = import__152.Cartesian3.normalize(cartesian2, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("normalize works with a result parameter that is an input parameter", function() { const cartesian2 = new import__152.Cartesian3(2, 0, 0); const expectedResult = new import__152.Cartesian3(1, 0, 0); const returnedResult = import__152.Cartesian3.normalize(cartesian2, cartesian2); expect(cartesian2).toBe(returnedResult); expect(cartesian2).toEqual(expectedResult); }); it("normalize throws with zero vector", function() { expect(function() { import__152.Cartesian3.normalize(import__152.Cartesian3.ZERO, new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("multiplyComponents works with a result parameter", function() { const left = new import__152.Cartesian3(2, 3, 6); const right = new import__152.Cartesian3(4, 5, 7); const result = new import__152.Cartesian3(); const expectedResult = new import__152.Cartesian3(8, 15, 42); const returnedResult = import__152.Cartesian3.multiplyComponents(left, right, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("multiplyComponents works with a result parameter that is an input parameter", function() { const left = new import__152.Cartesian3(2, 3, 6); const right = new import__152.Cartesian3(4, 5, 7); const expectedResult = new import__152.Cartesian3(8, 15, 42); const returnedResult = import__152.Cartesian3.multiplyComponents(left, right, left); expect(left).toBe(returnedResult); expect(left).toEqual(expectedResult); }); it("divideComponents works with a result parameter", function() { const left = new import__152.Cartesian3(2, 3, 6); const right = new import__152.Cartesian3(4, 5, 8); const result = new import__152.Cartesian3(); const expectedResult = new import__152.Cartesian3(0.5, 0.6, 0.75); const returnedResult = import__152.Cartesian3.divideComponents(left, right, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("divideComponents works with a result parameter that is an input parameter", function() { const left = new import__152.Cartesian3(2, 3, 6); const right = new import__152.Cartesian3(4, 5, 8); const expectedResult = new import__152.Cartesian3(0.5, 0.6, 0.75); const returnedResult = import__152.Cartesian3.divideComponents(left, right, left); expect(left).toBe(returnedResult); expect(left).toEqual(expectedResult); }); it("dot", function() { const left = new import__152.Cartesian3(2, 3, 6); const right = new import__152.Cartesian3(4, 5, 7); const expectedResult = 65; const result = import__152.Cartesian3.dot(left, right); expect(result).toEqual(expectedResult); }); it("add works with a result parameter", function() { const left = new import__152.Cartesian3(2, 3, 6); const right = new import__152.Cartesian3(4, 5, 7); const result = new import__152.Cartesian3(); const expectedResult = new import__152.Cartesian3(6, 8, 13); const returnedResult = import__152.Cartesian3.add(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expectedResult); }); it("add works with a result parameter that is an input parameter", function() { const left = new import__152.Cartesian3(2, 3, 6); const right = new import__152.Cartesian3(4, 5, 7); const expectedResult = new import__152.Cartesian3(6, 8, 13); const returnedResult = import__152.Cartesian3.add(left, right, left); expect(returnedResult).toBe(left); expect(left).toEqual(expectedResult); }); it("subtract works with a result parameter", function() { const left = new import__152.Cartesian3(2, 3, 4); const right = new import__152.Cartesian3(1, 5, 7); const result = new import__152.Cartesian3(); const expectedResult = new import__152.Cartesian3(1, -2, -3); const returnedResult = import__152.Cartesian3.subtract(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expectedResult); }); it("subtract works with this result parameter", function() { const left = new import__152.Cartesian3(2, 3, 4); const right = new import__152.Cartesian3(1, 5, 7); const expectedResult = new import__152.Cartesian3(1, -2, -3); const returnedResult = import__152.Cartesian3.subtract(left, right, left); expect(returnedResult).toBe(left); expect(left).toEqual(expectedResult); }); it("multiplyByScalar with a result parameter", function() { const cartesian2 = new import__152.Cartesian3(1, 2, 3); const result = new import__152.Cartesian3(); const scalar = 2; const expectedResult = new import__152.Cartesian3(2, 4, 6); const returnedResult = import__152.Cartesian3.multiplyByScalar( cartesian2, scalar, result ); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("multiplyByScalar with a result parameter that is an input parameter", function() { const cartesian2 = new import__152.Cartesian3(1, 2, 3); const scalar = 2; const expectedResult = new import__152.Cartesian3(2, 4, 6); const returnedResult = import__152.Cartesian3.multiplyByScalar( cartesian2, scalar, cartesian2 ); expect(cartesian2).toBe(returnedResult); expect(cartesian2).toEqual(expectedResult); }); it("divideByScalar with a result parameter", function() { const cartesian2 = new import__152.Cartesian3(1, 2, 3); const result = new import__152.Cartesian3(); const scalar = 2; const expectedResult = new import__152.Cartesian3(0.5, 1, 1.5); const returnedResult = import__152.Cartesian3.divideByScalar(cartesian2, scalar, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("divideByScalar with a result parameter that is an input parameter", function() { const cartesian2 = new import__152.Cartesian3(1, 2, 3); const scalar = 2; const expectedResult = new import__152.Cartesian3(0.5, 1, 1.5); const returnedResult = import__152.Cartesian3.divideByScalar( cartesian2, scalar, cartesian2 ); expect(cartesian2).toBe(returnedResult); expect(cartesian2).toEqual(expectedResult); }); it("negate without a result parameter", function() { const cartesian2 = new import__152.Cartesian3(1, -2, -5); const expectedResult = new import__152.Cartesian3(-1, 2, 5); const result = import__152.Cartesian3.negate(cartesian2, new import__152.Cartesian3()); expect(result).toEqual(expectedResult); }); it("negate with a result parameter", function() { const cartesian2 = new import__152.Cartesian3(1, -2, -5); const result = new import__152.Cartesian3(); const expectedResult = new import__152.Cartesian3(-1, 2, 5); const returnedResult = import__152.Cartesian3.negate(cartesian2, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("negate with a result parameter that is an input parameter", function() { const cartesian2 = new import__152.Cartesian3(1, -2, -5); const expectedResult = new import__152.Cartesian3(-1, 2, 5); const returnedResult = import__152.Cartesian3.negate(cartesian2, cartesian2); expect(cartesian2).toBe(returnedResult); expect(cartesian2).toEqual(expectedResult); }); it("abs without a result parameter", function() { const cartesian2 = new import__152.Cartesian3(1, -2, -4); const expectedResult = new import__152.Cartesian3(1, 2, 4); const result = import__152.Cartesian3.abs(cartesian2, new import__152.Cartesian3()); expect(result).toEqual(expectedResult); }); it("abs with a result parameter", function() { const cartesian2 = new import__152.Cartesian3(1, -2, -4); const result = new import__152.Cartesian3(); const expectedResult = new import__152.Cartesian3(1, 2, 4); const returnedResult = import__152.Cartesian3.abs(cartesian2, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("abs with a result parameter that is an input parameter", function() { const cartesian2 = new import__152.Cartesian3(1, -2, -4); const expectedResult = new import__152.Cartesian3(1, 2, 4); const returnedResult = import__152.Cartesian3.abs(cartesian2, cartesian2); expect(cartesian2).toBe(returnedResult); expect(cartesian2).toEqual(expectedResult); }); it("lerp works with a result parameter", function() { const start = new import__152.Cartesian3(4, 8, 10); const end = new import__152.Cartesian3(8, 20, 20); const t = 0.25; const result = new import__152.Cartesian3(); const expectedResult = new import__152.Cartesian3(5, 11, 12.5); const returnedResult = import__152.Cartesian3.lerp(start, end, t, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("lerp works with a result parameter that is an input parameter", function() { const start = new import__152.Cartesian3(4, 8, 10); const end = new import__152.Cartesian3(8, 20, 20); const t = 0.25; const expectedResult = new import__152.Cartesian3(5, 11, 12.5); const returnedResult = import__152.Cartesian3.lerp(start, end, t, start); expect(start).toBe(returnedResult); expect(start).toEqual(expectedResult); }); it("lerp extrapolate forward", function() { const start = new import__152.Cartesian3(4, 8, 10); const end = new import__152.Cartesian3(8, 20, 20); const t = 2; const expectedResult = new import__152.Cartesian3(12, 32, 30); const result = import__152.Cartesian3.lerp(start, end, t, new import__152.Cartesian3()); expect(result).toEqual(expectedResult); }); it("lerp extrapolate backward", function() { const start = new import__152.Cartesian3(4, 8, 10); const end = new import__152.Cartesian3(8, 20, 20); const t = -1; const expectedResult = new import__152.Cartesian3(0, -4, 0); const result = import__152.Cartesian3.lerp(start, end, t, new import__152.Cartesian3()); expect(result).toEqual(expectedResult); }); it("angleBetween works for right angles", function() { const x = import__152.Cartesian3.UNIT_X; const y = import__152.Cartesian3.UNIT_Y; expect(import__152.Cartesian3.angleBetween(x, y)).toEqual(import__153.Math.PI_OVER_TWO); expect(import__152.Cartesian3.angleBetween(y, x)).toEqual(import__153.Math.PI_OVER_TWO); }); it("angleBetween works for acute angles", function() { const x = new import__152.Cartesian3(0, 1, 0); const y = new import__152.Cartesian3(1, 1, 0); expect(import__152.Cartesian3.angleBetween(x, y)).toEqualEpsilon( import__153.Math.PI_OVER_FOUR, import__153.Math.EPSILON14 ); expect(import__152.Cartesian3.angleBetween(y, x)).toEqualEpsilon( import__153.Math.PI_OVER_FOUR, import__153.Math.EPSILON14 ); }); it("angleBetween works for obtuse angles", function() { const x = new import__152.Cartesian3(0, 1, 0); const y = new import__152.Cartesian3(0, -1, -1); expect(import__152.Cartesian3.angleBetween(x, y)).toEqualEpsilon( import__153.Math.PI * 3 / 4, import__153.Math.EPSILON14 ); expect(import__152.Cartesian3.angleBetween(y, x)).toEqualEpsilon( import__153.Math.PI * 3 / 4, import__153.Math.EPSILON14 ); }); it("angleBetween works for zero angles", function() { const x = import__152.Cartesian3.UNIT_X; expect(import__152.Cartesian3.angleBetween(x, x)).toEqual(0); }); it("most orthogonal angle is x", function() { const v = new import__152.Cartesian3(0, 1, 2); expect(import__152.Cartesian3.mostOrthogonalAxis(v, new import__152.Cartesian3())).toEqual( import__152.Cartesian3.UNIT_X ); }); it("most orthogonal angle is y", function() { const v = new import__152.Cartesian3(1, 0, 2); expect(import__152.Cartesian3.mostOrthogonalAxis(v, new import__152.Cartesian3())).toEqual( import__152.Cartesian3.UNIT_Y ); }); it("most orthogonal angle is z", function() { let v = new import__152.Cartesian3(1, 3, 0); expect(import__152.Cartesian3.mostOrthogonalAxis(v, new import__152.Cartesian3())).toEqual( import__152.Cartesian3.UNIT_Z ); v = new import__152.Cartesian3(3, 1, 0); expect(import__152.Cartesian3.mostOrthogonalAxis(v, new import__152.Cartesian3())).toEqual( import__152.Cartesian3.UNIT_Z ); }); it("equals", function() { const cartesian2 = new import__152.Cartesian3(1, 2, 3); expect(import__152.Cartesian3.equals(cartesian2, new import__152.Cartesian3(1, 2, 3))).toEqual( true ); expect(import__152.Cartesian3.equals(cartesian2, new import__152.Cartesian3(2, 2, 3))).toEqual( false ); expect(import__152.Cartesian3.equals(cartesian2, new import__152.Cartesian3(2, 1, 3))).toEqual( false ); expect(import__152.Cartesian3.equals(cartesian2, new import__152.Cartesian3(1, 2, 4))).toEqual( false ); expect(import__152.Cartesian3.equals(cartesian2, void 0)).toEqual(false); }); it("equalsEpsilon", function() { let cartesian2 = new import__152.Cartesian3(1, 2, 3); expect(cartesian2.equalsEpsilon(new import__152.Cartesian3(1, 2, 3), 0)).toEqual( true ); expect(cartesian2.equalsEpsilon(new import__152.Cartesian3(1, 2, 3), 1)).toEqual( true ); expect(cartesian2.equalsEpsilon(new import__152.Cartesian3(2, 2, 3), 1)).toEqual( true ); expect(cartesian2.equalsEpsilon(new import__152.Cartesian3(1, 3, 3), 1)).toEqual( true ); expect(cartesian2.equalsEpsilon(new import__152.Cartesian3(1, 2, 4), 1)).toEqual( true ); expect( cartesian2.equalsEpsilon( new import__152.Cartesian3(2, 2, 3), import__153.Math.EPSILON6 ) ).toEqual(false); expect( cartesian2.equalsEpsilon( new import__152.Cartesian3(1, 3, 3), import__153.Math.EPSILON6 ) ).toEqual(false); expect( cartesian2.equalsEpsilon( new import__152.Cartesian3(1, 2, 4), import__153.Math.EPSILON6 ) ).toEqual(false); expect(cartesian2.equalsEpsilon(void 0, 1)).toEqual(false); cartesian2 = new import__152.Cartesian3(3e6, 4e6, 5e6); expect( cartesian2.equalsEpsilon( new import__152.Cartesian3(3e6, 4e6, 5e6), 0 ) ).toEqual(true); expect( cartesian2.equalsEpsilon( new import__152.Cartesian3(30000002e-1, 4e6, 5e6), import__153.Math.EPSILON7 ) ).toEqual(true); expect( cartesian2.equalsEpsilon( new import__152.Cartesian3(3e6, 40000002e-1, 5e6), import__153.Math.EPSILON7 ) ).toEqual(true); expect( cartesian2.equalsEpsilon( new import__152.Cartesian3(3e6, 4e6, 50000002e-1), import__153.Math.EPSILON7 ) ).toEqual(true); expect( cartesian2.equalsEpsilon( new import__152.Cartesian3(30000002e-1, 40000002e-1, 50000002e-1), import__153.Math.EPSILON7 ) ).toEqual(true); expect( cartesian2.equalsEpsilon( new import__152.Cartesian3(30000002e-1, 40000002e-1, 50000002e-1), import__153.Math.EPSILON9 ) ).toEqual(false); expect(cartesian2.equalsEpsilon(void 0, 1)).toEqual(false); expect(import__152.Cartesian3.equalsEpsilon(void 0, cartesian2, 1)).toEqual(false); }); it("toString", function() { const cartesian2 = new import__152.Cartesian3(1.123, 2.345, 6.789); expect(cartesian2.toString()).toEqual("(1.123, 2.345, 6.789)"); }); it("cross works with a result parameter", function() { const left = new import__152.Cartesian3(1, 2, 5); const right = new import__152.Cartesian3(4, 3, 6); const result = new import__152.Cartesian3(); const expectedResult = new import__152.Cartesian3(-3, 14, -5); const returnedResult = import__152.Cartesian3.cross(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expectedResult); }); it("cross works with a result parameter that is an input parameter", function() { const left = new import__152.Cartesian3(1, 2, 5); const right = new import__152.Cartesian3(4, 3, 6); const expectedResult = new import__152.Cartesian3(-3, 14, -5); const returnedResult = import__152.Cartesian3.cross(left, right, left); expect(returnedResult).toBe(left); expect(left).toEqual(expectedResult); }); it("midpoint works with a result parameter", function() { const left = new import__152.Cartesian3(0, 0, 6); const right = new import__152.Cartesian3(0, 0, -6); const result = new import__152.Cartesian3(); const expectedResult = new import__152.Cartesian3(0, 0, 0); const returnedResult = import__152.Cartesian3.midpoint(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expectedResult); }); it("midpoint throws with no left", function() { expect(function() { return import__152.Cartesian3.midpoint(void 0, new import__152.Cartesian3(), new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("midpoint throws with no right", function() { expect(function() { return import__152.Cartesian3.midpoint(new import__152.Cartesian3(), void 0, new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("midpoint throws with no result", function() { expect(function() { return import__152.Cartesian3.midpoint(new import__152.Cartesian3(), new import__152.Cartesian3(), void 0); }).toThrowDeveloperError(); }); it("fromSpherical throws with no spherical parameter", function() { expect(function() { import__152.Cartesian3.fromSpherical(void 0); }).toThrowDeveloperError(); }); it("fromSpherical work with no result parameter", function() { expect(function() { import__152.Cartesian3.fromSpherical({ clock: sixtyDegrees, cone: fortyFiveDegrees + Math.PI / 2, magnitude: Math.sqrt(8) }); }).not.toThrowDeveloperError(); }); it("clone returns undefined with no parameter", function() { expect(import__152.Cartesian3.clone()).toBeUndefined(); }); it("maximumComponent throws with no parameter", function() { expect(function() { import__152.Cartesian3.maximumComponent(); }).toThrowDeveloperError(); }); it("minimumComponent throws with no parameter", function() { expect(function() { import__152.Cartesian3.minimumComponent(); }).toThrowDeveloperError(); }); it("magnitudeSquared throws with no parameter", function() { expect(function() { import__152.Cartesian3.magnitudeSquared(); }).toThrowDeveloperError(); }); it("magnitude throws with no parameter", function() { expect(function() { import__152.Cartesian3.magnitude(); }).toThrowDeveloperError(); }); it("normalize throws with no parameter", function() { expect(function() { import__152.Cartesian3.normalize(); }).toThrowDeveloperError(); }); it("dot throws with no left parameter", function() { expect(function() { import__152.Cartesian3.dot(void 0, new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("multiplyComponents throw with no left parameter", function() { const right = new import__152.Cartesian3(4, 5, 6); expect(function() { import__152.Cartesian3.multiplyComponents(void 0, right); }).toThrowDeveloperError(); }); it("multiplyComponents throw with no right parameter", function() { const left = new import__152.Cartesian3(4, 5, 6); expect(function() { import__152.Cartesian3.multiplyComponents(left, void 0); }).toThrowDeveloperError(); }); it("divideComponents throw with no left parameter", function() { const right = new import__152.Cartesian3(4, 5, 6); expect(function() { import__152.Cartesian3.divideComponents(void 0, right); }).toThrowDeveloperError(); }); it("divideComponents throw with no right parameter", function() { const left = new import__152.Cartesian3(4, 5, 6); expect(function() { import__152.Cartesian3.divideComponents(left, void 0); }).toThrowDeveloperError(); }); it("dot throws with no right parameter", function() { expect(function() { import__152.Cartesian3.dot(new import__152.Cartesian3(), void 0); }).toThrowDeveloperError(); }); it("add throws with no left parameter", function() { expect(function() { import__152.Cartesian3.add(void 0, new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("add throws with no right parameter", function() { expect(function() { import__152.Cartesian3.add(new import__152.Cartesian3(), void 0); }).toThrowDeveloperError(); }); it("subtract throws with no left parameter", function() { expect(function() { import__152.Cartesian3.subtract(void 0, new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("subtract throws with no right parameter", function() { expect(function() { import__152.Cartesian3.subtract(new import__152.Cartesian3(), void 0); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with no cartesian parameter", function() { expect(function() { import__152.Cartesian3.multiplyByScalar(void 0, 2); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with no scalar parameter", function() { expect(function() { import__152.Cartesian3.multiplyByScalar(new import__152.Cartesian3(), void 0); }).toThrowDeveloperError(); }); it("divideByScalar throws with no cartesian parameter", function() { expect(function() { import__152.Cartesian3.divideByScalar(void 0, 2); }).toThrowDeveloperError(); }); it("divideByScalar throws with no scalar parameter", function() { expect(function() { import__152.Cartesian3.divideByScalar(new import__152.Cartesian3(), void 0); }).toThrowDeveloperError(); }); it("negate throws with no cartesian parameter", function() { expect(function() { import__152.Cartesian3.negate(void 0); }).toThrowDeveloperError(); }); it("abs throws with no cartesian parameter", function() { expect(function() { import__152.Cartesian3.abs(void 0); }).toThrowDeveloperError(); }); it("lerp throws with no start parameter", function() { const end = new import__152.Cartesian3(8, 20, 6); const t = 0.25; expect(function() { import__152.Cartesian3.lerp(void 0, end, t); }).toThrowDeveloperError(); }); it("lerp throws with no end parameter", function() { const start = new import__152.Cartesian3(4, 8, 6); const t = 0.25; expect(function() { import__152.Cartesian3.lerp(start, void 0, t); }).toThrowDeveloperError(); }); it("lerp throws with no t parameter", function() { const start = new import__152.Cartesian3(4, 8, 6); const end = new import__152.Cartesian3(8, 20, 6); expect(function() { import__152.Cartesian3.lerp(start, end, void 0); }).toThrowDeveloperError(); }); it("angleBetween throws with no left parameter", function() { const right = new import__152.Cartesian3(8, 20, 6); expect(function() { import__152.Cartesian3.angleBetween(void 0, right); }).toThrowDeveloperError(); }); it("angleBetween throws with no right parameter", function() { const left = new import__152.Cartesian3(4, 8, 6); expect(function() { import__152.Cartesian3.angleBetween(left, void 0); }).toThrowDeveloperError(); }); it("mostOrthogonalAxis throws with no cartesian parameter", function() { expect(function() { import__152.Cartesian3.mostOrthogonalAxis(void 0); }).toThrowDeveloperError(); }); it("cross throw with no left paramater", function() { const right = new import__152.Cartesian3(4, 3, 6); expect(function() { import__152.Cartesian3.cross(void 0, right); }).toThrowDeveloperError(); }); it("cross throw with no left paramater", function() { const left = new import__152.Cartesian3(1, 2, 5); expect(function() { import__152.Cartesian3.cross(left, void 0); }).toThrowDeveloperError(); }); it("fromElements returns a cartesian3 with corrrect coordinates", function() { const cartesian2 = import__152.Cartesian3.fromElements(2, 2, 4); const expectedResult = new import__152.Cartesian3(2, 2, 4); expect(cartesian2).toEqual(expectedResult); }); it("fromElements result param returns cartesian3 with correct coordinates", function() { const cartesian3 = new import__152.Cartesian3(); import__152.Cartesian3.fromElements(2, 2, 4, cartesian3); const expectedResult = new import__152.Cartesian3(2, 2, 4); expect(cartesian3).toEqual(expectedResult); }); it("fromDegrees", function() { const lon = -115; const lat = 37; const ellipsoid = import__152.Ellipsoid.WGS84; const actual = import__152.Cartesian3.fromDegrees(lon, lat); const expected = ellipsoid.cartographicToCartesian( import__152.Cartographic.fromDegrees(lon, lat) ); expect(actual).toEqual(expected); }); it("fromDegrees with height", function() { const lon = -115; const lat = 37; const height = 1e5; const ellipsoid = import__152.Ellipsoid.WGS84; const actual = import__152.Cartesian3.fromDegrees(lon, lat, height); const expected = ellipsoid.cartographicToCartesian( import__152.Cartographic.fromDegrees(lon, lat, height) ); expect(actual).toEqual(expected); }); it("fromDegrees with result", function() { const lon = -115; const lat = 37; const height = 1e5; const ellipsoid = import__152.Ellipsoid.WGS84; const result = new import__152.Cartesian3(); const actual = import__152.Cartesian3.fromDegrees(lon, lat, height, ellipsoid, result); const expected = ellipsoid.cartographicToCartesian( import__152.Cartographic.fromDegrees(lon, lat, height) ); expect(actual).toEqual(expected); expect(actual).toBe(result); }); it("fromDegrees throws with no longitude", function() { expect(function() { import__152.Cartesian3.fromDegrees(); }).toThrowDeveloperError(); }); it("fromDegrees throws with no latitude", function() { expect(function() { import__152.Cartesian3.fromDegrees(1); }).toThrowDeveloperError(); }); it("fromRadians", function() { const lon = import__153.Math.toRadians(150); const lat = import__153.Math.toRadians(-40); const ellipsoid = import__152.Ellipsoid.WGS84; const actual = import__152.Cartesian3.fromRadians(lon, lat); const expected = ellipsoid.cartographicToCartesian( new import__152.Cartographic(lon, lat) ); expect(actual).toEqual(expected); }); it("fromRadians with height", function() { const lon = import__153.Math.toRadians(150); const lat = import__153.Math.toRadians(-40); const height = 1e5; const ellipsoid = import__152.Ellipsoid.WGS84; const actual = import__152.Cartesian3.fromRadians(lon, lat, height); const expected = ellipsoid.cartographicToCartesian( new import__152.Cartographic(lon, lat, height) ); expect(actual).toEqual(expected); }); it("fromRadians with result", function() { const lon = import__153.Math.toRadians(150); const lat = import__153.Math.toRadians(-40); const height = 1e5; const ellipsoid = import__152.Ellipsoid.WGS84; const result = new import__152.Cartesian3(); const actual = import__152.Cartesian3.fromRadians(lon, lat, height, ellipsoid, result); const expected = ellipsoid.cartographicToCartesian( new import__152.Cartographic(lon, lat, height) ); expect(actual).toEqual(expected); expect(actual).toBe(result); }); it("fromRadians throws with no longitude", function() { expect(function() { import__152.Cartesian3.fromRadians(); }).toThrowDeveloperError(); }); it("fromRadians throws with no latitude", function() { expect(function() { import__152.Cartesian3.fromRadians(1); }).toThrowDeveloperError(); }); it("fromDegreesArray", function() { const lon1 = 90; const lat1 = -70; const lon2 = -100; const lat2 = 40; const ellipsoid = import__152.Ellipsoid.WGS84; const actual = import__152.Cartesian3.fromDegreesArray([lon1, lat1, lon2, lat2]); const expected = ellipsoid.cartographicArrayToCartesianArray([ import__152.Cartographic.fromDegrees(lon1, lat1), import__152.Cartographic.fromDegrees(lon2, lat2) ]); expect(actual).toEqual(expected); }); it("fromDegreesArray throws with no positions", function() { expect(function() { import__152.Cartesian3.fromDegreesArray(); }).toThrowDeveloperError(); }); it("fromDegreesArray throws with positions length < 2", function() { expect(function() { import__152.Cartesian3.fromDegreesArray([]); }).toThrowDeveloperError(); }); it("fromDegreesArray throws with positions length not multiple of 2", function() { expect(function() { import__152.Cartesian3.fromDegreesArray([1, 3, 5]); }).toThrowDeveloperError(); }); it("fromRadiansArray", function() { const lon1 = import__153.Math.toRadians(90); const lat1 = import__153.Math.toRadians(-70); const lon2 = import__153.Math.toRadians(-100); const lat2 = import__153.Math.toRadians(40); const ellipsoid = import__152.Ellipsoid.WGS84; const actual = import__152.Cartesian3.fromRadiansArray([lon1, lat1, lon2, lat2]); const expected = ellipsoid.cartographicArrayToCartesianArray([ new import__152.Cartographic(lon1, lat1), new import__152.Cartographic(lon2, lat2) ]); expect(actual).toEqual(expected); }); it("fromRadiansArray with result", function() { const lon1 = import__153.Math.toRadians(90); const lat1 = import__153.Math.toRadians(-70); const lon2 = import__153.Math.toRadians(-100); const lat2 = import__153.Math.toRadians(40); const ellipsoid = import__152.Ellipsoid.WGS84; const result = [new import__152.Cartesian3(), new import__152.Cartesian3()]; const actual = import__152.Cartesian3.fromRadiansArray( [lon1, lat1, lon2, lat2], ellipsoid, result ); const expected = ellipsoid.cartographicArrayToCartesianArray([ new import__152.Cartographic(lon1, lat1), new import__152.Cartographic(lon2, lat2) ]); expect(result).toEqual(expected); expect(actual).toBe(result); }); it("fromRadiansArray throws with no positions", function() { expect(function() { import__152.Cartesian3.fromRadiansArray(); }).toThrowDeveloperError(); }); it("fromRadiansArray throws with positions length < 2", function() { expect(function() { import__152.Cartesian3.fromRadiansArray([]); }).toThrowDeveloperError(); }); it("fromRadiansArray throws with positions length not multiple of 2", function() { expect(function() { import__152.Cartesian3.fromRadiansArray([1, 3, 5]); }).toThrowDeveloperError(); }); it("fromDegreesArrayHeights", function() { const lon1 = 90; const lat1 = -70; const alt1 = 2e5; const lon2 = -100; const lat2 = 40; const alt2 = 1e5; const ellipsoid = import__152.Ellipsoid.WGS84; const actual = import__152.Cartesian3.fromDegreesArrayHeights([ lon1, lat1, alt1, lon2, lat2, alt2 ]); const expected = ellipsoid.cartographicArrayToCartesianArray([ import__152.Cartographic.fromDegrees(lon1, lat1, alt1), import__152.Cartographic.fromDegrees(lon2, lat2, alt2) ]); expect(actual).toEqual(expected); }); it("fromDegreesArrayHeights throws with no positions", function() { expect(function() { import__152.Cartesian3.fromDegreesArrayHeights(); }).toThrowDeveloperError(); }); it("fromDegreesArrayHeights throws with positions length < 3", function() { expect(function() { import__152.Cartesian3.fromDegreesArrayHeights([]); }).toThrowDeveloperError(); }); it("fromDegreesArrayHeights throws with positions length not multiple of 3", function() { expect(function() { import__152.Cartesian3.fromDegreesArrayHeights([1, 3, 5, 2]); }).toThrowDeveloperError(); }); it("fromRadiansArrayHeights", function() { const lon1 = import__153.Math.toRadians(90); const lat1 = import__153.Math.toRadians(-70); const alt1 = 2e5; const lon2 = import__153.Math.toRadians(-100); const lat2 = import__153.Math.toRadians(40); const alt2 = 1e5; const ellipsoid = import__152.Ellipsoid.WGS84; const actual = import__152.Cartesian3.fromRadiansArrayHeights([ lon1, lat1, alt1, lon2, lat2, alt2 ]); const expected = ellipsoid.cartographicArrayToCartesianArray([ new import__152.Cartographic(lon1, lat1, alt1), new import__152.Cartographic(lon2, lat2, alt2) ]); expect(actual).toEqual(expected); }); it("fromRadiansArrayHeights with result", function() { const lon1 = import__153.Math.toRadians(90); const lat1 = import__153.Math.toRadians(-70); const alt1 = 2e5; const lon2 = import__153.Math.toRadians(-100); const lat2 = import__153.Math.toRadians(40); const alt2 = 1e5; const ellipsoid = import__152.Ellipsoid.WGS84; const result = [new import__152.Cartesian3(), new import__152.Cartesian3()]; const actual = import__152.Cartesian3.fromRadiansArrayHeights( [lon1, lat1, alt1, lon2, lat2, alt2], ellipsoid, result ); const expected = ellipsoid.cartographicArrayToCartesianArray([ new import__152.Cartographic(lon1, lat1, alt1), new import__152.Cartographic(lon2, lat2, alt2) ]); expect(result).toEqual(expected); expect(actual).toBe(result); }); it("fromRadiansArrayHeights throws with no positions", function() { expect(function() { import__152.Cartesian3.fromRadiansArrayHeights(); }).toThrowDeveloperError(); }); it("fromRadiansArrayHeights throws with positions length < 3", function() { expect(function() { import__152.Cartesian3.fromRadiansArrayHeights([]); }).toThrowDeveloperError(); }); it("fromRadiansArrayHeights throws with positions length not multiple of 3", function() { expect(function() { import__152.Cartesian3.fromRadiansArrayHeights([1, 3, 5, 2]); }).toThrowDeveloperError(); }); it("minimumByComponent throws with no result", function() { expect(function() { import__152.Cartesian3.minimumByComponent(new import__152.Cartesian3(), new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("maximumByComponent throws with no result", function() { expect(function() { import__152.Cartesian3.maximumByComponent(new import__152.Cartesian3(), new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("clamp throws with no result", function() { expect(function() { import__152.Cartesian3.clamp(new import__152.Cartesian3(), new import__152.Cartesian3(), new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("normalize throws with no result", function() { expect(function() { import__152.Cartesian3.normalize(new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("multiplyComponents throws with no result", function() { expect(function() { import__152.Cartesian3.multiplyComponents(new import__152.Cartesian3(), new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("divideComponents throws with no result", function() { expect(function() { import__152.Cartesian3.divideComponents(new import__152.Cartesian3(), new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("add throws with no result", function() { expect(function() { import__152.Cartesian3.add(new import__152.Cartesian3(), new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("subtract throws with no result", function() { expect(function() { import__152.Cartesian3.subtract(new import__152.Cartesian3(), new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with no result", function() { expect(function() { import__152.Cartesian3.multiplyByScalar(new import__152.Cartesian3(), 5); }).toThrowDeveloperError(); }); it("divideByScalar throws with no result", function() { expect(function() { import__152.Cartesian3.divideByScalar(new import__152.Cartesian3(), 5); }).toThrowDeveloperError(); }); it("negate throws with no result", function() { expect(function() { import__152.Cartesian3.negate(new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("abs throws with no result", function() { expect(function() { import__152.Cartesian3.abs(new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("cross throws with no result", function() { expect(function() { import__152.Cartesian3.cross(new import__152.Cartesian3(), new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("lerp throws with no result", function() { expect(function() { import__152.Cartesian3.lerp(new import__152.Cartesian3(), new import__152.Cartesian3(), 10); }).toThrowDeveloperError(); }); it("mostOrthogonalAxis throws with no result", function() { expect(function() { import__152.Cartesian3.mostOrthogonalAxis(new import__152.Cartesian3()); }).toThrowDeveloperError(); }); it("projects vector a onto vector b", function() { let a = new import__152.Cartesian3(0, 1, 0); let b = new import__152.Cartesian3(1, 0, 0); let result = import__152.Cartesian3.projectVector(a, b, new import__152.Cartesian3()); expect(result).toEqual(new import__152.Cartesian3(0, 0, 0)); a = new import__152.Cartesian3(1, 1, 0); b = new import__152.Cartesian3(1, 0, 0); result = import__152.Cartesian3.projectVector(a, b, new import__152.Cartesian3()); expect(result).toEqual(new import__152.Cartesian3(1, 0, 0)); }); it("projectVector throws when missing parameters", function() { expect(function() { return import__152.Cartesian3.projectVector( void 0, new import__152.Cartesian3(), new import__152.Cartesian3() ); }).toThrowDeveloperError(); expect(function() { return import__152.Cartesian3.projectVector( new import__152.Cartesian3(), void 0, new import__152.Cartesian3() ); }).toThrowDeveloperError(); expect(function() { return import__152.Cartesian3.projectVector( new import__152.Cartesian3(), new import__152.Cartesian3(), void 0 ); }).toThrowDeveloperError(); }); createPackableSpecs_default(import__152.Cartesian3, new import__152.Cartesian3(1, 2, 3), [1, 2, 3]); createPackableArraySpecs_default( import__152.Cartesian3, [new import__152.Cartesian3(1, 2, 3), new import__152.Cartesian3(4, 5, 6)], [1, 2, 3, 4, 5, 6], 3 ); }); // packages/engine/Specs/Core/Cartesian4Spec.js var import__154 = __toESM(require_Cesium(), 1); var import__155 = __toESM(require_Cesium(), 1); describe("Core/Cartesian4", function() { it("construct with default values", function() { const cartesian = new import__154.Cartesian4(); expect(cartesian.x).toEqual(0); expect(cartesian.y).toEqual(0); expect(cartesian.z).toEqual(0); expect(cartesian.w).toEqual(0); }); it("construct with all values", function() { const cartesian = new import__154.Cartesian4(1, 2, 3, 4); expect(cartesian.x).toEqual(1); expect(cartesian.y).toEqual(2); expect(cartesian.z).toEqual(3); expect(cartesian.w).toEqual(4); }); it("fromArray creates a Cartesian4", function() { const cartesian = import__154.Cartesian4.fromArray([1, 2, 3, 4]); expect(cartesian).toEqual(new import__154.Cartesian4(1, 2, 3, 4)); }); it("fromArray with an offset creates a Cartesian4", function() { const cartesian = import__154.Cartesian4.fromArray([0, 1, 2, 3, 4, 0], 1); expect(cartesian).toEqual(new import__154.Cartesian4(1, 2, 3, 4)); }); it("fromArray creates a Cartesian4 with a result parameter", function() { const cartesian = new import__154.Cartesian4(); const result = import__154.Cartesian4.fromArray([1, 2, 3, 4], 0, cartesian); expect(result).toBe(cartesian); expect(result).toEqual(new import__154.Cartesian4(1, 2, 3, 4)); }); it("fromArray throws without values", function() { expect(function() { import__154.Cartesian4.fromArray(); }).toThrowDeveloperError(); }); it("fromElements returns a cartesian4 with corrrect coordinates", function() { const cartesian4 = import__154.Cartesian4.fromElements(2, 2, 4, 7); const expectedResult = new import__154.Cartesian4(2, 2, 4, 7); expect(cartesian4).toEqual(expectedResult); }); it("fromElements result param returns cartesian4 with correct coordinates", function() { const cartesian4 = new import__154.Cartesian4(); import__154.Cartesian4.fromElements(2, 2, 4, 7, cartesian4); const expectedResult = new import__154.Cartesian4(2, 2, 4, 7); expect(cartesian4).toEqual(expectedResult); }); it("fromColor returns a cartesian4 with corrrect coordinates", function() { const cartesian4 = import__154.Cartesian4.fromColor(new import__154.Color(1, 2, 3, 4)); expect(cartesian4).toEqual(new import__154.Cartesian4(1, 2, 3, 4)); }); it("fromColor result param returns cartesian4 with correct coordinates", function() { const cartesian4 = new import__154.Cartesian4(); const result = import__154.Cartesian4.fromColor( new import__154.Color(1, 2, 3, 4), cartesian4 ); expect(cartesian4).toBe(result); expect(cartesian4).toEqual(new import__154.Cartesian4(1, 2, 3, 4)); }); it("fromColor throws without color", function() { expect(function() { import__154.Cartesian4.fromColor(); }).toThrowDeveloperError(); }); it("clone without a result parameter", function() { const cartesian = new import__154.Cartesian4(1, 2, 3, 4); const result = import__154.Cartesian4.clone(cartesian, new import__154.Cartesian4()); expect(cartesian).not.toBe(result); expect(cartesian).toEqual(result); }); it("clone with a result parameter", function() { const cartesian = new import__154.Cartesian4(1, 2, 3, 4); const result = new import__154.Cartesian4(); const returnedResult = import__154.Cartesian4.clone(cartesian, result); expect(cartesian).not.toBe(result); expect(result).toBe(returnedResult); expect(cartesian).toEqual(result); }); it("clone works with a result parameter that is an input parameter", function() { const cartesian = new import__154.Cartesian4(1, 2, 3, 4); const returnedResult = import__154.Cartesian4.clone(cartesian, cartesian); expect(cartesian).toBe(returnedResult); }); it("maximumComponent works when X is greater", function() { const cartesian = new import__154.Cartesian4(2, 1, 0, -1); expect(import__154.Cartesian4.maximumComponent(cartesian)).toEqual(cartesian.x); }); it("maximumComponent works when Y is greater", function() { const cartesian = new import__154.Cartesian4(1, 2, 0, -1); expect(import__154.Cartesian4.maximumComponent(cartesian)).toEqual(cartesian.y); }); it("maximumComponent works when Z is greater", function() { const cartesian = new import__154.Cartesian4(1, 2, 3, -1); expect(import__154.Cartesian4.maximumComponent(cartesian)).toEqual(cartesian.z); }); it("maximumComponent works when W is greater", function() { const cartesian = new import__154.Cartesian4(1, 2, 3, 4); expect(import__154.Cartesian4.maximumComponent(cartesian)).toEqual(cartesian.w); }); it("minimumComponent works when X is lesser", function() { const cartesian = new import__154.Cartesian4(1, 2, 3, 4); expect(import__154.Cartesian4.minimumComponent(cartesian)).toEqual(cartesian.x); }); it("minimumComponent works when Y is lesser", function() { const cartesian = new import__154.Cartesian4(2, 1, 3, 4); expect(import__154.Cartesian4.minimumComponent(cartesian)).toEqual(cartesian.y); }); it("minimumComponent works when Z is lesser", function() { const cartesian = new import__154.Cartesian4(2, 1, 0, 4); expect(import__154.Cartesian4.minimumComponent(cartesian)).toEqual(cartesian.z); }); it("minimumComponent works when W is lesser", function() { const cartesian = new import__154.Cartesian4(2, 1, 0, -1); expect(import__154.Cartesian4.minimumComponent(cartesian)).toEqual(cartesian.w); }); it("minimumByComponent", function() { let first; let second; let expected; const result = new import__154.Cartesian4(); first = new import__154.Cartesian4(2, 0, 0, 0); second = new import__154.Cartesian4(1, 0, 0, 0); expected = new import__154.Cartesian4(1, 0, 0, 0); expect(import__154.Cartesian4.minimumByComponent(first, second, result)).toEqual( expected ); first = new import__154.Cartesian4(1, 0, 0, 0); second = new import__154.Cartesian4(2, 0, 0, 0); expected = new import__154.Cartesian4(1, 0, 0, 0); expect(import__154.Cartesian4.minimumByComponent(first, second, result)).toEqual( expected ); first = new import__154.Cartesian4(2, -15, 0, 0); second = new import__154.Cartesian4(1, -20, 0, 0); expected = new import__154.Cartesian4(1, -20, 0, 0); expect(import__154.Cartesian4.minimumByComponent(first, second, result)).toEqual( expected ); first = new import__154.Cartesian4(2, -20, 0, 0); second = new import__154.Cartesian4(1, -15, 0, 0); expected = new import__154.Cartesian4(1, -20, 0, 0); expect(import__154.Cartesian4.minimumByComponent(first, second, result)).toEqual( expected ); first = new import__154.Cartesian4(2, -15, 26.4, 0); second = new import__154.Cartesian4(1, -20, 26.5, 0); expected = new import__154.Cartesian4(1, -20, 26.4, 0); expect(import__154.Cartesian4.minimumByComponent(first, second, result)).toEqual( expected ); first = new import__154.Cartesian4(2, -15, 26.5, 0); second = new import__154.Cartesian4(1, -20, 26.4, 0); expected = new import__154.Cartesian4(1, -20, 26.4, 0); expect(import__154.Cartesian4.minimumByComponent(first, second, result)).toEqual( expected ); first = new import__154.Cartesian4(2, -15, 26.4, -450); second = new import__154.Cartesian4(1, -20, 26.5, 450); expected = new import__154.Cartesian4(1, -20, 26.4, -450); expect(import__154.Cartesian4.minimumByComponent(first, second, result)).toEqual( expected ); first = new import__154.Cartesian4(2, -15, 26.5, 450); second = new import__154.Cartesian4(1, -20, 26.4, -450); expected = new import__154.Cartesian4(1, -20, 26.4, -450); expect(import__154.Cartesian4.minimumByComponent(first, second, result)).toEqual( expected ); }); it("minimumByComponent with a result parameter", function() { const first = new import__154.Cartesian4(2, 0, 0, 0); const second = new import__154.Cartesian4(1, 0, 0, 0); const expected = new import__154.Cartesian4(1, 0, 0, 0); const result = new import__154.Cartesian4(); const returnedResult = import__154.Cartesian4.minimumByComponent(first, second, result); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expected); }); it("minimumByComponent with a result parameter that is an input parameter", function() { const first = new import__154.Cartesian4(2, 0, 0, 0); const second = new import__154.Cartesian4(1, 0, 0, 0); const expected = new import__154.Cartesian4(1, 0, 0, 0); expect(import__154.Cartesian4.minimumByComponent(first, second, first)).toEqual( expected ); first.x = 1; second.x = 2; expect(import__154.Cartesian4.minimumByComponent(first, second, second)).toEqual( expected ); }); it("minimumByComponent throws without first", function() { expect(function() { import__154.Cartesian4.minimumByComponent(); }).toThrowDeveloperError(); }); it("minimumByComponent throws without second", function() { expect(function() { import__154.Cartesian4.minimumByComponent(new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("minimumByComponent works when first's or second's X is lesser", function() { const first = new import__154.Cartesian4(2, 0, 0, 0); const second = new import__154.Cartesian4(1, 0, 0, 0); const expected = new import__154.Cartesian4(1, 0, 0, 0); const result = new import__154.Cartesian4(); expect(import__154.Cartesian4.minimumByComponent(first, second, result)).toEqual( expected ); second.x = 3; expected.x = 2; expect(import__154.Cartesian4.minimumByComponent(first, second, result)).toEqual( expected ); }); it("minimumByComponent works when first's or second's Y is lesser", function() { const first = new import__154.Cartesian4(0, 2, 0, 0); const second = new import__154.Cartesian4(0, 1, 0, 0); const expected = new import__154.Cartesian4(0, 1, 0, 0); const result = new import__154.Cartesian4(); expect(import__154.Cartesian4.minimumByComponent(first, second, result)).toEqual( expected ); second.y = 3; expected.y = 2; expect(import__154.Cartesian4.minimumByComponent(first, second, result)).toEqual( expected ); }); it("minimumByComponent works when first's or second's Z is lesser", function() { const first = new import__154.Cartesian4(0, 0, 2, 0); const second = new import__154.Cartesian4(0, 0, 1, 0); const expected = new import__154.Cartesian4(0, 0, 1, 0); const result = new import__154.Cartesian4(); expect(import__154.Cartesian4.minimumByComponent(first, second, result)).toEqual( expected ); second.z = 3; expected.z = 2; expect(import__154.Cartesian4.minimumByComponent(first, second, result)).toEqual( expected ); }); it("minimumByComponent works when first's or second's W is lesser", function() { const first = new import__154.Cartesian4(0, 0, 0, 2); const second = new import__154.Cartesian4(0, 0, 0, 1); const expected = new import__154.Cartesian4(0, 0, 0, 1); const result = new import__154.Cartesian4(); expect(import__154.Cartesian4.minimumByComponent(first, second, result)).toEqual( expected ); second.w = 3; expected.w = 2; expect(import__154.Cartesian4.minimumByComponent(first, second, result)).toEqual( expected ); }); it("maximumByComponent", function() { let first; let second; let expected; first = new import__154.Cartesian4(2, 0, 0, 0); second = new import__154.Cartesian4(1, 0, 0, 0); expected = new import__154.Cartesian4(2, 0, 0, 0); const result = new import__154.Cartesian4(); expect(import__154.Cartesian4.maximumByComponent(first, second, result)).toEqual( expected ); first = new import__154.Cartesian4(1, 0, 0, 0); second = new import__154.Cartesian4(2, 0, 0, 0); expected = new import__154.Cartesian4(2, 0, 0, 0); expect(import__154.Cartesian4.maximumByComponent(first, second, result)).toEqual( expected ); first = new import__154.Cartesian4(2, -15, 0, 0); second = new import__154.Cartesian4(1, -20, 0, 0); expected = new import__154.Cartesian4(2, -15, 0, 0); expect(import__154.Cartesian4.maximumByComponent(first, second, result)).toEqual( expected ); first = new import__154.Cartesian4(2, -20, 0, 0); second = new import__154.Cartesian4(1, -15, 0, 0); expected = new import__154.Cartesian4(2, -15, 0, 0); expect(import__154.Cartesian4.maximumByComponent(first, second, result)).toEqual( expected ); first = new import__154.Cartesian4(2, -15, 26.4, 0); second = new import__154.Cartesian4(1, -20, 26.5, 0); expected = new import__154.Cartesian4(2, -15, 26.5, 0); expect(import__154.Cartesian4.maximumByComponent(first, second, result)).toEqual( expected ); first = new import__154.Cartesian4(2, -15, 26.5, 0); second = new import__154.Cartesian4(1, -20, 26.4, 0); expected = new import__154.Cartesian4(2, -15, 26.5, 0); expect(import__154.Cartesian4.maximumByComponent(first, second, result)).toEqual( expected ); first = new import__154.Cartesian4(2, -15, 26.5, 450); second = new import__154.Cartesian4(1, -20, 26.4, -450); expected = new import__154.Cartesian4(2, -15, 26.5, 450); expect(import__154.Cartesian4.maximumByComponent(first, second, result)).toEqual( expected ); first = new import__154.Cartesian4(2, -15, 26.5, -450); second = new import__154.Cartesian4(1, -20, 26.4, 450); expected = new import__154.Cartesian4(2, -15, 26.5, 450); expect(import__154.Cartesian4.maximumByComponent(first, second, result)).toEqual( expected ); }); it("maximumByComponent with a result parameter", function() { const first = new import__154.Cartesian4(2, 0, 0, 0); const second = new import__154.Cartesian4(1, 0, 0, 0); const expected = new import__154.Cartesian4(2, 0, 0, 0); const result = new import__154.Cartesian4(); const returnedResult = import__154.Cartesian4.maximumByComponent(first, second, result); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expected); }); it("maximumByComponent with a result parameter that is an input parameter", function() { const first = new import__154.Cartesian4(2, 0, 0, 0); const second = new import__154.Cartesian4(1, 0, 0, 0); const expected = new import__154.Cartesian4(2, 0, 0, 0); expect(import__154.Cartesian4.maximumByComponent(first, second, first)).toEqual( expected ); first.x = 1; second.x = 2; expect(import__154.Cartesian4.maximumByComponent(first, second, second)).toEqual( expected ); }); it("maximumByComponent with a result parameter that is an input parameter", function() { const first = new import__154.Cartesian4(2, 0, 0, 0); const second = new import__154.Cartesian4(1, 0, 0, 0); const expected = new import__154.Cartesian4(2, 0, 0, 0); expect(import__154.Cartesian4.maximumByComponent(first, second, second)).toEqual( expected ); first.x = 1; second.x = 2; expect(import__154.Cartesian4.maximumByComponent(first, second, second)).toEqual( expected ); }); it("maximumByComponent throws without first", function() { expect(function() { import__154.Cartesian4.maximumByComponent(); }).toThrowDeveloperError(); }); it("maximumByComponent throws without second", function() { expect(function() { import__154.Cartesian4.maximumByComponent(new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("maximumByComponent works when first's or second's X is greater", function() { const first = new import__154.Cartesian4(2, 0, 0, 0); const second = new import__154.Cartesian4(1, 0, 0, 0); const expected = new import__154.Cartesian4(2, 0, 0, 0); const result = new import__154.Cartesian4(); expect(import__154.Cartesian4.maximumByComponent(first, second, result)).toEqual( expected ); second.x = 3; expected.x = 3; expect(import__154.Cartesian4.maximumByComponent(first, second, result)).toEqual( expected ); }); it("maximumByComponent works when first's or second's Y is greater", function() { const first = new import__154.Cartesian4(0, 2, 0, 0); const second = new import__154.Cartesian4(0, 1, 0, 0); const expected = new import__154.Cartesian4(0, 2, 0, 0); const result = new import__154.Cartesian4(); expect(import__154.Cartesian4.maximumByComponent(first, second, result)).toEqual( expected ); second.y = 3; expected.y = 3; expect(import__154.Cartesian4.maximumByComponent(first, second, result)).toEqual( expected ); }); it("maximumByComponent works when first's or second's Z is greater", function() { const first = new import__154.Cartesian4(0, 0, 2, 0); const second = new import__154.Cartesian4(0, 0, 1, 0); const expected = new import__154.Cartesian4(0, 0, 2, 0); const result = new import__154.Cartesian4(); expect(import__154.Cartesian4.maximumByComponent(first, second, result)).toEqual( expected ); second.z = 3; expected.z = 3; expect(import__154.Cartesian4.maximumByComponent(first, second, result)).toEqual( expected ); }); it("maximumByComponent works when first's or second's W is greater", function() { const first = new import__154.Cartesian4(0, 0, 0, 2); const second = new import__154.Cartesian4(0, 0, 0, 1); const expected = new import__154.Cartesian4(0, 0, 0, 2); const result = new import__154.Cartesian4(); expect(import__154.Cartesian4.maximumByComponent(first, second, result)).toEqual( expected ); second.w = 3; expected.w = 3; expect(import__154.Cartesian4.maximumByComponent(first, second, result)).toEqual( expected ); }); it("clamp", function() { let value; let min; let max; let expected; const result = new import__154.Cartesian4(); value = new import__154.Cartesian4(-1, 0, 0); min = new import__154.Cartesian4(0, 0, 0); max = new import__154.Cartesian4(1, 1, 1); expected = new import__154.Cartesian4(0, 0, 0); expect(import__154.Cartesian4.clamp(value, min, max, result)).toEqual(expected); value = new import__154.Cartesian4(2, 0, 0); min = new import__154.Cartesian4(0, 0, 0); max = new import__154.Cartesian4(1, 1, 1); expected = new import__154.Cartesian4(1, 0, 0); expect(import__154.Cartesian4.clamp(value, min, max, result)).toEqual(expected); value = new import__154.Cartesian4(0, -1, 0); min = new import__154.Cartesian4(0, 0, 0); max = new import__154.Cartesian4(1, 1, 1); expected = new import__154.Cartesian4(0, 0, 0); expect(import__154.Cartesian4.clamp(value, min, max, result)).toEqual(expected); value = new import__154.Cartesian4(0, 2, 0); min = new import__154.Cartesian4(0, 0, 0); max = new import__154.Cartesian4(1, 1, 1); expected = new import__154.Cartesian4(0, 1, 0); expect(import__154.Cartesian4.clamp(value, min, max, result)).toEqual(expected); value = new import__154.Cartesian4(0, 0, -1); min = new import__154.Cartesian4(0, 0, 0); max = new import__154.Cartesian4(1, 1, 1); expected = new import__154.Cartesian4(0, 0, 0); expect(import__154.Cartesian4.clamp(value, min, max, result)).toEqual(expected); value = new import__154.Cartesian4(0, 0, 2); min = new import__154.Cartesian4(0, 0, 0); max = new import__154.Cartesian4(1, 1, 1); expected = new import__154.Cartesian4(0, 0, 1); expect(import__154.Cartesian4.clamp(value, min, max, result)).toEqual(expected); value = new import__154.Cartesian4(-2, 3, 4); min = new import__154.Cartesian4(0, 0, 0); max = new import__154.Cartesian4(1, 1, 1); expected = new import__154.Cartesian4(0, 1, 1); expect(import__154.Cartesian4.clamp(value, min, max, result)).toEqual(expected); value = new import__154.Cartesian4(0, 0, 0); min = new import__154.Cartesian4(1, 2, 3); max = new import__154.Cartesian4(1, 2, 3); expected = new import__154.Cartesian4(1, 2, 3); expect(import__154.Cartesian4.clamp(value, min, max, result)).toEqual(expected); }); it("clamp with a result parameter", function() { const value = new import__154.Cartesian4(-1, -1, -1, -1); const min = new import__154.Cartesian4(0, 0, 0, 0); const max = new import__154.Cartesian4(1, 1, 1, 1); const expected = new import__154.Cartesian4(0, 0, 0, 0); const result = new import__154.Cartesian4(); const returnedResult = import__154.Cartesian4.clamp(value, min, max, result); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expected); }); it("clamp with a result parameter that is an input parameter", function() { const value = new import__154.Cartesian4(-1, -1, -1, -1); const min = new import__154.Cartesian4(0, 0, 0, 0); const max = new import__154.Cartesian4(1, 1, 1, 1); const expected = new import__154.Cartesian4(0, 0, 0, 0); expect(import__154.Cartesian4.clamp(value, min, max, value)).toEqual(expected); import__154.Cartesian4.fromElements(-1, -1, -1, -1, value); expect(import__154.Cartesian4.clamp(value, min, max, min)).toEqual(expected); import__154.Cartesian4.fromElements(0, 0, 0, 0, min); expect(import__154.Cartesian4.clamp(value, min, max, max)).toEqual(expected); }); it("clamp throws without value", function() { expect(function() { import__154.Cartesian4.clamp(); }).toThrowDeveloperError(); }); it("clamp throws without min", function() { expect(function() { import__154.Cartesian4.clamp(new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("clamp throws without max", function() { expect(function() { import__154.Cartesian4.clamp(new import__154.Cartesian4(), new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("magnitudeSquared", function() { const cartesian = new import__154.Cartesian4(3, 4, 5, 6); expect(import__154.Cartesian4.magnitudeSquared(cartesian)).toEqual(86); }); it("magnitude", function() { const cartesian = new import__154.Cartesian4(3, 4, 5, 6); expect(import__154.Cartesian4.magnitude(cartesian)).toEqual(Math.sqrt(86)); }); it("distance", function() { const distance = import__154.Cartesian4.distance( new import__154.Cartesian4(1, 0, 0, 0), new import__154.Cartesian4(2, 0, 0, 0) ); expect(distance).toEqual(1); }); it("distance throws without left", function() { expect(function() { import__154.Cartesian4.distance(); }).toThrowDeveloperError(); }); it("distance throws without right", function() { expect(function() { import__154.Cartesian4.distance(import__154.Cartesian4.UNIT_X); }).toThrowDeveloperError(); }); it("distanceSquared", function() { const distanceSquared = import__154.Cartesian4.distanceSquared( new import__154.Cartesian4(1, 0, 0, 0), new import__154.Cartesian4(3, 0, 0, 0) ); expect(distanceSquared).toEqual(4); }); it("distanceSquared throws without left", function() { expect(function() { import__154.Cartesian4.distanceSquared(); }).toThrowDeveloperError(); }); it("distanceSquared throws without right", function() { expect(function() { import__154.Cartesian4.distanceSquared(import__154.Cartesian4.UNIT_X); }).toThrowDeveloperError(); }); it("normalize works with a result parameter", function() { const cartesian = new import__154.Cartesian4(2, 0, 0, 0); const expectedResult = new import__154.Cartesian4(1, 0, 0, 0); const result = new import__154.Cartesian4(); const returnedResult = import__154.Cartesian4.normalize(cartesian, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("normalize works with a result parameter that is an input parameter", function() { const cartesian = new import__154.Cartesian4(2, 0, 0, 0); const expectedResult = new import__154.Cartesian4(1, 0, 0, 0); const returnedResult = import__154.Cartesian4.normalize(cartesian, cartesian); expect(cartesian).toBe(returnedResult); expect(cartesian).toEqual(expectedResult); }); it("normalize throws with zero vector", function() { expect(function() { import__154.Cartesian4.normalize(import__154.Cartesian4.ZERO, new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("multiplyComponents works with a result parameter", function() { const left = new import__154.Cartesian4(2, 3, 6, 8); const right = new import__154.Cartesian4(4, 5, 7, 9); const result = new import__154.Cartesian4(); const expectedResult = new import__154.Cartesian4(8, 15, 42, 72); const returnedResult = import__154.Cartesian4.multiplyComponents(left, right, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("multiplyComponents works with a result parameter that is an input parameter", function() { const left = new import__154.Cartesian4(2, 3, 6, 8); const right = new import__154.Cartesian4(4, 5, 7, 9); const expectedResult = new import__154.Cartesian4(8, 15, 42, 72); const returnedResult = import__154.Cartesian4.multiplyComponents(left, right, left); expect(left).toBe(returnedResult); expect(left).toEqual(expectedResult); }); it("divideComponents works with a result parameter", function() { const left = new import__154.Cartesian4(2, 3, 6, 15); const right = new import__154.Cartesian4(4, 5, 8, 2); const result = new import__154.Cartesian4(); const expectedResult = new import__154.Cartesian4(0.5, 0.6, 0.75, 7.5); const returnedResult = import__154.Cartesian4.divideComponents(left, right, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("divideComponents works with a result parameter that is an input parameter", function() { const left = new import__154.Cartesian4(2, 3, 6, 15); const right = new import__154.Cartesian4(4, 5, 8, 2); const expectedResult = new import__154.Cartesian4(0.5, 0.6, 0.75, 7.5); const returnedResult = import__154.Cartesian4.divideComponents(left, right, left); expect(left).toBe(returnedResult); expect(left).toEqual(expectedResult); }); it("dot", function() { const left = new import__154.Cartesian4(2, 3, 6, 8); const right = new import__154.Cartesian4(4, 5, 7, 9); const expectedResult = 137; const result = import__154.Cartesian4.dot(left, right); expect(result).toEqual(expectedResult); }); it("add works with a result parameter", function() { const left = new import__154.Cartesian4(2, 3, 6, 8); const right = new import__154.Cartesian4(4, 5, 7, 9); const result = new import__154.Cartesian4(); const expectedResult = new import__154.Cartesian4(6, 8, 13, 17); const returnedResult = import__154.Cartesian4.add(left, right, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("add works with a result parameter that is an input parameter", function() { const left = new import__154.Cartesian4(2, 3, 6, 8); const right = new import__154.Cartesian4(4, 5, 7, 9); const expectedResult = new import__154.Cartesian4(6, 8, 13, 17); const returnedResult = import__154.Cartesian4.add(left, right, left); expect(left).toBe(returnedResult); expect(left).toEqual(expectedResult); }); it("subtract works with a result parameter", function() { const left = new import__154.Cartesian4(2, 3, 4, 8); const right = new import__154.Cartesian4(1, 5, 7, 9); const result = new import__154.Cartesian4(); const expectedResult = new import__154.Cartesian4(1, -2, -3, -1); const returnedResult = import__154.Cartesian4.subtract(left, right, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("subtract works with this result parameter", function() { const left = new import__154.Cartesian4(2, 3, 4, 8); const right = new import__154.Cartesian4(1, 5, 7, 9); const expectedResult = new import__154.Cartesian4(1, -2, -3, -1); const returnedResult = import__154.Cartesian4.subtract(left, right, left); expect(returnedResult).toBe(left); expect(left).toEqual(expectedResult); }); it("multiplyByScalar with a result parameter", function() { const cartesian = new import__154.Cartesian4(1, 2, 3, 4); const result = new import__154.Cartesian4(); const scalar = 2; const expectedResult = new import__154.Cartesian4(2, 4, 6, 8); const returnedResult = import__154.Cartesian4.multiplyByScalar( cartesian, scalar, result ); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("multiplyByScalar with a result parameter that is an input parameter", function() { const cartesian = new import__154.Cartesian4(1, 2, 3, 4); const scalar = 2; const expectedResult = new import__154.Cartesian4(2, 4, 6, 8); const returnedResult = import__154.Cartesian4.multiplyByScalar( cartesian, scalar, cartesian ); expect(cartesian).toBe(returnedResult); expect(cartesian).toEqual(expectedResult); }); it("divideByScalar with a result parameter", function() { const cartesian = new import__154.Cartesian4(1, 2, 3, 4); const result = new import__154.Cartesian4(); const scalar = 2; const expectedResult = new import__154.Cartesian4(0.5, 1, 1.5, 2); const returnedResult = import__154.Cartesian4.divideByScalar(cartesian, scalar, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("divideByScalar with a result parameter that is an input parameter", function() { const cartesian = new import__154.Cartesian4(1, 2, 3, 4); const scalar = 2; const expectedResult = new import__154.Cartesian4(0.5, 1, 1.5, 2); const returnedResult = import__154.Cartesian4.divideByScalar( cartesian, scalar, cartesian ); expect(cartesian).toBe(returnedResult); expect(cartesian).toEqual(expectedResult); }); it("negate with a result parameter", function() { const cartesian = new import__154.Cartesian4(1, -2, -5, 4); const result = new import__154.Cartesian4(); const expectedResult = new import__154.Cartesian4(-1, 2, 5, -4); const returnedResult = import__154.Cartesian4.negate(cartesian, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("negate with a result parameter that is an input parameter", function() { const cartesian = new import__154.Cartesian4(1, -2, -5); const expectedResult = new import__154.Cartesian4(-1, 2, 5); const returnedResult = import__154.Cartesian4.negate(cartesian, cartesian); expect(cartesian).toBe(returnedResult); expect(cartesian).toEqual(expectedResult); }); it("abs with a result parameter", function() { const cartesian = new import__154.Cartesian4(1, -2, -4, -3); const result = new import__154.Cartesian4(); const expectedResult = new import__154.Cartesian4(1, 2, 4, 3); const returnedResult = import__154.Cartesian4.abs(cartesian, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("abs with a result parameter that is an input parameter", function() { const cartesian = new import__154.Cartesian4(1, -2, -4, -3); const expectedResult = new import__154.Cartesian4(1, 2, 4, 3); const returnedResult = import__154.Cartesian4.abs(cartesian, cartesian); expect(cartesian).toBe(returnedResult); expect(cartesian).toEqual(expectedResult); }); it("lerp works with a result parameter that is an input parameter", function() { const start = new import__154.Cartesian4(4, 8, 10, 20); const end = new import__154.Cartesian4(8, 20, 20, 30); const t = 0.25; const expectedResult = new import__154.Cartesian4(5, 11, 12.5, 22.5); const returnedResult = import__154.Cartesian4.lerp(start, end, t, start); expect(start).toBe(returnedResult); expect(start).toEqual(expectedResult); }); it("lerp extrapolate forward", function() { const start = new import__154.Cartesian4(4, 8, 10, 20); const end = new import__154.Cartesian4(8, 20, 20, 30); const t = 2; let result = new import__154.Cartesian4(); const expectedResult = new import__154.Cartesian4(12, 32, 30, 40); result = import__154.Cartesian4.lerp(start, end, t, result); expect(result).toEqual(expectedResult); }); it("lerp extrapolate backward", function() { const start = new import__154.Cartesian4(4, 8, 10, 20); const end = new import__154.Cartesian4(8, 20, 20, 30); const t = -1; let result = new import__154.Cartesian4(); const expectedResult = new import__154.Cartesian4(0, -4, 0, 10); result = import__154.Cartesian4.lerp(start, end, t, result); expect(result).toEqual(expectedResult); }); it("most orthogonal angle is x", function() { const v = new import__154.Cartesian4(0, 1, 2, 3); expect(import__154.Cartesian4.mostOrthogonalAxis(v, new import__154.Cartesian4())).toEqual( import__154.Cartesian4.UNIT_X ); }); it("most orthogonal angle is y", function() { const v = new import__154.Cartesian4(1, 0, 2, 3); expect(import__154.Cartesian4.mostOrthogonalAxis(v, new import__154.Cartesian4())).toEqual( import__154.Cartesian4.UNIT_Y ); }); it("most orthogonal angle is z", function() { let v = new import__154.Cartesian4(2, 3, 0, 1); expect(import__154.Cartesian4.mostOrthogonalAxis(v, new import__154.Cartesian4())).toEqual( import__154.Cartesian4.UNIT_Z ); v = new import__154.Cartesian4(3, 2, 0, 1); expect(import__154.Cartesian4.mostOrthogonalAxis(v, new import__154.Cartesian4())).toEqual( import__154.Cartesian4.UNIT_Z ); }); it("most orthogonal angle is w", function() { let v = new import__154.Cartesian4(1, 2, 3, 0); expect(import__154.Cartesian4.mostOrthogonalAxis(v, new import__154.Cartesian4())).toEqual( import__154.Cartesian4.UNIT_W ); v = new import__154.Cartesian4(2, 3, 1, 0); expect(import__154.Cartesian4.mostOrthogonalAxis(v, new import__154.Cartesian4())).toEqual( import__154.Cartesian4.UNIT_W ); v = new import__154.Cartesian4(3, 1, 2, 0); expect(import__154.Cartesian4.mostOrthogonalAxis(v, new import__154.Cartesian4())).toEqual( import__154.Cartesian4.UNIT_W ); v = new import__154.Cartesian4(3, 2, 1, 0); expect(import__154.Cartesian4.mostOrthogonalAxis(v, new import__154.Cartesian4())).toEqual( import__154.Cartesian4.UNIT_W ); }); it("equals", function() { const cartesian = new import__154.Cartesian4(1, 2, 3, 4); expect( import__154.Cartesian4.equals(cartesian, new import__154.Cartesian4(1, 2, 3, 4)) ).toEqual(true); expect( import__154.Cartesian4.equals(cartesian, new import__154.Cartesian4(2, 2, 3, 4)) ).toEqual(false); expect( import__154.Cartesian4.equals(cartesian, new import__154.Cartesian4(2, 1, 3, 4)) ).toEqual(false); expect( import__154.Cartesian4.equals(cartesian, new import__154.Cartesian4(1, 2, 4, 4)) ).toEqual(false); expect( import__154.Cartesian4.equals(cartesian, new import__154.Cartesian4(1, 2, 3, 5)) ).toEqual(false); expect(import__154.Cartesian4.equals(cartesian, void 0)).toEqual(false); }); it("equalsEpsilon", function() { let cartesian = new import__154.Cartesian4(1, 2, 3, 4); expect( cartesian.equalsEpsilon(new import__154.Cartesian4(1, 2, 3, 4), 0) ).toEqual(true); expect( cartesian.equalsEpsilon(new import__154.Cartesian4(1, 2, 3, 4), 1) ).toEqual(true); expect( cartesian.equalsEpsilon(new import__154.Cartesian4(2, 2, 3, 4), 1) ).toEqual(true); expect( cartesian.equalsEpsilon(new import__154.Cartesian4(1, 3, 3, 4), 1) ).toEqual(true); expect( cartesian.equalsEpsilon(new import__154.Cartesian4(1, 2, 4, 4), 1) ).toEqual(true); expect( cartesian.equalsEpsilon(new import__154.Cartesian4(1, 2, 3, 5), 1) ).toEqual(true); expect( cartesian.equalsEpsilon( new import__154.Cartesian4(2, 2, 3, 4), import__155.Math.EPSILON6 ) ).toEqual(false); expect( cartesian.equalsEpsilon( new import__154.Cartesian4(1, 3, 3, 4), import__155.Math.EPSILON6 ) ).toEqual(false); expect( cartesian.equalsEpsilon( new import__154.Cartesian4(1, 2, 4, 4), import__155.Math.EPSILON6 ) ).toEqual(false); expect( cartesian.equalsEpsilon( new import__154.Cartesian4(1, 2, 3, 5), import__155.Math.EPSILON6 ) ).toEqual(false); expect(cartesian.equalsEpsilon(void 0, 1)).toEqual(false); cartesian = new import__154.Cartesian4(3e6, 4e6, 5e6, 6e6); expect( cartesian.equalsEpsilon( new import__154.Cartesian4(3e6, 4e6, 5e6, 6e6), 0 ) ).toEqual(true); expect( cartesian.equalsEpsilon( new import__154.Cartesian4(30000002e-1, 4e6, 5e6, 6e6), import__155.Math.EPSILON7 ) ).toEqual(true); expect( cartesian.equalsEpsilon( new import__154.Cartesian4(3e6, 40000002e-1, 5e6, 6e6), import__155.Math.EPSILON7 ) ).toEqual(true); expect( cartesian.equalsEpsilon( new import__154.Cartesian4(3e6, 4e6, 50000002e-1, 6e6), import__155.Math.EPSILON7 ) ).toEqual(true); expect( cartesian.equalsEpsilon( new import__154.Cartesian4(3e6, 4e6, 5e6, 60000002e-1), import__155.Math.EPSILON7 ) ).toEqual(true); expect( cartesian.equalsEpsilon( new import__154.Cartesian4(30000002e-1, 40000002e-1, 50000002e-1, 60000002e-1), import__155.Math.EPSILON7 ) ).toEqual(true); expect( cartesian.equalsEpsilon( new import__154.Cartesian4(30000002e-1, 40000002e-1, 50000002e-1, 60000002e-1), import__155.Math.EPSILON9 ) ).toEqual(false); expect(cartesian.equalsEpsilon(void 0, 1)).toEqual(false); expect(import__154.Cartesian4.equalsEpsilon(void 0, cartesian, 1)).toEqual(false); }); it("toString", function() { const cartesian = new import__154.Cartesian4(1.123, 2.345, 6.789, 6.123); expect(cartesian.toString()).toEqual("(1.123, 2.345, 6.789, 6.123)"); }); it("clone returns undefined with no parameter", function() { expect(import__154.Cartesian4.clone()).toBeUndefined(); }); it("maximumComponent throws with no parameter", function() { expect(function() { import__154.Cartesian4.maximumComponent(); }).toThrowDeveloperError(); }); it("minimumComponent throws with no parameter", function() { expect(function() { import__154.Cartesian4.minimumComponent(); }).toThrowDeveloperError(); }); it("magnitudeSquared throws with no parameter", function() { expect(function() { import__154.Cartesian4.magnitudeSquared(); }).toThrowDeveloperError(); }); it("magnitude throws with no parameter", function() { expect(function() { import__154.Cartesian4.magnitude(); }).toThrowDeveloperError(); }); it("normalize throws with no parameter", function() { expect(function() { import__154.Cartesian4.normalize(); }).toThrowDeveloperError(); }); it("dot throws with no left parameter", function() { expect(function() { import__154.Cartesian4.dot(void 0, new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("multiplyComponents throw with no left parameter", function() { const right = new import__154.Cartesian4(4, 5, 6, 7); expect(function() { import__154.Cartesian4.multiplyComponents(void 0, right); }).toThrowDeveloperError(); }); it("multiplyComponents throw with no right parameter", function() { const left = new import__154.Cartesian4(4, 5, 6, 7); expect(function() { import__154.Cartesian4.multiplyComponents(left, void 0); }).toThrowDeveloperError(); }); it("divideComponents throw with no left parameter", function() { const right = new import__154.Cartesian4(4, 5, 6, 7); expect(function() { import__154.Cartesian4.divideComponents(void 0, right); }).toThrowDeveloperError(); }); it("divideComponents throw with no right parameter", function() { const left = new import__154.Cartesian4(4, 5, 6, 7); expect(function() { import__154.Cartesian4.divideComponents(left, void 0); }).toThrowDeveloperError(); }); it("dot throws with no right parameter", function() { expect(function() { import__154.Cartesian4.dot(new import__154.Cartesian4(), void 0); }).toThrowDeveloperError(); }); it("add throws with no left parameter", function() { expect(function() { import__154.Cartesian4.add(void 0, new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("add throws with no right parameter", function() { expect(function() { import__154.Cartesian4.add(new import__154.Cartesian4(), void 0); }).toThrowDeveloperError(); }); it("subtract throws with no left parameter", function() { expect(function() { import__154.Cartesian4.subtract(void 0, new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("subtract throws with no right parameter", function() { expect(function() { import__154.Cartesian4.subtract(new import__154.Cartesian4(), void 0); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with no cartesian parameter", function() { expect(function() { import__154.Cartesian4.multiplyByScalar(void 0, 2); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with no scalar parameter", function() { expect(function() { import__154.Cartesian4.multiplyByScalar(new import__154.Cartesian4(), void 0); }).toThrowDeveloperError(); }); it("divideByScalar throws with no cartesian parameter", function() { expect(function() { import__154.Cartesian4.divideByScalar(void 0, 2); }).toThrowDeveloperError(); }); it("divideByScalar throws with no scalar parameter", function() { expect(function() { import__154.Cartesian4.divideByScalar(new import__154.Cartesian4(), void 0); }).toThrowDeveloperError(); }); it("negate throws with no cartesian parameter", function() { expect(function() { import__154.Cartesian4.negate(void 0); }).toThrowDeveloperError(); }); it("abs throws with no cartesian parameter", function() { expect(function() { import__154.Cartesian4.abs(void 0); }).toThrowDeveloperError(); }); it("lerp throws with no start parameter", function() { const end = new import__154.Cartesian4(8, 20, 6); const t = 0.25; expect(function() { import__154.Cartesian4.lerp(void 0, end, t); }).toThrowDeveloperError(); }); it("lerp throws with no end parameter", function() { const start = new import__154.Cartesian4(4, 8, 6); const t = 0.25; expect(function() { import__154.Cartesian4.lerp(start, void 0, t); }).toThrowDeveloperError(); }); it("lerp throws with no t parameter", function() { const start = new import__154.Cartesian4(4, 8, 6, 7); const end = new import__154.Cartesian4(8, 20, 6, 7); expect(function() { import__154.Cartesian4.lerp(start, end, void 0); }).toThrowDeveloperError(); }); it("mostOrthogonalAxis throws with no cartesian parameter", function() { expect(function() { import__154.Cartesian4.mostOrthogonalAxis(void 0); }).toThrowDeveloperError(); }); it("minimumByComponent throws with no result", function() { expect(function() { import__154.Cartesian4.minimumByComponent(new import__154.Cartesian4(), new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("maximumByComponent throws with no result", function() { expect(function() { import__154.Cartesian4.maximumByComponent(new import__154.Cartesian4(), new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("clamp throws with no result", function() { expect(function() { import__154.Cartesian4.clamp(new import__154.Cartesian4(), new import__154.Cartesian4(), new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("normalize throws with no result", function() { expect(function() { import__154.Cartesian4.normalize(new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("multiplyComponents throws with no result", function() { expect(function() { import__154.Cartesian4.multiplyComponents(new import__154.Cartesian4(), new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("divideComponents throws with no result", function() { expect(function() { import__154.Cartesian4.divideComponents(new import__154.Cartesian4(), new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("add throws with no result", function() { expect(function() { import__154.Cartesian4.add(new import__154.Cartesian4(), new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("subtract throws with no result", function() { expect(function() { import__154.Cartesian4.subtract(new import__154.Cartesian4(), new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with no result", function() { expect(function() { import__154.Cartesian4.multiplyByScalar(new import__154.Cartesian4(), 2); }).toThrowDeveloperError(); }); it("divideByScalar throws with no result", function() { expect(function() { import__154.Cartesian4.divideByScalar(new import__154.Cartesian4(), 2); }).toThrowDeveloperError(); }); it("negate throws with no result", function() { expect(function() { import__154.Cartesian4.negate(new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("abs throws with no result", function() { expect(function() { import__154.Cartesian4.abs(new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("mostOrthogonalAxis throws with no result", function() { expect(function() { import__154.Cartesian4.mostOrthogonalAxis(new import__154.Cartesian4()); }).toThrowDeveloperError(); }); it("packs and unpacks floating point values for representation as uint8 4-vectors", function() { function testFloat(float) { const packedFloat = import__154.Cartesian4.packFloat(float); expect(0 <= packedFloat.x && packedFloat.x <= 255).toBe(true); expect(0 <= packedFloat.y && packedFloat.y <= 255).toBe(true); expect(0 <= packedFloat.z && packedFloat.z <= 255).toBe(true); expect(0 <= packedFloat.w && packedFloat.w <= 255).toBe(true); const unpackedFloat = import__154.Cartesian4.unpackFloat(packedFloat); expect(unpackedFloat).toEqual(float); } function testFloatNaN(float) { expect(float).toBeNaN(); const packedFloat = import__154.Cartesian4.packFloat(float); const unpackedFloat = import__154.Cartesian4.unpackFloat(packedFloat); expect(unpackedFloat).toBeNaN(); } function testFloatOutOfRange(float) { const packedFloat = import__154.Cartesian4.packFloat(float); const unpackedFloat = import__154.Cartesian4.unpackFloat(packedFloat); expect(unpackedFloat).toEqual(import__155.Math.sign(float) * Infinity); } testFloat(0); testFloat(-1); testFloat(1); testFloat(123.5); testFloat(16777216); testFloat(Infinity); testFloat(-Infinity); testFloatNaN(NaN); testFloatOutOfRange(+Number.MAX_VALUE); testFloatOutOfRange(-Number.MAX_VALUE); const f32 = new Float32Array(1); f32[0] = Infinity; testFloat(f32[0]); f32[0] = -Infinity; testFloat(f32[0]); f32[0] = NaN; testFloatNaN(f32[0]); }); createPackableSpecs_default(import__154.Cartesian4, new import__154.Cartesian4(1, 2, 3, 4), [1, 2, 3, 4]); createPackableArraySpecs_default( import__154.Cartesian4, [new import__154.Cartesian4(1, 2, 3, 4), new import__154.Cartesian4(5, 6, 7, 8)], [1, 2, 3, 4, 5, 6, 7, 8], 4 ); }); // packages/engine/Specs/Core/CartographicGeocoderServiceSpec.js var import__156 = __toESM(require_Cesium(), 1); describe("Core/CartographicGeocoderService", function() { const service = new import__156.CartographicGeocoderService(); it("conforms to GeocoderService interface", function() { expect(import__156.CartographicGeocoderService).toConformToInterface(import__156.GeocoderService); }); it("returns cartesian with matching coordinates for NS/EW input", function() { const query = "35N 75W"; return service.geocode(query).then(function(results) { expect(results.length).toEqual(1); expect(results[0].destination).toEqual( import__156.Cartesian3.fromDegrees(-75, 35, 300) ); }); }); it("returns cartesian with matching coordinates for EW/NS input", function() { const query = "75W 35N"; return service.geocode(query).then(function(results) { expect(results.length).toEqual(1); expect(results[0].destination).toEqual( import__156.Cartesian3.fromDegrees(-75, 35, 300) ); }); }); it("returns cartesian with matching coordinates for long/lat/height input", function() { const query = " 1.0, 2.0, 3.0 "; return service.geocode(query).then(function(results) { expect(results.length).toEqual(1); expect(results[0].destination).toEqual( import__156.Cartesian3.fromDegrees(1, 2, 3) ); }); }); it("returns cartesian with matching coordinates for long/lat input", function() { const query = " 1.0, 2.0 "; const defaultHeight = 300; return service.geocode(query).then(function(results) { expect(results.length).toEqual(1); expect(results[0].destination).toEqual( import__156.Cartesian3.fromDegrees(1, 2, defaultHeight) ); }); }); it("returns empty array for input with only longitudinal coordinates", function() { const query = " 1e 1e "; return service.geocode(query).then(function(results) { expect(results.length).toEqual(0); }); }); it("returns empty array for input with only one NSEW coordinate", function() { const query = " 1e 1 "; return service.geocode(query).then(function(results) { expect(results.length).toEqual(0); }); }); it("returns empty array for input with only one number", function() { const query = " 2.0 "; return service.geocode(query).then(function(results) { expect(results.length).toEqual(0); }); }); it("returns empty array for with string", function() { const query = " aoeu "; return service.geocode(query).then(function(results) { expect(results.length).toEqual(0); }); }); }); // packages/engine/Specs/Core/CartographicSpec.js var import__157 = __toESM(require_Cesium(), 1); var import__158 = __toESM(require_Cesium(), 1); describe("Core/Cartographic", function() { const surfaceCartesian = new import__157.Cartesian3( 4.0943277921465295e6, 1909216404474774e-9, 4487348408865919e-9 ); const surfaceCartographic = new import__157.Cartographic( import__158.Math.toRadians(25), import__158.Math.toRadians(45), 0 ); it("default constructor sets expected properties", function() { const c = new import__157.Cartographic(); expect(c.longitude).toEqual(0); expect(c.latitude).toEqual(0); expect(c.height).toEqual(0); }); it("constructor sets expected properties from parameters", function() { const c = new import__157.Cartographic(1, 2, 3); expect(c.longitude).toEqual(1); expect(c.latitude).toEqual(2); expect(c.height).toEqual(3); }); it("toCartesian conversion from Cartographic input to Cartesian3 output", function() { const lon = import__158.Math.toRadians(150); const lat = import__158.Math.toRadians(-40); const height = 1e5; const ellipsoid = import__157.Ellipsoid.WGS84; const actual = import__157.Cartographic.toCartesian(new import__157.Cartographic(lon, lat, height)); const expected = ellipsoid.cartographicToCartesian( new import__157.Cartographic(lon, lat, height) ); expect(actual).toEqual(expected); }); it("fromRadians works without a result parameter", function() { const c = import__157.Cartographic.fromRadians(Math.PI / 2, Math.PI / 4, 100); expect(c.longitude).toEqual(Math.PI / 2); expect(c.latitude).toEqual(Math.PI / 4); expect(c.height).toEqual(100); }); it("fromRadians works with a result parameter", function() { const result = new import__157.Cartographic(); const c = import__157.Cartographic.fromRadians(Math.PI / 2, Math.PI / 4, 100, result); expect(result).toBe(c); expect(c.longitude).toEqual(Math.PI / 2); expect(c.latitude).toEqual(Math.PI / 4); expect(c.height).toEqual(100); }); it("fromRadians throws without longitude or latitude parameter but defaults altitude", function() { expect(function() { import__157.Cartographic.fromRadians(void 0, 0); }).toThrowDeveloperError(); expect(function() { import__157.Cartographic.fromRadians(0, void 0); }).toThrowDeveloperError(); const c = import__157.Cartographic.fromRadians(Math.PI / 2, Math.PI / 4); expect(c.longitude).toEqual(Math.PI / 2); expect(c.latitude).toEqual(Math.PI / 4); expect(c.height).toEqual(0); }); it("fromDegrees works without a result parameter", function() { const c = import__157.Cartographic.fromDegrees(90, 45, 100); expect(c.longitude).toEqual(Math.PI / 2); expect(c.latitude).toEqual(Math.PI / 4); expect(c.height).toEqual(100); }); it("fromDegrees works with a result parameter", function() { const result = new import__157.Cartographic(); const c = import__157.Cartographic.fromDegrees(90, 45, 100, result); expect(result).toBe(c); expect(c.longitude).toEqual(Math.PI / 2); expect(c.latitude).toEqual(Math.PI / 4); expect(c.height).toEqual(100); }); it("fromDegrees throws without longitude or latitude parameter but defaults altitude", function() { expect(function() { import__157.Cartographic.fromDegrees(void 0, 0); }).toThrowDeveloperError(); expect(function() { import__157.Cartographic.fromDegrees(0, void 0); }).toThrowDeveloperError(); const c = import__157.Cartographic.fromDegrees(90, 45); expect(c.longitude).toEqual(Math.PI / 2); expect(c.latitude).toEqual(Math.PI / 4); expect(c.height).toEqual(0); }); it("fromCartesian works without a result parameter", function() { const ellipsoid = import__157.Ellipsoid.WGS84; const c = import__157.Cartographic.fromCartesian(surfaceCartesian, ellipsoid); expect(c).toEqualEpsilon(surfaceCartographic, import__158.Math.EPSILON8); }); it("fromCartesian works with a result parameter", function() { const ellipsoid = import__157.Ellipsoid.WGS84; const result = new import__157.Cartographic(); const c = import__157.Cartographic.fromCartesian(surfaceCartesian, ellipsoid, result); expect(c).toEqualEpsilon(surfaceCartographic, import__158.Math.EPSILON8); expect(result).toBe(c); }); it("fromCartesian works without an ellipsoid", function() { const c = import__157.Cartographic.fromCartesian(surfaceCartesian); expect(c).toEqualEpsilon(surfaceCartographic, import__158.Math.EPSILON8); }); it("fromCartesian throws when there is no cartesian", function() { expect(function() { import__157.Cartographic.fromCartesian(); }).toThrowDeveloperError(); }); it("fromCartesian works with a value that is above the ellipsoid surface", function() { const cartographic1 = import__157.Cartographic.fromDegrees(35.766989, 33.333602, 3e3); const cartesian1 = import__157.Cartesian3.fromRadians( cartographic1.longitude, cartographic1.latitude, cartographic1.height ); const cartographic2 = import__157.Cartographic.fromCartesian(cartesian1); expect(cartographic2).toEqualEpsilon(cartographic1, import__158.Math.EPSILON8); }); it("fromCartesian works with a value that is bellow the ellipsoid surface", function() { const cartographic1 = import__157.Cartographic.fromDegrees(35.766989, 33.333602, -3e3); const cartesian1 = import__157.Cartesian3.fromRadians( cartographic1.longitude, cartographic1.latitude, cartographic1.height ); const cartographic2 = import__157.Cartographic.fromCartesian(cartesian1); expect(cartographic2).toEqualEpsilon(cartographic1, import__158.Math.EPSILON8); }); it("clone without a result parameter", function() { const cartographic = new import__157.Cartographic(1, 2, 3); const result = cartographic.clone(); expect(cartographic).not.toBe(result); expect(cartographic).toEqual(result); }); it("clone with a result parameter", function() { const cartographic = new import__157.Cartographic(1, 2, 3); const result = new import__157.Cartographic(); const returnedResult = cartographic.clone(result); expect(cartographic).not.toBe(result); expect(result).toBe(returnedResult); expect(cartographic).toEqual(result); }); it('clone works with "this" result parameter', function() { const cartographic = new import__157.Cartographic(1, 2, 3); const returnedResult = cartographic.clone(cartographic); expect(cartographic).toBe(returnedResult); }); it("equals", function() { const cartographic = new import__157.Cartographic(1, 2, 3); expect(cartographic.equals(new import__157.Cartographic(1, 2, 3))).toEqual(true); expect(cartographic.equals(new import__157.Cartographic(2, 2, 3))).toEqual(false); expect(cartographic.equals(new import__157.Cartographic(2, 1, 3))).toEqual(false); expect(cartographic.equals(new import__157.Cartographic(1, 2, 4))).toEqual(false); expect(cartographic.equals(void 0)).toEqual(false); }); it("equalsEpsilon", function() { const cartographic = new import__157.Cartographic(1, 2, 3); expect( cartographic.equalsEpsilon(new import__157.Cartographic(1, 2, 3), 0) ).toEqual(true); expect( cartographic.equalsEpsilon(new import__157.Cartographic(1, 2, 3), 1) ).toEqual(true); expect( cartographic.equalsEpsilon(new import__157.Cartographic(2, 2, 3), 1) ).toEqual(true); expect( cartographic.equalsEpsilon(new import__157.Cartographic(1, 3, 3), 1) ).toEqual(true); expect( cartographic.equalsEpsilon(new import__157.Cartographic(1, 2, 4), 1) ).toEqual(true); expect( cartographic.equalsEpsilon(new import__157.Cartographic(2, 2, 3), 0.99999) ).toEqual(false); expect( cartographic.equalsEpsilon(new import__157.Cartographic(1, 3, 3), 0.99999) ).toEqual(false); expect( cartographic.equalsEpsilon(new import__157.Cartographic(1, 2, 4), 0.99999) ).toEqual(false); expect(cartographic.equalsEpsilon(void 0, 1)).toEqual(false); }); it("toString", function() { const cartographic = new import__157.Cartographic(1.123, 2.345, 6.789); expect(cartographic.toString()).toEqual("(1.123, 2.345, 6.789)"); }); it("clone returns undefined without cartographic parameter", function() { expect(import__157.Cartographic.clone(void 0)).toBeUndefined(); }); }); // packages/engine/Specs/Core/CatmullRomSplineSpec.js var import__159 = __toESM(require_Cesium(), 1); var import__160 = __toESM(require_Cesium(), 1); describe("Core/CatmullRomSpline", function() { let points; let times; beforeEach(function() { points = [ new import__159.Cartesian3(-1, -1, 0), new import__159.Cartesian3(-0.5, -0.125, 0), new import__159.Cartesian3(0.5, 0.125, 0), new import__159.Cartesian3(1, 1, 0) ]; times = [0, 1, 2, 3]; }); it("constructor throws without points or times", function() { expect(function() { return new import__159.CatmullRomSpline(); }).toThrowDeveloperError(); }); it("constructor throws when control points length is less than 2", function() { expect(function() { return new import__159.CatmullRomSpline({ points: [import__159.Cartesian3.ZERO] }); }).toThrowDeveloperError(); }); it("constructor throws when times.length is not equal to points.length", function() { expect(function() { return new import__159.CatmullRomSpline({ points, times: [0, 1] }); }).toThrowDeveloperError(); }); it("sets start and end tangents", function() { const start = import__159.Cartesian3.subtract(points[1], points[0], new import__159.Cartesian3()); const end = import__159.Cartesian3.subtract( points[points.length - 1], points[points.length - 2], new import__159.Cartesian3() ); const crs = new import__159.CatmullRomSpline({ points, times, firstTangent: start, lastTangent: end }); expect(start).toEqual(crs.firstTangent); expect(end).toEqual(crs.lastTangent); }); it("computes start and end tangents", function() { const controlPoint0 = import__159.Cartesian3.clone(points[0]); const controlPoint1 = import__159.Cartesian3.clone(points[1]); const controlPoint2 = import__159.Cartesian3.clone(points[2]); let start = new import__159.Cartesian3(); start = import__159.Cartesian3.multiplyByScalar( import__159.Cartesian3.subtract( import__159.Cartesian3.subtract( import__159.Cartesian3.multiplyByScalar(controlPoint1, 2, start), controlPoint2, start ), controlPoint0, start ), 0.5, start ); const controlPointn0 = import__159.Cartesian3.clone(points[points.length - 1]); const controlPointn1 = import__159.Cartesian3.clone(points[points.length - 2]); const controlPointn2 = import__159.Cartesian3.clone(points[points.length - 3]); let end = new import__159.Cartesian3(); end = import__159.Cartesian3.multiplyByScalar( import__159.Cartesian3.add( import__159.Cartesian3.subtract( controlPointn0, import__159.Cartesian3.multiplyByScalar(controlPointn1, 2, end), end ), controlPointn2, end ), 0.5, end ); const crs = new import__159.CatmullRomSpline({ points, times }); expect(start).toEqual(crs.firstTangent); expect(end).toEqual(crs.lastTangent); }); it("evaluate throws without time", function() { const crs = new import__159.CatmullRomSpline({ points, times }); expect(function() { crs.evaluate(); }).toThrowDeveloperError(); }); it("evaluate throws when time is out of range", function() { const crs = new import__159.CatmullRomSpline({ points, times }); expect(function() { crs.evaluate(times[0] - 1); }).toThrowDeveloperError(); }); it("check Catmull-Rom spline against a Hermite spline", function() { const crs = new import__159.CatmullRomSpline({ points, times }); const tangents = [crs.firstTangent]; for (let i = 1; i < points.length - 1; ++i) { tangents.push( import__159.Cartesian3.multiplyByScalar( import__159.Cartesian3.subtract(points[i + 1], points[i - 1], new import__159.Cartesian3()), 0.5, new import__159.Cartesian3() ) ); } tangents.push(crs.lastTangent); const hs = import__159.HermiteSpline.createC1({ points, tangents, times }); const granularity = 0.5; for (let j = times[0]; j <= times[points.length - 1]; j = j + granularity) { expect(hs.evaluate(j)).toEqualEpsilon( crs.evaluate(j), import__160.Math.EPSILON4 ); } }); it("evaluate with result parameter", function() { const crs = new import__159.CatmullRomSpline({ points, times }); const result = new import__159.Cartesian3(); const point = crs.evaluate(times[0], result); expect(point).toBe(result); expect(result).toEqual(points[0]); }); it("spline with 2 control points defaults to lerp", function() { points = points.slice(0, 2); times = times.slice(0, 2); const crs = new import__159.CatmullRomSpline({ points, times }); const t = (times[0] + times[1]) * 0.5; expect(crs.evaluate(t)).toEqual( import__159.Cartesian3.lerp(points[0], points[1], t, new import__159.Cartesian3()) ); }); it("spline with 2 control points defaults to lerp and result parameter", function() { points = points.slice(0, 2); times = times.slice(0, 2); const crs = new import__159.CatmullRomSpline({ points, times }); const t = (times[0] + times[1]) * 0.5; const result = new import__159.Cartesian3(); const actual = crs.evaluate(t, result); expect(actual).toBe(result); expect(actual).toEqual( import__159.Cartesian3.lerp(points[0], points[1], t, new import__159.Cartesian3()) ); }); }); // packages/engine/Specs/Core/CesiumTerrainProviderSpec.js var import__161 = __toESM(require_Cesium(), 1); describe("Core/CesiumTerrainProvider", function() { beforeEach(function() { import__161.RequestScheduler.clearForSpecs(); }); afterEach(function() { import__161.Resource._Implementations.loadWithXhr = import__161.Resource._DefaultImplementations.loadWithXhr; }); function returnTileJson(path) { const oldLoad = import__161.Resource._Implementations.loadWithXhr; import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { if (url.indexOf("layer.json") >= 0) { import__161.Resource._DefaultImplementations.loadWithXhr( path, responseType, method, data, headers, deferred ); } else { return oldLoad( url, responseType, method, data, headers, deferred, overrideMimeType ); } }; } function returnHeightmapTileJson() { return returnTileJson( "Data/CesiumTerrainTileJson/StandardHeightmap.tile.json" ); } function returnQuantizedMeshTileJson() { return returnTileJson("Data/CesiumTerrainTileJson/QuantizedMesh.tile.json"); } function returnVertexNormalTileJson() { return returnTileJson("Data/CesiumTerrainTileJson/VertexNormals.tile.json"); } function returnOctVertexNormalTileJson() { return returnTileJson( "Data/CesiumTerrainTileJson/OctVertexNormals.tile.json" ); } function returnWaterMaskTileJson() { return returnTileJson("Data/CesiumTerrainTileJson/WaterMask.tile.json"); } function returnPartialAvailabilityTileJson() { return returnTileJson( "Data/CesiumTerrainTileJson/PartialAvailability.tile.json" ); } function returnParentUrlTileJson() { const paths = [ "Data/CesiumTerrainTileJson/ParentUrl.tile.json", "Data/CesiumTerrainTileJson/Parent.tile.json" ]; let i = 0; const oldLoad = import__161.Resource._Implementations.loadWithXhr; import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { if (url.indexOf("layer.json") >= 0) { import__161.Resource._DefaultImplementations.loadWithXhr( paths[i++], responseType, method, data, headers, deferred ); } else { return oldLoad( url, responseType, method, data, headers, deferred, overrideMimeType ); } }; } function returnMetadataAvailabilityTileJson() { return returnTileJson( "Data/CesiumTerrainTileJson/MetadataAvailability.tile.json" ); } function returnParentUrlTileJsonWithMetadataAvailability() { const paths = [ "Data/CesiumTerrainTileJson/ParentUrlAvailability.tile.json", "Data/CesiumTerrainTileJson/ParentAvailability.tile.json" ]; let i = 0; const oldLoad = import__161.Resource._Implementations.loadWithXhr; import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { if (url.indexOf("layer.json") >= 0) { import__161.Resource._DefaultImplementations.loadWithXhr( paths[i++], responseType, method, data, headers, deferred ); } else { return oldLoad( url, responseType, method, data, headers, deferred, overrideMimeType ); } }; } async function waitForTile(level, x, y, requestNormals, requestWaterMask, f) { const terrainProvider = await import__161.CesiumTerrainProvider.fromUrl("made/up/url", { requestVertexNormals: requestNormals, requestWaterMask }); return terrainProvider.requestTileGeometry(level, x, y); } function createRequest() { return new import__161.Request({ throttleByServer: true }); } it("conforms to TerrainProvider interface", function() { expect(import__161.CesiumTerrainProvider).toConformToInterface(import__161.TerrainProvider); }); it("fromIonAssetId throws without assetId", async function() { await expectAsync( import__161.CesiumTerrainProvider.fromIonAssetId() ).toBeRejectedWithDeveloperError( "assetId is required, actual value was undefined" ); }); it("fromUrl throws without url", async function() { await expectAsync( import__161.CesiumTerrainProvider.fromUrl() ).toBeRejectedWithDeveloperError( "url is required, actual value was undefined" ); }); it("fromUrl resolves to created CesiumTerrainProvider", async function() { const provider = await import__161.CesiumTerrainProvider.fromUrl("made/up/url"); expect(provider).toBeInstanceOf(import__161.CesiumTerrainProvider); }); it("fromUrl resolves with url promise", async function() { const provider = await import__161.CesiumTerrainProvider.fromUrl( Promise.resolve("made/up/url") ); expect(provider).toBeInstanceOf(import__161.CesiumTerrainProvider); }); it("fromUrl resolves with Resource", async function() { const resource = new import__161.Resource({ url: "made/up/url" }); const provider = await import__161.CesiumTerrainProvider.fromUrl(resource); expect(provider).toBeInstanceOf(import__161.CesiumTerrainProvider); }); it("fromUrl rejects if url rejects", async function() { await expectAsync( import__161.CesiumTerrainProvider.fromUrl(Promise.reject(new Error("my message"))) ).toBeRejectedWithError("my message"); }); it("uses geographic tiling scheme by default", async function() { returnHeightmapTileJson(); const provider = await import__161.CesiumTerrainProvider.fromUrl("made/up/url"); expect(provider.tilingScheme).toBeInstanceOf(import__161.GeographicTilingScheme); }); it("can use a custom ellipsoid", async function() { returnHeightmapTileJson(); const ellipsoid = new import__161.Ellipsoid(1, 2, 3); const provider = await import__161.CesiumTerrainProvider.fromUrl("made/up/url", { ellipsoid }); expect(provider.tilingScheme.ellipsoid).toEqual(ellipsoid); }); it("has error event", async function() { const provider = await import__161.CesiumTerrainProvider.fromUrl("made/up/url"); expect(provider.errorEvent).toBeDefined(); expect(provider.errorEvent).toBe(provider.errorEvent); }); it("returns reasonable geometric error for various levels", async function() { returnQuantizedMeshTileJson(); const provider = await import__161.CesiumTerrainProvider.fromUrl("made/up/url"); expect(provider.getLevelMaximumGeometricError(0)).toBeGreaterThan(0); expect(provider.getLevelMaximumGeometricError(0)).toEqualEpsilon( provider.getLevelMaximumGeometricError(1) * 2, import__161.Math.EPSILON10 ); expect(provider.getLevelMaximumGeometricError(1)).toEqualEpsilon( provider.getLevelMaximumGeometricError(2) * 2, import__161.Math.EPSILON10 ); }); it("credit is undefined if credit option is not provided", async function() { returnHeightmapTileJson(); const provider = await import__161.CesiumTerrainProvider.fromUrl("made/up/url"); expect(provider.credit).toBeUndefined(); }); it("credit is defined if credit option is provided", async function() { returnHeightmapTileJson(); const provider = await import__161.CesiumTerrainProvider.fromUrl("made/up/url", { credit: "thanks to our awesome made up contributors!" }); expect(provider.credit).toBeDefined(); }); it("has a water mask", async function() { returnHeightmapTileJson(); const provider = await import__161.CesiumTerrainProvider.fromUrl("made/up/url"); expect(provider.hasWaterMask).toBe(true); }); it("has vertex normals", async function() { returnOctVertexNormalTileJson(); const provider = await import__161.CesiumTerrainProvider.fromUrl("made/up/url", { requestVertexNormals: true }); expect(provider.requestVertexNormals).toBe(true); expect(provider.hasVertexNormals).toBe(true); }); it("does not request vertex normals", async function() { returnOctVertexNormalTileJson(); const provider = await import__161.CesiumTerrainProvider.fromUrl("made/up/url", { requestVertexNormals: false }); expect(provider.requestVertexNormals).toBe(false); expect(provider.hasVertexNormals).toBe(false); }); it("requests parent layer.json", async function() { returnParentUrlTileJson(); const provider = await import__161.CesiumTerrainProvider.fromUrl("made/up/url", { requestVertexNormals: true, requestWaterMask: true }); expect(provider._tileCredits[0].html).toBe( "This is a child tileset! This amazing data is courtesy The Amazing Data Source!" ); expect(provider.requestVertexNormals).toBe(true); expect(provider.requestWaterMask).toBe(true); expect(provider.hasVertexNormals).toBe(false); expect(provider.hasWaterMask).toBe(true); expect(provider.availability.isTileAvailable(1, 2, 1)).toBe(true); expect(provider.availability.isTileAvailable(1, 3, 1)).toBe(true); expect(provider.availability.isTileAvailable(2, 0, 0)).toBe(false); const layers = provider._layers; expect(layers.length).toBe(2); expect(layers[0].hasVertexNormals).toBe(false); expect(layers[0].hasWaterMask).toBe(true); expect(layers[0].availability.isTileAvailable(1, 2, 1)).toBe(true); expect(layers[0].availability.isTileAvailable(1, 3, 1)).toBe(false); expect(layers[0].availability.isTileAvailable(2, 0, 0)).toBe(false); expect(layers[1].hasVertexNormals).toBe(false); expect(layers[1].hasWaterMask).toBe(false); expect(layers[1].availability.isTileAvailable(1, 2, 1)).toBe(true); expect(layers[1].availability.isTileAvailable(1, 3, 1)).toBe(true); expect(layers[1].availability.isTileAvailable(2, 0, 0)).toBe(false); }); it("fromUrl throws if layer.json specifies an unknown format", async function() { returnTileJson("Data/CesiumTerrainTileJson/InvalidFormat.tile.json"); await expectAsync( import__161.CesiumTerrainProvider.fromUrl("made/up/url") ).toBeRejectedWithError( import__161.RuntimeError, 'The tile format "awesometron-9000.0" is invalid or not supported.' ); }); it("fromUrl throws if layer.json does not specify quantized-mesh 1.x format", async function() { returnTileJson("Data/CesiumTerrainTileJson/QuantizedMesh2.0.tile.json"); await expectAsync( import__161.CesiumTerrainProvider.fromUrl("made/up/url") ).toBeRejectedWithError( import__161.RuntimeError, 'The tile format "quantized-mesh-2.0" is invalid or not supported.' ); }); it("fromUrl supports quantized-mesh1.x minor versions", async function() { returnTileJson("Data/CesiumTerrainTileJson/QuantizedMesh1.1.tile.json"); await expectAsync( import__161.CesiumTerrainProvider.fromUrl("made/up/url") ).toBeResolved(); }); it("fromUrl throws if layer.json does not specify a tiles property", async function() { returnTileJson("Data/CesiumTerrainTileJson/NoTiles.tile.json"); await expectAsync( import__161.CesiumTerrainProvider.fromUrl("made/up/url") ).toBeRejectedWithError( import__161.RuntimeError, "The layer.json file does not specify any tile URL templates." ); }); it("fromUrl throws if layer.json tiles property is an empty array", async function() { returnTileJson("Data/CesiumTerrainTileJson/EmptyTilesArray.tile.json"); await expectAsync( import__161.CesiumTerrainProvider.fromUrl("made/up/url") ).toBeRejectedWithError( import__161.RuntimeError, "The layer.json file does not specify any tile URL templates." ); }); it("fromUrl uses attribution specified in layer.json", async function() { returnTileJson("Data/CesiumTerrainTileJson/WithAttribution.tile.json"); const provider = await import__161.CesiumTerrainProvider.fromUrl("made/up/url"); expect(provider._tileCredits[0].html).toBe( "This amazing data is courtesy The Amazing Data Source!" ); }); it("formUrl does not add blank attribution if layer.json does not have one", async function() { returnTileJson("Data/CesiumTerrainTileJson/WaterMask.tile.json"); const provider = await import__161.CesiumTerrainProvider.fromUrl("made/up/url"); expect(provider._tileCredit).toBeUndefined(); }); it("The undefined availability tile is returned at level 0", function() { const layer = { availabilityLevels: 10 }; expect( import__161.CesiumTerrainProvider._getAvailabilityTile(layer, 0, 0, 0) ).toBeUndefined(); expect( import__161.CesiumTerrainProvider._getAvailabilityTile(layer, 1, 0, 0) ).toBeUndefined(); }); it("The correct availability tile is computed in first level", function() { const layer = { availabilityLevels: 10 }; expect(import__161.CesiumTerrainProvider._getAvailabilityTile(layer, 1, 1, 1)).toEqual({ level: 0, x: 0, y: 0 }); expect(import__161.CesiumTerrainProvider._getAvailabilityTile(layer, 4, 2, 2)).toEqual({ level: 0, x: 1, y: 0 }); expect( import__161.CesiumTerrainProvider._getAvailabilityTile(layer, 80, 50, 10) ).toEqual({ level: 0, x: 0, y: 0 }); }); it("The correct availability tile is computed in second level", function() { const layer = { availabilityLevels: 10 }; const expected = { level: 10, x: 80, y: 50 }; const xs = [expected.x, expected.x]; const ys = [expected.y, expected.y]; for (let i = 0; i < 10; ++i) { xs[0] *= 2; ys[0] *= 2; xs[1] = xs[1] * 2 + 1; ys[1] = ys[1] * 2 + 1; } expect( import__161.CesiumTerrainProvider._getAvailabilityTile(layer, xs[0], ys[0], 20) ).toEqual(expected); expect( import__161.CesiumTerrainProvider._getAvailabilityTile(layer, xs[1], ys[1], 20) ).toEqual(expected); }); describe("requestTileGeometry", function() { it("uses multiple urls specified in layer.json", async function() { returnTileJson("Data/CesiumTerrainTileJson/MultipleUrls.tile.json"); const provider = await import__161.CesiumTerrainProvider.fromUrl("made/up/url"); spyOn(import__161.Resource._Implementations, "loadWithXhr").and.callThrough(); try { await provider.requestTileGeometry(0, 0, 0); } catch (e) { expect( import__161.Resource._Implementations.loadWithXhr.calls.mostRecent().args[0] ).toContain("foo0.com"); } try { await provider.requestTileGeometry(1, 0, 0); } catch (e) { expect( import__161.Resource._Implementations.loadWithXhr.calls.mostRecent().args[0] ).toContain("foo1.com"); } try { await provider.requestTileGeometry(1, -1, 0); } catch (e) { expect( import__161.Resource._Implementations.loadWithXhr.calls.mostRecent().args[0] ).toContain("foo2.com"); } try { await provider.requestTileGeometry(1, 0, 1); } catch (e) { expect( import__161.Resource._Implementations.loadWithXhr.calls.mostRecent().args[0] ).toContain("foo3.com"); } }); it("supports scheme-less template URLs in layer.json resolved with absolute URL", async function() { returnTileJson("Data/CesiumTerrainTileJson/MultipleUrls.tile.json"); const url = (0, import__161.getAbsoluteUri)("Data/CesiumTerrainTileJson"); const provider = await import__161.CesiumTerrainProvider.fromUrl(url); spyOn(import__161.Resource._Implementations, "loadWithXhr").and.callThrough(); try { await provider.requestTileGeometry(0, 0, 0); } catch (e) { expect( import__161.Resource._Implementations.loadWithXhr.calls.mostRecent().args[0] ).toContain("foo0.com"); } try { await provider.requestTileGeometry(1, 0, 0); } catch (e) { expect( import__161.Resource._Implementations.loadWithXhr.calls.mostRecent().args[0] ).toContain("foo1.com"); } try { await provider.requestTileGeometry(1, -1, 0); } catch (e) { expect( import__161.Resource._Implementations.loadWithXhr.calls.mostRecent().args[0] ).toContain("foo2.com"); } try { await provider.requestTileGeometry(1, 0, 1); } catch (e) { expect( import__161.Resource._Implementations.loadWithXhr.calls.mostRecent().args[0] ).toContain("foo3.com"); } }); it("provides HeightmapTerrainData", function() { import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { return import__161.Resource._DefaultImplementations.loadWithXhr( "Data/EarthOrientationParameters/IcrfToFixedStkComponentsRotationData.json", responseType, method, data, headers, deferred ); }; returnHeightmapTileJson(); return waitForTile(0, 0, 0, false, false, function(loadedData) { expect(loadedData).toBeInstanceOf(import__161.HeightmapTerrainData); }); }); it("provides QuantizedMeshTerrainData", function() { import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__161.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.terrain", responseType, method, data, headers, deferred ); }; returnQuantizedMeshTileJson(); return waitForTile(0, 0, 0, false, false, function(loadedData) { expect(loadedData).toBeInstanceOf(import__161.QuantizedMeshTerrainData); }); }); it("provides QuantizedMeshTerrainData with 32bit indices", function() { import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__161.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.32bitIndices.terrain", responseType, method, data, headers, deferred ); }; returnQuantizedMeshTileJson(); return waitForTile(0, 0, 0, false, false, function(loadedData) { expect(loadedData).toBeInstanceOf(import__161.QuantizedMeshTerrainData); expect(loadedData._indices.BYTES_PER_ELEMENT).toBe(4); }); }); it("provides QuantizedMeshTerrainData with VertexNormals", function() { import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__161.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.vertexnormals.terrain", responseType, method, data, headers, deferred ); }; returnVertexNormalTileJson(); return waitForTile(0, 0, 0, true, false, function(loadedData) { expect(loadedData).toBeInstanceOf(import__161.QuantizedMeshTerrainData); expect(loadedData._encodedNormals).toBeDefined(); }); }); it("provides QuantizedMeshTerrainData with WaterMask", function() { import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__161.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.watermask.terrain", responseType, method, data, headers, deferred ); }; returnWaterMaskTileJson(); return waitForTile(0, 0, 0, false, true, function(loadedData) { expect(loadedData).toBeInstanceOf(import__161.QuantizedMeshTerrainData); expect(loadedData._waterMask).toBeDefined(); }); }); it("provides QuantizedMeshTerrainData with VertexNormals and WaterMask", function() { import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__161.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.octvertexnormals.watermask.terrain", responseType, method, data, headers, deferred ); }; returnWaterMaskTileJson(); return waitForTile(0, 0, 0, true, true, function(loadedData) { expect(loadedData).toBeInstanceOf(import__161.QuantizedMeshTerrainData); expect(loadedData._encodedNormals).toBeDefined(); expect(loadedData._waterMask).toBeDefined(); }); }); it("provides QuantizedMeshTerrainData with OctVertexNormals", function() { import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__161.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.octvertexnormals.terrain", responseType, method, data, headers, deferred ); }; returnOctVertexNormalTileJson(); return waitForTile(0, 0, 0, true, false, function(loadedData) { expect(loadedData).toBeInstanceOf(import__161.QuantizedMeshTerrainData); expect(loadedData._encodedNormals).toBeDefined(); }); }); it("provides QuantizedMeshTerrainData with VertexNormals and unknown extensions", function() { import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__161.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.vertexnormals.unknownext.terrain", responseType, method, data, headers, deferred ); }; returnVertexNormalTileJson(); return waitForTile(0, 0, 0, true, false, function(loadedData) { expect(loadedData).toBeInstanceOf(import__161.QuantizedMeshTerrainData); expect(loadedData._encodedNormals).toBeDefined(); }); }); it("provides QuantizedMeshTerrainData with OctVertexNormals and unknown extensions", function() { import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__161.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.octvertexnormals.unknownext.terrain", responseType, method, data, headers, deferred ); }; returnOctVertexNormalTileJson(); return waitForTile(0, 0, 0, true, false, function(loadedData) { expect(loadedData).toBeInstanceOf(import__161.QuantizedMeshTerrainData); expect(loadedData._encodedNormals).toBeDefined(); }); }); it("provides QuantizedMeshTerrainData with unknown extension", function() { import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__161.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.unknownext.terrain", responseType, method, data, headers, deferred ); }; returnOctVertexNormalTileJson(); return waitForTile(0, 0, 0, false, false, function(loadedData) { expect(loadedData).toBeInstanceOf(import__161.QuantizedMeshTerrainData); }); }); it("provides QuantizedMeshTerrainData with Metadata availability", async function() { import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__161.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.metadataavailability.terrain", responseType, method, data, headers, deferred ); }; returnMetadataAvailabilityTileJson(); const terrainProvider = await import__161.CesiumTerrainProvider.fromUrl( "made/up/url" ); expect(terrainProvider.hasMetadata).toBe(true); expect(terrainProvider._layers[0].availabilityLevels).toBe(10); expect(terrainProvider.availability.isTileAvailable(0, 0, 0)).toBe(true); expect(terrainProvider.availability.isTileAvailable(0, 1, 0)).toBe(true); expect(terrainProvider.availability.isTileAvailable(1, 0, 0)).toBe(false); const loadedData = await terrainProvider.requestTileGeometry(0, 0, 0); expect(loadedData).toBeInstanceOf(import__161.QuantizedMeshTerrainData); expect(terrainProvider.availability.isTileAvailable(1, 0, 0)).toBe(true); }); it("provides QuantizedMeshTerrainData with multiple layers and with Metadata availability ", async function() { import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__161.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.metadataavailability.terrain", responseType, method, data, headers, deferred ); }; returnParentUrlTileJsonWithMetadataAvailability(); const terrainProvider = await import__161.CesiumTerrainProvider.fromUrl( "made/up/url" ); expect(terrainProvider.hasMetadata).toBe(true); const layers = terrainProvider._layers; expect(layers.length).toBe(2); expect(terrainProvider.availability.isTileAvailable(1, 0, 0)).toBe(false); const loadedData = await terrainProvider.requestTileGeometry(0, 0, 1); expect(loadedData).toBeInstanceOf(import__161.QuantizedMeshTerrainData); expect(terrainProvider.availability.isTileAvailable(1, 0, 0)).toBe(true); }); it("returns undefined if too many requests are already in progress", async function() { const baseUrl = "made/up/url"; const deferreds = []; import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { deferreds.push(deferred); }; returnHeightmapTileJson(); const terrainProvider = await import__161.CesiumTerrainProvider.fromUrl(baseUrl); let promise; let i; for (i = 0; i < import__161.RequestScheduler.maximumRequestsPerServer; ++i) { const request = new import__161.Request({ throttle: true, throttleByServer: true }); promise = terrainProvider.requestTileGeometry(0, 0, 0, request).then(fail).catch((e) => { expect(e.message).toContain("Mesh buffer doesn't exist."); }); } import__161.RequestScheduler.update(); expect(promise).toBeDefined(); promise = terrainProvider.requestTileGeometry(0, 0, 0, createRequest()); expect(promise).toBeUndefined(); for (i = 0; i < deferreds.length; ++i) { deferreds[i].resolve(); } }); it("supports getTileDataAvailable()", async function() { const baseUrl = "made/up/url"; import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__161.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.terrain", responseType, method, data, headers, deferred ); }; returnQuantizedMeshTileJson(); const terrainProvider = await import__161.CesiumTerrainProvider.fromUrl(baseUrl); expect(terrainProvider.getTileDataAvailable(0, 0, 0)).toBe(true); expect(terrainProvider.getTileDataAvailable(0, 0, 2)).toBe(false); }); it("getTileDataAvailable() converts xyz to tms", async function() { const baseUrl = "made/up/url"; returnPartialAvailabilityTileJson(); const terrainProvider = await import__161.CesiumTerrainProvider.fromUrl(baseUrl); expect(terrainProvider.getTileDataAvailable(1, 3, 2)).toBe(true); expect(terrainProvider.getTileDataAvailable(1, 0, 2)).toBe(false); }); it("getTileDataAvailable() with Metadata availability", async function() { import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__161.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.metadataavailability.terrain", responseType, method, data, headers, deferred ); }; returnMetadataAvailabilityTileJson(); const terrainProvider = await import__161.CesiumTerrainProvider.fromUrl( "made/up/url" ); expect(terrainProvider.getTileDataAvailable(0, 0, 0)).toBe(true); expect(terrainProvider.getTileDataAvailable(0, 0, 1)).toBeUndefined(); await terrainProvider.requestTileGeometry(0, 0, 0); expect(terrainProvider.getTileDataAvailable(0, 0, 1)).toBe(true); }); it("supports a query string in the base URL", function() { import__161.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__161.Resource._DefaultImplementations.loadWithXhr( "Data/EarthOrientationParameters/IcrfToFixedStkComponentsRotationData.json", responseType, method, data, headers, deferred ); }; returnHeightmapTileJson(); return waitForTile(0, 0, 0, false, false, function(loadedData) { expect(loadedData).toBeInstanceOf(import__161.HeightmapTerrainData); }); }); it("Uses query parameter extensions for ion resource", async function() { const terrainProvider = await import__161.CesiumTerrainProvider.fromUrl( import__161.IonResource.fromAssetId(1), { requestVertexNormals: true, requestWaterMask: true } ); const getDerivedResource = spyOn( import__161.IonResource.prototype, "getDerivedResource" ).and.callThrough(); await terrainProvider.requestTileGeometry(0, 0, 0); const options = getDerivedResource.calls.argsFor(0)[0]; expect(options.queryParameters.extensions).toEqual( "octvertexnormals-watermask-metadata" ); }); }); }); // packages/engine/Specs/Core/CheckSpec.js var import__162 = __toESM(require_Cesium(), 1); describe("Core/Check", function() { describe("type checks", function() { it("Check.typeOf.bool does not throw when passed a boolean", function() { expect(function() { import__162.Check.typeOf.bool("bool", true); }).not.toThrowDeveloperError(); }); it("Check.typeOf.bool throws when passed a non-boolean", function() { expect(function() { import__162.Check.typeOf.bool("mockName", {}); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.bool("mockName", []); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.bool("mockName", 1); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.bool("mockName", "snth"); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.bool("mockName", function() { return true; }); }).toThrowDeveloperError(); }); it("Check.typeOf.bigint does not throw when passed a bigint", function() { if (!import__162.FeatureDetection.supportsBigInt()) { return; } expect(function() { import__162.Check.typeOf.bigint("bigint", BigInt()); }).not.toThrowDeveloperError(); }); it("Check.typeOf.bigint throws when passed a non-bigint", function() { if (!import__162.FeatureDetection.supportsBigInt()) { return; } expect(function() { import__162.Check.typeOf.bigint("mockName", {}); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.bigint("mockName", []); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.bigint("mockName", 1); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.bigint("mockName", true); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.bigint("mockName", "snth"); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.bigint("mockName", function() { return true; }); }).toThrowDeveloperError(); }); it("Check.typeOf.func does not throw when passed a function", function() { expect(function() { import__162.Check.typeOf.func("mockName", function() { return true; }); }).not.toThrowDeveloperError(); }); it("Check.typeOf.func throws when passed a non-function", function() { expect(function() { import__162.Check.typeOf.func("mockName", {}); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.func("mockName", [2]); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.func("mockName", 1); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.func("mockName", "snth"); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.func("mockName", true); }).toThrowDeveloperError(); }); it("Check.typeOf.object does not throw when passed object", function() { expect(function() { import__162.Check.typeOf.object("mockName", {}); }).not.toThrowDeveloperError(); }); it("Check.typeOf.object throws when passed non-object", function() { expect(function() { import__162.Check.typeOf.object("mockName", "snth"); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.object("mockName", true); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.object("mockName", 1); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.object("mockName", function() { return true; }); }).toThrowDeveloperError(); }); it("Check.typeOf.number does not throw when passed number", function() { expect(function() { import__162.Check.typeOf.number("mockName", 2); }).not.toThrowDeveloperError(); }); it("Check.typeOf.number throws when passed non-number", function() { expect(function() { import__162.Check.typeOf.number("mockName", "snth"); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.number("mockName", true); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.number("mockName", {}); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.number("mockName", [2]); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.number("mockName", function() { return true; }); }).toThrowDeveloperError(); }); it("Check.typeOf.string does not throw when passed a string", function() { expect(function() { import__162.Check.typeOf.string("mockName", "s"); }).not.toThrowDeveloperError(); }); it("Check.typeOf.string throws on non-string", function() { expect(function() { import__162.Check.typeOf.string("mockName", {}); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.string("mockName", true); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.string("mockName", 1); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.string("mockName", [2]); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.string("mockName", function() { return true; }); }).toThrowDeveloperError(); }); }); describe("Check.defined", function() { it("does not throw unless passed value that is undefined or null", function() { expect(function() { import__162.Check.defined("mockName", {}); }).not.toThrowDeveloperError(); expect(function() { import__162.Check.defined("mockName", []); }).not.toThrowDeveloperError(); expect(function() { import__162.Check.defined("mockName", 2); }).not.toThrowDeveloperError(); expect(function() { import__162.Check.defined("mockName", function() { return true; }); }).not.toThrowDeveloperError(); expect(function() { import__162.Check.defined("mockName", "snt"); }).not.toThrowDeveloperError(); }); it("throws when passed undefined", function() { expect(function() { import__162.Check.defined("mockName", void 0); }).toThrowDeveloperError(); }); }); describe("Check.typeOf.number.lessThan", function() { it("throws if test is equal to limit", function() { expect(function() { import__162.Check.typeOf.number.lessThan("mockName", 3, 3); }).toThrowDeveloperError(); }); it("throws if test is greater than limit", function() { expect(function() { import__162.Check.typeOf.number.lessThan("mockName", 4, 3); }).toThrowDeveloperError(); }); it("does not throw if test is less than limit", function() { expect(function() { import__162.Check.typeOf.number.lessThan("mockName", 2, 3); }).not.toThrowDeveloperError(); }); }); describe("Check.typeOf.number.lessThanOrEquals", function() { it("throws if test is greater than limit", function() { expect(function() { import__162.Check.typeOf.number.lessThanOrEquals("mockName", 4, 3); }).toThrowDeveloperError(); }); it("does not throw if test is equal to limit", function() { expect(function() { import__162.Check.typeOf.number.lessThanOrEquals("mockName", 3, 3); }).not.toThrowDeveloperError(); }); it("does not throw if test is less than limit", function() { expect(function() { import__162.Check.typeOf.number.lessThanOrEquals("mockName", 2, 3); }).not.toThrowDeveloperError(); }); }); describe("Check.typeOf.number.equals", function() { it("throws if either value is not a number", function() { expect(function() { import__162.Check.typeOf.number.equals("mockName1", "mockname2", "a", 3); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.number.equals("mockName1", "mockname2", 3, "a"); }).toThrowDeveloperError(); expect(function() { import__162.Check.typeOf.number.equals("mockName1", "mockname2", "b", "a"); }).toThrowDeveloperError(); }); it("throws if both the values are a number but not equal", function() { expect(function() { import__162.Check.typeOf.number.equals("mockName1", "mockName2", 1, 4); }).toThrowDeveloperError(); }); it("does not throw if both values are a number and are equal", function() { expect(function() { import__162.Check.typeOf.number.equal("mockName1", "mockName2", 3, 3); }).not.toThrowDeveloperError(); }); }); describe("Check.typeOf.number.greaterThan", function() { it("throws if test is equal to limit", function() { expect(function() { import__162.Check.typeOf.number.greaterThan("mockName", 3, 3); }).toThrowDeveloperError(); }); it("throws if test is less than limit", function() { expect(function() { import__162.Check.typeOf.number.greaterThan("mockName", 2, 3); }).toThrowDeveloperError(); }); it("does not throw if test is greater than limit", function() { expect(function() { import__162.Check.typeOf.number.greaterThan("mockName", 4, 3); }).not.toThrowDeveloperError(); }); }); describe("Check.typeOf.number.greaterThanOrEquals", function() { it("throws if test is less than limit", function() { expect(function() { import__162.Check.typeOf.number.greaterThanOrEquals("mockName", 2, 3); }).toThrowDeveloperError(); }); it("does not throw if test is equal to limit", function() { expect(function() { import__162.Check.typeOf.number.greaterThanOrEquals("mockName", 3, 3); }).not.toThrowDeveloperError(); }); it("does not throw if test is greater than limit", function() { expect(function() { import__162.Check.typeOf.number.greaterThanOrEquals("mockName", 4, 3); }).not.toThrowDeveloperError(); }); }); }); // packages/engine/Specs/Core/CircleGeometrySpec.js var import__163 = __toESM(require_Cesium(), 1); var import__164 = __toESM(require_Cesium(), 1); describe("Core/CircleGeometry", function() { it("throws without a center", function() { expect(function() { return new import__163.CircleGeometry({ radius: 1 }); }).toThrowDeveloperError(); }); it("throws without a radius", function() { expect(function() { return new import__163.CircleGeometry({ center: import__163.Cartesian3.fromDegrees(0, 0) }); }).toThrowDeveloperError(); }); it("throws with a negative granularity", function() { expect(function() { return new import__163.CircleGeometry({ center: import__163.Cartesian3.fromDegrees(0, 0), radius: 1, granularity: -1 }); }).toThrowDeveloperError(); }); it("computes positions", function() { const m = import__163.CircleGeometry.createGeometry( new import__163.CircleGeometry({ vertexFormat: import__163.VertexFormat.POSITION_ONLY, ellipsoid: import__163.Ellipsoid.WGS84, center: import__163.Cartesian3.fromDegrees(0, 0), granularity: 0.1, radius: 1 }) ); const numVertices = 16; const numTriangles = 22; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); expect(m.boundingSphere.radius).toEqual(1); }); it("compute all vertex attributes", function() { const m = import__163.CircleGeometry.createGeometry( new import__163.CircleGeometry({ vertexFormat: import__163.VertexFormat.ALL, ellipsoid: import__163.Ellipsoid.WGS84, center: import__163.Cartesian3.fromDegrees(0, 0), granularity: 0.1, radius: 1 }) ); const numVertices = 16; const numTriangles = 22; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.attributes.st.values.length).toEqual(numVertices * 2); expect(m.attributes.normal.values.length).toEqual(numVertices * 3); expect(m.attributes.tangent.values.length).toEqual(numVertices * 3); expect(m.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("computes positions extruded", function() { const m = import__163.CircleGeometry.createGeometry( new import__163.CircleGeometry({ vertexFormat: import__163.VertexFormat.POSITION_ONLY, ellipsoid: import__163.Ellipsoid.WGS84, center: import__163.Cartesian3.fromDegrees(0, 0), granularity: 0.1, radius: 1, extrudedHeight: 1e4 }) ); const numVertices = 48; const numTriangles = 60; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("compute all vertex attributes extruded", function() { const m = import__163.CircleGeometry.createGeometry( new import__163.CircleGeometry({ vertexFormat: import__163.VertexFormat.ALL, ellipsoid: import__163.Ellipsoid.WGS84, center: import__163.Cartesian3.fromDegrees(0, 0), granularity: 0.1, radius: 1, extrudedHeight: 1e4 }) ); const numVertices = 48; const numTriangles = 60; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.attributes.st.values.length).toEqual(numVertices * 2); expect(m.attributes.normal.values.length).toEqual(numVertices * 3); expect(m.attributes.tangent.values.length).toEqual(numVertices * 3); expect(m.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("compute texture coordinates with rotation", function() { const m = import__163.CircleGeometry.createGeometry( new import__163.CircleGeometry({ vertexFormat: import__163.VertexFormat.POSITION_AND_ST, ellipsoid: import__163.Ellipsoid.WGS84, center: import__163.Cartesian3.fromDegrees(0, 0), granularity: 0.1, radius: 1, stRotation: import__164.Math.PI_OVER_TWO }) ); const positions = m.attributes.position.values; const st = m.attributes.st.values; const length2 = st.length; expect(positions.length).toEqual(3 * 16); expect(length2).toEqual(2 * 16); expect(m.indices.length).toEqual(3 * 22); expect(st[length2 - 2]).toEqualEpsilon(0.5, import__164.Math.EPSILON2); expect(st[length2 - 1]).toEqualEpsilon(0, import__164.Math.EPSILON2); }); it("undefined is returned if radius is equal to or less than zero", function() { const circle0 = new import__163.CircleGeometry({ center: import__163.Cartesian3.fromDegrees(-75.59777, 40.03883), radius: 0 }); const circle1 = new import__163.CircleGeometry({ center: import__163.Cartesian3.fromDegrees(-75.59777, 40.03883), radius: -10 }); const geometry0 = import__163.CircleGeometry.createGeometry(circle0); const geometry1 = import__163.CircleGeometry.createGeometry(circle1); expect(geometry0).toBeUndefined(); expect(geometry1).toBeUndefined(); }); it("computing rectangle property", function() { const center2 = import__163.Cartesian3.fromDegrees(-75.59777, 40.03883); const ellipse = new import__163.CircleGeometry({ center: center2, radius: 1e3 }); const r = ellipse.rectangle; expect(r.north).toEqualEpsilon(0.698966597893341, import__164.Math.EPSILON15); expect(r.south).toEqualEpsilon(0.698652226072367, import__164.Math.EPSILON15); expect(r.east).toEqualEpsilon(-1.3192254919753026, import__164.Math.EPSILON15); expect(r.west).toEqualEpsilon(-1.3196344953554853, import__164.Math.EPSILON15); }); it("computing textureCoordinateRotationPoints property", function() { const center2 = import__163.Cartesian3.fromDegrees(0, 0); const ellipse = new import__163.CircleGeometry({ center: center2, radius: 1e3, stRotation: import__164.Math.toRadians(90) }); const textureCoordinateRotationPoints = ellipse.textureCoordinateRotationPoints; expect(textureCoordinateRotationPoints.length).toEqual(6); expect(textureCoordinateRotationPoints[0]).toEqualEpsilon( 0, import__164.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[1]).toEqualEpsilon( 1, import__164.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[2]).toEqualEpsilon( 1, import__164.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[3]).toEqualEpsilon( 1, import__164.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[4]).toEqualEpsilon( 0, import__164.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[5]).toEqualEpsilon( 0, import__164.Math.EPSILON7 ); }); const center = import__163.Cartesian3.fromDegrees(0, 0); const ellipsoid = import__163.Ellipsoid.WGS84; const packableInstance = new import__163.CircleGeometry({ vertexFormat: import__163.VertexFormat.POSITION_AND_ST, ellipsoid, center, granularity: 0.1, radius: 1, stRotation: import__164.Math.PI_OVER_TWO }); const packedInstance = [ center.x, center.y, center.z, ellipsoid.radii.x, ellipsoid.radii.y, ellipsoid.radii.z, 1, 0, 1, 0, 0, 0, 1, 1, 0, import__164.Math.PI_OVER_TWO, 0, 0.1, 0, 0, -1 ]; createPackableSpecs_default(import__163.CircleGeometry, packableInstance, packedInstance); }); // packages/engine/Specs/Core/CircleOutlineGeometrySpec.js var import__165 = __toESM(require_Cesium(), 1); describe("Core/CircleOutlineGeometry", function() { it("throws without a center", function() { expect(function() { return new import__165.CircleOutlineGeometry({ radius: 1 }); }).toThrowDeveloperError(); }); it("throws without a radius", function() { expect(function() { return new import__165.CircleOutlineGeometry({ center: import__165.Cartesian3.fromDegrees(0, 0) }); }).toThrowDeveloperError(); }); it("throws with a negative granularity", function() { expect(function() { return new import__165.CircleOutlineGeometry({ center: import__165.Cartesian3.fromDegrees(0, 0), radius: 1, granularity: -1 }); }).toThrowDeveloperError(); }); it("computes positions", function() { const m = import__165.CircleOutlineGeometry.createGeometry( new import__165.CircleOutlineGeometry({ ellipsoid: import__165.Ellipsoid.WGS84, center: import__165.Cartesian3.fromDegrees(0, 0), granularity: 0.1, radius: 1 }) ); expect(m.attributes.position.values.length).toEqual(8 * 3); expect(m.indices.length).toEqual(8 * 2); expect(m.boundingSphere.radius).toEqual(1); }); it("computes positions extruded", function() { const m = import__165.CircleOutlineGeometry.createGeometry( new import__165.CircleOutlineGeometry({ ellipsoid: import__165.Ellipsoid.WGS84, center: import__165.Cartesian3.fromDegrees(0, 0), granularity: 0.1, radius: 1, extrudedHeight: 5 }) ); expect(m.attributes.position.values.length).toEqual(16 * 3); expect(m.indices.length).toEqual(24 * 2); }); it("computes positions extruded, no lines between top and bottom", function() { const m = import__165.CircleOutlineGeometry.createGeometry( new import__165.CircleOutlineGeometry({ ellipsoid: import__165.Ellipsoid.WGS84, center: import__165.Cartesian3.fromDegrees(0, 0), granularity: 0.1, radius: 1, extrudedHeight: 1e4, numberOfVerticalLines: 0 }) ); expect(m.attributes.position.values.length).toEqual(16 * 3); expect(m.indices.length).toEqual(16 * 2); }); it("undefined is returned if radius is equal to or less than zero", function() { const circleOutline0 = new import__165.CircleOutlineGeometry({ center: import__165.Cartesian3.fromDegrees(-75.59777, 40.03883), radius: 0 }); const circleOutline1 = new import__165.CircleOutlineGeometry({ center: import__165.Cartesian3.fromDegrees(-75.59777, 40.03883), radius: -10 }); const geometry0 = import__165.CircleOutlineGeometry.createGeometry(circleOutline0); const geometry1 = import__165.CircleOutlineGeometry.createGeometry(circleOutline1); expect(geometry0).toBeUndefined(); expect(geometry1).toBeUndefined(); }); const center = new import__165.Cartesian3(8, 9, 10); const ellipsoid = new import__165.Ellipsoid(11, 12, 13); let packableInstance = new import__165.CircleOutlineGeometry({ ellipsoid, center, granularity: 1, radius: 2, numberOfVerticalLines: 4, height: 5, extrudedHeight: 7 }); let packedInstance = [ center.x, center.y, center.z, ellipsoid.radii.x, ellipsoid.radii.y, ellipsoid.radii.z, 2, 2, 0, 7, 1, 5, 4, -1 ]; createPackableSpecs_default( import__165.CircleOutlineGeometry, packableInstance, packedInstance, "extruded" ); packableInstance = new import__165.CircleOutlineGeometry({ ellipsoid, center, granularity: 1, radius: 2, numberOfVerticalLines: 4, height: 5 }); packedInstance = [ center.x, center.y, center.z, ellipsoid.radii.x, ellipsoid.radii.y, ellipsoid.radii.z, 2, 2, 0, 5, 1, 5, 4, -1 ]; createPackableSpecs_default( import__165.CircleOutlineGeometry, packableInstance, packedInstance, "at height" ); }); // packages/engine/Specs/Core/ClockSpec.js var import__166 = __toESM(require_Cesium(), 1); describe("Core/Clock", function() { it("sets default parameters when constructed", function() { const clock = new import__166.Clock(); expect(clock.stopTime).toEqual( import__166.JulianDate.addDays(clock.startTime, 1, new import__166.JulianDate()) ); expect(clock.startTime).toEqual(clock.currentTime); expect(clock.multiplier).toEqual(1); expect(clock.clockStep).toEqual(import__166.ClockStep.SYSTEM_CLOCK_MULTIPLIER); expect(clock.clockRange).toEqual(import__166.ClockRange.UNBOUNDED); expect(clock.canAnimate).toEqual(true); expect(clock.shouldAnimate).toEqual(false); }); it("sets provided constructor parameters correctly", function() { const start = new import__166.JulianDate(12); const stop = new import__166.JulianDate(112); const currentTime = new import__166.JulianDate(13); const step = import__166.ClockStep.TICK_DEPENDENT; const range = import__166.ClockRange.LOOP_STOP; const multiplier = 1.5; let clock = new import__166.Clock({ startTime: start, stopTime: stop, currentTime, clockStep: step, multiplier, clockRange: range }); expect(clock.startTime).toEqual(start); expect(clock.startTime).not.toBe(start); expect(clock.stopTime).toEqual(stop); expect(clock.stopTime).not.toBe(stop); expect(clock.currentTime).toEqual(currentTime); expect(clock.currentTime).not.toBe(currentTime); expect(clock.clockStep).toEqual(step); expect(clock.clockRange).toEqual(range); expect(clock.multiplier).toEqual(multiplier); expect(clock.canAnimate).toEqual(true); expect(clock.shouldAnimate).toEqual(false); clock = new import__166.Clock({ canAnimate: false }); expect(clock.canAnimate).toEqual(false); clock = new import__166.Clock({ shouldAnimate: true }); expect(clock.shouldAnimate).toEqual(true); }); it("works when constructed with no currentTime parameter", function() { const start = new import__166.JulianDate(12); const stop = new import__166.JulianDate(112); const step = import__166.ClockStep.TICK_DEPENDENT; const range = import__166.ClockRange.LOOP_STOP; const multiplier = 1.5; const clock = new import__166.Clock({ startTime: start, stopTime: stop, clockStep: step, multiplier, clockRange: range }); expect(clock.startTime).toEqual(start); expect(clock.stopTime).toEqual(stop); expect(clock.currentTime).toEqual(start); expect(clock.clockStep).toEqual(step); expect(clock.clockRange).toEqual(range); expect(clock.multiplier).toEqual(multiplier); expect(clock.canAnimate).toEqual(true); expect(clock.shouldAnimate).toEqual(false); }); it("works when constructed with no startTime parameter", function() { const stop = new import__166.JulianDate(112); const currentTime = new import__166.JulianDate(13); const step = import__166.ClockStep.TICK_DEPENDENT; const range = import__166.ClockRange.LOOP_STOP; const multiplier = 1.5; const clock = new import__166.Clock({ stopTime: stop, currentTime, clockStep: step, multiplier, clockRange: range }); expect(clock.startTime).toEqual(currentTime); expect(clock.stopTime).toEqual(stop); expect(clock.currentTime).toEqual(currentTime); expect(clock.clockStep).toEqual(step); expect(clock.clockRange).toEqual(range); expect(clock.multiplier).toEqual(multiplier); expect(clock.canAnimate).toEqual(true); expect(clock.shouldAnimate).toEqual(false); }); it("works when constructed with no startTime or stopTime", function() { const currentTime = new import__166.JulianDate(12); const step = import__166.ClockStep.TICK_DEPENDENT; const range = import__166.ClockRange.LOOP_STOP; const multiplier = 1.5; const clock = new import__166.Clock({ currentTime, clockStep: step, multiplier, clockRange: range }); const expectedStop = import__166.JulianDate.addDays(currentTime, 1, new import__166.JulianDate()); expect(clock.startTime).toEqual(currentTime); expect(clock.stopTime).toEqual(expectedStop); expect(clock.currentTime).toEqual(currentTime); expect(clock.clockStep).toEqual(step); expect(clock.clockRange).toEqual(range); expect(clock.multiplier).toEqual(multiplier); expect(clock.canAnimate).toEqual(true); expect(clock.shouldAnimate).toEqual(false); }); it("works when constructed with no startTime or currentTime", function() { const stop = new import__166.JulianDate(13); const step = import__166.ClockStep.TICK_DEPENDENT; const range = import__166.ClockRange.LOOP_STOP; const multiplier = 1.5; const clock = new import__166.Clock({ stopTime: stop, clockStep: step, multiplier, clockRange: range }); const expectedStart = import__166.JulianDate.addDays(stop, -1, new import__166.JulianDate()); expect(clock.startTime).toEqual(expectedStart); expect(clock.stopTime).toEqual(stop); expect(clock.currentTime).toEqual(expectedStart); expect(clock.clockStep).toEqual(step); expect(clock.clockRange).toEqual(range); expect(clock.multiplier).toEqual(multiplier); expect(clock.canAnimate).toEqual(true); expect(clock.shouldAnimate).toEqual(false); }); it("works when constructed with no currentTime or stopTime", function() { const start = new import__166.JulianDate(12); const step = import__166.ClockStep.TICK_DEPENDENT; const range = import__166.ClockRange.LOOP_STOP; const multiplier = 1.5; const clock = new import__166.Clock({ startTime: start, clockStep: step, multiplier, clockRange: range }); const expectedStop = import__166.JulianDate.addDays(start, 1, new import__166.JulianDate()); expect(clock.startTime).toEqual(start); expect(clock.stopTime).toEqual(expectedStop); expect(clock.currentTime).toEqual(start); expect(clock.clockStep).toEqual(step); expect(clock.clockRange).toEqual(range); expect(clock.multiplier).toEqual(multiplier); expect(clock.canAnimate).toEqual(true); expect(clock.shouldAnimate).toEqual(false); }); it("works when constructed with no stopTime parameter", function() { const start = new import__166.JulianDate(12); const currentTime = new import__166.JulianDate(12); const step = import__166.ClockStep.TICK_DEPENDENT; const range = import__166.ClockRange.LOOP_STOP; const multiplier = 1.5; const clock = new import__166.Clock({ startTime: start, currentTime, clockStep: step, multiplier, clockRange: range }); const expectedStop = import__166.JulianDate.addDays(start, 1, new import__166.JulianDate()); expect(clock.startTime).toEqual(start); expect(clock.stopTime).toEqual(expectedStop); expect(clock.currentTime).toEqual(currentTime); expect(clock.clockStep).toEqual(step); expect(clock.clockRange).toEqual(range); expect(clock.multiplier).toEqual(multiplier); expect(clock.canAnimate).toEqual(true); expect(clock.shouldAnimate).toEqual(false); }); it("throws when constructed if start time is after stop time", function() { const start = new import__166.JulianDate(1); const stop = new import__166.JulianDate(0); expect(function() { return new import__166.Clock({ startTime: start, stopTime: stop }); }).toThrowDeveloperError(); }); it("animates forward in TICK_DEPENDENT mode", function() { const start = new import__166.JulianDate(0); const stop = new import__166.JulianDate(1); let currentTime = new import__166.JulianDate(0.5); const multiplier = 1.5; const clock = new import__166.Clock({ startTime: start, stopTime: stop, currentTime, clockStep: import__166.ClockStep.TICK_DEPENDENT, multiplier, clockRange: import__166.ClockRange.LOOP_STOP, shouldAnimate: true }); expect(clock.currentTime).toEqual(currentTime); currentTime = import__166.JulianDate.addSeconds( currentTime, multiplier, new import__166.JulianDate() ); expect(currentTime).toEqual(clock.tick()); expect(clock.currentTime).toEqual(currentTime); currentTime = import__166.JulianDate.addSeconds( currentTime, multiplier, new import__166.JulianDate() ); expect(currentTime).toEqual(clock.tick()); expect(clock.currentTime).toEqual(currentTime); }); it("animates backwards in TICK_DEPENDENT mode", function() { const start = new import__166.JulianDate(0); const stop = new import__166.JulianDate(1); let currentTime = new import__166.JulianDate(0.5); const multiplier = -1.5; const clock = new import__166.Clock({ startTime: start, stopTime: stop, currentTime, clockStep: import__166.ClockStep.TICK_DEPENDENT, multiplier, clockRange: import__166.ClockRange.LOOP_STOP, shouldAnimate: true }); expect(clock.currentTime).toEqual(currentTime); currentTime = import__166.JulianDate.addSeconds( currentTime, multiplier, new import__166.JulianDate() ); expect(currentTime).toEqual(clock.tick()); expect(clock.currentTime).toEqual(currentTime); currentTime = import__166.JulianDate.addSeconds( currentTime, multiplier, new import__166.JulianDate() ); expect(currentTime).toEqual(clock.tick()); expect(clock.currentTime).toEqual(currentTime); }); it("animates forwards past stop time in UNBOUNDED TICK_DEPENDENT mode", function() { const start = new import__166.JulianDate(0); const stop = new import__166.JulianDate(1); let currentTime = stop; const multiplier = 1.5; const clock = new import__166.Clock({ startTime: start, stopTime: stop, currentTime, clockStep: import__166.ClockStep.TICK_DEPENDENT, multiplier, clockRange: import__166.ClockRange.UNBOUNDED, shouldAnimate: true }); expect(clock.currentTime).toEqual(currentTime); currentTime = import__166.JulianDate.addSeconds( currentTime, multiplier, new import__166.JulianDate() ); expect(currentTime).toEqual(clock.tick()); expect(clock.currentTime).toEqual(currentTime); currentTime = import__166.JulianDate.addSeconds( currentTime, multiplier, new import__166.JulianDate() ); expect(currentTime).toEqual(clock.tick()); expect(clock.currentTime).toEqual(currentTime); }); it("animates backwards past start time in UNBOUNDED TICK_DEPENDENT mode", function() { const start = new import__166.JulianDate(0); const stop = new import__166.JulianDate(1); let currentTime = start; const multiplier = -1.5; const clock = new import__166.Clock({ startTime: start, stopTime: stop, currentTime, clockStep: import__166.ClockStep.TICK_DEPENDENT, multiplier, clockRange: import__166.ClockRange.UNBOUNDED, shouldAnimate: true }); expect(clock.currentTime).toEqual(currentTime); currentTime = import__166.JulianDate.addSeconds( currentTime, multiplier, new import__166.JulianDate() ); expect(currentTime).toEqual(clock.tick()); expect(clock.currentTime).toEqual(currentTime); currentTime = import__166.JulianDate.addSeconds( currentTime, multiplier, new import__166.JulianDate() ); expect(currentTime).toEqual(clock.tick()); expect(clock.currentTime).toEqual(currentTime); }); it("loops back to start time when animating forward past stop time in LOOP_STOP TICK_DEPENDENT mode", function() { const start = new import__166.JulianDate(0); const stop = new import__166.JulianDate(1); let currentTime = stop; const multiplier = 1.5; const clock = new import__166.Clock({ startTime: start, stopTime: stop, currentTime, clockStep: import__166.ClockStep.TICK_DEPENDENT, multiplier, clockRange: import__166.ClockRange.LOOP_STOP, shouldAnimate: true }); expect(clock.currentTime).toEqual(currentTime); currentTime = import__166.JulianDate.addSeconds(start, multiplier, new import__166.JulianDate()); expect(currentTime).toEqual(clock.tick()); expect(clock.currentTime).toEqual(currentTime); currentTime = import__166.JulianDate.addSeconds( currentTime, multiplier, new import__166.JulianDate() ); expect(currentTime).toEqual(clock.tick()); expect(clock.currentTime).toEqual(currentTime); }); it("stops at start when animating backwards past start time in LOOP_STOP TICK_DEPENDENT mode", function() { const start = new import__166.JulianDate(0); const stop = new import__166.JulianDate(1); const currentTime = start; const multiplier = -100; const clock = new import__166.Clock({ startTime: start, stopTime: stop, currentTime, clockStep: import__166.ClockStep.TICK_DEPENDENT, multiplier, clockRange: import__166.ClockRange.LOOP_STOP, shouldAnimate: true }); expect(clock.currentTime).toEqual(currentTime); expect(start).toEqual(clock.tick()); expect(start).toEqual(clock.currentTime); }); it("stops at stop time when animating forwards past stop time in CLAMPED TICK_DEPENDENT mode", function() { const start = new import__166.JulianDate(0); const stop = new import__166.JulianDate(1); const currentTime = stop; const multiplier = 100; const clock = new import__166.Clock({ startTime: start, stopTime: stop, currentTime, clockStep: import__166.ClockStep.TICK_DEPENDENT, multiplier, clockRange: import__166.ClockRange.CLAMPED, shouldAnimate: true }); expect(clock.currentTime).toEqual(currentTime); expect(stop).toEqual(clock.tick()); expect(stop).toEqual(clock.currentTime); }); it("stops at start time when animating backwards past start time in CLAMPED TICK_DEPENDENT mode", function() { const start = new import__166.JulianDate(0); const stop = new import__166.JulianDate(1); const currentTime = start; const multiplier = -100; const clock = new import__166.Clock({ startTime: start, stopTime: stop, currentTime, clockStep: import__166.ClockStep.TICK_DEPENDENT, multiplier, clockRange: import__166.ClockRange.CLAMPED, shouldAnimate: true }); expect(clock.currentTime).toEqual(currentTime); expect(start).toEqual(clock.tick()); expect(start).toEqual(clock.currentTime); }); it("fires onEnd event when endTime is reached and clock range is CLAMPED", function() { const start = new import__166.JulianDate(0); const stop = new import__166.JulianDate(1); const currentTime = stop; const multiplier = 100; const clock = new import__166.Clock({ startTime: start, stopTime: stop, currentTime, clockStep: import__166.ClockStep.TICK_DEPENDENT, multiplier, clockRange: import__166.ClockRange.CLAMPED, shouldAnimate: true }); const onStopSpy = jasmine.createSpy("event"); clock.onStop.addEventListener(onStopSpy); clock.tick(); expect(onStopSpy).toHaveBeenCalled(); }); it("fires onEnd event when endTime is reached and clock range is LOOP_STOP", function() { const start = new import__166.JulianDate(0); const stop = new import__166.JulianDate(1); const currentTime = stop; const multiplier = 100; const clock = new import__166.Clock({ startTime: start, stopTime: stop, currentTime, clockStep: import__166.ClockStep.TICK_DEPENDENT, multiplier, clockRange: import__166.ClockRange.LOOP_STOP, shouldAnimate: true }); const onStopSpy = jasmine.createSpy("event"); clock.onStop.addEventListener(onStopSpy); clock.tick(); expect(onStopSpy).toHaveBeenCalled(); }); describe("SYSTEM_CLOCK modes", function() { const baseDate = new Date(2016, 6, 7); beforeEach(function() { jasmine.clock().install(); jasmine.clock().mockDate(baseDate); if (typeof performance !== "undefined" && (0, import__166.defined)(performance.now)) { spyOn(performance, "now").and.callFake(function() { return Date.now(); }); } }); afterEach(function() { jasmine.clock().uninstall(); }); it("uses current time in SYSTEM_CLOCK mode (real-time mode)", function() { const clock = new import__166.Clock({ clockStep: import__166.ClockStep.SYSTEM_CLOCK }); expect(clock.currentTime).toEqual(import__166.JulianDate.fromDate(baseDate)); expect(clock.multiplier).toEqual(1); expect(clock.shouldAnimate).toEqual(true); const time1 = clock.tick(); expect(time1).toEqual(import__166.JulianDate.fromDate(baseDate)); jasmine.clock().tick(1e3); const time2 = clock.tick(); expect(time2).toEqual( import__166.JulianDate.addSeconds( import__166.JulianDate.fromDate(baseDate), 1, new import__166.JulianDate() ) ); }); it("switches out of SYSTEM_CLOCK mode when changing currentTime", function() { const clock = new import__166.Clock({ clockStep: import__166.ClockStep.SYSTEM_CLOCK }); expect(clock.clockStep).toEqual(import__166.ClockStep.SYSTEM_CLOCK); clock.currentTime = clock.currentTime; expect(clock.clockStep).toEqual(import__166.ClockStep.SYSTEM_CLOCK); clock.currentTime = new import__166.JulianDate(1); expect(clock.clockStep).toEqual(import__166.ClockStep.SYSTEM_CLOCK_MULTIPLIER); }); it("switches out of SYSTEM_CLOCK mode when changing multiplier", function() { const clock = new import__166.Clock({ clockStep: import__166.ClockStep.SYSTEM_CLOCK }); expect(clock.clockStep).toEqual(import__166.ClockStep.SYSTEM_CLOCK); clock.multiplier = clock.multiplier; expect(clock.clockStep).toEqual(import__166.ClockStep.SYSTEM_CLOCK); clock.multiplier = 1.5; expect(clock.clockStep).toEqual(import__166.ClockStep.SYSTEM_CLOCK_MULTIPLIER); }); it("switches out of SYSTEM_CLOCK mode when changing shouldAnimate", function() { const clock = new import__166.Clock({ clockStep: import__166.ClockStep.SYSTEM_CLOCK }); expect(clock.clockStep).toEqual(import__166.ClockStep.SYSTEM_CLOCK); clock.shouldAnimate = clock.shouldAnimate; expect(clock.clockStep).toEqual(import__166.ClockStep.SYSTEM_CLOCK); clock.shouldAnimate = false; expect(clock.clockStep).toEqual(import__166.ClockStep.SYSTEM_CLOCK_MULTIPLIER); }); it("sets currentTime, multiplier and shouldAnimate when switching to SYSTEM_CLOCK mode", function() { const clock = new import__166.Clock({ currentTime: new import__166.JulianDate(1), clockStep: import__166.ClockStep.SYSTEM_CLOCK_MULTIPLIER, multiplier: 1.5 }); clock.clockStep = import__166.ClockStep.SYSTEM_CLOCK; expect(clock.clockStep).toEqual(import__166.ClockStep.SYSTEM_CLOCK); expect(clock.currentTime).toEqual(import__166.JulianDate.fromDate(baseDate)); expect(clock.multiplier).toEqual(1); expect(clock.shouldAnimate).toEqual(true); }); it("stays in SYSTEM_CLOCK mode when changing other unrelated properties", function() { const clock = new import__166.Clock({ clockStep: import__166.ClockStep.SYSTEM_CLOCK }); clock.startTime = new import__166.JulianDate(1); expect(clock.clockStep).toEqual(import__166.ClockStep.SYSTEM_CLOCK); clock.stopTime = new import__166.JulianDate(2); expect(clock.clockStep).toEqual(import__166.ClockStep.SYSTEM_CLOCK); clock.clockRange = import__166.ClockRange.CLAMP; expect(clock.clockStep).toEqual(import__166.ClockStep.SYSTEM_CLOCK); clock.canAnimate = false; expect(clock.clockStep).toEqual(import__166.ClockStep.SYSTEM_CLOCK); }); it("uses multiplier in SYSTEM_CLOCK_MULTIPLIER mode", function() { const clock = new import__166.Clock({ clockStep: import__166.ClockStep.SYSTEM_CLOCK_MULTIPLIER, multiplier: 2, shouldAnimate: true }); const time1 = clock.tick(); expect(time1).toEqual(import__166.JulianDate.fromDate(baseDate)); jasmine.clock().tick(1e3); const time2 = clock.tick(); expect(time2).toEqual( import__166.JulianDate.addSeconds( import__166.JulianDate.fromDate(baseDate), 2, new import__166.JulianDate() ) ); }); it("does not advance if shouldAnimate is false and does advance if true", function() { const start = import__166.JulianDate.fromDate(baseDate); const clock = new import__166.Clock({ startTime: start, clockStep: import__166.ClockStep.SYSTEM_CLOCK_MULTIPLIER }); expect(clock.currentTime).toEqual(start); clock.shouldAnimate = false; jasmine.clock().tick(1e3); let time1 = clock.tick(); expect(time1).toEqual(start); expect(clock.currentTime).toEqual(start); clock.shouldAnimate = true; jasmine.clock().tick(1e3); time1 = clock.tick(); expect(time1).toEqual( import__166.JulianDate.addSeconds( import__166.JulianDate.fromDate(baseDate), 1, new import__166.JulianDate() ) ); jasmine.clock().tick(1e3); const time2 = clock.tick(); expect(time2).toEqual( import__166.JulianDate.addSeconds( import__166.JulianDate.fromDate(baseDate), 2, new import__166.JulianDate() ) ); clock.currentTime = start; clock.clockStep = import__166.ClockStep.TICK_DEPENDENT; clock.shouldAnimate = false; time1 = clock.tick(); expect(time1).toEqual(start); expect(clock.currentTime).toEqual(start); clock.shouldAnimate = true; time1 = clock.tick(); expect(time1).toEqual( import__166.JulianDate.addSeconds( import__166.JulianDate.fromDate(baseDate), 1, new import__166.JulianDate() ) ); }); }); }); // packages/engine/Specs/Core/ColorGeometryInstanceAttributeSpec.js var import__167 = __toESM(require_Cesium(), 1); describe("Core/ColorGeometryInstanceAttribute", function() { it("constructor", function() { const attribute = new import__167.ColorGeometryInstanceAttribute(1, 1, 0, 0.5); expect(attribute.componentDatatype).toEqual( import__167.ComponentDatatype.UNSIGNED_BYTE ); expect(attribute.componentsPerAttribute).toEqual(4); expect(attribute.normalize).toEqual(true); const value = new Uint8Array(new import__167.Color(1, 1, 0, 0.5).toBytes()); expect(attribute.value).toEqual(value); }); it("fromColor", function() { const color = import__167.Color.AQUA; const attribute = import__167.ColorGeometryInstanceAttribute.fromColor(color); expect(attribute.componentDatatype).toEqual( import__167.ComponentDatatype.UNSIGNED_BYTE ); expect(attribute.componentsPerAttribute).toEqual(4); expect(attribute.normalize).toEqual(true); const value = new Uint8Array(color.toBytes()); expect(attribute.value).toEqual(value); }); it("fromColor throws without color", function() { expect(function() { import__167.ColorGeometryInstanceAttribute.fromColor(); }).toThrowDeveloperError(); }); it("toValue", function() { const color = import__167.Color.AQUA; const expectedResult = new Uint8Array(color.toBytes()); expect(import__167.ColorGeometryInstanceAttribute.toValue(color)).toEqual( expectedResult ); }); it("toValue works with result parameter", function() { const color = import__167.Color.AQUA; const expectedResult = new Uint8Array(color.toBytes()); const result = new Uint8Array(4); const returnedResult = import__167.ColorGeometryInstanceAttribute.toValue( color, result ); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expectedResult); }); it("toValue throws without a color", function() { expect(function() { import__167.ColorGeometryInstanceAttribute.toValue(); }).toThrowDeveloperError(); }); it("equals", function() { const color = new import__167.ColorGeometryInstanceAttribute(0.1, 0.2, 0.3, 0.4); expect(import__167.ColorGeometryInstanceAttribute.equals(color, color)).toEqual(true); expect( import__167.ColorGeometryInstanceAttribute.equals( color, new import__167.ColorGeometryInstanceAttribute(0.1, 0.2, 0.3, 0.4) ) ).toEqual(true); expect( import__167.ColorGeometryInstanceAttribute.equals( color, new import__167.ColorGeometryInstanceAttribute(0.5, 0.2, 0.3, 0.4) ) ).toEqual(false); expect( import__167.ColorGeometryInstanceAttribute.equals( color, new import__167.ColorGeometryInstanceAttribute(0.1, 0.5, 0.3, 0.4) ) ).toEqual(false); expect( import__167.ColorGeometryInstanceAttribute.equals( color, new import__167.ColorGeometryInstanceAttribute(0.1, 0.2, 0.5, 0.4) ) ).toEqual(false); expect( import__167.ColorGeometryInstanceAttribute.equals( color, new import__167.ColorGeometryInstanceAttribute(0.1, 0.2, 0.3, 0.5) ) ).toEqual(false); expect(import__167.ColorGeometryInstanceAttribute.equals(color, void 0)).toEqual( false ); expect(import__167.ColorGeometryInstanceAttribute.equals(void 0, color)).toEqual( false ); }); }); // packages/engine/Specs/Core/ColorSpec.js var import__168 = __toESM(require_Cesium(), 1); var import__169 = __toESM(require_Cesium(), 1); describe("Core/Color", function() { it("Constructing without arguments produces expected defaults", function() { const v = new import__168.Color(); expect(v.red).toEqual(1); expect(v.green).toEqual(1); expect(v.blue).toEqual(1); expect(v.alpha).toEqual(1); }); it("Constructing with arguments sets property values", function() { const v = new import__168.Color(0.1, 0.2, 0.3, 0.4); expect(v.red).toEqual(0.1); expect(v.green).toEqual(0.2); expect(v.blue).toEqual(0.3); expect(v.alpha).toEqual(0.4); }); it("fromBytes without arguments produces expected defaults", function() { const v = new import__168.Color(); expect(v.red).toEqual(1); expect(v.green).toEqual(1); expect(v.blue).toEqual(1); expect(v.alpha).toEqual(1); }); it("fromBytes with arguments sets property values", function() { const v = import__168.Color.fromBytes(0, 255, 51, 102); expect(v.red).toEqual(0); expect(v.green).toEqual(1); expect(v.blue).toEqual(0.2); expect(v.alpha).toEqual(0.4); }); it("fromBytes works with result parameter", function() { const result = new import__168.Color(); const v = import__168.Color.fromBytes(0, 255, 51, 102, result); expect(v).toBe(result); expect(v.red).toEqual(0); expect(v.green).toEqual(1); expect(v.blue).toEqual(0.2); expect(v.alpha).toEqual(0.4); }); it("toBytes returns the same values that fromBytes took", function() { const r = 5; const g = 87; const b = 23; const a = 88; const c = import__168.Color.fromBytes(r, g, b, a); const bytes = c.toBytes(); expect(bytes).toEqual([r, g, b, a]); }); it("toBytes works with a result parameter", function() { const color = new import__168.Color(0.1, 0.2, 0.3, 0.4); const result = []; const expectedResult = [25, 51, 76, 102]; const returnedResult = color.toBytes(result); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expectedResult); }); it("byteToFloat works in all cases", function() { expect(import__168.Color.byteToFloat(0)).toEqual(0); expect(import__168.Color.byteToFloat(255)).toEqual(1); expect(import__168.Color.byteToFloat(127)).toEqual(127 / 255); }); it("floatToByte works in all cases", function() { expect(import__168.Color.floatToByte(0)).toEqual(0); expect(import__168.Color.floatToByte(1)).toEqual(255); expect(import__168.Color.floatToByte(127 / 255)).toEqual(127); }); it("fromCartesian4 returns a color with corrrect values", function() { const color = import__168.Color.fromCartesian4(new import__168.Cartesian4(1, 2, 3, 4)); expect(color).toEqual(new import__168.Color(1, 2, 3, 4)); }); it("fromCartesian4 result param returns color with correct values", function() { const color = new import__168.Color(); const result = import__168.Color.fromCartesian4( new import__168.Cartesian4(1, 2, 3, 4), color ); expect(color).toBe(result); expect(color).toEqual(new import__168.Color(1, 2, 3, 4)); }); it("fromCartesian4 throws without a Cartesian4", function() { expect(function() { import__168.Color.fromCartesian4(); }).toThrowDeveloperError(); }); it("clone with no parameters returns a new identical copy.", function() { const v = new import__168.Color(0.1, 0.2, 0.3, 0.4); const clone24 = v.clone(); expect(clone24).toEqual(v); expect(clone24).not.toBe(v); }); it("clone with a parameter modifies the parameter.", function() { const v = new import__168.Color(0.1, 0.2, 0.3, 0.4); const v2 = new import__168.Color(); const clone24 = v.clone(v2); expect(clone24).toEqual(v2); expect(clone24).toBe(v2); }); it("equals works", function() { const v = new import__168.Color(0.1, 0.2, 0.3, 0.4); const v2 = new import__168.Color(0.1, 0.2, 0.3, 0.4); const v3 = new import__168.Color(0.1, 0.2, 0.3, 0.5); const v4 = new import__168.Color(0.1, 0.2, 0.5, 0.4); const v5 = new import__168.Color(0.1, 0.5, 0.3, 0.4); const v6 = new import__168.Color(0.5, 0.2, 0.3, 0.4); expect(v.equals(v2)).toEqual(true); expect(v.equals(v3)).toEqual(false); expect(v.equals(v4)).toEqual(false); expect(v.equals(v5)).toEqual(false); expect(v.equals(v6)).toEqual(false); }); it("equalsEpsilon works", function() { const v = new import__168.Color(0.1, 0.2, 0.3, 0.4); const v2 = new import__168.Color(0.1, 0.2, 0.3, 0.4); const v3 = new import__168.Color(0.1, 0.2, 0.3, 0.5); const v4 = new import__168.Color(0.1, 0.2, 0.5, 0.4); const v5 = new import__168.Color(0.1, 0.5, 0.3, 0.4); const v6 = new import__168.Color(0.5, 0.2, 0.3, 0.4); expect(v.equalsEpsilon(v2, 0)).toEqual(true); expect(v.equalsEpsilon(v3, 0)).toEqual(false); expect(v.equalsEpsilon(v4, 0)).toEqual(false); expect(v.equalsEpsilon(v5, 0)).toEqual(false); expect(v.equalsEpsilon(v6, 0)).toEqual(false); expect(v.equalsEpsilon(v2, 0.1)).toEqual(true); expect(v.equalsEpsilon(v3, 0.1)).toEqual(true); expect(v.equalsEpsilon(v4, 0.2)).toEqual(true); expect(v.equalsEpsilon(v5, 0.3)).toEqual(true); expect(v.equalsEpsilon(v6, 0.4)).toEqual(true); }); it("toCssColorString produces expected output", function() { expect(import__168.Color.WHITE.toCssColorString()).toEqual("rgb(255,255,255)"); expect(import__168.Color.RED.toCssColorString()).toEqual("rgb(255,0,0)"); expect(import__168.Color.BLUE.toCssColorString()).toEqual("rgb(0,0,255)"); expect(import__168.Color.LIME.toCssColorString()).toEqual("rgb(0,255,0)"); expect(new import__168.Color(0, 0, 0, 1).toCssColorString()).toEqual( "rgb(0,0,0)" ); expect(new import__168.Color(0.1, 0.2, 0.3, 0.4).toCssColorString()).toEqual( "rgba(25,51,76,0.4)" ); }); it("toCssHexString produces expected output", function() { expect(import__168.Color.WHITE.toCssHexString()).toEqual("#ffffff"); expect(import__168.Color.RED.toCssHexString()).toEqual("#ff0000"); expect(import__168.Color.BLUE.toCssHexString()).toEqual("#0000ff"); expect(import__168.Color.LIME.toCssHexString()).toEqual("#00ff00"); expect(new import__168.Color(0, 0, 0, 1).toCssHexString()).toEqual("#000000"); expect(new import__168.Color(0.1, 0.2, 0.3, 0.4).toCssHexString()).toEqual("#19334c66"); }); it("fromCssColorString supports transparent", function() { expect(import__168.Color.fromCssColorString("transparent")).toEqual( new import__168.Color(0, 0, 0, 0) ); }); it("fromCssColorString supports the #rgb format", function() { expect(import__168.Color.fromCssColorString("#369")).toEqual( new import__168.Color(0.2, 0.4, 0.6, 1) ); }); it("fromCssColorString supports the #rgb format with lowercase", function() { expect(import__168.Color.fromCssColorString("#f00")).toEqual(import__168.Color.RED); expect(import__168.Color.fromCssColorString("#0f0")).toEqual(import__168.Color.LIME); expect(import__168.Color.fromCssColorString("#00f")).toEqual(import__168.Color.BLUE); }); it("fromCssColorString supports the #rgb format with uppercase", function() { expect(import__168.Color.fromCssColorString("#F00")).toEqual(import__168.Color.RED); expect(import__168.Color.fromCssColorString("#0F0")).toEqual(import__168.Color.LIME); expect(import__168.Color.fromCssColorString("#00F")).toEqual(import__168.Color.BLUE); }); it("fromCssColorString supports the #rgba format", function() { expect(import__168.Color.fromCssColorString("#369c")).toEqual( new import__168.Color(0.2, 0.4, 0.6, 0.8) ); }); it("fromCssColorString supports the #rgba format with uppercase", function() { expect(import__168.Color.fromCssColorString("#369C")).toEqual( new import__168.Color(0.2, 0.4, 0.6, 0.8) ); }); it("fromCssColorString supports the #rrggbb format", function() { expect(import__168.Color.fromCssColorString("#336699")).toEqual( new import__168.Color(0.2, 0.4, 0.6, 1) ); }); it("fromCssColorString supports the #rrggbb format with lowercase", function() { expect(import__168.Color.fromCssColorString("#ff0000")).toEqual(import__168.Color.RED); expect(import__168.Color.fromCssColorString("#00ff00")).toEqual(import__168.Color.LIME); expect(import__168.Color.fromCssColorString("#0000ff")).toEqual(import__168.Color.BLUE); }); it("fromCssColorString supports the #rrggbb format with uppercase", function() { expect(import__168.Color.fromCssColorString("#FF0000")).toEqual(import__168.Color.RED); expect(import__168.Color.fromCssColorString("#00FF00")).toEqual(import__168.Color.LIME); expect(import__168.Color.fromCssColorString("#0000FF")).toEqual(import__168.Color.BLUE); }); it("fromCssColorString supports the #rrggbbaa format", function() { expect(import__168.Color.fromCssColorString("#336699cc")).toEqual( new import__168.Color(0.2, 0.4, 0.6, 0.8) ); }); it("fromCssColorString supports the #rrggbbaa format with uppercase", function() { expect(import__168.Color.fromCssColorString("#336699CC")).toEqual( new import__168.Color(0.2, 0.4, 0.6, 0.8) ); }); it("fromCssColorString supports the rgb() format with absolute values", function() { expect(import__168.Color.fromCssColorString("rgb(255, 0, 0)")).toEqual(import__168.Color.RED); expect(import__168.Color.fromCssColorString("rgb(0, 255, 0)")).toEqual(import__168.Color.LIME); expect(import__168.Color.fromCssColorString("rgb(0, 0, 255)")).toEqual(import__168.Color.BLUE); expect(import__168.Color.fromCssColorString("rgb(51, 102, 204)")).toEqual( new import__168.Color(0.2, 0.4, 0.8, 1) ); }); it("fromCssColorString supports the rgb() format with absolute values (space-separated)", function() { expect(import__168.Color.fromCssColorString("rgb(255 0 0)")).toEqual(import__168.Color.RED); expect(import__168.Color.fromCssColorString("rgb(0 255 0)")).toEqual(import__168.Color.LIME); expect(import__168.Color.fromCssColorString("rgb(0 0 255)")).toEqual(import__168.Color.BLUE); expect(import__168.Color.fromCssColorString("rgb(51 102 204)")).toEqual( new import__168.Color(0.2, 0.4, 0.8, 1) ); }); it("fromCssColorString supports the rgb() format with percentages", function() { expect(import__168.Color.fromCssColorString("rgb(100%, 0, 0)")).toEqual(import__168.Color.RED); expect(import__168.Color.fromCssColorString("rgb(0, 100%, 0)")).toEqual(import__168.Color.LIME); expect(import__168.Color.fromCssColorString("rgb(0, 0, 100%)")).toEqual(import__168.Color.BLUE); expect(import__168.Color.fromCssColorString("rgb(20%, 40%, 80%)")).toEqual( new import__168.Color(0.2, 0.4, 0.8, 1) ); }); it("fromCssColorString supports the rgb() format with percentages (space-separated)", function() { expect(import__168.Color.fromCssColorString("rgb(100% 0 0)")).toEqual(import__168.Color.RED); expect(import__168.Color.fromCssColorString("rgb(0 100% 0)")).toEqual(import__168.Color.LIME); expect(import__168.Color.fromCssColorString("rgb(0 0 100%)")).toEqual(import__168.Color.BLUE); expect(import__168.Color.fromCssColorString("rgb(20% 40% 80%)")).toEqual( new import__168.Color(0.2, 0.4, 0.8, 1) ); }); it("fromCssColorString supports the rgba() format with absolute values", function() { expect(import__168.Color.fromCssColorString("rgba(255, 0, 0, 1.0)")).toEqual(import__168.Color.RED); expect(import__168.Color.fromCssColorString("rgba(0, 255, 0, 1.0)")).toEqual( import__168.Color.LIME ); expect(import__168.Color.fromCssColorString("rgba(0, 0, 255, 1.0)")).toEqual( import__168.Color.BLUE ); expect(import__168.Color.fromCssColorString("rgba(51, 102, 204, 0.6)")).toEqual( new import__168.Color(0.2, 0.4, 0.8, 0.6) ); }); it("fromCssColorString supports the rgba() format with absolute values (space-separated)", function() { expect(import__168.Color.fromCssColorString("rgba(255 0 0 / 1.0)")).toEqual(import__168.Color.RED); expect(import__168.Color.fromCssColorString("rgba(0 255 0 / 1.0)")).toEqual(import__168.Color.LIME); expect(import__168.Color.fromCssColorString("rgba(0 0 255 / 1.0)")).toEqual(import__168.Color.BLUE); expect(import__168.Color.fromCssColorString("rgba(51 102 204 / 0.6)")).toEqual( new import__168.Color(0.2, 0.4, 0.8, 0.6) ); }); it("fromCssColorString supports the rgba() format with percentages", function() { expect(import__168.Color.fromCssColorString("rgba(100%, 0, 0, 1.0)")).toEqual( import__168.Color.RED ); expect(import__168.Color.fromCssColorString("rgba(0, 100%, 0, 1.0)")).toEqual( import__168.Color.LIME ); expect(import__168.Color.fromCssColorString("rgba(0, 0, 100%, 1.0)")).toEqual( import__168.Color.BLUE ); expect(import__168.Color.fromCssColorString("rgba(20%, 40%, 80%, 0.6)")).toEqual( new import__168.Color(0.2, 0.4, 0.8, 0.6) ); }); it("fromCssColorString supports the rgba() format with percentages (space-separated)", function() { expect(import__168.Color.fromCssColorString("rgba(100% 0 0 / 1.0)")).toEqual(import__168.Color.RED); expect(import__168.Color.fromCssColorString("rgba(0 100% 0 / 1.0)")).toEqual( import__168.Color.LIME ); expect(import__168.Color.fromCssColorString("rgba(0 0 100% / 1.0)")).toEqual( import__168.Color.BLUE ); expect(import__168.Color.fromCssColorString("rgba(20% 40% 80% / 0.6)")).toEqual( new import__168.Color(0.2, 0.4, 0.8, 0.6) ); }); it("fromCssColorString supports named colors regardless of case", function() { expect(import__168.Color.fromCssColorString("red")).toEqual(import__168.Color.RED); expect(import__168.Color.fromCssColorString("GREEN")).toEqual(import__168.Color.GREEN); expect(import__168.Color.fromCssColorString("BLue")).toEqual(import__168.Color.BLUE); }); it("fromCssColorString supports the hsl() format", function() { expect(import__168.Color.fromCssColorString("hsl(0, 100%, 50%)")).toEqual(import__168.Color.RED); expect(import__168.Color.fromCssColorString("hsl(120, 100%, 50%)")).toEqual(import__168.Color.LIME); expect(import__168.Color.fromCssColorString("hsl(240, 100%, 50%)")).toEqual(import__168.Color.BLUE); expect(import__168.Color.fromCssColorString("hsl(220, 60%, 50%)")).toEqualEpsilon( new import__168.Color(0.2, 0.4, 0.8), import__169.Math.EPSILON15 ); }); it("fromCssColorString supports the hsl() format (space-separated)", function() { expect(import__168.Color.fromCssColorString("hsl(0 100% 50%)")).toEqual(import__168.Color.RED); expect(import__168.Color.fromCssColorString("hsl(120 100% 50%)")).toEqual(import__168.Color.LIME); expect(import__168.Color.fromCssColorString("hsl(240 100% 50%)")).toEqual(import__168.Color.BLUE); expect(import__168.Color.fromCssColorString("hsl(220 60% 50%)")).toEqualEpsilon( new import__168.Color(0.2, 0.4, 0.8), import__169.Math.EPSILON15 ); }); it("fromCssColorString supports the hsla() format", function() { expect(import__168.Color.fromCssColorString("hsla(0, 100%, 50%, 1.0)")).toEqual( import__168.Color.RED ); expect(import__168.Color.fromCssColorString("hsla(120, 100%, 50%, 1.0)")).toEqual( import__168.Color.LIME ); expect(import__168.Color.fromCssColorString("hsla(240, 100%, 50%, 1.0)")).toEqual( import__168.Color.BLUE ); expect(import__168.Color.fromCssColorString("hsla(220, 60%, 50%, 0.6)")).toEqualEpsilon( new import__168.Color(0.2, 0.4, 0.8, 0.6), import__169.Math.EPSILON15 ); }); it("fromCssColorString supports the hsla() format (space-separated)", function() { expect(import__168.Color.fromCssColorString("hsla(0 100% 50% / 1.0)")).toEqual( import__168.Color.RED ); expect(import__168.Color.fromCssColorString("hsla(120 100% 50% / 1.0)")).toEqual( import__168.Color.LIME ); expect(import__168.Color.fromCssColorString("hsla(240 100% 50% / 1.0)")).toEqual( import__168.Color.BLUE ); expect(import__168.Color.fromCssColorString("hsla(220 60% 50% / 0.6)")).toEqualEpsilon( new import__168.Color(0.2, 0.4, 0.8, 0.6), import__169.Math.EPSILON15 ); }); it("fromCssColorString wraps hue into valid range for hsl() format", function() { expect(import__168.Color.fromCssColorString("hsl(720, 100%, 50%)")).toEqual(import__168.Color.RED); expect(import__168.Color.fromCssColorString("hsla(720, 100%, 50%, 1.0)")).toEqual( import__168.Color.RED ); }); it("fromCssColorString returns undefined for unknown colors", function() { expect(import__168.Color.fromCssColorString("not a color")).toBeUndefined(); }); it("fromCssColorString throws with undefined", function() { expect(function() { import__168.Color.fromCssColorString(void 0); }).toThrowDeveloperError(); }); it("fromCssColorString works with a result parameter.", function() { const c = new import__168.Color(); let c2 = import__168.Color.fromCssColorString("yellow", c); expect(c).toBe(c2); expect(c).toEqual(import__168.Color.YELLOW); c2 = import__168.Color.fromCssColorString("#f00", c); expect(c).toBe(c2); expect(c).toEqual(import__168.Color.RED); c.alpha = 0.5; c2 = import__168.Color.fromCssColorString("#f00", c); expect(c).toBe(c2); expect(c).toEqual(import__168.Color.RED); c2 = import__168.Color.fromCssColorString("#0000ff", c); expect(c).toBe(c2); expect(c).toEqual(import__168.Color.BLUE); c2 = import__168.Color.fromCssColorString("rgb(0, 255, 255)", c); expect(c).toBe(c2); expect(c).toEqual(import__168.Color.CYAN); c2 = import__168.Color.fromCssColorString("hsl(120, 100%, 50%)", c); expect(c).toBe(c2); expect(c).toEqual(import__168.Color.LIME); }); it("fromCssColorString understands the color string even with any number of unnecessary leading, trailing or middle spaces", function() { expect(import__168.Color.fromCssColorString(" rgb( 0, 0, 255)")).toEqual(import__168.Color.BLUE); expect(import__168.Color.fromCssColorString("rgb( 255, 255, 255) ")).toEqual( import__168.Color.WHITE ); expect(import__168.Color.fromCssColorString("rgb (0 0 255) ")).toEqual(import__168.Color.BLUE); expect(import__168.Color.fromCssColorString(" #FF0000")).toEqual(import__168.Color.RED); expect(import__168.Color.fromCssColorString("#FF0 ")).toEqual(import__168.Color.YELLOW); expect(import__168.Color.fromCssColorString(" hsla(720, 100%, 50%, 1.0) ")).toEqual( import__168.Color.RED ); expect(import__168.Color.fromCssColorString("hsl (720, 100%, 50%)")).toEqual(import__168.Color.RED); }); it("fromHsl produces expected output", function() { expect(import__168.Color.fromHsl(0, 1, 0.5, 1)).toEqual(import__168.Color.RED); expect(import__168.Color.fromHsl(120 / 360, 1, 0.5, 1)).toEqual(import__168.Color.LIME); expect(import__168.Color.fromHsl(240 / 360, 1, 0.5, 1)).toEqual(import__168.Color.BLUE); expect(import__168.Color.fromHsl(220 / 360, 0.6, 0.5, 0.7)).toEqualEpsilon( new import__168.Color(0.2, 0.4, 0.8, 0.7), import__169.Math.EPSILON15 ); }); it("fromHsl properly wraps hue into valid range", function() { expect(import__168.Color.fromHsl(5, 1, 0.5, 1)).toEqual(import__168.Color.RED); }); it("fromHsl works with result parameter", function() { const c1 = new import__168.Color(); const c2 = import__168.Color.fromHsl(5, 1, 0.5, 1, c1); expect(c1).toEqual(import__168.Color.RED); expect(c1).toBe(c2); }); it("fromRandom generates a random color with no options", function() { const color = import__168.Color.fromRandom(); expect(color.red).toBeBetween(0, 1); expect(color.green).toBeBetween(0, 1); expect(color.blue).toBeBetween(0, 1); expect(color.alpha).toBeBetween(0, 1); }); it("fromRandom generates a random color with no options", function() { const result = new import__168.Color(); const color = import__168.Color.fromRandom({}, result); expect(result).toBe(color); expect(color.red).toBeBetween(0, 1); expect(color.green).toBeBetween(0, 1); expect(color.blue).toBeBetween(0, 1); expect(color.alpha).toBeBetween(0, 1); }); it("fromRandom uses specified exact values", function() { const options = { red: 0.1, green: 0.2, blue: 0.3, alpha: 0.4 }; const color = import__168.Color.fromRandom(options); expect(color.red).toEqual(options.red); expect(color.green).toEqual(options.green); expect(color.blue).toEqual(options.blue); expect(color.alpha).toEqual(options.alpha); }); it("fromRandom generates a random kind of Red color within intervals", function() { const options = { red: void 0, minimumRed: 0.1, maximumRed: 0.2, minimumGreen: 0.3, maximumGreen: 0.4, minimumBlue: 0.5, maximumBlue: 0.6, minimumAlpha: 0.7, maximumAlpha: 0.8 }; for (let i = 0; i < 100; i++) { const color = import__168.Color.fromRandom(options); expect(color.red).toBeBetween(options.minimumRed, options.maximumRed); expect(color.green).toBeBetween( options.minimumGreen, options.maximumGreen ); expect(color.blue).toBeBetween(options.minimumBlue, options.maximumBlue); expect(color.alpha).toBeBetween( options.minimumAlpha, options.maximumAlpha ); } }); it("fromRandom throws with invalid minimum-maximum red values", function() { expect(function() { import__168.Color.fromRandom({ minimumRed: 1, maximumRed: 0 }); }).toThrowDeveloperError(); }); it("fromRandom throws with invalid minimum-maximum green values", function() { expect(function() { import__168.Color.fromRandom({ minimumGreen: 1, maximumGreen: 0 }); }).toThrowDeveloperError(); }); it("fromRandom throws with invalid minimum-maximum blue values", function() { expect(function() { import__168.Color.fromRandom({ minimumBlue: 1, maximumBlue: 0 }); }).toThrowDeveloperError(); }); it("fromRandom throws with invalid minimum-maximum alpha values", function() { expect(function() { import__168.Color.fromRandom({ minimumAlpha: 1, maximumAlpha: 0 }); }).toThrowDeveloperError(); }); it("fromAlpha works", function() { const result = import__168.Color.fromAlpha(import__168.Color.RED, 0.5); expect(result).toEqual(new import__168.Color(1, 0, 0, 0.5)); }); it("fromAlpha works with result parameter", function() { const resultParam = new import__168.Color(); const result = import__168.Color.fromAlpha(import__168.Color.RED, 0.5, resultParam); expect(resultParam).toBe(result); expect(result).toEqual(new import__168.Color(1, 0, 0, 0.5)); }); it("fromAlpha throws with undefined color", function() { const result = new import__168.Color(); expect(function() { import__168.Color.fromAlpha(void 0, 0.5, result); }).toThrowDeveloperError(); }); it("fromAlpha throws with undefined color", function() { const result = new import__168.Color(); expect(function() { import__168.Color.fromAlpha(void 0, 0.5, result); }).toThrowDeveloperError(); }); it("fromAlpha throws with undefined alpha", function() { const result = new import__168.Color(); const color = new import__168.Color(); expect(function() { import__168.Color.fromAlpha(color, void 0, result); }).toThrowDeveloperError(); }); it("withAlpha works", function() { const resultParam = new import__168.Color(); const result = import__168.Color.RED.withAlpha(0.5, resultParam); expect(resultParam).toBe(result); expect(result).toEqual(new import__168.Color(1, 0, 0, 0.5)); }); it("toString produces correct results", function() { expect(new import__168.Color(0.1, 0.2, 0.3, 0.4).toString()).toEqual( "(0.1, 0.2, 0.3, 0.4)" ); }); it("can convert to and from RGBA", function() { const color = import__168.Color.fromBytes(255, 204, 0, 238); const rgba = color.toRgba(); expect(rgba).toBeGreaterThan(0); const result = new import__168.Color(); const newColor = import__168.Color.fromRgba(rgba, result); expect(result).toBe(newColor); expect(color).toEqual(newColor); }); it("fromRgba works with result parameter", function() { const color = import__168.Color.fromBytes(255, 204, 0, 238); const rgba = color.toRgba(); const newColor = import__168.Color.fromRgba(rgba); expect(color).toEqual(newColor); }); it("Can brighten", function() { const dark = new import__168.Color(0.2, 0.4, 0.6, 0.8); const brighter = dark.brighten(0.5, new import__168.Color()); expect(brighter.red).toEqual(0.6); expect(brighter.green).toEqual(0.7); expect(brighter.blue).toEqual(0.8); expect(brighter.alpha).toEqual(0.8); }); it("Can darken", function() { const dark = new import__168.Color(0.1, 0.6, 0.8, 0.8); const darker = dark.darken(0.2, new import__168.Color()); expect(darker.red).toEqualEpsilon(0.08, import__169.Math.EPSILON15); expect(darker.green).toEqualEpsilon(0.48, import__169.Math.EPSILON15); expect(darker.blue).toEqualEpsilon(0.64, import__169.Math.EPSILON15); expect(darker.alpha).toEqualEpsilon(0.8, import__169.Math.EPSILON15); }); it("brighten throws without result", function() { expect(function() { import__168.Color.RED.brighten(0.5, void 0); }).toThrowDeveloperError(); }); it("darken throws without result", function() { expect(function() { import__168.Color.RED.darken(0.5, void 0); }).toThrowDeveloperError(); }); it("brighten throws negative magnitude", function() { expect(function() { import__168.Color.RED.brighten(-0.5, new import__168.Color()); }).toThrowDeveloperError(); }); it("darken throws negative magnitude", function() { expect(function() { import__168.Color.RED.darken(-0.5, new import__168.Color()); }).toThrowDeveloperError(); }); it("brighten throws undefined magnitude", function() { expect(function() { import__168.Color.RED.brighten(void 0, new import__168.Color()); }).toThrowDeveloperError(); }); it("darken throws undefined magnitude", function() { expect(function() { import__168.Color.RED.darken(void 0, new import__168.Color()); }).toThrowDeveloperError(); }); it("Can add", function() { const left = new import__168.Color(0.1, 0.2, 0.3, 0.4); const right = new import__168.Color(0.3, 0.3, 0.3, 0.3); const result = import__168.Color.add(left, right, new import__168.Color()); expect(result.red).toEqual(0.4); expect(result.green).toEqual(0.5); expect(result.blue).toEqual(0.6); expect(result.alpha).toEqual(0.7); }); it("add throws with undefined parameters", function() { expect(function() { import__168.Color.add(void 0, new import__168.Color(), new import__168.Color()); }).toThrowDeveloperError(); expect(function() { import__168.Color.add(new import__168.Color(), void 0, new import__168.Color()); }).toThrowDeveloperError(); expect(function() { import__168.Color.add(new import__168.Color(), new import__168.Color(), void 0); }).toThrowDeveloperError(); }); it("can add with a result parameter that is an input parameter", function() { const left = new import__168.Color(0.1, 0.2, 0.3, 0.4); const right = new import__168.Color(0.3, 0.3, 0.3, 0.3); const result = import__168.Color.add(left, right, left); expect(result.red).toEqual(0.4); expect(result.green).toEqual(0.5); expect(result.blue).toEqual(0.6); expect(result.alpha).toEqual(0.7); }); it("Can subtract", function() { const left = new import__168.Color(1, 1, 1, 1); const right = new import__168.Color(0.1, 0.2, 0.3, 0.4); const result = import__168.Color.subtract(left, right, new import__168.Color()); expect(result.red).toEqual(0.9); expect(result.green).toEqual(0.8); expect(result.blue).toEqual(0.7); expect(result.alpha).toEqual(0.6); }); it("subtract throws with undefined parameters", function() { expect(function() { import__168.Color.subtract(void 0, new import__168.Color(), new import__168.Color()); }).toThrowDeveloperError(); expect(function() { import__168.Color.subtract(new import__168.Color(), void 0, new import__168.Color()); }).toThrowDeveloperError(); expect(function() { import__168.Color.subtract(new import__168.Color(), new import__168.Color(), void 0); }).toThrowDeveloperError(); }); it("subtract multiply with a result parameter that is an input parameter", function() { const left = new import__168.Color(1, 1, 1, 1); const right = new import__168.Color(0.1, 0.2, 0.3, 0.4); const result = import__168.Color.subtract(left, right, left); expect(result.red).toEqual(0.9); expect(result.green).toEqual(0.8); expect(result.blue).toEqual(0.7); expect(result.alpha).toEqual(0.6); }); it("Can multiply", function() { const left = new import__168.Color(0.1, 0.2, 0.3, 0.4); const right = new import__168.Color(0.2, 0.2, 0.2, 0.2); const result = import__168.Color.multiply(left, right, new import__168.Color()); expect(result.red).toEqualEpsilon(0.02, import__169.Math.EPSILON15); expect(result.green).toEqualEpsilon(0.04, import__169.Math.EPSILON15); expect(result.blue).toEqualEpsilon(0.06, import__169.Math.EPSILON15); expect(result.alpha).toEqualEpsilon(0.08, import__169.Math.EPSILON15); }); it("multiply throws with undefined parameters", function() { expect(function() { import__168.Color.multiply(void 0, new import__168.Color(), new import__168.Color()); }).toThrowDeveloperError(); expect(function() { import__168.Color.multiply(new import__168.Color(), void 0, new import__168.Color()); }).toThrowDeveloperError(); expect(function() { import__168.Color.multiply(new import__168.Color(), new import__168.Color(), void 0); }).toThrowDeveloperError(); }); it("can multiply with a result parameter that is an input parameter", function() { const left = new import__168.Color(0.1, 0.2, 0.3, 0.4); const right = new import__168.Color(0.2, 0.2, 0.2, 0.2); const result = import__168.Color.multiply(left, right, left); expect(result.red).toEqualEpsilon(0.02, import__169.Math.EPSILON15); expect(result.green).toEqualEpsilon(0.04, import__169.Math.EPSILON15); expect(result.blue).toEqualEpsilon(0.06, import__169.Math.EPSILON15); expect(result.alpha).toEqualEpsilon(0.08, import__169.Math.EPSILON15); }); it("Can divide", function() { const left = new import__168.Color(0.1, 0.2, 0.1, 0.2); const right = new import__168.Color(0.2, 0.2, 0.4, 0.4); const result = import__168.Color.divide(left, right, new import__168.Color()); expect(result.red).toEqualEpsilon(0.5, import__169.Math.EPSILON15); expect(result.green).toEqualEpsilon(1, import__169.Math.EPSILON15); expect(result.blue).toEqualEpsilon(0.25, import__169.Math.EPSILON15); expect(result.alpha).toEqualEpsilon(0.5, import__169.Math.EPSILON15); }); it("divide throws with undefined parameters", function() { expect(function() { import__168.Color.divide(void 0, new import__168.Color(), new import__168.Color()); }).toThrowDeveloperError(); expect(function() { import__168.Color.divide(new import__168.Color(), void 0, new import__168.Color()); }).toThrowDeveloperError(); expect(function() { import__168.Color.divide(new import__168.Color(), new import__168.Color(), void 0); }).toThrowDeveloperError(); }); it("can divide with a result parameter that is an input parameter", function() { const left = new import__168.Color(0.1, 0.2, 0.1, 0.2); const right = new import__168.Color(0.2, 0.2, 0.4, 0.4); const result = import__168.Color.divide(left, right, left); expect(result.red).toEqualEpsilon(0.5, import__169.Math.EPSILON15); expect(result.green).toEqualEpsilon(1, import__169.Math.EPSILON15); expect(result.blue).toEqualEpsilon(0.25, import__169.Math.EPSILON15); expect(result.alpha).toEqualEpsilon(0.5, import__169.Math.EPSILON15); }); it("Can mod", function() { const left = new import__168.Color(0.1, 0.2, 0.3, 0.2); const right = new import__168.Color(0.2, 0.2, 0.2, 0.4); const result = import__168.Color.mod(left, right, new import__168.Color()); expect(result.red).toEqualEpsilon(0.1, import__169.Math.EPSILON15); expect(result.green).toEqualEpsilon(0, import__169.Math.EPSILON15); expect(result.blue).toEqualEpsilon(0.1, import__169.Math.EPSILON15); expect(result.alpha).toEqualEpsilon(0.2, import__169.Math.EPSILON15); }); it("mod throws with undefined parameters", function() { expect(function() { import__168.Color.mod(void 0, new import__168.Color(), new import__168.Color()); }).toThrowDeveloperError(); expect(function() { import__168.Color.mod(new import__168.Color(), void 0, new import__168.Color()); }).toThrowDeveloperError(); expect(function() { import__168.Color.mod(new import__168.Color(), new import__168.Color(), void 0); }).toThrowDeveloperError(); }); it("can mod with a result parameter that is an input parameter", function() { const left = new import__168.Color(0.1, 0.2, 0.3, 0.2); const right = new import__168.Color(0.2, 0.2, 0.2, 0.4); const result = import__168.Color.mod(left, right, left); expect(result.red).toEqualEpsilon(0.1, import__169.Math.EPSILON15); expect(result.green).toEqualEpsilon(0, import__169.Math.EPSILON15); expect(result.blue).toEqualEpsilon(0.1, import__169.Math.EPSILON15); expect(result.alpha).toEqualEpsilon(0.2, import__169.Math.EPSILON15); }); it("Can multiply by scalar", function() { const color = new import__168.Color(0.1, 0.2, 0.3, 0.4); const result = import__168.Color.multiplyByScalar(color, 2, new import__168.Color()); expect(result.red).toEqualEpsilon(0.2, import__169.Math.EPSILON15); expect(result.green).toEqualEpsilon(0.4, import__169.Math.EPSILON15); expect(result.blue).toEqualEpsilon(0.6, import__169.Math.EPSILON15); expect(result.alpha).toEqualEpsilon(0.8, import__169.Math.EPSILON15); }); it("multiply by scalar throws with undefined parameters", function() { expect(function() { import__168.Color.multiplyByScalar(void 0, new import__168.Color(), new import__168.Color()); }).toThrowDeveloperError(); expect(function() { import__168.Color.multiplyByScalar(new import__168.Color(), void 0, new import__168.Color()); }).toThrowDeveloperError(); expect(function() { import__168.Color.multiplyByScalar(new import__168.Color(), new import__168.Color(), void 0); }).toThrowDeveloperError(); }); it("can multiply by scalar with a result parameter that is an input parameter", function() { const color = new import__168.Color(0.1, 0.2, 0.3, 0.4); const result = import__168.Color.multiplyByScalar(color, 2, color); expect(result.red).toEqualEpsilon(0.2, import__169.Math.EPSILON15); expect(result.green).toEqualEpsilon(0.4, import__169.Math.EPSILON15); expect(result.blue).toEqualEpsilon(0.6, import__169.Math.EPSILON15); expect(result.alpha).toEqualEpsilon(0.8, import__169.Math.EPSILON15); }); it("Can divide by scalar", function() { const color = new import__168.Color(0.1, 0.2, 0.3, 0.4); const result = import__168.Color.divideByScalar(color, 2, new import__168.Color()); expect(result.red).toEqualEpsilon(0.05, import__169.Math.EPSILON15); expect(result.green).toEqualEpsilon(0.1, import__169.Math.EPSILON15); expect(result.blue).toEqualEpsilon(0.15, import__169.Math.EPSILON15); expect(result.alpha).toEqualEpsilon(0.2, import__169.Math.EPSILON15); }); it("divide by scalar throws with undefined parameters", function() { expect(function() { import__168.Color.divideByScalar(void 0, new import__168.Color(), new import__168.Color()); }).toThrowDeveloperError(); expect(function() { import__168.Color.divideByScalar(new import__168.Color(), void 0, new import__168.Color()); }).toThrowDeveloperError(); expect(function() { import__168.Color.divideByScalar(new import__168.Color(), new import__168.Color(), void 0); }).toThrowDeveloperError(); }); it("can divide by scalar with a result parameter that is an input parameter", function() { const color = new import__168.Color(0.1, 0.2, 0.3, 0.4); const result = import__168.Color.divideByScalar(color, 2, color); expect(result.red).toEqualEpsilon(0.05, import__169.Math.EPSILON15); expect(result.green).toEqualEpsilon(0.1, import__169.Math.EPSILON15); expect(result.blue).toEqualEpsilon(0.15, import__169.Math.EPSILON15); expect(result.alpha).toEqualEpsilon(0.2, import__169.Math.EPSILON15); }); it("lerp throws with undefined parameters", function() { expect(function() { import__168.Color.lerp(void 0, new import__168.Color(), 0, new import__168.Color()); }).toThrowDeveloperError(); expect(function() { import__168.Color.lerp(new import__168.Color(), void 0, 0, new import__168.Color()); }).toThrowDeveloperError(); expect(function() { import__168.Color.lerp(new import__168.Color(), new import__168.Color(), void 0, new import__168.Color()); }).toThrowDeveloperError(); expect(function() { import__168.Color.lerp(new import__168.Color(), new import__168.Color(), 0, void 0); }).toThrowDeveloperError(); }); it("can lerp between two colors", function() { const colorA = new import__168.Color(0, 0, 0, 0); const colorB = new import__168.Color(1, 1, 1, 1); const result = import__168.Color.lerp(colorA, colorB, 0.5, new import__168.Color()); expect(result.red).toEqualEpsilon(0.5, import__169.Math.EPSILON15); expect(result.green).toEqualEpsilon(0.5, import__169.Math.EPSILON15); expect(result.blue).toEqualEpsilon(0.5, import__169.Math.EPSILON15); expect(result.alpha).toEqualEpsilon(0.5, import__169.Math.EPSILON15); }); createPackableSpecs_default(import__168.Color, new import__168.Color(0.1, 0.2, 0.3, 0.4), [ 0.1, 0.2, 0.3, 0.4 ]); }); // packages/engine/Specs/Core/ComponentDatatypeSpec.js var import__170 = __toESM(require_Cesium(), 1); describe("Core/ComponentDatatype", function() { it("fromTypedArray works", function() { expect(import__170.ComponentDatatype.fromTypedArray(new Int8Array())).toBe( import__170.ComponentDatatype.BYTE ); expect(import__170.ComponentDatatype.fromTypedArray(new Uint8Array())).toBe( import__170.ComponentDatatype.UNSIGNED_BYTE ); expect(import__170.ComponentDatatype.fromTypedArray(new Int16Array())).toBe( import__170.ComponentDatatype.SHORT ); expect(import__170.ComponentDatatype.fromTypedArray(new Uint16Array())).toBe( import__170.ComponentDatatype.UNSIGNED_SHORT ); expect(import__170.ComponentDatatype.fromTypedArray(new Int32Array())).toBe( import__170.ComponentDatatype.INT ); expect(import__170.ComponentDatatype.fromTypedArray(new Uint32Array())).toBe( import__170.ComponentDatatype.UNSIGNED_INT ); expect(import__170.ComponentDatatype.fromTypedArray(new Float32Array())).toBe( import__170.ComponentDatatype.FLOAT ); expect(import__170.ComponentDatatype.fromTypedArray(new Float64Array())).toBe( import__170.ComponentDatatype.DOUBLE ); }); it("fromTypedArray throws if array is not a valid typed array", function() { expect(function() { import__170.ComponentDatatype.fromTypedArray([]); }).toThrowDeveloperError(); }); it("validate works", function() { expect(import__170.ComponentDatatype.validate(import__170.ComponentDatatype.BYTE)).toBe(true); expect(import__170.ComponentDatatype.validate(import__170.ComponentDatatype.UNSIGNED_BYTE)).toBe( true ); expect(import__170.ComponentDatatype.validate(import__170.ComponentDatatype.SHORT)).toBe(true); expect(import__170.ComponentDatatype.validate(import__170.ComponentDatatype.UNSIGNED_SHORT)).toBe( true ); expect(import__170.ComponentDatatype.validate(import__170.ComponentDatatype.INT)).toBe(true); expect(import__170.ComponentDatatype.validate(import__170.ComponentDatatype.UNSIGNED_INT)).toBe( true ); expect(import__170.ComponentDatatype.validate(import__170.ComponentDatatype.FLOAT)).toBe(true); expect(import__170.ComponentDatatype.validate(import__170.ComponentDatatype.DOUBLE)).toBe(true); expect(import__170.ComponentDatatype.validate(void 0)).toBe(false); expect(import__170.ComponentDatatype.validate({})).toBe(false); }); it("createTypedArray works with size", function() { let typedArray = import__170.ComponentDatatype.createTypedArray( import__170.ComponentDatatype.BYTE, 0 ); expect(typedArray).toBeInstanceOf(Int8Array); expect(typedArray.length).toBe(0); typedArray = import__170.ComponentDatatype.createTypedArray( import__170.ComponentDatatype.UNSIGNED_BYTE, 1 ); expect(typedArray).toBeInstanceOf(Uint8Array); expect(typedArray.length).toBe(1); typedArray = import__170.ComponentDatatype.createTypedArray(import__170.ComponentDatatype.SHORT, 2); expect(typedArray).toBeInstanceOf(Int16Array); expect(typedArray.length).toBe(2); typedArray = import__170.ComponentDatatype.createTypedArray( import__170.ComponentDatatype.UNSIGNED_SHORT, 3 ); expect(typedArray).toBeInstanceOf(Uint16Array); expect(typedArray.length).toBe(3); typedArray = import__170.ComponentDatatype.createTypedArray(import__170.ComponentDatatype.INT, 4); expect(typedArray).toBeInstanceOf(Int32Array); expect(typedArray.length).toBe(4); typedArray = import__170.ComponentDatatype.createTypedArray( import__170.ComponentDatatype.UNSIGNED_INT, 5 ); expect(typedArray).toBeInstanceOf(Uint32Array); expect(typedArray.length).toBe(5); typedArray = import__170.ComponentDatatype.createTypedArray(import__170.ComponentDatatype.FLOAT, 6); expect(typedArray).toBeInstanceOf(Float32Array); expect(typedArray.length).toBe(6); typedArray = import__170.ComponentDatatype.createTypedArray( import__170.ComponentDatatype.DOUBLE, 7 ); expect(typedArray).toBeInstanceOf(Float64Array); expect(typedArray.length).toBe(7); }); it("createTypedArray works with values", function() { const values = [34, 12, 4, 1]; let typedArray = import__170.ComponentDatatype.createTypedArray( import__170.ComponentDatatype.BYTE, values ); expect(typedArray).toBeInstanceOf(Int8Array); expect(typedArray).toEqual(values); expect(typedArray.length).toBe(values.length); typedArray = import__170.ComponentDatatype.createTypedArray( import__170.ComponentDatatype.UNSIGNED_BYTE, values ); expect(typedArray).toBeInstanceOf(Uint8Array); expect(typedArray).toEqual(values); expect(typedArray.length).toBe(values.length); typedArray = import__170.ComponentDatatype.createTypedArray( import__170.ComponentDatatype.SHORT, values ); expect(typedArray).toBeInstanceOf(Int16Array); expect(typedArray).toEqual(values); expect(typedArray.length).toBe(values.length); typedArray = import__170.ComponentDatatype.createTypedArray( import__170.ComponentDatatype.UNSIGNED_SHORT, values ); expect(typedArray).toBeInstanceOf(Uint16Array); expect(typedArray).toEqual(values); expect(typedArray.length).toBe(values.length); typedArray = import__170.ComponentDatatype.createTypedArray( import__170.ComponentDatatype.INT, values ); expect(typedArray).toBeInstanceOf(Int32Array); expect(typedArray).toEqual(values); expect(typedArray.length).toBe(values.length); typedArray = import__170.ComponentDatatype.createTypedArray( import__170.ComponentDatatype.UNSIGNED_INT, values ); expect(typedArray).toBeInstanceOf(Uint32Array); expect(typedArray).toEqual(values); expect(typedArray.length).toBe(values.length); typedArray = import__170.ComponentDatatype.createTypedArray( import__170.ComponentDatatype.FLOAT, values ); expect(typedArray).toBeInstanceOf(Float32Array); expect(typedArray).toEqual(values); expect(typedArray.length).toBe(values.length); typedArray = import__170.ComponentDatatype.createTypedArray( import__170.ComponentDatatype.DOUBLE, values ); expect(typedArray).toBeInstanceOf(Float64Array); expect(typedArray).toEqual(values); expect(typedArray.length).toBe(values.length); }); it("createArrayBufferView works", function() { const buffer = new ArrayBuffer(100); expect( import__170.ComponentDatatype.createArrayBufferView( import__170.ComponentDatatype.BYTE, buffer, 0, 1 ) ).toBeInstanceOf(Int8Array); expect( import__170.ComponentDatatype.createArrayBufferView( import__170.ComponentDatatype.UNSIGNED_BYTE, buffer, 0, 1 ) ).toBeInstanceOf(Uint8Array); expect( import__170.ComponentDatatype.createArrayBufferView( import__170.ComponentDatatype.SHORT, buffer, 0, 1 ) ).toBeInstanceOf(Int16Array); expect( import__170.ComponentDatatype.createArrayBufferView( import__170.ComponentDatatype.UNSIGNED_SHORT, buffer, 0, 1 ) ).toBeInstanceOf(Uint16Array); expect( import__170.ComponentDatatype.createArrayBufferView( import__170.ComponentDatatype.INT, buffer, 0, 1 ) ).toBeInstanceOf(Int32Array); expect( import__170.ComponentDatatype.createArrayBufferView( import__170.ComponentDatatype.UNSIGNED_INT, buffer, 0, 1 ) ).toBeInstanceOf(Uint32Array); expect( import__170.ComponentDatatype.createArrayBufferView( import__170.ComponentDatatype.FLOAT, buffer, 0, 1 ) ).toBeInstanceOf(Float32Array); expect( import__170.ComponentDatatype.createArrayBufferView( import__170.ComponentDatatype.DOUBLE, buffer, 0, 1 ) ).toBeInstanceOf(Float64Array); }); it("createTypedArray throws without type", function() { expect(function() { import__170.ComponentDatatype.createTypedArray(void 0, 1); }).toThrowDeveloperError(); }); it("createTypedArray throws without length or values", function() { expect(function() { import__170.ComponentDatatype.createTypedArray(import__170.ComponentDatatype.FLOAT, void 0); }).toThrowDeveloperError(); }); it("createArrayBufferView throws without type", function() { const buffer = new ArrayBuffer(100); expect(function() { import__170.ComponentDatatype.createTypedArray(void 0, buffer, 0, 1); }).toThrowDeveloperError(); }); it("createArrayBufferView throws with invalid type", function() { const buffer = new ArrayBuffer(100); expect(function() { import__170.ComponentDatatype.createTypedArray({}, buffer, 0, 1); }).toThrowDeveloperError(); }); it("createArrayBufferView throws without buffer", function() { expect(function() { import__170.ComponentDatatype.createTypedArray( import__170.ComponentDatatype.BYTE, void 0, 0, 1 ); }).toThrowDeveloperError(); }); it("fromName works", function() { expect(import__170.ComponentDatatype.fromName("BYTE")).toEqual(import__170.ComponentDatatype.BYTE); expect(import__170.ComponentDatatype.fromName("UNSIGNED_BYTE")).toEqual( import__170.ComponentDatatype.UNSIGNED_BYTE ); expect(import__170.ComponentDatatype.fromName("SHORT")).toEqual( import__170.ComponentDatatype.SHORT ); expect(import__170.ComponentDatatype.fromName("UNSIGNED_SHORT")).toEqual( import__170.ComponentDatatype.UNSIGNED_SHORT ); expect(import__170.ComponentDatatype.fromName("INT")).toEqual(import__170.ComponentDatatype.INT); expect(import__170.ComponentDatatype.fromName("UNSIGNED_INT")).toEqual( import__170.ComponentDatatype.UNSIGNED_INT ); expect(import__170.ComponentDatatype.fromName("FLOAT")).toEqual( import__170.ComponentDatatype.FLOAT ); expect(import__170.ComponentDatatype.fromName("DOUBLE")).toEqual( import__170.ComponentDatatype.DOUBLE ); }); it("fromName throws without name", function() { expect(function() { import__170.ComponentDatatype.fromName(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/ConstantSplineSpec.js var import__171 = __toESM(require_Cesium(), 1); describe("Core/ConstantSpline", function() { it("constructor throws without value", function() { expect(function() { return new import__171.ConstantSpline(); }).toThrowDeveloperError(); }); it("constructor throws with invalid value type", function() { expect(function() { return new import__171.ConstantSpline({}); }).toThrowDeveloperError(); }); it("value returns the input value", function() { const value = new import__171.Cartesian3(1, 2, 3); const spline = new import__171.ConstantSpline(value); expect(spline.value).toBe(value); }); it("wrapTime returns constant value", function() { const spline = new import__171.ConstantSpline(10); expect(spline.wrapTime(-0.5)).toEqual(0); expect(spline.wrapTime(2.5)).toEqual(0); }); it("clampTime returns constant value", function() { const spline = new import__171.ConstantSpline(10); expect(spline.clampTime(-0.5)).toEqual(0); expect(spline.clampTime(2.5)).toEqual(0); }); it("wrapTime throws without a time", function() { const spline = new import__171.ConstantSpline(10); expect(function() { spline.wrapTime(); }).toThrowDeveloperError(); }); it("clampTime throws without a time", function() { const spline = new import__171.ConstantSpline(10); expect(function() { spline.clampTime(); }).toThrowDeveloperError(); }); it("findTimeInterval throws", function() { const spline = new import__171.ConstantSpline(10); expect(function() { spline.findTimeInterval(0); }).toThrowDeveloperError(); }); it("evaluate throws without time", function() { const spline = new import__171.ConstantSpline(10); expect(function() { spline.evaluate(); }).toThrowDeveloperError(); }); it("evaluate returns number value", function() { const value = 10; const spline = new import__171.ConstantSpline(value); expect(spline.evaluate(0)).toEqual(value); }); it("evaluate returns cartesian3 value", function() { const value = new import__171.Cartesian3(1, 2, 3); const spline = new import__171.ConstantSpline(value); const returnedValue = spline.evaluate(0); expect(value).toEqual(returnedValue); }); it("evaluate returns cartesian3 value with result parameter", function() { const value = new import__171.Cartesian3(1, 2, 3); const spline = new import__171.ConstantSpline(value); const result = new import__171.Cartesian3(); const returnedValue = spline.evaluate(0, result); expect(returnedValue).toBe(result); expect(value).toEqual(returnedValue); }); it("evaluate returns quaternion value", function() { const value = new import__171.Quaternion(0.707, 0, 0.707, 1); const spline = new import__171.ConstantSpline(value); const returnedValue = spline.evaluate(0); expect(value).toEqual(returnedValue); }); it("evaluate returns quaternion value with result parameter", function() { const value = new import__171.Quaternion(0.707, 0, 0.707, 1); const spline = new import__171.ConstantSpline(value); const result = new import__171.Quaternion(); const returnedValue = spline.evaluate(0, result); expect(returnedValue).toBe(result); expect(value).toEqual(returnedValue); }); }); // packages/engine/Specs/Core/CoplanarPolygonGeometrySpec.js var import__172 = __toESM(require_Cesium(), 1); var import__173 = __toESM(require_Cesium(), 1); describe("Core/CoplanarPolygonGeometry", function() { it("throws with no hierarchy", function() { expect(function() { return new import__172.CoplanarPolygonGeometry(); }).toThrowDeveloperError(); }); it("fromPositions throws without positions", function() { expect(function() { return import__172.CoplanarPolygonGeometry.fromPositions(); }).toThrowDeveloperError(); }); it("returns undefined with less than 3 unique positions", function() { const geometry = import__172.CoplanarPolygonGeometry.createGeometry( import__172.CoplanarPolygonGeometry.fromPositions({ positions: import__172.Cartesian3.fromDegreesArrayHeights([ 49, 18, 1e3, 49, 18, 5e3, 49, 18, 5e3, 49, 18, 1e3 ]) }) ); expect(geometry).toBeUndefined(); }); it("returns undefined when positions are linear", function() { const geometry = import__172.CoplanarPolygonGeometry.createGeometry( import__172.CoplanarPolygonGeometry.fromPositions({ positions: import__172.Cartesian3.fromDegreesArrayHeights([ 0, 0, 1, 0, 0, 2, 0, 0, 3 ]) }) ); expect(geometry).toBeUndefined(); }); it("createGeometry returns undefined due to duplicate hierarchy positions", function() { const hierarchy2 = { positions: import__172.Cartesian3.fromDegreesArray([1, 1, 1, 1, 1, 1]), holes: [ { positions: import__172.Cartesian3.fromDegreesArray([ 0, 0, 0, 0, 0, 0 ]) } ] }; const geometry = import__172.CoplanarPolygonGeometry.createGeometry( new import__172.CoplanarPolygonGeometry({ polygonHierarchy: hierarchy2 }) ); expect(geometry).toBeUndefined(); }); it("computes positions", function() { const p = import__172.CoplanarPolygonGeometry.createGeometry( import__172.CoplanarPolygonGeometry.fromPositions({ vertexFormat: import__172.VertexFormat.POSITION_ONLY, positions: import__172.Cartesian3.fromDegreesArrayHeights([ -1, -1, 0, -1, 0, 1, -1, 1, 1, -1, 2, 0 ]) }) ); expect(p.attributes.position.values.length).toEqual(4 * 3); expect(p.indices.length).toEqual(2 * 3); }); it("computes all attributes", function() { const p = import__172.CoplanarPolygonGeometry.createGeometry( import__172.CoplanarPolygonGeometry.fromPositions({ vertexFormat: import__172.VertexFormat.ALL, positions: import__172.Cartesian3.fromDegreesArrayHeights([ -1, -1, 0, -1, 0, 1, -1, 1, 1, -1, 2, 0 ]) }) ); const numVertices = 4; const numTriangles = 2; expect(p.attributes.position.values.length).toEqual(numVertices * 3); expect(p.attributes.st.values.length).toEqual(numVertices * 2); expect(p.attributes.normal.values.length).toEqual(numVertices * 3); expect(p.attributes.tangent.values.length).toEqual(numVertices * 3); expect(p.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(p.indices.length).toEqual(numTriangles * 3); }); it("flips normal to roughly match surface normal", function() { const p = import__172.CoplanarPolygonGeometry.createGeometry( import__172.CoplanarPolygonGeometry.fromPositions({ vertexFormat: import__172.VertexFormat.ALL, positions: import__172.Cartesian3.fromDegreesArrayHeights([ 90, -1, 0, 90, 1, 0, 92, 1, 0, 92, -1, 0 ]) }) ); const center = import__172.Cartesian3.fromDegrees(91, 0); const expectedNormal = import__172.Ellipsoid.WGS84.geodeticSurfaceNormal(center); const actual = import__172.Cartesian3.unpack(p.attributes.normal.values); expect(expectedNormal).toEqualEpsilon(actual, import__173.Math.EPSILON6); }); const positions = import__172.Cartesian3.fromDegreesArray([ -12.4, 3.5, -12, 3.5, -12, 4 ]); const holePositions0 = import__172.Cartesian3.fromDegreesArray([ -12.2, 3.5, -12.2, 3.6, -12.3, 3.6 ]); const holePositions1 = import__172.Cartesian3.fromDegreesArray([ -12.2, 3.5, -12.25, 3.5, -12.25, 3.55 ]); const hierarchy = { positions, holes: [ { positions: holePositions0, holes: [ { positions: holePositions1, holes: void 0 } ] } ] }; const polygon = new import__172.CoplanarPolygonGeometry({ vertexFormat: import__172.VertexFormat.POSITION_ONLY, polygonHierarchy: hierarchy }); function addPositions(array, positions2) { for (let i = 0; i < positions2.length; ++i) { array.push(positions2[i].x, positions2[i].y, positions2[i].z); } } function addPositions2D(array, positions2) { for (let i = 0; i < positions2.length; ++i) { array.push(positions2[i].x, positions2[i].y); } } const packedInstance = [3, 1]; addPositions(packedInstance, positions); packedInstance.push(3, 1); addPositions(packedInstance, holePositions0); packedInstance.push(3, 0); addPositions(packedInstance, holePositions1); packedInstance.push( import__172.Ellipsoid.WGS84.radii.x, import__172.Ellipsoid.WGS84.radii.y, import__172.Ellipsoid.WGS84.radii.z ); packedInstance.push(1, 0, 0, 0, 0, 0, 0, -1, 45); createPackableSpecs_default(import__172.CoplanarPolygonGeometry, polygon, packedInstance); const textureCoordinates = { positions: [ new import__172.Cartesian2(0, 0), new import__172.Cartesian2(1, 0), new import__172.Cartesian2(0, 1), new import__172.Cartesian2(0.1, 0.1), new import__172.Cartesian2(0.5, 0.1), new import__172.Cartesian2(0.1, 0.5), new import__172.Cartesian2(0.2, 0.2), new import__172.Cartesian2(0.3, 0.2), new import__172.Cartesian2(0.2, 0.3) ], holes: void 0 }; const polygonTextured = new import__172.CoplanarPolygonGeometry({ vertexFormat: import__172.VertexFormat.POSITION_ONLY, polygonHierarchy: hierarchy, textureCoordinates }); const packedInstanceTextured = [3, 1]; addPositions(packedInstanceTextured, positions); packedInstanceTextured.push(3, 1); addPositions(packedInstanceTextured, holePositions0); packedInstanceTextured.push(3, 0); addPositions(packedInstanceTextured, holePositions1); packedInstanceTextured.push( import__172.Ellipsoid.WGS84.radii.x, import__172.Ellipsoid.WGS84.radii.y, import__172.Ellipsoid.WGS84.radii.z ); packedInstanceTextured.push(1, 0, 0, 0, 0, 0, 0); packedInstanceTextured.push(9, 0); addPositions2D(packedInstanceTextured, textureCoordinates.positions); packedInstanceTextured.push(64); createPackableSpecs_default( import__172.CoplanarPolygonGeometry, polygonTextured, packedInstanceTextured ); }); // packages/engine/Specs/Core/CoplanarPolygonOutlineGeometrySpec.js var import__174 = __toESM(require_Cesium(), 1); describe("Core/CoplanarPolygonOutlineGeometry", function() { it("throws with no hierarchy", function() { expect(function() { return new import__174.CoplanarPolygonOutlineGeometry(); }).toThrowDeveloperError(); }); it("fromPositions throws without positions", function() { expect(function() { return import__174.CoplanarPolygonOutlineGeometry.fromPositions(); }).toThrowDeveloperError(); }); it("returns undefined with less than 3 unique positions", function() { const geometry = import__174.CoplanarPolygonOutlineGeometry.createGeometry( import__174.CoplanarPolygonOutlineGeometry.fromPositions({ positions: import__174.Cartesian3.fromDegreesArrayHeights([ 49, 18, 1e3, 49, 18, 5e3, 49, 18, 5e3, 49, 18, 1e3 ]) }) ); expect(geometry).toBeUndefined(); }); it("returns undefined when positions are linear", function() { const geometry = import__174.CoplanarPolygonOutlineGeometry.createGeometry( import__174.CoplanarPolygonOutlineGeometry.fromPositions({ positions: import__174.Cartesian3.fromDegreesArrayHeights([ 0, 0, 1, 0, 0, 2, 0, 0, 3 ]) }) ); expect(geometry).toBeUndefined(); }); it("createGeometry returns undefined due to duplicate hierarchy positions", function() { const hierarchy2 = { positions: import__174.Cartesian3.fromDegreesArray([1, 1, 1, 1, 1, 1]), holes: [ { positions: import__174.Cartesian3.fromDegreesArray([ 0, 0, 0, 0, 0, 0 ]) } ] }; const geometry = import__174.CoplanarPolygonOutlineGeometry.createGeometry( new import__174.CoplanarPolygonOutlineGeometry({ polygonHierarchy: hierarchy2 }) ); expect(geometry).toBeUndefined(); }); it("creates positions", function() { const geometry = import__174.CoplanarPolygonOutlineGeometry.createGeometry( import__174.CoplanarPolygonOutlineGeometry.fromPositions({ positions: import__174.Cartesian3.fromDegreesArrayHeights([ -1, -1, 0, -1, 0, 1, -1, 1, 1, -1, 2, 0 ]) }) ); expect(geometry.attributes.position.values.length).toEqual(4 * 3); expect(geometry.indices.length).toEqual(4 * 2); }); const positions = import__174.Cartesian3.fromDegreesArray([ -124, 35, -110, 35, -110, 40 ]); const holePositions0 = import__174.Cartesian3.fromDegreesArray([ -122, 36, -122, 39, -112, 39 ]); const holePositions1 = import__174.Cartesian3.fromDegreesArray([ -120, 36.5, -114, 36.5, -114, 38.5 ]); const hierarchy = { positions, holes: [ { positions: holePositions0, holes: [ { positions: holePositions1, holes: void 0 } ] } ] }; const polygon = new import__174.CoplanarPolygonOutlineGeometry({ polygonHierarchy: hierarchy }); function addPositions(array, positions2) { for (let i = 0; i < positions2.length; ++i) { array.push(positions2[i].x, positions2[i].y, positions2[i].z); } } const packedInstance = [3, 1]; addPositions(packedInstance, positions); packedInstance.push(3, 1); addPositions(packedInstance, holePositions0); packedInstance.push(3, 0); addPositions(packedInstance, holePositions1); packedInstance.push(34); createPackableSpecs_default(import__174.CoplanarPolygonOutlineGeometry, polygon, packedInstance); }); // packages/engine/Specs/Core/CorridorGeometrySpec.js var import__175 = __toESM(require_Cesium(), 1); var import__176 = __toESM(require_Cesium(), 1); describe("Core/CorridorGeometry", function() { it("throws without positions", function() { expect(function() { return new import__175.CorridorGeometry({}); }).toThrowDeveloperError(); }); it("throws without width", function() { expect(function() { return new import__175.CorridorGeometry({ positions: [new import__175.Cartesian3()] }); }).toThrowDeveloperError(); }); it("createGeometry returns undefined without 2 unique positions", function() { let geometry = import__175.CorridorGeometry.createGeometry( new import__175.CorridorGeometry({ positions: import__175.Cartesian3.fromDegreesArray([90, -30, 90, -30]), width: 1e4 }) ); expect(geometry).toBeUndefined(); geometry = import__175.CorridorGeometry.createGeometry( new import__175.CorridorGeometry({ positions: [ new import__175.Cartesian3( -1349511388149118e-9, -506397322857992e-8, 3.6231416372688496e6 ), //same lon/lat, different height new import__175.Cartesian3( -1.3490464811926484e6, -5062228688739784e-9, 3.6218850521561056e6 ) ], width: 1e4 }) ); expect(geometry).toBeUndefined(); }); it("computes positions", function() { const m = import__175.CorridorGeometry.createGeometry( new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.POSITION_ONLY, positions: import__175.Cartesian3.fromDegreesArray([90, -30, 90, -35]), cornerType: import__175.CornerType.MITERED, width: 3e4 }) ); const numVertices = 12; const numTriangles = 10; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("compute all vertex attributes", function() { const m = import__175.CorridorGeometry.createGeometry( new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.ALL, positions: import__175.Cartesian3.fromDegreesArray([90, -30, 90, -35]), cornerType: import__175.CornerType.MITERED, width: 3e4 }) ); const numVertices = 12; const numTriangles = 10; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.attributes.st.values.length).toEqual(numVertices * 2); expect(m.attributes.normal.values.length).toEqual(numVertices * 3); expect(m.attributes.tangent.values.length).toEqual(numVertices * 3); expect(m.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("computes positions extruded", function() { const m = import__175.CorridorGeometry.createGeometry( new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.POSITION_ONLY, positions: import__175.Cartesian3.fromDegreesArray([90, -30, 90, -35]), cornerType: import__175.CornerType.MITERED, width: 3e4, extrudedHeight: 3e4 }) ); const numVertices = 72; const numTriangles = 44; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("compute all vertex attributes extruded", function() { const m = import__175.CorridorGeometry.createGeometry( new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.ALL, positions: import__175.Cartesian3.fromDegreesArray([90, -30, 90, -35]), cornerType: import__175.CornerType.MITERED, width: 3e4, extrudedHeight: 3e4 }) ); const numVertices = 72; const numTriangles = 44; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.attributes.st.values.length).toEqual(numVertices * 2); expect(m.attributes.normal.values.length).toEqual(numVertices * 3); expect(m.attributes.tangent.values.length).toEqual(numVertices * 3); expect(m.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("computes offset attribute", function() { const m = import__175.CorridorGeometry.createGeometry( new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.POSITION_ONLY, positions: import__175.Cartesian3.fromDegreesArray([90, -30, 90, -35]), cornerType: import__175.CornerType.MITERED, width: 3e4, offsetAttribute: import__175.GeometryOffsetAttribute.TOP }) ); const numVertices = 12; expect(m.attributes.position.values.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("computes offset attribute extruded for top vertices", function() { const m = import__175.CorridorGeometry.createGeometry( new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.POSITION_ONLY, positions: import__175.Cartesian3.fromDegreesArray([90, -30, 90, -35]), cornerType: import__175.CornerType.MITERED, width: 3e4, extrudedHeight: 3e4, offsetAttribute: import__175.GeometryOffsetAttribute.TOP }) ); const numVertices = 72; expect(m.attributes.position.values.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(0).fill(1, 0, 12).fill(1, 24, 48); expect(offset).toEqual(expected); }); it("computes offset attribute extruded for all vertices", function() { const m = import__175.CorridorGeometry.createGeometry( new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.POSITION_ONLY, positions: import__175.Cartesian3.fromDegreesArray([90, -30, 90, -35]), cornerType: import__175.CornerType.MITERED, width: 3e4, extrudedHeight: 3e4, offsetAttribute: import__175.GeometryOffsetAttribute.ALL }) ); const numVertices = 72; expect(m.attributes.position.values.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("computes right turn", function() { const m = import__175.CorridorGeometry.createGeometry( new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.POSITION_ONLY, positions: import__175.Cartesian3.fromDegreesArray([ 90, -30, 90, -31, 91, -31 ]), cornerType: import__175.CornerType.MITERED, width: 3e4 }) ); expect(m.attributes.position.values.length).toEqual(8 * 3); expect(m.indices.length).toEqual(6 * 3); }); it("computes left turn", function() { const m = import__175.CorridorGeometry.createGeometry( new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.POSITION_ONLY, positions: import__175.Cartesian3.fromDegreesArray([ 90, -30, 90, -31, 89, -31 ]), cornerType: import__175.CornerType.MITERED, width: 3e4 }) ); expect(m.attributes.position.values.length).toEqual(8 * 3); expect(m.indices.length).toEqual(6 * 3); }); it("computes with rounded corners", function() { const m = import__175.CorridorGeometry.createGeometry( new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.POSITION_AND_ST, positions: import__175.Cartesian3.fromDegreesArray([ 90, -30, 90, -31, 89, -31, 89, -32 ]), cornerType: import__175.CornerType.ROUNDED, width: 3e4 }) ); const endCaps = 72; const corners = 37; const numVertices = 10 + endCaps + corners; const numTriangles = 8 + endCaps + corners; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.attributes.st.values.length).toEqual(numVertices * 2); expect(m.indices.length).toEqual(numTriangles * 3); }); it("computes with beveled corners", function() { const m = import__175.CorridorGeometry.createGeometry( new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.POSITION_ONLY, positions: import__175.Cartesian3.fromDegreesArray([ 90, -30, 90, -31, 89, -31, 89, -32 ]), cornerType: import__175.CornerType.BEVELED, width: 3e4 }) ); expect(m.attributes.position.values.length).toEqual(10 * 3); expect(m.indices.length).toEqual(8 * 3); }); it("computes sharp turns", function() { const m = import__175.CorridorGeometry.createGeometry( new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.POSITION_ONLY, positions: import__175.Cartesian3.fromDegreesArray([ 2.00571672577652, 52.7781459942399, 1.99188457974115, 52.7764958852886, 2.01325961458495, 52.7674170680511, 1.98708058340534, 52.7733979856253, 2.00634853946644, 52.7650460748473 ]), cornerType: import__175.CornerType.BEVELED, width: 100 }) ); expect(m.attributes.position.values.length).toEqual(13 * 3); expect(m.indices.length).toEqual(11 * 3); }); it("computes straight corridors", function() { const m = import__175.CorridorGeometry.createGeometry( new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.POSITION_ONLY, positions: import__175.Cartesian3.fromDegreesArray([ -67.655, 0, -67.655, 15, -67.655, 20 ]), cornerType: import__175.CornerType.BEVELED, width: 4e5, granularity: Math.PI / 6 }) ); expect(m.attributes.position.values.length).toEqual(4 * 3); expect(m.indices.length).toEqual(2 * 3); }); it( "undefined is returned if there are less than two positions or the width is equal to or less than zero", function() { const corridor0 = new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.POSITION_ONLY, positions: import__175.Cartesian3.fromDegreesArray([-72, 35]), width: 1e5 }); const corridor1 = new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.POSITION_ONLY, positions: import__175.Cartesian3.fromDegreesArray([ -67.655, 0, -67.655, 15, -67.655, 20 ]), width: 0 }); const corridor2 = new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.POSITION_ONLY, positions: import__175.Cartesian3.fromDegreesArray([ -67.655, 0, -67.655, 15, -67.655, 20 ]), width: -100 }); const geometry0 = import__175.CorridorGeometry.createGeometry(corridor0); const geometry1 = import__175.CorridorGeometry.createGeometry(corridor1); const geometry2 = import__175.CorridorGeometry.createGeometry(corridor2); expect(geometry0).toBeUndefined(); expect(geometry1).toBeUndefined(); expect(geometry2).toBeUndefined(); } ); it("computing rectangle property", function() { const c = new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.POSITION_ONLY, positions: import__175.Cartesian3.fromDegreesArray([ -67.655, 0, -67.655, 15, -67.655, 20 ]), cornerType: import__175.CornerType.MITERED, width: 1, granularity: Math.PI / 6 }); const r = c.rectangle; expect(import__176.Math.toDegrees(r.north)).toEqualEpsilon( 20, import__176.Math.EPSILON13 ); expect(import__176.Math.toDegrees(r.south)).toEqualEpsilon( 0, import__176.Math.EPSILON20 ); expect(import__176.Math.toDegrees(r.east)).toEqual(-67.65499522658291); expect(import__176.Math.toDegrees(r.west)).toEqual(-67.6550047734171); }); it("computeRectangle", function() { const options = { vertexFormat: import__175.VertexFormat.POSITION_ONLY, positions: import__175.Cartesian3.fromDegreesArray([ -67.655, 0, -67.655, 15, -67.655, 20 ]), cornerType: import__175.CornerType.MITERED, width: 1 }; const geometry = new import__175.CorridorGeometry(options); const expected = geometry.rectangle; const result = import__175.CorridorGeometry.computeRectangle(options); expect(result).toEqual(expected); }); it("computeRectangle with result parameter", function() { const options = { positions: import__175.Cartesian3.fromDegreesArray([ 72, 0, 85, 15, 83, 20 ]), width: 5 }; const geometry = new import__175.CorridorGeometry(options); const result = new import__175.Rectangle(); const expected = geometry.rectangle; const returned = import__175.CorridorGeometry.computeRectangle(options, result); expect(returned).toEqual(expected); expect(returned).toBe(result); }); it("computing textureCoordinateRotationPoints property", function() { const c = new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.POSITION_ONLY, positions: import__175.Cartesian3.fromDegreesArray([ -67.655, 0, -67.655, 15, -67.655, 20 ]), cornerType: import__175.CornerType.MITERED, width: 1, granularity: Math.PI / 6 }); const textureCoordinateRotationPoints = c.textureCoordinateRotationPoints; expect(textureCoordinateRotationPoints.length).toEqual(6); expect(textureCoordinateRotationPoints[0]).toEqualEpsilon( 0, import__176.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[1]).toEqualEpsilon( 0, import__176.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[2]).toEqualEpsilon( 0, import__176.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[3]).toEqualEpsilon( 1, import__176.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[4]).toEqualEpsilon( 1, import__176.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[5]).toEqualEpsilon( 0, import__176.Math.EPSILON7 ); }); const positions = import__175.Cartesian3.fromDegreesArray([90, -30, 90, -31]); const corridor = new import__175.CorridorGeometry({ vertexFormat: import__175.VertexFormat.POSITION_ONLY, positions, cornerType: import__175.CornerType.BEVELED, width: 3e4, granularity: 0.1 }); const packedInstance = [ 2, positions[0].x, positions[0].y, positions[0].z, positions[1].x, positions[1].y, positions[1].z ]; packedInstance.push( import__175.Ellipsoid.WGS84.radii.x, import__175.Ellipsoid.WGS84.radii.y, import__175.Ellipsoid.WGS84.radii.z ); packedInstance.push(1, 0, 0, 0, 0, 0); packedInstance.push(3e4, 0, 0, 2, 0.1, 0, -1); createPackableSpecs_default(import__175.CorridorGeometry, corridor, packedInstance); }); // packages/engine/Specs/Core/CorridorOutlineGeometrySpec.js var import__177 = __toESM(require_Cesium(), 1); describe("Core/CorridorOutlineGeometry", function() { it("throws without positions", function() { expect(function() { return new import__177.CorridorOutlineGeometry({}); }).toThrowDeveloperError(); }); it("throws without width", function() { expect(function() { return new import__177.CorridorOutlineGeometry({ positions: [new import__177.Cartesian3()] }); }).toThrowDeveloperError(); }); it("createGeometry returns undefined without 2 unique positions", function() { let geometry = import__177.CorridorOutlineGeometry.createGeometry( new import__177.CorridorOutlineGeometry({ positions: import__177.Cartesian3.fromDegreesArray([90, -30, 90, -30]), width: 1e4 }) ); expect(geometry).toBeUndefined(); geometry = import__177.CorridorOutlineGeometry.createGeometry( new import__177.CorridorOutlineGeometry({ positions: [ new import__177.Cartesian3( -1349511388149118e-9, -506397322857992e-8, 3.6231416372688496e6 ), //same lon/lat, different height new import__177.Cartesian3( -1.3490464811926484e6, -5062228688739784e-9, 3.6218850521561056e6 ) ], width: 1e4 }) ); expect(geometry).toBeUndefined(); }); it("computes positions", function() { const m = import__177.CorridorOutlineGeometry.createGeometry( new import__177.CorridorOutlineGeometry({ positions: import__177.Cartesian3.fromDegreesArray([90, -30, 90, -35]), cornerType: import__177.CornerType.MITERED, width: 3e4 }) ); expect(m.attributes.position.values.length).toEqual(12 * 3); expect(m.indices.length).toEqual(12 * 2); }); it("computes positions extruded", function() { const m = import__177.CorridorOutlineGeometry.createGeometry( new import__177.CorridorOutlineGeometry({ positions: import__177.Cartesian3.fromDegreesArray([90, -30, 90, -35]), cornerType: import__177.CornerType.MITERED, width: 3e4, extrudedHeight: 3e4 }) ); expect(m.attributes.position.values.length).toEqual(24 * 3); expect(m.indices.length).toEqual(28 * 2); }); it("computes offset attribute for top vertices", function() { const m = import__177.CorridorOutlineGeometry.createGeometry( new import__177.CorridorOutlineGeometry({ positions: import__177.Cartesian3.fromDegreesArray([90, -30, 90, -35]), cornerType: import__177.CornerType.MITERED, width: 3e4, offsetAttribute: import__177.GeometryOffsetAttribute.TOP }) ); const numVertices = 12; expect(m.attributes.position.values.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("computes offset attribute extruded for top vertices", function() { const m = import__177.CorridorOutlineGeometry.createGeometry( new import__177.CorridorOutlineGeometry({ positions: import__177.Cartesian3.fromDegreesArray([90, -30, 90, -35]), cornerType: import__177.CornerType.MITERED, width: 3e4, extrudedHeight: 3e4, offsetAttribute: import__177.GeometryOffsetAttribute.TOP }) ); const numVertices = 24; expect(m.attributes.position.values.length).toEqual(24 * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(0).fill(1, 0, 12); expect(offset).toEqual(expected); }); it("computes offset attribute extruded for all vertices", function() { const m = import__177.CorridorOutlineGeometry.createGeometry( new import__177.CorridorOutlineGeometry({ positions: import__177.Cartesian3.fromDegreesArray([90, -30, 90, -35]), cornerType: import__177.CornerType.MITERED, width: 3e4, extrudedHeight: 3e4, offsetAttribute: import__177.GeometryOffsetAttribute.ALL }) ); const numVertices = 24; expect(m.attributes.position.values.length).toEqual(24 * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("computes right turn", function() { const m = import__177.CorridorOutlineGeometry.createGeometry( new import__177.CorridorOutlineGeometry({ positions: import__177.Cartesian3.fromDegreesArray([ 90, -30, 90, -31, 91, -31 ]), cornerType: import__177.CornerType.MITERED, width: 3e4 }) ); expect(m.attributes.position.values.length).toEqual(8 * 3); expect(m.indices.length).toEqual(8 * 2); }); it("computes left turn", function() { const m = import__177.CorridorOutlineGeometry.createGeometry( new import__177.CorridorOutlineGeometry({ positions: import__177.Cartesian3.fromDegreesArray([ 90, -30, 90, -31, 89, -31 ]), cornerType: import__177.CornerType.MITERED, width: 3e4 }) ); expect(m.attributes.position.values.length).toEqual(8 * 3); expect(m.indices.length).toEqual(8 * 2); }); it("computes with rounded corners", function() { const m = import__177.CorridorOutlineGeometry.createGeometry( new import__177.CorridorOutlineGeometry({ positions: import__177.Cartesian3.fromDegreesArray([ 90, -30, 90, -31, 89, -31, 89, -32 ]), cornerType: import__177.CornerType.ROUNDED, width: 3e4 }) ); const endCaps = 72; const corners = 37; const numVertices = 10 + endCaps + corners; const numLines = 10 + endCaps + corners; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numLines * 2); }); it("computes with beveled corners", function() { const m = import__177.CorridorOutlineGeometry.createGeometry( new import__177.CorridorOutlineGeometry({ positions: import__177.Cartesian3.fromDegreesArray([ 90, -30, 90, -31, 89, -31, 89, -32 ]), cornerType: import__177.CornerType.BEVELED, width: 3e4 }) ); expect(m.attributes.position.values.length).toEqual(10 * 3); expect(m.indices.length).toEqual(10 * 2); }); it( "undefined is returned if there are less than two positions or the width is equal to or less than zero", function() { const corridorOutline0 = new import__177.CorridorOutlineGeometry({ positions: import__177.Cartesian3.fromDegreesArray([-72, 35]), width: 1e5 }); const corridorOutline1 = new import__177.CorridorOutlineGeometry({ positions: import__177.Cartesian3.fromDegreesArray([ -67.655, 0, -67.655, 15, -67.655, 20 ]), width: 0 }); const corridorOutline2 = new import__177.CorridorOutlineGeometry({ positions: import__177.Cartesian3.fromDegreesArray([ -67.655, 0, -67.655, 15, -67.655, 20 ]), width: -100 }); const geometry0 = import__177.CorridorOutlineGeometry.createGeometry( corridorOutline0 ); const geometry1 = import__177.CorridorOutlineGeometry.createGeometry( corridorOutline1 ); const geometry2 = import__177.CorridorOutlineGeometry.createGeometry( corridorOutline2 ); expect(geometry0).toBeUndefined(); expect(geometry1).toBeUndefined(); expect(geometry2).toBeUndefined(); } ); const positions = import__177.Cartesian3.fromDegreesArray([90, -30, 90, -31]); const corridor = new import__177.CorridorOutlineGeometry({ positions, cornerType: import__177.CornerType.BEVELED, width: 3e4, granularity: 0.1 }); const packedInstance = [ 2, positions[0].x, positions[0].y, positions[0].z, positions[1].x, positions[1].y, positions[1].z ]; packedInstance.push( import__177.Ellipsoid.WGS84.radii.x, import__177.Ellipsoid.WGS84.radii.y, import__177.Ellipsoid.WGS84.radii.z ); packedInstance.push(3e4, 0, 0, 2, 0.1, -1); createPackableSpecs_default(import__177.CorridorOutlineGeometry, corridor, packedInstance); }); // packages/engine/Specs/Core/CubicRealPolynomialSpec.js var import__178 = __toESM(require_Cesium(), 1); var import__179 = __toESM(require_Cesium(), 1); describe("Core/CubicRealPolynomial", function() { it("discriminant throws without a", function() { expect(function() { import__178.CubicRealPolynomial.computeDiscriminant(); }).toThrowDeveloperError(); }); it("discriminant throws without b", function() { expect(function() { import__178.CubicRealPolynomial.computeDiscriminant(1); }).toThrowDeveloperError(); }); it("discriminant throws without c", function() { expect(function() { import__178.CubicRealPolynomial.computeDiscriminant(1, 1); }).toThrowDeveloperError(); }); it("discriminant throws without d", function() { expect(function() { import__178.CubicRealPolynomial.computeDiscriminant(1, 1, 1); }).toThrowDeveloperError(); }); it("discriminant", function() { const a = 3; const b = 2; const c = 1; const d = 1; const expected = b * b * c * c - 4 * a * c * c * c - 4 * b * b * b * d - 27 * a * a * d * d + 18 * a * b * c * d; const actual = import__178.CubicRealPolynomial.computeDiscriminant(a, b, c, d); expect(actual).toEqualEpsilon(expected, import__179.Math.EPSILON14); }); it("real roots throws without a", function() { expect(function() { import__178.CubicRealPolynomial.computeRealRoots(); }).toThrowDeveloperError(); }); it("real roots throws without b", function() { expect(function() { import__178.CubicRealPolynomial.computeRealRoots(1); }).toThrowDeveloperError(); }); it("real roots throws without c", function() { expect(function() { import__178.CubicRealPolynomial.computeRealRoots(1, 1); }).toThrowDeveloperError(); }); it("real roots throws without d", function() { expect(function() { import__178.CubicRealPolynomial.computeRealRoots(1, 1, 1); }).toThrowDeveloperError(); }); it("three repeated roots", function() { const roots = import__178.CubicRealPolynomial.computeRealRoots(2, -12, 24, -16); expect(roots.length).toEqual(3); expect(roots[0]).toEqualEpsilon(2, import__179.Math.EPSILON15); expect(roots[1]).toEqualEpsilon(2, import__179.Math.EPSILON15); expect(roots[2]).toEqualEpsilon(2, import__179.Math.EPSILON15); }); it("one unique and two repeated roots", function() { const roots = import__178.CubicRealPolynomial.computeRealRoots(2, 2, -2, -2); expect(roots.length).toEqual(3); expect(roots[0]).toEqualEpsilon(-1, import__179.Math.EPSILON15); expect(roots[1]).toEqualEpsilon(-1, import__179.Math.EPSILON15); expect(roots[2]).toEqualEpsilon(1, import__179.Math.EPSILON15); }); it("three unique roots", function() { const roots = import__178.CubicRealPolynomial.computeRealRoots(2, 6, -26, -30); expect(roots.length).toEqual(3); expect(roots[0]).toEqualEpsilon(-5, import__179.Math.EPSILON15); expect(roots[1]).toEqualEpsilon(-1, import__179.Math.EPSILON15); expect(roots[2]).toEqualEpsilon(3, import__179.Math.EPSILON15); }); it("complex roots", function() { const roots = import__178.CubicRealPolynomial.computeRealRoots(2, -6, 10, -6); expect(roots.length).toEqual(1); expect(roots[0]).toEqualEpsilon(1, import__179.Math.EPSILON15); }); it("quadratic case", function() { const roots = import__178.CubicRealPolynomial.computeRealRoots(0, 2, -4, -6); expect(roots.length).toEqual(2); expect(roots[0]).toEqual(-1); expect(roots[1]).toEqual(3); }); it("deflated case", function() { let roots = import__178.CubicRealPolynomial.computeRealRoots(1, 0, 1, 2); expect(roots.length).toEqual(1); expect(roots[0]).toEqualEpsilon(-1, import__179.Math.EPSILON14); roots = import__178.CubicRealPolynomial.computeRealRoots(1, 0, 0, -8); expect(roots.length).toEqual(3); expect(roots[0]).toEqualEpsilon(2, import__179.Math.EPSILON14); roots = import__178.CubicRealPolynomial.computeRealRoots(1, 0, -1, 0); expect(roots.length).toEqual(3); expect(roots[0]).toEqual(-1); expect(roots[1]).toEqual(0); expect(roots[2]).toEqual(1); roots = import__178.CubicRealPolynomial.computeRealRoots(1, 1, 0, 0); expect(roots.length).toEqual(3); expect(roots[0]).toEqual(-1); expect(roots[1]).toEqual(0); expect(roots[2]).toEqual(0); roots = import__178.CubicRealPolynomial.computeRealRoots(1, -1, 0, 0); expect(roots.length).toEqual(3); expect(roots[0]).toEqual(0); expect(roots[1]).toEqual(0); expect(roots[2]).toEqual(1); roots = import__178.CubicRealPolynomial.computeRealRoots(1, 1, 1, 0); expect(roots.length).toEqual(1); expect(roots[0]).toEqual(0); }); }); // packages/engine/Specs/Core/CullingVolumeSpec.js var import__180 = __toESM(require_Cesium(), 1); describe("Core/CullingVolume", function() { let cullingVolume; beforeEach(function() { const frustum = new import__180.PerspectiveFrustum(); frustum.near = 1; frustum.far = 2; frustum.fov = Math.PI / 3; frustum.aspectRatio = 1; cullingVolume = frustum.computeCullingVolume( new import__180.Cartesian3(), import__180.Cartesian3.negate(import__180.Cartesian3.UNIT_Z, new import__180.Cartesian3()), import__180.Cartesian3.UNIT_Y ); }); it("computeVisibility throws without a bounding volume", function() { expect(function() { return new import__180.CullingVolume().computeVisibility(); }).toThrowDeveloperError(); }); it("computeVisibilityWithPlaneMask throws without a bounding volume", function() { expect(function() { return new import__180.CullingVolume().computeVisibilityWithPlaneMask( void 0, import__180.CullingVolume.MASK_INDETERMINATE ); }).toThrowDeveloperError(); }); it("computeVisibilityWithPlaneMask throws without a parent plane mask", function() { expect(function() { return new import__180.CullingVolume().computeVisibilityWithPlaneMask( new import__180.BoundingSphere(), void 0 ); }).toThrowDeveloperError(); }); function testWithAndWithoutPlaneMask(culling, bound, intersect) { expect(culling.computeVisibility(bound)).toEqual(intersect); const mask = culling.computeVisibilityWithPlaneMask( bound, import__180.CullingVolume.MASK_INDETERMINATE ); if (intersect === import__180.Intersect.INSIDE) { expect(mask).toEqual(import__180.CullingVolume.MASK_INSIDE); } else if (intersect === import__180.Intersect.OUTSIDE) { expect(mask).toEqual(import__180.CullingVolume.MASK_OUTSIDE); } else { expect(mask).not.toEqual(import__180.CullingVolume.MASK_INSIDE); expect(mask).not.toEqual(import__180.CullingVolume.MASK_OUTSIDE); } expect(culling.computeVisibilityWithPlaneMask(bound, mask)).toEqual(mask); } describe("box intersections", function() { it("can contain an axis aligned bounding box", function() { const box1 = import__180.AxisAlignedBoundingBox.fromPoints([ new import__180.Cartesian3(-0.5, 0, -1.25), new import__180.Cartesian3(0.5, 0, -1.25), new import__180.Cartesian3(-0.5, 0, -1.75), new import__180.Cartesian3(0.5, 0, -1.75) ]); testWithAndWithoutPlaneMask(cullingVolume, box1, import__180.Intersect.INSIDE); }); describe("can partially contain an axis aligned bounding box", function() { it("on the far plane", function() { const box2 = import__180.AxisAlignedBoundingBox.fromPoints([ new import__180.Cartesian3(-0.5, 0, -1.5), new import__180.Cartesian3(0.5, 0, -1.5), new import__180.Cartesian3(-0.5, 0, -2.5), new import__180.Cartesian3(0.5, 0, -2.5) ]); testWithAndWithoutPlaneMask( cullingVolume, box2, import__180.Intersect.INTERSECTING ); }); it("on the near plane", function() { const box3 = import__180.AxisAlignedBoundingBox.fromPoints([ new import__180.Cartesian3(-0.5, 0, -0.5), new import__180.Cartesian3(0.5, 0, -0.5), new import__180.Cartesian3(-0.5, 0, -1.5), new import__180.Cartesian3(0.5, 0, -1.5) ]); testWithAndWithoutPlaneMask( cullingVolume, box3, import__180.Intersect.INTERSECTING ); }); it("on the left plane", function() { const box4 = import__180.AxisAlignedBoundingBox.fromPoints([ new import__180.Cartesian3(-1.5, 0, -1.25), new import__180.Cartesian3(0, 0, -1.25), new import__180.Cartesian3(-1.5, 0, -1.5), new import__180.Cartesian3(0, 0, -1.5) ]); testWithAndWithoutPlaneMask( cullingVolume, box4, import__180.Intersect.INTERSECTING ); }); it("on the right plane", function() { const box5 = import__180.AxisAlignedBoundingBox.fromPoints([ new import__180.Cartesian3(0, 0, -1.25), new import__180.Cartesian3(1.5, 0, -1.25), new import__180.Cartesian3(0, 0, -1.5), new import__180.Cartesian3(1.5, 0, -1.5) ]); testWithAndWithoutPlaneMask( cullingVolume, box5, import__180.Intersect.INTERSECTING ); }); it("on the top plane", function() { const box6 = import__180.AxisAlignedBoundingBox.fromPoints([ new import__180.Cartesian3(-0.5, 0, -1.25), new import__180.Cartesian3(0.5, 0, -1.25), new import__180.Cartesian3(-0.5, 2, -1.75), new import__180.Cartesian3(0.5, 2, -1.75) ]); testWithAndWithoutPlaneMask( cullingVolume, box6, import__180.Intersect.INTERSECTING ); }); it("on the bottom plane", function() { const box7 = import__180.AxisAlignedBoundingBox.fromPoints([ new import__180.Cartesian3(-0.5, -2, -1.25), new import__180.Cartesian3(0.5, 0, -1.25), new import__180.Cartesian3(-0.5, -2, -1.5), new import__180.Cartesian3(0.5, 0, -1.5) ]); testWithAndWithoutPlaneMask( cullingVolume, box7, import__180.Intersect.INTERSECTING ); }); }); describe("can not contain an axis aligned bounding box", function() { it("past the far plane", function() { const box8 = import__180.AxisAlignedBoundingBox.fromPoints([ new import__180.Cartesian3(-0.5, 0, -2.25), new import__180.Cartesian3(0.5, 0, -2.25), new import__180.Cartesian3(-0.5, 0, -2.75), new import__180.Cartesian3(0.5, 0, -2.75) ]); testWithAndWithoutPlaneMask(cullingVolume, box8, import__180.Intersect.OUTSIDE); }); it("before the near plane", function() { const box9 = import__180.AxisAlignedBoundingBox.fromPoints([ new import__180.Cartesian3(-0.5, 0, -0.25), new import__180.Cartesian3(0.5, 0, -0.25), new import__180.Cartesian3(-0.5, 0, -0.75), new import__180.Cartesian3(0.5, 0, -0.75) ]); testWithAndWithoutPlaneMask(cullingVolume, box9, import__180.Intersect.OUTSIDE); }); it("past the left plane", function() { const box10 = import__180.AxisAlignedBoundingBox.fromPoints([ new import__180.Cartesian3(-5, 0, -1.25), new import__180.Cartesian3(-3, 0, -1.25), new import__180.Cartesian3(-5, 0, -1.75), new import__180.Cartesian3(-3, 0, -1.75) ]); testWithAndWithoutPlaneMask(cullingVolume, box10, import__180.Intersect.OUTSIDE); }); it("past the right plane", function() { const box11 = import__180.AxisAlignedBoundingBox.fromPoints([ new import__180.Cartesian3(3, 0, -1.25), new import__180.Cartesian3(5, 0, -1.25), new import__180.Cartesian3(3, 0, -1.75), new import__180.Cartesian3(5, 0, -1.75) ]); testWithAndWithoutPlaneMask(cullingVolume, box11, import__180.Intersect.OUTSIDE); }); it("past the top plane", function() { const box12 = import__180.AxisAlignedBoundingBox.fromPoints([ new import__180.Cartesian3(-0.5, 3, -1.25), new import__180.Cartesian3(0.5, 3, -1.25), new import__180.Cartesian3(-0.5, 5, -1.75), new import__180.Cartesian3(0.5, 5, -1.75) ]); testWithAndWithoutPlaneMask(cullingVolume, box12, import__180.Intersect.OUTSIDE); }); it("past the bottom plane", function() { const box13 = import__180.AxisAlignedBoundingBox.fromPoints([ new import__180.Cartesian3(-0.5, -3, -1.25), new import__180.Cartesian3(0.5, -3, -1.25), new import__180.Cartesian3(-0.5, -5, -1.75), new import__180.Cartesian3(0.5, -5, -1.75) ]); testWithAndWithoutPlaneMask(cullingVolume, box13, import__180.Intersect.OUTSIDE); }); }); }); describe("sphere intersection", function() { it("can contain a sphere", function() { const sphere1 = import__180.BoundingSphere.fromPoints([ new import__180.Cartesian3(0, 0, -1.25), new import__180.Cartesian3(0, 0, -1.75) ]); testWithAndWithoutPlaneMask(cullingVolume, sphere1, import__180.Intersect.INSIDE); }); describe("can partially contain a sphere", function() { it("on the far plane", function() { const sphere2 = import__180.BoundingSphere.fromPoints([ new import__180.Cartesian3(0, 0, -1.5), new import__180.Cartesian3(0, 0, -2.5) ]); testWithAndWithoutPlaneMask( cullingVolume, sphere2, import__180.Intersect.INTERSECTING ); }); it("on the near plane", function() { const sphere3 = import__180.BoundingSphere.fromPoints([ new import__180.Cartesian3(0, 0, -0.5), new import__180.Cartesian3(0, 0, -1.5) ]); testWithAndWithoutPlaneMask( cullingVolume, sphere3, import__180.Intersect.INTERSECTING ); }); it("on the left plane", function() { const sphere4 = import__180.BoundingSphere.fromPoints([ new import__180.Cartesian3(-1, 0, -1.5), new import__180.Cartesian3(0, 0, -1.5) ]); testWithAndWithoutPlaneMask( cullingVolume, sphere4, import__180.Intersect.INTERSECTING ); }); it("on the right plane", function() { const sphere5 = import__180.BoundingSphere.fromPoints([ new import__180.Cartesian3(0, 0, -1.5), new import__180.Cartesian3(1, 0, -1.5) ]); testWithAndWithoutPlaneMask( cullingVolume, sphere5, import__180.Intersect.INTERSECTING ); }); it("on the top plane", function() { const sphere6 = import__180.BoundingSphere.fromPoints([ new import__180.Cartesian3(0, 0, -1.5), new import__180.Cartesian3(0, 2, -1.5) ]); testWithAndWithoutPlaneMask( cullingVolume, sphere6, import__180.Intersect.INTERSECTING ); }); it("on the bottom plane", function() { const sphere7 = import__180.BoundingSphere.fromPoints([ new import__180.Cartesian3(0, -2, -1.5), new import__180.Cartesian3(0, 0, -1.5) ]); testWithAndWithoutPlaneMask( cullingVolume, sphere7, import__180.Intersect.INTERSECTING ); }); }); describe("can not contain a sphere", function() { it("past the far plane", function() { const sphere8 = import__180.BoundingSphere.fromPoints([ new import__180.Cartesian3(0, 0, -2.25), new import__180.Cartesian3(0, 0, -2.75) ]); testWithAndWithoutPlaneMask(cullingVolume, sphere8, import__180.Intersect.OUTSIDE); }); it("before the near plane", function() { const sphere9 = import__180.BoundingSphere.fromPoints([ new import__180.Cartesian3(0, 0, -0.25), new import__180.Cartesian3(0, 0, -0.5) ]); testWithAndWithoutPlaneMask(cullingVolume, sphere9, import__180.Intersect.OUTSIDE); }); it("past the left plane", function() { const sphere10 = import__180.BoundingSphere.fromPoints([ new import__180.Cartesian3(-5, 0, -1.25), new import__180.Cartesian3(-4.5, 0, -1.75) ]); testWithAndWithoutPlaneMask(cullingVolume, sphere10, import__180.Intersect.OUTSIDE); }); it("past the right plane", function() { const sphere11 = import__180.BoundingSphere.fromPoints([ new import__180.Cartesian3(4.5, 0, -1.25), new import__180.Cartesian3(5, 0, -1.75) ]); testWithAndWithoutPlaneMask(cullingVolume, sphere11, import__180.Intersect.OUTSIDE); }); it("past the top plane", function() { const sphere12 = import__180.BoundingSphere.fromPoints([ new import__180.Cartesian3(-0.5, 4.5, -1.25), new import__180.Cartesian3(-0.5, 5, -1.25) ]); testWithAndWithoutPlaneMask(cullingVolume, sphere12, import__180.Intersect.OUTSIDE); }); it("past the bottom plane", function() { const sphere13 = import__180.BoundingSphere.fromPoints([ new import__180.Cartesian3(-0.5, -4.5, -1.25), new import__180.Cartesian3(-0.5, -5, -1.25) ]); testWithAndWithoutPlaneMask(cullingVolume, sphere13, import__180.Intersect.OUTSIDE); }); }); }); describe("construct from bounding sphere", function() { const boundingSphereCullingVolume = new import__180.BoundingSphere( new import__180.Cartesian3(1e3, 2e3, 3e3), 100 ); const cullingVolume2 = import__180.CullingVolume.fromBoundingSphere( boundingSphereCullingVolume ); it("throws without a boundingSphere", function() { expect(function() { import__180.CullingVolume.fromBoundingSphere(void 0); }).toThrowDeveloperError(); }); it("can contain a volume", function() { const sphere1 = import__180.BoundingSphere.clone(boundingSphereCullingVolume); sphere1.radius *= 0.5; testWithAndWithoutPlaneMask(cullingVolume2, sphere1, import__180.Intersect.INSIDE); }); describe("can partially contain a volume", function() { it("on the far plane", function() { const offset = new import__180.Cartesian3( 0, 0, boundingSphereCullingVolume.radius * 1.5 ); const center = import__180.Cartesian3.add( boundingSphereCullingVolume.center, offset, new import__180.Cartesian3() ); const radius = boundingSphereCullingVolume.radius * 0.5; const sphere2 = new import__180.BoundingSphere(center, radius); testWithAndWithoutPlaneMask( cullingVolume2, sphere2, import__180.Intersect.INTERSECTING ); }); it("on the near plane", function() { const offset = new import__180.Cartesian3( 0, 0, -boundingSphereCullingVolume.radius * 1.5 ); const center = import__180.Cartesian3.add( boundingSphereCullingVolume.center, offset, new import__180.Cartesian3() ); const radius = boundingSphereCullingVolume.radius * 0.5; const sphere3 = new import__180.BoundingSphere(center, radius); testWithAndWithoutPlaneMask( cullingVolume2, sphere3, import__180.Intersect.INTERSECTING ); }); it("on the left plane", function() { const offset = new import__180.Cartesian3( -boundingSphereCullingVolume.radius * 1.5, 0, 0 ); const center = import__180.Cartesian3.add( boundingSphereCullingVolume.center, offset, new import__180.Cartesian3() ); const radius = boundingSphereCullingVolume.radius * 0.5; const sphere4 = new import__180.BoundingSphere(center, radius); testWithAndWithoutPlaneMask( cullingVolume2, sphere4, import__180.Intersect.INTERSECTING ); }); it("on the right plane", function() { const offset = new import__180.Cartesian3( boundingSphereCullingVolume.radius * 1.5, 0, 0 ); const center = import__180.Cartesian3.add( boundingSphereCullingVolume.center, offset, new import__180.Cartesian3() ); const radius = boundingSphereCullingVolume.radius * 0.5; const sphere5 = new import__180.BoundingSphere(center, radius); testWithAndWithoutPlaneMask( cullingVolume2, sphere5, import__180.Intersect.INTERSECTING ); }); it("on the top plane", function() { const offset = new import__180.Cartesian3( 0, boundingSphereCullingVolume.radius * 1.5, 0 ); const center = import__180.Cartesian3.add( boundingSphereCullingVolume.center, offset, new import__180.Cartesian3() ); const radius = boundingSphereCullingVolume.radius * 0.5; const sphere6 = new import__180.BoundingSphere(center, radius); testWithAndWithoutPlaneMask( cullingVolume2, sphere6, import__180.Intersect.INTERSECTING ); }); it("on the bottom plane", function() { const offset = new import__180.Cartesian3( 0, -boundingSphereCullingVolume.radius * 1.5, 0 ); const center = import__180.Cartesian3.add( boundingSphereCullingVolume.center, offset, new import__180.Cartesian3() ); const radius = boundingSphereCullingVolume.radius * 0.5; const sphere7 = new import__180.BoundingSphere(center, radius); testWithAndWithoutPlaneMask( cullingVolume2, sphere7, import__180.Intersect.INTERSECTING ); }); }); describe("can not contain a volume", function() { it("past the far plane", function() { const offset = new import__180.Cartesian3( 0, 0, boundingSphereCullingVolume.radius * 2 ); const center = import__180.Cartesian3.add( boundingSphereCullingVolume.center, offset, new import__180.Cartesian3() ); const radius = boundingSphereCullingVolume.radius * 0.5; const sphere8 = new import__180.BoundingSphere(center, radius); testWithAndWithoutPlaneMask(cullingVolume2, sphere8, import__180.Intersect.OUTSIDE); }); it("before the near plane", function() { const offset = new import__180.Cartesian3( 0, 0, -boundingSphereCullingVolume.radius * 2 ); const center = import__180.Cartesian3.add( boundingSphereCullingVolume.center, offset, new import__180.Cartesian3() ); const radius = boundingSphereCullingVolume.radius * 0.5; const sphere9 = new import__180.BoundingSphere(center, radius); testWithAndWithoutPlaneMask(cullingVolume2, sphere9, import__180.Intersect.OUTSIDE); }); it("past the left plane", function() { const offset = new import__180.Cartesian3( -boundingSphereCullingVolume.radius * 2, 0, 0 ); const center = import__180.Cartesian3.add( boundingSphereCullingVolume.center, offset, new import__180.Cartesian3() ); const radius = boundingSphereCullingVolume.radius * 0.5; const sphere10 = new import__180.BoundingSphere(center, radius); testWithAndWithoutPlaneMask(cullingVolume2, sphere10, import__180.Intersect.OUTSIDE); }); it("past the right plane", function() { const offset = new import__180.Cartesian3( boundingSphereCullingVolume.radius * 2, 0, 0 ); const center = import__180.Cartesian3.add( boundingSphereCullingVolume.center, offset, new import__180.Cartesian3() ); const radius = boundingSphereCullingVolume.radius * 0.5; const sphere11 = new import__180.BoundingSphere(center, radius); testWithAndWithoutPlaneMask(cullingVolume2, sphere11, import__180.Intersect.OUTSIDE); }); it("past the top plane", function() { const offset = new import__180.Cartesian3( 0, boundingSphereCullingVolume.radius * 2, 0 ); const center = import__180.Cartesian3.add( boundingSphereCullingVolume.center, offset, new import__180.Cartesian3() ); const radius = boundingSphereCullingVolume.radius * 0.5; const sphere12 = new import__180.BoundingSphere(center, radius); testWithAndWithoutPlaneMask(cullingVolume2, sphere12, import__180.Intersect.OUTSIDE); }); it("past the bottom plane", function() { const offset = new import__180.Cartesian3( 0, -boundingSphereCullingVolume.radius * 2, 0 ); const center = import__180.Cartesian3.add( boundingSphereCullingVolume.center, offset, new import__180.Cartesian3() ); const radius = boundingSphereCullingVolume.radius * 0.5; const sphere13 = new import__180.BoundingSphere(center, radius); testWithAndWithoutPlaneMask(cullingVolume2, sphere13, import__180.Intersect.OUTSIDE); }); }); }); }); // packages/engine/Specs/Core/CustomHeightmapTerrainProviderSpec.js var import__181 = __toESM(require_Cesium(), 1); describe("Core/CustomHeightmapTerrainProvider", function() { it("conforms to TerrainProvider interface", function() { expect(import__181.CustomHeightmapTerrainProvider).toConformToInterface( import__181.TerrainProvider ); }); it("constructor throws if callback is not provided", function() { const width = 2; const height = 2; expect(function() { return new import__181.CustomHeightmapTerrainProvider({ width, height }); }).toThrowDeveloperError(); }); it("constructor throws if width is not provided", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Float32Array(width * height); }; expect(function() { return new import__181.CustomHeightmapTerrainProvider({ callback, height }); }).toThrowDeveloperError(); }); it("constructor throws if height is not provided", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Float32Array(width * height); }; expect(function() { return new import__181.CustomHeightmapTerrainProvider({ callback, width }); }).toThrowDeveloperError(); }); it("constructs with a credit", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Float32Array(width * height); }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height, credit: "Credit" }); expect(provider.credit).toBeDefined(); }); it("constructs with a tiling scheme", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Float32Array(width * height); }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height, tilingScheme: new import__181.WebMercatorTilingScheme() }); expect(provider.tilingScheme).toBeInstanceOf(import__181.WebMercatorTilingScheme); }); it("has error event", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Float32Array(width * height); }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height }); expect(provider.errorEvent).toBeDefined(); expect(provider.errorEvent).toBe(provider.errorEvent); }); it("gets geometric error", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Float32Array(width * height); }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height }); const geometricError = import__181.TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap( provider.tilingScheme.ellipsoid, Math.max(provider.width, provider.height), provider.tilingScheme.getNumberOfXTilesAtLevel(0) ); expect(provider.getLevelMaximumGeometricError(0)).toBe(geometricError); }); it("water mask is disabled", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Float32Array(width * height); }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height }); expect(provider.hasWaterMask).toBe(false); }); it("vertex normals are disabled", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Float32Array(width * height); }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height }); expect(provider.hasVertexNormals).toBe(false); }); it("requestTileGeometry receives heightmap data as Int8Array", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Int8Array(width * height); }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height }); const terrainData = provider.requestTileGeometry(0, 0, 0); expect(terrainData).toBeDefined(); }); it("requestTileGeometry receives heightmap data as Uint8Array", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Uint8Array(width * height); }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height }); const terrainData = provider.requestTileGeometry(0, 0, 0); expect(terrainData).toBeDefined(); }); it("requestTileGeometry receives heightmap data as Int16Array", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Int16Array(width * height); }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height }); const terrainData = provider.requestTileGeometry(0, 0, 0); expect(terrainData).toBeDefined(); }); it("requestTileGeometry receives heightmap data as Uint16Array", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Uint16Array(width * height); }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height }); const terrainData = provider.requestTileGeometry(0, 0, 0); expect(terrainData).toBeDefined(); }); it("requestTileGeometry receives heightmap data as Int32Array", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Int32Array(width * height); }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height }); const terrainData = provider.requestTileGeometry(0, 0, 0); expect(terrainData).toBeDefined(); }); it("requestTileGeometry receives heightmap data as Uint32Array", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Uint32Array(width * height); }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height }); const terrainData = provider.requestTileGeometry(0, 0, 0); expect(terrainData).toBeDefined(); }); it("requestTileGeometry receives heightmap data as Float32Array", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Float32Array(width * height); }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height }); const terrainData = provider.requestTileGeometry(0, 0, 0); expect(terrainData).toBeDefined(); }); it("requestTileGeometry receives heightmap data as Float64Array", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Float64Array(width * height); }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height }); const terrainData = provider.requestTileGeometry(0, 0, 0); expect(terrainData).toBeDefined(); }); it("requestTileGeometry receives heightmap data as Number array", function() { const width = 2; const height = 2; const callback = function(x, y, level) { const buffer = new Array(4); buffer[0] = 0; buffer[1] = 0; buffer[2] = 0; buffer[3] = 0; return buffer; }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height }); const terrainData = provider.requestTileGeometry(0, 0, 0); expect(terrainData).toBeDefined(); }); it("requestTileGeometry returns undefined when callback function returns undefined", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return void 0; }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height }); expect(provider.requestTileGeometry()).toBeUndefined(); }); it("gets width and height", function() { const width = 2; const height = 3; const callback = function(x, y, level) { return new Float32Array(width * height); }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height }); expect(provider.width).toEqual(width); expect(provider.height).toEqual(height); }); it("returns undefined for getTileDataAvailable", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Int16Array(width * height); }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height }); expect(provider.getTileDataAvailable()).toBeUndefined(); }); it("returns undefined for loadTileDataAvailability", function() { const width = 2; const height = 2; const callback = function(x, y, level) { return new Int16Array(width * height); }; const provider = new import__181.CustomHeightmapTerrainProvider({ callback, width, height }); expect(provider.loadTileDataAvailability()).toBeUndefined(); }); }); // packages/engine/Specs/Core/CylinderGeometrySpec.js var import__182 = __toESM(require_Cesium(), 1); describe("Core/CylinderGeometry", function() { it("constructor throws with no length", function() { expect(function() { return new import__182.CylinderGeometry({}); }).toThrowDeveloperError(); }); it("constructor throws with no topRadius", function() { expect(function() { return new import__182.CylinderGeometry({ length: 1 }); }).toThrowDeveloperError(); }); it("constructor throws with no bottomRadius", function() { expect(function() { return new import__182.CylinderGeometry({ length: 1, topRadius: 1 }); }).toThrowDeveloperError(); }); it("constructor throws if slices is less than 3", function() { expect(function() { return new import__182.CylinderGeometry({ length: 1, topRadius: 1, bottomRadius: 1, slices: 2 }); }).toThrowDeveloperError(); }); it("computes positions", function() { const m = import__182.CylinderGeometry.createGeometry( new import__182.CylinderGeometry({ vertexFormat: import__182.VertexFormat.POSITION_ONLY, length: 1, topRadius: 1, bottomRadius: 1, slices: 3 }) ); const numVertices = 12; const numTriangles = 8; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("computes offset attribute", function() { const m = import__182.CylinderGeometry.createGeometry( new import__182.CylinderGeometry({ vertexFormat: import__182.VertexFormat.POSITION_ONLY, length: 1, topRadius: 1, bottomRadius: 1, slices: 3, offsetAttribute: import__182.GeometryOffsetAttribute.ALL }) ); const numVertices = 12; expect(m.attributes.position.values.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("compute all vertex attributes", function() { const m = import__182.CylinderGeometry.createGeometry( new import__182.CylinderGeometry({ vertexFormat: import__182.VertexFormat.ALL, length: 1, topRadius: 1, bottomRadius: 1, slices: 3 }) ); const numVertices = 12; const numTriangles = 8; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.attributes.st.values.length).toEqual(numVertices * 2); expect(m.attributes.normal.values.length).toEqual(numVertices * 3); expect(m.attributes.tangent.values.length).toEqual(numVertices * 3); expect(m.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("computes positions with topRadius equals 0", function() { const m = import__182.CylinderGeometry.createGeometry( new import__182.CylinderGeometry({ vertexFormat: import__182.VertexFormat.POSITION_ONLY, length: 1, topRadius: 0, bottomRadius: 1, slices: 3 }) ); const numVertices = 12; const numTriangles = 8; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("computes positions with bottomRadius equals 0", function() { const m = import__182.CylinderGeometry.createGeometry( new import__182.CylinderGeometry({ vertexFormat: import__182.VertexFormat.POSITION_ONLY, length: 1, topRadius: 1, bottomRadius: 0, slices: 3 }) ); const numVertices = 12; const numTriangles = 8; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it( "undefined is returned if the length is less than or equal to zero or if both radii are equal to zero or is either radii and less than zero", function() { const cylinder0 = new import__182.CylinderGeometry({ length: 0, topRadius: 8e4, bottomRadius: 2e5 }); const cylinder1 = new import__182.CylinderGeometry({ length: 2e5, topRadius: 0, bottomRadius: 0 }); const cylinder2 = new import__182.CylinderGeometry({ length: 2e5, topRadius: -10, bottomRadius: 4 }); const cylinder3 = new import__182.CylinderGeometry({ length: -2e5, topRadius: 100, bottomRadius: 100 }); const cylinder4 = new import__182.CylinderGeometry({ length: 2e5, topRadius: 0, bottomRadius: -34 }); const geometry0 = import__182.CylinderGeometry.createGeometry(cylinder0); const geometry1 = import__182.CylinderGeometry.createGeometry(cylinder1); const geometry2 = import__182.CylinderGeometry.createGeometry(cylinder2); const geometry3 = import__182.CylinderGeometry.createGeometry(cylinder3); const geometry4 = import__182.CylinderGeometry.createGeometry(cylinder4); expect(geometry0).toBeUndefined(); expect(geometry1).toBeUndefined(); expect(geometry2).toBeUndefined(); expect(geometry3).toBeUndefined(); expect(geometry4).toBeUndefined(); } ); const cylinder = new import__182.CylinderGeometry({ vertexFormat: import__182.VertexFormat.POSITION_ONLY, length: 1, topRadius: 1, bottomRadius: 0, slices: 3 }); const packedInstance = [ 1, 0, 0, 0, 0, 0, 1, 1, 0, 3, -1 ]; createPackableSpecs_default(import__182.CylinderGeometry, cylinder, packedInstance); }); // packages/engine/Specs/Core/CylinderOutlineGeometrySpec.js var import__183 = __toESM(require_Cesium(), 1); describe("Core/CylinderOutlineGeometry", function() { it("constructor throws with no length", function() { expect(function() { return new import__183.CylinderOutlineGeometry({}); }).toThrowDeveloperError(); }); it("constructor throws with no topRadius", function() { expect(function() { return new import__183.CylinderOutlineGeometry({ length: 1 }); }).toThrowDeveloperError(); }); it("constructor throws with no bottomRadius", function() { expect(function() { return new import__183.CylinderOutlineGeometry({ length: 1, topRadius: 1 }); }).toThrowDeveloperError(); }); it("constructor throws if slices is less than 3", function() { expect(function() { return new import__183.CylinderOutlineGeometry({ length: 1, topRadius: 1, bottomRadius: 1, slices: 2 }); }).toThrowDeveloperError(); }); it("computes positions", function() { const m = import__183.CylinderOutlineGeometry.createGeometry( new import__183.CylinderOutlineGeometry({ length: 1, topRadius: 1, bottomRadius: 1, slices: 3 }) ); expect(m.attributes.position.values.length).toEqual(6 * 3); expect(m.indices.length).toEqual(9 * 2); }); it("computes offset attribute", function() { const m = import__183.CylinderOutlineGeometry.createGeometry( new import__183.CylinderOutlineGeometry({ length: 1, topRadius: 1, bottomRadius: 1, slices: 3, offsetAttribute: import__183.GeometryOffsetAttribute.ALL }) ); const numVertices = 6; expect(m.attributes.position.values.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("computes positions with no lines along the length", function() { const m = import__183.CylinderOutlineGeometry.createGeometry( new import__183.CylinderOutlineGeometry({ length: 1, topRadius: 1, bottomRadius: 1, slices: 3, numberOfVerticalLines: 0 }) ); const numVertices = 6; const numLines = 6; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numLines * 2); }); it( "undefined is returned if the length is less than or equal to zero or if both radii are equal to zero or is either radii and less than zero", function() { const cylinderOutline0 = new import__183.CylinderOutlineGeometry({ length: 0, topRadius: 8e4, bottomRadius: 2e5 }); const cylinderOutline1 = new import__183.CylinderOutlineGeometry({ length: 2e5, topRadius: 0, bottomRadius: 0 }); const cylinderOutline2 = new import__183.CylinderOutlineGeometry({ length: 2e5, topRadius: -10, bottomRadius: 4 }); const cylinderOutline3 = new import__183.CylinderOutlineGeometry({ length: -2e5, topRadius: 100, bottomRadius: 100 }); const cylinderOutline4 = new import__183.CylinderOutlineGeometry({ length: 2e5, topRadius: 32, bottomRadius: -100 }); const geometry0 = import__183.CylinderOutlineGeometry.createGeometry( cylinderOutline0 ); const geometry1 = import__183.CylinderOutlineGeometry.createGeometry( cylinderOutline1 ); const geometry2 = import__183.CylinderOutlineGeometry.createGeometry( cylinderOutline2 ); const geometry3 = import__183.CylinderOutlineGeometry.createGeometry( cylinderOutline3 ); const geometry4 = import__183.CylinderOutlineGeometry.createGeometry( cylinderOutline4 ); expect(geometry0).toBeUndefined(); expect(geometry1).toBeUndefined(); expect(geometry2).toBeUndefined(); expect(geometry3).toBeUndefined(); expect(geometry4).toBeUndefined(); } ); const cylinder = new import__183.CylinderOutlineGeometry({ length: 1, topRadius: 1, bottomRadius: 0, slices: 3, numberOfVerticalLines: 0 }); const packedInstance = [1, 1, 0, 3, 0, -1]; createPackableSpecs_default(import__183.CylinderOutlineGeometry, cylinder, packedInstance); }); // packages/engine/Specs/Core/DeveloperErrorSpec.js var import__184 = __toESM(require_Cesium(), 1); describe("Core/DeveloperError", function() { const name = "DeveloperError"; const testMessage = "Testing"; let e; beforeEach(function() { e = new import__184.DeveloperError(testMessage); }); it("has a name property", function() { expect(e.name).toEqual(name); }); it("has a message property", function() { expect(e.message).toEqual(testMessage); }); it("has a stack property", function() { if (!window.specsUsingRelease) { expect(e.stack).toContain(name); } }); it("has a working toString", function() { const str = new import__184.DeveloperError(testMessage).toString(); if (!window.specsUsingRelease) { expect(str).toContain(`${name}: ${testMessage}`); } else { expect(str).toContain(testMessage); } }); }); // packages/engine/Specs/Core/DistanceDisplayConditionGeometryInstanceAttributeSpec.js var import__185 = __toESM(require_Cesium(), 1); describe("Core/DistanceDisplayConditionGeometryInstanceAttribute", function() { it("constructor", function() { const attribute = new import__185.DistanceDisplayConditionGeometryInstanceAttribute( 10, 100 ); expect(attribute.componentDatatype).toEqual(import__185.ComponentDatatype.FLOAT); expect(attribute.componentsPerAttribute).toEqual(2); expect(attribute.normalize).toEqual(false); const value = new Float32Array([10, 100]); expect(attribute.value).toEqual(value); }); it("constructor throws with far > near", function() { expect(function() { return new import__185.DistanceDisplayConditionGeometryInstanceAttribute(100, 10); }).toThrowDeveloperError(); }); it("fromDistanceDisplayCondition", function() { const dc = new import__185.DistanceDisplayCondition(10, 100); const attribute = import__185.DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition( dc ); expect(attribute.componentDatatype).toEqual(import__185.ComponentDatatype.FLOAT); expect(attribute.componentsPerAttribute).toEqual(2); expect(attribute.normalize).toEqual(false); const value = new Float32Array([dc.near, dc.far]); expect(attribute.value).toEqual(value); }); it("fromDistanceDisplayCondition throws without distanceDisplayCondition", function() { expect(function() { import__185.DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(); }).toThrowDeveloperError(); }); it("fromDistanceDisplayCondition throws with far >= near", function() { expect(function() { import__185.DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition( new import__185.DistanceDisplayCondition(100, 10) ); }).toThrowDeveloperError(); }); it("toValue", function() { const dc = new import__185.DistanceDisplayCondition(10, 200); const expectedResult = new Float32Array([dc.near, dc.far]); expect( import__185.DistanceDisplayConditionGeometryInstanceAttribute.toValue(dc) ).toEqual(expectedResult); }); it("toValue works with result parameter", function() { const dc = new import__185.DistanceDisplayCondition(10, 200); const expectedResult = new Float32Array([dc.near, dc.far]); const result = new Float32Array(2); const returnedResult = import__185.DistanceDisplayConditionGeometryInstanceAttribute.toValue( dc, result ); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expectedResult); }); it("toValue throws without a distanceDisplayCondition", function() { expect(function() { import__185.DistanceDisplayConditionGeometryInstanceAttribute.toValue(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/DistanceDisplayConditionSpec.js var import__186 = __toESM(require_Cesium(), 1); describe("Core/DistanceDisplayCondition", function() { it("default constructs", function() { const dc = new import__186.DistanceDisplayCondition(); expect(dc.near).toEqual(0); expect(dc.far).toEqual(Number.MAX_VALUE); }); it("constructs with parameters", function() { const near = 10; const far = 100; const dc = new import__186.DistanceDisplayCondition(near, far); expect(dc.near).toEqual(near); expect(dc.far).toEqual(far); }); it("gets and sets properties", function() { const dc = new import__186.DistanceDisplayCondition(); const near = 10; const far = 100; dc.near = near; dc.far = far; expect(dc.near).toEqual(near); expect(dc.far).toEqual(far); }); it("determines equality with static function", function() { const dc = new import__186.DistanceDisplayCondition(10, 100); expect( import__186.DistanceDisplayCondition.equals( dc, new import__186.DistanceDisplayCondition(10, 100) ) ).toEqual(true); expect( import__186.DistanceDisplayCondition.equals( dc, new import__186.DistanceDisplayCondition(11, 100) ) ).toEqual(false); expect( import__186.DistanceDisplayCondition.equals( dc, new import__186.DistanceDisplayCondition(10, 101) ) ).toEqual(false); expect(import__186.DistanceDisplayCondition.equals(dc, void 0)).toEqual(false); }); it("determines equality with prototype function", function() { const dc = new import__186.DistanceDisplayCondition(10, 100); expect(dc.equals(new import__186.DistanceDisplayCondition(10, 100))).toEqual(true); expect(dc.equals(new import__186.DistanceDisplayCondition(11, 100))).toEqual(false); expect(dc.equals(new import__186.DistanceDisplayCondition(10, 101))).toEqual(false); expect(dc.equals(void 0)).toEqual(false); }); it("static clones", function() { const dc = new import__186.DistanceDisplayCondition(10, 100); const result = import__186.DistanceDisplayCondition.clone(dc); expect(dc).toEqual(result); }); it("static clone with a result parameter", function() { const dc = new import__186.DistanceDisplayCondition(10, 100); const result = new import__186.DistanceDisplayCondition(); const returnedResult = import__186.DistanceDisplayCondition.clone(dc, result); expect(dc).not.toBe(result); expect(result).toBe(returnedResult); expect(dc).toEqual(result); }); it("static clone works with a result parameter that is an input parameter", function() { const dc = new import__186.DistanceDisplayCondition(10, 100); const returnedResult = import__186.DistanceDisplayCondition.clone(dc, dc); expect(dc).toBe(returnedResult); }); it("clones", function() { const dc = new import__186.DistanceDisplayCondition(10, 100); const result = dc.clone(); expect(dc).toEqual(result); }); it("clone with a result parameter", function() { const dc = new import__186.DistanceDisplayCondition(10, 100); const result = new import__186.DistanceDisplayCondition(); const returnedResult = dc.clone(result); expect(dc).not.toBe(result); expect(result).toBe(returnedResult); expect(dc).toEqual(result); }); it("clone works with a result parameter that is an input parameter", function() { const dc = new import__186.DistanceDisplayCondition(10, 100); const returnedResult = dc.clone(dc); expect(dc).toBe(returnedResult); }); createPackableSpecs_default( import__186.DistanceDisplayCondition, new import__186.DistanceDisplayCondition(1, 2), [1, 2] ); }); // packages/engine/Specs/Core/DoubleEndedPriorityQueueSpec.js var import__187 = __toESM(require_Cesium(), 1); describe("Core/DoubleEndedPriorityQueue", function() { function comparator(a, b) { return a - b; } it("constructor throws without options", function() { expect(function() { return new import__187.DoubleEndedPriorityQueue(); }).toThrowDeveloperError(); }); it("constructor throws if maximum length is less than zero", function() { expect(function() { return new import__187.DoubleEndedPriorityQueue({ comparator, maximumLength: -1 }); }).toThrowDeveloperError(); }); it("constructor throws without comparator", function() { expect(function() { return new import__187.DoubleEndedPriorityQueue({ comparator: void 0 }); }).toThrowDeveloperError(); }); it("gets comparator", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator }); const returnedComparator = queue.comparator; expect(returnedComparator).toEqual(comparator); }); it("uses different comparator", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator: function(a, b) { return b - a; } }); queue.insert(1); queue.insert(2); expect(queue.length).toEqual(2); expect(queue.getMinimum()).toEqual(2); expect(queue.getMaximum()).toEqual(1); }); it("checks state of default empty queue", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator }); expect(queue.length).toEqual(0); expect(queue.maximumLength).toBeUndefined(); expect(queue.internalArray.length).toEqual(0); expect(queue.getMinimum()).toBeUndefined(); expect(queue.getMaximum()).toBeUndefined(); }); it("inserts one element into queue", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator }); queue.insert(1); expect(queue.length).toEqual(1); expect(queue.internalArray.length).toEqual(1); expect(queue.getMinimum()).toEqual(1); expect(queue.getMaximum()).toEqual(1); }); it("inserts two elements into queue", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator }); queue.insert(1); queue.insert(2); expect(queue.length).toEqual(2); expect(queue.internalArray.length).toEqual(2); expect(queue.getMinimum()).toEqual(1); expect(queue.getMaximum()).toEqual(2); }); it("inserts three elements into queue", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator }); queue.insert(1); queue.insert(2); queue.insert(3); expect(queue.length).toEqual(3); expect(queue.internalArray.length).toEqual(3); expect(queue.getMinimum()).toEqual(1); expect(queue.getMaximum()).toEqual(3); }); it("inserts four elements into queue", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator }); queue.insert(1); queue.insert(2); queue.insert(3); queue.insert(4); expect(queue.length).toEqual(4); expect(queue.internalArray.length).toEqual(4); expect(queue.getMinimum()).toEqual(1); expect(queue.getMaximum()).toEqual(4); }); it("insert removes and returns minimum element when the queue is full", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator, maximumLength: 1 }); const nothing = queue.insert(1); const removed = queue.insert(2); expect(queue.length).toEqual(1); expect(queue.maximumLength).toEqual(1); expect(queue.internalArray.length).toEqual(1); expect(queue.getMinimum()).toEqual(2); expect(queue.getMaximum()).toEqual(2); expect(nothing).toBeUndefined(); expect(removed).toEqual(1); }); it("insert returns undefined when new element is less than or equal priority to the minimum element and the queue is full", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator: function(a, b) { return a.value - b.value; }, maximumLength: 2 }); const obj1 = { value: 1, id: 0 }; const obj2 = { value: 2, id: 0 }; const obj3 = { value: 1, id: 1 }; const obj4 = { value: 0, id: 1 }; const result1 = queue.insert(obj1); const result2 = queue.insert(obj2); const result3 = queue.insert(obj3); const result4 = queue.insert(obj4); expect(queue.length).toEqual(2); expect(queue.maximumLength).toEqual(2); expect(queue.internalArray.length).toEqual(2); expect(queue.getMinimum().id).toEqual(0); expect(result1).toBeUndefined(); expect(result2).toBeUndefined(); expect(result3).toEqual(obj3); expect(result4).toEqual(obj4); }); it("remove and return minimum element", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator }); queue.insert(1); queue.insert(2); queue.insert(3); const minimumValue = queue.removeMinimum(); expect(queue.length).toEqual(2); expect(minimumValue).toEqual(1); expect(queue.getMinimum()).toEqual(2); expect(queue.internalArray[2]).toBeUndefined(); }); it("removeMinimum returns undefined when queue is empty", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator }); const minimumValue = queue.removeMinimum(); expect(minimumValue).toBeUndefined(); }); it("remove and return maximum element", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator }); queue.insert(1); queue.insert(2); queue.insert(3); const maximumValue = queue.removeMaximum(); expect(queue.length).toEqual(2); expect(maximumValue).toEqual(3); expect(queue.getMaximum()).toEqual(2); expect(queue.internalArray[2]).toBeUndefined(); }); it("removeMaximum returns undefined when queue is empty", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator }); const maximumValue = queue.removeMaximum(); expect(maximumValue).toBeUndefined(); }); it("clones queue", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator, maximumLength: 4 }); queue.insert(1); queue.insert(2); const clone24 = queue.clone(); expect(clone24.length).toEqual(queue.length); expect(clone24.maximumLength).toEqual(queue.maximumLength); expect(clone24.comparator).toEqual(queue.comparator); expect(clone24.getMaximum()).toEqual(queue.getMaximum()); expect(clone24.getMinimum()).toEqual(queue.getMinimum()); }); it("resets queue", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator }); queue.insert(1); queue.insert(2); queue.reset(); expect(queue.length).toEqual(0); expect(queue.getMinimum()).toBeUndefined(); expect(queue.getMaximum()).toBeUndefined(); expect(queue.internalArray.length).toEqual(0); }); it("resets queue with maximum length", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator, maximumLength: 1 }); queue.insert(1); queue.reset(); expect(queue.length).toEqual(0); expect(queue.getMinimum()).toBeUndefined(); expect(queue.getMaximum()).toBeUndefined(); expect(queue.internalArray.length).toEqual(1); expect(queue.internalArray[0]).toBeUndefined(); }); it("creates queue with maximum length of zero", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator, maximumLength: 0 }); queue.insert(1); expect(queue.length).toEqual(0); expect(queue.maximumLength).toEqual(0); expect(queue.internalArray.length).toEqual(0); expect(queue.getMinimum()).toBeUndefined(); expect(queue.getMaximum()).toBeUndefined(); }); it("creates queue with maximum length of one", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator, maximumLength: 1 }); queue.insert(1); queue.insert(2); expect(queue.length).toEqual(1); expect(queue.maximumLength).toEqual(1); expect(queue.internalArray.length).toEqual(1); expect(queue.getMinimum()).toEqual(2); expect(queue.getMaximum()).toEqual(2); }); it("throws when maximum length is set to less than zero", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator }); expect(function() { queue.maximumLength = -1; }).toThrowDeveloperError(); }); it("sets maximum length to undefined", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator }); queue.maximumLength = 2; queue.insert(1); queue.insert(2); queue.maximumLength = void 0; queue.insert(3); expect(queue.length).toEqual(3); expect(queue.maximumLength).toBeUndefined(); expect(queue.getMinimum()).toEqual(1); expect(queue.getMaximum()).toEqual(3); }); it("sets maximum length to less than current length", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator }); const maximumLength = 5; for (let i = 0; i < maximumLength * 2; i++) { const value = i; queue.insert(value); } queue.maximumLength = maximumLength; expect(queue.length).toEqual(maximumLength); expect(queue.maximumLength).toEqual(maximumLength); expect(queue.internalArray.length).toEqual(maximumLength); expect(queue.getMinimum()).toEqual(maximumLength); expect(queue.getMaximum()).toEqual(maximumLength * 2 - 1); }); function isValidQueue(queue) { const minArray = []; const maxArray = []; const minQueue = queue.clone(); const maxQueue = queue.clone(); while (minQueue.length > 0) { minArray.push(minQueue.removeMinimum()); } while (maxQueue.length > 0) { maxArray.push(maxQueue.removeMaximum()); } if (minQueue.length !== 0 || maxQueue.length !== 0) { return false; } let i; for (i = 0; i < minArray.length - 1; i++) { if (minArray[i] > minArray[i + 1]) { return false; } } for (i = 0; i < maxArray.length - 1; i++) { if (maxArray[i] < maxArray[i + 1]) { return false; } } return true; } it("maintains priority with ascending insertions", function() { const length2 = 200; const maximumLength = 100; const queue = new import__187.DoubleEndedPriorityQueue({ comparator, maximumLength }); let pass = true; for (let i = 0; i < length2; ++i) { const value = i; queue.insert(value); pass = pass && isValidQueue(queue); } expect(pass).toBe(true); }); it("maintains priority with descending insertions", function() { const length2 = 200; const maximumLength = 100; const queue = new import__187.DoubleEndedPriorityQueue({ comparator, maximumLength }); let pass = true; for (let i = 0; i < length2; ++i) { const value = length2 - 1 - i; queue.insert(value); pass = pass && isValidQueue(queue); } expect(pass).toBe(true); }); it("maintains priority with random insertions", function() { const length2 = 200; const maximumLength = 100; const queue = new import__187.DoubleEndedPriorityQueue({ comparator, maximumLength }); let pass = true; for (let i = 0; i < length2; ++i) { const value = Math.random(); queue.insert(value); pass = pass && isValidQueue(queue); } expect(pass).toBe(true); }); it("resorts queue", function() { const queue = new import__187.DoubleEndedPriorityQueue({ comparator }); let i; const length2 = 200; for (i = 0; i < length2; ++i) { queue.insert(0); } const array = queue.internalArray; for (i = 0; i < length2; i++) { array[i] = Math.random(); } queue.resort(); const pass = isValidQueue(queue); expect(pass).toBe(true); }); }); // packages/engine/Specs/Core/DoublyLinkedListSpec.js var import__188 = __toESM(require_Cesium(), 1); describe("Core/DoublyLinkedList", function() { it("constructs", function() { const list = new import__188.DoublyLinkedList(); expect(list.head).not.toBeDefined(); expect(list.tail).not.toBeDefined(); expect(list.length).toEqual(0); }); it("adds items", function() { const list = new import__188.DoublyLinkedList(); const node = list.add(1); expect(list.head).toEqual(node); expect(list.tail).toEqual(node); expect(list.length).toEqual(1); expect(node).toBeDefined(); expect(node.item).toEqual(1); expect(node.previous).not.toBeDefined(); expect(node.next).not.toBeDefined(); const node2 = list.add(2); expect(list.head).toEqual(node); expect(list.tail).toEqual(node2); expect(list.length).toEqual(2); expect(node2).toBeDefined(); expect(node2.item).toEqual(2); expect(node2.previous).toEqual(node); expect(node2.next).not.toBeDefined(); expect(node.next).toEqual(node2); const node3 = list.add(3); expect(list.head).toEqual(node); expect(list.tail).toEqual(node3); expect(list.length).toEqual(3); expect(node3).toBeDefined(); expect(node3.item).toEqual(3); expect(node3.previous).toEqual(node2); expect(node3.next).not.toBeDefined(); expect(node2.next).toEqual(node3); }); it("removes from a list with one item", function() { const list = new import__188.DoublyLinkedList(); const node = list.add(1); list.remove(node); expect(list.head).not.toBeDefined(); expect(list.tail).not.toBeDefined(); expect(list.length).toEqual(0); }); it("removes head of list", function() { const list = new import__188.DoublyLinkedList(); const node = list.add(1); const node2 = list.add(2); list.remove(node); expect(list.head).toEqual(node2); expect(list.tail).toEqual(node2); expect(list.length).toEqual(1); }); it("removes tail of list", function() { const list = new import__188.DoublyLinkedList(); const node = list.add(1); const node2 = list.add(2); list.remove(node2); expect(list.head).toEqual(node); expect(list.tail).toEqual(node); expect(list.length).toEqual(1); }); it("removes middle of list", function() { const list = new import__188.DoublyLinkedList(); const node = list.add(1); const node2 = list.add(2); const node3 = list.add(3); list.remove(node2); expect(list.head).toEqual(node); expect(list.tail).toEqual(node3); expect(list.length).toEqual(2); }); it("removes nothing", function() { const list = new import__188.DoublyLinkedList(); const node = list.add(1); list.remove(void 0); expect(list.head).toEqual(node); expect(list.tail).toEqual(node); expect(list.length).toEqual(1); }); function expectOrder(list, nodes) { const length2 = nodes.length; expect(list.length).toEqual(length2); expect(list.head).toEqual(nodes[0]); expect(list.tail).toEqual(nodes[length2 - 1]); let node = list.head; for (let i = 0; i < length2; ++i) { const nextNode = i === length2 - 1 ? void 0 : nodes[i + 1]; const previousNode = i === 0 ? void 0 : nodes[i - 1]; expect(node).toEqual(nodes[i]); expect(node.next).toEqual(nextNode); expect(node.previous).toEqual(previousNode); node = node.next; } } it("splices nextNode before node", function() { const list = new import__188.DoublyLinkedList(); const node = list.add(1); const node2 = list.add(2); const node3 = list.add(3); const node4 = list.add(4); const node5 = list.add(5); list.splice(node4, node2); expectOrder(list, [node, node3, node4, node2, node5]); }); it("splices nextNode after node", function() { const list = new import__188.DoublyLinkedList(); const node = list.add(1); const node2 = list.add(2); const node3 = list.add(3); const node4 = list.add(4); const node5 = list.add(5); list.splice(node2, node4); expectOrder(list, [node, node2, node4, node3, node5]); }); it("splices nextNode immediately before node", function() { const list = new import__188.DoublyLinkedList(); const node = list.add(1); const node2 = list.add(2); const node3 = list.add(3); const node4 = list.add(4); list.splice(node3, node2); expectOrder(list, [node, node3, node2, node4]); }); it("splices nextNode immediately after node", function() { const list = new import__188.DoublyLinkedList(); const node = list.add(1); const node2 = list.add(2); const node3 = list.add(3); const node4 = list.add(4); list.splice(node2, node3); expectOrder(list, [node, node2, node3, node4]); }); it("splices node === nextNode", function() { const list = new import__188.DoublyLinkedList(); const node = list.add(1); const node2 = list.add(2); const node3 = list.add(3); list.splice(node2, node2); expectOrder(list, [node, node2, node3]); }); it("splices when nextNode was tail", function() { const list = new import__188.DoublyLinkedList(); const node = list.add(1); const node2 = list.add(2); const node3 = list.add(3); const node4 = list.add(4); list.splice(node2, node4); expectOrder(list, [node, node2, node4, node3]); }); it("splices when node was tail", function() { const list = new import__188.DoublyLinkedList(); const node = list.add(1); const node2 = list.add(2); const node3 = list.add(3); const node4 = list.add(4); list.splice(node4, node2); expectOrder(list, [node, node3, node4, node2]); }); it("splices when nextNode was head", function() { const list = new import__188.DoublyLinkedList(); const node = list.add(1); const node2 = list.add(2); const node3 = list.add(3); const node4 = list.add(4); list.splice(node3, node); expectOrder(list, [node2, node3, node, node4]); }); it("splices when node was head", function() { const list = new import__188.DoublyLinkedList(); const node = list.add(1); const node2 = list.add(2); const node3 = list.add(3); const node4 = list.add(4); list.splice(node, node3); expectOrder(list, [node, node3, node2, node4]); }); }); // packages/engine/Specs/Core/EarthOrientationParametersSpec.js var import__189 = __toESM(require_Cesium(), 1); describe("Core/EarthOrientationParameters", function() { let officialLeapSeconds; beforeAll(function() { officialLeapSeconds = import__189.JulianDate.leapSeconds.slice(0); }); afterEach(function() { import__189.JulianDate.leapSeconds = officialLeapSeconds.slice(0); }); it("adds leap seconds found in the data by default", function() { const eop = new import__189.EarthOrientationParameters({ data: { columnNames: [ "dateIso8601", "modifiedJulianDateUtc", "xPoleWanderRadians", "yPoleWanderRadians", "xCelestialPoleOffsetRadians", "yCelestialPoleOffsetRadians", "ut1MinusUtcSeconds", "taiMinusUtcSeconds", "lengthOfDayCorrectionSeconds" ], samples: [ "2011-08-25T00:00:00Z", 55798, 2117957047295119e-22, 2111518721609984e-21, 3393695767766752e-26, 33452143996557983e-26, -0.2908948, 34, -2956e-7, "2011-08-26T00:00:00Z", 55799, 2193297093339541e-22, 2115460256837405e-21, -8241832578862112e-26, 5623838700870617e-25, -0.29065, 34.5, -1824e-7, "2011-08-27T00:00:00Z", 55800, 2262286080161428e-22, 21191157519929706e-22, -3490658503988659e-25, 6981317007977318e-25, -0.2905572, 34.5, 19e-7, "2011-08-28T00:00:00Z", 55801, 23411652660779493e-23, 2122751854601292e-21, -6205615118202061e-25, 7853981633974483e-25, -0.2907007, 34.5, 2695e-7 ] } }); expect(eop).not.toBeNull(); const leapSeconds = import__189.JulianDate.leapSeconds; expect(leapSeconds.length).toBe(officialLeapSeconds.length + 1); const newDate = new import__189.JulianDate(24557995e-1, 34.5, import__189.TimeStandard.TAI); let foundNew = false; let previousDate; for (let i = 0, len = leapSeconds.length; i < len; ++i) { const leapSecond = leapSeconds[i]; if (leapSecond.julianDate.equals(newDate)) { foundNew = true; } if ((0, import__189.defined)(previousDate)) { expect( import__189.JulianDate.compare(previousDate, leapSecond.julianDate) ).toBeLessThan(0); } previousDate = leapSecond.julianDate; } expect(foundNew).toBe(true); }); it("does not add leap seconds if told not to do so", function() { const eop = new import__189.EarthOrientationParameters({ addNewLeapSeconds: false, data: { columnNames: [ "dateIso8601", "modifiedJulianDateUtc", "xPoleWanderRadians", "yPoleWanderRadians", "xCelestialPoleOffsetRadians", "yCelestialPoleOffsetRadians", "ut1MinusUtcSeconds", "taiMinusUtcSeconds", "lengthOfDayCorrectionSeconds" ], samples: [ "2011-08-25T00:00:00Z", 55798, 2117957047295119e-22, 2111518721609984e-21, 3393695767766752e-26, 33452143996557983e-26, -0.2908948, 35, -2956e-7, "2011-08-26T00:00:00Z", 55799, 2193297093339541e-22, 2115460256837405e-21, -8241832578862112e-26, 5623838700870617e-25, -0.29065, 36, -1824e-7, "2011-08-27T00:00:00Z", 55800, 2262286080161428e-22, 21191157519929706e-22, -3490658503988659e-25, 6981317007977318e-25, -0.2905572, 36, 19e-7, "2011-08-28T00:00:00Z", 55801, 23411652660779493e-23, 2122751854601292e-21, -6205615118202061e-25, 7853981633974483e-25, -0.2907007, 36, 2695e-7 ] } }); expect(eop).not.toBeNull(); const leapSeconds = import__189.JulianDate.leapSeconds; expect(leapSeconds.length).toBe(officialLeapSeconds.length); }); describe("loading eop", function() { function linearInterp(dx, y1, y2) { return y1 + dx * (y2 - y1); } it("interpolates data correctly under normal circumstances", function() { const eopDescription = { data: { columnNames: [ "dateIso8601", "modifiedJulianDateUtc", "xPoleWanderRadians", "yPoleWanderRadians", "xCelestialPoleOffsetRadians", "yCelestialPoleOffsetRadians", "ut1MinusUtcSeconds", "taiMinusUtcSeconds", "lengthOfDayCorrectionSeconds" ], samples: [ "2011-07-01T00:00:00Z", 55743, 2117957047295119e-22, 2111518721609984e-21, 3393695767766752e-26, 33452143996557983e-26, -0.2908948, 34, -2956e-7, "2011-07-02T00:00:00Z", 55744, 2193297093339541e-22, 2115460256837405e-21, -8241832578862112e-26, 5623838700870617e-25, -0.29065, 34, -1824e-7, "2011-07-03T00:00:00Z", 55745, 2262286080161428e-22, 21191157519929706e-22, -3490658503988659e-25, 6981317007977318e-25, -0.2905572, 34, 19e-7, "2011-07-04T00:00:00Z", 55746, 23411652660779493e-23, 2122751854601292e-21, -6205615118202061e-25, 7853981633974483e-25, -0.2907007, 34, 2695e-7 ] } }; const eop = new import__189.EarthOrientationParameters(eopDescription); const date = import__189.JulianDate.fromIso8601("2011-07-02T12:34:56Z"); const result = eop.compute(date); const nColumns = eopDescription.data.columnNames.length; let x0 = eopDescription.data.samples[1 * nColumns + 2]; let x1 = eopDescription.data.samples[2 * nColumns + 2]; const dt = import__189.JulianDate.secondsDifference( date, import__189.JulianDate.fromIso8601(eopDescription.data.samples[nColumns]) ) / 86400; let expected = linearInterp(dt, x0, x1); expect(result.xPoleWander).toEqualEpsilon(expected, 1e-22); x0 = eopDescription.data.samples[1 * nColumns + 3]; x1 = eopDescription.data.samples[2 * nColumns + 3]; expected = linearInterp(dt, x0, x1); expect(result.yPoleWander).toEqualEpsilon(expected, 1e-22); x0 = eopDescription.data.samples[1 * nColumns + 4]; x1 = eopDescription.data.samples[2 * nColumns + 4]; expected = linearInterp(dt, x0, x1); expect(result.xPoleOffset).toEqualEpsilon(expected, 1e-22); x0 = eopDescription.data.samples[1 * nColumns + 5]; x1 = eopDescription.data.samples[2 * nColumns + 5]; expected = linearInterp(dt, x0, x1); expect(result.yPoleOffset).toEqualEpsilon(expected, 1e-22); x0 = eopDescription.data.samples[1 * nColumns + 6]; x1 = eopDescription.data.samples[2 * nColumns + 6]; expected = linearInterp(dt, x0, x1); expect(result.ut1MinusUtc).toEqualEpsilon(expected, 1e-15); }); it("interpolates UT1 correctly over a leap second", function() { const eopDescription = { data: { columnNames: [ "dateIso8601", "modifiedJulianDateUtc", "xPoleWanderRadians", "yPoleWanderRadians", "xCelestialPoleOffsetRadians", "yCelestialPoleOffsetRadians", "ut1MinusUtcSeconds", "taiMinusUtcSeconds", "lengthOfDayCorrectionSeconds" ], samples: [ "2008-12-30T00:00:00Z", 54830, -46702101901281595e-24, 6989752766028624e-22, -780550026586353e-24, -1052045688007693e-24, -0.5911461, 33, 57e-5, "2008-12-31T00:00:00Z", 54831, -6507169227852191e-23, 702873178598983e-21, -780550026586353e-24, -18907733563271904e-25, -0.59187, 33, 8303e-7, "2009-01-01T00:00:00Z", 54832, -825443773457096e-22, 7089575902969077e-22, -8047907106418297e-25, -20604581447155277e-25, 0.4071533, 34, 10604e-7, "2009-01-02T00:00:00Z", 54833, -9884381330461219e-23, 7147559619229779e-22, -8435758051305926e-25, -18228994409718553e-25, 0.4059739, 34, 12279e-7, "2009-01-03T00:00:00Z", 54834, -11269009203710055e-23, 7226826656091187e-22, -9066015836748322e-25, -15029224114395617e-25, 0.404674, 34, 13014e-7 ] } }; const eop = new import__189.EarthOrientationParameters(eopDescription); const dateAtLeapSecond = import__189.JulianDate.fromIso8601("2009-01-01T00:00:00Z"); const dateSlightlyBefore = import__189.JulianDate.addSeconds( dateAtLeapSecond, -1, new import__189.JulianDate() ); const dateSlightlyAfter = import__189.JulianDate.addSeconds( dateAtLeapSecond, 1, new import__189.JulianDate() ); const nColumns = eopDescription.data.columnNames.length; const x0 = eopDescription.data.samples[1 * nColumns + 6]; const x1 = eopDescription.data.samples[2 * nColumns + 6]; const x2 = eopDescription.data.samples[3 * nColumns + 6]; const t0 = import__189.JulianDate.fromIso8601(eopDescription.data.samples[nColumns]); const t1 = import__189.JulianDate.fromIso8601( eopDescription.data.samples[2 * nColumns] ); let dt = import__189.JulianDate.secondsDifference(dateSlightlyBefore, t0) / (86400 + 1); const expectedBefore = linearInterp(dt, x0, x1 - 1); const resultBefore = eop.compute(dateSlightlyBefore); expect(resultBefore.ut1MinusUtc).toEqualEpsilon(expectedBefore, 1e-15); const expectedAt = eopDescription.data.samples[2 * nColumns + 6]; const resultAt = eop.compute(dateAtLeapSecond); expect(resultAt.ut1MinusUtc).toEqualEpsilon(expectedAt, 1e-15); dt = import__189.JulianDate.secondsDifference(dateSlightlyAfter, t1) / 86400; const expectedAfter = linearInterp(dt, x1, x2); const resultAfter = eop.compute(dateSlightlyAfter); expect(resultAfter.ut1MinusUtc).toEqualEpsilon(expectedAfter, 1e-15); expect( Math.abs(resultBefore.ut1MinusUtc - resultAfter.ut1MinusUtc) > 0.5 ).toEqual(true); }); }); it("fromUrl loads EOP data", async function() { const eop = await import__189.EarthOrientationParameters.fromUrl( "Data/EarthOrientationParameters/EOP-2011-July.json" ); expect(eop).toBeInstanceOf(import__189.EarthOrientationParameters); const time2 = new import__189.JulianDate(2455745, 43200); const result = eop.compute(time2); expect(result.xPoleWander).not.toEqual(0); expect(result.yPoleWander).not.toEqual(0); expect(result.xPoleOffset).not.toEqual(0); expect(result.yPoleOffset).not.toEqual(0); expect(result.ut1MinusUtc).not.toEqual(0); }); it("fromUrl throws a RuntimeError when loading invalid EOP data", async function() { await expectAsync( import__189.EarthOrientationParameters.fromUrl( "Data/EarthOrientationParameters/EOP-Invalid.json" ) ).toBeRejectedWithError( import__189.RuntimeError, "Error in loaded EOP data: The columnNames property is required." ); }); it("fromUrl throws a RuntimeError when using a missing EOP data file", async function() { await expectAsync( import__189.EarthOrientationParameters.fromUrl( "Data/EarthOrientationParameters/EOP-DoesNotExist.json" ) ).toBeRejectedWithError( import__189.RuntimeError, "An error occurred while retrieving the EOP data from the URL Data/EarthOrientationParameters/EOP-DoesNotExist.json." ); }); }); // packages/engine/Specs/Core/EllipseGeometrySpec.js var import__190 = __toESM(require_Cesium(), 1); var import__191 = __toESM(require_Cesium(), 1); describe("Core/EllipseGeometry", function() { it("throws without a center", function() { expect(function() { return new import__190.EllipseGeometry({ semiMajorAxis: 1, semiMinorAxis: 1 }); }).toThrowDeveloperError(); }); it("throws without a semiMajorAxis", function() { expect(function() { return new import__190.EllipseGeometry({ center: import__190.Cartesian3.fromDegrees(0, 0), semiMinorAxis: 1 }); }).toThrowDeveloperError(); }); it("throws without a semiMinorAxis", function() { expect(function() { return new import__190.EllipseGeometry({ center: import__190.Cartesian3.fromDegrees(0, 0), semiMajorAxis: 1 }); }).toThrowDeveloperError(); }); it("throws with a negative granularity", function() { expect(function() { return new import__190.EllipseGeometry({ center: import__190.Cartesian3.fromDegrees(0, 0), semiMajorAxis: 1, semiMinorAxis: 1, granularity: -1 }); }).toThrowDeveloperError(); }); it("throws when semiMajorAxis is less than the semiMajorAxis", function() { expect(function() { return new import__190.EllipseGeometry({ center: import__190.Cartesian3.fromDegrees(0, 0), semiMajorAxis: 1, semiMinorAxis: 2 }); }).toThrowDeveloperError(); }); it("computes positions", function() { const m = import__190.EllipseGeometry.createGeometry( new import__190.EllipseGeometry({ vertexFormat: import__190.VertexFormat.POSITION_ONLY, ellipsoid: import__190.Ellipsoid.WGS84, center: import__190.Cartesian3.fromDegrees(0, 0), granularity: 0.1, semiMajorAxis: 1, semiMinorAxis: 1 }) ); expect(m.attributes.position.values.length).toEqual(16 * 3); expect(m.indices.length).toEqual(22 * 3); expect(m.boundingSphere.radius).toEqual(1); }); it("compute all vertex attributes", function() { const m = import__190.EllipseGeometry.createGeometry( new import__190.EllipseGeometry({ vertexFormat: import__190.VertexFormat.ALL, ellipsoid: import__190.Ellipsoid.WGS84, center: import__190.Cartesian3.fromDegrees(0, 0), granularity: 0.1, semiMajorAxis: 1, semiMinorAxis: 1 }) ); const numVertices = 16; const numTriangles = 22; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.attributes.st.values.length).toEqual(numVertices * 2); expect(m.attributes.normal.values.length).toEqual(numVertices * 3); expect(m.attributes.tangent.values.length).toEqual(numVertices * 3); expect(m.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("compute texture coordinates with rotation", function() { const m = import__190.EllipseGeometry.createGeometry( new import__190.EllipseGeometry({ vertexFormat: import__190.VertexFormat.POSITION_AND_ST, ellipsoid: import__190.Ellipsoid.WGS84, center: import__190.Cartesian3.fromDegrees(0, 0), granularity: 0.1, semiMajorAxis: 1, semiMinorAxis: 1, stRotation: import__191.Math.PI_OVER_TWO }) ); const positions = m.attributes.position.values; const st = m.attributes.st.values; const length2 = st.length; const numVertices = 16; const numTriangles = 22; expect(positions.length).toEqual(numVertices * 3); expect(length2).toEqual(numVertices * 2); expect(m.indices.length).toEqual(numTriangles * 3); expect(st[length2 - 2]).toEqualEpsilon(0.5, import__191.Math.EPSILON2); expect(st[length2 - 1]).toEqualEpsilon(0, import__191.Math.EPSILON2); }); it("computes positions extruded", function() { const m = import__190.EllipseGeometry.createGeometry( new import__190.EllipseGeometry({ vertexFormat: import__190.VertexFormat.POSITION_ONLY, ellipsoid: import__190.Ellipsoid.WGS84, center: import__190.Cartesian3.fromDegrees(0, 0), granularity: 0.1, semiMajorAxis: 1, semiMinorAxis: 1, extrudedHeight: 5e4 }) ); const numVertices = 48; const numTriangles = 60; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("computes offset attribute", function() { const m = import__190.EllipseGeometry.createGeometry( new import__190.EllipseGeometry({ vertexFormat: import__190.VertexFormat.POSITION_ONLY, ellipsoid: import__190.Ellipsoid.WGS84, center: import__190.Cartesian3.fromDegrees(0, 0), granularity: 0.1, semiMajorAxis: 1, semiMinorAxis: 1, offsetAttribute: import__190.GeometryOffsetAttribute.TOP }) ); const numVertices = 16; expect(m.attributes.position.values.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("computes offset attribute extruded for top vertices", function() { const m = import__190.EllipseGeometry.createGeometry( new import__190.EllipseGeometry({ vertexFormat: import__190.VertexFormat.POSITION_ONLY, ellipsoid: import__190.Ellipsoid.WGS84, center: import__190.Cartesian3.fromDegrees(0, 0), granularity: 0.1, semiMajorAxis: 1, semiMinorAxis: 1, extrudedHeight: 5e4, offsetAttribute: import__190.GeometryOffsetAttribute.TOP }) ); const numVertices = 48; expect(m.attributes.position.values.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(0).fill(1, 0, 16).fill(1, 32, 40); expect(offset).toEqual(expected); }); it("computes offset attribute extruded for all vertices", function() { const m = import__190.EllipseGeometry.createGeometry( new import__190.EllipseGeometry({ vertexFormat: import__190.VertexFormat.POSITION_ONLY, ellipsoid: import__190.Ellipsoid.WGS84, center: import__190.Cartesian3.fromDegrees(0, 0), granularity: 0.1, semiMajorAxis: 1, semiMinorAxis: 1, extrudedHeight: 5e4, offsetAttribute: import__190.GeometryOffsetAttribute.ALL }) ); const numVertices = 48; expect(m.attributes.position.values.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("compute all vertex attributes extruded", function() { const m = import__190.EllipseGeometry.createGeometry( new import__190.EllipseGeometry({ vertexFormat: import__190.VertexFormat.ALL, ellipsoid: import__190.Ellipsoid.WGS84, center: import__190.Cartesian3.fromDegrees(0, 0), granularity: 0.1, semiMajorAxis: 1, semiMinorAxis: 1, extrudedHeight: 5e4 }) ); const numVertices = 48; const numTriangles = 60; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.attributes.st.values.length).toEqual(numVertices * 2); expect(m.attributes.normal.values.length).toEqual(numVertices * 3); expect(m.attributes.tangent.values.length).toEqual(numVertices * 3); expect(m.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("undefined is returned if the minor axis is equal to or less than zero", function() { const ellipse0 = new import__190.EllipseGeometry({ center: import__190.Cartesian3.fromDegrees(-75.59777, 40.03883), semiMajorAxis: 3e5, semiMinorAxis: 0 }); const ellipse1 = new import__190.EllipseGeometry({ center: import__190.Cartesian3.fromDegrees(-75.59777, 40.03883), semiMajorAxis: 0, semiMinorAxis: -1 }); const ellipse2 = new import__190.EllipseGeometry({ center: import__190.Cartesian3.fromDegrees(-75.59777, 40.03883), semiMajorAxis: 3e5, semiMinorAxis: -10 }); const ellipse3 = new import__190.EllipseGeometry({ center: import__190.Cartesian3.fromDegrees(-75.59777, 40.03883), semiMajorAxis: -1, semiMinorAxis: -2 }); const geometry0 = import__190.EllipseGeometry.createGeometry(ellipse0); const geometry1 = import__190.EllipseGeometry.createGeometry(ellipse1); const geometry2 = import__190.EllipseGeometry.createGeometry(ellipse2); const geometry3 = import__190.EllipseGeometry.createGeometry(ellipse3); expect(geometry0).toBeUndefined(); expect(geometry1).toBeUndefined(); expect(geometry2).toBeUndefined(); expect(geometry3).toBeUndefined(); }); it("createShadowVolume uses properties from geometry", function() { const m = new import__190.EllipseGeometry({ center: import__190.Cartesian3.fromDegrees(-75.59777, 40.03883), semiMajorAxis: 3e3, semiMinorAxis: 1500, ellipsoid: import__190.Ellipsoid.WGS84, rotation: import__191.Math.PI_OVER_TWO, stRotation: import__191.Math.PI_OVER_FOUR, granularity: 1e4, extrudedHeight: 0, height: 100, vertexFormat: import__190.VertexFormat.ALL }); const minHeightFunc = function() { return 100; }; const maxHeightFunc = function() { return 1e3; }; const sv = import__190.EllipseGeometry.createShadowVolume( m, minHeightFunc, maxHeightFunc ); expect(sv._center.equals(m._center)).toBe(true); expect(sv._semiMajorAxis).toBe(m._semiMajorAxis); expect(sv._semiMinorAxis).toBe(m._semiMinorAxis); expect(sv._ellipsoid.equals(m._ellipsoid)).toBe(true); expect(sv._rotation).toBe(m._rotation); expect(sv._stRotation).toBe(m._stRotation); expect(sv._granularity).toBe(m._granularity); expect(sv._extrudedHeight).toBe(minHeightFunc()); expect(sv._height).toBe(maxHeightFunc()); expect(sv._vertexFormat.bitangent).toBe( import__190.VertexFormat.POSITION_ONLY.bitangent ); expect(sv._vertexFormat.color).toBe(import__190.VertexFormat.POSITION_ONLY.color); expect(sv._vertexFormat.normal).toBe(import__190.VertexFormat.POSITION_ONLY.normal); expect(sv._vertexFormat.position).toBe(import__190.VertexFormat.POSITION_ONLY.position); expect(sv._vertexFormat.st).toBe(import__190.VertexFormat.POSITION_ONLY.st); expect(sv._vertexFormat.tangent).toBe(import__190.VertexFormat.POSITION_ONLY.tangent); }); it("computing rectangle property", function() { let center2 = import__190.Cartesian3.fromDegrees(-75.59777, 40.03883); let ellipse = new import__190.EllipseGeometry({ center: center2, semiMajorAxis: 2e3, semiMinorAxis: 1e3 }); let r = ellipse.rectangle; expect(r.north).toEqualEpsilon(0.6989665987920752, import__191.Math.EPSILON7); expect(r.south).toEqualEpsilon(0.6986522252554146, import__191.Math.EPSILON7); expect(r.east).toEqualEpsilon(-1.3190209903056758, import__191.Math.EPSILON7); expect(r.west).toEqualEpsilon(-1.3198389970251112, import__191.Math.EPSILON7); center2 = import__190.Cartesian3.fromDegrees(0, 90); ellipse = new import__190.EllipseGeometry({ center: center2, semiMajorAxis: 2e3, semiMinorAxis: 1e3 }); r = ellipse.rectangle; expect(r.north).toEqualEpsilon( import__191.Math.PI_OVER_TWO - import__191.Math.EPSILON7, import__191.Math.EPSILON7 ); expect(r.south).toEqualEpsilon(1.570483806950967, import__191.Math.EPSILON7); expect(r.east).toEqualEpsilon(import__191.Math.PI, import__191.Math.EPSILON7); expect(r.west).toEqualEpsilon(-import__191.Math.PI, import__191.Math.EPSILON7); }); it("computeRectangle", function() { const options = { center: import__190.Cartesian3.fromDegrees(-30, 33), semiMajorAxis: 2e3, semiMinorAxis: 1e3, rotation: import__191.Math.PI_OVER_TWO, granularity: 0.5, ellipsoid: import__190.Ellipsoid.UNIT_SPHERE }; const geometry = new import__190.EllipseGeometry(options); const expected = geometry.rectangle; const result = import__190.EllipseGeometry.computeRectangle(options); expect(result).toEqual(expected); }); it("computeRectangle with result parameter", function() { const options = { center: import__190.Cartesian3.fromDegrees(30, -33), semiMajorAxis: 500, semiMinorAxis: 200 }; const geometry = new import__190.EllipseGeometry(options); const result = new import__190.Rectangle(); const expected = geometry.rectangle; const returned = import__190.EllipseGeometry.computeRectangle(options, result); expect(returned).toEqual(expected); expect(returned).toBe(result); }); it("computing textureCoordinateRotationPoints property", function() { const center2 = import__190.Cartesian3.fromDegrees(0, 0); let ellipse = new import__190.EllipseGeometry({ center: center2, semiMajorAxis: 2e3, semiMinorAxis: 1e3, stRotation: import__191.Math.toRadians(90) }); let textureCoordinateRotationPoints = ellipse.textureCoordinateRotationPoints; expect(textureCoordinateRotationPoints.length).toEqual(6); expect(textureCoordinateRotationPoints[0]).toEqualEpsilon( 0, import__191.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[1]).toEqualEpsilon( 1, import__191.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[2]).toEqualEpsilon( 1, import__191.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[3]).toEqualEpsilon( 1, import__191.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[4]).toEqualEpsilon( 0, import__191.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[5]).toEqualEpsilon( 0, import__191.Math.EPSILON7 ); ellipse = new import__190.EllipseGeometry({ center: center2, semiMajorAxis: 2e3, semiMinorAxis: 1e3, stRotation: import__191.Math.toRadians(0) }); textureCoordinateRotationPoints = ellipse.textureCoordinateRotationPoints; expect(textureCoordinateRotationPoints.length).toEqual(6); expect(textureCoordinateRotationPoints[0]).toEqualEpsilon( 0, import__191.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[1]).toEqualEpsilon( 0, import__191.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[2]).toEqualEpsilon( 0, import__191.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[3]).toEqualEpsilon( 1, import__191.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[4]).toEqualEpsilon( 1, import__191.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[5]).toEqualEpsilon( 0, import__191.Math.EPSILON7 ); }); const center = import__190.Cartesian3.fromDegrees(0, 0); const ellipsoid = import__190.Ellipsoid.WGS84; const packableInstance = new import__190.EllipseGeometry({ vertexFormat: import__190.VertexFormat.POSITION_AND_ST, ellipsoid, center, granularity: 0.1, semiMajorAxis: 1, semiMinorAxis: 1, stRotation: import__191.Math.PI_OVER_TWO }); const packedInstance = [ center.x, center.y, center.z, ellipsoid.radii.x, ellipsoid.radii.y, ellipsoid.radii.z, 1, 0, 1, 0, 0, 0, 1, 1, 0, import__191.Math.PI_OVER_TWO, 0, 0.1, 0, 0, -1 ]; createPackableSpecs_default(import__190.EllipseGeometry, packableInstance, packedInstance); }); // packages/engine/Specs/Core/EllipseOutlineGeometrySpec.js var import__192 = __toESM(require_Cesium(), 1); describe("Core/EllipseOutlineGeometry", function() { it("throws without a center", function() { expect(function() { return new import__192.EllipseOutlineGeometry({ semiMajorAxis: 1, semiMinorAxis: 1 }); }).toThrowDeveloperError(); }); it("throws without a semiMajorAxis", function() { expect(function() { return new import__192.EllipseOutlineGeometry({ center: import__192.Cartesian3.fromDegrees(0, 0), semiMinorAxis: 1 }); }).toThrowDeveloperError(); }); it("throws without a semiMinorAxis", function() { expect(function() { return new import__192.EllipseOutlineGeometry({ center: import__192.Cartesian3.fromDegrees(0, 0), semiMajorAxis: 1 }); }).toThrowDeveloperError(); }); it("throws with a negative granularity", function() { expect(function() { return new import__192.EllipseOutlineGeometry({ center: import__192.Cartesian3.fromDegrees(0, 0), semiMajorAxis: 1, semiMinorAxis: 1, granularity: -1 }); }).toThrowDeveloperError(); }); it("throws when semiMajorAxis is less than the semiMajorAxis", function() { expect(function() { return new import__192.EllipseOutlineGeometry({ center: import__192.Cartesian3.fromDegrees(0, 0), semiMajorAxis: 1, semiMinorAxis: 2 }); }).toThrowDeveloperError(); }); it("computes positions", function() { const m = import__192.EllipseOutlineGeometry.createGeometry( new import__192.EllipseOutlineGeometry({ ellipsoid: import__192.Ellipsoid.WGS84, center: import__192.Cartesian3.fromDegrees(0, 0), granularity: 0.1, semiMajorAxis: 1, semiMinorAxis: 1 }) ); expect(m.attributes.position.values.length).toEqual(8 * 3); expect(m.indices.length).toEqual(8 * 2); expect(m.boundingSphere.radius).toEqual(1); }); it("computes positions extruded", function() { const m = import__192.EllipseOutlineGeometry.createGeometry( new import__192.EllipseOutlineGeometry({ ellipsoid: import__192.Ellipsoid.WGS84, center: import__192.Cartesian3.fromDegrees(0, 0), granularity: 0.1, semiMajorAxis: 1, semiMinorAxis: 1, extrudedHeight: 5 }) ); expect(m.attributes.position.values.length).toEqual(16 * 3); expect(m.indices.length).toEqual(24 * 2); }); it("computes offset attribute", function() { const m = import__192.EllipseOutlineGeometry.createGeometry( new import__192.EllipseOutlineGeometry({ ellipsoid: import__192.Ellipsoid.WGS84, center: import__192.Cartesian3.fromDegrees(0, 0), granularity: 0.1, semiMajorAxis: 1, semiMinorAxis: 1, offsetAttribute: import__192.GeometryOffsetAttribute.TOP }) ); const numVertices = 8; expect(m.attributes.position.values.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("computes offset attribute extruded for top vertices", function() { const m = import__192.EllipseOutlineGeometry.createGeometry( new import__192.EllipseOutlineGeometry({ ellipsoid: import__192.Ellipsoid.WGS84, center: import__192.Cartesian3.fromDegrees(0, 0), granularity: 0.1, semiMajorAxis: 1, semiMinorAxis: 1, extrudedHeight: 5, offsetAttribute: import__192.GeometryOffsetAttribute.TOP }) ); const numVertices = 16; expect(m.attributes.position.values.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(0).fill(1, 0, 8); expect(offset).toEqual(expected); }); it("computes offset attribute extruded for all vertices", function() { const m = import__192.EllipseOutlineGeometry.createGeometry( new import__192.EllipseOutlineGeometry({ ellipsoid: import__192.Ellipsoid.WGS84, center: import__192.Cartesian3.fromDegrees(0, 0), granularity: 0.1, semiMajorAxis: 1, semiMinorAxis: 1, extrudedHeight: 5, offsetAttribute: import__192.GeometryOffsetAttribute.ALL }) ); const numVertices = 16; expect(m.attributes.position.values.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("computes positions extruded, no lines drawn between top and bottom", function() { const m = import__192.EllipseOutlineGeometry.createGeometry( new import__192.EllipseOutlineGeometry({ ellipsoid: import__192.Ellipsoid.WGS84, center: import__192.Cartesian3.fromDegrees(0, 0), granularity: 0.1, semiMajorAxis: 1, semiMinorAxis: 1, extrudedHeight: 5, numberOfVerticalLines: 0 }) ); expect(m.attributes.position.values.length).toEqual(16 * 3); expect(m.indices.length).toEqual(16 * 2); }); it("undefined is returned if the minor axis is equal to or less than zero", function() { const ellipseOutline0 = new import__192.EllipseOutlineGeometry({ center: import__192.Cartesian3.fromDegrees(-75.59777, 40.03883), semiMajorAxis: 3e5, semiMinorAxis: 0 }); const ellipseOutline1 = new import__192.EllipseOutlineGeometry({ center: import__192.Cartesian3.fromDegrees(-75.59777, 40.03883), semiMajorAxis: 0, semiMinorAxis: -1 }); const ellipseOutline2 = new import__192.EllipseOutlineGeometry({ center: import__192.Cartesian3.fromDegrees(-75.59777, 40.03883), semiMajorAxis: 3e5, semiMinorAxis: -10 }); const ellipseOutline3 = new import__192.EllipseOutlineGeometry({ center: import__192.Cartesian3.fromDegrees(-75.59777, 40.03883), semiMajorAxis: -1, semiMinorAxis: -2 }); const geometry0 = import__192.EllipseOutlineGeometry.createGeometry(ellipseOutline0); const geometry1 = import__192.EllipseOutlineGeometry.createGeometry(ellipseOutline1); const geometry2 = import__192.EllipseOutlineGeometry.createGeometry(ellipseOutline2); const geometry3 = import__192.EllipseOutlineGeometry.createGeometry(ellipseOutline3); expect(geometry0).toBeUndefined(); expect(geometry1).toBeUndefined(); expect(geometry2).toBeUndefined(); expect(geometry3).toBeUndefined(); }); const center = new import__192.Cartesian3(8, 9, 10); const ellipsoid = new import__192.Ellipsoid(11, 12, 13); let packableInstance = new import__192.EllipseOutlineGeometry({ ellipsoid, center, granularity: 1, semiMinorAxis: 2, semiMajorAxis: 3, numberOfVerticalLines: 4, height: 5, rotation: 6, extrudedHeight: 7 }); let packedInstance = [ center.x, center.y, center.z, ellipsoid.radii.x, ellipsoid.radii.y, ellipsoid.radii.z, 3, 2, 6, 7, 1, 5, 4, -1 ]; createPackableSpecs_default( import__192.EllipseOutlineGeometry, packableInstance, packedInstance, "extruded" ); packableInstance = new import__192.EllipseOutlineGeometry({ ellipsoid, center, granularity: 1, semiMinorAxis: 2, semiMajorAxis: 3, numberOfVerticalLines: 4, height: 5, rotation: 6 }); packedInstance = [ center.x, center.y, center.z, ellipsoid.radii.x, ellipsoid.radii.y, ellipsoid.radii.z, 3, 2, 6, 5, 1, 5, 4, -1 ]; createPackableSpecs_default( import__192.EllipseOutlineGeometry, packableInstance, packedInstance, "at height" ); }); // packages/engine/Specs/Core/EllipsoidGeodesicSpec.js var import__193 = __toESM(require_Cesium(), 1); var import__194 = __toESM(require_Cesium(), 1); describe("Core/EllipsoidGeodesic", function() { it("throws without start", function() { expect(function() { const elGeo = new import__193.EllipsoidGeodesic(); return elGeo.interpolateUsingSurfaceDistance(0); }).toThrowDeveloperError(); }); it("throws without end", function() { expect(function() { const elGeo = new import__193.EllipsoidGeodesic(new import__193.Cartographic(Math.PI, Math.PI)); return elGeo.interpolateUsingSurfaceDistance(0); }).toThrowDeveloperError(); }); it("throws without unique position", function() { expect(function() { const elGeo = new import__193.EllipsoidGeodesic( new import__193.Cartographic(Math.PI, Math.PI), new import__193.Cartographic(0, Math.PI) ); return elGeo.interpolateUsingSurfaceDistance(0); }).toThrowDeveloperError(); }); it("setEndPoints throws without start", function() { expect(function() { const elGeo = new import__193.EllipsoidGeodesic(); elGeo.setEndPoints(); }).toThrowDeveloperError(); }); it("setEndPoints throws without end", function() { expect(function() { const start = new import__193.Cartographic(import__194.Math.PI_OVER_TWO, 0); const elGeo = new import__193.EllipsoidGeodesic(); elGeo.setEndPoints(start); return elGeo.interpolateUsingSurfaceDistance(0); }).toThrowDeveloperError(); }); it("getSurfaceDistance throws if start or end never defined", function() { expect(function() { const elGeo = new import__193.EllipsoidGeodesic(); return elGeo.surfaceDistance; }).toThrowDeveloperError(); }); it("getStartHeading throws if start or end never defined", function() { expect(function() { const elGeo = new import__193.EllipsoidGeodesic(); return elGeo.startHeading; }).toThrowDeveloperError(); }); it("getEndHeading throws if start or end never defined", function() { expect(function() { const elGeo = new import__193.EllipsoidGeodesic(); return elGeo.endHeading; }).toThrowDeveloperError(); }); it("works with two points", function() { const fifteenDegrees = Math.PI / 12; const start = new import__193.Cartographic(fifteenDegrees, fifteenDegrees); const thirtyDegrees = Math.PI / 6; const end = new import__193.Cartographic(thirtyDegrees, thirtyDegrees); const geodesic = new import__193.EllipsoidGeodesic(start, end); expect(start).toEqual(geodesic.start); expect(end).toEqual(geodesic.end); }); it("sets end points", function() { const start = new import__193.Cartographic(import__194.Math.PI_OVER_TWO, 0); const end = new import__193.Cartographic( import__194.Math.PI_OVER_TWO, import__194.Math.PI_OVER_TWO ); const geodesic = new import__193.EllipsoidGeodesic(); geodesic.setEndPoints(start, end); expect(start).toEqual(geodesic.start); expect(end).toEqual(geodesic.end); }); it("gets start heading", function() { const ellipsoid = new import__193.Ellipsoid(6, 6, 3); const start = new import__193.Cartographic(import__194.Math.PI_OVER_TWO, 0); const end = new import__193.Cartographic(Math.PI, 0); const geodesic = new import__193.EllipsoidGeodesic(start, end, ellipsoid); expect(import__194.Math.PI_OVER_TWO).toEqualEpsilon( geodesic.startHeading, import__194.Math.EPSILON11 ); }); it("gets end heading", function() { const ellipsoid = new import__193.Ellipsoid(6, 6, 3); const start = new import__193.Cartographic(import__194.Math.PI_OVER_TWO, 0); const end = new import__193.Cartographic(Math.PI, 0); const geodesic = new import__193.EllipsoidGeodesic(start, end, ellipsoid); expect(import__194.Math.PI_OVER_TWO).toEqualEpsilon( geodesic.endHeading, import__194.Math.EPSILON11 ); }); it("computes distance at equator", function() { const ellipsoid = new import__193.Ellipsoid(6, 6, 3); const start = new import__193.Cartographic(import__194.Math.PI_OVER_TWO, 0); const end = new import__193.Cartographic(Math.PI, 0); const geodesic = new import__193.EllipsoidGeodesic(start, end, ellipsoid); expect(import__194.Math.PI_OVER_TWO * 6).toEqualEpsilon( geodesic.surfaceDistance, import__194.Math.EPSILON11 ); }); it("computes distance very close to equator", function() { const ellipsoid = new import__193.Ellipsoid(6, 6, 3); const start = new import__193.Cartographic(-import__194.Math.EPSILON10, import__194.Math.EPSILON10); const end = new import__193.Cartographic(+import__194.Math.EPSILON10, import__194.Math.EPSILON10); const geodesic = new import__193.EllipsoidGeodesic(start, end, ellipsoid); expect(geodesic.surfaceDistance).not.toBeNaN(); }); it("computes distance at meridian", function() { const ellipsoid = new import__193.Ellipsoid(6, 6, 6); const fifteenDegrees = Math.PI / 12; const start = new import__193.Cartographic(import__194.Math.PI_OVER_TWO, fifteenDegrees); const fortyfiveDegrees = Math.PI / 4; const end = new import__193.Cartographic(import__194.Math.PI_OVER_TWO, fortyfiveDegrees); const geodesic = new import__193.EllipsoidGeodesic(start, end, ellipsoid); const thirtyDegrees = Math.PI / 6; expect(thirtyDegrees * 6).toEqualEpsilon( geodesic.surfaceDistance, import__194.Math.EPSILON11 ); }); it("computes distance at pole", function() { const ellipsoid = new import__193.Ellipsoid(6, 6, 6); const seventyfiveDegrees = Math.PI / 12 * 5; const fortyfiveDegrees = Math.PI / 4; const start = new import__193.Cartographic(0, -fortyfiveDegrees); const end = new import__193.Cartographic(Math.PI, -seventyfiveDegrees); const geodesic = new import__193.EllipsoidGeodesic(start, end, ellipsoid); const sixtyDegrees = Math.PI / 3; expect(sixtyDegrees * 6).toEqualEpsilon( geodesic.surfaceDistance, import__194.Math.EPSILON11 ); }); it("interpolates start and end points", function() { const fifteenDegrees = Math.PI / 12; const start = new import__193.Cartographic(fifteenDegrees, fifteenDegrees); const thirtyDegrees = Math.PI / 6; const end = new import__193.Cartographic(thirtyDegrees, thirtyDegrees); const geodesic = new import__193.EllipsoidGeodesic(start, end); const distance = geodesic.surfaceDistance; const first = geodesic.interpolateUsingSurfaceDistance(0); const last = geodesic.interpolateUsingSurfaceDistance(distance); expect(start.longitude).toEqualEpsilon( first.longitude, import__194.Math.EPSILON13 ); expect(start.latitude).toEqualEpsilon(first.latitude, import__194.Math.EPSILON13); expect(end.longitude).toEqualEpsilon(last.longitude, import__194.Math.EPSILON13); expect(end.latitude).toEqualEpsilon(last.latitude, import__194.Math.EPSILON13); }); it("interpolates midpoint", function() { const fifteenDegrees = Math.PI / 12; const start = new import__193.Cartographic(fifteenDegrees, 0); const fortyfiveDegrees = Math.PI / 4; const end = new import__193.Cartographic(fortyfiveDegrees, 0); const thirtyDegrees = Math.PI / 6; const expectedMid = new import__193.Cartographic(thirtyDegrees, 0); const geodesic = new import__193.EllipsoidGeodesic(start, end); const distance = import__193.Ellipsoid.WGS84.radii.x * fifteenDegrees; const midpoint = geodesic.interpolateUsingSurfaceDistance(distance); expect(expectedMid.longitude).toEqualEpsilon( midpoint.longitude, import__194.Math.EPSILON13 ); expect(expectedMid.latitude).toEqualEpsilon( midpoint.latitude, import__194.Math.EPSILON13 ); }); it("interpolates start and end points using fraction", function() { const fifteenDegrees = Math.PI / 12; const start = new import__193.Cartographic(fifteenDegrees, fifteenDegrees); const thirtyDegrees = Math.PI / 6; const end = new import__193.Cartographic(thirtyDegrees, thirtyDegrees); const geodesic = new import__193.EllipsoidGeodesic(start, end); const first = geodesic.interpolateUsingFraction(0); const last = geodesic.interpolateUsingFraction(1); expect(start.longitude).toEqualEpsilon( first.longitude, import__194.Math.EPSILON13 ); expect(start.latitude).toEqualEpsilon(first.latitude, import__194.Math.EPSILON13); expect(end.longitude).toEqualEpsilon(last.longitude, import__194.Math.EPSILON13); expect(end.latitude).toEqualEpsilon(last.latitude, import__194.Math.EPSILON13); }); it("interpolates midpoint using fraction", function() { const fifteenDegrees = Math.PI / 12; const start = new import__193.Cartographic(fifteenDegrees, 0); const fortyfiveDegrees = Math.PI / 4; const end = new import__193.Cartographic(fortyfiveDegrees, 0); const thirtyDegrees = Math.PI / 6; const expectedMid = new import__193.Cartographic(thirtyDegrees, 0); const geodesic = new import__193.EllipsoidGeodesic(start, end); const midpoint = geodesic.interpolateUsingFraction(0.5); expect(expectedMid.longitude).toEqualEpsilon( midpoint.longitude, import__194.Math.EPSILON12 ); expect(expectedMid.latitude).toEqualEpsilon( midpoint.latitude, import__194.Math.EPSILON12 ); }); it("interpolates midpoint fraction using result parameter", function() { const fifteenDegrees = Math.PI / 12; const start = new import__193.Cartographic(fifteenDegrees, 0); const fortyfiveDegrees = Math.PI / 4; const end = new import__193.Cartographic(fortyfiveDegrees, 0); const thirtyDegrees = Math.PI / 6; const expectedMid = new import__193.Cartographic(thirtyDegrees, 0); const geodesic = new import__193.EllipsoidGeodesic(start, end); const result = new import__193.Cartographic(); const midpoint = geodesic.interpolateUsingFraction(0.5, result); expect(result).toBe(midpoint); expect(expectedMid.longitude).toEqualEpsilon( result.longitude, import__194.Math.EPSILON12 ); expect(expectedMid.latitude).toEqualEpsilon( result.latitude, import__194.Math.EPSILON12 ); }); it("interpolates midpoint using result parameter", function() { const fifteenDegrees = Math.PI / 12; const start = new import__193.Cartographic(fifteenDegrees, 0); const fortyfiveDegrees = Math.PI / 4; const end = new import__193.Cartographic(fortyfiveDegrees, 0); const thirtyDegrees = Math.PI / 6; const expectedMid = new import__193.Cartographic(thirtyDegrees, 0); const geodesic = new import__193.EllipsoidGeodesic(start, end); const distance = import__193.Ellipsoid.WGS84.radii.x * fifteenDegrees; const result = new import__193.Cartographic(); const midpoint = geodesic.interpolateUsingSurfaceDistance(distance, result); expect(result).toBe(midpoint); expect(expectedMid.longitude).toEqualEpsilon( result.longitude, import__194.Math.EPSILON13 ); expect(expectedMid.latitude).toEqualEpsilon( result.latitude, import__194.Math.EPSILON13 ); }); }); // packages/engine/Specs/Core/EllipsoidGeometrySpec.js var import__195 = __toESM(require_Cesium(), 1); var import__196 = __toESM(require_Cesium(), 1); describe("Core/EllipsoidGeometry", function() { it("constructor rounds floating-point slicePartitions", function() { const m = new import__195.EllipsoidGeometry({ slicePartitions: 3.5, stackPartitions: 3 }); expect(m._slicePartitions).toEqual(4); }); it("constructor rounds floating-point stackPartitions", function() { const m = new import__195.EllipsoidGeometry({ slicePartitions: 3, stackPartitions: 3.5 }); expect(m._stackPartitions).toEqual(4); }); it("constructor throws with invalid slicePartitions", function() { expect(function() { return new import__195.EllipsoidGeometry({ slicePartitions: -1 }); }).toThrowDeveloperError(); }); it("constructor throws with invalid stackPartitions", function() { expect(function() { return new import__195.EllipsoidGeometry({ stackPartitions: -1 }); }).toThrowDeveloperError(); }); it("computes positions", function() { const m = import__195.EllipsoidGeometry.createGeometry( new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, slicePartitions: 3, stackPartitions: 3 }) ); const numVertices = 36; const numTriangles = 18; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); expect(m.boundingSphere.radius).toEqual(1); }); it("computes offset attribute", function() { const m = import__195.EllipsoidGeometry.createGeometry( new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, slicePartitions: 3, stackPartitions: 3, offsetAttribute: import__195.GeometryOffsetAttribute.ALL }) ); const numVertices = 36; expect(m.attributes.position.values.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("compute all vertex attributes", function() { const m = import__195.EllipsoidGeometry.createGeometry( new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.ALL, slicePartitions: 3, stackPartitions: 3 }) ); const numVertices = 36; const numTriangles = 18; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.attributes.st.values.length).toEqual(numVertices * 2); expect(m.attributes.normal.values.length).toEqual(numVertices * 3); expect(m.attributes.tangent.values.length).toEqual(numVertices * 3); expect(m.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("computes attributes for a unit sphere", function() { const m = import__195.EllipsoidGeometry.createGeometry( new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.ALL, slicePartitions: 3, stackPartitions: 3 }) ); const positions = m.attributes.position.values; const normals = m.attributes.normal.values; const tangents = m.attributes.tangent.values; const bitangents = m.attributes.bitangent.values; for (let i = 0; i < positions.length; i += 3) { const position = import__195.Cartesian3.fromArray(positions, i); const normal = import__195.Cartesian3.fromArray(normals, i); const tangent = import__195.Cartesian3.fromArray(tangents, i); const bitangent = import__195.Cartesian3.fromArray(bitangents, i); expect(import__195.Cartesian3.magnitude(position)).toEqualEpsilon( 1, import__196.Math.EPSILON10 ); expect(normal).toEqualEpsilon( import__195.Cartesian3.normalize(position, new import__195.Cartesian3()), import__196.Math.EPSILON7 ); expect(import__195.Cartesian3.dot(import__195.Cartesian3.UNIT_Z, tangent)).not.toBeLessThan(0); expect(bitangent).toEqualEpsilon( import__195.Cartesian3.cross(normal, tangent, new import__195.Cartesian3()), import__196.Math.EPSILON7 ); } }); it("computes positions with inner surface", function() { const m = import__195.EllipsoidGeometry.createGeometry( new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, slicePartitions: 3, stackPartitions: 3, innerRadii: new import__195.Cartesian3(0.5, 0.5, 0.5) }) ); const numVertices = 72; const numTriangles = 36; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); expect(m.boundingSphere.radius).toEqual(1); }); it("computes positions with inner surface and partial clock range", function() { const m = import__195.EllipsoidGeometry.createGeometry( new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, slicePartitions: 4, stackPartitions: 4, innerRadii: new import__195.Cartesian3(0.5, 0.5, 0.5), minimumClock: import__196.Math.toRadians(90), maximumClock: import__196.Math.toRadians(270) }) ); const numVertices = 70; const numTriangles = 48; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); expect(m.boundingSphere.radius).toEqual(1); }); it("computes positions with inner surface and partial clock range and open top", function() { const m = import__195.EllipsoidGeometry.createGeometry( new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, slicePartitions: 4, stackPartitions: 4, innerRadii: new import__195.Cartesian3(0.5, 0.5, 0.5), minimumClock: import__196.Math.toRadians(90), maximumClock: import__196.Math.toRadians(270), minimumCone: import__196.Math.toRadians(30) }) ); const numVertices = 60; const numTriangles = 40; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); expect(m.boundingSphere.radius).toEqual(1); }); it("computes partitions to default to 2 if less than 2", function() { const geometry = new import__195.EllipsoidGeometry({ radii: new import__195.Cartesian3(0.5, 0.5, 0.5) }); geometry._slicePartitions = 0; geometry._stackPartitions = 0; const m = import__195.EllipsoidGeometry.createGeometry(geometry); expect(m.indices.length).toEqual(6); }); it("negates normals on an ellipsoid", function() { let negatedNormals = 0; const m = import__195.EllipsoidGeometry.createGeometry( new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.ALL, radii: new import__195.Cartesian3(1, 1, 1), innerRadii: new import__195.Cartesian3(0.5, 0.5, 0.5), minimumCone: import__196.Math.toRadians(60), maximumCone: import__196.Math.toRadians(140) }) ); const positions = m.attributes.position.values; const normals = m.attributes.normal.values; for (let i = 0; i < positions.length; i += 3) { const normal = import__195.Cartesian3.fromArray(normals, i); if (normal.x < 0 && normal.y < 0 && normal.z < 0) { negatedNormals++; } } expect(negatedNormals).toEqual(496); }); it("computes the unit ellipsoid", function() { const ellipsoid = import__195.EllipsoidGeometry.getUnitEllipsoid(); expect(ellipsoid).toBeDefined(); expect(ellipsoid.boundingSphere.radius).toEqual(1); expect(import__195.EllipsoidGeometry.getUnitEllipsoid()).toBe(ellipsoid); }); it("computes positions with inner surface and partial clock range and open top and bottom", function() { const m = import__195.EllipsoidGeometry.createGeometry( new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, slicePartitions: 4, stackPartitions: 4, innerRadii: new import__195.Cartesian3(0.5, 0.5, 0.5), minimumClock: import__196.Math.toRadians(90), maximumClock: import__196.Math.toRadians(270), minimumCone: import__196.Math.toRadians(30), maximumCone: import__196.Math.toRadians(120) }) ); const numVertices = 50; const numTriangles = 32; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); expect(m.boundingSphere.radius).toEqual(1); }); it("undefined is returned if the x, y, or z radii or innerRadii are equal or less than zero", function() { const ellipsoid0 = new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, radii: new import__195.Cartesian3(0, 5e5, 5e5) }); const ellipsoid1 = new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, radii: new import__195.Cartesian3(1e6, 0, 5e5) }); const ellipsoid2 = new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, radii: new import__195.Cartesian3(1e6, 5e5, 0) }); const ellipsoid3 = new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, radii: new import__195.Cartesian3(-10, 5e5, 5e5) }); const ellipsoid4 = new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, radii: new import__195.Cartesian3(1e6, -10, 5e5) }); const ellipsoid5 = new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, radii: new import__195.Cartesian3(1e6, 5e5, -10) }); const ellipsoid6 = new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, radii: new import__195.Cartesian3(5e5, 5e5, 5e5), innerRadii: new import__195.Cartesian3(0, 1e5, 1e5) }); const ellipsoid7 = new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, radii: new import__195.Cartesian3(5e5, 5e5, 5e5), innerRadii: new import__195.Cartesian3(1e5, 0, 1e5) }); const ellipsoid8 = new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, radii: new import__195.Cartesian3(5e5, 5e5, 5e5), innerRadii: new import__195.Cartesian3(1e5, 1e5, 0) }); const ellipsoid9 = new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, radii: new import__195.Cartesian3(5e5, 5e5, 5e5), innerRadii: new import__195.Cartesian3(-10, 1e5, 1e5) }); const ellipsoid10 = new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, radii: new import__195.Cartesian3(5e5, 5e5, 5e5), innerRadii: new import__195.Cartesian3(1e5, -10, 1e5) }); const ellipsoid11 = new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, radii: new import__195.Cartesian3(5e5, 5e5, 5e5), innerRadii: new import__195.Cartesian3(1e5, 1e5, -10) }); const geometry0 = import__195.EllipsoidGeometry.createGeometry(ellipsoid0); const geometry1 = import__195.EllipsoidGeometry.createGeometry(ellipsoid1); const geometry2 = import__195.EllipsoidGeometry.createGeometry(ellipsoid2); const geometry3 = import__195.EllipsoidGeometry.createGeometry(ellipsoid3); const geometry4 = import__195.EllipsoidGeometry.createGeometry(ellipsoid4); const geometry5 = import__195.EllipsoidGeometry.createGeometry(ellipsoid5); const geometry6 = import__195.EllipsoidGeometry.createGeometry(ellipsoid6); const geometry7 = import__195.EllipsoidGeometry.createGeometry(ellipsoid7); const geometry8 = import__195.EllipsoidGeometry.createGeometry(ellipsoid8); const geometry9 = import__195.EllipsoidGeometry.createGeometry(ellipsoid9); const geometry10 = import__195.EllipsoidGeometry.createGeometry(ellipsoid10); const geometry11 = import__195.EllipsoidGeometry.createGeometry(ellipsoid11); expect(geometry0).toBeUndefined(); expect(geometry1).toBeUndefined(); expect(geometry2).toBeUndefined(); expect(geometry3).toBeUndefined(); expect(geometry4).toBeUndefined(); expect(geometry5).toBeUndefined(); expect(geometry6).toBeUndefined(); expect(geometry7).toBeUndefined(); expect(geometry8).toBeUndefined(); expect(geometry9).toBeUndefined(); expect(geometry10).toBeUndefined(); expect(geometry11).toBeUndefined(); }); const ellipsoidgeometry = new import__195.EllipsoidGeometry({ vertexFormat: import__195.VertexFormat.POSITION_ONLY, radii: new import__195.Cartesian3(1, 2, 3), innerRadii: new import__195.Cartesian3(0.5, 0.6, 0.7), minimumClock: 0.1, maximumClock: 0.2, minimumCone: 0.3, maximumCone: 0.4, slicePartitions: 3, stackPartitions: 3 }); const packedInstance = [ 1, 2, 3, 0.5, 0.6, 0.7, 1, 0, 0, 0, 0, 0, 0.1, 0.2, 0.3, 0.4, 3, 3, -1 ]; createPackableSpecs_default(import__195.EllipsoidGeometry, ellipsoidgeometry, packedInstance); }); // packages/engine/Specs/Core/EllipsoidOutlineGeometrySpec.js var import__197 = __toESM(require_Cesium(), 1); var import__198 = __toESM(require_Cesium(), 1); describe("Core/EllipsoidOutlineGeometry", function() { it("constructor throws if stackPartitions less than 1", function() { expect(function() { return new import__197.EllipsoidOutlineGeometry({ stackPartitions: 0 }); }).toThrowDeveloperError(); }); it("constructor throws if slicePartitions less than 0", function() { expect(function() { return new import__197.EllipsoidOutlineGeometry({ slicePartitions: -1 }); }).toThrowDeveloperError(); }); it("constructor throws if subdivisions less than 0", function() { expect(function() { return new import__197.EllipsoidOutlineGeometry({ subdivisions: -2 }); }).toThrowDeveloperError(); }); it("constructor throws if offset attribute is equal to GeometryOffsetAttribute.TOP", function() { expect(function() { return new import__197.EllipsoidOutlineGeometry({ offsetAttribute: import__197.GeometryOffsetAttribute.TOP }); }).toThrowDeveloperError(); }); it("constructor rounds floating-point slicePartitions", function() { const m = new import__197.EllipsoidOutlineGeometry({ slicePartitions: 3.5, stackPartitions: 3, subdivisions: 3 }); expect(m._slicePartitions).toEqual(4); }); it("constructor rounds floating-point stackPartitions", function() { const m = new import__197.EllipsoidOutlineGeometry({ slicePartitions: 3, stackPartitions: 3.5, subdivisions: 3 }); expect(m._stackPartitions).toEqual(4); }); it("constructor rounds floating-point subdivisions", function() { const m = new import__197.EllipsoidOutlineGeometry({ slicePartitions: 3, stackPartitions: 3, subdivisions: 3.5 }); expect(m._subdivisions).toEqual(4); }); it("computes positions", function() { const m = import__197.EllipsoidOutlineGeometry.createGeometry( new import__197.EllipsoidOutlineGeometry({ stackPartitions: 3, slicePartitions: 3, subdivisions: 3 }) ); expect(m.attributes.position.values.length).toEqual(24 * 3); expect(m.indices.length).toEqual(16 * 2); expect(m.boundingSphere.radius).toEqual(1); }); it("computes positions for partial ellipsoid", function() { const m = import__197.EllipsoidOutlineGeometry.createGeometry( new import__197.EllipsoidOutlineGeometry({ innerRadii: new import__197.Cartesian3(0.5, 0.5, 0.5), minimumClock: import__198.Math.toRadians(90), maximumClock: import__198.Math.toRadians(270), minimumCone: import__198.Math.toRadians(30), maximumCone: import__198.Math.toRadians(120), stackPartitions: 3, slicePartitions: 3, subdivisions: 3 }) ); expect(m.attributes.position.values.length).toEqual(24 * 3); expect(m.indices.length).toEqual(20 * 2); expect(m.boundingSphere.radius).toEqual(1); }); it("computes offset attribute", function() { const m = import__197.EllipsoidOutlineGeometry.createGeometry( new import__197.EllipsoidOutlineGeometry({ stackPartitions: 3, slicePartitions: 3, subdivisions: 3, offsetAttribute: import__197.GeometryOffsetAttribute.ALL }) ); const numVertices = 24; expect(m.attributes.position.values.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("computes partitions to default to 2 if less than 2", function() { const geometry = new import__197.EllipsoidOutlineGeometry({ radii: new import__197.Cartesian3(0.5, 0.5, 0.5) }); geometry._slicePartitions = 0; geometry._stackPartitions = 0; const m = import__197.EllipsoidOutlineGeometry.createGeometry(geometry); expect(m.indices.length).toEqual(1016); }); it("undefined is returned if the x, y, or z radii are equal or less than zero", function() { const ellipsoidOutline0 = new import__197.EllipsoidOutlineGeometry({ radii: new import__197.Cartesian3(0, 5e5, 5e5) }); const ellipsoidOutline1 = new import__197.EllipsoidOutlineGeometry({ radii: new import__197.Cartesian3(1e6, 0, 5e5) }); const ellipsoidOutline2 = new import__197.EllipsoidOutlineGeometry({ radii: new import__197.Cartesian3(1e6, 5e5, 0) }); const ellipsoidOutline3 = new import__197.EllipsoidOutlineGeometry({ radii: new import__197.Cartesian3(-10, 5e5, 5e5) }); const ellipsoidOutline4 = new import__197.EllipsoidOutlineGeometry({ radii: new import__197.Cartesian3(1e6, -10, 5e5) }); const ellipsoidOutline5 = new import__197.EllipsoidOutlineGeometry({ radii: new import__197.Cartesian3(1e6, 5e5, -10) }); const ellipsoidOutline6 = new import__197.EllipsoidOutlineGeometry({ radii: new import__197.Cartesian3(5e5, 5e5, 5e5), innerRadii: new import__197.Cartesian3(0, 1e5, 1e5) }); const ellipsoidOutline7 = new import__197.EllipsoidOutlineGeometry({ radii: new import__197.Cartesian3(5e5, 5e5, 5e5), innerRadii: new import__197.Cartesian3(1e5, 0, 1e5) }); const ellipsoidOutline8 = new import__197.EllipsoidOutlineGeometry({ radii: new import__197.Cartesian3(5e5, 5e5, 5e5), innerRadii: new import__197.Cartesian3(1e5, 1e5, 0) }); const ellipsoidOutline9 = new import__197.EllipsoidOutlineGeometry({ radii: new import__197.Cartesian3(5e5, 5e5, 5e5), innerRadii: new import__197.Cartesian3(-10, 1e5, 1e5) }); const ellipsoidOutline10 = new import__197.EllipsoidOutlineGeometry({ radii: new import__197.Cartesian3(5e5, 5e5, 5e5), innerRadii: new import__197.Cartesian3(1e5, -10, 1e5) }); const ellipsoidOutline11 = new import__197.EllipsoidOutlineGeometry({ radii: new import__197.Cartesian3(5e5, 5e5, 5e5), innerRadii: new import__197.Cartesian3(1e5, 1e5, -10) }); const geometry0 = import__197.EllipsoidOutlineGeometry.createGeometry( ellipsoidOutline0 ); const geometry1 = import__197.EllipsoidOutlineGeometry.createGeometry( ellipsoidOutline1 ); const geometry2 = import__197.EllipsoidOutlineGeometry.createGeometry( ellipsoidOutline2 ); const geometry3 = import__197.EllipsoidOutlineGeometry.createGeometry( ellipsoidOutline3 ); const geometry4 = import__197.EllipsoidOutlineGeometry.createGeometry( ellipsoidOutline4 ); const geometry5 = import__197.EllipsoidOutlineGeometry.createGeometry( ellipsoidOutline5 ); const geometry6 = import__197.EllipsoidOutlineGeometry.createGeometry( ellipsoidOutline6 ); const geometry7 = import__197.EllipsoidOutlineGeometry.createGeometry( ellipsoidOutline7 ); const geometry8 = import__197.EllipsoidOutlineGeometry.createGeometry( ellipsoidOutline8 ); const geometry9 = import__197.EllipsoidOutlineGeometry.createGeometry( ellipsoidOutline9 ); const geometry10 = import__197.EllipsoidOutlineGeometry.createGeometry( ellipsoidOutline10 ); const geometry11 = import__197.EllipsoidOutlineGeometry.createGeometry( ellipsoidOutline11 ); expect(geometry0).toBeUndefined(); expect(geometry1).toBeUndefined(); expect(geometry2).toBeUndefined(); expect(geometry3).toBeUndefined(); expect(geometry4).toBeUndefined(); expect(geometry5).toBeUndefined(); expect(geometry6).toBeUndefined(); expect(geometry7).toBeUndefined(); expect(geometry8).toBeUndefined(); expect(geometry9).toBeUndefined(); expect(geometry10).toBeUndefined(); expect(geometry11).toBeUndefined(); }); const ellipsoidgeometry = new import__197.EllipsoidOutlineGeometry({ radii: new import__197.Cartesian3(1, 2, 3), innerRadii: new import__197.Cartesian3(0.5, 0.6, 0.7), minimumClock: 0.1, maximumClock: 0.2, minimumCone: 0.3, maximumCone: 0.4, slicePartitions: 3, stackPartitions: 3, subdivisions: 3 }); const packedInstance = [ 1, 2, 3, 0.5, 0.6, 0.7, 0.1, 0.2, 0.3, 0.4, 3, 3, 3, -1 ]; createPackableSpecs_default( import__197.EllipsoidOutlineGeometry, ellipsoidgeometry, packedInstance ); }); // packages/engine/Specs/Core/EllipsoidRhumbLineSpec.js var import__199 = __toESM(require_Cesium(), 1); var import__200 = __toESM(require_Cesium(), 1); describe("Core/EllipsoidRhumbLine", function() { const oneDegree = import__200.Math.RADIANS_PER_DEGREE; const fifteenDegrees = Math.PI / 12; const thirtyDegrees = Math.PI / 6; const fortyfiveDegrees = Math.PI / 4; const threeHundredDegrees = 5 * Math.PI / 6; it("throws without start", function() { expect(function() { const rhumb = new import__199.EllipsoidRhumbLine(); return rhumb.interpolateUsingSurfaceDistance(0); }).toThrowDeveloperError(); }); it("throws without end", function() { expect(function() { const rhumb = new import__199.EllipsoidRhumbLine(new import__199.Cartographic(Math.PI, Math.PI)); return rhumb.interpolateUsingSurfaceDistance(0); }).toThrowDeveloperError(); }); it("throws without unique position", function() { expect(function() { const rhumb = new import__199.EllipsoidRhumbLine( new import__199.Cartographic(Math.PI, Math.PI), new import__199.Cartographic(0, Math.PI) ); return rhumb.interpolateUsingSurfaceDistance(0); }).toThrowDeveloperError(); }); it("setEndPoints throws without start", function() { expect(function() { const rhumb = new import__199.EllipsoidRhumbLine(); rhumb.setEndPoints(); }).toThrowDeveloperError(); }); it("setEndPoints throws without end", function() { expect(function() { const start = new import__199.Cartographic(import__200.Math.PI_OVER_TWO, 0); const rhumb = new import__199.EllipsoidRhumbLine(); rhumb.setEndPoints(start); return rhumb.interpolateUsingSurfaceDistance(0); }).toThrowDeveloperError(); }); it("can create using fromStartHeadingDistance function", function() { const ellipsoid = import__199.Ellipsoid.WGS84; const start = new import__199.Cartographic(fifteenDegrees, fifteenDegrees); const heading = fifteenDegrees; const distance = fifteenDegrees * ellipsoid.maximumRadius; const rhumb = import__199.EllipsoidRhumbLine.fromStartHeadingDistance( start, heading, distance, ellipsoid ); expect(start).toEqual(rhumb.start); expect(distance).toEqualEpsilon(rhumb.surfaceDistance, import__200.Math.EPSILON6); expect(heading).toEqualEpsilon(rhumb.heading, import__200.Math.EPSILON12); }); it("can create using fromStartHeadingDistance function with result", function() { const ellipsoid = import__199.Ellipsoid.WGS84; const scratch = new import__199.EllipsoidRhumbLine(void 0, void 0, ellipsoid); const start = new import__199.Cartographic(fifteenDegrees, fifteenDegrees); const heading = fifteenDegrees; const distance = fifteenDegrees * ellipsoid.maximumRadius; const rhumb = import__199.EllipsoidRhumbLine.fromStartHeadingDistance( start, heading, distance, ellipsoid, scratch ); expect(rhumb).toBe(scratch); expect(rhumb.ellipsoid).toBe(ellipsoid); expect(start).toEqual(rhumb.start); expect(distance).toEqualEpsilon(rhumb.surfaceDistance, import__200.Math.EPSILON6); expect(heading).toEqualEpsilon(rhumb.heading, import__200.Math.EPSILON12); }); it("getSurfaceDistance throws if start or end never defined", function() { expect(function() { const rhumb = new import__199.EllipsoidRhumbLine(); return rhumb.surfaceDistance; }).toThrowDeveloperError(); }); it("getHeading throws if start or end never defined", function() { expect(function() { const rhumb = new import__199.EllipsoidRhumbLine(); return rhumb.heading; }).toThrowDeveloperError(); }); it("works with two points", function() { const start = new import__199.Cartographic(fifteenDegrees, fifteenDegrees); const end = new import__199.Cartographic(thirtyDegrees, thirtyDegrees); const rhumb = new import__199.EllipsoidRhumbLine(start, end); expect(start).toEqual(rhumb.start); expect(end).toEqual(rhumb.end); }); it("sets end points", function() { const start = new import__199.Cartographic(import__200.Math.PI_OVER_TWO, 0); const end = new import__199.Cartographic( import__200.Math.PI_OVER_TWO, import__200.Math.PI_OVER_TWO ); const rhumb = new import__199.EllipsoidRhumbLine(); rhumb.setEndPoints(start, end); expect(start).toEqual(rhumb.start); expect(end).toEqual(rhumb.end); }); it("gets heading", function() { const ellipsoid = new import__199.Ellipsoid(6, 6, 3); const start = new import__199.Cartographic(import__200.Math.PI_OVER_TWO, 0); const end = new import__199.Cartographic(Math.PI, 0); const rhumb = new import__199.EllipsoidRhumbLine(start, end, ellipsoid); expect(import__200.Math.PI_OVER_TWO).toEqualEpsilon( rhumb.heading, import__200.Math.EPSILON12 ); }); it("computes heading not going over the pole", function() { const ellipsoid = import__199.Ellipsoid.WGS84; const start = new import__199.Cartographic(0, 1.2); const end = new import__199.Cartographic(Math.PI, 1.5); const rhumb = new import__199.EllipsoidRhumbLine(start, end, ellipsoid); expect(0).not.toEqual(rhumb.heading); }); it("computes heading going over the pole", function() { const ellipsoid = import__199.Ellipsoid.WGS84; const start = new import__199.Cartographic(1.3, import__200.Math.PI_OVER_TWO); const end = new import__199.Cartographic(0, import__200.Math.PI / 2.4); const rhumb = new import__199.EllipsoidRhumbLine(start, end, ellipsoid); expect(0).not.toEqual(rhumb.heading); }); it("heading works when going around the world at constant latitude", function() { const ellipsoid = new import__199.Ellipsoid(6, 6, 6); let start = new import__199.Cartographic(0, 0.3); let end = new import__199.Cartographic(import__200.Math.PI_OVER_TWO, 0.3); const rhumb = new import__199.EllipsoidRhumbLine(start, end, ellipsoid); expect(import__200.Math.PI_OVER_TWO).toEqualEpsilon( rhumb.heading, import__200.Math.EPSILON12 ); start = new import__199.Cartographic(3 * import__200.Math.PI_OVER_TWO, 0.3); end = new import__199.Cartographic(import__200.Math.PI, 0.3); const rhumb2 = new import__199.EllipsoidRhumbLine(start, end, ellipsoid); expect(-import__200.Math.PI_OVER_TWO).toEqualEpsilon( rhumb2.heading, import__200.Math.EPSILON12 ); }); it("computes heading for vertical lines", function() { const ellipsoid = import__199.Ellipsoid.WGS84; const start = new import__199.Cartographic(0, 1.2); const end = new import__199.Cartographic(0, 1.5); const rhumb = new import__199.EllipsoidRhumbLine(start, end, ellipsoid); expect(0).toEqualEpsilon(rhumb.heading, import__200.Math.EPSILON12); const rhumb2 = new import__199.EllipsoidRhumbLine(end, start, ellipsoid); expect(import__200.Math.PI).toEqualEpsilon(rhumb2.heading, import__200.Math.EPSILON12); }); it("computes distance at equator", function() { const ellipsoid = new import__199.Ellipsoid(6, 6, 3); const start = new import__199.Cartographic(-import__200.Math.PI_OVER_FOUR, 0); const end = new import__199.Cartographic(import__200.Math.PI_OVER_FOUR, 0); const rhumb = new import__199.EllipsoidRhumbLine(start, end, ellipsoid); expect(import__200.Math.PI_OVER_TWO * 6).toEqualEpsilon( rhumb.surfaceDistance, import__200.Math.EPSILON12 ); }); it("computes distance at meridian", function() { const ellipsoid = new import__199.Ellipsoid(6, 6, 6); const start = new import__199.Cartographic(import__200.Math.PI_OVER_TWO, fifteenDegrees); const end = new import__199.Cartographic(import__200.Math.PI_OVER_TWO, fortyfiveDegrees); const rhumb = new import__199.EllipsoidRhumbLine(start, end, ellipsoid); expect(thirtyDegrees * 6).toEqualEpsilon( rhumb.surfaceDistance, import__200.Math.EPSILON12 ); }); it("computes equal distance on sphere for 90 degrees arcs along meridian and equator", function() { const ellipsoid = new import__199.Ellipsoid(6, 6, 6); const fortyFiveSouth = new import__199.Cartographic(0, -import__200.Math.PI_OVER_FOUR); const fortyFiveNorth = new import__199.Cartographic(0, import__200.Math.PI_OVER_FOUR); const fortyFiveWest = new import__199.Cartographic(-import__200.Math.PI_OVER_FOUR, 0); const fortyFiveEast = new import__199.Cartographic(import__200.Math.PI_OVER_FOUR, 0); const westEastRhumb = new import__199.EllipsoidRhumbLine( fortyFiveWest, fortyFiveEast, ellipsoid ); const southNorthRhumb = new import__199.EllipsoidRhumbLine( fortyFiveSouth, fortyFiveNorth, ellipsoid ); const eastWestRhumb = new import__199.EllipsoidRhumbLine( fortyFiveEast, fortyFiveWest, ellipsoid ); const northSouthRhumb = new import__199.EllipsoidRhumbLine( fortyFiveNorth, fortyFiveSouth, ellipsoid ); expect(import__200.Math.PI_OVER_TWO * 6).toEqualEpsilon( westEastRhumb.surfaceDistance, import__200.Math.EPSILON12 ); expect(import__200.Math.PI_OVER_TWO * 6).toEqualEpsilon( southNorthRhumb.surfaceDistance, import__200.Math.EPSILON12 ); expect(westEastRhumb.surfaceDistance).toEqualEpsilon( southNorthRhumb.surfaceDistance, import__200.Math.EPSILON12 ); expect(import__200.Math.PI_OVER_TWO * 6).toEqualEpsilon( eastWestRhumb.surfaceDistance, import__200.Math.EPSILON12 ); expect(import__200.Math.PI_OVER_TWO * 6).toEqualEpsilon( northSouthRhumb.surfaceDistance, import__200.Math.EPSILON12 ); expect(eastWestRhumb.surfaceDistance).toEqualEpsilon( northSouthRhumb.surfaceDistance, import__200.Math.EPSILON12 ); }); it("computes distance at same latitude", function() { const ellipsoid = new import__199.Ellipsoid(6, 6, 6); const start = new import__199.Cartographic(0, -fortyfiveDegrees); const end = new import__199.Cartographic(import__200.Math.PI_OVER_TWO, -fortyfiveDegrees); const rhumb = new import__199.EllipsoidRhumbLine(start, end, ellipsoid); const distance = Math.cos(fortyfiveDegrees) * import__200.Math.PI_OVER_TWO * 6; expect(distance).toEqualEpsilon( rhumb.surfaceDistance, import__200.Math.EPSILON12 ); }); it("throws when interpolating rhumb line of zero length", function() { const radius = 6378137; const ellipsoid = new import__199.Ellipsoid(radius, radius, radius); const initial = new import__199.Cartographic(fifteenDegrees, fifteenDegrees); expect(function() { const rhumb = import__199.EllipsoidRhumbLine.fromStartHeadingDistance( initial, fifteenDegrees, 0, ellipsoid ); return rhumb.interpolateUsingSurfaceDistance(0); }).toThrowDeveloperError(); }); it("computes heading and distance given endpoints on sphere ", function() { const radius = 6378137; const ellipsoid = new import__199.Ellipsoid(radius, radius, radius); const initial = new import__199.Cartographic(fifteenDegrees, fifteenDegrees); const distance = radius * fifteenDegrees; const rhumb1 = import__199.EllipsoidRhumbLine.fromStartHeadingDistance( initial, fifteenDegrees, distance, ellipsoid ); const rhumb2 = new import__199.EllipsoidRhumbLine(initial, rhumb1.end, ellipsoid); expect(fifteenDegrees).toEqualEpsilon(rhumb2.heading, import__200.Math.EPSILON12); expect(distance).toEqualEpsilon( rhumb2.surfaceDistance, import__200.Math.EPSILON6 ); }); it("computes heading and distance given endpoints on sphereoid", function() { const ellipsoid = import__199.Ellipsoid.WGS84; const initial = new import__199.Cartographic(fifteenDegrees, fifteenDegrees); const distance = ellipsoid.maximumRadius * fifteenDegrees; const rhumb1 = import__199.EllipsoidRhumbLine.fromStartHeadingDistance( initial, fifteenDegrees, distance, ellipsoid ); const rhumb2 = new import__199.EllipsoidRhumbLine(initial, rhumb1.end, ellipsoid); expect(fifteenDegrees).toEqualEpsilon(rhumb2.heading, import__200.Math.EPSILON12); expect(distance).toEqualEpsilon( rhumb2.surfaceDistance, import__200.Math.EPSILON6 ); }); it("tests sphere close to 90 degrees", function() { const radius = 6378137; const ellipsoid = new import__199.Ellipsoid(radius, radius, radius); const initial = new import__199.Cartographic(fifteenDegrees, fifteenDegrees); const distance = radius * fifteenDegrees; const eightyNineDegrees = 89 * oneDegree; const eightyNinePointNineDegrees = 89.9 * oneDegree; const ninetyDegrees = 90 * oneDegree; const ninetyPointOneDegrees = 90.1 * oneDegree; const ninetyPointZeroTwoDegrees = 90.02 * oneDegree; let rhumb1 = import__199.EllipsoidRhumbLine.fromStartHeadingDistance( initial, eightyNineDegrees, distance, ellipsoid ); let rhumb2 = new import__199.EllipsoidRhumbLine(initial, rhumb1.end, ellipsoid); expect(rhumb1.heading).toEqualEpsilon(rhumb2.heading, import__200.Math.EPSILON12); expect(rhumb1.surfaceDistance).toEqualEpsilon( rhumb2.surfaceDistance, import__200.Math.EPSILON6 ); rhumb1 = import__199.EllipsoidRhumbLine.fromStartHeadingDistance( initial, eightyNinePointNineDegrees, distance, ellipsoid ); rhumb2 = new import__199.EllipsoidRhumbLine(initial, rhumb1.end, ellipsoid); expect(rhumb1.heading).toEqualEpsilon(rhumb2.heading, import__200.Math.EPSILON12); expect(rhumb1.surfaceDistance).toEqualEpsilon( rhumb2.surfaceDistance, import__200.Math.EPSILON6 ); rhumb1 = import__199.EllipsoidRhumbLine.fromStartHeadingDistance( initial, ninetyDegrees, distance, ellipsoid ); rhumb2 = new import__199.EllipsoidRhumbLine(initial, rhumb1.end, ellipsoid); expect(rhumb1.heading).toEqualEpsilon(rhumb2.heading, import__200.Math.EPSILON12); expect(rhumb1.surfaceDistance).toEqualEpsilon( rhumb2.surfaceDistance, import__200.Math.EPSILON6 ); rhumb1 = import__199.EllipsoidRhumbLine.fromStartHeadingDistance( initial, ninetyPointOneDegrees, distance, ellipsoid ); rhumb2 = new import__199.EllipsoidRhumbLine(initial, rhumb1.end, ellipsoid); expect(rhumb1.heading).toEqualEpsilon(rhumb2.heading, import__200.Math.EPSILON12); expect(rhumb1.surfaceDistance).toEqualEpsilon( rhumb2.surfaceDistance, import__200.Math.EPSILON6 ); rhumb1 = import__199.EllipsoidRhumbLine.fromStartHeadingDistance( initial, ninetyPointZeroTwoDegrees, distance, ellipsoid ); rhumb2 = new import__199.EllipsoidRhumbLine(initial, rhumb1.end, ellipsoid); expect(rhumb1.heading).toEqualEpsilon(rhumb2.heading, import__200.Math.EPSILON12); expect(rhumb1.surfaceDistance).toEqualEpsilon( rhumb2.surfaceDistance, import__200.Math.EPSILON6 ); }); it("tests spheroid close to 90 degrees", function() { const ellipsoid = import__199.Ellipsoid.WGS84; const initial = new import__199.Cartographic(fifteenDegrees, fifteenDegrees); const distance = ellipsoid.maximumRadius * fifteenDegrees; const eightyNineDegrees = 89 * oneDegree; const eightyNinePointNineDegrees = 89.9 * oneDegree; const ninetyDegrees = 90 * oneDegree; const ninetyPointOneDegrees = 90.1 * oneDegree; const ninetyPointZeroTwoDegrees = 90.02 * oneDegree; let rhumb1 = import__199.EllipsoidRhumbLine.fromStartHeadingDistance( initial, eightyNineDegrees, distance, ellipsoid ); let rhumb2 = new import__199.EllipsoidRhumbLine(initial, rhumb1.end, ellipsoid); expect(rhumb1.heading).toEqualEpsilon(rhumb2.heading, import__200.Math.EPSILON12); expect(rhumb1.surfaceDistance).toEqualEpsilon( rhumb2.surfaceDistance, import__200.Math.EPSILON6 ); rhumb1 = import__199.EllipsoidRhumbLine.fromStartHeadingDistance( initial, eightyNinePointNineDegrees, distance, ellipsoid ); rhumb2 = new import__199.EllipsoidRhumbLine(initial, rhumb1.end, ellipsoid); expect(rhumb1.heading).toEqualEpsilon(rhumb2.heading, import__200.Math.EPSILON12); expect(rhumb1.surfaceDistance).toEqualEpsilon( rhumb2.surfaceDistance, import__200.Math.EPSILON6 ); rhumb1 = import__199.EllipsoidRhumbLine.fromStartHeadingDistance( initial, ninetyDegrees, distance, ellipsoid ); rhumb2 = new import__199.EllipsoidRhumbLine(initial, rhumb1.end, ellipsoid); expect(rhumb1.heading).toEqualEpsilon(rhumb2.heading, import__200.Math.EPSILON12); expect(rhumb1.surfaceDistance).toEqualEpsilon( rhumb2.surfaceDistance, import__200.Math.EPSILON6 ); rhumb1 = import__199.EllipsoidRhumbLine.fromStartHeadingDistance( initial, ninetyPointOneDegrees, distance, ellipsoid ); rhumb2 = new import__199.EllipsoidRhumbLine(initial, rhumb1.end, ellipsoid); expect(rhumb1.heading).toEqualEpsilon(rhumb2.heading, import__200.Math.EPSILON12); expect(rhumb1.surfaceDistance).toEqualEpsilon( rhumb2.surfaceDistance, import__200.Math.EPSILON6 ); rhumb1 = import__199.EllipsoidRhumbLine.fromStartHeadingDistance( initial, ninetyPointZeroTwoDegrees, distance, ellipsoid ); rhumb2 = new import__199.EllipsoidRhumbLine(initial, rhumb1.end, ellipsoid); expect(rhumb1.heading).toEqualEpsilon(rhumb2.heading, import__200.Math.EPSILON12); expect(rhumb1.surfaceDistance).toEqualEpsilon( rhumb2.surfaceDistance, import__200.Math.EPSILON6 ); }); it("test sphereoid across meridian", function() { const ellipsoid = import__199.Ellipsoid.WGS84; const initial = new import__199.Cartographic(-fifteenDegrees, 0); const final = new import__199.Cartographic(fifteenDegrees, 0); const distance = ellipsoid.maximumRadius * 2 * fifteenDegrees; const rhumb1 = new import__199.EllipsoidRhumbLine(initial, final, ellipsoid); const rhumb2 = import__199.EllipsoidRhumbLine.fromStartHeadingDistance( initial, import__200.Math.PI_OVER_TWO, distance, ellipsoid ); expect(rhumb1.heading).toEqualEpsilon(rhumb2.heading, import__200.Math.EPSILON12); expect(rhumb1.surfaceDistance).toEqualEpsilon( rhumb2.surfaceDistance, import__200.Math.EPSILON6 ); }); it("test across IDL with -PI to PI range of longitude", function() { const ellipsoid = import__199.Ellipsoid.WGS84; const initial = new import__199.Cartographic(-import__200.Math.PI + fifteenDegrees, 0); const final = new import__199.Cartographic(import__200.Math.PI - fifteenDegrees, 0); const distance = ellipsoid.maximumRadius * 2 * fifteenDegrees; const rhumb1 = new import__199.EllipsoidRhumbLine(initial, final, ellipsoid); const rhumb2 = new import__199.EllipsoidRhumbLine.fromStartHeadingDistance( initial, 3 * import__200.Math.PI_OVER_TWO, distance, ellipsoid ); expect(-import__200.Math.PI_OVER_TWO).toEqualEpsilon( rhumb1.heading, import__200.Math.EPSILON12 ); expect(distance).toEqualEpsilon( rhumb1.surfaceDistance, import__200.Math.EPSILON6 ); expect(rhumb1.heading).toEqualEpsilon(rhumb2.heading, import__200.Math.EPSILON12); expect(rhumb1.surfaceDistance).toEqualEpsilon( rhumb2.surfaceDistance, import__200.Math.EPSILON6 ); const rhumb3 = new import__199.EllipsoidRhumbLine(final, initial, ellipsoid); const rhumb4 = new import__199.EllipsoidRhumbLine.fromStartHeadingDistance( final, import__200.Math.PI_OVER_TWO, distance, ellipsoid ); expect(import__200.Math.PI_OVER_TWO).toEqualEpsilon( rhumb3.heading, import__200.Math.EPSILON12 ); expect(distance).toEqualEpsilon( rhumb3.surfaceDistance, import__200.Math.EPSILON6 ); expect(rhumb3.heading).toEqualEpsilon(rhumb4.heading, import__200.Math.EPSILON12); expect(rhumb3.surfaceDistance).toEqualEpsilon( rhumb4.surfaceDistance, import__200.Math.EPSILON6 ); }); it("test across equator", function() { const ellipsoid = import__199.Ellipsoid.WGS84; const initial = new import__199.Cartographic(fifteenDegrees, -oneDegree); const final = new import__199.Cartographic(fifteenDegrees, oneDegree); const rhumb = new import__199.EllipsoidRhumbLine(initial, final, ellipsoid); const geodesic = new import__199.EllipsoidGeodesic(initial, final, ellipsoid); expect(0).toEqualEpsilon(rhumb.heading, import__200.Math.EPSILON12); expect(geodesic.startHeading).toEqualEpsilon( rhumb.heading, import__200.Math.EPSILON12 ); expect(geodesic.surfaceDistance).toEqualEpsilon( rhumb.surfaceDistance, import__200.Math.EPSILON6 ); }); it("test on equator", function() { const ellipsoid = import__199.Ellipsoid.WGS84; const initial = new import__199.Cartographic(0, 0); const final = new import__199.Cartographic(import__200.Math.PI - 1, 0); const rhumb = new import__199.EllipsoidRhumbLine(initial, final, ellipsoid); const geodesic = new import__199.EllipsoidGeodesic(initial, final, ellipsoid); expect(import__200.Math.PI_OVER_TWO).toEqualEpsilon( rhumb.heading, import__200.Math.EPSILON12 ); expect(geodesic.startHeading).toEqualEpsilon( rhumb.heading, import__200.Math.EPSILON12 ); expect(geodesic.surfaceDistance).toEqualEpsilon( rhumb.surfaceDistance, import__200.Math.EPSILON4 ); }); it("test close to poles", function() { const ellipsoid = import__199.Ellipsoid.WGS84; const fiveDegrees = import__200.Math.PI / 36; const eightyDegrees = 16 * fiveDegrees; const distance = fifteenDegrees * ellipsoid.maximumRadius; const initial = new import__199.Cartographic(0, eightyDegrees); const rhumb1 = import__199.EllipsoidRhumbLine.fromStartHeadingDistance( initial, eightyDegrees, distance, ellipsoid ); const rhumb2 = new import__199.EllipsoidRhumbLine(initial, rhumb1.end, ellipsoid); expect(rhumb1.heading).toEqualEpsilon(rhumb2.heading, import__200.Math.EPSILON12); expect(rhumb1.surfaceDistance).toEqualEpsilon( rhumb2.surfaceDistance, import__200.Math.EPSILON6 ); }); it("test interpolate fraction", function() { const ellipsoid = import__199.Ellipsoid.WGS84; const initial = new import__199.Cartographic(0, 0); const final = new import__199.Cartographic(import__200.Math.PI_OVER_TWO, 0); const halfway = new import__199.Cartographic(import__200.Math.PI_OVER_FOUR, 0); const rhumb = new import__199.EllipsoidRhumbLine(initial, final, ellipsoid); const interpolatedPoint = rhumb.interpolateUsingFraction(0.5); expect(halfway.longitude).toEqualEpsilon( interpolatedPoint.longitude, import__200.Math.EPSILON12 ); expect(halfway.latitude).toEqualEpsilon( interpolatedPoint.latitude, import__200.Math.EPSILON12 ); }); it("test interpolate distance", function() { const ellipsoid = import__199.Ellipsoid.WGS84; const initial = new import__199.Cartographic(0, 0); const final = new import__199.Cartographic(import__200.Math.PI_OVER_TWO, 0); const halfway = new import__199.Cartographic(import__200.Math.PI_OVER_FOUR, 0); const distance = ellipsoid.maximumRadius * import__200.Math.PI_OVER_FOUR; const rhumb = new import__199.EllipsoidRhumbLine(initial, final, ellipsoid); const interpolatedPoint = rhumb.interpolateUsingSurfaceDistance(distance); expect(halfway.longitude).toEqualEpsilon( interpolatedPoint.longitude, import__200.Math.EPSILON12 ); expect(halfway.latitude).toEqualEpsilon( interpolatedPoint.latitude, import__200.Math.EPSILON12 ); }); it("interpolates start and end points", function() { const start = new import__199.Cartographic(fifteenDegrees, fifteenDegrees); const end = new import__199.Cartographic(thirtyDegrees, thirtyDegrees); const rhumb = new import__199.EllipsoidRhumbLine(start, end); const distance = rhumb.surfaceDistance; const first = rhumb.interpolateUsingSurfaceDistance(0); const last = rhumb.interpolateUsingSurfaceDistance(distance); expect(start.longitude).toEqualEpsilon( first.longitude, import__200.Math.EPSILON12 ); expect(start.latitude).toEqualEpsilon(first.latitude, import__200.Math.EPSILON12); expect(end.longitude).toEqualEpsilon(last.longitude, import__200.Math.EPSILON12); expect(end.latitude).toEqualEpsilon(last.latitude, import__200.Math.EPSILON12); }); it("interpolates midpoint", function() { const start = new import__199.Cartographic(fifteenDegrees, 0); const end = new import__199.Cartographic(fortyfiveDegrees, 0); const expectedMid = new import__199.Cartographic(thirtyDegrees, 0); const rhumb = new import__199.EllipsoidRhumbLine(start, end); const distance = import__199.Ellipsoid.WGS84.radii.x * fifteenDegrees; const midpoint = rhumb.interpolateUsingSurfaceDistance(distance); expect(expectedMid.longitude).toEqualEpsilon( midpoint.longitude, import__200.Math.EPSILON12 ); expect(expectedMid.latitude).toEqualEpsilon( midpoint.latitude, import__200.Math.EPSILON12 ); }); it("interpolates start and end points using fraction", function() { const start = new import__199.Cartographic(fifteenDegrees, fifteenDegrees); const end = new import__199.Cartographic(thirtyDegrees, thirtyDegrees); const rhumb = new import__199.EllipsoidRhumbLine(start, end); const first = rhumb.interpolateUsingFraction(0); const last = rhumb.interpolateUsingFraction(1); expect(start.longitude).toEqualEpsilon( first.longitude, import__200.Math.EPSILON12 ); expect(start.latitude).toEqualEpsilon(first.latitude, import__200.Math.EPSILON12); expect(end.longitude).toEqualEpsilon(last.longitude, import__200.Math.EPSILON12); expect(end.latitude).toEqualEpsilon(last.latitude, import__200.Math.EPSILON12); }); it("interpolates midpoint using fraction", function() { const start = new import__199.Cartographic(fifteenDegrees, 0); const end = new import__199.Cartographic(fortyfiveDegrees, 0); const expectedMid = new import__199.Cartographic(thirtyDegrees, 0); const rhumb = new import__199.EllipsoidRhumbLine(start, end); const midpoint = rhumb.interpolateUsingFraction(0.5); expect(expectedMid.longitude).toEqualEpsilon( midpoint.longitude, import__200.Math.EPSILON12 ); expect(expectedMid.latitude).toEqualEpsilon( midpoint.latitude, import__200.Math.EPSILON12 ); }); it("interpolates when heading is near 90 degrees", function() { const start = new import__199.Cartographic(0, 0); const end = new import__199.Cartographic(Math.PI / 2, 0); const expectedMid = new import__199.Cartographic(fortyfiveDegrees, 0); const rhumb = new import__199.EllipsoidRhumbLine(start, end); expect(rhumb.heading).toEqualEpsilon(Math.PI / 2, import__200.Math.EPSILON12); const midpoint = rhumb.interpolateUsingFraction(0.5); expect(expectedMid.longitude).toEqualEpsilon( midpoint.longitude, import__200.Math.EPSILON12 ); expect(expectedMid.latitude).toEqualEpsilon( midpoint.latitude, import__200.Math.EPSILON12 ); }); it("interpolates when heading is near 0 degrees", function() { const start = new import__199.Cartographic(-threeHundredDegrees, fifteenDegrees); const end = new import__199.Cartographic(-threeHundredDegrees, fortyfiveDegrees); const expectedMid = new import__199.Cartographic(-threeHundredDegrees, thirtyDegrees); const rhumb = new import__199.EllipsoidRhumbLine(start, end); expect(rhumb.heading).toEqualEpsilon(0, import__200.Math.EPSILON12); const midpoint = rhumb.interpolateUsingFraction(0.5); expect(expectedMid.longitude).toEqualEpsilon( midpoint.longitude, import__200.Math.EPSILON12 ); expect(expectedMid.latitude).toEqualEpsilon( midpoint.latitude, import__200.Math.EPSILON3 ); }); it("interpolates midpoint fraction using result parameter", function() { const start = new import__199.Cartographic(fifteenDegrees, 0); const end = new import__199.Cartographic(fortyfiveDegrees, 0); const expectedMid = new import__199.Cartographic(thirtyDegrees, 0); const rhumb = new import__199.EllipsoidRhumbLine(start, end); const result = new import__199.Cartographic(); const midpoint = rhumb.interpolateUsingFraction(0.5, result); expect(result).toBe(midpoint); expect(expectedMid.longitude).toEqualEpsilon( result.longitude, import__200.Math.EPSILON12 ); expect(expectedMid.latitude).toEqualEpsilon( result.latitude, import__200.Math.EPSILON12 ); }); it("interpolates midpoint using result parameter", function() { const start = new import__199.Cartographic(fifteenDegrees, 0); const end = new import__199.Cartographic(fortyfiveDegrees, 0); const expectedMid = new import__199.Cartographic(thirtyDegrees, 0); const rhumb = new import__199.EllipsoidRhumbLine(start, end); const distance = import__199.Ellipsoid.WGS84.radii.x * fifteenDegrees; const result = new import__199.Cartographic(); const midpoint = rhumb.interpolateUsingSurfaceDistance(distance, result); expect(result).toBe(midpoint); expect(expectedMid.longitude).toEqualEpsilon( result.longitude, import__200.Math.EPSILON12 ); expect(expectedMid.latitude).toEqualEpsilon( result.latitude, import__200.Math.EPSILON12 ); }); it("finds midpoint and other points using intersection with longitude", function() { const start = new import__199.Cartographic(fifteenDegrees, 0); const end = new import__199.Cartographic(fortyfiveDegrees, thirtyDegrees); const rhumb = new import__199.EllipsoidRhumbLine(start, end); const midpointUsingInterpolation = rhumb.interpolateUsingFraction(0.5); const midpointUsingIntersection = rhumb.findIntersectionWithLongitude( midpointUsingInterpolation.longitude ); expect( import__199.Cartographic.equalsEpsilon( midpointUsingInterpolation, midpointUsingIntersection, import__200.Math.EPSILON12 ) ).toBe(true); let pointUsingInterpolation = rhumb.interpolateUsingFraction(0.1); let pointUsingIntersection = rhumb.findIntersectionWithLongitude( pointUsingInterpolation.longitude ); expect( import__199.Cartographic.equalsEpsilon( pointUsingInterpolation, pointUsingIntersection, import__200.Math.EPSILON12 ) ).toBe(true); pointUsingInterpolation = rhumb.interpolateUsingFraction(0.75); pointUsingIntersection = rhumb.findIntersectionWithLongitude( pointUsingInterpolation.longitude ); expect( import__199.Cartographic.equalsEpsilon( pointUsingInterpolation, pointUsingIntersection, import__200.Math.EPSILON12 ) ).toBe(true); pointUsingInterpolation = rhumb.interpolateUsingFraction(1.1); pointUsingIntersection = rhumb.findIntersectionWithLongitude( pointUsingInterpolation.longitude ); expect( import__199.Cartographic.equalsEpsilon( pointUsingInterpolation, pointUsingIntersection, import__200.Math.EPSILON12 ) ).toBe(true); }); it("finds correct intersection with IDL", function() { const start = import__199.Cartographic.fromDegrees(170, 10); const end = import__199.Cartographic.fromDegrees(-170, 23); const rhumb = new import__199.EllipsoidRhumbLine(start, end); let idlIntersection1 = rhumb.findIntersectionWithLongitude(-Math.PI); let idlIntersection2 = rhumb.findIntersectionWithLongitude(Math.PI); expect( import__199.Cartographic.equalsEpsilon( idlIntersection1, idlIntersection2, import__200.Math.EPSILON12 ) ).toBe(true); expect(idlIntersection1.longitude).toEqualEpsilon( Math.PI, import__200.Math.EPSILON14 ); expect(idlIntersection2.longitude).toEqualEpsilon( Math.PI, import__200.Math.EPSILON14 ); rhumb.setEndPoints(end, start); idlIntersection1 = rhumb.findIntersectionWithLongitude(-Math.PI); idlIntersection2 = rhumb.findIntersectionWithLongitude(Math.PI); expect( import__199.Cartographic.equalsEpsilon( idlIntersection1, idlIntersection2, import__200.Math.EPSILON12 ) ).toBe(true); expect(idlIntersection1.longitude).toEqualEpsilon( -Math.PI, import__200.Math.EPSILON14 ); expect(idlIntersection2.longitude).toEqualEpsilon( -Math.PI, import__200.Math.EPSILON14 ); }); it("intersection with longitude handles E-W lines", function() { const start = new import__199.Cartographic(fifteenDegrees, 0); const end = new import__199.Cartographic(fortyfiveDegrees, 0); const rhumb = new import__199.EllipsoidRhumbLine(start, end); const midpointUsingInterpolation = rhumb.interpolateUsingFraction(0.5); const midpointUsingIntersection = rhumb.findIntersectionWithLongitude( midpointUsingInterpolation.longitude ); expect( import__199.Cartographic.equalsEpsilon( midpointUsingInterpolation, midpointUsingIntersection, import__200.Math.EPSILON12 ) ).toBe(true); }); it("intersection with longitude handles N-S lines", function() { const start = new import__199.Cartographic(fifteenDegrees, 0); const end = new import__199.Cartographic(fifteenDegrees, thirtyDegrees); const rhumb = new import__199.EllipsoidRhumbLine(start, end); const midpointUsingInterpolation = rhumb.interpolateUsingFraction(0.5); const midpointUsingIntersection = rhumb.findIntersectionWithLongitude( midpointUsingInterpolation.longitude ); expect(midpointUsingIntersection).not.toBeDefined(); }); it("intersection with longitude handles N-S lines with different longitude", function() { const start = new import__199.Cartographic(fifteenDegrees, 0); const end = new import__199.Cartographic(fifteenDegrees, thirtyDegrees); const rhumb = new import__199.EllipsoidRhumbLine(start, end); const midpointUsingIntersection = rhumb.findIntersectionWithLongitude( thirtyDegrees ); expect(midpointUsingIntersection.latitude).toEqualEpsilon( import__200.Math.PI_OVER_TWO, import__200.Math.EPSILON12 ); }); it("finds midpoint and other points using intersection with latitude", function() { const start = new import__199.Cartographic(fifteenDegrees, 0); const end = new import__199.Cartographic(fortyfiveDegrees, thirtyDegrees); const rhumb = new import__199.EllipsoidRhumbLine(start, end); const midpointUsingInterpolation = rhumb.interpolateUsingFraction(0.5); const midpointUsingIntersection = rhumb.findIntersectionWithLatitude( midpointUsingInterpolation.latitude ); expect( import__199.Cartographic.equalsEpsilon( midpointUsingInterpolation, midpointUsingIntersection, import__200.Math.EPSILON12 ) ).toBe(true); let pointUsingInterpolation = rhumb.interpolateUsingFraction(0.1); let pointUsingIntersection = rhumb.findIntersectionWithLatitude( pointUsingInterpolation.latitude ); expect( import__199.Cartographic.equalsEpsilon( pointUsingInterpolation, pointUsingIntersection, import__200.Math.EPSILON12 ) ).toBe(true); pointUsingInterpolation = rhumb.interpolateUsingFraction(0.75); pointUsingIntersection = rhumb.findIntersectionWithLatitude( pointUsingInterpolation.latitude ); expect( import__199.Cartographic.equalsEpsilon( pointUsingInterpolation, pointUsingIntersection, import__200.Math.EPSILON12 ) ).toBe(true); pointUsingInterpolation = rhumb.interpolateUsingFraction(1.1); pointUsingIntersection = rhumb.findIntersectionWithLatitude( pointUsingInterpolation.latitude ); expect( import__199.Cartographic.equalsEpsilon( pointUsingInterpolation, pointUsingIntersection, import__200.Math.EPSILON12 ) ).toBe(true); }); it("intersection with latitude handles E-W lines", function() { const start = new import__199.Cartographic(fifteenDegrees, 0); const end = new import__199.Cartographic(fortyfiveDegrees, 0); const rhumb = new import__199.EllipsoidRhumbLine(start, end); const midpointUsingInterpolation = rhumb.interpolateUsingFraction(0.5); const midpointUsingIntersection = rhumb.findIntersectionWithLatitude( midpointUsingInterpolation.latitude ); expect(midpointUsingIntersection).not.toBeDefined(); }); it("intersection with latitude handles N-S lines", function() { const start = new import__199.Cartographic(fifteenDegrees, 0); const end = new import__199.Cartographic(fifteenDegrees, thirtyDegrees); const rhumb = new import__199.EllipsoidRhumbLine(start, end); const midpointUsingInterpolation = rhumb.interpolateUsingFraction(0.5); const midpointUsingIntersection = rhumb.findIntersectionWithLatitude( midpointUsingInterpolation.latitude ); expect( import__199.Cartographic.equalsEpsilon( midpointUsingInterpolation, midpointUsingIntersection, import__200.Math.EPSILON12 ) ).toBe(true); }); it("returns the start point when interpolating at surface distance 0.0", function() { const p0 = new import__199.Cartesian3( 899411.2767873341, -5079219747324299e-9, 3738850924729517e-9 ); const p1 = new import__199.Cartesian3( 899411.0994891181, -5079219778719673e-9, 3.7388509247295167e6 ); const ellipsoid = import__199.Ellipsoid.WGS84; const c0 = ellipsoid.cartesianToCartographic(p0, new import__199.Cartographic()); const c1 = ellipsoid.cartesianToCartographic(p1, new import__199.Cartographic()); const rhumb = new import__199.EllipsoidRhumbLine(c0, c1, ellipsoid); const c = rhumb.interpolateUsingSurfaceDistance(0, new import__199.Cartographic()); const p = ellipsoid.cartographicToCartesian(c, new import__199.Cartesian3()); expect(p).toEqualEpsilon(p0, import__200.Math.EPSILON7); }); }); // packages/engine/Specs/Core/EllipsoidSpec.js var import__201 = __toESM(require_Cesium(), 1); describe("Core/Ellipsoid", function() { const radii = new import__201.Cartesian3(1, 2, 3); const radiiSquared = import__201.Cartesian3.multiplyComponents( radii, radii, new import__201.Cartesian3() ); const radiiToTheFourth = import__201.Cartesian3.multiplyComponents( radiiSquared, radiiSquared, new import__201.Cartesian3() ); const oneOverRadii = new import__201.Cartesian3(1 / radii.x, 1 / radii.y, 1 / radii.z); const oneOverRadiiSquared = new import__201.Cartesian3( 1 / radiiSquared.x, 1 / radiiSquared.y, 1 / radiiSquared.z ); const minimumRadius = 1; const maximumRadius = 3; const spaceCartesian = new import__201.Cartesian3( 4582719882730089e-9, -4582719882730088e-9, 1.7255104250797231e6 ); const spaceCartesianGeodeticSurfaceNormal = new import__201.Cartesian3( 0.6829975339864266, -0.6829975339864265, 0.25889908678270795 ); const spaceCartographic = new import__201.Cartographic( import__201.Math.toRadians(-45), import__201.Math.toRadians(15), 33e4 ); const spaceCartographicGeodeticSurfaceNormal = new import__201.Cartesian3( 0.6830127018922194, -0.6830127018922193, 0.25881904510252074 ); const surfaceCartesian = new import__201.Cartesian3( 4.0943277921465295e6, 1909216404474774e-9, 4487348408865919e-9 ); const surfaceCartographic = new import__201.Cartographic( import__201.Math.toRadians(25), import__201.Math.toRadians(45), 0 ); it("default constructor creates zero Ellipsoid", function() { const ellipsoid = new import__201.Ellipsoid(); expect(ellipsoid.radii).toEqual(import__201.Cartesian3.ZERO); expect(ellipsoid.radiiSquared).toEqual(import__201.Cartesian3.ZERO); expect(ellipsoid.radiiToTheFourth).toEqual(import__201.Cartesian3.ZERO); expect(ellipsoid.oneOverRadii).toEqual(import__201.Cartesian3.ZERO); expect(ellipsoid.oneOverRadiiSquared).toEqual(import__201.Cartesian3.ZERO); expect(ellipsoid.minimumRadius).toEqual(0); expect(ellipsoid.maximumRadius).toEqual(0); }); it("fromCartesian3 creates zero Ellipsoid with no parameters", function() { const ellipsoid = import__201.Ellipsoid.fromCartesian3(); expect(ellipsoid.radii).toEqual(import__201.Cartesian3.ZERO); expect(ellipsoid.radiiSquared).toEqual(import__201.Cartesian3.ZERO); expect(ellipsoid.radiiToTheFourth).toEqual(import__201.Cartesian3.ZERO); expect(ellipsoid.oneOverRadii).toEqual(import__201.Cartesian3.ZERO); expect(ellipsoid.oneOverRadiiSquared).toEqual(import__201.Cartesian3.ZERO); expect(ellipsoid.minimumRadius).toEqual(0); expect(ellipsoid.maximumRadius).toEqual(0); }); it("constructor computes correct values", function() { const ellipsoid = new import__201.Ellipsoid(radii.x, radii.y, radii.z); expect(ellipsoid.radii).toEqual(radii); expect(ellipsoid.radiiSquared).toEqual(radiiSquared); expect(ellipsoid.radiiToTheFourth).toEqual(radiiToTheFourth); expect(ellipsoid.oneOverRadii).toEqual(oneOverRadii); expect(ellipsoid.oneOverRadiiSquared).toEqual(oneOverRadiiSquared); expect(ellipsoid.minimumRadius).toEqual(minimumRadius); expect(ellipsoid.maximumRadius).toEqual(maximumRadius); }); it("fromCartesian3 computes correct values", function() { const ellipsoid = import__201.Ellipsoid.fromCartesian3(radii); expect(ellipsoid.radii).toEqual(radii); expect(ellipsoid.radiiSquared).toEqual(radiiSquared); expect(ellipsoid.radiiToTheFourth).toEqual(radiiToTheFourth); expect(ellipsoid.oneOverRadii).toEqual(oneOverRadii); expect(ellipsoid.oneOverRadiiSquared).toEqual(oneOverRadiiSquared); expect(ellipsoid.minimumRadius).toEqual(minimumRadius); expect(ellipsoid.maximumRadius).toEqual(maximumRadius); }); it("geodeticSurfaceNormalCartographic works without a result parameter", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const returnedResult = ellipsoid.geodeticSurfaceNormalCartographic( spaceCartographic ); expect(returnedResult).toEqualEpsilon( spaceCartographicGeodeticSurfaceNormal, import__201.Math.EPSILON15 ); }); it("geodeticSurfaceNormalCartographic works with a result parameter", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const result = new import__201.Cartesian3(); const returnedResult = ellipsoid.geodeticSurfaceNormalCartographic( spaceCartographic, result ); expect(returnedResult).toBe(result); expect(returnedResult).toEqualEpsilon( spaceCartographicGeodeticSurfaceNormal, import__201.Math.EPSILON15 ); }); it("geodeticSurfaceNormal works without a result parameter", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const returnedResult = ellipsoid.geodeticSurfaceNormal(spaceCartesian); expect(returnedResult).toEqualEpsilon( spaceCartesianGeodeticSurfaceNormal, import__201.Math.EPSILON15 ); }); it("geodeticSurfaceNormal returns undefined when given the origin", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const returnedResult = ellipsoid.geodeticSurfaceNormal(import__201.Cartesian3.ZERO); expect(returnedResult).toBeUndefined(); }); it("geodeticSurfaceNormal works with a result parameter", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const result = new import__201.Cartesian3(); const returnedResult = ellipsoid.geodeticSurfaceNormal( spaceCartesian, result ); expect(returnedResult).toBe(result); expect(returnedResult).toEqualEpsilon( spaceCartesianGeodeticSurfaceNormal, import__201.Math.EPSILON15 ); }); it("cartographicToCartesian works without a result parameter", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const returnedResult = ellipsoid.cartographicToCartesian(spaceCartographic); expect(returnedResult).toEqualEpsilon(spaceCartesian, import__201.Math.EPSILON7); }); it("cartographicToCartesian works with a result parameter", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const result = new import__201.Cartesian3(); const returnedResult = ellipsoid.cartographicToCartesian( spaceCartographic, result ); expect(result).toBe(returnedResult); expect(returnedResult).toEqualEpsilon(spaceCartesian, import__201.Math.EPSILON7); }); it("cartographicArrayToCartesianArray works without a result parameter", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const returnedResult = ellipsoid.cartographicArrayToCartesianArray([ spaceCartographic, surfaceCartographic ]); expect(returnedResult.length).toEqual(2); expect(returnedResult[0]).toEqualEpsilon( spaceCartesian, import__201.Math.EPSILON7 ); expect(returnedResult[1]).toEqualEpsilon( surfaceCartesian, import__201.Math.EPSILON7 ); }); it("cartographicArrayToCartesianArray works with a result parameter", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const resultCartesian = new import__201.Cartesian3(); const result = [resultCartesian]; const returnedResult = ellipsoid.cartographicArrayToCartesianArray( [spaceCartographic, surfaceCartographic], result ); expect(result).toBe(returnedResult); expect(result[0]).toBe(resultCartesian); expect(returnedResult.length).toEqual(2); expect(returnedResult[0]).toEqualEpsilon( spaceCartesian, import__201.Math.EPSILON7 ); expect(returnedResult[1]).toEqualEpsilon( surfaceCartesian, import__201.Math.EPSILON7 ); }); it("cartesianToCartographic works without a result parameter", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const returnedResult = ellipsoid.cartesianToCartographic(surfaceCartesian); expect(returnedResult).toEqualEpsilon( surfaceCartographic, import__201.Math.EPSILON8 ); }); it("cartesianToCartographic works with a result parameter", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const result = new import__201.Cartographic(); const returnedResult = ellipsoid.cartesianToCartographic( surfaceCartesian, result ); expect(result).toBe(returnedResult); expect(returnedResult).toEqualEpsilon( surfaceCartographic, import__201.Math.EPSILON8 ); }); it("cartesianToCartographic works close to center", function() { const expected = new import__201.Cartographic( 9999999999999999e-26, 10067394967422763e-36, -6378137 ); const returnedResult = import__201.Ellipsoid.WGS84.cartesianToCartographic( new import__201.Cartesian3(1e-50, 1e-60, 1e-70) ); expect(returnedResult).toEqual(expected); }); it("cartesianToCartographic return undefined very close to center", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const returnedResult = ellipsoid.cartesianToCartographic( new import__201.Cartesian3(1e-150, 1e-150, 1e-150) ); expect(returnedResult).toBeUndefined(); }); it("cartesianToCartographic return undefined at center", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const returnedResult = ellipsoid.cartesianToCartographic(import__201.Cartesian3.ZERO); expect(returnedResult).toBeUndefined(); }); it("cartesianArrayToCartographicArray works without a result parameter", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const returnedResult = ellipsoid.cartesianArrayToCartographicArray([ spaceCartesian, surfaceCartesian ]); expect(returnedResult.length).toEqual(2); expect(returnedResult[0]).toEqualEpsilon( spaceCartographic, import__201.Math.EPSILON7 ); expect(returnedResult[1]).toEqualEpsilon( surfaceCartographic, import__201.Math.EPSILON7 ); }); it("cartesianArrayToCartographicArray works with a result parameter", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const resultCartographic = new import__201.Cartographic(); const result = [resultCartographic]; const returnedResult = ellipsoid.cartesianArrayToCartographicArray( [spaceCartesian, surfaceCartesian], result ); expect(result).toBe(returnedResult); expect(result.length).toEqual(2); expect(result[0]).toBe(resultCartographic); expect(result[0]).toEqualEpsilon(spaceCartographic, import__201.Math.EPSILON7); expect(result[1]).toEqualEpsilon(surfaceCartographic, import__201.Math.EPSILON7); }); it("scaleToGeodeticSurface scaled in the x direction", function() { const ellipsoid = new import__201.Ellipsoid(1, 2, 3); const expected = new import__201.Cartesian3(1, 0, 0); const cartesian = new import__201.Cartesian3(9, 0, 0); const returnedResult = ellipsoid.scaleToGeodeticSurface(cartesian); expect(returnedResult).toEqual(expected); }); it("scaleToGeodeticSurface scaled in the y direction", function() { const ellipsoid = new import__201.Ellipsoid(1, 2, 3); const expected = new import__201.Cartesian3(0, 2, 0); const cartesian = new import__201.Cartesian3(0, 8, 0); const returnedResult = ellipsoid.scaleToGeodeticSurface(cartesian); expect(returnedResult).toEqual(expected); }); it("scaleToGeodeticSurface scaled in the z direction", function() { const ellipsoid = new import__201.Ellipsoid(1, 2, 3); const expected = new import__201.Cartesian3(0, 0, 3); const cartesian = new import__201.Cartesian3(0, 0, 8); const returnedResult = ellipsoid.scaleToGeodeticSurface(cartesian); expect(returnedResult).toEqual(expected); }); it("scaleToGeodeticSurface works without a result parameter", function() { const ellipsoid = new import__201.Ellipsoid(1, 2, 3); const expected = new import__201.Cartesian3( 0.2680893773941855, 1.1160466902266495, 2.3559801120411263 ); const cartesian = new import__201.Cartesian3(4, 5, 6); const returnedResult = ellipsoid.scaleToGeodeticSurface(cartesian); expect(returnedResult).toEqualEpsilon(expected, import__201.Math.EPSILON16); }); it("scaleToGeodeticSurface works with a result parameter", function() { const ellipsoid = new import__201.Ellipsoid(1, 2, 3); const expected = new import__201.Cartesian3( 0.2680893773941855, 1.1160466902266495, 2.3559801120411263 ); const cartesian = new import__201.Cartesian3(4, 5, 6); const result = new import__201.Cartesian3(); const returnedResult = ellipsoid.scaleToGeodeticSurface(cartesian, result); expect(returnedResult).toBe(result); expect(result).toEqualEpsilon(expected, import__201.Math.EPSILON16); }); it("scaleToGeocentricSurface scaled in the x direction", function() { const ellipsoid = new import__201.Ellipsoid(1, 2, 3); const expected = new import__201.Cartesian3(1, 0, 0); const cartesian = new import__201.Cartesian3(9, 0, 0); const returnedResult = ellipsoid.scaleToGeocentricSurface(cartesian); expect(returnedResult).toEqual(expected); }); it("scaleToGeocentricSurface scaled in the y direction", function() { const ellipsoid = new import__201.Ellipsoid(1, 2, 3); const expected = new import__201.Cartesian3(0, 2, 0); const cartesian = new import__201.Cartesian3(0, 8, 0); const returnedResult = ellipsoid.scaleToGeocentricSurface(cartesian); expect(returnedResult).toEqual(expected); }); it("scaleToGeocentricSurface scaled in the z direction", function() { const ellipsoid = new import__201.Ellipsoid(1, 2, 3); const expected = new import__201.Cartesian3(0, 0, 3); const cartesian = new import__201.Cartesian3(0, 0, 8); const returnedResult = ellipsoid.scaleToGeocentricSurface(cartesian); expect(returnedResult).toEqual(expected); }); it("scaleToGeocentricSurface works without a result parameter", function() { const ellipsoid = new import__201.Ellipsoid(1, 2, 3); const expected = new import__201.Cartesian3( 0.7807200583588266, 0.9759000729485333, 1.1710800875382399 ); const cartesian = new import__201.Cartesian3(4, 5, 6); const returnedResult = ellipsoid.scaleToGeocentricSurface(cartesian); expect(returnedResult).toEqualEpsilon(expected, import__201.Math.EPSILON16); }); it("scaleToGeocentricSurface works with a result parameter", function() { const ellipsoid = new import__201.Ellipsoid(1, 2, 3); const expected = new import__201.Cartesian3( 0.7807200583588266, 0.9759000729485333, 1.1710800875382399 ); const cartesian = new import__201.Cartesian3(4, 5, 6); const result = new import__201.Cartesian3(); const returnedResult = ellipsoid.scaleToGeocentricSurface( cartesian, result ); expect(returnedResult).toBe(result); expect(result).toEqualEpsilon(expected, import__201.Math.EPSILON16); }); it("scaleToGeodeticSurface returns undefined at center", function() { const ellipsoid = new import__201.Ellipsoid(1, 2, 3); const cartesian = new import__201.Cartesian3(0, 0, 0); const returnedResult = ellipsoid.scaleToGeodeticSurface(cartesian); expect(returnedResult).toBeUndefined(); }); it("transformPositionToScaledSpace works without a result parameter", function() { const ellipsoid = new import__201.Ellipsoid(2, 3, 4); const expected = new import__201.Cartesian3(2, 2, 2); const cartesian = new import__201.Cartesian3(4, 6, 8); const returnedResult = ellipsoid.transformPositionToScaledSpace(cartesian); expect(returnedResult).toEqualEpsilon(expected, import__201.Math.EPSILON16); }); it("transformPositionToScaledSpace works with a result parameter", function() { const ellipsoid = new import__201.Ellipsoid(2, 3, 4); const expected = new import__201.Cartesian3(3, 3, 3); const cartesian = new import__201.Cartesian3(6, 9, 12); const result = new import__201.Cartesian3(); const returnedResult = ellipsoid.transformPositionToScaledSpace( cartesian, result ); expect(returnedResult).toBe(result); expect(result).toEqualEpsilon(expected, import__201.Math.EPSILON16); }); it("transformPositionFromScaledSpace works without a result parameter", function() { const ellipsoid = new import__201.Ellipsoid(2, 3, 4); const expected = new import__201.Cartesian3(4, 6, 8); const cartesian = new import__201.Cartesian3(2, 2, 2); const returnedResult = ellipsoid.transformPositionFromScaledSpace( cartesian ); expect(returnedResult).toEqualEpsilon(expected, import__201.Math.EPSILON16); }); it("transformPositionFromScaledSpace works with a result parameter", function() { const ellipsoid = new import__201.Ellipsoid(2, 3, 4); const expected = new import__201.Cartesian3(6, 9, 12); const cartesian = new import__201.Cartesian3(3, 3, 3); const result = new import__201.Cartesian3(); const returnedResult = ellipsoid.transformPositionFromScaledSpace( cartesian, result ); expect(returnedResult).toBe(result); expect(result).toEqualEpsilon(expected, import__201.Math.EPSILON16); }); it("equals works in all cases", function() { const ellipsoid = new import__201.Ellipsoid(1, 0, 0); expect(ellipsoid.equals(new import__201.Ellipsoid(1, 0, 0))).toEqual(true); expect(ellipsoid.equals(new import__201.Ellipsoid(1, 1, 0))).toEqual(false); expect(ellipsoid.equals(void 0)).toEqual(false); }); it("toString produces expected values", function() { const expected = "(1, 2, 3)"; const ellipsoid = new import__201.Ellipsoid(1, 2, 3); expect(ellipsoid.toString()).toEqual(expected); }); it("constructor throws if x less than 0", function() { expect(function() { return new import__201.Ellipsoid(-1, 0, 0); }).toThrowDeveloperError(); }); it("constructor throws if y less than 0", function() { expect(function() { return new import__201.Ellipsoid(0, -1, 0); }).toThrowDeveloperError(); }); it("constructor throws if z less than 0", function() { expect(function() { return new import__201.Ellipsoid(0, 0, -1); }).toThrowDeveloperError(); }); it("expect Ellipsoid.geocentricSurfaceNormal is be Cartesian3.normalize", function() { expect(import__201.Ellipsoid.WGS84.geocentricSurfaceNormal).toBe(import__201.Cartesian3.normalize); }); it("geodeticSurfaceNormalCartographic throws with no cartographic", function() { expect(function() { import__201.Ellipsoid.WGS84.geodeticSurfaceNormalCartographic(void 0); }).toThrowDeveloperError(); }); it("geodeticSurfaceNormal throws with no cartesian", function() { expect(function() { import__201.Ellipsoid.WGS84.geodeticSurfaceNormal(void 0); }).toThrowDeveloperError(); }); it("cartographicToCartesian throws with no cartographic", function() { expect(function() { import__201.Ellipsoid.WGS84.cartographicToCartesian(void 0); }).toThrowDeveloperError(); }); it("cartographicArrayToCartesianArray throws with no cartographics", function() { expect(function() { import__201.Ellipsoid.WGS84.cartographicArrayToCartesianArray(void 0); }).toThrowDeveloperError(); }); it("cartesianToCartographic throws with no cartesian", function() { expect(function() { import__201.Ellipsoid.WGS84.cartesianToCartographic(void 0); }).toThrowDeveloperError(); }); it("cartesianArrayToCartographicArray throws with no cartesians", function() { expect(function() { import__201.Ellipsoid.WGS84.cartesianArrayToCartographicArray(void 0); }).toThrowDeveloperError(); }); it("scaleToGeodeticSurface throws with no cartesian", function() { expect(function() { import__201.Ellipsoid.WGS84.scaleToGeodeticSurface(void 0); }).toThrowDeveloperError(); }); it("scaleToGeocentricSurface throws with no cartesian", function() { expect(function() { import__201.Ellipsoid.WGS84.scaleToGeocentricSurface(void 0); }).toThrowDeveloperError(); }); it("clone copies any object with the proper structure", function() { const myEllipsoid = { _radii: { x: 1, y: 2, z: 3 }, _radiiSquared: { x: 4, y: 5, z: 6 }, _radiiToTheFourth: { x: 7, y: 8, z: 9 }, _oneOverRadii: { x: 10, y: 11, z: 12 }, _oneOverRadiiSquared: { x: 13, y: 14, z: 15 }, _minimumRadius: 16, _maximumRadius: 17, _centerToleranceSquared: 18 }; const cloned = import__201.Ellipsoid.clone(myEllipsoid); expect(cloned).toBeInstanceOf(import__201.Ellipsoid); expect(cloned).toEqual(myEllipsoid); }); it("clone uses result parameter if provided", function() { const myEllipsoid = { _radii: { x: 1, y: 2, z: 3 }, _radiiSquared: { x: 4, y: 5, z: 6 }, _radiiToTheFourth: { x: 7, y: 8, z: 9 }, _oneOverRadii: { x: 10, y: 11, z: 12 }, _oneOverRadiiSquared: { x: 13, y: 14, z: 15 }, _minimumRadius: 16, _maximumRadius: 17, _centerToleranceSquared: 18 }; const result = new import__201.Ellipsoid(); const cloned = import__201.Ellipsoid.clone(myEllipsoid, result); expect(cloned).toBe(result); expect(cloned).toEqual(myEllipsoid); }); it("getSurfaceNormalIntersectionWithZAxis throws with no position", function() { expect(function() { import__201.Ellipsoid.WGS84.getSurfaceNormalIntersectionWithZAxis(void 0); }).toThrowDeveloperError(); }); it("getSurfaceNormalIntersectionWithZAxis throws if the ellipsoid is not an ellipsoid of revolution", function() { expect(function() { const ellipsoid = new import__201.Ellipsoid(1, 2, 3); const cartesian = new import__201.Cartesian3(); ellipsoid.getSurfaceNormalIntersectionWithZAxis(cartesian); }).toThrowDeveloperError(); }); it("getSurfaceNormalIntersectionWithZAxis throws if the ellipsoid has radii.z === 0", function() { expect(function() { const ellipsoid = new import__201.Ellipsoid(1, 2, 0); const cartesian = new import__201.Cartesian3(); ellipsoid.getSurfaceNormalIntersectionWithZAxis(cartesian); }).toThrowDeveloperError(); }); it("getSurfaceNormalIntersectionWithZAxis works without a result parameter", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const cartographic = import__201.Cartographic.fromDegrees(35.23, 33.23); const cartesianOnTheSurface = ellipsoid.cartographicToCartesian( cartographic ); const returnedResult = ellipsoid.getSurfaceNormalIntersectionWithZAxis( cartesianOnTheSurface ); expect(returnedResult).toBeInstanceOf(import__201.Cartesian3); }); it("getSurfaceNormalIntersectionWithZAxis works with a result parameter", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const cartographic = import__201.Cartographic.fromDegrees(35.23, 33.23); const cartesianOnTheSurface = ellipsoid.cartographicToCartesian( cartographic ); const returnedResult = ellipsoid.getSurfaceNormalIntersectionWithZAxis( cartesianOnTheSurface, void 0, cartesianOnTheSurface ); expect(returnedResult).toBe(cartesianOnTheSurface); }); it("getSurfaceNormalIntersectionWithZAxis returns undefined if the result is outside the ellipsoid with buffer parameter", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const cartographic = import__201.Cartographic.fromDegrees(35.23, 33.23); const cartesianOnTheSurface = ellipsoid.cartographicToCartesian( cartographic ); const returnedResult = ellipsoid.getSurfaceNormalIntersectionWithZAxis( cartesianOnTheSurface, ellipsoid.radii.z ); expect(returnedResult).toBe(void 0); }); it("getSurfaceNormalIntersectionWithZAxis returns undefined if the result is outside the ellipsoid without buffer parameter", function() { const majorAxis = 10; const minorAxis = 1; const ellipsoid = new import__201.Ellipsoid(majorAxis, majorAxis, minorAxis); const cartographic = import__201.Cartographic.fromDegrees(45, 90); const cartesianOnTheSurface = ellipsoid.cartographicToCartesian( cartographic ); const returnedResult = ellipsoid.getSurfaceNormalIntersectionWithZAxis( cartesianOnTheSurface, void 0 ); expect(returnedResult).toBe(void 0); }); it("getSurfaceNormalIntersectionWithZAxis returns a result that is equal to a value that computed in a different way", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const cartographic = import__201.Cartographic.fromDegrees(35.23, 33.23); let cartesianOnTheSurface = ellipsoid.cartographicToCartesian(cartographic); const surfaceNormal = ellipsoid.geodeticSurfaceNormal( cartesianOnTheSurface ); const magnitude = cartesianOnTheSurface.x / surfaceNormal.x; const expected = new import__201.Cartesian3(); expected.z = cartesianOnTheSurface.z - surfaceNormal.z * magnitude; let result = ellipsoid.getSurfaceNormalIntersectionWithZAxis( cartesianOnTheSurface, void 0 ); expect(result).toEqualEpsilon(expected, import__201.Math.EPSILON8); cartesianOnTheSurface = new import__201.Cartesian3(ellipsoid.radii.x, 0, 0); result = ellipsoid.getSurfaceNormalIntersectionWithZAxis( cartesianOnTheSurface, void 0 ); expect(result).toEqualEpsilon(import__201.Cartesian3.ZERO, import__201.Math.EPSILON8); }); it("getSurfaceNormalIntersectionWithZAxis returns a result that when it's used as an origin for a vector with the surface normal direction it produces an accurate cartographic", function() { const ellipsoid = import__201.Ellipsoid.WGS84; let cartographic = import__201.Cartographic.fromDegrees(35.23, 33.23); let cartesianOnTheSurface = ellipsoid.cartographicToCartesian(cartographic); let surfaceNormal = ellipsoid.geodeticSurfaceNormal(cartesianOnTheSurface); let result = ellipsoid.getSurfaceNormalIntersectionWithZAxis( cartesianOnTheSurface, void 0 ); let surfaceNormalWithLength = import__201.Cartesian3.multiplyByScalar( surfaceNormal, ellipsoid.maximumRadius, new import__201.Cartesian3() ); let position = import__201.Cartesian3.add( result, surfaceNormalWithLength, new import__201.Cartesian3() ); let resultCartographic = ellipsoid.cartesianToCartographic(position); resultCartographic.height = 0; expect(resultCartographic).toEqualEpsilon( cartographic, import__201.Math.EPSILON8 ); cartographic = import__201.Cartographic.fromDegrees(0, 90); cartesianOnTheSurface = new import__201.Cartesian3(0, 0, ellipsoid.radii.z); surfaceNormal = ellipsoid.geodeticSurfaceNormal(cartesianOnTheSurface); surfaceNormalWithLength = import__201.Cartesian3.multiplyByScalar( surfaceNormal, ellipsoid.maximumRadius, new import__201.Cartesian3() ); result = ellipsoid.getSurfaceNormalIntersectionWithZAxis( cartesianOnTheSurface, void 0 ); position = import__201.Cartesian3.add( result, surfaceNormalWithLength, new import__201.Cartesian3() ); resultCartographic = ellipsoid.cartesianToCartographic(position); resultCartographic.height = 0; expect(resultCartographic).toEqualEpsilon( cartographic, import__201.Math.EPSILON8 ); }); it("getLocalCurvature throws with no position", function() { expect(function() { import__201.Ellipsoid.WGS84.getLocalCurvature(void 0); }).toThrowDeveloperError(); }); it("getLocalCurvature returns expected values at the equator", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const cartographic = import__201.Cartographic.fromDegrees(0, 0); const cartesianOnTheSurface = ellipsoid.cartographicToCartesian( cartographic ); const returnedResult = ellipsoid.getLocalCurvature(cartesianOnTheSurface); const expectedResult = new import__201.Cartesian2( 1 / ellipsoid.maximumRadius, ellipsoid.maximumRadius / (ellipsoid.minimumRadius * ellipsoid.minimumRadius) ); expect(returnedResult).toEqualEpsilon(expectedResult, import__201.Math.EPSILON8); }); it("getLocalCurvature returns expected values at the north pole", function() { const ellipsoid = import__201.Ellipsoid.WGS84; const cartographic = import__201.Cartographic.fromDegrees(0, 90); const cartesianOnTheSurface = ellipsoid.cartographicToCartesian( cartographic ); const returnedResult = ellipsoid.getLocalCurvature(cartesianOnTheSurface); const semiLatusRectum = ellipsoid.maximumRadius * ellipsoid.maximumRadius / ellipsoid.minimumRadius; const expectedResult = new import__201.Cartesian2( 1 / semiLatusRectum, 1 / semiLatusRectum ); expect(returnedResult).toEqualEpsilon(expectedResult, import__201.Math.EPSILON8); }); it("ellipsoid is initialized with _squaredXOverSquaredZ property", function() { const ellipsoid = new import__201.Ellipsoid(4, 4, 3); const squaredXOverSquaredZ = ellipsoid.radiiSquared.x / ellipsoid.radiiSquared.z; expect(ellipsoid._squaredXOverSquaredZ).toEqual(squaredXOverSquaredZ); }); it("surfaceArea throws without rectangle", function() { expect(function() { return import__201.Ellipsoid.WGS84.surfaceArea(void 0); }).toThrowDeveloperError(); }); it("computes surfaceArea", function() { let ellipsoid = new import__201.Ellipsoid(4, 4, 3); let a2 = ellipsoid.radiiSquared.x; let c2 = ellipsoid.radiiSquared.z; let e = Math.sqrt(1 - c2 / a2); let area = import__201.Math.TWO_PI * a2 + import__201.Math.PI * (c2 / e) * Math.log((1 + e) / (1 - e)); expect( ellipsoid.surfaceArea( new import__201.Rectangle( -import__201.Math.PI, -import__201.Math.PI_OVER_TWO, import__201.Math.PI, import__201.Math.PI_OVER_TWO ) ) ).toEqualEpsilon(area, import__201.Math.EPSILON3); ellipsoid = new import__201.Ellipsoid(3, 3, 4); a2 = ellipsoid.radiiSquared.x; c2 = ellipsoid.radiiSquared.z; e = Math.sqrt(1 - a2 / c2); const a = ellipsoid.radii.x; const c = ellipsoid.radii.z; area = import__201.Math.TWO_PI * a2 + import__201.Math.TWO_PI * (a * c / e) * Math.asin(e); expect( ellipsoid.surfaceArea( new import__201.Rectangle( -import__201.Math.PI, -import__201.Math.PI_OVER_TWO, import__201.Math.PI, import__201.Math.PI_OVER_TWO ) ) ).toEqualEpsilon(area, import__201.Math.EPSILON3); }); createPackableSpecs_default(import__201.Ellipsoid, import__201.Ellipsoid.WGS84, [ import__201.Ellipsoid.WGS84.radii.x, import__201.Ellipsoid.WGS84.radii.y, import__201.Ellipsoid.WGS84.radii.z ]); }); // packages/engine/Specs/Core/EllipsoidTangentPlaneSpec.js var import__202 = __toESM(require_Cesium(), 1); describe("Core/EllipsoidTangentPlane", function() { it("constructor defaults to WGS84", function() { const origin = new import__202.Cartesian3(import__202.Ellipsoid.WGS84.radii.x, 0, 0); const tangentPlane = new import__202.EllipsoidTangentPlane(origin); expect(tangentPlane.ellipsoid).toBe(import__202.Ellipsoid.WGS84); expect(tangentPlane.origin).toEqual(origin); }); it("constructor sets expected values", function() { const tangentPlane = new import__202.EllipsoidTangentPlane( import__202.Cartesian3.UNIT_X, import__202.Ellipsoid.UNIT_SPHERE ); expect(tangentPlane.ellipsoid).toBe(import__202.Ellipsoid.UNIT_SPHERE); expect(tangentPlane.origin).toEqual(import__202.Cartesian3.UNIT_X); }); it("fromPoints sets expected values", function() { const points = [ new import__202.Cartesian3(2, 0, 0), new import__202.Cartesian3(0, 0, 0) ]; const tangentPlane = import__202.EllipsoidTangentPlane.fromPoints( points, import__202.Ellipsoid.UNIT_SPHERE ); expect(tangentPlane.ellipsoid).toBe(import__202.Ellipsoid.UNIT_SPHERE); expect(tangentPlane.origin).toEqual(import__202.Cartesian3.UNIT_X); }); it("projectPointOntoPlane returns undefined for unsolvable projections", function() { const ellipsoid = import__202.Ellipsoid.UNIT_SPHERE; const origin = new import__202.Cartesian3(1, 0, 0); const tangentPlane = new import__202.EllipsoidTangentPlane(origin, ellipsoid); const positions = new import__202.Cartesian3(0, 0, 1); const returnedResult = tangentPlane.projectPointOntoPlane(positions); expect(returnedResult).toBeUndefined(); }); it("projectPointOntoPlane works without a result parameter", function() { const ellipsoid = import__202.Ellipsoid.UNIT_SPHERE; const origin = new import__202.Cartesian3(1, 0, 0); const tangentPlane = new import__202.EllipsoidTangentPlane(origin, ellipsoid); const positions = new import__202.Cartesian3(1, 0, 1); const expectedResult = new import__202.Cartesian2(0, 1); const returnedResult = tangentPlane.projectPointOntoPlane(positions); expect(returnedResult).toEqual(expectedResult); }); it("projectPointOntoPlane works with a result parameter", function() { const ellipsoid = import__202.Ellipsoid.UNIT_SPHERE; const origin = new import__202.Cartesian3(1, 0, 0); const tangentPlane = new import__202.EllipsoidTangentPlane(origin, ellipsoid); const positions = new import__202.Cartesian3(1, 0, 1); const expectedResult = new import__202.Cartesian2(0, 1); const result = new import__202.Cartesian2(); const returnedResult = tangentPlane.projectPointOntoPlane( positions, result ); expect(result).toBe(returnedResult); expect(returnedResult).toEqual(expectedResult); }); it("projectPointsOntoPlane works without a result parameter", function() { const ellipsoid = import__202.Ellipsoid.UNIT_SPHERE; const origin = new import__202.Cartesian3(1, 0, 0); const tangentPlane = new import__202.EllipsoidTangentPlane(origin, ellipsoid); const positions = [ new import__202.Cartesian3(1, 0, 1), new import__202.Cartesian3(1, 0, 0), new import__202.Cartesian3(1, 1, 0) ]; const expectedResults = [ new import__202.Cartesian2(0, 1), new import__202.Cartesian2(0, 0), new import__202.Cartesian2(1, 0) ]; const returnedResults = tangentPlane.projectPointsOntoPlane(positions); expect(returnedResults).toEqual(expectedResults); }); it("projectPointsOntoPlane works with a result parameter", function() { const ellipsoid = import__202.Ellipsoid.UNIT_SPHERE; const origin = new import__202.Cartesian3(1, 0, 0); const tangentPlane = new import__202.EllipsoidTangentPlane(origin, ellipsoid); const positions = [ new import__202.Cartesian3(1, 0, 1), new import__202.Cartesian3(1, 0, 0), new import__202.Cartesian3(1, 1, 0) ]; const expectedResults = [ new import__202.Cartesian2(0, 1), new import__202.Cartesian2(0, 0), new import__202.Cartesian2(1, 0) ]; const index0 = new import__202.Cartesian2(); const result = [index0]; const returnedResults = tangentPlane.projectPointsOntoPlane( positions, result ); expect(result).toBe(returnedResults); expect(result[0]).toBe(index0); expect(returnedResults).toEqual(expectedResults); }); it("projectPointsOntoPlane works when some points cannot be projected", function() { const ellipsoid = import__202.Ellipsoid.UNIT_SPHERE; const origin = new import__202.Cartesian3(1, 0, 0); const tangentPlane = new import__202.EllipsoidTangentPlane(origin, ellipsoid); const positions = [ new import__202.Cartesian3(1, 0, 1), new import__202.Cartesian3(1, 0, 0), new import__202.Cartesian3(0, 0, 1), new import__202.Cartesian3(1, 1, 0), new import__202.Cartesian3(0, 1, 0) ]; const expectedResults = [ new import__202.Cartesian2(0, 1), new import__202.Cartesian2(0, 0), new import__202.Cartesian2(1, 0) ]; const returnedResults = tangentPlane.projectPointsOntoPlane(positions); expect(returnedResults).toEqual(expectedResults); }); it("projectPointOntoEllipsoid works without a result parameter", function() { const ellipsoid = import__202.Ellipsoid.UNIT_SPHERE; const origin = new import__202.Cartesian3(1, 0, 0); const tangentPlane = new import__202.EllipsoidTangentPlane(origin, ellipsoid); const position = new import__202.Cartesian3(2, 2, 0); const expectedResult = new import__202.Cartesian3(1 / 3, 2 / 3, 2 / 3); const returnedResult = tangentPlane.projectPointOntoEllipsoid(position); expect(returnedResult).toEqual(expectedResult); }); it("projectPointOntoEllipsoid works with a result parameter", function() { const ellipsoid = import__202.Ellipsoid.UNIT_SPHERE; const origin = new import__202.Cartesian3(1, 0, 0); const tangentPlane = new import__202.EllipsoidTangentPlane(origin, ellipsoid); const position = new import__202.Cartesian3(2, -2, 0); const expectedResult = new import__202.Cartesian3(1 / 3, 2 / 3, -2 / 3); const result = new import__202.Cartesian3(); const returnedResult = tangentPlane.projectPointOntoEllipsoid( position, result ); expect(result).toBe(returnedResult); expect(returnedResult).toEqual(expectedResult); }); it("projectPointsOntoEllipsoid works without a result parameter", function() { const ellipsoid = import__202.Ellipsoid.UNIT_SPHERE; const origin = new import__202.Cartesian3(1, 0, 0); const tangentPlane = new import__202.EllipsoidTangentPlane(origin, ellipsoid); const positions = [ new import__202.Cartesian3(2, -2, 0), new import__202.Cartesian3(2, 2, 0) ]; const expectedResults = [ new import__202.Cartesian3(1 / 3, 2 / 3, -2 / 3), new import__202.Cartesian3(1 / 3, 2 / 3, 2 / 3) ]; const returnedResults = tangentPlane.projectPointsOntoEllipsoid(positions); expect(returnedResults).toEqual(expectedResults); }); it("projectPointsOntoEllipsoid works with a result parameter", function() { const ellipsoid = import__202.Ellipsoid.UNIT_SPHERE; const origin = new import__202.Cartesian3(1, 0, 0); const tangentPlane = new import__202.EllipsoidTangentPlane(origin, ellipsoid); const positions = [ new import__202.Cartesian3(2, -2, 0), new import__202.Cartesian3(2, 2, 0) ]; const expectedResults = [ new import__202.Cartesian3(1 / 3, 2 / 3, -2 / 3), new import__202.Cartesian3(1 / 3, 2 / 3, 2 / 3) ]; const index0 = new import__202.Cartesian3(); const result = [index0]; const returnedResults = tangentPlane.projectPointsOntoEllipsoid( positions, result ); expect(result).toBe(returnedResults); expect(result[0]).toBe(index0); expect(returnedResults).toEqual(expectedResults); }); it("projectPointToNearestOnPlane works without a result parameter", function() { const ellipsoid = import__202.Ellipsoid.UNIT_SPHERE; const origin = new import__202.Cartesian3(1, 0, 0); const tangentPlane = new import__202.EllipsoidTangentPlane(origin, ellipsoid); const positions = new import__202.Cartesian3(1, 0, 1); const expectedResult = new import__202.Cartesian2(0, 1); const returnedResult = tangentPlane.projectPointToNearestOnPlane(positions); expect(returnedResult).toEqual(expectedResult); }); it("projectPointToNearestOnPlane works projecting from various distances", function() { const ellipsoid = import__202.Ellipsoid.ZERO; const origin = new import__202.Cartesian3(1, 0, 0); const tangentPlane = new import__202.EllipsoidTangentPlane(origin, ellipsoid); expect( tangentPlane.projectPointToNearestOnPlane(new import__202.Cartesian3(2, 0, 0)) ).toEqual(new import__202.Cartesian2(0, 0)); expect( tangentPlane.projectPointToNearestOnPlane(new import__202.Cartesian3(1, 0, 0)) ).toEqual(new import__202.Cartesian2(0, 0)); expect( tangentPlane.projectPointToNearestOnPlane(new import__202.Cartesian3(0, 0, 0)) ).toEqual(new import__202.Cartesian2(0, 0)); expect( tangentPlane.projectPointToNearestOnPlane(new import__202.Cartesian3(-1, 0, 0)) ).toEqual(new import__202.Cartesian2(0, 0)); }); it("projectPointToNearestOnPlane works with a result parameter", function() { const ellipsoid = import__202.Ellipsoid.UNIT_SPHERE; const origin = new import__202.Cartesian3(1, 0, 0); const tangentPlane = new import__202.EllipsoidTangentPlane(origin, ellipsoid); const positions = new import__202.Cartesian3(1, 0, 1); const expectedResult = new import__202.Cartesian2(0, 1); const result = new import__202.Cartesian2(); const returnedResult = tangentPlane.projectPointToNearestOnPlane( positions, result ); expect(result).toBe(returnedResult); expect(returnedResult).toEqual(expectedResult); }); it("projectPointsToNearestOnPlane works without a result parameter", function() { const ellipsoid = import__202.Ellipsoid.UNIT_SPHERE; const origin = new import__202.Cartesian3(1, 0, 0); const tangentPlane = new import__202.EllipsoidTangentPlane(origin, ellipsoid); const positions = [ new import__202.Cartesian3(1, 0, 1), new import__202.Cartesian3(1, 0, 0), new import__202.Cartesian3(1, 1, 0) ]; const expectedResults = [ new import__202.Cartesian2(0, 1), new import__202.Cartesian2(0, 0), new import__202.Cartesian2(1, 0) ]; const returnedResults = tangentPlane.projectPointsToNearestOnPlane( positions ); expect(returnedResults).toEqual(expectedResults); }); it("projectPointsToNearestOnPlane works with a result parameter", function() { const ellipsoid = import__202.Ellipsoid.UNIT_SPHERE; const origin = new import__202.Cartesian3(1, 0, 0); const tangentPlane = new import__202.EllipsoidTangentPlane(origin, ellipsoid); const positions = [ new import__202.Cartesian3(1, 0, 1), new import__202.Cartesian3(1, 0, 0), new import__202.Cartesian3(1, 1, 0) ]; const expectedResults = [ new import__202.Cartesian2(0, 1), new import__202.Cartesian2(0, 0), new import__202.Cartesian2(1, 0) ]; const index0 = new import__202.Cartesian2(); const result = [index0]; const returnedResults = tangentPlane.projectPointsToNearestOnPlane( positions, result ); expect(result).toBe(returnedResults); expect(result[0]).toBe(index0); expect(returnedResults).toEqual(expectedResults); }); it("constructor throws without origin", function() { expect(function() { return new import__202.EllipsoidTangentPlane(void 0, import__202.Ellipsoid.WGS84); }).toThrowDeveloperError(); }); it("constructor throws if origin is at the center of the ellipsoid", function() { expect(function() { return new import__202.EllipsoidTangentPlane(import__202.Cartesian3.ZERO, import__202.Ellipsoid.WGS84); }).toThrowDeveloperError(); }); it("fromPoints throws without cartesians", function() { expect(function() { return import__202.EllipsoidTangentPlane.fromPoints(void 0, import__202.Ellipsoid.WGS84); }).toThrowDeveloperError(); }); it("projectPointOntoPlane throws without cartesian", function() { const tangentPlane = new import__202.EllipsoidTangentPlane( import__202.Cartesian3.UNIT_X, import__202.Ellipsoid.UNIT_SPHERE ); expect(function() { return tangentPlane.projectPointOntoPlane(void 0); }).toThrowDeveloperError(); }); it("projectPointsOntoPlane throws without cartesians", function() { const tangentPlane = new import__202.EllipsoidTangentPlane( import__202.Cartesian3.UNIT_X, import__202.Ellipsoid.UNIT_SPHERE ); expect(function() { return tangentPlane.projectPointsOntoPlane(void 0); }).toThrowDeveloperError(); }); it("projectPointToNearestOnPlane throws without cartesian", function() { const tangentPlane = new import__202.EllipsoidTangentPlane( import__202.Cartesian3.UNIT_X, import__202.Ellipsoid.UNIT_SPHERE ); expect(function() { return tangentPlane.projectPointToNearestOnPlane(void 0); }).toThrowDeveloperError(); }); it("projectPointsToNearestOnPlane throws without cartesians", function() { const tangentPlane = new import__202.EllipsoidTangentPlane( import__202.Cartesian3.UNIT_X, import__202.Ellipsoid.UNIT_SPHERE ); expect(function() { return tangentPlane.projectPointsToNearestOnPlane(void 0); }).toThrowDeveloperError(); }); it("projectPointsOntoEllipsoid throws without cartesians", function() { const tangentPlane = new import__202.EllipsoidTangentPlane( import__202.Cartesian3.UNIT_X, import__202.Ellipsoid.UNIT_SPHERE ); expect(function() { return tangentPlane.projectPointsOntoEllipsoid(void 0); }).toThrowDeveloperError(); }); it("projectPointsOntoEllipsoid works with an arbitrary ellipsoid using fromPoints", function() { const points = import__202.Cartesian3.fromDegreesArray([ -72, 40, -68, 35, -75, 30, -70, 30, -68, 40 ]); const tangentPlane = import__202.EllipsoidTangentPlane.fromPoints( points, import__202.Ellipsoid.WGS84 ); const points2D = tangentPlane.projectPointsOntoPlane(points); const positionsBack = tangentPlane.projectPointsOntoEllipsoid(points2D); expect(positionsBack[0].x).toBeCloseTo(points[0].x); expect(positionsBack[0].y).toBeCloseTo(points[0].y); expect(positionsBack[0].z).toBeCloseTo(points[0].z); }); }); // packages/engine/Specs/Core/EllipsoidTerrainProviderSpec.js var import__203 = __toESM(require_Cesium(), 1); describe( "Core/EllipsoidTerrainProvider", function() { let context; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); it("conforms to TerrainProvider interface", function() { expect(import__203.EllipsoidTerrainProvider).toConformToInterface(import__203.TerrainProvider); }); it("requestTileGeometry creates terrain data.", function() { const terrain = new import__203.EllipsoidTerrainProvider(); const terrainData = terrain.requestTileGeometry(0, 0, 0); expect(terrainData).toBeDefined(); }); it("has error event", function() { const provider = new import__203.EllipsoidTerrainProvider(); expect(provider.errorEvent).toBeDefined(); expect(provider.errorEvent).toBe(provider.errorEvent); }); it("returns undefined on getTileDataAvailable()", function() { const provider = new import__203.EllipsoidTerrainProvider(); expect(provider.getTileDataAvailable()).toBeUndefined(); }); }, "WebGL" ); // packages/engine/Specs/Core/EllipsoidalOccluderSpec.js var import__204 = __toESM(require_Cesium(), 1); var import__205 = __toESM(require_Cesium(), 1); describe("Core/EllipsoidalOccluder", function() { it("uses ellipsoid", function() { const ellipsoid = new import__204.Ellipsoid(2, 3, 4); const occluder = new import__204.EllipsoidalOccluder(ellipsoid); expect(occluder.ellipsoid).toEqual(ellipsoid); }); it("throws if ellipsoid is not provided to constructor", function() { function createOccluderWithoutEllipsoid() { return new import__204.EllipsoidalOccluder(void 0, new import__204.Cartesian3(1, 2, 3)); } expect(createOccluderWithoutEllipsoid).toThrowDeveloperError(); }); it("isPointVisible example works as claimed", function() { const cameraPosition = new import__204.Cartesian3(0, 0, 2.5); const ellipsoid = new import__204.Ellipsoid(1, 1.1, 0.9); const occluder = new import__204.EllipsoidalOccluder(ellipsoid, cameraPosition); const point = new import__204.Cartesian3(0, -3, -3); expect(occluder.isPointVisible(point)).toEqual(true); }); it("isScaledSpacePointVisible example works as claimed", function() { const cameraPosition = new import__204.Cartesian3(0, 0, 2.5); const ellipsoid = new import__204.Ellipsoid(1, 1.1, 0.9); const occluder = new import__204.EllipsoidalOccluder(ellipsoid, cameraPosition); const point = new import__204.Cartesian3(0, -3, -3); const scaledSpacePoint = ellipsoid.transformPositionToScaledSpace(point); expect(occluder.isScaledSpacePointVisible(scaledSpacePoint)).toEqual(true); }); it("isScaledSpacePointVisiblePossiblyUnderEllipsoid example works as claimed", function() { const cameraPosition = new import__204.Cartesian3(0, 0, 1); const ellipsoid = new import__204.Ellipsoid(1, 1, 1); const occluder = new import__204.EllipsoidalOccluder(ellipsoid, cameraPosition); const height = -0.5; let direction = import__204.Cartesian3.normalize( new import__204.Cartesian3(1, 1, 1), new import__204.Cartesian3() ); let point = import__204.Cartesian3.multiplyByScalar(direction, 0.5, new import__204.Cartesian3()); let scaledSpacePoint = occluder.computeHorizonCullingPoint(point, [point]); let scaledSpacePointShrunk = occluder.computeHorizonCullingPointPossiblyUnderEllipsoid( point, [point], height ); expect(occluder.isScaledSpacePointVisible(scaledSpacePoint)).toEqual(false); expect( occluder.isScaledSpacePointVisiblePossiblyUnderEllipsoid( scaledSpacePointShrunk, height ) ).toEqual(true); direction = new import__204.Cartesian3(0, 1, 0); point = import__204.Cartesian3.multiplyByScalar(direction, 0.5, new import__204.Cartesian3()); scaledSpacePoint = occluder.computeHorizonCullingPoint(point, [point]); scaledSpacePointShrunk = occluder.computeHorizonCullingPointPossiblyUnderEllipsoid( point, [point], height ); expect(occluder.isScaledSpacePointVisible(scaledSpacePoint)).toEqual(false); expect( occluder.isScaledSpacePointVisiblePossiblyUnderEllipsoid( scaledSpacePointShrunk, height ) ).toEqual(false); }); it("reports not visible when point is directly behind ellipsoid", function() { const ellipsoid = import__204.Ellipsoid.WGS84; const occluder = new import__204.EllipsoidalOccluder(ellipsoid); occluder.cameraPosition = new import__204.Cartesian3(7e6, 0, 0); const point = new import__204.Cartesian3(-7e6, 0, 0); expect(occluder.isPointVisible(point)).toEqual(false); }); it("reports not visible when point is directly behind ellipsoid and camera is inside the ellispoid", function() { const ellipsoid = import__204.Ellipsoid.WGS84; const occluder = new import__204.EllipsoidalOccluder(ellipsoid); occluder.cameraPosition = new import__204.Cartesian3( ellipsoid.minimumRadius - 100, 0, 0 ); const point = new import__204.Cartesian3(-7e6, 0, 0); expect(occluder.isPointVisible(point)).toEqual(false); }); it("reports visible when point is in front of ellipsoid", function() { const ellipsoid = import__204.Ellipsoid.WGS84; const occluder = new import__204.EllipsoidalOccluder(ellipsoid); occluder.cameraPosition = new import__204.Cartesian3(7e6, 0, 0); const point = new import__204.Cartesian3(69e5, 0, 0); expect(occluder.isPointVisible(point)).toEqual(true); }); it("reports visible when point is in opposite direction from ellipsoid", function() { const ellipsoid = import__204.Ellipsoid.WGS84; const occluder = new import__204.EllipsoidalOccluder(ellipsoid); occluder.cameraPosition = new import__204.Cartesian3(7e6, 0, 0); const point = new import__204.Cartesian3(71e5, 0, 0); expect(occluder.isPointVisible(point)).toEqual(true); }); it("reports not visible when point is over horizon", function() { const ellipsoid = import__204.Ellipsoid.WGS84; const occluder = new import__204.EllipsoidalOccluder(ellipsoid); occluder.cameraPosition = new import__204.Cartesian3(7e6, 0, 0); const point = new import__204.Cartesian3(4510635, 4510635, 0); expect(occluder.isPointVisible(point)).toEqual(false); }); describe("computeHorizonCullingPoint", function() { it("requires directionToPoint and positions", function() { const ellipsoid = new import__204.Ellipsoid(12345, 12345, 12345); const ellipsoidalOccluder = new import__204.EllipsoidalOccluder(ellipsoid); const positions = [new import__204.Cartesian3(-12345, 12345, 12345)]; const directionToPoint = import__204.BoundingSphere.fromPoints(positions).center; expect(function() { ellipsoidalOccluder.computeHorizonCullingPoint(void 0, positions); }).toThrowDeveloperError(); expect(function() { ellipsoidalOccluder.computeHorizonCullingPoint( directionToPoint, void 0 ); }).toThrowDeveloperError(); }); it("returns point on ellipsoid when single position is on center line", function() { const ellipsoid = new import__204.Ellipsoid(12345, 4567, 8910); const ellipsoidalOccluder = new import__204.EllipsoidalOccluder(ellipsoid); const positions = [new import__204.Cartesian3(12345, 0, 0)]; const directionToPoint = new import__204.Cartesian3(1, 0, 0); const result = ellipsoidalOccluder.computeHorizonCullingPoint( directionToPoint, positions ); expect(result.x).toEqualEpsilon(1, import__205.Math.EPSILON14); expect(result.y).toEqualEpsilon(0, import__205.Math.EPSILON14); expect(result.z).toEqualEpsilon(0, import__205.Math.EPSILON14); }); it("returns undefined when horizon of single point is parallel to center line", function() { const ellipsoid = new import__204.Ellipsoid(12345, 4567, 8910); const ellipsoidalOccluder = new import__204.EllipsoidalOccluder(ellipsoid); const positions = [new import__204.Cartesian3(0, 4567, 0)]; const directionToPoint = new import__204.Cartesian3(1, 0, 0); const result = ellipsoidalOccluder.computeHorizonCullingPoint( directionToPoint, positions ); expect(result).toBeUndefined(); }); it("returns undefined when single point is in the opposite direction of the center line", function() { const ellipsoid = new import__204.Ellipsoid(12345, 4567, 8910); const ellipsoidalOccluder = new import__204.EllipsoidalOccluder(ellipsoid); const positions = [new import__204.Cartesian3(-14e3, -1e3, 0)]; const directionToPoint = new import__204.Cartesian3(1, 0, 0); const result = ellipsoidalOccluder.computeHorizonCullingPoint( directionToPoint, positions ); expect(result).toBeUndefined(); }); it("returns undefined when any point is in the opposite direction of the center line", function() { const ellipsoid = new import__204.Ellipsoid(1, 1, 1); const ellipsoidalOccluder = new import__204.EllipsoidalOccluder(ellipsoid); const positions = [ new import__204.Cartesian3(2, 0, 0), new import__204.Cartesian3(-1, 0, 0) ]; const directionToPoint = new import__204.Cartesian3(1, 0, 0); const result = ellipsoidalOccluder.computeHorizonCullingPoint( directionToPoint, positions ); expect(result).toBeUndefined(); }); it("returns undefined when the direction is zero", function() { const ellipsoid = new import__204.Ellipsoid(1, 1, 1); const ellipsoidalOccluder = new import__204.EllipsoidalOccluder(ellipsoid); const positions = [new import__204.Cartesian3(1, 0, 0)]; const directionToPoint = new import__204.Cartesian3(0, 0, 0); const result = ellipsoidalOccluder.computeHorizonCullingPoint( directionToPoint, positions ); expect(result).toBeUndefined(); }); it("computes a point from a single position with a grazing altitude close to zero", function() { const ellipsoid = new import__204.Ellipsoid(12345, 12345, 12345); const ellipsoidalOccluder = new import__204.EllipsoidalOccluder(ellipsoid); const positions = [ new import__204.Cartesian3(-12345, 12345, 12345), new import__204.Cartesian3(-12346, 12345, 12345) ]; const boundingSphere = import__204.BoundingSphere.fromPoints(positions); const firstPositionArray = [positions[0]]; const result = ellipsoidalOccluder.computeHorizonCullingPoint( boundingSphere.center, firstPositionArray ); const unscaledResult = import__204.Cartesian3.multiplyComponents( result, ellipsoid.radii, new import__204.Cartesian3() ); const direction = import__204.Cartesian3.normalize( import__204.Cartesian3.subtract(positions[0], unscaledResult, new import__204.Cartesian3()), new import__204.Cartesian3() ); const nearest = import__204.IntersectionTests.grazingAltitudeLocation( new import__204.Ray(unscaledResult, direction), ellipsoid ); const nearestCartographic = ellipsoid.cartesianToCartographic(nearest); expect(nearestCartographic.height).toEqualEpsilon( 0, import__205.Math.EPSILON5 ); }); it("computes a point from multiple positions with a grazing altitude close to zero for one of the positions and less than zero for the others", function() { const ellipsoid = new import__204.Ellipsoid(12345, 12345, 12345); const ellipsoidalOccluder = new import__204.EllipsoidalOccluder(ellipsoid); const positions = [ new import__204.Cartesian3(-12345, 12345, 12345), new import__204.Cartesian3(-12346, 12345, 12345), new import__204.Cartesian3(-12446, 12445, 12445) ]; const boundingSphere = import__204.BoundingSphere.fromPoints(positions); const result = ellipsoidalOccluder.computeHorizonCullingPoint( boundingSphere.center, positions ); const unscaledResult = import__204.Cartesian3.multiplyComponents( result, ellipsoid.radii, new import__204.Cartesian3() ); let foundOneNearZero = false; for (let i = 0; i < positions.length; ++i) { const direction = import__204.Cartesian3.normalize( import__204.Cartesian3.subtract(positions[i], unscaledResult, new import__204.Cartesian3()), new import__204.Cartesian3() ); const nearest = import__204.IntersectionTests.grazingAltitudeLocation( new import__204.Ray(unscaledResult, direction), ellipsoid ); const nearestCartographic = ellipsoid.cartesianToCartographic(nearest); if (Math.abs(nearestCartographic.height) < import__205.Math.EPSILON5) { foundOneNearZero = true; } else { expect(nearestCartographic.height).toBeLessThan(0); } } expect(foundOneNearZero).toBe(true); }); it("computes a point under the ellipsoid with computeHorizonCullingPointPossiblyUnderEllipsoid", function() { const ellipsoid = new import__204.Ellipsoid(12345, 4567, 8910); const ellipsoidalOccluder = new import__204.EllipsoidalOccluder(ellipsoid); const positions = [new import__204.Cartesian3(12344, 0, 0)]; const directionToPoint = new import__204.Cartesian3(1, 0, 0); const result = ellipsoidalOccluder.computeHorizonCullingPointPossiblyUnderEllipsoid( directionToPoint, positions, -1 ); expect(result.x).toEqualEpsilon(1, import__205.Math.EPSILON14); expect(result.y).toEqualEpsilon(0, import__205.Math.EPSILON14); expect(result.z).toEqualEpsilon(0, import__205.Math.EPSILON14); }); }); describe("computeHorizonCullingPointFromVertices", function() { it("requires directionToPoint, vertices, and stride", function() { const ellipsoid = new import__204.Ellipsoid(12345, 12345, 12345); const ellipsoidalOccluder = new import__204.EllipsoidalOccluder(ellipsoid); const positions = [ new import__204.Cartesian3(-12345, 12345, 12345), new import__204.Cartesian3(-12346, 12345, 12345), new import__204.Cartesian3(-12446, 12445, 12445) ]; const boundingSphere = import__204.BoundingSphere.fromPoints(positions); const vertices = []; for (let i = 0; i < positions.length; ++i) { const position = positions[i]; vertices.push(position.x); vertices.push(position.y); vertices.push(position.z); vertices.push(1); vertices.push(2); vertices.push(3); vertices.push(4); } ellipsoidalOccluder.computeHorizonCullingPointFromVertices( boundingSphere.center, vertices, 7 ); expect(function() { ellipsoidalOccluder.computeHorizonCullingPointFromVertices( void 0, vertices, 7 ); }).toThrowDeveloperError(); expect(function() { ellipsoidalOccluder.computeHorizonCullingPointFromVertices( boundingSphere.center, void 0, 7 ); }).toThrowDeveloperError(); expect(function() { ellipsoidalOccluder.computeHorizonCullingPointFromVertices( boundingSphere.center, vertices, void 0 ); }).toThrowDeveloperError(); }); it("produces same answers as computeHorizonCullingPoint", function() { const ellipsoid = new import__204.Ellipsoid(12345, 12345, 12345); const ellipsoidalOccluder = new import__204.EllipsoidalOccluder(ellipsoid); const positions = [ new import__204.Cartesian3(-12345, 12345, 12345), new import__204.Cartesian3(-12346, 12345, 12345), new import__204.Cartesian3(-12446, 12445, 12445) ]; const boundingSphere = import__204.BoundingSphere.fromPoints(positions); const center = new import__204.Cartesian3(-12e3, 12e3, 12e3); const vertices = []; for (let i = 0; i < positions.length; ++i) { const position = positions[i]; vertices.push(position.x - center.x); vertices.push(position.y - center.y); vertices.push(position.z - center.z); vertices.push(1); vertices.push(2); vertices.push(3); vertices.push(4); } const result1 = ellipsoidalOccluder.computeHorizonCullingPoint( boundingSphere.center, positions ); const result2 = ellipsoidalOccluder.computeHorizonCullingPointFromVertices( boundingSphere.center, vertices, 7, center ); expect(result1.x).toEqualEpsilon(result2.x, import__205.Math.EPSILON14); expect(result1.y).toEqualEpsilon(result2.y, import__205.Math.EPSILON14); expect(result1.z).toEqualEpsilon(result2.z, import__205.Math.EPSILON14); }); it("computes a point under the ellipsoid with computeHorizonCullingPointFromVerticesPossiblyUnderEllipsoid", function() { const ellipsoid = new import__204.Ellipsoid(12345, 4567, 8910); const ellipsoidalOccluder = new import__204.EllipsoidalOccluder(ellipsoid); const vertices = [12344, 0, 0]; const directionToPoint = new import__204.Cartesian3(1, 0, 0); const center = import__204.Cartesian3.ZERO; const result = ellipsoidalOccluder.computeHorizonCullingPointFromVerticesPossiblyUnderEllipsoid( directionToPoint, vertices, 3, center, -1 ); expect(result.x).toEqualEpsilon(1, import__205.Math.EPSILON14); expect(result.y).toEqualEpsilon(0, import__205.Math.EPSILON14); expect(result.z).toEqualEpsilon(0, import__205.Math.EPSILON14); }); }); describe("computeHorizonCullingPointFromRectangle", function() { it("returns undefined for global rectangle", function() { const ellipsoid = new import__204.Ellipsoid(12345, 12345, 12345); const ellipsoidalOccluder = new import__204.EllipsoidalOccluder(ellipsoid); const rectangle = import__204.Rectangle.MAX_VALUE; const result = ellipsoidalOccluder.computeHorizonCullingPointFromRectangle( rectangle, ellipsoid ); expect(result).toBeUndefined(); }); it("computes a point with a grazing altitude close to zero for one of the rectangle corners and less than or equal to zero for the others", function() { const ellipsoid = new import__204.Ellipsoid(12345, 12345, 12345); const ellipsoidalOccluder = new import__204.EllipsoidalOccluder(ellipsoid); const rectangle = new import__204.Rectangle(0.1, 0.2, 0.3, 0.4); const result = ellipsoidalOccluder.computeHorizonCullingPointFromRectangle( rectangle, ellipsoid ); expect(result).toBeDefined(); const unscaledResult = import__204.Cartesian3.multiplyComponents( result, ellipsoid.radii, new import__204.Cartesian3() ); const positions = [ ellipsoid.cartographicToCartesian(import__204.Rectangle.southwest(rectangle)), ellipsoid.cartographicToCartesian(import__204.Rectangle.southeast(rectangle)), ellipsoid.cartographicToCartesian(import__204.Rectangle.northwest(rectangle)), ellipsoid.cartographicToCartesian(import__204.Rectangle.northeast(rectangle)) ]; let foundOneNearZero = false; for (let i = 0; i < positions.length; ++i) { const direction = import__204.Cartesian3.normalize( import__204.Cartesian3.subtract(positions[i], unscaledResult, new import__204.Cartesian3()), new import__204.Cartesian3() ); const nearest = import__204.IntersectionTests.grazingAltitudeLocation( new import__204.Ray(unscaledResult, direction), ellipsoid ); const nearestCartographic = ellipsoid.cartesianToCartographic(nearest); if (Math.abs(nearestCartographic.height) < import__205.Math.EPSILON5) { foundOneNearZero = true; } else { expect(nearestCartographic.height).toBeLessThanOrEqual(0); } } expect(foundOneNearZero).toBe(true); }); }); }); // packages/engine/Specs/Core/EncodedCartesian3Spec.js var import__206 = __toESM(require_Cesium(), 1); describe("Core/EncodedCartesian3", function() { it("construct with default values", function() { const encoded = new import__206.EncodedCartesian3(); expect(encoded.high).toEqual(import__206.Cartesian3.ZERO); expect(encoded.low).toEqual(import__206.Cartesian3.ZERO); }); it("endcode encodes a positive value", function() { const encoded = import__206.EncodedCartesian3.encode(-1e7); expect(encoded.high + encoded.low).toEqual(-1e7); }); it("endcode encodes a negative value", function() { const encoded = import__206.EncodedCartesian3.encode(1e7); expect(encoded.high + encoded.low).toEqual(1e7); }); it("endcode encodes with a result parameter", function() { const result = { high: 0, low: 0 }; const returnedResult = import__206.EncodedCartesian3.encode(0, result); expect(result).toBe(returnedResult); expect(returnedResult.high + returnedResult.low).toEqual(0); }); it("fromCartesian encodes a cartesian", function() { const c = new import__206.Cartesian3(-1e7, 0, 1e7); const encoded = import__206.EncodedCartesian3.fromCartesian(c); expect(encoded.high.x + encoded.low.x).toEqual(-1e7); expect(encoded.high.y + encoded.low.y).toEqual(0); expect(encoded.high.z + encoded.low.z).toEqual(1e7); }); it("fromCartesian encodes a cartesian with a result parameter", function() { const p = new import__206.Cartesian3(-1e7, 0, 1e7); const encoded = import__206.EncodedCartesian3.fromCartesian(p); const positions = new Float32Array(6); import__206.EncodedCartesian3.writeElements(p, positions, 0); expect(encoded.high.x).toEqual(positions[0]); expect(encoded.high.y).toEqual(positions[1]); expect(encoded.high.z).toEqual(positions[2]); expect(encoded.low.x).toEqual(positions[3]); expect(encoded.low.y).toEqual(positions[4]); expect(encoded.low.z).toEqual(positions[5]); }); it("writeElements encodes a cartesian", function() { const c = new import__206.Cartesian3(-1e7, 0, 1e7); const encoded = new import__206.EncodedCartesian3(); const encoded2 = import__206.EncodedCartesian3.fromCartesian(c, encoded); expect(encoded2).toBe(encoded); expect(encoded.high.x + encoded.low.x).toEqual(-1e7); expect(encoded.high.y + encoded.low.y).toEqual(0); expect(encoded.high.z + encoded.low.z).toEqual(1e7); }); it("encode throws without a value", function() { expect(function() { import__206.EncodedCartesian3.encode(); }).toThrowDeveloperError(); }); it("fromCartesian throws without a cartesian", function() { expect(function() { import__206.EncodedCartesian3.fromCartesian(); }).toThrowDeveloperError(); }); it("writeElements throws without a cartesian", function() { expect(function() { import__206.EncodedCartesian3.writeElements(); }).toThrowDeveloperError(); }); it("writeElements throws without a cartesianArray", function() { expect(function() { import__206.EncodedCartesian3.writeElements(new import__206.Cartesian3()); }).toThrowDeveloperError(); }); it("writeElements throws without an index", function() { expect(function() { import__206.EncodedCartesian3.writeElements(new import__206.Cartesian3(), new Float32Array(6)); }).toThrowDeveloperError(); }); it("writeElements throws with a negative index", function() { expect(function() { import__206.EncodedCartesian3.writeElements( new import__206.Cartesian3(), new Float32Array(6), -1 ); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/EventSpec.js var import__207 = __toESM(require_Cesium(), 1); describe("Core/Event", function() { let event; let spyListener; beforeEach(function() { event = new import__207.Event(); spyListener = jasmine.createSpy("listener"); }); it("works with no scope", function() { const someValue = 123; event.addEventListener(spyListener); event.raiseEvent(someValue); expect(spyListener).toHaveBeenCalledWith(someValue); spyListener.calls.reset(); event.removeEventListener(spyListener); event.raiseEvent(someValue); expect(spyListener).not.toHaveBeenCalled(); }); it("works with scope", function() { const someValue = 123; const scope = {}; event.addEventListener(spyListener, scope); event.raiseEvent(someValue); expect(spyListener).toHaveBeenCalledWith(someValue); expect(spyListener.calls.first().object).toBe(scope); spyListener.calls.reset(); event.removeEventListener(spyListener, scope); event.raiseEvent(someValue); expect(spyListener).not.toHaveBeenCalled(); }); it("can remove from within a callback", function() { const doNothing = function(evt) { }; const removeEventCb = function(evt) { event.removeEventListener(removeEventCb); }; const doNothing2 = function(evt) { }; event.addEventListener(doNothing); event.addEventListener(removeEventCb); event.addEventListener(doNothing2); event.raiseEvent(); expect(event.numberOfListeners).toEqual(2); event.removeEventListener(doNothing); event.removeEventListener(doNothing2); expect(event.numberOfListeners).toEqual(0); }); it("can remove multiple listeners within a callback", function() { const removeEvent0 = event.addEventListener(function() { removeEvent0(); }); event.addEventListener(function() { }); const removeEvent2 = event.addEventListener(function() { removeEvent2(); }); event.addEventListener(function() { }); const removeEvent4 = event.addEventListener(function() { removeEvent4(); }); event.addEventListener(function() { }); const removeEvent6 = event.addEventListener(function() { removeEvent6(); }); event.addEventListener(function() { }); const removeEvent8 = event.addEventListener(function() { removeEvent8(); }); event.addEventListener(function() { }); expect(event.numberOfListeners).toEqual(10); event.raiseEvent(); expect(event.numberOfListeners).toEqual(5); event.raiseEvent(); expect(event.numberOfListeners).toEqual(5); }); it("addEventListener and removeEventListener works with same function of different scopes", function() { const Scope = function() { this.timesCalled = 0; }; Scope.prototype.myCallback = function() { this.timesCalled++; }; const scope1 = new Scope(); const scope2 = new Scope(); event.addEventListener(Scope.prototype.myCallback, scope1); event.addEventListener(Scope.prototype.myCallback, scope2); event.raiseEvent(); expect(scope1.timesCalled).toEqual(1); expect(scope2.timesCalled).toEqual(1); event.removeEventListener(Scope.prototype.myCallback, scope1); expect(event.numberOfListeners).toEqual(1); event.raiseEvent(); expect(scope1.timesCalled).toEqual(1); expect(scope2.timesCalled).toEqual(2); event.removeEventListener(Scope.prototype.myCallback, scope2); expect(event.numberOfListeners).toEqual(0); }); it("numberOfListeners returns the correct number", function() { const callback1 = function() { }; const callback2 = function() { }; expect(event.numberOfListeners).toEqual(0); event.addEventListener(callback1); expect(event.numberOfListeners).toEqual(1); event.addEventListener(callback2); expect(event.numberOfListeners).toEqual(2); event.removeEventListener(callback2); expect(event.numberOfListeners).toEqual(1); }); it("removeEventListener indicates if the listener is registered with the event", function() { const callback = function() { }; event.addEventListener(callback); expect(event.numberOfListeners).toEqual(1); expect(event.removeEventListener(callback)).toEqual(true); expect(event.numberOfListeners).toEqual(0); expect(event.removeEventListener(callback)).toEqual(false); }); it("removeEventListener does not remove a registered listener of a different scope", function() { const myFunc = function() { }; const scope = {}; event.addEventListener(myFunc, scope); expect(event.removeEventListener(myFunc)).toEqual(false); }); it("works with no listeners", function() { event.raiseEvent(123); }); it("addEventListener returns a function allowing removal", function() { const someValue = 123; const remove = event.addEventListener(spyListener); event.raiseEvent(someValue); expect(spyListener).toHaveBeenCalledWith(someValue); spyListener.calls.reset(); remove(); event.raiseEvent(someValue); expect(spyListener).not.toHaveBeenCalled(); }); it("addEventListener with scope returns a function allowing removal", function() { const someValue = 123; const scope = {}; const remove = event.addEventListener(spyListener, scope); event.raiseEvent(someValue); expect(spyListener).toHaveBeenCalledWith(someValue); spyListener.calls.reset(); remove(); event.raiseEvent(someValue); expect(spyListener).not.toHaveBeenCalled(); }); it("addEventListener throws with undefined listener", function() { expect(function() { event.addEventListener(void 0); }).toThrowDeveloperError(); }); it("addEventListener throws with null listener", function() { expect(function() { event.addEventListener(null); }).toThrowDeveloperError(); }); it("addEventListener throws with non-function listener", function() { expect(function() { event.addEventListener({}); }).toThrowDeveloperError(); }); it("removeEventListener throws with undefined listener", function() { expect(function() { event.removeEventListener(void 0); }).toThrowDeveloperError(); }); it("removeEventListener throws with null listener", function() { expect(function() { event.removeEventListener(null); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/FeatureDetectionSpec.js var import__208 = __toESM(require_Cesium(), 1); describe("Core/FeatureDetection", function() { it("detects fullscreen support", function() { const supportsFullscreen = import__208.FeatureDetection.supportsFullscreen(); expect(typeof supportsFullscreen).toEqual("boolean"); }); it("detects web worker support", function() { const supportsWebWorkers = import__208.FeatureDetection.supportsWebWorkers(); expect(typeof supportsWebWorkers).toEqual("boolean"); }); it("detects typed array support", function() { const supportsTypedArrays = import__208.FeatureDetection.supportsTypedArrays(); expect(typeof supportsTypedArrays).toEqual("boolean"); }); it("detects BigInt64Array support", function() { const supportsBigInt64Array = import__208.FeatureDetection.supportsBigInt64Array(); expect(typeof supportsBigInt64Array).toEqual("boolean"); }); it("detects BigUint64Array support", function() { const supportsBigUint64Array = import__208.FeatureDetection.supportsBigUint64Array(); expect(typeof supportsBigUint64Array).toEqual("boolean"); }); it("detects BigInt support", function() { const supportsBigInt = import__208.FeatureDetection.supportsBigInt(); expect(typeof supportsBigInt).toEqual("boolean"); }); it("detects web assembly support", function() { const supportsWebAssembly = import__208.FeatureDetection.supportsWebAssembly(); expect(typeof supportsWebAssembly).toEqual("boolean"); }); function checkVersionArray(array) { expect(Array.isArray(array)).toEqual(true); array.forEach(function(d) { expect(typeof d).toEqual("number"); }); } it("detects Chrome", function() { const isChrome = import__208.FeatureDetection.isChrome(); expect(typeof isChrome).toEqual("boolean"); if (isChrome) { const chromeVersion = import__208.FeatureDetection.chromeVersion(); checkVersionArray(chromeVersion); console.log(`detected Chrome ${chromeVersion.join(".")}`); } }); it("detects Safari", function() { const isSafari = import__208.FeatureDetection.isSafari(); expect(typeof isSafari).toEqual("boolean"); if (isSafari) { const safariVersion = import__208.FeatureDetection.safariVersion(); checkVersionArray(safariVersion); console.log(`detected Safari ${safariVersion.join(".")}`); } }); it("detects Webkit", function() { const isWebkit = import__208.FeatureDetection.isWebkit(); expect(typeof isWebkit).toEqual("boolean"); if (isWebkit) { const webkitVersion = import__208.FeatureDetection.webkitVersion(); checkVersionArray(webkitVersion); expect(typeof webkitVersion.isNightly).toEqual("boolean"); console.log( `detected Webkit ${webkitVersion.join(".")}${webkitVersion.isNightly ? " (Nightly)" : ""}` ); } }); it("detects Internet Explorer", function() { const isInternetExplorer = import__208.FeatureDetection.isInternetExplorer(); expect(typeof isInternetExplorer).toEqual("boolean"); if (isInternetExplorer) { const internetExplorerVersion = import__208.FeatureDetection.internetExplorerVersion(); checkVersionArray(internetExplorerVersion); console.log( `detected Internet Explorer ${internetExplorerVersion.join(".")}` ); } }); it("detects Edge", function() { const isEdge = import__208.FeatureDetection.isEdge(); expect(typeof isEdge).toEqual("boolean"); if (isEdge) { const edgeVersion = import__208.FeatureDetection.edgeVersion(); checkVersionArray(edgeVersion); console.log(`detected Edge ${edgeVersion.join(".")}`); } }); it("detects Firefox", function() { const isFirefox = import__208.FeatureDetection.isFirefox(); expect(typeof isFirefox).toEqual("boolean"); if (isFirefox) { const firefoxVersion = import__208.FeatureDetection.firefoxVersion(); checkVersionArray(firefoxVersion); console.log(`detected Firefox ${firefoxVersion.join(".")}`); } }); it("detects iPad or iOS", function() { const iPadOrIOS = import__208.FeatureDetection.isIPadOrIOS(); expect(typeof iPadOrIOS).toEqual("boolean"); }); it("detects imageRendering support", function() { const supportsImageRenderingPixelated = import__208.FeatureDetection.supportsImageRenderingPixelated(); expect(typeof supportsImageRenderingPixelated).toEqual("boolean"); if (supportsImageRenderingPixelated) { expect(import__208.FeatureDetection.imageRenderingValue()).toBeDefined(); } else { expect(import__208.FeatureDetection.imageRenderingValue()).not.toBeDefined(); } }); it("supportWebP throws when it has not been initialized", function() { import__208.FeatureDetection.supportsWebP._promise = void 0; import__208.FeatureDetection.supportsWebP._result = void 0; expect(function() { import__208.FeatureDetection.supportsWebP(); }).toThrowDeveloperError(); }); it("detects WebP support", function() { import__208.FeatureDetection.supportsWebP._promise = void 0; import__208.FeatureDetection.supportsWebP._result = void 0; return import__208.FeatureDetection.supportsWebP.initialize().then(function(supportsWebP) { expect(typeof supportsWebP).toEqual("boolean"); expect(import__208.FeatureDetection.supportsWebP()).toEqual(supportsWebP); }); }); it("detects WebGL2 support", function() { const scene2 = createScene_default(); expect(import__208.FeatureDetection.supportsWebgl2(scene2)).toEqual( scene2.context.webgl2 ); scene2.destroyForSpecs(); }); }); // packages/engine/Specs/Core/FrustumGeometrySpec.js var import__209 = __toESM(require_Cesium(), 1); var import__210 = __toESM(require_Cesium(), 1); describe("Core/FrustumGeometry", function() { it("constructor throws without options", function() { expect(function() { return new import__209.FrustumGeometry(); }).toThrowDeveloperError(); }); it("constructor throws without frustum", function() { expect(function() { return new import__209.FrustumGeometry({ origin: import__209.Cartesian3.ZERO, orientation: import__209.Quaternion.IDENTITY }); }).toThrowDeveloperError(); }); it("constructor throws without position", function() { expect(function() { return new import__209.FrustumGeometry({ frustum: new import__209.PerspectiveFrustum(), orientation: import__209.Quaternion.IDENTITY }); }).toThrowDeveloperError(); }); it("constructor throws without orientation", function() { expect(function() { return new import__209.FrustumGeometry({ frustum: new import__209.PerspectiveFrustum(), origin: import__209.Cartesian3.ZERO }); }).toThrowDeveloperError(); }); it("constructor computes all vertex attributes", function() { const frustum = new import__209.PerspectiveFrustum(); frustum.fov = import__210.Math.toRadians(30); frustum.aspectRatio = 1920 / 1080; frustum.near = 1; frustum.far = 3; const m = import__209.FrustumGeometry.createGeometry( new import__209.FrustumGeometry({ frustum, origin: import__209.Cartesian3.ZERO, orientation: import__209.Quaternion.IDENTITY, vertexFormat: import__209.VertexFormat.ALL }) ); const numVertices = 24; const numTriangles = 12; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.attributes.normal.values.length).toEqual(numVertices * 3); expect(m.attributes.tangent.values.length).toEqual(numVertices * 3); expect(m.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(m.attributes.st.values.length).toEqual(numVertices * 2); expect(m.indices.length).toEqual(numTriangles * 3); expect(m.boundingSphere.center).toEqual(new import__209.Cartesian3(0, 0, 2)); expect(m.boundingSphere.radius).toBeGreaterThan(1); expect(m.boundingSphere.radius).toBeLessThan(2); }); const packableFrustum = new import__209.PerspectiveFrustum(); packableFrustum.fov = 1; packableFrustum.aspectRatio = 2; packableFrustum.near = 3; packableFrustum.far = 4; createPackableSpecs_default( import__209.FrustumGeometry, new import__209.FrustumGeometry({ frustum: packableFrustum, origin: import__209.Cartesian3.ZERO, orientation: import__209.Quaternion.IDENTITY, vertexFormat: import__209.VertexFormat.POSITION_ONLY }), [ 0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1 ] ); }); // packages/engine/Specs/Core/FrustumOutlineGeometrySpec.js var import__211 = __toESM(require_Cesium(), 1); var import__212 = __toESM(require_Cesium(), 1); describe("Core/FrustumOutlineGeometry", function() { it("constructor throws without options", function() { expect(function() { return new import__211.FrustumOutlineGeometry(); }).toThrowDeveloperError(); }); it("constructor throws without frustum", function() { expect(function() { return new import__211.FrustumOutlineGeometry({ origin: import__211.Cartesian3.ZERO, orientation: import__211.Quaternion.IDENTITY }); }).toThrowDeveloperError(); }); it("constructor throws without position", function() { expect(function() { return new import__211.FrustumOutlineGeometry({ frustum: new import__211.PerspectiveFrustum(), orientation: import__211.Quaternion.IDENTITY }); }).toThrowDeveloperError(); }); it("constructor throws without orientation", function() { expect(function() { return new import__211.FrustumOutlineGeometry({ frustum: new import__211.PerspectiveFrustum(), origin: import__211.Cartesian3.ZERO }); }).toThrowDeveloperError(); }); it("constructor computes all vertex attributes", function() { const frustum = new import__211.PerspectiveFrustum(); frustum.fov = import__212.Math.toRadians(30); frustum.aspectRatio = 1920 / 1080; frustum.near = 1; frustum.far = 3; const m = import__211.FrustumOutlineGeometry.createGeometry( new import__211.FrustumOutlineGeometry({ frustum, origin: import__211.Cartesian3.ZERO, orientation: import__211.Quaternion.IDENTITY }) ); const numVertices = 8; const numLines = 12; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numLines * 2); expect(m.boundingSphere.center).toEqual(new import__211.Cartesian3(0, 0, 2)); expect(m.boundingSphere.radius).toBeGreaterThan(1); expect(m.boundingSphere.radius).toBeLessThan(2); }); const packableFrustum = new import__211.PerspectiveFrustum(); packableFrustum.fov = 1; packableFrustum.aspectRatio = 2; packableFrustum.near = 3; packableFrustum.far = 4; createPackableSpecs_default( import__211.FrustumOutlineGeometry, new import__211.FrustumOutlineGeometry({ frustum: packableFrustum, origin: import__211.Cartesian3.ZERO, orientation: import__211.Quaternion.IDENTITY, vertexFormat: import__211.VertexFormat.POSITION_ONLY }), [0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1] ); }); // packages/engine/Specs/Core/FullscreenSpec.js var import__213 = __toESM(require_Cesium(), 1); describe("Core/Fullscreen", function() { it("can tell if fullscreen is supported", function() { expect(import__213.Fullscreen.supportsFullscreen()).toBeDefined(); }); it("can tell if fullscreen is enabled", function() { if (import__213.Fullscreen.supportsFullscreen()) { expect(import__213.Fullscreen.enabled).toBeDefined(); } else { expect(import__213.Fullscreen.enabled).toBeUndefined(); } }); it("can get fullscreen element", function() { if (import__213.Fullscreen.supportsFullscreen()) { expect(import__213.Fullscreen.element).toBeNull(); } else { expect(import__213.Fullscreen.element).toBeUndefined(); } }); it("can tell if the browser is in fullscreen", function() { if (import__213.Fullscreen.supportsFullscreen()) { expect(import__213.Fullscreen.fullscreen).toEqual(false); } else { expect(import__213.Fullscreen.fullscreen).toBeUndefined(); } }); it("can request fullscreen", function() { if (import__213.Fullscreen.supportsFullscreen()) { spyOn(document.body, import__213.Fullscreen._names.requestFullscreen); spyOn(document, import__213.Fullscreen._names.exitFullscreen); import__213.Fullscreen.requestFullscreen(document.body); expect( document.body[import__213.Fullscreen._names.requestFullscreen] ).toHaveBeenCalled(); import__213.Fullscreen.exitFullscreen(); expect(document[import__213.Fullscreen._names.exitFullscreen]).toHaveBeenCalled(); } else { import__213.Fullscreen.requestFullscreen(document.body); import__213.Fullscreen.exitFullscreen(); } }); if (!import__213.FeatureDetection.isInternetExplorer()) { it("can get the fullscreen change event name", function() { if (import__213.Fullscreen.supportsFullscreen()) { expect(document[`on${import__213.Fullscreen.changeEventName}`]).toBeDefined(); } else { expect(import__213.Fullscreen.changeEventName).toBeUndefined(); } }); it("can get the fullscreen error event name", function() { if (import__213.Fullscreen.supportsFullscreen()) { expect(document[`on${import__213.Fullscreen.errorEventName}`]).toBeDefined(); } else { expect(import__213.Fullscreen.errorEventName).toBeUndefined(); } }); } }); // packages/engine/Specs/Core/GeographicProjectionSpec.js var import__214 = __toESM(require_Cesium(), 1); var import__215 = __toESM(require_Cesium(), 1); describe("Core/GeographicProjection", function() { it("construct0", function() { const projection = new import__214.GeographicProjection(); expect(projection.ellipsoid).toEqual(import__214.Ellipsoid.WGS84); }); it("construct1", function() { const ellipsoid = import__214.Ellipsoid.UNIT_SPHERE; const projection = new import__214.GeographicProjection(ellipsoid); expect(projection.ellipsoid).toEqual(ellipsoid); }); it("project0", function() { const height = 10; const cartographic = new import__214.Cartographic(0, 0, height); const projection = new import__214.GeographicProjection(); expect(projection.project(cartographic)).toEqual( new import__214.Cartesian3(0, 0, height) ); }); it("project1", function() { const ellipsoid = import__214.Ellipsoid.WGS84; const cartographic = new import__214.Cartographic(Math.PI, import__215.Math.PI_OVER_TWO, 0); const expected = new import__214.Cartesian3( Math.PI * ellipsoid.radii.x, import__215.Math.PI_OVER_TWO * ellipsoid.radii.x, 0 ); const projection = new import__214.GeographicProjection(ellipsoid); expect(projection.project(cartographic)).toEqual(expected); }); it("project2", function() { const ellipsoid = import__214.Ellipsoid.UNIT_SPHERE; const cartographic = new import__214.Cartographic( -Math.PI, import__215.Math.PI_OVER_TWO, 0 ); const expected = new import__214.Cartesian3(-Math.PI, import__215.Math.PI_OVER_TWO, 0); const projection = new import__214.GeographicProjection(ellipsoid); expect(projection.project(cartographic)).toEqual(expected); }); it("project3", function() { const ellipsoid = import__214.Ellipsoid.WGS84; const cartographic = new import__214.Cartographic(Math.PI, import__215.Math.PI_OVER_TWO, 0); const expected = new import__214.Cartesian3( Math.PI * ellipsoid.radii.x, import__215.Math.PI_OVER_TWO * ellipsoid.radii.x, 0 ); const projection = new import__214.GeographicProjection(ellipsoid); const result = new import__214.Cartesian3(0, 0, 0); const returnValue = projection.project(cartographic, result); expect(result).toEqual(returnValue); expect(result).toEqual(expected); }); it("unproject0", function() { const cartographic = new import__214.Cartographic( import__215.Math.PI_OVER_TWO, import__215.Math.PI_OVER_FOUR, 12 ); const projection = new import__214.GeographicProjection(); const projected = projection.project(cartographic); expect(projection.unproject(projected)).toEqual(cartographic); }); it("unproject1", function() { const cartographic = new import__214.Cartographic( import__215.Math.PI_OVER_TWO, import__215.Math.PI_OVER_FOUR, 12 ); const projection = new import__214.GeographicProjection(); const projected = projection.project(cartographic); const result = new import__214.Cartographic(0, 0, 0); const returnValue = projection.unproject(projected, result); expect(result).toEqual(returnValue); expect(result).toEqual(cartographic); }); it("project throws without cartesian", function() { const projection = new import__214.GeographicProjection(); expect(function() { return projection.unproject(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/GeographicTilingSchemeSpec.js var import__216 = __toESM(require_Cesium(), 1); var import__217 = __toESM(require_Cesium(), 1); describe("Core/GeographicTilingScheme", function() { it("conforms to TilingScheme interface.", function() { expect(import__216.GeographicTilingScheme).toConformToInterface(import__216.TilingScheme); }); describe("Conversions from tile indices to cartographic rectangles.", function() { it("tileXYToRectangle returns full rectangle for single root tile.", function() { const tilingScheme = new import__216.GeographicTilingScheme({ numberOfLevelZeroTilesX: 1, numberOfLevelZeroTilesY: 1 }); const tilingSchemeRectangle = tilingScheme.rectangle; const rectangle = tilingScheme.tileXYToRectangle(0, 0, 0); expect(rectangle.west).toEqualEpsilon( tilingSchemeRectangle.west, import__217.Math.EPSILON10 ); expect(rectangle.south).toEqualEpsilon( tilingSchemeRectangle.south, import__217.Math.EPSILON10 ); expect(rectangle.east).toEqualEpsilon( tilingSchemeRectangle.east, import__217.Math.EPSILON10 ); expect(rectangle.north).toEqualEpsilon( tilingSchemeRectangle.north, import__217.Math.EPSILON10 ); }); it("tileXYToRectangle uses result parameter if provided", function() { const tilingScheme = new import__216.GeographicTilingScheme({ numberOfLevelZeroTilesX: 1, numberOfLevelZeroTilesY: 1 }); const tilingSchemeRectangle = tilingScheme.rectangle; const result = new import__216.Rectangle(0, 0, 0); const rectangle = tilingScheme.tileXYToRectangle(0, 0, 0, result); expect(result).toEqual(rectangle); expect(rectangle.west).toEqualEpsilon( tilingSchemeRectangle.west, import__217.Math.EPSILON10 ); expect(rectangle.south).toEqualEpsilon( tilingSchemeRectangle.south, import__217.Math.EPSILON10 ); expect(rectangle.east).toEqualEpsilon( tilingSchemeRectangle.east, import__217.Math.EPSILON10 ); expect(rectangle.north).toEqualEpsilon( tilingSchemeRectangle.north, import__217.Math.EPSILON10 ); }); it("tiles are numbered from the northwest corner.", function() { const tilingScheme = new import__216.GeographicTilingScheme({ numberOfLevelZeroTilesX: 2, numberOfLevelZeroTilesY: 2 }); const northwest = tilingScheme.tileXYToRectangle(0, 0, 1); const northeast = tilingScheme.tileXYToRectangle(1, 0, 1); const southeast = tilingScheme.tileXYToRectangle(1, 1, 1); const southwest = tilingScheme.tileXYToRectangle(0, 1, 1); expect(northeast.north).toEqual(northwest.north); expect(northeast.south).toEqual(northwest.south); expect(southeast.north).toEqual(southwest.north); expect(southeast.south).toEqual(southwest.south); expect(northwest.west).toEqual(southwest.west); expect(northwest.east).toEqual(southwest.east); expect(northeast.west).toEqual(southeast.west); expect(northeast.east).toEqual(southeast.east); expect(northeast.north).toBeGreaterThan(southeast.north); expect(northeast.south).toBeGreaterThan(southeast.south); expect(northwest.north).toBeGreaterThan(southwest.north); expect(northwest.south).toBeGreaterThan(southwest.south); expect(northeast.east).toBeGreaterThan(northwest.east); expect(northeast.west).toBeGreaterThan(northwest.west); expect(southeast.east).toBeGreaterThan(southwest.east); expect(southeast.west).toBeGreaterThan(southwest.west); }); it("adjacent tiles have overlapping coordinates", function() { const tilingScheme = new import__216.GeographicTilingScheme({ numberOfLevelZeroTilesX: 2, numberOfLevelZeroTilesY: 2 }); const northwest = tilingScheme.tileXYToRectangle(0, 0, 1); const northeast = tilingScheme.tileXYToRectangle(1, 0, 1); const southeast = tilingScheme.tileXYToRectangle(1, 1, 1); const southwest = tilingScheme.tileXYToRectangle(0, 1, 1); expect(northeast.south).toEqualEpsilon( southeast.north, import__217.Math.EPSILON15 ); expect(northwest.south).toEqualEpsilon( southwest.north, import__217.Math.EPSILON15 ); expect(northeast.west).toEqualEpsilon( northwest.east, import__217.Math.EPSILON15 ); expect(southeast.west).toEqualEpsilon( southwest.east, import__217.Math.EPSILON15 ); }); }); it("uses a GeographicProjection", function() { const tilingScheme = new import__216.GeographicTilingScheme(); expect(tilingScheme.projection).toBeInstanceOf(import__216.GeographicProjection); }); describe("rectangleToNativeRectangle", function() { it("converts radians to degrees", function() { const tilingScheme = new import__216.GeographicTilingScheme(); const rectangleInRadians = new import__216.Rectangle(0.1, 0.2, 0.3, 0.4); const nativeRectangle = tilingScheme.rectangleToNativeRectangle( rectangleInRadians ); expect(nativeRectangle.west).toEqualEpsilon( rectangleInRadians.west * 180 / Math.PI, import__217.Math.EPSILON13 ); expect(nativeRectangle.south).toEqualEpsilon( rectangleInRadians.south * 180 / Math.PI, import__217.Math.EPSILON13 ); expect(nativeRectangle.east).toEqualEpsilon( rectangleInRadians.east * 180 / Math.PI, import__217.Math.EPSILON13 ); expect(nativeRectangle.north).toEqualEpsilon( rectangleInRadians.north * 180 / Math.PI, import__217.Math.EPSILON13 ); }); it("uses result parameter if provided", function() { const tilingScheme = new import__216.GeographicTilingScheme(); const rectangleInRadians = new import__216.Rectangle(0.1, 0.2, 0.3, 0.4); const resultRectangle = new import__216.Rectangle(0, 0, 0, 0); const outputRectangle = tilingScheme.rectangleToNativeRectangle( rectangleInRadians, resultRectangle ); expect(outputRectangle).toEqual(resultRectangle); expect(resultRectangle.west).toEqualEpsilon( rectangleInRadians.west * 180 / Math.PI, import__217.Math.EPSILON13 ); expect(resultRectangle.south).toEqualEpsilon( rectangleInRadians.south * 180 / Math.PI, import__217.Math.EPSILON13 ); expect(resultRectangle.east).toEqualEpsilon( rectangleInRadians.east * 180 / Math.PI, import__217.Math.EPSILON13 ); expect(resultRectangle.north).toEqualEpsilon( rectangleInRadians.north * 180 / Math.PI, import__217.Math.EPSILON13 ); }); }); describe("positionToTileXY", function() { it("returns undefined when outside rectangle", function() { const tilingScheme = new import__216.GeographicTilingScheme({ rectangle: new import__216.Rectangle(0.1, 0.2, 0.3, 0.4) }); const tooFarWest = new import__216.Cartographic(0.05, 0.3); expect(tilingScheme.positionToTileXY(tooFarWest, 0)).toBeUndefined(); const tooFarSouth = new import__216.Cartographic(0.2, 0.1); expect(tilingScheme.positionToTileXY(tooFarSouth, 0)).toBeUndefined(); const tooFarEast = new import__216.Cartographic(0.4, 0.3); expect(tilingScheme.positionToTileXY(tooFarEast, 0)).toBeUndefined(); const tooFarNorth = new import__216.Cartographic(0.2, 0.5); expect(tilingScheme.positionToTileXY(tooFarNorth, 0)).toBeUndefined(); }); it("returns correct tile for position in center of tile", function() { const tilingScheme = new import__216.GeographicTilingScheme(); const centerOfWesternRootTile = new import__216.Cartographic(-Math.PI / 2, 0); expect(tilingScheme.positionToTileXY(centerOfWesternRootTile, 0)).toEqual( new import__216.Cartesian2(0, 0) ); const centerOfNortheastChildOfEasternRootTile = new import__216.Cartographic( 3 * Math.PI / 4, Math.PI / 2 ); expect( tilingScheme.positionToTileXY( centerOfNortheastChildOfEasternRootTile, 1 ) ).toEqual(new import__216.Cartesian2(3, 0)); }); it("returns Southeast tile when on the boundary between tiles", function() { const tilingScheme = new import__216.GeographicTilingScheme(); const centerOfMap = new import__216.Cartographic(0, 0); expect(tilingScheme.positionToTileXY(centerOfMap, 1)).toEqual( new import__216.Cartesian2(2, 1) ); }); it("does not return tile outside valid range", function() { const tilingScheme = new import__216.GeographicTilingScheme(); const southeastCorner = new import__216.Cartographic(Math.PI, -Math.PI / 2); expect(tilingScheme.positionToTileXY(southeastCorner, 0)).toEqual( new import__216.Cartesian2(1, 0) ); }); it("uses result parameter if supplied", function() { const tilingScheme = new import__216.GeographicTilingScheme(); const centerOfNortheastChildOfEasternRootTile = new import__216.Cartographic( 3 * Math.PI / 4, Math.PI / 2 ); const resultParameter = new import__216.Cartesian2(0, 0); const returnedResult = tilingScheme.positionToTileXY( centerOfNortheastChildOfEasternRootTile, 1, resultParameter ); expect(resultParameter).toEqual(returnedResult); expect(resultParameter).toEqual(new import__216.Cartesian2(3, 0)); }); }); }); // packages/engine/Specs/Core/GeometryAttributeSpec.js var import__218 = __toESM(require_Cesium(), 1); describe("Core/GeometryAttribute", function() { it("constructor", function() { const color = new import__218.GeometryAttribute({ componentDatatype: import__218.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 4, normalize: true, values: new Uint8Array([255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255]) }); expect(color.componentDatatype).toEqual(import__218.ComponentDatatype.UNSIGNED_BYTE); expect(color.componentsPerAttribute).toEqual(4); expect(color.normalize).toEqual(true); expect(color.values).toEqual([ 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255 ]); }); it("constructor throws without componentDatatype", function() { expect(function() { return new import__218.GeometryAttribute({ componentsPerAttribute: 4, values: new Uint8Array([ 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255 ]) }); }).toThrowDeveloperError(); }); it("constructor throws without componentsPerAttribute", function() { expect(function() { return new import__218.GeometryAttribute({ componentDatatype: import__218.ComponentDatatype.UNSIGNED_BYTE, values: new Uint8Array([ 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255 ]) }); }).toThrowDeveloperError(); }); it("constructor throws when componentsPerAttribute is less than 1 or greater than 4", function() { expect(function() { return new import__218.GeometryAttribute({ componentDatatype: import__218.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 7, values: new Uint8Array([ 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255 ]) }); }).toThrowDeveloperError(); }); it("constructor throws without values", function() { expect(function() { return new import__218.GeometryAttribute({ componentDatatype: import__218.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 4 }); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/GeometryInstanceAttributeSpec.js var import__219 = __toESM(require_Cesium(), 1); describe("Core/GeometryInstanceAttribute", function() { it("constructor", function() { const color = new import__219.GeometryInstanceAttribute({ componentDatatype: import__219.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 4, normalize: true, value: new Uint8Array([255, 255, 0, 255]) }); expect(color.componentDatatype).toEqual(import__219.ComponentDatatype.UNSIGNED_BYTE); expect(color.componentsPerAttribute).toEqual(4); expect(color.normalize).toEqual(true); expect(color.value).toEqual([255, 255, 0, 255]); }); it("constructor throws without componentDatatype", function() { expect(function() { return new import__219.GeometryInstanceAttribute({ componentsPerAttribute: 4, value: new Uint8Array([255, 255, 0, 255]) }); }).toThrowDeveloperError(); }); it("constructor throws without componentsPerAttribute", function() { expect(function() { return new import__219.GeometryInstanceAttribute({ componentDatatype: import__219.ComponentDatatype.UNSIGNED_BYTE, value: new Uint8Array([255, 255, 0, 255]) }); }).toThrowDeveloperError(); }); it("constructor throws when componentsPerAttribute is less than 1 or greater than 4", function() { expect(function() { return new import__219.GeometryInstanceAttribute({ componentDatatype: import__219.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 7, value: new Uint8Array([255, 255, 0, 255]) }); }).toThrowDeveloperError(); }); it("constructor throws without values", function() { expect(function() { return new import__219.GeometryInstanceAttribute({ componentDatatype: import__219.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 4 }); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/GeometryInstanceSpec.js var import__220 = __toESM(require_Cesium(), 1); describe("Core/GeometryInstance", function() { it("constructor", function() { const geometry = new import__220.Geometry({ attributes: { position: new import__220.GeometryAttribute({ componentDatatype: import__220.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ 0, 0, 0, 1, 0, 0, 0, 1, 0 ]) }) }, indices: new Uint16Array([0, 1, 2]), primitiveType: import__220.PrimitiveType.TRIANGLES, boundingSphere: new import__220.BoundingSphere(new import__220.Cartesian3(0.5, 0.5, 0), 1) }); const modelMatrix = import__220.Matrix4.multiplyByTranslation( import__220.Matrix4.IDENTITY, new import__220.Cartesian3(0, 0, 9e6), new import__220.Matrix4() ); const attributes = { color: new import__220.GeometryInstanceAttribute({ componentDatatype: import__220.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 4, normalize: true, value: new Uint8Array([255, 255, 0, 255]) }) }; const instance = new import__220.GeometryInstance({ geometry, modelMatrix, id: "geometry", attributes }); expect(instance.geometry).toBe(geometry); expect(instance.modelMatrix).toEqual(modelMatrix); expect(instance.id).toEqual("geometry"); expect(attributes).toBe(attributes); }); it("constructor throws without geometry", function() { expect(function() { return new import__220.GeometryInstance(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/GeometryPipelineSpec.js var import__221 = __toESM(require_Cesium(), 1); var import__222 = __toESM(require_Cesium(), 1); describe("Core/GeometryPipeline", function() { it("converts triangles to wireframe in place", function() { const geometry = import__221.GeometryPipeline.toWireframe( new import__221.Geometry({ attributes: {}, indices: [0, 1, 2, 3, 4, 5], primitiveType: import__221.PrimitiveType.TRIANGLES }) ); expect(geometry.primitiveType).toEqual(import__221.PrimitiveType.LINES); const v = geometry.indices; expect(v.length).toEqual(12); expect(v[0]).toEqual(0); expect(v[1]).toEqual(1); expect(v[2]).toEqual(1); expect(v[3]).toEqual(2); expect(v[4]).toEqual(2); expect(v[5]).toEqual(0); expect(v[6]).toEqual(3); expect(v[7]).toEqual(4); expect(v[8]).toEqual(4); expect(v[9]).toEqual(5); expect(v[10]).toEqual(5); expect(v[11]).toEqual(3); }); it("converts a triangle fan to wireframe in place", function() { const geometry = import__221.GeometryPipeline.toWireframe( new import__221.Geometry({ attributes: {}, indices: [0, 1, 2, 3], primitiveType: import__221.PrimitiveType.TRIANGLE_FAN }) ); expect(geometry.primitiveType).toEqual(import__221.PrimitiveType.LINES); const v = geometry.indices; expect(v.length).toEqual(12); expect(v[0]).toEqual(0); expect(v[1]).toEqual(1); expect(v[2]).toEqual(1); expect(v[3]).toEqual(2); expect(v[4]).toEqual(2); expect(v[5]).toEqual(0); expect(v[6]).toEqual(0); expect(v[7]).toEqual(2); expect(v[8]).toEqual(2); expect(v[9]).toEqual(3); expect(v[10]).toEqual(3); expect(v[11]).toEqual(0); }); it("converts a triangle strip to wireframe in place", function() { const geometry = import__221.GeometryPipeline.toWireframe( new import__221.Geometry({ attributes: {}, indices: [0, 1, 2, 3], primitiveType: import__221.PrimitiveType.TRIANGLE_STRIP }) ); expect(geometry.primitiveType).toEqual(import__221.PrimitiveType.LINES); const v = geometry.indices; expect(v.length).toEqual(12); expect(v[0]).toEqual(0); expect(v[1]).toEqual(1); expect(v[2]).toEqual(1); expect(v[3]).toEqual(2); expect(v[4]).toEqual(2); expect(v[5]).toEqual(0); expect(v[6]).toEqual(2); expect(v[7]).toEqual(3); expect(v[8]).toEqual(3); expect(v[9]).toEqual(1); expect(v[10]).toEqual(1); expect(v[11]).toEqual(2); }); it("toWireframe throws without a geometry", function() { expect(function() { import__221.GeometryPipeline.toWireframe(void 0); }).toThrowDeveloperError(); }); it("toWireframe throws when primitiveType is not a triangle type", function() { expect(function() { import__221.GeometryPipeline.toWireframe( new import__221.Geometry({ attributes: {}, indices: [], primitiveType: import__221.PrimitiveType.POINTS }) ); }).toThrowDeveloperError(); }); it("createLineSegmentsForVectors", function() { const geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0, 1, 0, 0, 0, 1, 0] }), normal: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 1, 0, 0, 1, 0, 0, 1] }) }, primitiveType: import__221.PrimitiveType.TRIANGLES, boundingSphere: new import__221.BoundingSphere(new import__221.Cartesian3(0.5, 0.5, 0), 1) }); const lines = import__221.GeometryPipeline.createLineSegmentsForVectors( geometry, "normal", 1 ); const linePositions = [ 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1 ]; expect(lines.attributes).toBeDefined(); expect(lines.attributes.position).toBeDefined(); expect(lines.attributes.position.values).toEqual(linePositions); expect(lines.primitiveType).toEqual(import__221.PrimitiveType.LINES); expect(lines.boundingSphere.center).toEqual(geometry.boundingSphere.center); expect(lines.boundingSphere.radius).toEqual( geometry.boundingSphere.radius + 1 ); }); it("createLineSegmentsForVectors throws without geometry", function() { expect(function() { import__221.GeometryPipeline.createLineSegmentsForVectors(); }).toThrowDeveloperError(); }); it("createLineSegmentsForVectors throws without geometry.attributes.position", function() { expect(function() { import__221.GeometryPipeline.createLineSegmentsForVectors(); }).toThrowDeveloperError(); }); it("createLineSegmentsForVectors throws when geometry.attributes does not have an attributeName property", function() { const geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 1, 2, 3, 4, 5] }) }, primitiveType: import__221.PrimitiveType.TRIANGLES }); expect(function() { import__221.GeometryPipeline.createLineSegmentsForVectors(geometry, "bitangent"); }).toThrowDeveloperError(); }); it("creates attribute indices", function() { const geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [] }), normal: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [] }), color: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 4, values: [] }) }, primitiveType: import__221.PrimitiveType.TRIANGLES }); const indices = import__221.GeometryPipeline.createAttributeLocations(geometry); const validIndices = [0, 1, 2]; expect(validIndices).toContain(indices.position); expect(validIndices).toContain(indices.normal); expect(validIndices).toContain(indices.color); expect(indices.position).not.toEqual(indices.normal); expect(indices.position).not.toEqual(indices.color); }); it("createAttributeLocations throws without a geometry", function() { expect(function() { import__221.GeometryPipeline.createAttributeLocations(void 0); }).toThrowDeveloperError(); }); it("reorderForPreVertexCache reorders all indices and attributes for the pre vertex cache", function() { const geometry = new import__221.Geometry({ attributes: { weight: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 1, values: [0, 1, 2, 3, 4, 5] }), positions: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ] }) }, indices: [5, 3, 2, 0, 1, 4, 4, 1, 3, 2, 5, 0], primitiveType: import__221.PrimitiveType.TRIANGLES }); import__221.GeometryPipeline.reorderForPreVertexCache(geometry); expect(geometry.indices[0]).toEqual(0); expect(geometry.indices[1]).toEqual(1); expect(geometry.indices[2]).toEqual(2); expect(geometry.indices[3]).toEqual(3); expect(geometry.indices[4]).toEqual(4); expect(geometry.indices[5]).toEqual(5); expect(geometry.indices[6]).toEqual(5); expect(geometry.indices[7]).toEqual(4); expect(geometry.indices[8]).toEqual(1); expect(geometry.indices[9]).toEqual(2); expect(geometry.indices[10]).toEqual(0); expect(geometry.indices[11]).toEqual(3); expect(geometry.attributes.weight.values[0]).toEqual(5); expect(geometry.attributes.weight.values[1]).toEqual(3); expect(geometry.attributes.weight.values[2]).toEqual(2); expect(geometry.attributes.weight.values[3]).toEqual(0); expect(geometry.attributes.weight.values[4]).toEqual(1); expect(geometry.attributes.weight.values[5]).toEqual(4); expect(geometry.attributes.positions.values[0]).toEqual(15); expect(geometry.attributes.positions.values[1]).toEqual(16); expect(geometry.attributes.positions.values[2]).toEqual(17); expect(geometry.attributes.positions.values[3]).toEqual(9); expect(geometry.attributes.positions.values[4]).toEqual(10); expect(geometry.attributes.positions.values[5]).toEqual(11); expect(geometry.attributes.positions.values[6]).toEqual(6); expect(geometry.attributes.positions.values[7]).toEqual(7); expect(geometry.attributes.positions.values[8]).toEqual(8); expect(geometry.attributes.positions.values[9]).toEqual(0); expect(geometry.attributes.positions.values[10]).toEqual(1); expect(geometry.attributes.positions.values[11]).toEqual(2); expect(geometry.attributes.positions.values[12]).toEqual(3); expect(geometry.attributes.positions.values[13]).toEqual(4); expect(geometry.attributes.positions.values[14]).toEqual(5); expect(geometry.attributes.positions.values[15]).toEqual(12); expect(geometry.attributes.positions.values[16]).toEqual(13); expect(geometry.attributes.positions.values[17]).toEqual(14); }); it("reoderForPreVertexCache removes unused vertices", function() { const geometry = new import__221.Geometry({ attributes: { weight: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 1, values: [0, 1, 2, 3, 4, 5] }), positions: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ] }) }, indices: [5, 3, 2, 4, 1, 3], primitiveType: import__221.PrimitiveType.TRIANGLES }); import__221.GeometryPipeline.reorderForPreVertexCache(geometry); expect(geometry.indices.length).toEqual(6); expect(geometry.attributes.positions.values.length).toEqual((6 - 1) * 3); expect(geometry.attributes.weight.values.length).toEqual(6 - 1); }); it("reorderForPreVertexCache throws without a geometry", function() { expect(function() { import__221.GeometryPipeline.reorderForPreVertexCache(void 0); }).toThrowDeveloperError(); }); it("reorderForPreVertexCache throws when attributes have a different number of attributes", function() { expect(function() { const geometry = new import__221.Geometry({ attributes: { attribute1: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 1, values: [0, 1, 2] }), attribute2: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 1, 2, 3, 4, 5] }) } }); import__221.GeometryPipeline.reorderForPreVertexCache(geometry); }).toThrowDeveloperError(); }); it("reorderForPostVertexCache reorders indices for the post vertex cache", function() { let geometry = import__221.EllipsoidGeometry.createGeometry(new import__221.EllipsoidGeometry()); const acmrBefore = import__221.Tipsify.calculateACMR({ indices: geometry.indices, cacheSize: 24 }); expect(acmrBefore).toBeGreaterThan(1); geometry = import__221.GeometryPipeline.reorderForPostVertexCache(geometry); const acmrAfter = import__221.Tipsify.calculateACMR({ indices: geometry.indices, cacheSize: 24 }); expect(acmrAfter).toBeLessThan(0.7); }); it("reorderForPostVertexCache throws without a geometry", function() { expect(function() { import__221.GeometryPipeline.reorderForPostVertexCache(void 0); }).toThrowDeveloperError(); }); it("fitToUnsignedShortIndicestoThrowDeveloperErrorot change geometry", function() { const geometry = new import__221.Geometry({ attributes: { time: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 1, values: [10] }), heat: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 1, values: [1] }) }, indices: [0, 0, 0], primitiveType: import__221.PrimitiveType.TRIANGLES }); const geometries = import__221.GeometryPipeline.fitToUnsignedShortIndices(geometry); expect(geometries.length).toEqual(1); expect(geometries[0]).toBe(geometry); }); it("fitToUnsignedShortIndices creates one geometry", function() { const sixtyFourK = import__222.Math.SIXTY_FOUR_KILOBYTES; const times = []; for (let i = 0; i < sixtyFourK + 1; ++i) { times.push(i); } const geometry = new import__221.Geometry({ attributes: { time: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 1, values: times }) }, indices: [0, 0, 0, sixtyFourK, sixtyFourK, sixtyFourK, 0, sixtyFourK, 0], primitiveType: import__221.PrimitiveType.TRIANGLES }); const geometries = import__221.GeometryPipeline.fitToUnsignedShortIndices(geometry); expect(geometries.length).toEqual(1); expect(geometries[0].attributes.time.componentDatatype).toEqual( import__221.ComponentDatatype.FLOAT ); expect(geometries[0].attributes.time.componentsPerAttribute).toEqual(1); expect(geometries[0].attributes.time.values).toEqual([0, sixtyFourK]); expect(geometries[0].primitiveType).toEqual(import__221.PrimitiveType.TRIANGLES); expect(geometries[0].indices).toEqual([0, 0, 0, 1, 1, 1, 0, 1, 0]); }); it("fitToUnsignedShortIndices creates two triangle geometries", function() { const sixtyFourK = import__222.Math.SIXTY_FOUR_KILOBYTES; const positions = []; for (let i = 0; i < sixtyFourK + 1; ++i) { positions.push(i, i, i); } const indices = []; for (let j = sixtyFourK; j > 1; j -= 3) { indices.push(j, j - 1, j - 2); } indices.push(0, 1, 2); const geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: positions }) }, indices, primitiveType: import__221.PrimitiveType.TRIANGLES }); const geometries = import__221.GeometryPipeline.fitToUnsignedShortIndices(geometry); expect(geometries.length).toEqual(2); expect(geometries[0].attributes.position.values.length).toEqual( positions.length - 6 ); expect(geometries[0].indices.length).toEqual(indices.length - 3); expect(geometries[1].attributes.position.values.length).toEqual(9); expect(geometries[1].indices.length).toEqual(3); }); it("fitToUnsignedShortIndices creates two line geometries", function() { const sixtyFourK = import__222.Math.SIXTY_FOUR_KILOBYTES; const positions = []; for (let i = 0; i < sixtyFourK + 2; ++i) { positions.push(i, i, i); } const indices = []; for (let j = sixtyFourK; j > 1; j -= 2) { indices.push(j, j - 1); } indices.push(0, 1); const geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: positions }) }, indices, primitiveType: import__221.PrimitiveType.LINES }); const geometries = import__221.GeometryPipeline.fitToUnsignedShortIndices(geometry); expect(geometries.length).toEqual(2); expect(geometries[0].attributes.position.values.length).toEqual( positions.length - 12 ); expect(geometries[0].indices.length).toEqual(indices.length - 4); expect(geometries[1].attributes.position.values.length).toEqual(9); expect(geometries[1].indices.length).toEqual(4); }); it("fitToUnsignedShortIndices creates two point geometries", function() { const sixtyFourK = import__222.Math.SIXTY_FOUR_KILOBYTES; const positions = []; const indices = []; for (let i = 0; i < sixtyFourK + 1; ++i) { positions.push(i, i, i); indices.push(i); } const geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: positions }) }, indices, primitiveType: import__221.PrimitiveType.POINTS }); const geometries = import__221.GeometryPipeline.fitToUnsignedShortIndices(geometry); expect(geometries.length).toEqual(2); expect(geometries[0].attributes.position.values.length).toEqual( positions.length - 6 ); expect(geometries[0].indices.length).toEqual(indices.length - 2); expect(geometries[1].attributes.position.values.length).toEqual(6); expect(geometries[1].indices.length).toEqual(2); }); it("fitToUnsignedShortIndices throws without a geometry", function() { expect(function() { import__221.GeometryPipeline.fitToUnsignedShortIndices(void 0); }).toThrowDeveloperError(); }); it("fitToUnsignedShortIndices throws without triangles, lines, or points", function() { const geometry = new import__221.Geometry({ attributes: { time: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 1, values: [10, 11, 12] }) }, indices: [0, 1, 2], primitiveType: import__221.PrimitiveType.TRIANGLE_STRIP }); expect(function() { return import__221.GeometryPipeline.fitToUnsignedShortIndices(geometry); }).toThrowDeveloperError(); }); it("fitToUnsignedShortIndices throws with different numbers of attributes", function() { const geometry = new import__221.Geometry({ attributes: { time: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 1, values: [10] }), heat: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 1, values: [1, 2] }) }, indices: [0, 0, 0], primitiveType: import__221.PrimitiveType.TRIANGLES }); expect(function() { return import__221.GeometryPipeline.fitToUnsignedShortIndices(geometry); }).toThrowDeveloperError(); }); it("projectTo2D", function() { const p1 = new import__221.Cartesian3(1e5, 2e5, 3e5); const p2 = new import__221.Cartesian3(4e5, 5e5, 6e5); let geometry = {}; geometry.attributes = {}; geometry.attributes.position = { componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: [p1.x, p1.y, p1.z, p2.x, p2.y, p2.z] }; geometry = import__221.GeometryPipeline.projectTo2D( geometry, "position", "position3D", "position2D" ); const ellipsoid = import__221.Ellipsoid.WGS84; const projection = new import__221.GeographicProjection(); const projectedP1 = projection.project( ellipsoid.cartesianToCartographic(p1) ); const projectedP2 = projection.project( ellipsoid.cartesianToCartographic(p2) ); expect(geometry.attributes.position2D.values[0]).toEqual(projectedP1.x); expect(geometry.attributes.position2D.values[1]).toEqual(projectedP1.y); expect(geometry.attributes.position2D.values[2]).toEqual(projectedP1.z); expect(geometry.attributes.position2D.values[3]).toEqual(projectedP2.x); expect(geometry.attributes.position2D.values[4]).toEqual(projectedP2.y); expect(geometry.attributes.position2D.values[5]).toEqual(projectedP2.z); expect(geometry.attributes.position3D.values[0]).toEqual(p1.x); expect(geometry.attributes.position3D.values[1]).toEqual(p1.y); expect(geometry.attributes.position3D.values[2]).toEqual(p1.z); expect(geometry.attributes.position3D.values[3]).toEqual(p2.x); expect(geometry.attributes.position3D.values[4]).toEqual(p2.y); expect(geometry.attributes.position3D.values[5]).toEqual(p2.z); }); it("projectTo2D throws without a geometry", function() { expect(function() { import__221.GeometryPipeline.projectTo2D(void 0); }).toThrowDeveloperError(); }); it("projectTo2D throws without attributeName", function() { expect(function() { import__221.GeometryPipeline.projectTo2D( new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: [0, 0, 0] }) }, primitiveType: import__221.PrimitiveType.POINTS }) ); }).toThrowDeveloperError(); }); it("projectTo2D throws without attributeName3D", function() { expect(function() { import__221.GeometryPipeline.projectTo2D( new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: [0, 0, 0] }) }, primitiveType: import__221.PrimitiveType.POINTS }), "position" ); }).toThrowDeveloperError(); }); it("projectTo2D throws without attributeName2D", function() { expect(function() { import__221.GeometryPipeline.projectTo2D( new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: [0, 0, 0] }) }, primitiveType: import__221.PrimitiveType.POINTS }), "position", "position3D" ); }).toThrowDeveloperError(); }); it("projectTo2D throws without attribute", function() { expect(function() { import__221.GeometryPipeline.projectTo2D( new import__221.Geometry({ attributes: { normal: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: [0, 0, 0] }) }, primitiveType: import__221.PrimitiveType.POINTS }), "position", "position3D", "position2D" ); }).toThrowDeveloperError(); }); it("projectTo2D throws without ComponentDatatype.DOUBLE", function() { expect(function() { const geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.UNSIGNED_SHORT, componentsPerAttribute: 1, values: [0] }) } }); import__221.GeometryPipeline.projectTo2D( geometry, "position", "position3D", "position2D" ); }).toThrowDeveloperError(); }); it("projectTo2D throws when trying to project a point close to the origin", function() { const geometry = {}; geometry.attributes = {}; geometry.attributes.position = { componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: [1e5, 2e5, 3e5, 0, 0, 0] }; expect(function() { return import__221.GeometryPipeline.projectTo2D( geometry, "position", "position3D", "position2D" ); }).toThrowDeveloperError(); }); it("encodeAttribute encodes positions", function() { const c = new import__221.Cartesian3(-1e7, 0, 1e7); const encoded = import__221.EncodedCartesian3.fromCartesian(c); let geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: [c.x, c.y, c.z] }) }, primitiveType: import__221.PrimitiveType.POINTS }); geometry = import__221.GeometryPipeline.encodeAttribute( geometry, "position", "positionHigh", "positionLow" ); expect(geometry.attributes.positionHigh).toBeDefined(); expect(geometry.attributes.positionHigh.values[0]).toEqual(encoded.high.x); expect(geometry.attributes.positionHigh.values[1]).toEqual(encoded.high.y); expect(geometry.attributes.positionHigh.values[2]).toEqual(encoded.high.z); expect(geometry.attributes.positionLow).toBeDefined(); expect(geometry.attributes.positionLow.values[0]).toEqual(encoded.low.x); expect(geometry.attributes.positionLow.values[1]).toEqual(encoded.low.y); expect(geometry.attributes.positionLow.values[2]).toEqual(encoded.low.z); expect(geometry.attributes.position).not.toBeDefined(); }); it("encodeAttribute throws without a geometry", function() { expect(function() { import__221.GeometryPipeline.encodeAttribute(void 0); }).toThrowDeveloperError(); }); it("encodeAttribute throws without attributeName", function() { expect(function() { import__221.GeometryPipeline.encodeAttribute( new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: [0, 0, 0] }) }, primitiveType: import__221.PrimitiveType.POINTS }) ); }).toThrowDeveloperError(); }); it("encodeAttribute throws without attributeHighName", function() { expect(function() { import__221.GeometryPipeline.encodeAttribute( new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: [0, 0, 0] }) }, primitiveType: import__221.PrimitiveType.POINTS }), "position" ); }).toThrowDeveloperError(); }); it("encodeAttribute throws without attributeLowName", function() { expect(function() { import__221.GeometryPipeline.encodeAttribute( new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: [0, 0, 0] }) }, primitiveType: import__221.PrimitiveType.POINTS }), "position", "positionHigh" ); }).toThrowDeveloperError(); }); it("encodeAttribute throws without attribute", function() { expect(function() { import__221.GeometryPipeline.encodeAttribute( new import__221.Geometry({ attributes: { normal: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: [0, 0, 0] }) }, primitiveType: import__221.PrimitiveType.POINTS }), "position", "positionHigh", "positionLow" ); }).toThrowDeveloperError(); }); it("encodeAttribute throws without ComponentDatatype.DOUBLE", function() { expect(function() { const geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.UNSIGNED_SHORT, componentsPerAttribute: 1, values: [0] }) } }); import__221.GeometryPipeline.encodeAttribute( geometry, "position", "positionHigh", "positionLow" ); }).toThrowDeveloperError(); }); it("transformToWorldCoordinates", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0, 1, 0, 0, 0, 1, 0] }), normal: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 1, 0, 0, 1, 0, 0, 1] }) }, indices: [0, 1, 2], primitiveType: import__221.PrimitiveType.TRIANGLES, boundingSphere: new import__221.BoundingSphere(new import__221.Cartesian3(0.5, 0.5, 0), 1) }), modelMatrix: new import__221.Matrix4( 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 ) }); const transformed = import__221.GeometryPipeline.transformToWorldCoordinates(instance); const transformedPositions = [0, 0, 0, 0, 1, 0, 0, 0, 1]; const transformedNormals = [1, 0, 0, 1, 0, 0, 1, 0, 0]; expect(transformed.geometry.attributes.position.values).toEqual( transformedPositions ); expect(transformed.geometry.attributes.normal.values).toEqual( transformedNormals ); expect(transformed.geometry.boundingSphere).toEqual( new import__221.BoundingSphere(new import__221.Cartesian3(0, 0.5, 0.5), 1) ); expect(transformed.modelMatrix).toEqual(import__221.Matrix4.IDENTITY); }); it("transformToWorldCoordinates with non-uniform scale", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0, 1, 0, 0, 0, 1, 0] }), normal: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 1, 0, 0, 1, 0, 0, 1] }) }, indices: [0, 1, 2], primitiveType: import__221.PrimitiveType.TRIANGLES, boundingSphere: new import__221.BoundingSphere(new import__221.Cartesian3(0.5, 0.5, 0), 1) }), modelMatrix: import__221.Matrix4.fromScale(new import__221.Cartesian3(1, 2, 4)) }); const transformed = import__221.GeometryPipeline.transformToWorldCoordinates(instance); const transformedPositions = [0, 0, 0, 1, 0, 0, 0, 2, 0]; const transformedNormals = [0, 0, 1, 0, 0, 1, 0, 0, 1]; expect(transformed.geometry.attributes.position.values).toEqual( transformedPositions ); expect(transformed.geometry.attributes.normal.values).toEqual( transformedNormals ); expect(transformed.geometry.boundingSphere).toEqual( new import__221.BoundingSphere(new import__221.Cartesian3(0.5, 1, 0), 4) ); expect(transformed.modelMatrix).toEqual(import__221.Matrix4.IDENTITY); }); it("transformToWorldCoordinates does nothing when already in world coordinates", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0, 1, 0, 0, 0, 1, 0] }), normal: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 1, 0, 0, 1, 0, 0, 1] }) }, indices: [0, 1, 2], primitiveType: import__221.PrimitiveType.TRIANGLES, boundingSphere: new import__221.BoundingSphere(new import__221.Cartesian3(0.5, 0.5, 0), 1) }), modelMatrix: import__221.Matrix4.IDENTITY }); const transformed = import__221.GeometryPipeline.transformToWorldCoordinates(instance); const transformedPositions = [0, 0, 0, 1, 0, 0, 0, 1, 0]; const transformedNormals = [0, 0, 1, 0, 0, 1, 0, 0, 1]; expect(transformed.geometry.attributes.position.values).toEqual( transformedPositions ); expect(transformed.geometry.attributes.normal.values).toEqual( transformedNormals ); expect(transformed.geometry.boundingSphere).toEqual( new import__221.BoundingSphere(new import__221.Cartesian3(0.5, 0.5, 0), 1) ); expect(transformed.modelMatrix).toEqual(import__221.Matrix4.IDENTITY); }); it("transformToWorldCoordinates throws without an instance", function() { expect(function() { import__221.GeometryPipeline.transformToWorldCoordinates(); }).toThrowDeveloperError(); }); it("combineInstances combines one geometry", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: new Float32Array([0, 0, 0]) }) }, primitiveType: import__221.PrimitiveType.POINTS }) }); const combined = import__221.GeometryPipeline.combineInstances([instance])[0]; expect(combined).toEqual(instance.geometry); }); it("combineInstances combines several geometries without indicess", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0] }) }, primitiveType: import__221.PrimitiveType.POINTS }) }); const anotherInstance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [1, 1, 1] }) }, primitiveType: import__221.PrimitiveType.POINTS }) }); const combined = import__221.GeometryPipeline.combineInstances([ instance, anotherInstance ])[0]; expect(combined).toEqual( new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: new Float32Array([0, 0, 0, 1, 1, 1]) }) }, primitiveType: import__221.PrimitiveType.POINTS }) ); }); it("combineInstances combines several geometries with indicess", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0, 1, 1, 1, 2, 2, 2] }), normal: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0, 1, 1, 1, 2, 2, 2] }) }, indices: [0, 1, 2], primitiveType: import__221.PrimitiveType.TRIANGLES }) }); const anotherInstance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [3, 3, 3, 4, 4, 4, 5, 5, 5] }) }, indices: [0, 1, 2], primitiveType: import__221.PrimitiveType.TRIANGLES }) }); const combined = import__221.GeometryPipeline.combineInstances([ instance, anotherInstance ])[0]; expect(combined).toEqual( new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: new Float32Array([ 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5 ]) }) }, indices: new Uint16Array([0, 1, 2, 3, 4, 5]), primitiveType: import__221.PrimitiveType.TRIANGLES }) ); }); it("combineInstances with geometry that is and is not split by the IDL", function() { const instances = [ import__221.GeometryPipeline.splitLongitude( new import__221.GeometryInstance({ geometry: import__221.PolygonGeometry.createGeometry( import__221.PolygonGeometry.fromPositions({ positions: import__221.Cartesian3.fromDegreesArray([ 179, 1, 179, -1, -179, -1, -179, 1 ]), vertexFormat: import__221.VertexFormat.POSITION_ONLY, granularity: 2 * import__222.Math.RADIANS_PER_DEGREE }) ) }) ), new import__221.GeometryInstance({ geometry: import__221.PolygonGeometry.createGeometry( import__221.PolygonGeometry.fromPositions({ positions: import__221.Cartesian3.fromDegreesArray([ -1, 1, -1, -1, 1, -1, 1, 1 ]), vertexFormat: import__221.VertexFormat.POSITION_ONLY, granularity: 2 * import__222.Math.RADIANS_PER_DEGREE }) ) }) ]; const combinedInstances = import__221.GeometryPipeline.combineInstances(instances); expect(combinedInstances.length).toEqual(3); }); it("combineInstances combines bounding spheres", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0, 1, 0, 0, 0, 1, 0] }) }, indices: [0, 1, 2], primitiveType: import__221.PrimitiveType.TRIANGLES, boundingSphere: new import__221.BoundingSphere(new import__221.Cartesian3(0.5, 0.5, 0), 1) }) }); const anotherInstance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [1, 0, 0, 2, 0, 0, 1, 1, 0] }) }, indices: [0, 1, 2], primitiveType: import__221.PrimitiveType.TRIANGLES, boundingSphere: new import__221.BoundingSphere(new import__221.Cartesian3(1.5, 0.5, 0), 1) }) }); const combined = import__221.GeometryPipeline.combineInstances([ instance, anotherInstance ])[0]; const expected = import__221.BoundingSphere.union( instance.geometry.boundingSphere, anotherInstance.geometry.boundingSphere ); expect(combined.boundingSphere).toEqual(expected); }); it("combineInstances throws without instances", function() { expect(function() { import__221.GeometryPipeline.combineInstances(); }).toThrowDeveloperError(); }); it("combineInstances throws when instances.length is zero", function() { expect(function() { import__221.GeometryPipeline.combineInstances([]); }).toThrowDeveloperError(); }); it("combineInstances throws when instances.modelMatrix do not match", function() { const instance0 = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0] }) }, primitiveType: import__221.PrimitiveType.POINTS }), modelMatrix: import__221.Matrix4.fromScale(new import__221.Cartesian3(1, 1, 1)) }); const instance1 = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0] }) }, primitiveType: import__221.PrimitiveType.POINTS }), modelMatrix: import__221.Matrix4.fromScale(new import__221.Cartesian3(2, 2, 2)) }); expect(function() { import__221.GeometryPipeline.combineInstances([instance0, instance1]); }).toThrowDeveloperError(); }); it("combineInstances throws when instance geometries do not all have or not have an indices", function() { const instance0 = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0] }) }, indices: [0], primitiveType: import__221.PrimitiveType.POINTS }) }); const instance1 = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0] }) }, primitiveType: import__221.PrimitiveType.POINTS }) }); expect(function() { import__221.GeometryPipeline.combineInstances([instance0, instance1]); }).toThrowDeveloperError(); }); it("combineInstances throws when instance geometries do not all have the same primitive type", function() { const instance0 = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0] }) }, primitiveType: import__221.PrimitiveType.POINTS }) }); const instance1 = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: [0, 0, 0, 1, 0, 0] }) }, primitiveType: import__221.PrimitiveType.LINES }) }); expect(function() { import__221.GeometryPipeline.combineInstances([instance0, instance1]); }).toThrowDeveloperError(); }); it("computeNormal throws when geometry is undefined", function() { expect(function() { import__221.GeometryPipeline.computeNormal(); }).toThrowDeveloperError(); }); it("computeNormal throws when geometry.attributes.position is undefined", function() { const geometry = new import__221.Geometry({ attributes: {}, primitiveType: import__221.PrimitiveType.TRIANGLES }); expect(function() { import__221.GeometryPipeline.computeNormal(geometry); }).toThrowDeveloperError(); }); it("computeNormal throws when geometry.indices is undefined", function() { const geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 0, 0, 1, 0], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }) }, primitiveType: import__221.PrimitiveType.TRIANGLES }); expect(function() { import__221.GeometryPipeline.computeNormal(geometry); }).toThrowDeveloperError(); }); it("computeNormal throws when geometry.indices.length is not a multiple of 3", function() { const geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 0, 0, 1], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }) }, primitiveType: import__221.PrimitiveType.TRIANGLES }); expect(function() { import__221.GeometryPipeline.computeNormal(geometry); }).toThrowDeveloperError(); }); it("computeNormal throws when primitive type is not triangle", function() { const geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 0, 0, 1, 0], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }) }, indices: [0, 1, 2], primitiveType: import__221.PrimitiveType.TRIANGLE_STRIP }); expect(function() { import__221.GeometryPipeline.computeNormal(geometry); }).toThrowDeveloperError(); }); it("computeNormal computes normal for one triangle", function() { let geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 0, 0, 1, 0], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }) }, indices: [0, 1, 2], primitiveType: import__221.PrimitiveType.TRIANGLES }); geometry = import__221.GeometryPipeline.computeNormal(geometry); expect(geometry.attributes.normal.values.length).toEqual(3 * 3); expect(geometry.attributes.normal.values).toEqual([ 0, 0, 1, 0, 0, 1, 0, 0, 1 ]); }); it("computeNormal computes normal for two triangles", function() { let geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 1, 1, 1, 1, 2, 0, 0], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }) }, indices: [0, 1, 2, 1, 3, 2], primitiveType: import__221.PrimitiveType.TRIANGLES }); geometry = import__221.GeometryPipeline.computeNormal(geometry); const normals = geometry.attributes.normal.values; expect(normals.length).toEqual(4 * 3); let a = import__221.Cartesian3.normalize(new import__221.Cartesian3(-1, 0, 1), new import__221.Cartesian3()); expect(import__221.Cartesian3.fromArray(normals, 0)).toEqualEpsilon( a, import__222.Math.EPSILON7 ); expect(import__221.Cartesian3.fromArray(normals, 3)).toEqualEpsilon( import__221.Cartesian3.UNIT_Z, import__222.Math.EPSILON7 ); expect(import__221.Cartesian3.fromArray(normals, 6)).toEqualEpsilon( import__221.Cartesian3.UNIT_Z, import__222.Math.EPSILON7 ); a = import__221.Cartesian3.normalize(new import__221.Cartesian3(1, 0, 1), new import__221.Cartesian3()); expect(import__221.Cartesian3.fromArray(normals, 9)).toEqualEpsilon( a, import__222.Math.EPSILON7 ); }); it("computeNormal computes normal for six triangles", function() { let geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ values: [ 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0 ], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }) }, indices: [0, 1, 2, 3, 0, 2, 4, 0, 3, 4, 5, 0, 5, 6, 0, 6, 1, 0], primitiveType: import__221.PrimitiveType.TRIANGLES }); geometry = import__221.GeometryPipeline.computeNormal(geometry); const normals = geometry.attributes.normal.values; expect(normals.length).toEqual(7 * 3); let a = import__221.Cartesian3.normalize(new import__221.Cartesian3(-1, -1, -1), new import__221.Cartesian3()); expect(import__221.Cartesian3.fromArray(normals, 0)).toEqualEpsilon( a, import__222.Math.EPSILON7 ); a = import__221.Cartesian3.normalize(new import__221.Cartesian3(0, -1, -1), new import__221.Cartesian3()); expect(import__221.Cartesian3.fromArray(normals, 3)).toEqualEpsilon( a, import__222.Math.EPSILON7 ); expect(import__221.Cartesian3.fromArray(normals, 6)).toEqualEpsilon( import__221.Cartesian3.negate(import__221.Cartesian3.UNIT_Y, new import__221.Cartesian3()), import__222.Math.EPSILON7 ); a = import__221.Cartesian3.normalize(new import__221.Cartesian3(-1, -1, 0), new import__221.Cartesian3()); expect(import__221.Cartesian3.fromArray(normals, 9)).toEqualEpsilon( a, import__222.Math.EPSILON7 ); expect(import__221.Cartesian3.fromArray(normals, 12)).toEqualEpsilon( import__221.Cartesian3.negate(import__221.Cartesian3.UNIT_X, new import__221.Cartesian3()), import__222.Math.EPSILON7 ); a = import__221.Cartesian3.normalize(new import__221.Cartesian3(-1, 0, -1), new import__221.Cartesian3()); expect(import__221.Cartesian3.fromArray(normals, 15)).toEqualEpsilon( a, import__222.Math.EPSILON7 ); expect(import__221.Cartesian3.fromArray(normals, 18)).toEqualEpsilon( import__221.Cartesian3.negate(import__221.Cartesian3.UNIT_Z, new import__221.Cartesian3()), import__222.Math.EPSILON7 ); }); it("computeNormal computes normal of (0,0,1) for a degenerate triangle", function() { let geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 0], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }) }, indices: [0, 1, 0], primitiveType: import__221.PrimitiveType.TRIANGLES }); geometry = import__221.GeometryPipeline.computeNormal(geometry); expect(geometry.attributes.normal.values.length).toEqual(2 * 3); expect(geometry.attributes.normal.values).toEqual([0, 0, 1, 0, 0, 1]); }); it("computeNormal takes first normal for two coplanar triangles with opposite winding orders", function() { let geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 1, 1, 1, 1], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }) }, indices: [0, 1, 2, 2, 1, 0], primitiveType: import__221.PrimitiveType.TRIANGLES }); geometry = import__221.GeometryPipeline.computeNormal(geometry); const normals = geometry.attributes.normal.values; expect(normals.length).toEqual(3 * 3); const a = import__221.Cartesian3.normalize(new import__221.Cartesian3(-1, 0, 1), new import__221.Cartesian3()); expect(import__221.Cartesian3.fromArray(normals, 0)).toEqualEpsilon( a, import__222.Math.EPSILON7 ); expect(import__221.Cartesian3.fromArray(normals, 3)).toEqualEpsilon( a, import__222.Math.EPSILON7 ); expect(import__221.Cartesian3.fromArray(normals, 6)).toEqualEpsilon( a, import__222.Math.EPSILON7 ); }); it("computeTangentAndBitangent throws when geometry is undefined", function() { expect(function() { import__221.GeometryPipeline.computeTangentAndBitangent(); }).toThrowDeveloperError(); }); it("computeTangentAndBitangent throws when position is undefined", function() { const geometry = new import__221.Geometry({ attributes: { normal: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 0, 0, 1, 0], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }), st: new import__221.GeometryAttribute({ values: [0, 0, 1, 1], componentsPerAttribute: 2, componentDatatype: import__221.ComponentDatatype.FLOAT }) }, indices: [0, 1, 2], primitiveType: import__221.PrimitiveType.TRIANGLE_STRIP }); expect(function() { import__221.GeometryPipeline.computeTangentAndBitangent(geometry); }).toThrowDeveloperError(); }); it("computeTangentAndBitangent throws when normal is undefined", function() { const geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 0, 0, 1, 0], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }), st: new import__221.GeometryAttribute({ values: [0, 0, 1, 1], componentsPerAttribute: 2, componentDatatype: import__221.ComponentDatatype.FLOAT }) }, indices: [0, 1, 2], primitiveType: import__221.PrimitiveType.TRIANGLE_STRIP }); expect(function() { import__221.GeometryPipeline.computeTangentAndBitangent(geometry); }).toThrowDeveloperError(); }); it("computeTangentAndBitangent throws when st is undefined", function() { const geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 0, 0, 1, 0], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }), normal: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 0, 0, 1, 0], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }) }, indices: [0, 1, 2], primitiveType: import__221.PrimitiveType.TRIANGLE_STRIP }); expect(function() { import__221.GeometryPipeline.computeTangentAndBitangent(geometry); }).toThrowDeveloperError(); }); it("computeTangentAndBitangent throws when geometry.indices is undefined", function() { const geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 0, 0, 1, 0], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }), normal: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 0, 0, 1, 0], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }), st: new import__221.GeometryAttribute({ values: [0, 0, 1, 1], componentsPerAttribute: 2, componentDatatype: import__221.ComponentDatatype.FLOAT }) }, primitiveType: import__221.PrimitiveType.POINTS }); expect(function() { import__221.GeometryPipeline.computeTangentAndBitangent(geometry); }).toThrowDeveloperError(); }); it("computeTangentAndBitangent throws when indices is not a multiple of 3", function() { const geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 0, 0, 1, 0], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }), normal: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 0, 0, 1, 0], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }), st: new import__221.GeometryAttribute({ values: [0, 0, 1, 1], componentsPerAttribute: 2, componentDatatype: import__221.ComponentDatatype.FLOAT }) }, indices: [0, 1, 2, 3, 4], primitiveType: import__221.PrimitiveType.TRIANGLES }); expect(function() { import__221.GeometryPipeline.computeTangentAndBitangent(geometry); }).toThrowDeveloperError(); }); it("computeTangentAndBitangent throws when primitive type is not triangle", function() { const geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 0, 0, 1, 0], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }), normal: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 0, 0, 1, 0], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }), st: new import__221.GeometryAttribute({ values: [0, 0, 1, 1], componentsPerAttribute: 2, componentDatatype: import__221.ComponentDatatype.FLOAT }) }, indices: [0, 1, 2], primitiveType: import__221.PrimitiveType.TRIANGLE_STRIP }); expect(function() { import__221.GeometryPipeline.computeTangentAndBitangent(geometry); }).toThrowDeveloperError(); }); it("computeTangentAndBitangent computes tangent and bitangent for one triangle", function() { let geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 0, 0, 1, 0], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }), st: new import__221.GeometryAttribute({ values: [0, 0, 1, 0, 0, 1], componentsPerAttribute: 2, componentDatatype: import__221.ComponentDatatype.FLOAT }) }, indices: [0, 1, 2], primitiveType: import__221.PrimitiveType.TRIANGLES }); geometry = import__221.GeometryPipeline.computeNormal(geometry); geometry = import__221.GeometryPipeline.computeTangentAndBitangent(geometry); expect(geometry.attributes.tangent.values).toEqual([ 1, 0, 0, 1, 0, 0, 1, 0, 0 ]); expect(geometry.attributes.bitangent.values).toEqual([ 0, 1, 0, 0, 1, 0, 0, 1, 0 ]); }); it("computeTangentAndBitangent computes tangent and bitangent for two triangles", function() { let geometry = new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ values: [0, 0, 0, 1, 0, 1, 1, 1, 1, 2, 0, 0], componentsPerAttribute: 3, componentDatatype: import__221.ComponentDatatype.FLOAT }), st: new import__221.GeometryAttribute({ values: [0, 0, 1, 0, 1, 1, 0, 1], componentsPerAttribute: 2, componentDatatype: import__221.ComponentDatatype.FLOAT }) }, indices: [0, 1, 2, 1, 3, 2], primitiveType: import__221.PrimitiveType.TRIANGLES }); geometry = import__221.GeometryPipeline.computeNormal(geometry); geometry = import__221.GeometryPipeline.computeTangentAndBitangent(geometry); expect(geometry.attributes.tangent.values).toEqualEpsilon( [ 0.7071067811865475, 0, 0.7071067811865475, 0, 1, 0, 0, 1, 0, -0.5773502691896258, 0.5773502691896258, 0.5773502691896258 ], import__222.Math.EPSILON7 ); expect(geometry.attributes.bitangent.values).toEqualEpsilon( [ 0, 1, 0, -1, 0, 0, -1, 0, 0, -0.4082482904638631, -0.8164965809277261, 0.4082482904638631 ], import__222.Math.EPSILON7 ); }); it("computeTangentAndBitangent computes tangent and bitangent for BoxGeometry", function() { let geometry = import__221.BoxGeometry.createGeometry( new import__221.BoxGeometry({ vertexFormat: new import__221.VertexFormat({ position: true, normal: true, st: true }), maximum: new import__221.Cartesian3(25e4, 25e4, 25e4), minimum: new import__221.Cartesian3(-25e4, -25e4, -25e4) }) ); geometry = import__221.GeometryPipeline.computeTangentAndBitangent(geometry); const actualTangents = geometry.attributes.tangent.values; const actualBitangents = geometry.attributes.bitangent.values; const expectedGeometry = import__221.BoxGeometry.createGeometry( new import__221.BoxGeometry({ vertexFormat: import__221.VertexFormat.ALL, maximum: new import__221.Cartesian3(25e4, 25e4, 25e4), minimum: new import__221.Cartesian3(-25e4, -25e4, -25e4) }) ); const expectedTangents = expectedGeometry.attributes.tangent.values; const expectedBitangents = expectedGeometry.attributes.bitangent.values; expect(actualTangents.length).toEqual(expectedTangents.length); expect(actualBitangents.length).toEqual(expectedBitangents.length); for (let i = 0; i < actualTangents.length; i += 3) { let actual = import__221.Cartesian3.fromArray(actualTangents, i); let expected = import__221.Cartesian3.fromArray(expectedTangents, i); expect(actual).toEqualEpsilon(expected, import__222.Math.EPSILON1); actual = import__221.Cartesian3.fromArray(actualBitangents, i); expected = import__221.Cartesian3.fromArray(expectedBitangents, i); expect(actual).toEqualEpsilon(expected, import__222.Math.EPSILON1); } }); it("compressVertices throws without geometry", function() { expect(function() { return import__221.GeometryPipeline.compressVertices(); }).toThrowDeveloperError(); }); it("compressVertices on geometry without normals or texture coordinates does nothing", function() { let geometry = import__221.BoxGeometry.createGeometry( new import__221.BoxGeometry({ vertexFormat: new import__221.VertexFormat({ position: true }), maximum: new import__221.Cartesian3(25e4, 25e4, 25e4), minimum: new import__221.Cartesian3(-25e4, -25e4, -25e4) }) ); expect(geometry.attributes.normal).not.toBeDefined(); geometry = import__221.GeometryPipeline.compressVertices(geometry); expect(geometry.attributes.normal).not.toBeDefined(); }); it("compressVertices compresses normals", function() { let geometry = import__221.BoxGeometry.createGeometry( new import__221.BoxGeometry({ vertexFormat: new import__221.VertexFormat({ position: true, normal: true }), maximum: new import__221.Cartesian3(25e4, 25e4, 25e4), minimum: new import__221.Cartesian3(-25e4, -25e4, -25e4) }) ); expect(geometry.attributes.normal).toBeDefined(); const originalNormals = geometry.attributes.normal.values.slice(); geometry = import__221.GeometryPipeline.compressVertices(geometry); expect(geometry.attributes.compressedAttributes).toBeDefined(); const normals = geometry.attributes.compressedAttributes.values; expect(normals.length).toEqual(originalNormals.length / 3); for (let i = 0; i < normals.length; ++i) { expect( import__221.AttributeCompression.octDecodeFloat(normals[i], new import__221.Cartesian3()) ).toEqualEpsilon( import__221.Cartesian3.fromArray(originalNormals, i * 3), import__222.Math.EPSILON2 ); } }); it("compressVertices compresses texture coordinates", function() { let geometry = import__221.BoxGeometry.createGeometry( new import__221.BoxGeometry({ vertexFormat: new import__221.VertexFormat({ position: true, st: true }), maximum: new import__221.Cartesian3(25e4, 25e4, 25e4), minimum: new import__221.Cartesian3(-25e4, -25e4, -25e4) }) ); expect(geometry.attributes.st).toBeDefined(); const originalST = geometry.attributes.st.values.slice(); geometry = import__221.GeometryPipeline.compressVertices(geometry); expect(geometry.attributes.st).not.toBeDefined(); expect(geometry.attributes.compressedAttributes).toBeDefined(); const st = geometry.attributes.compressedAttributes.values; expect(st.length).toEqual(originalST.length / 2); for (let i = 0; i < st.length; ++i) { const temp = st[i] / 4096; const stx = Math.floor(temp) / 4096; const sty = temp - Math.floor(temp); const texCoord = new import__221.Cartesian2(stx, sty); expect(texCoord).toEqualEpsilon( import__221.Cartesian2.fromArray(originalST, i * 2, new import__221.Cartesian2()), import__222.Math.EPSILON2 ); } }); it("compressVertices packs compressed normals with texture coordinates", function() { let geometry = import__221.BoxGeometry.createGeometry( new import__221.BoxGeometry({ vertexFormat: new import__221.VertexFormat({ position: true, normal: true, st: true }), maximum: new import__221.Cartesian3(25e4, 25e4, 25e4), minimum: new import__221.Cartesian3(-25e4, -25e4, -25e4) }) ); expect(geometry.attributes.normal).toBeDefined(); expect(geometry.attributes.st).toBeDefined(); const originalNormals = geometry.attributes.normal.values.slice(); const originalST = geometry.attributes.st.values.slice(); geometry = import__221.GeometryPipeline.compressVertices(geometry); expect(geometry.attributes.normal).not.toBeDefined(); expect(geometry.attributes.st).not.toBeDefined(); expect(geometry.attributes.compressedAttributes).toBeDefined(); const stNormal = geometry.attributes.compressedAttributes.values; expect(stNormal.length).toEqual(originalST.length); for (let i = 0; i < stNormal.length; i += 2) { expect( import__221.AttributeCompression.decompressTextureCoordinates( stNormal[i], new import__221.Cartesian2() ) ).toEqualEpsilon( import__221.Cartesian2.fromArray(originalST, i, new import__221.Cartesian2()), import__222.Math.EPSILON2 ); expect( import__221.AttributeCompression.octDecodeFloat(stNormal[i + 1], new import__221.Cartesian3()) ).toEqualEpsilon( import__221.Cartesian3.fromArray(originalNormals, i / 2 * 3), import__222.Math.EPSILON2 ); } }); it("compressVertices packs compressed tangents and bitangents", function() { let geometry = import__221.BoxGeometry.createGeometry( new import__221.BoxGeometry({ vertexFormat: new import__221.VertexFormat({ position: true, normal: true, tangent: true, bitangent: true }), maximum: new import__221.Cartesian3(25e4, 25e4, 25e4), minimum: new import__221.Cartesian3(-25e4, -25e4, -25e4) }) ); expect(geometry.attributes.normal).toBeDefined(); expect(geometry.attributes.tangent).toBeDefined(); expect(geometry.attributes.bitangent).toBeDefined(); const originalNormals = geometry.attributes.normal.values.slice(); const originalTangents = geometry.attributes.tangent.values.slice(); const originalBitangents = geometry.attributes.bitangent.values.slice(); geometry = import__221.GeometryPipeline.compressVertices(geometry); expect(geometry.attributes.tangent).not.toBeDefined(); expect(geometry.attributes.bitangent).not.toBeDefined(); expect(geometry.attributes.compressedAttributes).toBeDefined(); const compressedNormals = geometry.attributes.compressedAttributes.values; expect(compressedNormals.length).toEqual(originalNormals.length / 3 * 2); const normal = new import__221.Cartesian3(); const tangent = new import__221.Cartesian3(); const bitangent = new import__221.Cartesian3(); for (let i = 0; i < compressedNormals.length; i += 2) { const compressed = import__221.Cartesian2.fromArray( compressedNormals, i, new import__221.Cartesian2() ); import__221.AttributeCompression.octUnpack(compressed, normal, tangent, bitangent); expect(normal).toEqualEpsilon( import__221.Cartesian3.fromArray(originalNormals, i / 2 * 3), import__222.Math.EPSILON2 ); expect(tangent).toEqualEpsilon( import__221.Cartesian3.fromArray(originalTangents, i / 2 * 3), import__222.Math.EPSILON2 ); expect(bitangent).toEqualEpsilon( import__221.Cartesian3.fromArray(originalBitangents, i / 2 * 3), import__222.Math.EPSILON2 ); } }); it("splitLongitude does nothing for geometry not split by the IDL", function() { const instance = new import__221.GeometryInstance({ geometry: import__221.PolygonGeometry.createGeometry( import__221.PolygonGeometry.fromPositions({ positions: import__221.Cartesian3.fromDegreesArray([ -1, 1, -1, -1, 1, -1, 1, 1 ]), vertexFormat: import__221.VertexFormat.POSITION_ONLY, granularity: 2 * import__222.Math.RADIANS_PER_DEGREE }) ) }); const splitInstance = import__221.GeometryPipeline.splitLongitude(instance); expect(splitInstance).toBe(instance); }); it("splitLongitude interpolates custom attributes for geometry split by the IDL", function() { const p0 = import__221.Cartesian3.fromDegrees(-179, 0); const p1 = import__221.Cartesian3.fromDegrees(179, 0); const p2 = import__221.Cartesian3.fromDegrees(-179, 1); const positions = new Float64Array([ p0.x, p0.y, p0.z, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z ]); const vec4s = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0]); const vec3s = new Uint8Array([0, 0, 0, 0, 0, 255, 0, 0, 0]); const vec2s = new Uint8Array([0, 0, 0, 255, 0, 0]); const scalars = new Uint8Array([0, 255, 0]); const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: positions }), vec4s: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 4, values: vec4s }), vec3s: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 3, values: vec3s }), vec2s: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 2, values: vec2s }), scalars: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 1, values: scalars }) }, indices: new Uint16Array([0, 1, 2]), primitiveType: import__221.PrimitiveType.TRIANGLES, boundingSphere: import__221.BoundingSphere.fromVertices(positions) }) }); const splitInstance = import__221.GeometryPipeline.splitLongitude(instance); const eastHemisphereGeometry = splitInstance.eastHemisphereGeometry; expect(eastHemisphereGeometry.indices.length).toEqual(3); let newVec4s = eastHemisphereGeometry.attributes.vec4s.values; let newVec3s = eastHemisphereGeometry.attributes.vec3s.values; let newVec2s = eastHemisphereGeometry.attributes.vec2s.values; let newScalars = eastHemisphereGeometry.attributes.scalars.values; let i; let index; expect(Array.prototype.indexOf.call(newScalars, 127)).not.toBe(-1); expect(Array.prototype.indexOf.call(newVec4s, 127)).not.toBe(-1); expect(Array.prototype.indexOf.call(newVec3s, 127)).not.toBe(-1); expect(Array.prototype.indexOf.call(newVec2s, 127)).not.toBe(-1); for (i = 0; i < 3; i++) { expect(newScalars[i] === 255 || newScalars[i] === 127).toBe(true); index = i * 2; expect(newVec2s[index]).toBe(0); expect(newVec2s[index + 1] === 255 || newVec2s[index + 1] === 127).toBe( true ); index = i * 3; expect(newVec3s[index]).toBe(0); expect(newVec3s[index + 1]).toBe(0); expect(newVec3s[index + 2] === 255 || newVec3s[index + 2] === 127).toBe( true ); index = i * 4; expect(newVec4s[index]).toBe(0); expect(newVec4s[index + 1]).toBe(0); expect(newVec4s[index + 2]).toBe(0); expect(newVec4s[index + 3] === 255 || newVec4s[index + 3] === 127).toBe( true ); } const westHemisphereGeometry = splitInstance.westHemisphereGeometry; expect(westHemisphereGeometry.indices.length).toEqual(6); newVec4s = westHemisphereGeometry.attributes.vec4s.values; newVec3s = westHemisphereGeometry.attributes.vec3s.values; newVec2s = westHemisphereGeometry.attributes.vec2s.values; newScalars = westHemisphereGeometry.attributes.scalars.values; expect(Array.prototype.indexOf.call(newScalars, 127)).not.toBe(-1); expect(Array.prototype.indexOf.call(newVec4s, 127)).not.toBe(-1); expect(Array.prototype.indexOf.call(newVec3s, 127)).not.toBe(-1); expect(Array.prototype.indexOf.call(newVec2s, 127)).not.toBe(-1); for (i = 0; i < 4; i++) { expect(newScalars[i] === 0 || newScalars[i] === 127).toBe(true); index = i * 2; expect(newVec2s[index]).toBe(0); expect(newVec2s[index + 1] === 0 || newVec2s[index + 1] === 127).toBe( true ); index = i * 3; expect(newVec3s[index]).toBe(0); expect(newVec3s[index + 1]).toBe(0); expect(newVec3s[index + 2] === 0 || newVec3s[index + 2] === 127).toBe( true ); index = i * 4; expect(newVec4s[index]).toBe(0); expect(newVec4s[index + 1]).toBe(0); expect(newVec4s[index + 2]).toBe(0); expect(newVec4s[index + 3] === 0 || newVec4s[index + 3] === 127).toBe( true ); } }); it("splitLongitude provides indices for an un-indexed triangle list", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1, 0 ]) }) }, primitiveType: import__221.PrimitiveType.TRIANGLES }) }); import__221.GeometryPipeline.splitLongitude(instance); expect(instance.geometry.indices).toEqual([0, 1, 2, 3, 4, 5]); }); it("splitLongitude returns unchanged geometry if indices are already defined for an un-indexed triangle list", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1, 0 ]) }) }, primitiveType: import__221.PrimitiveType.TRIANGLES, indices: new Uint16Array([0, 1, 2, 3, 4, 5]) }) }); import__221.GeometryPipeline.splitLongitude(instance); expect(instance.geometry.indices).toEqual([0, 1, 2, 3, 4, 5]); }); it("splitLongitude throws when primitive type is TRIANGLES and number of vertices is less than 3", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([0, 1, 2]) }) }, primitiveType: import__221.PrimitiveType.TRIANGLES }) }); expect(function() { import__221.GeometryPipeline.splitLongitude(instance); }).toThrowDeveloperError(); }); it("splitLongitude throws when primitive type is TRIANGLES and number of vertices is not a multiple of 3", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1 ]) }) }, primitiveType: import__221.PrimitiveType.TRIANGLES }) }); expect(function() { import__221.GeometryPipeline.splitLongitude(instance); }).toThrowDeveloperError(); }); it("splitLongitude creates indexed triangles for a triangle fan", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6 ]) }) }, primitiveType: import__221.PrimitiveType.TRIANGLE_FAN }) }); import__221.GeometryPipeline.splitLongitude(instance); expect(instance.geometry.primitiveType).toEqual(import__221.PrimitiveType.TRIANGLES); expect(instance.geometry.indices).toEqual([0, 1, 2, 2, 1, 3]); }); it("splitLongitude throws when primitive type is TRIANGLE_FAN and number of vertices is less than 3", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([0, 1, 2]) }) }, primitiveType: import__221.PrimitiveType.TRIANGLE_FAN }) }); expect(function() { import__221.GeometryPipeline.splitLongitude(instance); }).toThrowDeveloperError(); }); it("splitLongitude creates indexd triangles for triangle strips", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1, 0 ]) }) }, primitiveType: import__221.PrimitiveType.TRIANGLE_STRIP }) }); import__221.GeometryPipeline.splitLongitude(instance); expect(instance.geometry.primitiveType).toEqual(import__221.PrimitiveType.TRIANGLES); expect(instance.geometry.indices).toEqual([ 0, 1, 2, 0, 2, 3, 3, 2, 4, 3, 4, 5 ]); }); it("splitLongitude throws when the primitive type is TRIANGLE_STRIP and number of vertices is less than 3", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([0, 1, 2]) }) }, primitiveType: import__221.PrimitiveType.TRIANGLE_STRIP }) }); expect(function() { import__221.GeometryPipeline.splitLongitude(instance); }).toThrowDeveloperError(); }); it("splitLongitude creates indexed lines", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6 ]) }) }, primitiveType: import__221.PrimitiveType.LINES }) }); import__221.GeometryPipeline.splitLongitude(instance); expect(instance.geometry.indices).toEqual([0, 1, 2, 3]); }); it("splitLongitude returns lines unchanged if indices are provided", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6 ]) }) }, primitiveType: import__221.PrimitiveType.LINES, indices: new Uint16Array([0, 1, 2, 3]) }) }); import__221.GeometryPipeline.splitLongitude(instance); expect(instance.geometry.indices).toEqual([0, 1, 2, 3]); }); it("splitLongitude throws when primitive type is LINES and number of vertices is less than 2", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([0, 1, 2]) }) }, primitiveType: import__221.PrimitiveType.LINES }) }); expect(function() { import__221.GeometryPipeline.splitLongitude(instance); }).toThrowDeveloperError(); }); it("splitLongitude throws when primitive type is LINES and number of vertices is not a multiple 2", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]) }) }, primitiveType: import__221.PrimitiveType.LINES }) }); expect(function() { import__221.GeometryPipeline.splitLongitude(instance); }).toThrowDeveloperError(); }); it("splitLongitude creates indexed lines from line strip", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6 ]) }) }, primitiveType: import__221.PrimitiveType.LINE_STRIP }) }); import__221.GeometryPipeline.splitLongitude(instance); expect(instance.geometry.primitiveType).toEqual(import__221.PrimitiveType.LINES); expect(instance.geometry.indices).toEqual([0, 1, 1, 2, 2, 3]); }); it("splitLongitude throws when primitive type is LINE_STRIP and number of vertices is less than 2", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([0, 1, 2]) }) }, primitiveType: import__221.PrimitiveType.LINE_STRIP }) }); expect(function() { import__221.GeometryPipeline.splitLongitude(instance); }).toThrowDeveloperError(); }); it("splitLongitude creates indexed lines from line loops", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6 ]) }) }, primitiveType: import__221.PrimitiveType.LINE_LOOP }) }); import__221.GeometryPipeline.splitLongitude(instance); expect(instance.geometry.primitiveType).toEqual(import__221.PrimitiveType.LINES); expect(instance.geometry.indices).toEqual([0, 1, 1, 2, 2, 3, 3, 0]); }); it("splitLongitude throws when the primitive type is LINE_LOOP and number of vertices is less than 2", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([0, 1, 2]) }) }, primitiveType: import__221.PrimitiveType.LINE_LOOP }) }); expect(function() { import__221.GeometryPipeline.splitLongitude(instance); }).toThrowDeveloperError(); }); it("splitLongitude subdivides triangle crossing the international date line, p0 behind", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, -1, 0, -1, 1, 2, -1, 2, 2 ]) }) }, indices: new Uint16Array([0, 1, 2]), primitiveType: import__221.PrimitiveType.TRIANGLES }) }); import__221.GeometryPipeline.splitLongitude(instance); expect(instance.geometry).not.toBeDefined(); expect(instance.westHemisphereGeometry).toBeDefined(); expect(instance.westHemisphereGeometry.indices).toBeDefined(); expect(instance.westHemisphereGeometry.indices.length).toEqual(3); expect(instance.westHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.westHemisphereGeometry.attributes.position.values.length ).toEqual(3 * 3); expect(instance.eastHemisphereGeometry).toBeDefined(); expect(instance.eastHemisphereGeometry.indices).toBeDefined(); expect(instance.eastHemisphereGeometry.indices.length).toEqual(6); expect(instance.eastHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.eastHemisphereGeometry.attributes.position.values.length ).toEqual(5 * 3); }); it("splitLongitude subdivides triangle crossing the international date line, p1 behind", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, 1, 2, -1, -1, 0, -1, 2, 2 ]) }) }, indices: new Uint16Array([0, 1, 2]), primitiveType: import__221.PrimitiveType.TRIANGLES }) }); import__221.GeometryPipeline.splitLongitude(instance); expect(instance.geometry).not.toBeDefined(); expect(instance.westHemisphereGeometry).toBeDefined(); expect(instance.westHemisphereGeometry.indices).toBeDefined(); expect(instance.westHemisphereGeometry.indices.length).toEqual(3); expect(instance.westHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.westHemisphereGeometry.attributes.position.values.length ).toEqual(3 * 3); expect(instance.eastHemisphereGeometry).toBeDefined(); expect(instance.eastHemisphereGeometry.indices).toBeDefined(); expect(instance.eastHemisphereGeometry.indices.length).toEqual(6); expect(instance.eastHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.eastHemisphereGeometry.attributes.position.values.length ).toEqual(5 * 3); }); it("splitLongitude subdivides triangle crossing the international date line, p2 behind", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, 1, 2, -1, 2, 2, -1, -1, 0 ]) }) }, indices: new Uint16Array([0, 1, 2]), primitiveType: import__221.PrimitiveType.TRIANGLES }) }); import__221.GeometryPipeline.splitLongitude(instance); expect(instance.geometry).not.toBeDefined(); expect(instance.westHemisphereGeometry).toBeDefined(); expect(instance.westHemisphereGeometry.indices).toBeDefined(); expect(instance.westHemisphereGeometry.indices.length).toEqual(3); expect(instance.westHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.westHemisphereGeometry.attributes.position.values.length ).toEqual(3 * 3); expect(instance.eastHemisphereGeometry).toBeDefined(); expect(instance.eastHemisphereGeometry.indices).toBeDefined(); expect(instance.eastHemisphereGeometry.indices.length).toEqual(6); expect(instance.eastHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.eastHemisphereGeometry.attributes.position.values.length ).toEqual(5 * 3); }); it("splitLongitude subdivides triangle crossing the international date line, p0 ahead", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, 1, 0, -1, -1, 0, -2, -1, 0 ]) }) }, indices: new Uint16Array([0, 1, 2]), primitiveType: import__221.PrimitiveType.TRIANGLES }) }); import__221.GeometryPipeline.splitLongitude(instance); expect(instance.geometry).not.toBeDefined(); expect(instance.westHemisphereGeometry).toBeDefined(); expect(instance.westHemisphereGeometry.indices).toBeDefined(); expect(instance.westHemisphereGeometry.indices.length).toEqual(6); expect(instance.westHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.westHemisphereGeometry.attributes.position.values.length ).toEqual(5 * 3); expect(instance.eastHemisphereGeometry).toBeDefined(); expect(instance.eastHemisphereGeometry.indices).toBeDefined(); expect(instance.eastHemisphereGeometry.indices.length).toEqual(3); expect(instance.eastHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.eastHemisphereGeometry.attributes.position.values.length ).toEqual(3 * 3); }); it("splitLongitude subdivides triangle crossing the international date line, p1 ahead", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -2, -1, 0, -1, 1, 0, -1, -1, 0 ]) }) }, indices: new Uint16Array([0, 1, 2]), primitiveType: import__221.PrimitiveType.TRIANGLES }) }); import__221.GeometryPipeline.splitLongitude(instance); expect(instance.geometry).not.toBeDefined(); expect(instance.westHemisphereGeometry).toBeDefined(); expect(instance.westHemisphereGeometry.indices).toBeDefined(); expect(instance.westHemisphereGeometry.indices.length).toEqual(6); expect(instance.westHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.westHemisphereGeometry.attributes.position.values.length ).toEqual(5 * 3); expect(instance.eastHemisphereGeometry).toBeDefined(); expect(instance.eastHemisphereGeometry.indices).toBeDefined(); expect(instance.eastHemisphereGeometry.indices.length).toEqual(3); expect(instance.eastHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.eastHemisphereGeometry.attributes.position.values.length ).toEqual(3 * 3); }); it("splitLongitude subdivides triangle crossing the international date line, p2 ahead", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, -1, 0, -2, -1, 0, -1, 1, 0 ]) }) }, indices: new Uint16Array([0, 1, 2]), primitiveType: import__221.PrimitiveType.TRIANGLES }) }); import__221.GeometryPipeline.splitLongitude(instance); expect(instance.geometry).not.toBeDefined(); expect(instance.westHemisphereGeometry).toBeDefined(); expect(instance.westHemisphereGeometry.indices).toBeDefined(); expect(instance.westHemisphereGeometry.indices.length).toEqual(6); expect(instance.westHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.westHemisphereGeometry.attributes.position.values.length ).toEqual(5 * 3); expect(instance.eastHemisphereGeometry).toBeDefined(); expect(instance.eastHemisphereGeometry.indices).toBeDefined(); expect(instance.eastHemisphereGeometry.indices.length).toEqual(3); expect(instance.eastHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.eastHemisphereGeometry.attributes.position.values.length ).toEqual(3 * 3); }); it("splitLongitude returns offset triangle that touches the international date line", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, 0, 1, -1, import__222.Math.EPSILON14, 2, -2, 2, 2 ]) }) }, indices: new Uint16Array([0, 1, 2]), primitiveType: import__221.PrimitiveType.TRIANGLES }) }); import__221.GeometryPipeline.splitLongitude(instance); const geometry = instance.geometry; expect(geometry.indices).toEqual([0, 1, 2]); const positions = geometry.attributes.position.values; expect(positions).toEqual([ -1, import__222.Math.EPSILON6, 1, -1, import__222.Math.EPSILON6, 2, -2, 2, 2 ]); expect(positions.length).toEqual(3 * 3); }); it("splitLongitude returns the same points if the triangle doesn't cross the international date line, behind", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, -1, 1, -1, -2, 1, -1, -2, 2 ]) }) }, indices: new Uint16Array([0, 1, 2]), primitiveType: import__221.PrimitiveType.TRIANGLES }) }); import__221.GeometryPipeline.splitLongitude(instance); const geometry = instance.geometry; expect(geometry.indices).toEqual([0, 1, 2]); const positions = geometry.attributes.position.values; expect(positions).toEqual([ -1, -1, 1, -1, -2, 1, -1, -2, 2 ]); expect(positions.length).toEqual(3 * 3); }); it("splitLongitude returns the same points if the triangle doesn't cross the international date line, ahead", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, 1, 1, -1, 2, 1, -1, 2, 2 ]) }) }, indices: new Uint16Array([0, 1, 2]), primitiveType: import__221.PrimitiveType.TRIANGLES }) }); import__221.GeometryPipeline.splitLongitude(instance); const geometry = instance.geometry; expect(geometry.indices).toEqual([0, 1, 2]); const positions = geometry.attributes.position.values; expect(positions).toEqual([-1, 1, 1, -1, 2, 1, -1, 2, 2]); expect(positions.length).toEqual(3 * 3); }); it("splitLongitude returns the same points if the triangle doesn't cross the international date line, positive x", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ 1, 1, 1, 1, 2, 1, 1, 2, 2 ]) }) }, indices: new Uint16Array([0, 1, 2]), primitiveType: import__221.PrimitiveType.TRIANGLES }) }); import__221.GeometryPipeline.splitLongitude(instance); const geometry = instance.geometry; expect(geometry.indices).toEqual([0, 1, 2]); const positions = geometry.attributes.position.values; expect(positions).toEqual([1, 1, 1, 1, 2, 1, 1, 2, 2]); expect(positions.length).toEqual(3 * 3); }); it("splitLongitude computes all attributes for a triangle crossing the international date line", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -2, -1, 0, -3, 1, 0, -1, 1, 0 ]) }), normal: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: new Float32Array([ 0, 0, 1, 0, 0, 1, 0, 0, 1 ]) }), tangent: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: new Float32Array([ -1, 0, 0, -1, 0, 0, -1, 0, 0 ]) }), bitangent: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: new Float32Array([ 0, -1, 0, 0, -1, 0, 0, -1, 0 ]) }), st: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 2, values: new Float32Array([0, 0, 1, 0, 0.5, 0.5]) }) }, indices: new Uint16Array([1, 2, 0]), primitiveType: import__221.PrimitiveType.TRIANGLES }) }); import__221.GeometryPipeline.splitLongitude(instance); expect(instance.geometry).not.toBeDefined(); expect(instance.westHemisphereGeometry).toBeDefined(); expect(instance.westHemisphereGeometry.indices).toBeDefined(); expect(instance.westHemisphereGeometry.indices.length).toEqual(3); expect(instance.westHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.westHemisphereGeometry.attributes.position.values.length ).toEqual(3 * 3); expect(instance.westHemisphereGeometry.attributes.normal).toBeDefined(); expect( instance.westHemisphereGeometry.attributes.normal.values.length ).toEqual(3 * 3); expect(instance.westHemisphereGeometry.attributes.bitangent).toBeDefined(); expect( instance.westHemisphereGeometry.attributes.bitangent.values.length ).toEqual(3 * 3); expect(instance.westHemisphereGeometry.attributes.tangent).toBeDefined(); expect( instance.westHemisphereGeometry.attributes.tangent.values.length ).toEqual(3 * 3); expect(instance.westHemisphereGeometry.attributes.st).toBeDefined(); expect(instance.westHemisphereGeometry.attributes.st.values.length).toEqual( 3 * 2 ); expect(instance.eastHemisphereGeometry).toBeDefined(); expect(instance.eastHemisphereGeometry.indices).toBeDefined(); expect(instance.eastHemisphereGeometry.indices.length).toEqual(6); expect(instance.eastHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.eastHemisphereGeometry.attributes.position.values.length ).toEqual(5 * 3); expect(instance.eastHemisphereGeometry.attributes.normal).toBeDefined(); expect( instance.eastHemisphereGeometry.attributes.normal.values.length ).toEqual(5 * 3); expect(instance.eastHemisphereGeometry.attributes.bitangent).toBeDefined(); expect( instance.eastHemisphereGeometry.attributes.bitangent.values.length ).toEqual(5 * 3); expect(instance.eastHemisphereGeometry.attributes.tangent).toBeDefined(); expect( instance.eastHemisphereGeometry.attributes.tangent.values.length ).toEqual(5 * 3); expect(instance.eastHemisphereGeometry.attributes.st).toBeDefined(); expect(instance.eastHemisphereGeometry.attributes.st.values.length).toEqual( 5 * 2 ); }); it("splitLongitude subdivides line crossing the international date line", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([-1, -1, 0, -1, 1, 2]) }) }, indices: new Uint16Array([0, 1]), primitiveType: import__221.PrimitiveType.LINES }) }); import__221.GeometryPipeline.splitLongitude(instance); expect(instance.geometry).not.toBeDefined(); expect(instance.westHemisphereGeometry).toBeDefined(); expect(instance.westHemisphereGeometry.indices).toBeDefined(); expect(instance.westHemisphereGeometry.indices.length).toEqual(2); expect(instance.westHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.westHemisphereGeometry.attributes.position.values.length ).toEqual(2 * 3); expect(instance.eastHemisphereGeometry).toBeDefined(); expect(instance.eastHemisphereGeometry.indices).toBeDefined(); expect(instance.eastHemisphereGeometry.indices.length).toEqual(2); expect(instance.eastHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.eastHemisphereGeometry.attributes.position.values.length ).toEqual(2 * 3); }); it("splitLongitude returns offset line that touches the international date line", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([-1, 0, 0, -1, 1, 2]) }) }, indices: new Uint16Array([0, 1]), primitiveType: import__221.PrimitiveType.LINES }) }); import__221.GeometryPipeline.splitLongitude(instance); const geometry = instance.geometry; expect(geometry.indices).toEqual([0, 1]); const positions = geometry.attributes.position.values; expect(positions).toEqual([-1, import__222.Math.EPSILON6, 0, -1, 1, 2]); }); it("splitLongitude returns the same points if the line doesn't cross the international date line", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([1, 1, 0, 1, 1, 2]) }) }, indices: new Uint16Array([0, 1]), primitiveType: import__221.PrimitiveType.LINES }) }); import__221.GeometryPipeline.splitLongitude(instance); const geometry = instance.geometry; expect(geometry.indices).toEqual([0, 1]); const positions = geometry.attributes.position.values; expect(positions).toEqual([1, 1, 0, 1, 1, 2]); }); it("splitLongitude does nothing for points", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([1, 1, 0, 1, 1, 2]) }) }, primitiveType: import__221.PrimitiveType.POINTS }) }); import__221.GeometryPipeline.splitLongitude(instance); const geometry = instance.geometry; expect(geometry.indices).not.toBeDefined(); const positions = geometry.attributes.position.values; expect(positions).toEqual([1, 1, 0, 1, 1, 2]); }); describe("splitLongitude polylines", function() { it("subdivides wide line crossing the international date line", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, -1, 0, -1, -1, 0, -1, 1, 2, -1, 1, 2 ]) }), nextPosition: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, 1, 2, -1, 1, 2, -1, 2, 3, -1, 2, 3 ]) }), prevPosition: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, -2, -1, -1, -2, -1, -1, -1, 0, -1, -1, 0 ]) }), expandAndWidth: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 2, values: new Float32Array([ -1, 5, 1, 5, -1, -5, 1, -5 ]) }) }, indices: new Uint16Array([0, 2, 1, 1, 2, 3]), primitiveType: import__221.PrimitiveType.TRIANGLES, geometryType: import__221.GeometryType.POLYLINES }) }); import__221.GeometryPipeline.splitLongitude(instance); expect(instance.geometry).not.toBeDefined(); expect(instance.westHemisphereGeometry).toBeDefined(); expect(instance.westHemisphereGeometry.indices).toBeDefined(); expect(instance.westHemisphereGeometry.indices.length).toEqual(6); expect(instance.westHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.westHemisphereGeometry.attributes.position.values.length ).toEqual(4 * 3); expect( instance.westHemisphereGeometry.attributes.nextPosition ).toBeDefined(); expect( instance.westHemisphereGeometry.attributes.nextPosition.values.length ).toEqual(4 * 3); expect( instance.westHemisphereGeometry.attributes.prevPosition ).toBeDefined(); expect( instance.westHemisphereGeometry.attributes.prevPosition.values.length ).toEqual(4 * 3); expect( instance.westHemisphereGeometry.attributes.expandAndWidth ).toBeDefined(); expect( instance.westHemisphereGeometry.attributes.expandAndWidth.values.length ).toEqual(4 * 2); expect(instance.eastHemisphereGeometry).toBeDefined(); expect(instance.eastHemisphereGeometry.indices).toBeDefined(); expect(instance.eastHemisphereGeometry.indices.length).toEqual(6); expect(instance.eastHemisphereGeometry.attributes.position).toBeDefined(); expect( instance.eastHemisphereGeometry.attributes.position.values.length ).toEqual(4 * 3); expect( instance.eastHemisphereGeometry.attributes.nextPosition ).toBeDefined(); expect( instance.eastHemisphereGeometry.attributes.nextPosition.values.length ).toEqual(4 * 3); expect( instance.eastHemisphereGeometry.attributes.prevPosition ).toBeDefined(); expect( instance.eastHemisphereGeometry.attributes.prevPosition.values.length ).toEqual(4 * 3); expect( instance.eastHemisphereGeometry.attributes.expandAndWidth ).toBeDefined(); expect( instance.eastHemisphereGeometry.attributes.expandAndWidth.values.length ).toEqual(4 * 2); }); it("returns offset wide line with first point on the IDL and the second is east", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, 0, 0, -1, 0, 0, -1, 1, 2, -1, 1, 2 ]) }), nextPosition: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, 1, 2, -1, 1, 2, -1, 2, 3, -1, 2, 3 ]) }), prevPosition: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, -2, -1, -1, -2, -1, -1, 0, 0, -1, 0, 0 ]) }), expandAndWidth: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 2, values: new Float32Array([ -1, 5, 1, 5, -1, -5, 1, -5 ]) }) }, indices: new Uint16Array([0, 2, 1, 1, 2, 3]), primitiveType: import__221.PrimitiveType.TRIANGLES, geometryType: import__221.GeometryType.POLYLINES }) }); import__221.GeometryPipeline.splitLongitude(instance); const geometry = instance.geometry; expect(geometry.indices).toEqual([0, 2, 1, 1, 2, 3]); const positions = geometry.attributes.position.values; const nextPositions = geometry.attributes.nextPosition.values; const prevPositions = geometry.attributes.prevPosition.values; expect(positions).toEqual([ -1, import__222.Math.EPSILON6, 0, -1, import__222.Math.EPSILON6, 0, -1, 1, 2, -1, 1, 2 ]); expect(prevPositions).toEqual([ -1, import__222.Math.EPSILON6, 0, -1, import__222.Math.EPSILON6, 0, -1, import__222.Math.EPSILON6, 0, -1, import__222.Math.EPSILON6, 0 ]); expect(nextPositions).toEqual([ -1, 1, 2, -1, 1, 2, -1, 2, 3, -1, 2, 3 ]); }); it("returns offset wide line with first point on the IDL and the second is west", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, 0, 0, -1, 0, 0, -1, -1, 2, -1, -1, 2 ]) }), nextPosition: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, -1, 2, -1, -1, 2, -1, -2, 0, -1, -2, 0 ]) }), prevPosition: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, 1, -1, -1, 1, -1, -1, 0, 0, -1, 0, 0 ]) }), expandAndWidth: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 2, values: new Float32Array([ -1, 5, 1, 5, -1, -5, 1, -5 ]) }) }, indices: new Uint16Array([0, 2, 1, 1, 2, 3]), primitiveType: import__221.PrimitiveType.TRIANGLES, geometryType: import__221.GeometryType.POLYLINES }) }); import__221.GeometryPipeline.splitLongitude(instance); const geometry = instance.geometry; expect(geometry.indices).toEqual([0, 2, 1, 1, 2, 3]); const positions = geometry.attributes.position.values; const nextPositions = geometry.attributes.nextPosition.values; const prevPositions = geometry.attributes.prevPosition.values; expect(positions).toEqual([ -1, -import__222.Math.EPSILON6, 0, -1, -import__222.Math.EPSILON6, 0, -1, -1, 2, -1, -1, 2 ]); expect(prevPositions).toEqual([ -1, -import__222.Math.EPSILON6, 0, -1, -import__222.Math.EPSILON6, 0, -1, -import__222.Math.EPSILON6, 0, -1, -import__222.Math.EPSILON6, 0 ]); expect(nextPositions).toEqual([ -1, -1, 2, -1, -1, 2, -1, -2, 0, -1, -2, 0 ]); }); it("returns offset wide line with first point is east and the second is on the IDL", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, 1, 2, -1, 1, 2, -1, 0, 0, -1, 0, 0 ]) }), nextPosition: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, 0, 0, -1, 0, 0, -1, -1, 2, -1, -1, 2 ]) }), prevPosition: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -2, 2, 2, -1, 2, 2, -1, 1, 2, -1, 1, 2 ]) }), expandAndWidth: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 2, values: new Float32Array([ -1, 5, 1, 5, -1, -5, 1, -5 ]) }) }, indices: new Uint16Array([0, 2, 1, 1, 2, 3]), primitiveType: import__221.PrimitiveType.TRIANGLES, geometryType: import__221.GeometryType.POLYLINES }) }); import__221.GeometryPipeline.splitLongitude(instance); const geometry = instance.geometry; expect(geometry.indices).toEqual([0, 2, 1, 1, 2, 3]); const positions = geometry.attributes.position.values; const nextPositions = geometry.attributes.nextPosition.values; const prevPositions = geometry.attributes.prevPosition.values; expect(positions).toEqual([ -1, 1, 2, -1, 1, 2, -1, import__222.Math.EPSILON6, 0, -1, import__222.Math.EPSILON6, 0 ]); expect(nextPositions).toEqual([ -1, import__222.Math.EPSILON6, 0, -1, import__222.Math.EPSILON6, 0, -1, import__222.Math.EPSILON6, 0, -1, import__222.Math.EPSILON6, 0 ]); expect(prevPositions).toEqual([ -2, 2, 2, -1, 2, 2, -1, 1, 2, -1, 1, 2 ]); }); it("returns offset wide line with first point is west and the second is on the IDL", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, -1, 2, -1, -1, 2, -1, 0, 0, -1, 0, 0 ]) }), nextPosition: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, 0, 0, -1, 0, 0, -1, 1, 2, -1, 1, 2 ]) }), prevPosition: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -2, -2, 2, -1, -2, 2, -1, -1, 2, -1, -1, 2 ]) }), expandAndWidth: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 2, values: new Float32Array([ -1, 5, 1, 5, -1, -5, 1, -5 ]) }) }, indices: new Uint16Array([0, 2, 1, 1, 2, 3]), primitiveType: import__221.PrimitiveType.TRIANGLES, geometryType: import__221.GeometryType.POLYLINES }) }); import__221.GeometryPipeline.splitLongitude(instance); const geometry = instance.geometry; expect(geometry.indices).toEqual([0, 2, 1, 1, 2, 3]); const positions = geometry.attributes.position.values; const nextPositions = geometry.attributes.nextPosition.values; const prevPositions = geometry.attributes.prevPosition.values; expect(positions).toEqual([ -1, -1, 2, -1, -1, 2, -1, -import__222.Math.EPSILON6, 0, -1, -import__222.Math.EPSILON6, 0 ]); expect(nextPositions).toEqual([ -1, -import__222.Math.EPSILON6, 0, -1, -import__222.Math.EPSILON6, 0, -1, -import__222.Math.EPSILON6, 0, -1, -import__222.Math.EPSILON6, 0 ]); expect(prevPositions).toEqual([ -2, -2, 2, -1, -2, 2, -1, -1, 2, -1, -1, 2 ]); }); it("returns the same points if the wide line doesn't cross the international date line", function() { const instance = new import__221.GeometryInstance({ geometry: new import__221.Geometry({ attributes: { position: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, 1, 0, -1, 1, 0, -1, 1, 2, -1, 1, 2 ]) }), nextPosition: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, 1, 2, -1, 1, 2, -1, 2, 3, -1, 2, 3 ]) }), prevPosition: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ -1, -2, -1, -1, -2, -1, -1, 0, 0, -1, 0, 0 ]) }), expandAndWidth: new import__221.GeometryAttribute({ componentDatatype: import__221.ComponentDatatype.FLOAT, componentsPerAttribute: 2, values: new Float32Array([ -1, 5, 1, 5, -1, -5, 1, -5 ]) }) }, indices: new Uint16Array([0, 2, 1, 1, 2, 3]), primitiveType: import__221.PrimitiveType.TRIANGLES, geometryType: import__221.GeometryType.POLYLINES }) }); import__221.GeometryPipeline.splitLongitude(instance); const geometry = instance.geometry; expect(geometry.indices).toEqual([0, 2, 1, 1, 2, 3]); const positions = geometry.attributes.position.values; expect(positions).toEqual([ -1, 1, 0, -1, 1, 0, -1, 1, 2, -1, 1, 2 ]); }); }); it("splitLongitude throws when geometry is undefined", function() { expect(function() { return import__221.GeometryPipeline.splitLongitude(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/GeometrySpec.js var import__223 = __toESM(require_Cesium(), 1); var import__224 = __toESM(require_Cesium(), 1); describe("Core/Geometry", function() { it("constructor", function() { const attributes = { position: new import__223.GeometryAttribute({ componentDatatype: import__223.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([0, 0, 0, 1, 0, 0, 0, 1, 0]) }) }; const indices = new Uint16Array([0, 1, 2]); const boundingSphere = new import__223.BoundingSphere( new import__223.Cartesian3(0.5, 0.5, 0), 1 ); const geometry = new import__223.Geometry({ attributes, indices, primitiveType: import__223.PrimitiveType.TRIANGLES, boundingSphere, geometryType: import__223.GeometryType.TRIANGLES }); expect(geometry.attributes).toBe(attributes); expect(geometry.indices).toBe(indices); expect(geometry.primitiveType).toEqual(import__223.PrimitiveType.TRIANGLES); expect(geometry.boundingSphere).toBe(boundingSphere); expect(geometry.geometryType).toEqual(import__223.GeometryType.TRIANGLES); }); it("constructor throws without attributes", function() { expect(function() { return new import__223.Geometry({ primitiveType: import__223.PrimitiveType.TRIANGLES }); }).toThrowDeveloperError(); }); it("computeNumberOfVertices", function() { const attributes = { position: new import__223.GeometryAttribute({ componentDatatype: import__223.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([0, 0, 0, 1, 0, 0, 0, 1, 0]) }), st: new import__223.GeometryAttribute({ componentDatatype: import__223.ComponentDatatype.FLOAT, componentsPerAttribute: 2, values: new Float32Array([0, 0, 1, 0, 0, 1]) }) }; const indices = new Uint16Array([0, 1, 2]); const boundingSphere = new import__223.BoundingSphere( new import__223.Cartesian3(0.5, 0.5, 0), 1 ); const geometry = new import__223.Geometry({ attributes, indices, primitiveType: import__223.PrimitiveType.TRIANGLES, boundingSphere }); expect(import__223.Geometry.computeNumberOfVertices(geometry)).toEqual(3); }); it("computeNumberOfVertices throws when attributes have different number of vertices", function() { const attributes = { position: new import__223.GeometryAttribute({ componentDatatype: import__223.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([0, 0, 0, 1, 0, 0, 0, 1, 0]) }), st: new import__223.GeometryAttribute({ componentDatatype: import__223.ComponentDatatype.FLOAT, componentsPerAttribute: 2, values: new Float32Array([0, 0, 1, 0]) }) }; const indices = new Uint16Array([0, 1, 2]); const boundingSphere = new import__223.BoundingSphere( new import__223.Cartesian3(0.5, 0.5, 0), 1 ); const geometry = new import__223.Geometry({ attributes, indices, primitiveType: import__223.PrimitiveType.TRIANGLES, boundingSphere }); expect(function() { import__223.Geometry.computeNumberOfVertices(geometry); }).toThrowDeveloperError(); }); it("computeNumberOfVertices throws without geometry", function() { expect(function() { import__223.Geometry.computeNumberOfVertices(); }).toThrowDeveloperError(); }); it("computes textureCoordinateRotationPoints for collections of points", function() { const positions = import__223.Cartesian3.fromDegreesArrayHeights([ -10, -10, 0, -10, 10, 0, 10, -10, 0, 10, 10, 0 ]); const boundingRectangle = import__223.Rectangle.fromCartesianArray(positions); const textureCoordinateRotationPoints = import__223.Geometry._textureCoordinateRotationPoints( positions, 0, import__223.Ellipsoid.WGS84, boundingRectangle ); expect(textureCoordinateRotationPoints.length).toEqual(6); expect(textureCoordinateRotationPoints[0]).toEqualEpsilon( 0, import__224.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[1]).toEqualEpsilon( 0, import__224.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[2]).toEqualEpsilon( 0, import__224.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[3]).toEqualEpsilon( 1, import__224.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[4]).toEqualEpsilon( 1, import__224.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[5]).toEqualEpsilon( 0, import__224.Math.EPSILON7 ); }); }); // packages/engine/Specs/Core/GoogleEarthEnterpriseMetadataSpec.js var import__225 = __toESM(require_Cesium(), 1); describe("Core/GoogleEarthEnterpriseMetadata", function() { it("tileXYToQuadKey", function() { expect(import__225.GoogleEarthEnterpriseMetadata.tileXYToQuadKey(1, 0, 0)).toEqual("2"); expect(import__225.GoogleEarthEnterpriseMetadata.tileXYToQuadKey(1, 2, 1)).toEqual( "02" ); expect(import__225.GoogleEarthEnterpriseMetadata.tileXYToQuadKey(3, 5, 2)).toEqual( "021" ); expect(import__225.GoogleEarthEnterpriseMetadata.tileXYToQuadKey(4, 7, 2)).toEqual( "100" ); }); it("quadKeyToTileXY", function() { expect(import__225.GoogleEarthEnterpriseMetadata.quadKeyToTileXY("2")).toEqual({ x: 1, y: 0, level: 0 }); expect(import__225.GoogleEarthEnterpriseMetadata.quadKeyToTileXY("02")).toEqual({ x: 1, y: 2, level: 1 }); expect(import__225.GoogleEarthEnterpriseMetadata.quadKeyToTileXY("021")).toEqual({ x: 3, y: 5, level: 2 }); expect(import__225.GoogleEarthEnterpriseMetadata.quadKeyToTileXY("100")).toEqual({ x: 4, y: 7, level: 2 }); }); it("decode", function() { import__225.Math.setRandomNumberSeed(123123); const key = new Uint8Array(1025); const data = new Uint8Array(1025); for (let i = 0; i < 1025; ++i) { key[i] = Math.floor(import__225.Math.nextRandomNumber() * 256); data[i] = Math.floor(import__225.Math.nextRandomNumber() * 256); } const keyBuffer = key.buffer.slice(0, 1024); const dataBuffer = data.buffer.slice(); const a = new Uint8Array(dataBuffer); (0, import__225.decodeGoogleEarthEnterpriseData)(keyBuffer, dataBuffer); expect(a).not.toEqual(data); (0, import__225.decodeGoogleEarthEnterpriseData)(keyBuffer, dataBuffer); expect(a).toEqual(data); }); it("decode requires key", function() { const data = new Uint8Array(3); expect(function() { (0, import__225.decodeGoogleEarthEnterpriseData)(void 0, data.buffer); }).toThrowDeveloperError(); }); it("decode requires data", function() { const key = new Uint8Array(4); expect(function() { (0, import__225.decodeGoogleEarthEnterpriseData)(key.buffer); }).toThrowDeveloperError(); }); it("decode throws if key length isn't greater than 0 and a multiple 4", function() { let key; const data = new Uint8Array(3); key = new Uint8Array(0); expect(function() { (0, import__225.decodeGoogleEarthEnterpriseData)(key.buffer, data.buffer); }).toThrowError(import__225.RuntimeError); key = new Uint8Array(1); expect(function() { (0, import__225.decodeGoogleEarthEnterpriseData)(key.buffer, data.buffer); }).toThrowError(import__225.RuntimeError); key = new Uint8Array(2); expect(function() { (0, import__225.decodeGoogleEarthEnterpriseData)(key.buffer, data.buffer); }).toThrowError(import__225.RuntimeError); key = new Uint8Array(3); expect(function() { (0, import__225.decodeGoogleEarthEnterpriseData)(key.buffer, data.buffer); }).toThrowError(import__225.RuntimeError); }); it("populateSubtree", async function() { const quad = "0123"; let index = 0; spyOn( import__225.GoogleEarthEnterpriseMetadata.prototype, "getQuadTreePacket" ).and.callFake(function(quadKey, version, request2) { quadKey = (0, import__225.defaultValue)(quadKey, "") + index.toString(); this._tileInfo[quadKey] = new import__225.GoogleEarthEnterpriseTileInformation( 255, 1, 1, 1 ); index = (index + 1) % 4; return Promise.resolve(); }); const metadata = await import__225.GoogleEarthEnterpriseMetadata.fromUrl( "http://test.server" ); const request = new import__225.Request({ throttle: true }); const tileXY = import__225.GoogleEarthEnterpriseMetadata.quadKeyToTileXY(quad); await metadata.populateSubtree(tileXY.x, tileXY.y, tileXY.level, request); expect( import__225.GoogleEarthEnterpriseMetadata.prototype.getQuadTreePacket.calls.count() ).toEqual(4); expect( import__225.GoogleEarthEnterpriseMetadata.prototype.getQuadTreePacket ).toHaveBeenCalledWith("", 1); expect( import__225.GoogleEarthEnterpriseMetadata.prototype.getQuadTreePacket ).toHaveBeenCalledWith("0", 1, request); expect( import__225.GoogleEarthEnterpriseMetadata.prototype.getQuadTreePacket ).toHaveBeenCalledWith("01", 1, request); expect( import__225.GoogleEarthEnterpriseMetadata.prototype.getQuadTreePacket ).toHaveBeenCalledWith("012", 1, request); const tileInfo = metadata._tileInfo; expect(tileInfo["0"]).toBeDefined(); expect(tileInfo["01"]).toBeDefined(); expect(tileInfo["012"]).toBeDefined(); expect(tileInfo["0123"]).toBeDefined(); }); it("from url resolves to GoogleEarthEnterpriseMetadata", async function() { const baseurl = "http://fake.fake.invalid/"; let req = 0; spyOn(import__225.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(responseType).toEqual("arraybuffer"); if (req === 0) { expect(url).toEqual(`${baseurl}dbRoot.v5?output=proto`); deferred.reject(); } else { expect(url).toEqual(`${baseurl}flatfile?q2-0-q.1`); import__225.Resource._DefaultImplementations.loadWithXhr( "Data/GoogleEarthEnterprise/gee.metadata", responseType, method, data, headers, deferred ); } ++req; }); const provider = await import__225.GoogleEarthEnterpriseMetadata.fromUrl(baseurl); expect(provider.imageryPresent).toBe(true); expect(provider.protoImagery).toBeUndefined(); expect(provider.terrainPresent).toBe(true); expect(provider.negativeAltitudeThreshold).toBe(import__225.Math.EPSILON12); expect(provider.negativeAltitudeExponentBias).toBe(32); expect(provider.providers).toEqual({}); const tileInfo = provider._tileInfo["0"]; expect(tileInfo).toBeDefined(); expect(tileInfo._bits).toEqual(64); expect(tileInfo.cnodeVersion).toEqual(2); expect(tileInfo.imageryVersion).toEqual(1); expect(tileInfo.terrainVersion).toEqual(1); expect(tileInfo.ancestorHasTerrain).toEqual(false); expect(tileInfo.terrainState).toBeUndefined(); }); it("fromUrl with Resource resolves to GoogleEarthEnterpriseMetadata", async function() { const baseurl = "http://fake.fake.invalid/"; const resource = new import__225.Resource({ url: baseurl }); let req = 0; spyOn(import__225.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(responseType).toEqual("arraybuffer"); if (req === 0) { expect(url).toEqual(`${baseurl}dbRoot.v5?output=proto`); deferred.reject(); } else { expect(url).toEqual(`${baseurl}flatfile?q2-0-q.1`); import__225.Resource._DefaultImplementations.loadWithXhr( "Data/GoogleEarthEnterprise/gee.metadata", responseType, method, data, headers, deferred ); } ++req; }); const metadata = await import__225.GoogleEarthEnterpriseMetadata.fromUrl(resource); expect(metadata.imageryPresent).toBe(true); expect(metadata.protoImagery).toBeUndefined(); expect(metadata.terrainPresent).toBe(true); expect(metadata.negativeAltitudeThreshold).toBe(import__225.Math.EPSILON12); expect(metadata.negativeAltitudeExponentBias).toBe(32); expect(metadata.providers).toEqual({}); const tileInfo = metadata._tileInfo["0"]; expect(tileInfo).toBeDefined(); expect(tileInfo._bits).toEqual(64); expect(tileInfo.cnodeVersion).toEqual(2); expect(tileInfo.imageryVersion).toEqual(1); expect(tileInfo.terrainVersion).toEqual(1); expect(tileInfo.ancestorHasTerrain).toEqual(false); expect(tileInfo.terrainState).toBeUndefined(); }); it("fromUrl rejects on error", async function() { const url = "host.invalid/"; await expectAsync( import__225.GoogleEarthEnterpriseMetadata.fromUrl(url) ).toBeRejectedWithError( import__225.RuntimeError, new RegExp("Request has failed. Status Code: 404") ); }); }); // packages/engine/Specs/Core/GoogleEarthEnterpriseTerrainDataSpec.js var import__226 = __toESM(require_Cesium(), 1); var import__227 = __toESM(require_Cesium(), 1); describe("Core/GoogleEarthEnterpriseTerrainData", function() { const sizeOfUint8 = Uint8Array.BYTES_PER_ELEMENT; const sizeOfUint16 = Uint16Array.BYTES_PER_ELEMENT; const sizeOfInt32 = Int32Array.BYTES_PER_ELEMENT; const sizeOfUint32 = Uint32Array.BYTES_PER_ELEMENT; const sizeOfFloat = Float32Array.BYTES_PER_ELEMENT; const sizeOfDouble = Float64Array.BYTES_PER_ELEMENT; const toEarthRadii = 1 / 6371010; function getBuffer(tilingScheme, x, y, level) { const rectangle = tilingScheme.tileXYToRectangle(x, y, level); const center = import__226.Rectangle.center(rectangle); const southwest = import__226.Rectangle.southwest(rectangle); const stepX = import__227.Math.toDegrees(rectangle.width / 2) / 180; const stepY = import__227.Math.toDegrees(rectangle.height / 2) / 180; const pointSize = 2 * sizeOfUint8 + sizeOfFloat; const faceSize = 3 * sizeOfUint16; const quadSize = 4 * sizeOfDouble + 3 * sizeOfInt32 + 4 * pointSize + 2 * faceSize; const totalSize = 4 * (quadSize + sizeOfUint32); const buf = new ArrayBuffer(totalSize); const dv = new DataView(buf); let altitudeStart = 0; let offset = 0; for (let i = 0; i < 4; ++i) { altitudeStart = 0; dv.setUint32(offset, quadSize, true); offset += sizeOfUint32; let xOrigin = southwest.longitude; let yOrigin = southwest.latitude; if ((i & 2) !== 0) { if ((i & 1) === 0) { xOrigin = center.longitude; altitudeStart = 10; } yOrigin = center.latitude; } else if ((i & 1) !== 0) { xOrigin = center.longitude; altitudeStart = 10; } dv.setFloat64(offset, import__227.Math.toDegrees(xOrigin) / 180, true); offset += sizeOfDouble; dv.setFloat64(offset, import__227.Math.toDegrees(yOrigin) / 180, true); offset += sizeOfDouble; dv.setFloat64(offset, stepX, true); offset += sizeOfDouble; dv.setFloat64(offset, stepY, true); offset += sizeOfDouble; dv.setInt32(offset, 4, true); offset += sizeOfInt32; dv.setInt32(offset, 2, true); offset += sizeOfInt32; dv.setInt32(offset, 0, true); offset += sizeOfInt32; let j; for (j = 0; j < 4; ++j) { let xPos = 0; let yPos = 0; let altitude = altitudeStart; if (j & 1) { ++xPos; altitude += 10; } if (j & 2) { ++yPos; } dv.setUint8(offset++, xPos); dv.setUint8(offset++, yPos); dv.setFloat32(offset, altitude * toEarthRadii, true); offset += sizeOfFloat; } const indices = [0, 1, 2, 1, 3, 2]; for (j = 0; j < indices.length; ++j) { dv.setUint16(offset, indices[j], true); offset += sizeOfUint16; } } return buf; } it("conforms to TerrainData interface", function() { expect(import__226.GoogleEarthEnterpriseTerrainData).toConformToInterface(import__226.TerrainData); }); describe("upsample", function() { it("works for all four children of a simple quad", function() { const maxShort = 32767; let tilingScheme = new import__226.GeographicTilingScheme(); const buffer = getBuffer(tilingScheme, 0, 0, 0); const data = new import__226.GoogleEarthEnterpriseTerrainData({ buffer, childTileMask: 15, negativeAltitudeExponentBias: 32, negativeElevationThreshold: import__227.Math.EPSILON12 }); tilingScheme = new import__226.GeographicTilingScheme(); const childRectangles = [ tilingScheme.tileXYToRectangle(0, 0, 1), tilingScheme.tileXYToRectangle(1, 0, 1), tilingScheme.tileXYToRectangle(0, 1, 1), tilingScheme.tileXYToRectangle(1, 1, 1) ]; return Promise.resolve( data.createMesh({ tilingScheme, x: 0, y: 0, level: 0 }) ).then(function() { const swPromise = data.upsample(tilingScheme, 0, 0, 0, 0, 0, 1); const sePromise = data.upsample(tilingScheme, 0, 0, 0, 1, 0, 1); const nwPromise = data.upsample(tilingScheme, 0, 0, 0, 0, 1, 1); const nePromise = data.upsample(tilingScheme, 0, 0, 0, 1, 1, 1); return Promise.all([swPromise, sePromise, nwPromise, nePromise]); }).then(function(upsampleResults) { expect(upsampleResults.length).toBe(4); for (let i = 0; i < upsampleResults.length; ++i) { const upsampled = upsampleResults[i]; expect(upsampled).toBeDefined(); const uBuffer = upsampled._uValues; const vBuffer = upsampled._vValues; const ib = upsampled._indices; const heights = upsampled._heightValues; expect(uBuffer.length).toBe(4); expect(vBuffer.length).toBe(4); expect(heights.length).toBe(4); expect(ib.length).toBe(6); const rectangle = childRectangles[i]; let north = 0; let south = 0; let east = 0; let west = 0; let index, u, v; for (let j = 0; j < ib.length; ++j) { index = ib[j]; u = uBuffer[index] / maxShort * rectangle.width + rectangle.west; v = vBuffer[index] / maxShort * rectangle.height + rectangle.south; if (import__227.Math.equalsEpsilon(u, rectangle.west, import__227.Math.EPSILON7)) { ++west; } else if (import__227.Math.equalsEpsilon(u, rectangle.east, import__227.Math.EPSILON7)) { ++east; } if (import__227.Math.equalsEpsilon( v, rectangle.south, import__227.Math.EPSILON7 )) { ++south; } else if (import__227.Math.equalsEpsilon( v, rectangle.north, import__227.Math.EPSILON7 )) { ++north; } } expect(north).toEqual(3); expect(south).toEqual(3); expect(east).toEqual(3); expect(west).toEqual(3); expect(upsampled._westIndices.length).toEqual(2); expect(upsampled._southIndices.length).toEqual(2); expect(upsampled._eastIndices.length).toEqual(2); expect(upsampled._northIndices.length).toEqual(2); } }); }); }); describe("createMesh", function() { let data; let tilingScheme; let buffer; beforeEach(function() { tilingScheme = new import__226.GeographicTilingScheme(); buffer = getBuffer(tilingScheme, 0, 0, 0); data = new import__226.GoogleEarthEnterpriseTerrainData({ buffer, childTileMask: 15, negativeAltitudeExponentBias: 32, negativeElevationThreshold: import__227.Math.EPSILON12 }); }); it("requires tilingScheme", function() { expect(function() { data.createMesh({ tilingScheme: void 0, x: 0, y: 0, level: 0 }); }).toThrowDeveloperError(); }); it("requires x", function() { expect(function() { data.createMesh({ tilingScheme, x: void 0, y: 0, level: 0 }); }).toThrowDeveloperError(); }); it("requires y", function() { expect(function() { data.createMesh({ tilingScheme, x: 0, y: void 0, level: 0 }); }).toThrowDeveloperError(); }); it("requires level", function() { expect(function() { data.createMesh({ tilingScheme, x: 0, y: 0, level: void 0 }); }).toThrowDeveloperError(); }); it("creates specified vertices plus skirt vertices", function() { const rectangle = tilingScheme.tileXYToRectangle(0, 0, 0); const wgs84 = import__226.Ellipsoid.WGS84; return data.createMesh({ tilingScheme, x: 0, y: 0, level: 0 }).then(function(mesh) { expect(mesh).toBeInstanceOf(import__226.TerrainMesh); expect(mesh.vertices.length).toBe(17 * mesh.encoding.stride); expect(mesh.indices.length).toBe(4 * 6 * 3); expect(mesh.minimumHeight).toBe(0); expect(mesh.maximumHeight).toBeCloseTo(20, 5); const encoding = mesh.encoding; const cartesian = new import__226.Cartesian3(); const cartographic = new import__226.Cartographic(); const count = mesh.vertices.length / mesh.encoding.stride; for (let i = 0; i < count; ++i) { const height = encoding.decodeHeight(mesh.vertices, i); if (i < 9) { expect(height).toBeBetween(0, 20); encoding.decodePosition(mesh.vertices, i, cartesian); wgs84.cartesianToCartographic(cartesian, cartographic); cartographic.longitude = import__227.Math.convertLongitudeRange( cartographic.longitude ); expect(import__226.Rectangle.contains(rectangle, cartographic)).toBe(true); } else { expect(height).toBeBetween(-1e3, -980); } } }); }); it("exaggerates mesh", function() { return data.createMesh({ tilingScheme, x: 0, y: 0, level: 0, exaggeration: 2 }).then(function(mesh) { expect(mesh).toBeInstanceOf(import__226.TerrainMesh); expect(mesh.vertices.length).toBe(17 * mesh.encoding.stride); expect(mesh.indices.length).toBe(4 * 6 * 3); expect(mesh.minimumHeight).toBe(0); expect(mesh.maximumHeight).toBeCloseTo(20, 5); expect(mesh.encoding.exaggeration).toBe(2); const encoding = mesh.encoding; const count = mesh.vertices.length / mesh.encoding.stride; for (let i = 0; i < count; ++i) { const height = encoding.decodeHeight(mesh.vertices, i); if (i < 9) { expect(height).toBeBetween(0, 40); } else { expect(height).toBeBetween(-1e3, -960); } } }); }); }); describe("interpolateHeight", function() { let tilingScheme; let rectangle; let mesh; beforeEach(function() { tilingScheme = new import__226.GeographicTilingScheme(); rectangle = tilingScheme.tileXYToRectangle(7, 6, 5); const buffer = getBuffer(tilingScheme, 7, 6, 5); mesh = new import__226.GoogleEarthEnterpriseTerrainData({ buffer, childTileMask: 15, negativeAltitudeExponentBias: 32, negativeElevationThreshold: import__227.Math.EPSILON12 }); }); it("clamps coordinates if given a position outside the mesh", function() { expect(mesh.interpolateHeight(rectangle, 0, 0)).toBe( mesh.interpolateHeight(rectangle, rectangle.east, rectangle.south) ); }); it("returns a height interpolated from the correct triangle", function() { let longitude = rectangle.west + (rectangle.east - rectangle.west) * 0.25; let latitude = rectangle.south + (rectangle.north - rectangle.south) * 0.75; let result = mesh.interpolateHeight(rectangle, longitude, latitude); expect(result).toBeBetween(0, 10); longitude = rectangle.west + (rectangle.east - rectangle.west) * 0.75; latitude = rectangle.south + (rectangle.north - rectangle.south) * 0.25; result = mesh.interpolateHeight(rectangle, longitude, latitude); expect(result).toBeBetween(10, 20); longitude = rectangle.west + (rectangle.east - rectangle.west) * 0.5; latitude = rectangle.south + (rectangle.north - rectangle.south) * 0.5; result = mesh.interpolateHeight(rectangle, longitude, latitude); expect(result).toEqualEpsilon(10, 1e-6); }); }); describe("isChildAvailable", function() { let data; beforeEach(function() { data = new import__226.GoogleEarthEnterpriseTerrainData({ buffer: new ArrayBuffer(1), childTileMask: 15, negativeAltitudeExponentBias: 32, negativeElevationThreshold: import__227.Math.EPSILON12 }); }); it("requires thisX", function() { expect(function() { data.isChildAvailable(void 0, 0, 0, 0); }).toThrowDeveloperError(); }); it("requires thisY", function() { expect(function() { data.isChildAvailable(0, void 0, 0, 0); }).toThrowDeveloperError(); }); it("requires childX", function() { expect(function() { data.isChildAvailable(0, 0, void 0, 0); }).toThrowDeveloperError(); }); it("requires childY", function() { expect(function() { data.isChildAvailable(0, 0, 0, void 0); }).toThrowDeveloperError(); }); it("returns true for all children when child mask is not explicitly specified", function() { data = new import__226.GoogleEarthEnterpriseTerrainData({ buffer: new ArrayBuffer(1), negativeAltitudeExponentBias: 32, negativeElevationThreshold: import__227.Math.EPSILON12 }); expect(data.isChildAvailable(10, 20, 20, 40)).toBe(true); expect(data.isChildAvailable(10, 20, 21, 40)).toBe(true); expect(data.isChildAvailable(10, 20, 20, 41)).toBe(true); expect(data.isChildAvailable(10, 20, 21, 41)).toBe(true); }); it("works when only southwest child is available", function() { data = new import__226.GoogleEarthEnterpriseTerrainData({ buffer: new ArrayBuffer(1), childTileMask: 1, negativeAltitudeExponentBias: 32, negativeElevationThreshold: import__227.Math.EPSILON12 }); expect(data.isChildAvailable(10, 20, 20, 40)).toBe(false); expect(data.isChildAvailable(10, 20, 21, 40)).toBe(false); expect(data.isChildAvailable(10, 20, 20, 41)).toBe(true); expect(data.isChildAvailable(10, 20, 21, 41)).toBe(false); }); it("works when only southeast child is available", function() { data = new import__226.GoogleEarthEnterpriseTerrainData({ buffer: new ArrayBuffer(1), childTileMask: 2, negativeAltitudeExponentBias: 32, negativeElevationThreshold: import__227.Math.EPSILON12 }); expect(data.isChildAvailable(10, 20, 20, 40)).toBe(false); expect(data.isChildAvailable(10, 20, 21, 40)).toBe(false); expect(data.isChildAvailable(10, 20, 20, 41)).toBe(false); expect(data.isChildAvailable(10, 20, 21, 41)).toBe(true); }); it("works when only northeast child is available", function() { data = new import__226.GoogleEarthEnterpriseTerrainData({ buffer: new ArrayBuffer(1), childTileMask: 4, negativeAltitudeExponentBias: 32, negativeElevationThreshold: import__227.Math.EPSILON12 }); expect(data.isChildAvailable(10, 20, 20, 40)).toBe(false); expect(data.isChildAvailable(10, 20, 21, 40)).toBe(true); expect(data.isChildAvailable(10, 20, 20, 41)).toBe(false); expect(data.isChildAvailable(10, 20, 21, 41)).toBe(false); }); it("works when only northwest child is available", function() { data = new import__226.GoogleEarthEnterpriseTerrainData({ buffer: new ArrayBuffer(1), childTileMask: 8, negativeAltitudeExponentBias: 32, negativeElevationThreshold: import__227.Math.EPSILON12 }); expect(data.isChildAvailable(10, 20, 20, 40)).toBe(true); expect(data.isChildAvailable(10, 20, 21, 40)).toBe(false); expect(data.isChildAvailable(10, 20, 20, 41)).toBe(false); expect(data.isChildAvailable(10, 20, 21, 41)).toBe(false); }); }); it("requires buffer", function() { expect(function() { const data = new import__226.GoogleEarthEnterpriseTerrainData({ childTileMask: 8, negativeAltitudeExponentBias: 32, negativeElevationThreshold: import__227.Math.EPSILON12 }); }).toThrowDeveloperError(); }); it("requires negativeAltitudeExponentBias", function() { expect(function() { const data = new import__226.GoogleEarthEnterpriseTerrainData({ buffer: new ArrayBuffer(1), childTileMask: 8, negativeElevationThreshold: import__227.Math.EPSILON12 }); }).toThrowDeveloperError(); }); it("requires negativeElevationThreshold", function() { expect(function() { const data = new import__226.GoogleEarthEnterpriseTerrainData({ buffer: new ArrayBuffer(1), childTileMask: 8, negativeAltitudeExponentBias: 32 }); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/GoogleEarthEnterpriseTerrainProviderSpec.js var import__228 = __toESM(require_Cesium(), 1); describe("Core/GoogleEarthEnterpriseTerrainProvider", function() { function installMockGetQuadTreePacket() { spyOn( import__228.GoogleEarthEnterpriseMetadata.prototype, "getQuadTreePacket" ).and.callFake(function(quadKey, version) { quadKey = (0, import__228.defaultValue)(quadKey, ""); let t = new import__228.GoogleEarthEnterpriseTileInformation(255, 1, 1, 1); t.ancestorHasTerrain = true; this._tileInfo[`${quadKey}0`] = t; t = new import__228.GoogleEarthEnterpriseTileInformation(255, 1, 1, 1); t.ancestorHasTerrain = true; this._tileInfo[`${quadKey}1`] = t; t = new import__228.GoogleEarthEnterpriseTileInformation(255, 1, 1, 1); t.ancestorHasTerrain = true; this._tileInfo[`${quadKey}2`] = t; t = new import__228.GoogleEarthEnterpriseTileInformation(255, 1, 1, 1); t.ancestorHasTerrain = true; this._tileInfo[`${quadKey}3`] = t; return Promise.resolve(); }); } let terrainProvider; async function waitForTile(level, x, y, f) { const metadata = await import__228.GoogleEarthEnterpriseMetadata.fromUrl("made/up/url"); terrainProvider = import__228.GoogleEarthEnterpriseTerrainProvider.fromMetadata( metadata ); return pollToPromise_default(function() { return terrainProvider.getTileDataAvailable(x, y, level); }).then(function() { const promise = terrainProvider.requestTileGeometry(level, x, y); return Promise.resolve(promise, f, function(error) { expect("requestTileGeometry").toBe("returning a tile."); }); }); } function createRequest() { return new import__228.Request({ throttleByServer: true }); } beforeEach(function() { import__228.RequestScheduler.clearForSpecs(); }); afterEach(function() { import__228.Resource._Implementations.loadWithXhr = import__228.Resource._DefaultImplementations.loadWithXhr; }); it("conforms to TerrainProvider interface", function() { expect(import__228.GoogleEarthEnterpriseTerrainProvider).toConformToInterface( import__228.TerrainProvider ); }); it("fromMetadata throws without metadata", function() { installMockGetQuadTreePacket(); expect( () => import__228.GoogleEarthEnterpriseTerrainProvider.fromMetadata() ).toThrowDeveloperError("metadata is required, actual value was undefined"); }); it("fromMetadata throws if there isn't terrain", async function() { installMockGetQuadTreePacket(); const metadata = await import__228.GoogleEarthEnterpriseMetadata.fromUrl("made/up/url"); metadata.terrainPresent = false; expect( () => import__228.GoogleEarthEnterpriseTerrainProvider.fromMetadata(metadata) ).toThrowError( import__228.RuntimeError, "The server made/up/url/ doesn't have terrain" ); }); it("uses geographic tiling scheme by default", async function() { installMockGetQuadTreePacket(); const metadata = await import__228.GoogleEarthEnterpriseMetadata.fromUrl("made/up/url"); terrainProvider = import__228.GoogleEarthEnterpriseTerrainProvider.fromMetadata( metadata ); expect(terrainProvider.tilingScheme).toBeInstanceOf(import__228.GeographicTilingScheme); }); it("can use a custom ellipsoid", async function() { installMockGetQuadTreePacket(); const ellipsoid = new import__228.Ellipsoid(1, 2, 3); const metadata = await import__228.GoogleEarthEnterpriseMetadata.fromUrl("made/up/url"); terrainProvider = import__228.GoogleEarthEnterpriseTerrainProvider.fromMetadata( metadata, { ellipsoid } ); expect(terrainProvider.tilingScheme.ellipsoid).toEqual(ellipsoid); }); it("has error event", async function() { installMockGetQuadTreePacket(); const metadata = await import__228.GoogleEarthEnterpriseMetadata.fromUrl("made/up/url"); terrainProvider = import__228.GoogleEarthEnterpriseTerrainProvider.fromMetadata( metadata ); expect(terrainProvider.errorEvent).toBeDefined(); expect(terrainProvider.errorEvent).toBe(terrainProvider.errorEvent); }); it("returns reasonable geometric error for various levels", async function() { installMockGetQuadTreePacket(); const metadata = await import__228.GoogleEarthEnterpriseMetadata.fromUrl("made/up/url"); terrainProvider = import__228.GoogleEarthEnterpriseTerrainProvider.fromMetadata( metadata ); expect(terrainProvider.getLevelMaximumGeometricError(0)).toBeGreaterThan( 0 ); expect(terrainProvider.getLevelMaximumGeometricError(0)).toEqualEpsilon( terrainProvider.getLevelMaximumGeometricError(1) * 2, import__228.Math.EPSILON10 ); expect(terrainProvider.getLevelMaximumGeometricError(1)).toEqualEpsilon( terrainProvider.getLevelMaximumGeometricError(2) * 2, import__228.Math.EPSILON10 ); }); it("credit is undefined if credit is not provided", async function() { installMockGetQuadTreePacket(); const metadata = await import__228.GoogleEarthEnterpriseMetadata.fromUrl("made/up/url"); terrainProvider = import__228.GoogleEarthEnterpriseTerrainProvider.fromMetadata( metadata ); expect(terrainProvider.credit).toBeUndefined(); }); it("logo is defined if credit is provided", async function() { installMockGetQuadTreePacket(); const metadata = await import__228.GoogleEarthEnterpriseMetadata.fromUrl("made/up/url"); terrainProvider = import__228.GoogleEarthEnterpriseTerrainProvider.fromMetadata( metadata, { credit: "thanks to our awesome made up contributors!" } ); expect(terrainProvider.credit).toBeDefined(); }); it("has a water mask is false", async function() { installMockGetQuadTreePacket(); const metadata = await import__228.GoogleEarthEnterpriseMetadata.fromUrl("made/up/url"); terrainProvider = import__228.GoogleEarthEnterpriseTerrainProvider.fromMetadata( metadata ); expect(terrainProvider.hasWaterMask).toBe(false); }); it("has vertex normals is false", async function() { installMockGetQuadTreePacket(); const metadata = await import__228.GoogleEarthEnterpriseMetadata.fromUrl("made/up/url"); terrainProvider = import__228.GoogleEarthEnterpriseTerrainProvider.fromMetadata( metadata ); expect(terrainProvider.hasVertexNormals).toBe(false); }); describe("requestTileGeometry", function() { it("provides GoogleEarthEnterpriseTerrainData", function() { installMockGetQuadTreePacket(); import__228.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__228.Resource._DefaultImplementations.loadWithXhr( "Data/GoogleEarthEnterprise/gee.terrain", responseType, method, data, headers, deferred ); }; return waitForTile(0, 0, 0, function(loadedData) { expect(loadedData).toBeInstanceOf(import__228.GoogleEarthEnterpriseTerrainData); }); }); it("provides GoogleEarthEnterpriseTerrainData with fromMetadata", async function() { installMockGetQuadTreePacket(); import__228.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__228.Resource._DefaultImplementations.loadWithXhr( "Data/GoogleEarthEnterprise/gee.terrain", responseType, method, data, headers, deferred ); }; const metadata = await import__228.GoogleEarthEnterpriseMetadata.fromUrl( "made/up/url" ); terrainProvider = import__228.GoogleEarthEnterpriseTerrainProvider.fromMetadata( metadata ); await pollToPromise_default(function() { return terrainProvider.getTileDataAvailable(0, 0, 0); }); const loadedData = await terrainProvider.requestTileGeometry(0, 0, 0); expect(loadedData).toBeInstanceOf(import__228.GoogleEarthEnterpriseTerrainData); }); it("returns undefined if too many requests are already in progress", async function() { installMockGetQuadTreePacket(); const baseUrl = "made/up/url"; const deferreds = []; let loadRealTile = true; import__228.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { if (url.indexOf("dbRoot.v5") !== -1) { return deferred.reject(); } if (loadRealTile) { loadRealTile = false; return import__228.Resource._DefaultImplementations.loadWithXhr( "Data/GoogleEarthEnterprise/gee.terrain", responseType, method, data, headers, deferred ); } deferreds.push(deferred); }; const metadata = await import__228.GoogleEarthEnterpriseMetadata.fromUrl(baseUrl); terrainProvider = import__228.GoogleEarthEnterpriseTerrainProvider.fromMetadata( metadata ); const promises = []; return pollToPromise_default(function() { let b = true; for (let i = 0; i < import__228.RequestScheduler.maximumRequestsPerServer + 2; ++i) { b = b && terrainProvider.getTileDataAvailable(i, i, i); } return b && terrainProvider.getTileDataAvailable(1, 2, 3); }).then(function() { let promise; for (let i = 0; i < import__228.RequestScheduler.maximumRequestsPerServer; ++i) { const request = new import__228.Request({ throttle: true, throttleByServer: true }); promise = terrainProvider.requestTileGeometry(i, i, i, request); promises.push(promise); } import__228.RequestScheduler.update(); expect(promise).toBeDefined(); return terrainProvider.requestTileGeometry(1, 2, 3, createRequest()); }).then(function(terrainData) { expect(terrainData).toBeUndefined(); for (let i = 0; i < deferreds.length; ++i) { deferreds[i].resolve(); } return Promise.all(promises).catch(function() { loadRealTile = true; return terrainProvider.requestTileGeometry(1, 2, 3); }); }).then(function(terrainData) { expect(terrainData).toBeDefined(); }); }); it("supports getTileDataAvailable()", async function() { installMockGetQuadTreePacket(); const baseUrl = "made/up/url"; import__228.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__228.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.terrain", responseType, method, data, headers, deferred ); }; const metadata = await import__228.GoogleEarthEnterpriseMetadata.fromUrl(baseUrl); terrainProvider = import__228.GoogleEarthEnterpriseTerrainProvider.fromMetadata( metadata ); const tileInfo = terrainProvider._metadata._tileInfo; const info = tileInfo[import__228.GoogleEarthEnterpriseMetadata.tileXYToQuadKey(0, 1, 0)]; info._bits = 127; info.terrainState = 1; info.ancestorHasTerrain = true; expect(terrainProvider.getTileDataAvailable(0, 0, 0)).toBe(true); expect(terrainProvider.getTileDataAvailable(0, 1, 0)).toBe(false); expect(terrainProvider.getTileDataAvailable(1, 0, 0)).toBe(true); expect(terrainProvider.getTileDataAvailable(1, 1, 0)).toBe(true); expect(terrainProvider.getTileDataAvailable(0, 0, 2)).toBe(false); }); }); }); // packages/engine/Specs/Core/GregorianDateSpec.js var import__229 = __toESM(require_Cesium(), 1); describe("Core/GregorianDate", function() { describe("With valid parameters", function() { it("Constructs any valid date", function() { const validDate = new import__229.GregorianDate(2022, 2, 4, 23, 54, 0, 999.9, false); expect(validDate.year).toEqual(2022); expect(validDate.month).toEqual(2); expect(validDate.day).toEqual(4); expect(validDate.hour).toEqual(23); expect(validDate.minute).toEqual(54); expect(validDate.second).toEqual(0); expect(validDate.millisecond).toEqual(999.9); expect(validDate.isLeapSecond).toBe(false); }); it("Constructs valid leap year date", function() { const validDate = new import__229.GregorianDate(2024, 2, 29, 23, 54, 0, 999.9, false); expect(validDate.year).toEqual(2024); expect(validDate.month).toEqual(2); expect(validDate.day).toEqual(29); expect(validDate.hour).toEqual(23); expect(validDate.minute).toEqual(54); expect(validDate.second).toEqual(0); expect(validDate.millisecond).toEqual(999.9); expect(validDate.isLeapSecond).toBe(false); }); it("Constructs the minimum date when no parameters are passed", function() { const minimumDate = new import__229.GregorianDate(); expect(minimumDate.year).toEqual(1); expect(minimumDate.month).toEqual(1); expect(minimumDate.day).toEqual(1); expect(minimumDate.hour).toEqual(0); expect(minimumDate.minute).toEqual(0); expect(minimumDate.second).toEqual(0); expect(minimumDate.millisecond).toEqual(0); expect(minimumDate.isLeapSecond).toBe(false); }); it("Constructs valid dates for edge cases of days", function() { expect(function() { return new import__229.GregorianDate(2022, 1, 31); }).not.toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2e3, 2, 28); }).not.toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2020, 2, 29); }).not.toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 3, 31); }).not.toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 4, 30); }).not.toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 5, 31); }).not.toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 6, 30); }).not.toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 7, 31); }).not.toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 8, 31); }).not.toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 9, 30); }).not.toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 10, 31); }).not.toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 11, 30); }).not.toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 12, 31); }).not.toThrowDeveloperError(); }); it("Constructs the minimum possible date of the year when only year parameter is passed", function() { const minimumDate = new import__229.GregorianDate(2022); expect(minimumDate.year).toEqual(2022); expect(minimumDate.month).toEqual(1); expect(minimumDate.day).toEqual(1); expect(minimumDate.hour).toEqual(0); expect(minimumDate.minute).toEqual(0); expect(minimumDate.second).toEqual(0); expect(minimumDate.millisecond).toEqual(0); expect(minimumDate.isLeapSecond).toBe(false); }); it("Constructs the minimum possible day of the month when only year and month parameters are passed", function() { const minimumDate = new import__229.GregorianDate(2022, 2); expect(minimumDate.year).toEqual(2022); expect(minimumDate.month).toEqual(2); expect(minimumDate.day).toEqual(1); expect(minimumDate.hour).toEqual(0); expect(minimumDate.minute).toEqual(0); expect(minimumDate.second).toEqual(0); expect(minimumDate.millisecond).toEqual(0); expect(minimumDate.isLeapSecond).toBe(false); }); it("Constructs the minimum possible time of the day when only year, month and day parameters are passed", function() { const minimumDate = new import__229.GregorianDate(2022, 2, 28); expect(minimumDate.year).toEqual(2022); expect(minimumDate.month).toEqual(2); expect(minimumDate.day).toEqual(28); expect(minimumDate.hour).toEqual(0); expect(minimumDate.minute).toEqual(0); expect(minimumDate.second).toEqual(0); expect(minimumDate.millisecond).toEqual(0); expect(minimumDate.isLeapSecond).toBe(false); }); it("Constructs the minimum possible time of the day when only year, month, day and hour parameters are passed", function() { const minimumDate = new import__229.GregorianDate(2022, 2, 28, 10); expect(minimumDate.year).toEqual(2022); expect(minimumDate.month).toEqual(2); expect(minimumDate.day).toEqual(28); expect(minimumDate.hour).toEqual(10); expect(minimumDate.minute).toEqual(0); expect(minimumDate.second).toEqual(0); expect(minimumDate.millisecond).toEqual(0); expect(minimumDate.isLeapSecond).toBe(false); }); it("Constructs the minimum possible time of the day when only year, month, day, hour and minutes parameters are passed", function() { const minimumDate = new import__229.GregorianDate(2022, 2, 28, 10, 59); expect(minimumDate.year).toEqual(2022); expect(minimumDate.month).toEqual(2); expect(minimumDate.day).toEqual(28); expect(minimumDate.hour).toEqual(10); expect(minimumDate.minute).toEqual(59); expect(minimumDate.second).toEqual(0); expect(minimumDate.millisecond).toEqual(0); expect(minimumDate.isLeapSecond).toBe(false); }); it("Constructs the minimum possible time of the day when only year, month, day, hour, minutes and seconds parameters are passed", function() { const minimumDate = new import__229.GregorianDate(2022, 2, 28, 10, 59, 59); expect(minimumDate.year).toEqual(2022); expect(minimumDate.month).toEqual(2); expect(minimumDate.day).toEqual(28); expect(minimumDate.hour).toEqual(10); expect(minimumDate.minute).toEqual(59); expect(minimumDate.second).toEqual(59); expect(minimumDate.millisecond).toEqual(0); expect(minimumDate.isLeapSecond).toBe(false); }); it("Constructs the date with leap second", function() { const minimumDate = new import__229.GregorianDate(2022, 2, 28, 10, 59, 60, 100, true); expect(minimumDate.year).toEqual(2022); expect(minimumDate.month).toEqual(2); expect(minimumDate.day).toEqual(28); expect(minimumDate.hour).toEqual(10); expect(minimumDate.minute).toEqual(59); expect(minimumDate.second).toEqual(60); expect(minimumDate.millisecond).toEqual(100); expect(minimumDate.isLeapSecond).toBe(true); }); }); describe("With invalid parameters", function() { it("Should throw error if invalid year is passed", function() { expect(function() { return new import__229.GregorianDate(-1, 2, 4, 23, 54, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(0, 2, 4, 23, 54, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(1e4, 2, 4, 23, 54, 0, 999.9, false); }).toThrowDeveloperError(); }); it("Should throw error if invalid month is passed", function() { expect(function() { return new import__229.GregorianDate(2022, -1, 4, 23, 54, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 0, 4, 23, 54, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 13, 4, 23, 54, 0, 999.9, false); }).toThrowDeveloperError(); }); it("Should throw error if invalid day is passed", function() { expect(function() { return new import__229.GregorianDate(2022, 12, -10, 23, 54, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 12, 0, 23, 54, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 12, 32, 23, 54, 0, 999.9, false); }).toThrowDeveloperError(); }); it("Should throw error if day is out of range for month", function() { expect(function() { return new import__229.GregorianDate(2020, 2, 30, 23, 54, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 11, 31, 23, 54, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 4, 31, 23, 54, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 6, 31, 23, 54, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 9, 31, 23, 54, 0, 999.9, false); }).toThrowDeveloperError(); }); it("Should throw error if leap day is given for non-leap year", function() { expect(function() { return new import__229.GregorianDate(2022, 2, 29, 23, 54, 0, 999.9, false); }).toThrowDeveloperError(); }); it("Should throw error if invalid hours is passed", function() { expect(function() { return new import__229.GregorianDate(2022, 2, 4, -10, 54, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 2, 4, -1, 54, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 2, 4, 24, 54, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 11, 4, 100, 54, 0, 999.9, false); }).toThrowDeveloperError(); }); it("Should throw error if invalid minute is passed", function() { expect(function() { return new import__229.GregorianDate(2022, 2, 4, 15, -1, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 2, 4, 15, 60, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 2, 4, 7, 60, 0, 999.9, true); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 11, 4, 0, -1, 0, 999.9, true); }).toThrowDeveloperError(); }); it("Should throw error if invalid second is passed", function() { expect(function() { return new import__229.GregorianDate(2022, 2, 4, 15, 1, -1, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 2, 4, 15, 59, 60, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 2, 4, 7, 59, 61, 999.9, true); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 11, 4, 0, 1, -1, 999.9, true); }).toThrowDeveloperError(); }); it("Should throw error if invalid millisecond is passed", function() { expect(function() { return new import__229.GregorianDate(2022, 2, 4, 15, 1, 0, -1, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 2, 4, 15, 59, 59, 1e3, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 2, 4, 7, 59, 60, 1e3, true); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 11, 4, 0, 1, 0, -12, true); }).toThrowDeveloperError(); }); it("Should throw error if invalid type is passed", function() { expect(function() { return new import__229.GregorianDate("2022A", 2, 4, 15, 1, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, "Two", 4, 15, 1, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 2, "F0UR", 15, 1, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 2, 4, "15th", 1, 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 2, 4, 15, "1st", 0, 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 2, 4, 15, 1, "Zero", 999.9, false); }).toThrowDeveloperError(); expect(function() { return new import__229.GregorianDate(2022, 2, 4, 15, 1, 0, "999,9O", false); }).toThrowDeveloperError(); }); }); }); // packages/engine/Specs/Core/GroundPolylineGeometrySpec.js var import__230 = __toESM(require_Cesium(), 1); var import__231 = __toESM(require_Cesium(), 1); describe("Core/GroundPolylineGeometry", function() { beforeAll(function() { return import__230.ApproximateTerrainHeights.initialize(); }); afterAll(function() { import__230.ApproximateTerrainHeights._initPromise = void 0; import__230.ApproximateTerrainHeights._terrainHeights = void 0; }); function verifyAttributeValuesIdentical(attribute) { const values = attribute.values; const componentsPerAttribute = attribute.componentsPerAttribute; const vertexCount = values.length / componentsPerAttribute; const firstVertex = values.slice(0, componentsPerAttribute); let identical = true; for (let i = 1; i < vertexCount; i++) { const index = i * componentsPerAttribute; const vertex = values.slice(index, index + componentsPerAttribute); for (let j = 0; j < componentsPerAttribute; j++) { if (vertex[j] !== firstVertex[j]) { identical = false; break; } } } expect(identical).toBe(true); } it("computes positions and additional attributes for polylines", function() { const startCartographic = import__230.Cartographic.fromDegrees(0.01, 0); const endCartographic = import__230.Cartographic.fromDegrees(0.02, 0); const groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromRadiansArray([ startCartographic.longitude, startCartographic.latitude, endCartographic.longitude, endCartographic.latitude ]), granularity: 0 }); const geometry = import__230.GroundPolylineGeometry.createGeometry( groundPolylineGeometry ); expect(geometry.indices.length).toEqual(36); expect(geometry.attributes.position.values.length).toEqual(24); const startHiAndForwardOffsetX = geometry.attributes.startHiAndForwardOffsetX; const startLoAndForwardOffsetY = geometry.attributes.startLoAndForwardOffsetY; const startNormalAndForwardOffsetZ = geometry.attributes.startNormalAndForwardOffsetZ; const endNormalAndTextureCoordinateNormalizationX = geometry.attributes.endNormalAndTextureCoordinateNormalizationX; const rightNormalAndTextureCoordinateNormalizationY = geometry.attributes.rightNormalAndTextureCoordinateNormalizationY; const startHiLo2D = geometry.attributes.startHiLo2D; const offsetAndRight2D = geometry.attributes.offsetAndRight2D; const startEndNormals2D = geometry.attributes.startEndNormals2D; const texcoordNormalization2D = geometry.attributes.texcoordNormalization2D; verifyAttributeValuesIdentical(startHiAndForwardOffsetX); verifyAttributeValuesIdentical(startLoAndForwardOffsetY); verifyAttributeValuesIdentical(startNormalAndForwardOffsetZ); verifyAttributeValuesIdentical(startHiLo2D); verifyAttributeValuesIdentical(offsetAndRight2D); verifyAttributeValuesIdentical(startEndNormals2D); let i; let index; let values = endNormalAndTextureCoordinateNormalizationX.values; for (i = 0; i < 4; i++) { index = i * 4 + 3; expect(import__231.Math.sign(values[index])).toEqual(1); } for (i = 4; i < 8; i++) { index = i * 4 + 3; expect(import__231.Math.sign(values[index])).toEqual(-1); } values = texcoordNormalization2D.values; for (i = 0; i < 4; i++) { index = i * 2; expect(import__231.Math.sign(values[index])).toEqual(1); } for (i = 4; i < 8; i++) { index = i * 2; expect(import__231.Math.sign(values[index])).toEqual(-1); } values = rightNormalAndTextureCoordinateNormalizationY.values; expect(values[3]).toBeGreaterThan(1); expect(values[1 * 4 + 3]).toBeGreaterThan(1); expect(values[4 * 4 + 3]).toBeGreaterThan(1); expect(values[5 * 4 + 3]).toBeGreaterThan(1); values = texcoordNormalization2D.values; expect(values[1]).toBeGreaterThan(1); expect(values[1 * 2 + 1]).toBeGreaterThan(1); expect(values[4 * 2 + 1]).toBeGreaterThan(1); expect(values[5 * 2 + 1]).toBeGreaterThan(1); const startPosition3D = new import__230.Cartesian3(); startPosition3D.x = startHiAndForwardOffsetX.values[0] + startLoAndForwardOffsetY.values[0]; startPosition3D.y = startHiAndForwardOffsetX.values[1] + startLoAndForwardOffsetY.values[1]; startPosition3D.z = startHiAndForwardOffsetX.values[2] + startLoAndForwardOffsetY.values[2]; let reconstructedCarto = import__230.Cartographic.fromCartesian(startPosition3D); reconstructedCarto.height = 0; expect( import__230.Cartographic.equalsEpsilon( reconstructedCarto, startCartographic, import__231.Math.EPSILON7 ) ).toBe(true); const endPosition3D = new import__230.Cartesian3(); endPosition3D.x = startPosition3D.x + startHiAndForwardOffsetX.values[3]; endPosition3D.y = startPosition3D.y + startLoAndForwardOffsetY.values[3]; endPosition3D.z = startPosition3D.z + startNormalAndForwardOffsetZ.values[3]; reconstructedCarto = import__230.Cartographic.fromCartesian(endPosition3D); reconstructedCarto.height = 0; expect( import__230.Cartographic.equalsEpsilon( reconstructedCarto, endCartographic, import__231.Math.EPSILON7 ) ).toBe(true); const startNormal3D = import__230.Cartesian3.unpack( startNormalAndForwardOffsetZ.values ); expect( import__230.Cartesian3.equalsEpsilon( startNormal3D, new import__230.Cartesian3(0, 1, 0), import__231.Math.EPSILON2 ) ).toBe(true); const endNormal3D = import__230.Cartesian3.unpack( endNormalAndTextureCoordinateNormalizationX.values ); expect( import__230.Cartesian3.equalsEpsilon( endNormal3D, new import__230.Cartesian3(0, -1, 0), import__231.Math.EPSILON2 ) ).toBe(true); const rightNormal3D = import__230.Cartesian3.unpack( rightNormalAndTextureCoordinateNormalizationY.values ); expect( import__230.Cartesian3.equalsEpsilon( rightNormal3D, new import__230.Cartesian3(0, 0, -1), import__231.Math.EPSILON2 ) ).toBe(true); let texcoordNormalizationX = endNormalAndTextureCoordinateNormalizationX.values[3]; expect(texcoordNormalizationX).toEqualEpsilon(1, import__231.Math.EPSILON3); const projection = new import__230.GeographicProjection(); const startPosition2D = new import__230.Cartesian3(); startPosition2D.x = startHiLo2D.values[0] + startHiLo2D.values[2]; startPosition2D.y = startHiLo2D.values[1] + startHiLo2D.values[3]; reconstructedCarto = projection.unproject(startPosition2D); reconstructedCarto.height = 0; expect( import__230.Cartographic.equalsEpsilon( reconstructedCarto, startCartographic, import__231.Math.EPSILON7 ) ).toBe(true); const endPosition2D = new import__230.Cartesian3(); endPosition2D.x = startPosition2D.x + offsetAndRight2D.values[0]; endPosition2D.y = startPosition2D.y + offsetAndRight2D.values[1]; reconstructedCarto = projection.unproject(endPosition2D); reconstructedCarto.height = 0; expect( import__230.Cartographic.equalsEpsilon( reconstructedCarto, endCartographic, import__231.Math.EPSILON7 ) ).toBe(true); const startNormal2D = new import__230.Cartesian3(); startNormal2D.x = startEndNormals2D.values[0]; startNormal2D.y = startEndNormals2D.values[1]; expect( import__230.Cartesian3.equalsEpsilon( startNormal2D, new import__230.Cartesian3(1, 0, 0), import__231.Math.EPSILON2 ) ).toBe(true); const endNormal2D = new import__230.Cartesian3(); endNormal2D.x = startEndNormals2D.values[2]; endNormal2D.y = startEndNormals2D.values[3]; expect( import__230.Cartesian3.equalsEpsilon( endNormal2D, new import__230.Cartesian3(-1, 0, 0), import__231.Math.EPSILON2 ) ).toBe(true); const rightNormal2D = new import__230.Cartesian3(); rightNormal2D.x = offsetAndRight2D.values[2]; rightNormal2D.y = offsetAndRight2D.values[3]; expect( import__230.Cartesian3.equalsEpsilon( rightNormal2D, new import__230.Cartesian3(0, -1, 0), import__231.Math.EPSILON2 ) ).toBe(true); texcoordNormalizationX = texcoordNormalization2D.values[0]; expect(texcoordNormalizationX).toEqualEpsilon(1, import__231.Math.EPSILON3); }); it("does not generate 2D attributes when scene3DOnly is true", function() { const startCartographic = import__230.Cartographic.fromDegrees(0.01, 0); const endCartographic = import__230.Cartographic.fromDegrees(0.02, 0); const groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromRadiansArray([ startCartographic.longitude, startCartographic.latitude, endCartographic.longitude, endCartographic.latitude ]), granularity: 0 }); groundPolylineGeometry._scene3DOnly = true; const geometry = import__230.GroundPolylineGeometry.createGeometry( groundPolylineGeometry ); expect(geometry.attributes.startHiAndForwardOffsetX).toBeDefined(); expect(geometry.attributes.startLoAndForwardOffsetY).toBeDefined(); expect(geometry.attributes.startNormalAndForwardOffsetZ).toBeDefined(); expect( geometry.attributes.endNormalAndTextureCoordinateNormalizationX ).toBeDefined(); expect( geometry.attributes.rightNormalAndTextureCoordinateNormalizationY ).toBeDefined(); expect(geometry.attributes.startHiLo2D).not.toBeDefined(); expect(geometry.attributes.offsetAndRight2D).not.toBeDefined(); expect(geometry.attributes.startEndNormals2D).not.toBeDefined(); expect(geometry.attributes.texcoordNormalization2D).not.toBeDefined(); }); it("removes adjacent positions with the same latitude/longitude", function() { const startCartographic = import__230.Cartographic.fromDegrees(0.01, 0); const endCartographic = import__230.Cartographic.fromDegrees(0.02, 0); const groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromRadiansArrayHeights([ startCartographic.longitude, startCartographic.latitude, 0, endCartographic.longitude, endCartographic.latitude, 0, endCartographic.longitude, endCartographic.latitude, 0, endCartographic.longitude, endCartographic.latitude, 10 ]), granularity: 0 }); const geometry = import__230.GroundPolylineGeometry.createGeometry( groundPolylineGeometry ); expect(geometry.indices.length).toEqual(36); expect(geometry.attributes.position.values.length).toEqual(24); }); it("returns undefined if filtered points are not a valid geometry", function() { const startCartographic = import__230.Cartographic.fromDegrees(0.01, 0); const groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromRadiansArrayHeights([ startCartographic.longitude, startCartographic.latitude, 0, startCartographic.longitude, startCartographic.latitude, 0 ]), granularity: 0 }); const geometry = import__230.GroundPolylineGeometry.createGeometry( groundPolylineGeometry ); expect(geometry).toBeUndefined(); }); it("miters turns", function() { const groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromDegreesArray([ 0.01, 0, 0.02, 0, 0.02, 0.01 ]), granularity: 0 }); const geometry = import__230.GroundPolylineGeometry.createGeometry( groundPolylineGeometry ); expect(geometry.indices.length).toEqual(72); expect(geometry.attributes.position.values.length).toEqual(48); const startNormalAndForwardOffsetZvalues = geometry.attributes.startNormalAndForwardOffsetZ.values; const endNormalAndTextureCoordinateNormalizationXvalues = geometry.attributes.endNormalAndTextureCoordinateNormalizationX.values; const miteredStartNormal = import__230.Cartesian3.unpack( startNormalAndForwardOffsetZvalues, 32 ); const miteredEndNormal = import__230.Cartesian3.unpack( endNormalAndTextureCoordinateNormalizationXvalues, 0 ); const reverseMiteredEndNormal = import__230.Cartesian3.multiplyByScalar( miteredEndNormal, -1, new import__230.Cartesian3() ); expect( import__230.Cartesian3.equalsEpsilon( miteredStartNormal, reverseMiteredEndNormal, import__231.Math.EPSILON7 ) ).toBe(true); const approximateExpectedMiterNormal = new import__230.Cartesian3(0, 1, 1); import__230.Cartesian3.normalize( approximateExpectedMiterNormal, approximateExpectedMiterNormal ); expect( import__230.Cartesian3.equalsEpsilon( approximateExpectedMiterNormal, miteredStartNormal, import__231.Math.EPSILON2 ) ).toBe(true); }); it("breaks miters for tight turns", function() { let groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromDegreesArray([ 0.01, 0, 0.02, 0, 0.01, import__231.Math.EPSILON7 ]), granularity: 0 }); let geometry = import__230.GroundPolylineGeometry.createGeometry( groundPolylineGeometry ); let startNormalAndForwardOffsetZvalues = geometry.attributes.startNormalAndForwardOffsetZ.values; let endNormalAndTextureCoordinateNormalizationXvalues = geometry.attributes.endNormalAndTextureCoordinateNormalizationX.values; let miteredStartNormal = import__230.Cartesian3.unpack( startNormalAndForwardOffsetZvalues, 32 ); let miteredEndNormal = import__230.Cartesian3.unpack( endNormalAndTextureCoordinateNormalizationXvalues, 0 ); expect( import__230.Cartesian3.equalsEpsilon( miteredStartNormal, miteredEndNormal, import__231.Math.EPSILON7 ) ).toBe(true); let approximateExpectedMiterNormal = new import__230.Cartesian3(0, -1, 0); import__230.Cartesian3.normalize( approximateExpectedMiterNormal, approximateExpectedMiterNormal ); expect( import__230.Cartesian3.equalsEpsilon( approximateExpectedMiterNormal, miteredStartNormal, import__231.Math.EPSILON2 ) ).toBe(true); groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromDegreesArray([ 0.01, 0, 0.02, 0, 0.015, import__231.Math.EPSILON7 ]), granularity: 0, loop: true }); geometry = import__230.GroundPolylineGeometry.createGeometry(groundPolylineGeometry); startNormalAndForwardOffsetZvalues = geometry.attributes.startNormalAndForwardOffsetZ.values; endNormalAndTextureCoordinateNormalizationXvalues = geometry.attributes.endNormalAndTextureCoordinateNormalizationX.values; miteredStartNormal = import__230.Cartesian3.unpack( startNormalAndForwardOffsetZvalues, 0 ); miteredEndNormal = import__230.Cartesian3.unpack( endNormalAndTextureCoordinateNormalizationXvalues, 32 * 2 ); expect( import__230.Cartesian3.equalsEpsilon( miteredStartNormal, miteredEndNormal, import__231.Math.EPSILON7 ) ).toBe(true); approximateExpectedMiterNormal = new import__230.Cartesian3(0, 1, 0); import__230.Cartesian3.normalize( approximateExpectedMiterNormal, approximateExpectedMiterNormal ); expect( import__230.Cartesian3.equalsEpsilon( approximateExpectedMiterNormal, miteredStartNormal, import__231.Math.EPSILON2 ) ).toBe(true); }); it("interpolates long polyline segments", function() { let groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromDegreesArray([0.01, 0, 0.02, 0]), granularity: 600 // 0.01 to 0.02 is about 1113 meters with default ellipsoid, expect two segments }); let geometry = import__230.GroundPolylineGeometry.createGeometry( groundPolylineGeometry ); expect(geometry.indices.length).toEqual(72); expect(geometry.attributes.position.values.length).toEqual(48); groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromDegreesArray([ 0.01, 0, 0.02, 0, 0.0201, 0 ]), granularity: 600 }); geometry = import__230.GroundPolylineGeometry.createGeometry(groundPolylineGeometry); expect(geometry.indices.length).toEqual(36 * 3); expect(geometry.attributes.position.values.length).toEqual(24 * 3); }); it("interpolates long polyline segments for rhumb lines", function() { let positions2 = import__230.Cartesian3.fromDegreesArray([10, 75, 20, 75]); let rhumbGroundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: positions2, granularity: 2890, arcType: import__230.ArcType.RHUMB }); let geodesicGroundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: positions2, granularity: 2890, arcType: import__230.ArcType.GEODESIC }); let rhumbGeometry = import__230.GroundPolylineGeometry.createGeometry( rhumbGroundPolylineGeometry ); let geodesicGeometry = import__230.GroundPolylineGeometry.createGeometry( geodesicGroundPolylineGeometry ); expect(rhumbGeometry.indices.length).toEqual(3636); expect(geodesicGeometry.indices.length).toEqual(3600); expect(geodesicGeometry.attributes.position.values.length).toEqual(2400); expect(rhumbGeometry.attributes.position.values.length).toEqual(2424); positions2 = import__230.Cartesian3.fromDegreesArray([10, 75, 20, 75, 20.01, 75]); rhumbGroundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: positions2, granularity: 2890, arcType: import__230.ArcType.RHUMB }); geodesicGroundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: positions2, granularity: 2890, arcType: import__230.ArcType.GEODESIC }); rhumbGeometry = import__230.GroundPolylineGeometry.createGeometry( rhumbGroundPolylineGeometry ); geodesicGeometry = import__230.GroundPolylineGeometry.createGeometry( geodesicGroundPolylineGeometry ); expect(rhumbGeometry.indices.length).toEqual(3636 + 36); expect(geodesicGeometry.indices.length).toEqual(3600 + 36); expect(geodesicGeometry.attributes.position.values.length).toEqual( 2400 + 24 ); expect(rhumbGeometry.attributes.position.values.length).toEqual(2424 + 24); }); it("loops when there are enough positions and loop is specified", function() { let groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromDegreesArray([0.01, 0, 0.02, 0]), granularity: 0, loop: true }); let geometry = import__230.GroundPolylineGeometry.createGeometry( groundPolylineGeometry ); expect(geometry.indices.length).toEqual(36); groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromDegreesArray([ 0.01, 0, 0.02, 0, 0.02, 0.02 ]), granularity: 0, loop: true }); geometry = import__230.GroundPolylineGeometry.createGeometry(groundPolylineGeometry); expect(geometry.indices.length).toEqual(108); }); it("subdivides geometry across the IDL and Prime Meridian", function() { let groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromDegreesArray([-1, 0, 1, 0]), granularity: 0 // no interpolative subdivision }); let geometry = import__230.GroundPolylineGeometry.createGeometry( groundPolylineGeometry ); expect(geometry.indices.length).toEqual(72); expect(geometry.attributes.position.values.length).toEqual(48); groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromDegreesArray([-179, 0, 179, 0]), granularity: 0 // no interpolative subdivision }); geometry = import__230.GroundPolylineGeometry.createGeometry(groundPolylineGeometry); expect(geometry.indices.length).toEqual(72); expect(geometry.attributes.position.values.length).toEqual(48); groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromDegreesArray([ 179, 0, 179, 1, -179, 1, -179, 0 ]), granularity: 0, // no interpolative subdivision loop: true }); geometry = import__230.GroundPolylineGeometry.createGeometry(groundPolylineGeometry); expect(geometry.indices.length).toEqual(6 * 36); expect(geometry.attributes.position.values.length).toEqual(6 * 24); groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromDegreesArray([179.999, 80, -179.999, 80]), granularity: 0 // no interpolative subdivision }); geometry = import__230.GroundPolylineGeometry.createGeometry(groundPolylineGeometry); expect(geometry.indices.length).toEqual(72); expect(geometry.attributes.position.values.length).toEqual(48); }); it("throws errors if not enough positions have been provided", function() { expect(function() { return new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromDegreesArray([0.01, 0]), granularity: 0, loop: true }); }).toThrowDeveloperError(); }); it("can unpack onto an existing instance", function() { const groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromDegreesArray([-1, 0, 1, 0]), loop: true, granularity: 10 // no interpolative subdivision }); groundPolylineGeometry._scene3DOnly = true; import__230.GroundPolylineGeometry.setProjectionAndEllipsoid( groundPolylineGeometry, new import__230.WebMercatorProjection(import__230.Ellipsoid.UNIT_SPHERE) ); const packedArray = [0]; import__230.GroundPolylineGeometry.pack(groundPolylineGeometry, packedArray, 1); const scratch = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromDegreesArray([-1, 0, 1, 0]) }); import__230.GroundPolylineGeometry.unpack(packedArray, 1, scratch); const scratchPositions = scratch._positions; expect(scratchPositions.length).toEqual(2); expect( import__230.Cartesian3.equals( scratchPositions[0], groundPolylineGeometry._positions[0] ) ).toBe(true); expect( import__230.Cartesian3.equals( scratchPositions[1], groundPolylineGeometry._positions[1] ) ).toBe(true); expect(scratch.loop).toBe(true); expect(scratch.granularity).toEqual(10); expect(scratch._ellipsoid.equals(import__230.Ellipsoid.UNIT_SPHERE)).toBe(true); expect(scratch._scene3DOnly).toBe(true); expect(scratch._projectionIndex).toEqual(1); }); it("can unpack onto a new instance", function() { const groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromDegreesArray([-1, 0, 1, 0]), loop: true, granularity: 10 // no interpolative subdivision }); groundPolylineGeometry._scene3DOnly = true; import__230.GroundPolylineGeometry.setProjectionAndEllipsoid( groundPolylineGeometry, new import__230.WebMercatorProjection(import__230.Ellipsoid.UNIT_SPHERE) ); const packedArray = [0]; import__230.GroundPolylineGeometry.pack(groundPolylineGeometry, packedArray, 1); const result = import__230.GroundPolylineGeometry.unpack(packedArray, 1); const scratchPositions = result._positions; expect(scratchPositions.length).toEqual(2); expect( import__230.Cartesian3.equals( scratchPositions[0], groundPolylineGeometry._positions[0] ) ).toBe(true); expect( import__230.Cartesian3.equals( scratchPositions[1], groundPolylineGeometry._positions[1] ) ).toBe(true); expect(result.loop).toBe(true); expect(result.granularity).toEqual(10); expect(result._ellipsoid.equals(import__230.Ellipsoid.UNIT_SPHERE)).toBe(true); expect(result._scene3DOnly).toBe(true); expect(result._projectionIndex).toEqual(1); }); it("provides a method for setting projection and ellipsoid", function() { const groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: import__230.Cartesian3.fromDegreesArray([-1, 0, 1, 0]), loop: true, granularity: 10 // no interpolative subdivision }); import__230.GroundPolylineGeometry.setProjectionAndEllipsoid( groundPolylineGeometry, new import__230.WebMercatorProjection(import__230.Ellipsoid.UNIT_SPHERE) ); expect(groundPolylineGeometry._projectionIndex).toEqual(1); expect( groundPolylineGeometry._ellipsoid.equals(import__230.Ellipsoid.UNIT_SPHERE) ).toBe(true); }); const positions = import__230.Cartesian3.fromDegreesArray([ 0.01, 0, 0.02, 0, 0.02, 0.1 ]); const polyline = new import__230.GroundPolylineGeometry({ positions, granularity: 1e3, loop: true }); it("projects normals that cross the IDL", function() { const projection = new import__230.GeographicProjection(); const cartographic = new import__230.Cartographic( import__231.Math.PI - import__231.Math.EPSILON11, 0 ); const normal = new import__230.Cartesian3(0, -1, 0); const projectedPosition = projection.project( cartographic, new import__230.Cartesian3() ); const result = new import__230.Cartesian3(); import__230.GroundPolylineGeometry._projectNormal( projection, cartographic, normal, projectedPosition, result ); expect( import__230.Cartesian3.equalsEpsilon( result, new import__230.Cartesian3(1, 0, 0), import__231.Math.EPSILON7 ) ).toBe(true); }); it("creates bounding spheres that cover the entire polyline volume height", function() { const positions2 = import__230.Cartesian3.fromDegreesArray([ -122.17580380403314, 46.19984918190237, -122.17581380403314, 46.19984918190237 ]); const groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: positions2, granularity: 0 // no interpolative subdivision }); const geometry = import__230.GroundPolylineGeometry.createGeometry( groundPolylineGeometry ); const boundingSphere = geometry.boundingSphere; const pointsDistance = import__230.Cartesian3.distance(positions2[0], positions2[1]); expect(boundingSphere.radius).toBeGreaterThan(pointsDistance); expect(boundingSphere.radius).toBeGreaterThan(1e3); }); it("creates bounding spheres that cover the entire polyline volume height in negative elevation regions", function() { const positions2 = import__230.Cartesian3.fromDegreesArray([ 35.549174, 31.377954, 35.549174, 31.377953 ]); const groundPolylineGeometry = new import__230.GroundPolylineGeometry({ positions: positions2, granularity: 0 // no interpolative subdivision }); const geometry = import__230.GroundPolylineGeometry.createGeometry( groundPolylineGeometry ); const boundingSphere = geometry.boundingSphere; const pointsDistance = import__230.Cartesian3.distance(positions2[0], positions2[1]); expect(boundingSphere.radius).toBeGreaterThan(pointsDistance); expect(boundingSphere.radius).toBeGreaterThan(3087 / 2); }); const packedInstance = [positions.length]; import__230.Cartesian3.pack(positions[0], packedInstance, packedInstance.length); import__230.Cartesian3.pack(positions[1], packedInstance, packedInstance.length); import__230.Cartesian3.pack(positions[2], packedInstance, packedInstance.length); packedInstance.push(polyline.granularity); packedInstance.push(polyline.loop ? 1 : 0); packedInstance.push(polyline.arcType); import__230.Ellipsoid.pack(import__230.Ellipsoid.WGS84, packedInstance, packedInstance.length); packedInstance.push(0); packedInstance.push(0); createPackableSpecs_default(import__230.GroundPolylineGeometry, polyline, packedInstance); }); // packages/engine/Specs/Core/HeadingPitchRangeSpec.js var import__232 = __toESM(require_Cesium(), 1); describe("Core/HeadingPitchRange", function() { it("construct with default values", function() { const hpr = new import__232.HeadingPitchRange(); expect(hpr.heading).toEqual(0); expect(hpr.pitch).toEqual(0); expect(hpr.range).toEqual(0); }); it("construct with all values", function() { const hpr = new import__232.HeadingPitchRange(1, 2, 3); expect(hpr.heading).toEqual(1); expect(hpr.pitch).toEqual(2); expect(hpr.range).toEqual(3); }); it("clone with a result parameter", function() { const hpr = new import__232.HeadingPitchRange(1, 2, 3); const result = new import__232.HeadingPitchRange(); const returnedResult = import__232.HeadingPitchRange.clone(hpr, result); expect(hpr).not.toBe(result); expect(result).toBe(returnedResult); expect(hpr).toEqual(result); }); it("clone works with a result parameter that is an input parameter", function() { const hpr = new import__232.HeadingPitchRange(1, 2, 3); const returnedResult = import__232.HeadingPitchRange.clone(hpr, hpr); expect(hpr).toBe(returnedResult); }); }); // packages/engine/Specs/Core/HeadingPitchRollSpec.js var import__233 = __toESM(require_Cesium(), 1); var import__234 = __toESM(require_Cesium(), 1); describe("Core/HeadingPitchRoll", function() { const deg2rad = import__234.Math.RADIANS_PER_DEGREE; it("construct with default values", function() { const headingPitchRoll = new import__233.HeadingPitchRoll(); expect(headingPitchRoll.heading).toEqual(0); expect(headingPitchRoll.pitch).toEqual(0); expect(headingPitchRoll.roll).toEqual(0); }); it("construct with all values", function() { const headingPitchRoll = new import__233.HeadingPitchRoll( 1 * deg2rad, 2 * deg2rad, 3 * deg2rad ); expect(headingPitchRoll.heading).toEqual( 1 * deg2rad, 2 * deg2rad, 3 * deg2rad ); expect(headingPitchRoll.pitch).toEqual( 2 * deg2rad, 2 * deg2rad, 3 * deg2rad ); expect(headingPitchRoll.roll).toEqual( 3 * deg2rad, 2 * deg2rad, 3 * deg2rad ); }); it("conversion from quaternion", function() { const testingTab = [ [0, 0, 0], [90 * deg2rad, 0, 0], [-90 * deg2rad, 0, 0], [0, 89 * deg2rad, 0], [0, -89 * deg2rad, 0], [0, 0, 90 * deg2rad], [0, 0, -90 * deg2rad], [30 * deg2rad, 30 * deg2rad, 30 * deg2rad], [-30 * deg2rad, -30 * deg2rad, 45 * deg2rad] ]; const hpr = new import__233.HeadingPitchRoll(); for (let i = 0; i < testingTab.length; i++) { const init = testingTab[i]; hpr.heading = init[0]; hpr.pitch = init[1]; hpr.roll = init[2]; const result = import__233.HeadingPitchRoll.fromQuaternion( import__233.Quaternion.fromHeadingPitchRoll(hpr) ); expect(init[0]).toEqualEpsilon(result.heading, import__234.Math.EPSILON11); expect(init[1]).toEqualEpsilon(result.pitch, import__234.Math.EPSILON11); expect(init[2]).toEqualEpsilon(result.roll, import__234.Math.EPSILON11); } }); it("it should return the correct pitch, even with a quaternion rounding error", function() { const q = new import__233.Quaternion( 8801218199179452e-32, -0.7071067801637715, -8801218315071006e-32, -0.7071067822093238 ); const result = import__233.HeadingPitchRoll.fromQuaternion(q); expect(result.pitch).toEqual(-(Math.PI / 2)); }); it("conversion from degrees", function() { const testingTab = [ [0, 0, 0], [90, 0, 0], [-90, 0, 0], [0, 89, 0], [0, -89, 0], [0, 0, 90], [0, 0, -90], [30, 30, 30], [-30, -30, 45] ]; for (let i = 0; i < testingTab.length; i++) { const init = testingTab[i]; const result = import__233.HeadingPitchRoll.fromDegrees(init[0], init[1], init[2]); expect(init[0] * deg2rad).toEqualEpsilon( result.heading, import__234.Math.EPSILON11 ); expect(init[1] * deg2rad).toEqualEpsilon( result.pitch, import__234.Math.EPSILON11 ); expect(init[2] * deg2rad).toEqualEpsilon( result.roll, import__234.Math.EPSILON11 ); } }); it("fromDegrees with result", function() { const headingDeg = -115; const pitchDeg = 37; const rollDeg = 40; const headingRad = headingDeg * deg2rad; const pitchRad = pitchDeg * deg2rad; const rollRad = rollDeg * deg2rad; const result = new import__233.HeadingPitchRoll(); const actual = import__233.HeadingPitchRoll.fromDegrees( headingDeg, pitchDeg, rollDeg, result ); const expected = new import__233.HeadingPitchRoll(headingRad, pitchRad, rollRad); expect(actual).toEqual(expected); expect(actual).toBe(result); }); it("clone with a result parameter", function() { const headingPitchRoll = new import__233.HeadingPitchRoll( 1 * deg2rad, 2 * deg2rad, 3 * deg2rad ); const result = new import__233.HeadingPitchRoll(); const returnedResult = import__233.HeadingPitchRoll.clone(headingPitchRoll, result); expect(headingPitchRoll).not.toBe(result); expect(result).toBe(returnedResult); expect(headingPitchRoll).toEqual(result); }); it("clone works with a result parameter that is an input parameter", function() { const headingPitchRoll = new import__233.HeadingPitchRoll( 1 * deg2rad, 2 * deg2rad, 3 * deg2rad ); const returnedResult = import__233.HeadingPitchRoll.clone( headingPitchRoll, headingPitchRoll ); expect(headingPitchRoll).toBe(returnedResult); }); it("equals", function() { const headingPitchRoll = new import__233.HeadingPitchRoll(1, 2, 3); expect( import__233.HeadingPitchRoll.equals( headingPitchRoll, new import__233.HeadingPitchRoll(1, 2, 3) ) ).toEqual(true); expect( import__233.HeadingPitchRoll.equals( headingPitchRoll, new import__233.HeadingPitchRoll(2, 2, 3) ) ).toEqual(false); expect( import__233.HeadingPitchRoll.equals( headingPitchRoll, new import__233.HeadingPitchRoll(2, 1, 3) ) ).toEqual(false); expect( import__233.HeadingPitchRoll.equals( headingPitchRoll, new import__233.HeadingPitchRoll(1, 2, 4) ) ).toEqual(false); expect(import__233.HeadingPitchRoll.equals(headingPitchRoll, void 0)).toEqual(false); }); it("equalsEpsilon", function() { let headingPitchRoll = new import__233.HeadingPitchRoll(1, 2, 3); expect( headingPitchRoll.equalsEpsilon(new import__233.HeadingPitchRoll(1, 2, 3), 0) ).toEqual(true); expect( headingPitchRoll.equalsEpsilon(new import__233.HeadingPitchRoll(1, 2, 3), 1) ).toEqual(true); expect( headingPitchRoll.equalsEpsilon(new import__233.HeadingPitchRoll(2, 2, 3), 1) ).toEqual(true); expect( headingPitchRoll.equalsEpsilon(new import__233.HeadingPitchRoll(1, 3, 3), 1) ).toEqual(true); expect( headingPitchRoll.equalsEpsilon(new import__233.HeadingPitchRoll(1, 2, 4), 1) ).toEqual(true); expect( headingPitchRoll.equalsEpsilon( new import__233.HeadingPitchRoll(2, 2, 3), import__234.Math.EPSILON6 ) ).toEqual(false); expect( headingPitchRoll.equalsEpsilon( new import__233.HeadingPitchRoll(1, 3, 3), import__234.Math.EPSILON6 ) ).toEqual(false); expect( headingPitchRoll.equalsEpsilon( new import__233.HeadingPitchRoll(1, 2, 4), import__234.Math.EPSILON6 ) ).toEqual(false); expect(headingPitchRoll.equalsEpsilon(void 0, 1)).toEqual(false); headingPitchRoll = new import__233.HeadingPitchRoll(3e6, 4e6, 5e6); expect( headingPitchRoll.equalsEpsilon( new import__233.HeadingPitchRoll(3e6, 4e6, 5e6), 0 ) ).toEqual(true); expect( headingPitchRoll.equalsEpsilon( new import__233.HeadingPitchRoll(30000002e-1, 4e6, 5e6), import__234.Math.EPSILON7 ) ).toEqual(true); expect( headingPitchRoll.equalsEpsilon( new import__233.HeadingPitchRoll(3e6, 40000002e-1, 5e6), import__234.Math.EPSILON7 ) ).toEqual(true); expect( headingPitchRoll.equalsEpsilon( new import__233.HeadingPitchRoll(3e6, 4e6, 50000002e-1), import__234.Math.EPSILON7 ) ).toEqual(true); expect( headingPitchRoll.equalsEpsilon( new import__233.HeadingPitchRoll(30000002e-1, 40000002e-1, 50000002e-1), import__234.Math.EPSILON7 ) ).toEqual(true); expect( headingPitchRoll.equalsEpsilon( new import__233.HeadingPitchRoll(30000002e-1, 40000002e-1, 50000002e-1), import__234.Math.EPSILON9 ) ).toEqual(false); expect(headingPitchRoll.equalsEpsilon(void 0, 1)).toEqual(false); expect( import__233.HeadingPitchRoll.equalsEpsilon(void 0, headingPitchRoll, 1) ).toEqual(false); }); it("toString", function() { const headingPitchRoll = new import__233.HeadingPitchRoll(1.123, 2.345, 6.789); expect(headingPitchRoll.toString()).toEqual("(1.123, 2.345, 6.789)"); }); it("fromQuaternion throws with no parameter", function() { expect(function() { import__233.HeadingPitchRoll.fromQuaternion(); }).toThrowDeveloperError(); }); const scratchHeadingPitchRoll = new import__233.HeadingPitchRoll(); it("fromDegrees throws with no heading parameter", function() { expect(function() { import__233.HeadingPitchRoll.fromDegrees(void 0, 0, 0, scratchHeadingPitchRoll); }).toThrowDeveloperError(); expect(function() { import__233.HeadingPitchRoll.fromDegrees(void 0, 0, 0); }).toThrowDeveloperError(); }); it("fromDegrees throws with no pitch parameter", function() { expect(function() { import__233.HeadingPitchRoll.fromDegrees(0, void 0, 0, scratchHeadingPitchRoll); }).toThrowDeveloperError(); expect(function() { import__233.HeadingPitchRoll.fromDegrees(0, void 0, 0); }).toThrowDeveloperError(); }); it("fromDegrees throws with no roll parameter", function() { expect(function() { import__233.HeadingPitchRoll.fromDegrees(0, 0, void 0, scratchHeadingPitchRoll); }).toThrowDeveloperError(); expect(function() { import__233.HeadingPitchRoll.fromDegrees(0, 0, void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/HeapSpec.js var import__235 = __toESM(require_Cesium(), 1); describe("Core/Heap", function() { const length2 = 100; function expectTrailingReferenceToBeRemoved(heap) { const array = heap._array; const length3 = heap._length; const reservedLength = array.length; for (let i = length3; i < reservedLength; ++i) { expect(array[i]).toBeUndefined(); } } function checkHeap(heap, comparator2) { const array = heap.internalArray; let pass = true; const length3 = heap.length; for (let i = 0; i < length3; ++i) { const left = 2 * (i + 1) - 1; const right = 2 * (i + 1); if (left < heap.length) { pass = pass && comparator2(array[i], array[left]) <= 0; } if (right < heap.length) { pass = pass && comparator2(array[i], array[right]) <= 0; } } return pass; } function comparator(a, b) { return a - b; } it("maintains heap property on insert", function() { const heap = new import__235.Heap({ comparator }); let pass = true; for (let i = 0; i < length2; ++i) { heap.insert(Math.random()); pass = pass && checkHeap(heap, comparator); } expect(pass).toBe(true); }); it("maintains heap property on pop", function() { const heap = new import__235.Heap({ comparator }); let i; for (i = 0; i < length2; ++i) { heap.insert(Math.random()); } let pass = true; for (i = 0; i < length2; ++i) { heap.pop(); pass = pass && checkHeap(heap, comparator); } expect(pass).toBe(true); }); it("limited by maximum length", function() { const heap = new import__235.Heap({ comparator }); heap.maximumLength = length2 / 2; let pass = true; for (let i = 0; i < length2; ++i) { heap.insert(Math.random()); pass = pass && checkHeap(heap, comparator); } expect(pass).toBe(true); expect(heap.length).toBeLessThanOrEqual(heap.maximumLength); expect(heap.internalArray.length).toBeLessThanOrEqual( heap.maximumLength + 1 ); }); it("pops in sorted order", function() { const heap = new import__235.Heap({ comparator }); let i; for (i = 0; i < length2; ++i) { heap.insert(Math.random()); } let curr = heap.pop(); let pass = true; for (i = 0; i < length2 - 1; ++i) { const next = heap.pop(); pass = pass && comparator(curr, next) <= 0; curr = next; } expect(pass).toBe(true); }); it("pop removes trailing references", function() { const heap = new import__235.Heap({ comparator }); for (let i = 0; i < 10; ++i) { heap.insert(Math.random()); } heap.pop(); heap.pop(); expectTrailingReferenceToBeRemoved(heap); }); it("setting maximum length less than current length removes trailing references", function() { const heap = new import__235.Heap({ comparator }); for (let i = 0; i < 10; ++i) { heap.insert(Math.random()); } heap.maximumLength = 5; expectTrailingReferenceToBeRemoved(heap); }); it("insert returns the removed element when maximumLength is set", function() { const heap = new import__235.Heap({ comparator }); heap.maximumLength = length2; let i; let max = 0; let min = 1; const values = new Array(length2); for (i = 0; i < length2; ++i) { const value = Math.random(); max = Math.max(max, value); min = Math.min(min, value); values[i] = value; } for (i = 0; i < length2 - 1; ++i) { heap.insert(values[i]); } let removed = heap.insert(values[length2 - 1]); expect(removed).toBeUndefined(); removed = heap.insert(max - 0.1); expect(removed).toBeDefined(); removed = heap.insert(max + 0.1); expect(removed).toBe(max + 0.1); }); it("resort", function() { function comparator2(a, b) { return a.distance - b.distance; } let i; const heap = new import__235.Heap({ comparator: comparator2 }); for (i = 0; i < length2; ++i) { heap.insert({ distance: i / (length2 - 1), id: i }); } let element; const elements = []; let currentId = 0; while (heap.length > 0) { element = heap.pop(); elements.push(element); expect(element.id).toBeGreaterThanOrEqual(currentId); currentId = element.id; } for (i = 0; i < length2; ++i) { heap.insert(elements[i]); } for (i = 0; i < length2; ++i) { elements[i].distance = 1 - elements[i].distance; } heap.resort(); while (heap.length > 0) { element = heap.pop(); expect(element.id).toBeLessThanOrEqual(currentId); currentId = element.id; } }); it("maximumLength setter throws if length is less than 0", function() { const heap = new import__235.Heap({ comparator }); expect(function() { heap.maximumLength = -1; }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/HeightmapTerrainDataSpec.js var import__236 = __toESM(require_Cesium(), 1); describe("Core/HeightmapTerrainData", function() { it("conforms to TerrainData interface", function() { expect(import__236.HeightmapTerrainData).toConformToInterface(import__236.TerrainData); }); describe("constructor", function() { it("requires buffer", function() { expect(function() { return new import__236.HeightmapTerrainData(); }).toThrowDeveloperError(); expect(function() { return new import__236.HeightmapTerrainData({ width: 5, height: 5 }); }).toThrowDeveloperError(); }); it("requires width", function() { expect(function() { return new import__236.HeightmapTerrainData({ buffer: new Float32Array(25), height: 5 }); }).toThrowDeveloperError(); }); it("requires height", function() { expect(function() { return new import__236.HeightmapTerrainData({ buffer: new Float32Array(25), width: 5 }); }).toThrowDeveloperError(); }); it("non-LERC encoded buffers sets correct buffer type", function() { const data = new import__236.HeightmapTerrainData({ buffer: new Uint16Array(25), width: 5, height: 5 }); expect(data._encoding).toBe(import__236.HeightmapEncoding.NONE); expect(data._bufferType).toBe(Uint16Array); }); it("LERC encoded buffers sets correct buffer type", function() { const data = new import__236.HeightmapTerrainData({ buffer: new Uint16Array(25), width: 5, height: 5, encoding: import__236.HeightmapEncoding.LERC }); expect(data._encoding).toBe(import__236.HeightmapEncoding.LERC); expect(data._bufferType).toBe(Float32Array); }); }); describe("createMesh", function() { let data; let tilingScheme; function createSampleTerrainData() { return new import__236.HeightmapTerrainData({ buffer: new Float32Array(25), width: 5, height: 5 }); } beforeEach(function() { tilingScheme = new import__236.GeographicTilingScheme(); data = createSampleTerrainData(); }); it("requires tilingScheme", function() { expect(function() { data.createMesh({ tilingScheme: void 0, x: 0, y: 0, level: 0 }); }).toThrowDeveloperError(); }); it("requires x", function() { expect(function() { data.createMesh({ tilingScheme, x: void 0, y: 0, level: 0 }); }).toThrowDeveloperError(); }); it("requires y", function() { expect(function() { data.createMesh({ tilingScheme, x: 0, y: void 0, level: 0 }); }).toThrowDeveloperError(); }); it("requires level", function() { expect(function() { data.createMesh({ tilingScheme, x: 0, y: 0, level: void 0 }); }).toThrowDeveloperError(); }); it("enables throttling for asynchronous tasks", function() { const options = { tilingScheme, x: 0, y: 0, level: 0, throttle: true }; const taskCount = import__236.TerrainData.maximumAsynchronousTasks + 1; const promises = new Array(); for (let i = 0; i < taskCount; i++) { const tempData = createSampleTerrainData(); const promise = tempData.createMesh(options); if ((0, import__236.defined)(promise)) { promises.push(promise); } } expect(promises.length).toBe(import__236.TerrainData.maximumAsynchronousTasks); return Promise.all(promises); }); it("disables throttling for asynchronous tasks", function() { const options = { tilingScheme, x: 0, y: 0, level: 0, throttle: false }; const taskCount = import__236.TerrainData.maximumAsynchronousTasks + 1; const promises = new Array(); for (let i = 0; i < taskCount; i++) { const tempData = createSampleTerrainData(); const promise = tempData.createMesh(options); if ((0, import__236.defined)(promise)) { promises.push(promise); } } expect(promises.length).toBe(taskCount); return Promise.all(promises); }); }); describe("upsample", function() { let data; let tilingScheme; beforeEach(function() { tilingScheme = new import__236.GeographicTilingScheme(); data = new import__236.HeightmapTerrainData({ buffer: new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9]), width: 3, height: 3 }); }); it("requires tilingScheme", function() { expect(function() { data.upsample(void 0, 0, 0, 0, 0, 0, 0); }).toThrowDeveloperError(); }); it("requires thisX", function() { expect(function() { data.upsample(tilingScheme, void 0, 0, 0, 0, 0, 0); }).toThrowDeveloperError(); }); it("requires thisY", function() { expect(function() { data.upsample(tilingScheme, 0, void 0, 0, 0, 0, 0); }).toThrowDeveloperError(); }); it("requires thisLevel", function() { expect(function() { data.upsample(tilingScheme, 0, 0, void 0, 0, 0, 0); }).toThrowDeveloperError(); }); it("requires descendantX", function() { expect(function() { data.upsample(tilingScheme, 0, 0, 0, void 0, 0, 0); }).toThrowDeveloperError(); }); it("requires descendantY", function() { expect(function() { data.upsample(tilingScheme, 0, 0, 0, 0, void 0, 0); }).toThrowDeveloperError(); }); it("requires descendantLevel", function() { expect(function() { data.upsample(tilingScheme, 0, 0, 0, 0, 0, void 0); }).toThrowDeveloperError(); }); it("can only upsample cross one level", function() { expect(function() { data.upsample(tilingScheme, 0, 0, 0, 0, 0, 2); }).toThrowDeveloperError(); }); it("upsamples", function() { data = new import__236.HeightmapTerrainData({ buffer: new Float32Array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]), width: 4, height: 4 }); return data.createMesh({ tilingScheme, x: 0, y: 0, level: 0 }).then(function() { return data.upsample(tilingScheme, 0, 0, 0, 0, 0, 1); }).then(function(upsampled) { expect(upsampled.wasCreatedByUpsampling()).toBe(true); expect(upsampled._width).toBe(4); expect(upsampled._height).toBe(4); expect(upsampled._buffer).toEqual([ 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5 ]); }); }); it("upsample works with a stride", function() { data = new import__236.HeightmapTerrainData({ buffer: new Uint8Array([ 1, 1, 10, 2, 1, 10, 3, 1, 10, 4, 1, 10, 5, 1, 10, 6, 1, 10, 7, 1, 10, 8, 1, 10, 9, 1, 10, 10, 1, 10, 11, 1, 10, 12, 1, 10, 13, 1, 10, 14, 1, 10, 15, 1, 10, 16, 1, 10 ]), width: 4, height: 4, structure: { stride: 3, elementsPerHeight: 2 } }); return data.createMesh({ tilingScheme, x: 0, y: 0, level: 0 }).then(function() { return data.upsample(tilingScheme, 0, 0, 0, 0, 0, 1); }).then(function(upsampled) { expect(upsampled.wasCreatedByUpsampling()).toBe(true); expect(upsampled._width).toBe(4); expect(upsampled._height).toBe(4); expect(upsampled._buffer).toEqual([ 1, 1, 0, 1, 1, 0, 2, 1, 0, 2, 1, 0, 3, 1, 0, 3, 1, 0, 4, 1, 0, 4, 1, 0, 5, 1, 0, 5, 1, 0, 6, 1, 0, 6, 1, 0, 7, 1, 0, 7, 1, 0, 8, 1, 0, 8, 1, 0 ]); }); }); it("upsample works with a big endian stride", function() { data = new import__236.HeightmapTerrainData({ buffer: new Uint8Array([ 1, 1, 10, 1, 2, 10, 1, 3, 10, 1, 4, 10, 1, 5, 10, 1, 6, 10, 1, 7, 10, 1, 8, 10, 1, 9, 10, 1, 10, 10, 1, 11, 10, 1, 12, 10, 1, 13, 10, 1, 14, 10, 1, 15, 10, 1, 16, 10 ]), width: 4, height: 4, structure: { stride: 3, elementsPerHeight: 2, isBigEndian: true } }); return data.createMesh({ tilingScheme, x: 0, y: 0, level: 0 }).then(function() { return data.upsample(tilingScheme, 0, 0, 0, 0, 0, 1); }).then(function(upsampled) { expect(upsampled.wasCreatedByUpsampling()).toBe(true); expect(upsampled._width).toBe(4); expect(upsampled._height).toBe(4); expect(upsampled._buffer).toEqual([ 1, 1, 0, 1, 1, 0, 1, 2, 0, 1, 2, 0, 1, 3, 0, 1, 3, 0, 1, 4, 0, 1, 4, 0, 1, 5, 0, 1, 5, 0, 1, 6, 0, 1, 6, 0, 1, 7, 0, 1, 7, 0, 1, 8, 0, 1, 8, 0 ]); }); }); it("upsample works for an eastern child", function() { data = new import__236.HeightmapTerrainData({ buffer: new Float32Array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]), width: 4, height: 4 }); return data.createMesh({ tilingScheme, x: 0, y: 0, level: 0 }).then(function() { return data.upsample(tilingScheme, 0, 0, 0, 1, 0, 1); }).then(function(upsampled) { expect(upsampled.wasCreatedByUpsampling()).toBe(true); expect(upsampled._width).toBe(4); expect(upsampled._height).toBe(4); expect(upsampled._buffer).toEqual([ 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10 ]); }); }); it("upsample works with a stride for an eastern child", function() { data = new import__236.HeightmapTerrainData({ buffer: new Uint8Array([ 1, 1, 10, 2, 1, 10, 3, 1, 10, 4, 1, 10, 5, 1, 10, 6, 1, 10, 7, 1, 10, 8, 1, 10, 9, 1, 10, 10, 1, 10, 11, 1, 10, 12, 1, 10, 13, 1, 10, 14, 1, 10, 15, 1, 10, 16, 1, 10 ]), width: 4, height: 4, structure: { stride: 3, elementsPerHeight: 2 } }); return data.createMesh({ tilingScheme, x: 0, y: 0, level: 0 }).then(function() { return data.upsample(tilingScheme, 0, 0, 0, 1, 0, 1); }).then(function(upsampled) { expect(upsampled.wasCreatedByUpsampling()).toBe(true); expect(upsampled._width).toBe(4); expect(upsampled._height).toBe(4); expect(upsampled._buffer).toEqual([ 2, 1, 0, 3, 1, 0, 3, 1, 0, 4, 1, 0, 4, 1, 0, 5, 1, 0, 5, 1, 0, 6, 1, 0, 6, 1, 0, 7, 1, 0, 7, 1, 0, 8, 1, 0, 8, 1, 0, 9, 1, 0, 9, 1, 0, 10, 1, 0 ]); }); }); it("upsample clamps out of range data", function() { data = new import__236.HeightmapTerrainData({ buffer: new Float32Array([ -1, -2, -3, -4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]), width: 4, height: 4, structure: { stride: 1, elementsPerHeight: 1, lowestEncodedHeight: 1, highestEncodedHeight: 7 } }); return data.createMesh({ tilingScheme, x: 0, y: 0, level: 0 }).then(function() { return data.upsample(tilingScheme, 0, 0, 0, 0, 0, 1); }).then(function(upsampled) { expect(upsampled.wasCreatedByUpsampling()).toBe(true); expect(upsampled._width).toBe(4); expect(upsampled._height).toBe(4); expect(upsampled._buffer).toEqual([ 1, 1, 1, 1, 2, 1.5, 2, 1.5, 5, 5.5, 6, 6.5, 7, 7, 7, 7 ]); }); }); }); describe("isChildAvailable", function() { let data; beforeEach(function() { data = new import__236.HeightmapTerrainData({ buffer: new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9]), width: 3, height: 3 }); }); it("requires thisX", function() { expect(function() { data.isChildAvailable(void 0, 0, 0, 0); }).toThrowDeveloperError(); }); it("requires thisY", function() { expect(function() { data.isChildAvailable(0, void 0, 0, 0); }).toThrowDeveloperError(); }); it("requires childX", function() { expect(function() { data.isChildAvailable(0, 0, void 0, 0); }).toThrowDeveloperError(); }); it("requires childY", function() { expect(function() { data.isChildAvailable(0, 0, 0, void 0); }).toThrowDeveloperError(); }); }); }); // packages/engine/Specs/Core/HermitePolynomialApproximationSpec.js var import__237 = __toESM(require_Cesium(), 1); describe("Core/HermitePolynomialApproximation", function() { const xTable = [0, 60, 120, 180, 240, 300, 360, 420]; const yTable = [ 13378137, 0, 133741283576279e-7, 0, 133621048328212e-7, 0, 133420736310691e-7, 0, 133140467567223e-7, 0, 13278041005799e-6, 0, 132340779559193e-7, 0, 13182183953374e-6, 0 ]; const dyTable = [ 0, 0, -133.614738921601, 0, -267.149404854867, 0, -400.523972797808, 0, -533.658513692378, 0, -666.473242324565, 0, -798.888565138278, 0, -930.82512793439, 0 ]; const yTableCombined = new Array(yTable.length * 2); for (let i = 0; i < yTable.length / 2; ++i) { yTableCombined[i * 4 + 0] = yTable[i * 2 + 0]; yTableCombined[i * 4 + 1] = yTable[i * 2 + 1]; yTableCombined[i * 4 + 2] = dyTable[i * 2 + 0]; yTableCombined[i * 4 + 3] = dyTable[i * 2 + 1]; } const x = 100; it("interpolating produces correct results.", function() { const result = import__237.HermitePolynomialApproximation.interpolateOrderZero( x, xTable, yTableCombined, 4 ); const expectedResult = 13367002870928625e-9; expect(result[0]).toEqualEpsilon(expectedResult, 1e-6); }); it("interpolating produces correct results with a result parameter.", function() { const result = new Array(4); const returnedResult = import__237.HermitePolynomialApproximation.interpolateOrderZero( x, xTable, yTableCombined, 4, result ); const expectedResult = 13367002870928625e-9; expect(result).toBe(returnedResult); expect(result[0]).toEqualEpsilon(expectedResult, 1e-6); }); it("getRequiredDataPoints should be 1 more than degree, except for 0, which requires 2", function() { expect(import__237.HermitePolynomialApproximation.getRequiredDataPoints(0)).toEqual(2); expect(import__237.HermitePolynomialApproximation.getRequiredDataPoints(1)).toEqual(2); expect(import__237.HermitePolynomialApproximation.getRequiredDataPoints(2)).toEqual(3); expect(import__237.HermitePolynomialApproximation.getRequiredDataPoints(3)).toEqual(4); expect(import__237.HermitePolynomialApproximation.getRequiredDataPoints(3, 1)).toEqual( 2 ); expect(import__237.HermitePolynomialApproximation.getRequiredDataPoints(5, 1)).toEqual( 3 ); expect(import__237.HermitePolynomialApproximation.getRequiredDataPoints(7, 1)).toEqual( 4 ); }); it("higher order interpolation produces correct results.", function() { const result = import__237.HermitePolynomialApproximation.interpolate( x, xTable, yTableCombined, 2, 1, 1 ); const expectedResult = [13367002870928625e-9, 0, -222.65168787012135, 0]; expect(result).toEqualEpsilon(expectedResult, 1e-8); }); }); // packages/engine/Specs/Core/HermiteSplineSpec.js var import__238 = __toESM(require_Cesium(), 1); var import__239 = __toESM(require_Cesium(), 1); describe("Core/HermiteSpline", function() { let points; let times; beforeEach(function() { points = [ new import__238.Cartesian3(-1, -1, 0), new import__238.Cartesian3(-0.5, -0.125, 0), new import__238.Cartesian3(0.5, 0.125, 0), new import__238.Cartesian3(1, 1, 0) ]; times = [0, 1, 2, 3]; }); it("constructor throws without points, times or tangents", function() { expect(function() { return new import__238.HermiteSpline(); }).toThrowDeveloperError(); }); it("constructor throws when control points length is less than 2", function() { expect(function() { return new import__238.HermiteSpline({ points: [import__238.Cartesian3.ZERO] }); }).toThrowDeveloperError(); }); it("constructor throws when times.length is not equal to points.length", function() { expect(function() { return new import__238.HermiteSpline({ points, times: [0, 1] }); }).toThrowDeveloperError(); }); it("constructor throws when inTangents or outTangents length is not equal to points.length - 1", function() { expect(function() { return new import__238.HermiteSpline({ points, times, inTangents: [import__238.Cartesian3.ZERO], outTangents: [import__238.Cartesian3.UNIT_X] }); }).toThrowDeveloperError(); }); it("constructor throws when inTangents and outTangents are not the same type as points.", function() { expect(function() { return new import__238.HermiteSpline({ points, times, inTangents: [0, 0, 0], outTangents: [0, 0, 0] }); }).toThrowDeveloperError(); }); function createHermiteBasis(p, pT, q, qT) { return function(u) { const a = 2 * u * u * u - 3 * u * u + 1; const b = -2 * u * u * u + 3 * u * u; const c = u * u * u - 2 * u * u + u; const d = u * u * u - u * u; const p0 = import__238.Cartesian3.multiplyByScalar(p, a, new import__238.Cartesian3()); const p1 = import__238.Cartesian3.multiplyByScalar(q, b, new import__238.Cartesian3()); const p2 = import__238.Cartesian3.multiplyByScalar(pT, c, new import__238.Cartesian3()); const p3 = import__238.Cartesian3.multiplyByScalar(qT, d, new import__238.Cartesian3()); return import__238.Cartesian3.add( import__238.Cartesian3.add(import__238.Cartesian3.add(p0, p1, p0), p2, p0), p3, p0 ); }; } it("create spline", function() { const hs = new import__238.HermiteSpline({ times: [0, 1, 3, 4.5, 6], points: [ new import__238.Cartesian3(1235398, -4810983, 4146266), new import__238.Cartesian3(1372574, -5345182, 4606657), new import__238.Cartesian3(-757983, -5542796, 4514323), new import__238.Cartesian3(-2821260, -5248423, 4021290), new import__238.Cartesian3(-2539788, -4724797, 3620093) ], outTangents: [ new import__238.Cartesian3(1125196, -161816, 270551), new import__238.Cartesian3(-996690.5, -365906.5, 184028.5), new import__238.Cartesian3(-2096917, 48379.5, -292683.5), new import__238.Cartesian3(-890902.5, 408999.5, -447115) ], inTangents: [ new import__238.Cartesian3(-1993381, -731813, 368057), new import__238.Cartesian3(-4193834, 96759, -585367), new import__238.Cartesian3(-1781805, 817999, -894230), new import__238.Cartesian3(1165345, 112641, 47281) ] }); const p0 = hs.points[0]; const p1 = hs.points[1]; const pT0 = hs.outTangents[0]; const pT1 = hs.inTangents[0]; const interpolate = createHermiteBasis(p0, pT0, p1, pT1); const granularity = 0.1; for (let i = 0; i < 1; i = i + granularity) { expect(hs.evaluate(i)).toEqualEpsilon( interpolate(i), import__239.Math.EPSILON3 ); } }); it("createC1 throws without points", function() { expect(function() { return import__238.HermiteSpline.createC1(); }).toThrowDeveloperError(); }); it("createC1 throws when control points length is less than 2", function() { expect(function() { return import__238.HermiteSpline.createC1({ points: [import__238.Cartesian3.ZERO] }); }).toThrowDeveloperError(); }); it("createC1 throws without times", function() { expect(function() { return import__238.HermiteSpline.createC1({ points }); }).toThrowDeveloperError(); }); it("createC1 throws when times.length is not equal to points.length", function() { expect(function() { return import__238.HermiteSpline.createC1({ points, times: [0, 1] }); }).toThrowDeveloperError(); }); it("createC1 throws without tangents", function() { expect(function() { return import__238.HermiteSpline.createC1({ points, times }); }).toThrowDeveloperError(); }); it("createC1 throws when tangents.length is not equal to times.length", function() { expect(function() { return import__238.HermiteSpline.createC1({ points, times, tangents: [import__238.Cartesian3.ZERO] }); }).toThrowDeveloperError(); }); it("C1 spline", function() { const times2 = [0, 1, 3, 4.5, 6]; const points2 = [ new import__238.Cartesian3(1235398, -4810983, 4146266), new import__238.Cartesian3(1372574, -5345182, 4606657), new import__238.Cartesian3(-757983, -5542796, 4514323), new import__238.Cartesian3(-2821260, -5248423, 4021290), new import__238.Cartesian3(-2539788, -4724797, 3620093) ]; const tangents = new Array(points2.length); tangents[0] = new import__238.Cartesian3(1125196, -161816, 270551); for (let i = 1; i < tangents.length - 1; ++i) { tangents[i] = import__238.Cartesian3.multiplyByScalar( import__238.Cartesian3.subtract(points2[i + 1], points2[i - 1], new import__238.Cartesian3()), 0.5, new import__238.Cartesian3() ); } tangents[tangents.length - 1] = new import__238.Cartesian3(1165345, 112641, 47281); const interpolate = createHermiteBasis( points2[0], tangents[0], points2[1], tangents[1] ); const hs = import__238.HermiteSpline.createC1({ times: times2, points: points2, tangents }); const granularity = 0.1; for (let j = times2[0]; j < times2[1]; j = j + granularity) { expect(hs.evaluate(j)).toEqualEpsilon( interpolate(j), import__239.Math.EPSILON3 ); } }); it("createNaturalCubic throws without points", function() { expect(function() { return import__238.HermiteSpline.createNaturalCubic(); }).toThrowDeveloperError(); }); it("createNaturalCubic throws when control points length is less than 2", function() { expect(function() { return import__238.HermiteSpline.createNaturalCubic({ points: [import__238.Cartesian3.ZERO] }); }).toThrowDeveloperError(); }); it("createNaturalCubic throws without times", function() { expect(function() { return import__238.HermiteSpline.createNaturalCubic({ points }); }).toThrowDeveloperError(); }); it("createNaturalCubic throws when times.length is not equal to points.length", function() { expect(function() { return import__238.HermiteSpline.createNaturalCubic({ points, times: [0, 1] }); }).toThrowDeveloperError(); }); it("natural cubic spline", function() { points = [ new import__238.Cartesian3(1, 0, 0), new import__238.Cartesian3(0, 1, import__239.Math.PI_OVER_TWO), new import__238.Cartesian3(-1, 0, Math.PI), new import__238.Cartesian3(0, -1, import__239.Math.THREE_PI_OVER_TWO) ]; const p0Tangent = new import__238.Cartesian3(-0.87, 1.53, 1.57); const p1Tangent = new import__238.Cartesian3(-1.27, -0.07, 1.57); const interpolate = createHermiteBasis( points[0], p0Tangent, points[1], p1Tangent ); const hs = import__238.HermiteSpline.createNaturalCubic({ points, times }); const granularity = 0.1; for (let i = times[0]; i < times[1]; i = i + granularity) { expect(hs.evaluate(i)).toEqualEpsilon( interpolate(i), import__239.Math.EPSILON3 ); } }); it("createClampedCubic throws without points", function() { expect(function() { return import__238.HermiteSpline.createClampedCubic(); }).toThrowDeveloperError(); }); it("createClampedCubic throws when control points length is less than 2", function() { expect(function() { return import__238.HermiteSpline.createClampedCubic({ points: [import__238.Cartesian3.ZERO] }); }).toThrowDeveloperError(); }); it("createClampedCubic throws without times", function() { expect(function() { return import__238.HermiteSpline.createClampedCubic({ points }); }).toThrowDeveloperError(); }); it("createClampedCubic throws when times.length is not equal to points.length", function() { expect(function() { return import__238.HermiteSpline.createClampedCubic({ points, times: [0, 1] }); }).toThrowDeveloperError(); }); it("createClampedCubic throws without firstTangent", function() { expect(function() { return import__238.HermiteSpline.createClampedCubic({ points, times }); }).toThrowDeveloperError(); }); it("createClampedCubic throws without lastTangent", function() { expect(function() { return import__238.HermiteSpline.createClampedCubic({ points, times, firstTangent: import__238.Cartesian3.ZERO }); }).toThrowDeveloperError(); }); it("clamped cubic spline", function() { points = [ new import__238.Cartesian3(1, 0, 0), new import__238.Cartesian3(0, 1, import__239.Math.PI_OVER_TWO), new import__238.Cartesian3(-1, 0, Math.PI), new import__238.Cartesian3(0, -1, import__239.Math.THREE_PI_OVER_TWO) ]; const firstTangent = new import__238.Cartesian3(0, 1, 0); const lastTangent = new import__238.Cartesian3(1, 0, 0); const p0Tangent = firstTangent; const p1Tangent = new import__238.Cartesian3(-1.53, 0.13, 1.88); const interpolate = createHermiteBasis( points[0], p0Tangent, points[1], p1Tangent ); const hs = import__238.HermiteSpline.createClampedCubic({ points, times, firstTangent, lastTangent }); const granularity = 0.1; for (let i = points[0].time; i < points[1].time; i = i + granularity) { expect(hs.evaluate(i)).toEqualEpsilon( interpolate(i), import__239.Math.EPSILON3 ); } }); it("evaluate fails with undefined time", function() { const hs = import__238.HermiteSpline.createNaturalCubic({ points, times }); expect(function() { hs.evaluate(); }).toThrowDeveloperError(); }); it("evaluate fails with time out of range", function() { const hs = import__238.HermiteSpline.createNaturalCubic({ points, times }); expect(function() { hs.evaluate(times[0] - 1); }).toThrowDeveloperError(); }); it("evaluate returns number value", function() { const numberTimes = [0, 0.5, 1]; const numberPoints = [0, 1, 0]; const numberInTangents = [0, 1]; const numberOutTangents = [0, -3]; const hs = new import__238.HermiteSpline({ times: numberTimes, points: numberPoints, inTangents: numberInTangents, outTangents: numberOutTangents }); let point = hs.evaluate(numberTimes[1]); expect(point).toEqual(numberPoints[1]); const expected = 0.25; point = hs.evaluate(0.75); expect(point).toEqual(expected); }); it("evaluate returns cartesian3 value", function() { const cartesianTimes = [0, 0.5, 1]; const cartesianPoints = [ new import__238.Cartesian3(-1, 0, 0), new import__238.Cartesian3(1, 2, 0), new import__238.Cartesian3(-1, 0, 0) ]; const cartesianInTangents = [import__238.Cartesian3.ZERO, import__238.Cartesian3.ZERO]; const cartesianOutTangents = [ import__238.Cartesian3.ZERO, new import__238.Cartesian3(0, -3, 0) ]; const hs = new import__238.HermiteSpline({ times: cartesianTimes, points: cartesianPoints, inTangents: cartesianInTangents, outTangents: cartesianOutTangents }); let point = hs.evaluate(cartesianTimes[1]); expect(point).toEqual(cartesianPoints[1]); const expected = new import__238.Cartesian3(0, 0.8125, 0); point = hs.evaluate(0.75); expect(point).toEqual(expected); }); it("evaluate returns cartesian3 value with result parameter", function() { const hs = import__238.HermiteSpline.createNaturalCubic({ points, times }); const result = new import__238.Cartesian3(); const point = hs.evaluate(times[0], result); expect(point).toBe(result); expect(result).toEqual(points[0]); }); const quaternionTimes = [0, 0.5, 1]; const quaternionPoints = [ import__238.Quaternion.IDENTITY, new import__238.Quaternion(0, 0, -0.3827, 0.9239), new import__238.Quaternion(0, 0, -0.7071, 0.7071) ]; const quaternionInTangents = [ new import__238.Quaternion(0, 0, -0.04789, 0.9988), new import__238.Quaternion(-0, 0, -0.03546, 0.99937) ]; const quaternionOutTangents = [ import__238.Quaternion.IDENTITY, new import__238.Quaternion(0, 0, -0.04789, 0.9988) ]; it("evaluate returns quaternion value", function() { const hs = new import__238.HermiteSpline({ times: quaternionTimes, points: quaternionPoints, inTangents: quaternionInTangents, outTangents: quaternionOutTangents }); let point = hs.evaluate(quaternionTimes[1]); expect(point).toEqual(quaternionPoints[1]); const expected = new import__238.Quaternion(0, 0, -0.54567, 0.81546); point = hs.evaluate(0.75); expect(import__238.Quaternion.equalsEpsilon(point, expected, import__239.Math.EPSILON4)).toBe( true ); }); it("evaluate returns quaternion value with result parameter", function() { const hs = new import__238.HermiteSpline({ times: quaternionTimes, points: quaternionPoints, inTangents: quaternionInTangents, outTangents: quaternionOutTangents }); const result = new import__238.Quaternion(); const point = hs.evaluate(quaternionTimes[1], result); expect(point).toBe(result); expect(result).toEqual(quaternionPoints[1]); }); it("createNaturalCubic with 2 control points defaults to lerp", function() { points = points.slice(0, 2); times = times.slice(0, 2); const hs = import__238.HermiteSpline.createNaturalCubic({ points, times }); const t = (times[0] + times[1]) * 0.5; expect(hs.evaluate(t)).toEqual( import__238.Cartesian3.lerp(points[0], points[1], t, new import__238.Cartesian3()) ); }); it("createClampedCubic with 2 control points defaults to lerp", function() { points = points.slice(0, 2); times = times.slice(0, 2); const hs = import__238.HermiteSpline.createNaturalCubic({ points, times }); const t = (times[0] + times[1]) * 0.5; expect(hs.evaluate(t)).toEqual( import__238.Cartesian3.lerp(points[0], points[1], t, new import__238.Cartesian3()) ); }); }); // packages/engine/Specs/Core/HilbertOrderSpec.js var import__240 = __toESM(require_Cesium(), 1); describe("Core/HilbertOrder", function() { if (!import__240.FeatureDetection.supportsBigInt()) { return; } it("encode2D throws for undefined inputs", function() { expect(function() { return import__240.HilbertOrder.encode2D(void 0, 0, 0); }).toThrowDeveloperError(); expect(function() { return import__240.HilbertOrder.encode2D(0, void 0, 0); }).toThrowDeveloperError(); expect(function() { return import__240.HilbertOrder.encode2D(0, 0, void 0); }).toThrowDeveloperError(); }); it("encode2D throws for invalid level", function() { expect(function() { return import__240.HilbertOrder.encode2D(-1, 0, 0); }).toThrowDeveloperError(); expect(function() { return import__240.HilbertOrder.encode2D(0, 0, 0); }).toThrowDeveloperError(); }); it("encode2D throws for invalid coordinates", function() { expect(function() { return import__240.HilbertOrder.encode2D(1, -1, 0); }).toThrowDeveloperError(); expect(function() { return import__240.HilbertOrder.encode2D(0, -1, 0); }).toThrowDeveloperError(); expect(function() { return import__240.HilbertOrder.encode2D(-1, -1, 0); }).toThrowDeveloperError(); expect(function() { return import__240.HilbertOrder.encode2D(1, 2, 0); }).toThrowDeveloperError(); expect(function() { return import__240.HilbertOrder.encode2D(1, 0, 2); }).toThrowDeveloperError(); expect(function() { return import__240.HilbertOrder.encode2D(1, 2, 2); }).toThrowDeveloperError(); }); it("encode2D works", function() { expect(import__240.HilbertOrder.encode2D(1, 0, 0)).toEqual(BigInt(0)); expect(import__240.HilbertOrder.encode2D(1, 0, 1)).toEqual(BigInt(1)); expect(import__240.HilbertOrder.encode2D(1, 1, 1)).toEqual(BigInt(2)); expect(import__240.HilbertOrder.encode2D(1, 1, 0)).toEqual(BigInt(3)); expect(import__240.HilbertOrder.encode2D(2, 0, 0)).toEqual(BigInt(0)); expect(import__240.HilbertOrder.encode2D(2, 1, 0)).toEqual(BigInt(1)); expect(import__240.HilbertOrder.encode2D(2, 1, 1)).toEqual(BigInt(2)); expect(import__240.HilbertOrder.encode2D(2, 0, 1)).toEqual(BigInt(3)); expect(import__240.HilbertOrder.encode2D(2, 0, 2)).toEqual(BigInt(4)); expect(import__240.HilbertOrder.encode2D(2, 0, 3)).toEqual(BigInt(5)); expect(import__240.HilbertOrder.encode2D(2, 1, 3)).toEqual(BigInt(6)); expect(import__240.HilbertOrder.encode2D(2, 1, 2)).toEqual(BigInt(7)); expect(import__240.HilbertOrder.encode2D(2, 2, 2)).toEqual(BigInt(8)); expect(import__240.HilbertOrder.encode2D(2, 2, 3)).toEqual(BigInt(9)); expect(import__240.HilbertOrder.encode2D(2, 3, 3)).toEqual(BigInt(10)); expect(import__240.HilbertOrder.encode2D(2, 3, 2)).toEqual(BigInt(11)); expect(import__240.HilbertOrder.encode2D(2, 3, 1)).toEqual(BigInt(12)); expect(import__240.HilbertOrder.encode2D(2, 2, 1)).toEqual(BigInt(13)); expect(import__240.HilbertOrder.encode2D(2, 2, 0)).toEqual(BigInt(14)); expect(import__240.HilbertOrder.encode2D(2, 3, 0)).toEqual(BigInt(15)); }); it("decode2D throws for invalid level", function() { expect(function() { return import__240.HilbertOrder.decode2D(-1, BigInt(0)); }).toThrowDeveloperError(); expect(function() { return import__240.HilbertOrder.decode2D(0, BigInt(0)); }).toThrowDeveloperError(); }); it("decode2D throws for invalid index", function() { expect(function() { return import__240.HilbertOrder.decode2D(1, BigInt(4)); }).toThrowDeveloperError(); }); it("decode2D works", function() { expect(import__240.HilbertOrder.decode2D(1, BigInt(0))).toEqual([0, 0]); expect(import__240.HilbertOrder.decode2D(1, BigInt(1))).toEqual([0, 1]); expect(import__240.HilbertOrder.decode2D(1, BigInt(2))).toEqual([1, 1]); expect(import__240.HilbertOrder.decode2D(1, BigInt(3))).toEqual([1, 0]); expect(import__240.HilbertOrder.decode2D(2, BigInt(0))).toEqual([0, 0]); expect(import__240.HilbertOrder.decode2D(2, BigInt(1))).toEqual([1, 0]); expect(import__240.HilbertOrder.decode2D(2, BigInt(2))).toEqual([1, 1]); expect(import__240.HilbertOrder.decode2D(2, BigInt(3))).toEqual([0, 1]); expect(import__240.HilbertOrder.decode2D(2, BigInt(4))).toEqual([0, 2]); expect(import__240.HilbertOrder.decode2D(2, BigInt(5))).toEqual([0, 3]); expect(import__240.HilbertOrder.decode2D(2, BigInt(6))).toEqual([1, 3]); expect(import__240.HilbertOrder.decode2D(2, BigInt(7))).toEqual([1, 2]); expect(import__240.HilbertOrder.decode2D(2, BigInt(8))).toEqual([2, 2]); expect(import__240.HilbertOrder.decode2D(2, BigInt(9))).toEqual([2, 3]); expect(import__240.HilbertOrder.decode2D(2, BigInt(10))).toEqual([3, 3]); expect(import__240.HilbertOrder.decode2D(2, BigInt(11))).toEqual([3, 2]); expect(import__240.HilbertOrder.decode2D(2, BigInt(12))).toEqual([3, 1]); expect(import__240.HilbertOrder.decode2D(2, BigInt(13))).toEqual([2, 1]); expect(import__240.HilbertOrder.decode2D(2, BigInt(14))).toEqual([2, 0]); expect(import__240.HilbertOrder.decode2D(2, BigInt(15))).toEqual([3, 0]); }); }); // packages/engine/Specs/Core/Iau2000OrientationSpec.js var import__241 = __toESM(require_Cesium(), 1); describe("Core/Iau2000Orientation", function() { it("compute moon", function() { const date = new import__241.JulianDate(2451545, -32.184, import__241.TimeStandard.TAI); const param = import__241.Iau2000Orientation.ComputeMoon(date); const expectedRightAscension = 4.657546083023791; const expectedDeclination = 1.1456533675897986; const expectedRotation = 0.7189929926922297; const expectedRotationRate = 2651806642576454e-21; expect(param.rightAscension).toEqual(expectedRightAscension); expect(param.declination).toEqual(expectedDeclination); expect(param.rotation).toEqual(expectedRotation); expect(param.rotationRate).toEqual(expectedRotationRate); }); }); // packages/engine/Specs/Core/Iau2006XysDataSpec.js var import__242 = __toESM(require_Cesium(), 1); describe("Core/Iau2006XysData", function() { let xys; beforeEach(function() { xys = new import__242.Iau2006XysData(); }); it("returns undefined initially", function() { expect(xys.computeXysRadians(2442398, 1234.56)).toBeUndefined(); }); it("eventually returns an answer", function() { return pollToPromise_default(function() { return (0, import__242.defined)(xys.computeXysRadians(2442398, 1234.56)); }).then(function() { expect(xys.computeXysRadians(2442399, 777.77)).toBeDefined(); }); }); it("returns the same answer as STK Components", function() { let result; return pollToPromise_default(function() { result = xys.computeXysRadians(2442399, 777.77); return (0, import__242.defined)(result); }).then(function() { expect(result).toEqual( new import__242.Iau2006XysSample( -0.0024019733101066816, -2484327949445831e-20, -1694174791742123e-23 ) ); }); }); it("returns undefined prior to the XYS table epoch", function() { expect(xys.computeXysRadians(2442395, 0)).toBeUndefined(); }); it("returns undefined after the last XYS table sample", function() { expect(xys.computeXysRadians(2442396 + 27427, 0)).toBeUndefined(); }); it("allows configuring xysFileUrlTemplate", function() { xys = new import__242.Iau2006XysData({ // this should be the same location as the default, but specifying the value // takes the code through a different code path. xysFileUrlTemplate: (0, import__242.buildModuleUrl)( "Assets/IAU2006_XYS/IAU2006_XYS_{0}.json" ) }); return pollToPromise_default(function() { return (0, import__242.defined)(xys.computeXysRadians(2442398, 1234.56)); }); }); }); // packages/engine/Specs/Core/IauOrientationAxesSpec.js var import__243 = __toESM(require_Cesium(), 1); var import__244 = __toESM(require_Cesium(), 1); describe("Core/IauOrientationAxes", function() { it("compute ICRF to Moon Fixed", function() { const date = new import__243.JulianDate(2451545, -32.184, import__243.TimeStandard.TAI); const axes = new import__243.IauOrientationAxes(import__243.Iau2000Orientation.ComputeMoon); const expectedMatrix = new import__243.Matrix3( 0.784227052091917, 0.5578471124601639, 0.27165148607559436, -0.6200619152508556, 0.7205566654668133, 0.3103567513471994, -0.022608671404182448, -0.41183090094261243, 0.9109797785934294 ); const mtx = axes.evaluate(date); expect(mtx).toEqualEpsilon(expectedMatrix, import__244.Math.EPSILON13); }); }); // packages/engine/Specs/Core/IndexDatatypeSpec.js var import__245 = __toESM(require_Cesium(), 1); var import__246 = __toESM(require_Cesium(), 1); describe("Core/IndexDatatype", function() { it("validate validates input", function() { expect(import__245.IndexDatatype.validate(import__245.IndexDatatype.UNSIGNED_SHORT)).toEqual(true); expect(import__245.IndexDatatype.validate("invalid")).toEqual(false); expect(import__245.IndexDatatype.validate(void 0)).toEqual(false); }); it("createTypedArray creates array", function() { expect(import__245.IndexDatatype.createTypedArray(3, 3).BYTES_PER_ELEMENT).toEqual( Uint16Array.BYTES_PER_ELEMENT ); expect( import__245.IndexDatatype.createTypedArray(import__246.Math.SIXTY_FOUR_KILOBYTES + 1, 3).BYTES_PER_ELEMENT ).toEqual(Uint32Array.BYTES_PER_ELEMENT); }); it("createTypedArray throws without numberOfVertices", function() { expect(function() { import__245.IndexDatatype.createTypedArray(void 0); }).toThrowDeveloperError(); }); it("createTypedArrayFromArrayBuffer creates Uint16Array", function() { const sourceArray = new Uint16Array(10); sourceArray.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); const indexBuffer = import__245.IndexDatatype.createTypedArrayFromArrayBuffer( 3, sourceArray.buffer, 0, 5 ); expect(indexBuffer.BYTES_PER_ELEMENT).toEqual( Uint16Array.BYTES_PER_ELEMENT ); expect(indexBuffer.length).toEqual(5); expect(indexBuffer[0]).toEqual(0); }); it("createTypedArrayFromArrayBuffer creates Uint16Array with offset", function() { const sourceArray = new Uint16Array(10); sourceArray.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); const indexBuffer = import__245.IndexDatatype.createTypedArrayFromArrayBuffer( 3, sourceArray.buffer, Uint16Array.BYTES_PER_ELEMENT * 5, 5 ); expect(indexBuffer.BYTES_PER_ELEMENT).toEqual( Uint16Array.BYTES_PER_ELEMENT ); expect(indexBuffer.length).toEqual(5); expect(indexBuffer[0]).toEqual(5); }); it("createTypedArrayFromArrayBuffer creates Uint32Array", function() { const sourceArray = new Uint32Array(10); sourceArray.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); const indexBuffer = import__245.IndexDatatype.createTypedArrayFromArrayBuffer( import__246.Math.SIXTY_FOUR_KILOBYTES + 1, sourceArray.buffer, 0, 5 ); expect(indexBuffer.BYTES_PER_ELEMENT).toEqual( Uint32Array.BYTES_PER_ELEMENT ); expect(indexBuffer.length).toEqual(5); expect(indexBuffer[0]).toEqual(0); }); it("createTypedArrayFromArrayBuffer creates Uint32Array with offset", function() { const sourceArray = new Uint32Array(10); sourceArray.set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); const indexBuffer = import__245.IndexDatatype.createTypedArrayFromArrayBuffer( import__246.Math.SIXTY_FOUR_KILOBYTES + 1, sourceArray.buffer, Uint32Array.BYTES_PER_ELEMENT * 5, 5 ); expect(indexBuffer.BYTES_PER_ELEMENT).toEqual( Uint32Array.BYTES_PER_ELEMENT ); expect(indexBuffer.length).toEqual(5); expect(indexBuffer[0]).toEqual(5); }); it("createTypedArrayFromArrayBuffer throws without numberOfVertices", function() { expect(function() { import__245.IndexDatatype.createTypedArrayFromArrayBuffer(void 0); }).toThrowDeveloperError(); }); it("createTypedArrayFromArrayBuffer throws without sourceArray", function() { expect(function() { import__245.IndexDatatype.createTypedArrayFromArrayBuffer(3, void 0); }).toThrowDeveloperError(); }); it("createTypedArrayFromArrayBuffer throws without byteOffset", function() { const sourceArray = new Uint16Array(5); expect(function() { import__245.IndexDatatype.createTypedArrayFromArrayBuffer( 3, sourceArray.buffer, void 0 ); }).toThrowDeveloperError(); }); it("getSizeInBytes returns size", function() { expect(import__245.IndexDatatype.getSizeInBytes(import__245.IndexDatatype.UNSIGNED_BYTE)).toEqual( Uint8Array.BYTES_PER_ELEMENT ); expect(import__245.IndexDatatype.getSizeInBytes(import__245.IndexDatatype.UNSIGNED_SHORT)).toEqual( Uint16Array.BYTES_PER_ELEMENT ); expect(import__245.IndexDatatype.getSizeInBytes(import__245.IndexDatatype.UNSIGNED_INT)).toEqual( Uint32Array.BYTES_PER_ELEMENT ); }); it("getSizeInBytes throws without indexDatatype", function() { expect(function() { import__245.IndexDatatype.getSizeInBytes(void 0); }).toThrowDeveloperError(); }); it("fromTypedArray works", function() { expect(import__245.IndexDatatype.fromTypedArray(new Uint8Array())).toBe( import__245.IndexDatatype.UNSIGNED_BYTE ); expect(import__245.IndexDatatype.fromTypedArray(new Uint16Array())).toBe( import__245.IndexDatatype.UNSIGNED_SHORT ); expect(import__245.IndexDatatype.fromTypedArray(new Uint32Array())).toBe( import__245.IndexDatatype.UNSIGNED_INT ); }); it("fromTypedArray throws if array is not a valid typed array", function() { expect(function() { import__245.IndexDatatype.fromTypedArray(new Int8Array()); }).toThrowDeveloperError(); expect(function() { import__245.IndexDatatype.fromTypedArray([]); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/IntersectionTestsSpec.js var import__247 = __toESM(require_Cesium(), 1); var import__248 = __toESM(require_Cesium(), 1); describe("Core/IntersectionTests", function() { it("rayPlane intersects", function() { const ray = new import__247.Ray( new import__247.Cartesian3(2, 0, 0), new import__247.Cartesian3(-1, 0, 0) ); const plane = new import__247.Plane(import__247.Cartesian3.UNIT_X, -1); const intersectionPoint = import__247.IntersectionTests.rayPlane(ray, plane); expect(intersectionPoint).toEqual(new import__247.Cartesian3(1, 0, 0)); }); it("rayPlane misses", function() { const ray = new import__247.Ray( new import__247.Cartesian3(2, 0, 0), new import__247.Cartesian3(1, 0, 0) ); const plane = new import__247.Plane(import__247.Cartesian3.UNIT_X, -1); const intersectionPoint = import__247.IntersectionTests.rayPlane(ray, plane); expect(intersectionPoint).not.toBeDefined(); }); it("rayPlane misses (parallel)", function() { const ray = new import__247.Ray( new import__247.Cartesian3(2, 0, 0), new import__247.Cartesian3(0, 1, 0) ); const plane = new import__247.Plane(import__247.Cartesian3.UNIT_X, -1); const intersectionPoint = import__247.IntersectionTests.rayPlane(ray, plane); expect(intersectionPoint).not.toBeDefined(); }); it("rayPlane throws without ray", function() { expect(function() { import__247.IntersectionTests.rayPlane(); }).toThrowDeveloperError(); }); it("rayPlane throws without plane", function() { expect(function() { import__247.IntersectionTests.rayPlane(new import__247.Ray(new import__247.Cartesian3(), new import__247.Cartesian3())); }).toThrowDeveloperError(); }); it("rayTriangle throws without ray", function() { expect(function() { import__247.IntersectionTests.rayTriangle(); }).toThrowDeveloperError(); }); it("rayTriangle throws without p0", function() { expect(function() { import__247.IntersectionTests.rayTriangle(new import__247.Ray()); }).toThrowDeveloperError(); }); it("rayTriangle throws without p1", function() { expect(function() { import__247.IntersectionTests.rayTriangle(new import__247.Ray(), new import__247.Cartesian3()); }).toThrowDeveloperError(); }); it("rayTriangle throws without p2", function() { expect(function() { import__247.IntersectionTests.rayTriangle( new import__247.Ray(), new import__247.Cartesian3(), new import__247.Cartesian3() ); }).toThrowDeveloperError(); }); it("rayTriangle intersects front face", function() { const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 0); const ray = new import__247.Ray( import__247.Cartesian3.UNIT_Z, import__247.Cartesian3.negate(import__247.Cartesian3.UNIT_Z, new import__247.Cartesian3()) ); const intersection = import__247.IntersectionTests.rayTriangle(ray, p0, p1, p2); expect(intersection).toEqual(import__247.Cartesian3.ZERO); }); it("rayTriangle intersects back face without culling", function() { const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 0); const ray = new import__247.Ray( import__247.Cartesian3.negate(import__247.Cartesian3.UNIT_Z, new import__247.Cartesian3()), import__247.Cartesian3.UNIT_Z ); const intersection = import__247.IntersectionTests.rayTriangle(ray, p0, p1, p2); expect(intersection).toEqual(import__247.Cartesian3.ZERO); }); it("rayTriangle does not intersect back face with culling", function() { const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 0); const ray = new import__247.Ray( import__247.Cartesian3.negate(import__247.Cartesian3.UNIT_Z, new import__247.Cartesian3()), import__247.Cartesian3.UNIT_Z ); const intersection = import__247.IntersectionTests.rayTriangle(ray, p0, p1, p2, true); expect(intersection).not.toBeDefined(); }); it("rayTriangle does not intersect outside the 0-1 edge", function() { const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 0); const ray = new import__247.Ray( new import__247.Cartesian3(0, -1, 1), import__247.Cartesian3.negate(import__247.Cartesian3.UNIT_Z, new import__247.Cartesian3()) ); const intersection = import__247.IntersectionTests.rayTriangle(ray, p0, p1, p2); expect(intersection).not.toBeDefined(); }); it("rayTriangle does not intersect outside the 1-2 edge", function() { const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 0); const ray = new import__247.Ray( new import__247.Cartesian3(1, 1, 1), import__247.Cartesian3.negate(import__247.Cartesian3.UNIT_Z, new import__247.Cartesian3()) ); const intersection = import__247.IntersectionTests.rayTriangle(ray, p0, p1, p2); expect(intersection).not.toBeDefined(); }); it("rayTriangle does not intersect outside the 2-0 edge", function() { const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 0); const ray = new import__247.Ray( new import__247.Cartesian3(-1, 1, 1), import__247.Cartesian3.negate(import__247.Cartesian3.UNIT_Z, new import__247.Cartesian3()) ); const intersection = import__247.IntersectionTests.rayTriangle(ray, p0, p1, p2); expect(intersection).not.toBeDefined(); }); it("rayTriangle does not intersect parallel ray and triangle", function() { const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 0); const ray = new import__247.Ray(new import__247.Cartesian3(-1, 0, 1), import__247.Cartesian3.UNIT_X); const intersection = import__247.IntersectionTests.rayTriangle(ray, p0, p1, p2); expect(intersection).not.toBeDefined(); }); it("rayTriangle does not intersect behind the ray origin", function() { const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 0); const ray = new import__247.Ray(import__247.Cartesian3.UNIT_Z, import__247.Cartesian3.UNIT_Z); const intersection = import__247.IntersectionTests.rayTriangle(ray, p0, p1, p2); expect(intersection).not.toBeDefined(); }); it("lineSegmentTriangle throws without v0", function() { expect(function() { import__247.IntersectionTests.lineSegmentTriangle(); }).toThrowDeveloperError(); }); it("lineSegmentTriangle throws without v1", function() { expect(function() { import__247.IntersectionTests.lineSegmentTriangle(new import__247.Cartesian3()); }).toThrowDeveloperError(); }); it("lineSegmentTriangle throws without p0", function() { expect(function() { import__247.IntersectionTests.lineSegmentTriangle(new import__247.Cartesian3(), new import__247.Cartesian3()); }).toThrowDeveloperError(); }); it("lineSegmentTriangle throws without p1", function() { expect(function() { import__247.IntersectionTests.lineSegmentTriangle( new import__247.Cartesian3(), new import__247.Cartesian3(), new import__247.Cartesian3() ); }).toThrowDeveloperError(); }); it("lineSegmentTriangle throws without p2", function() { expect(function() { import__247.IntersectionTests.lineSegmentTriangle( new import__247.Cartesian3(), new import__247.Cartesian3(), new import__247.Cartesian3(), new import__247.Cartesian3() ); }).toThrowDeveloperError(); }); it("lineSegmentTriangle intersects front face", function() { const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 0); const v0 = import__247.Cartesian3.UNIT_Z; const v1 = import__247.Cartesian3.negate(import__247.Cartesian3.UNIT_Z, new import__247.Cartesian3()); const intersection = import__247.IntersectionTests.lineSegmentTriangle( v0, v1, p0, p1, p2 ); expect(intersection).toEqual(import__247.Cartesian3.ZERO); }); it("lineSegmentTriangle intersects back face without culling", function() { const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 0); const v0 = import__247.Cartesian3.negate(import__247.Cartesian3.UNIT_Z, new import__247.Cartesian3()); const v1 = import__247.Cartesian3.UNIT_Z; const intersection = import__247.IntersectionTests.lineSegmentTriangle( v0, v1, p0, p1, p2 ); expect(intersection).toEqual(import__247.Cartesian3.ZERO); }); it("lineSegmentTriangle does not intersect back face with culling", function() { const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 0); const v0 = import__247.Cartesian3.negate(import__247.Cartesian3.UNIT_Z, new import__247.Cartesian3()); const v1 = import__247.Cartesian3.UNIT_Z; const intersection = import__247.IntersectionTests.lineSegmentTriangle( v0, v1, p0, p1, p2, true ); expect(intersection).not.toBeDefined(); }); it("lineSegmentTriangle does not intersect outside the 0-1 edge", function() { const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 0); const v0 = new import__247.Cartesian3(0, -1, 1); const v1 = import__247.Cartesian3.add( v0, import__247.Cartesian3.negate(import__247.Cartesian3.UNIT_Z, new import__247.Cartesian3()), new import__247.Cartesian3() ); const intersection = import__247.IntersectionTests.lineSegmentTriangle( v0, v1, p0, p1, p2 ); expect(intersection).not.toBeDefined(); }); it("lineSegmentTriangle does not intersect outside the 1-2 edge", function() { const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 0); const v0 = new import__247.Cartesian3(1, 1, 1); const v1 = import__247.Cartesian3.add( v0, import__247.Cartesian3.negate(import__247.Cartesian3.UNIT_Z, new import__247.Cartesian3()), new import__247.Cartesian3() ); const intersection = import__247.IntersectionTests.lineSegmentTriangle( v0, v1, p0, p1, p2 ); expect(intersection).not.toBeDefined(); }); it("lineSegmentTriangle does not intersect outside the 2-0 edge", function() { const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 0); const v0 = new import__247.Cartesian3(-1, 1, 1); const v1 = import__247.Cartesian3.add( v0, import__247.Cartesian3.negate(import__247.Cartesian3.UNIT_Z, new import__247.Cartesian3()), new import__247.Cartesian3() ); const intersection = import__247.IntersectionTests.lineSegmentTriangle( v0, v1, p0, p1, p2 ); expect(intersection).not.toBeDefined(); }); it("lineSegmentTriangle does not intersect parallel ray and triangle", function() { const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 0); const v0 = new import__247.Cartesian3(-1, 0, 1); const v1 = import__247.Cartesian3.add(v0, import__247.Cartesian3.UNIT_X, new import__247.Cartesian3()); const intersection = import__247.IntersectionTests.lineSegmentTriangle( v0, v1, p0, p1, p2 ); expect(intersection).not.toBeDefined(); }); it("lineSegmentTriangle does not intersect behind the v0", function() { const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 0); const v0 = import__247.Cartesian3.UNIT_Z; const v1 = import__247.Cartesian3.multiplyByScalar( import__247.Cartesian3.UNIT_Z, 2, new import__247.Cartesian3() ); const intersection = import__247.IntersectionTests.lineSegmentTriangle( v0, v1, p0, p1, p2 ); expect(intersection).not.toBeDefined(); }); it("lineSegmentTriangle does not intersect behind the v1", function() { const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 0); const v0 = import__247.Cartesian3.multiplyByScalar( import__247.Cartesian3.UNIT_Z, 2, new import__247.Cartesian3() ); const v1 = import__247.Cartesian3.UNIT_Z; const intersection = import__247.IntersectionTests.lineSegmentTriangle( v0, v1, p0, p1, p2 ); expect(intersection).not.toBeDefined(); }); it("raySphere throws without ray", function() { expect(function() { import__247.IntersectionTests.raySphere(); }).toThrowDeveloperError(); }); it("raySphere throws without ellipsoid", function() { expect(function() { import__247.IntersectionTests.raySphere(new import__247.Ray()); }).toThrowDeveloperError(); }); it("raySphere outside intersections", function() { const unitSphere = new import__247.BoundingSphere(import__247.Cartesian3.ZERO, 1); let ray = new import__247.Ray( new import__247.Cartesian3(2, 0, 0), new import__247.Cartesian3(-1, 0, 0) ); let intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(0, 2, 0), new import__247.Cartesian3(0, -1, 0) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(0, 0, 2), new import__247.Cartesian3(0, 0, -1) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(1, 1, 0), new import__247.Cartesian3(-1, 0, 0) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(-2, 0, 0), new import__247.Cartesian3(1, 0, 0) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(0, -2, 0), new import__247.Cartesian3(0, 1, 0) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(0, 0, -2), new import__247.Cartesian3(0, 0, 1) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(-1, -1, 0), new import__247.Cartesian3(1, 0, 0) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(-2, 0, 0), new import__247.Cartesian3(-1, 0, 0) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections).toBeUndefined(); ray = new import__247.Ray( new import__247.Cartesian3(0, -2, 0), new import__247.Cartesian3(0, -1, 0) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections).toBeUndefined(); ray = new import__247.Ray( new import__247.Cartesian3(0, 0, -2), new import__247.Cartesian3(0, 0, -1) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections).toBeUndefined(); }); it("raySphere ray inside pointing in intersection", function() { const sphere = new import__247.BoundingSphere(import__247.Cartesian3.ZERO, 5e3); const origin = new import__247.Cartesian3(200, 0, 0); const direction = import__247.Cartesian3.negate( import__247.Cartesian3.normalize(origin, new import__247.Cartesian3()), new import__247.Cartesian3() ); const ray = new import__247.Ray(origin, direction); const expected = { start: 0, stop: sphere.radius + origin.x }; const actual = import__247.IntersectionTests.raySphere(ray, sphere); expect(actual).toBeDefined(); expect(actual.start).toEqual(expected.start); expect(actual.stop).toEqual(expected.stop); }); it("raySphere ray inside pointing out intersection", function() { const sphere = new import__247.BoundingSphere(import__247.Cartesian3.ZERO, 5e3); const origin = new import__247.Cartesian3(200, 0, 0); const direction = import__247.Cartesian3.normalize(origin, new import__247.Cartesian3()); const ray = new import__247.Ray(origin, direction); const expected = { start: 0, stop: sphere.radius - origin.x }; const actual = import__247.IntersectionTests.raySphere(ray, sphere); expect(actual).toBeDefined(); expect(actual.start).toEqual(expected.start); expect(actual.stop).toEqual(expected.stop); }); it("raySphere tangent intersections", function() { const unitSphere = new import__247.BoundingSphere(import__247.Cartesian3.ZERO, 1); const ray = new import__247.Ray(import__247.Cartesian3.UNIT_X, import__247.Cartesian3.UNIT_Z); const intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections).not.toBeDefined(); }); it("raySphere no intersections", function() { const unitSphere = new import__247.BoundingSphere(import__247.Cartesian3.ZERO, 1); let ray = new import__247.Ray( new import__247.Cartesian3(2, 0, 0), new import__247.Cartesian3(0, 0, 1) ); let intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections).not.toBeDefined(); ray = new import__247.Ray( new import__247.Cartesian3(2, 0, 0), new import__247.Cartesian3(0, 0, -1) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections).not.toBeDefined(); ray = new import__247.Ray(new import__247.Cartesian3(2, 0, 0), new import__247.Cartesian3(0, 1, 0)); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections).not.toBeDefined(); ray = new import__247.Ray( new import__247.Cartesian3(2, 0, 0), new import__247.Cartesian3(0, -1, 0) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections).not.toBeDefined(); }); it("raySphere intersection with sphere center not the origin", function() { const unitSphere = new import__247.BoundingSphere(new import__247.Cartesian3(200, 0, 0), 1); let ray = new import__247.Ray( new import__247.Cartesian3(202, 0, 0), new import__247.Cartesian3(-1, 0, 0) ); let intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(200, 2, 0), new import__247.Cartesian3(0, -1, 0) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(200, 0, 2), new import__247.Cartesian3(0, 0, -1) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(201, 1, 0), new import__247.Cartesian3(-1, 0, 0) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(198, 0, 0), new import__247.Cartesian3(1, 0, 0) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(200, -2, 0), new import__247.Cartesian3(0, 1, 0) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(200, 0, -2), new import__247.Cartesian3(0, 0, 1) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(199, -1, 0), new import__247.Cartesian3(1, 0, 0) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(198, 0, 0), new import__247.Cartesian3(-1, 0, 0) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections).toBeUndefined(); ray = new import__247.Ray( new import__247.Cartesian3(200, -2, 0), new import__247.Cartesian3(0, -1, 0) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections).toBeUndefined(); ray = new import__247.Ray( new import__247.Cartesian3(200, 0, -2), new import__247.Cartesian3(0, 0, -1) ); intersections = import__247.IntersectionTests.raySphere(ray, unitSphere); expect(intersections).toBeUndefined(); }); it("rayEllipsoid throws without ray", function() { expect(function() { import__247.IntersectionTests.rayEllipsoid(); }).toThrowDeveloperError(); }); it("rayEllipsoid throws without ellipsoid", function() { expect(function() { import__247.IntersectionTests.rayEllipsoid( new import__247.Ray(new import__247.Cartesian3(), new import__247.Cartesian3()) ); }).toThrowDeveloperError(); }); it("rayEllipsoid outside intersections", function() { const unitSphere = import__247.Ellipsoid.UNIT_SPHERE; let ray = new import__247.Ray( new import__247.Cartesian3(2, 0, 0), new import__247.Cartesian3(-1, 0, 0) ); let intersections = import__247.IntersectionTests.rayEllipsoid(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(0, 2, 0), new import__247.Cartesian3(0, -1, 0) ); intersections = import__247.IntersectionTests.rayEllipsoid(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(0, 0, 2), new import__247.Cartesian3(0, 0, -1) ); intersections = import__247.IntersectionTests.rayEllipsoid(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(1, 1, 0), new import__247.Cartesian3(-1, 0, 0) ); intersections = import__247.IntersectionTests.rayEllipsoid(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(-2, 0, 0), new import__247.Cartesian3(1, 0, 0) ); intersections = import__247.IntersectionTests.rayEllipsoid(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(0, -2, 0), new import__247.Cartesian3(0, 1, 0) ); intersections = import__247.IntersectionTests.rayEllipsoid(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(0, 0, -2), new import__247.Cartesian3(0, 0, 1) ); intersections = import__247.IntersectionTests.rayEllipsoid(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); expect(intersections.stop).toEqualEpsilon(3, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(-1, -1, 0), new import__247.Cartesian3(1, 0, 0) ); intersections = import__247.IntersectionTests.rayEllipsoid(ray, unitSphere); expect(intersections.start).toEqualEpsilon(1, import__248.Math.EPSILON14); ray = new import__247.Ray( new import__247.Cartesian3(-2, 0, 0), new import__247.Cartesian3(-1, 0, 0) ); intersections = import__247.IntersectionTests.rayEllipsoid(ray, unitSphere); expect(intersections).toBeUndefined(); ray = new import__247.Ray( new import__247.Cartesian3(0, -2, 0), new import__247.Cartesian3(0, -1, 0) ); intersections = import__247.IntersectionTests.rayEllipsoid(ray, unitSphere); expect(intersections).toBeUndefined(); ray = new import__247.Ray( new import__247.Cartesian3(0, 0, -2), new import__247.Cartesian3(0, 0, -1) ); intersections = import__247.IntersectionTests.rayEllipsoid(ray, unitSphere); expect(intersections).toBeUndefined(); }); it("rayEllipsoid ray inside pointing in intersection", function() { const ellipsoid = import__247.Ellipsoid.WGS84; const origin = new import__247.Cartesian3(2e4, 0, 0); const direction = import__247.Cartesian3.negate( import__247.Cartesian3.normalize(origin, new import__247.Cartesian3()), new import__247.Cartesian3() ); const ray = new import__247.Ray(origin, direction); const expected = { start: 0, stop: ellipsoid.radii.x + origin.x }; const actual = import__247.IntersectionTests.rayEllipsoid(ray, ellipsoid); expect(actual).toBeDefined(); expect(actual.start).toEqual(expected.start); expect(actual.stop).toEqual(expected.stop); }); it("rayEllipsoid ray inside pointing out intersection", function() { const ellipsoid = import__247.Ellipsoid.WGS84; const origin = new import__247.Cartesian3(2e4, 0, 0); const direction = import__247.Cartesian3.normalize(origin, new import__247.Cartesian3()); const ray = new import__247.Ray(origin, direction); const expected = { start: 0, stop: ellipsoid.radii.x - origin.x }; const actual = import__247.IntersectionTests.rayEllipsoid(ray, ellipsoid); expect(actual).toBeDefined(); expect(actual.start).toEqual(expected.start); expect(actual.stop).toEqual(expected.stop); }); it("rayEllipsoid tangent intersections", function() { const unitSphere = import__247.Ellipsoid.UNIT_SPHERE; const ray = new import__247.Ray(import__247.Cartesian3.UNIT_X, import__247.Cartesian3.UNIT_Z); const intersections = import__247.IntersectionTests.rayEllipsoid(ray, unitSphere); expect(intersections).not.toBeDefined(); }); it("rayEllipsoid no intersections", function() { const unitSphere = import__247.Ellipsoid.UNIT_SPHERE; let ray = new import__247.Ray( new import__247.Cartesian3(2, 0, 0), new import__247.Cartesian3(0, 0, 1) ); let intersections = import__247.IntersectionTests.rayEllipsoid(ray, unitSphere); expect(intersections).not.toBeDefined(); ray = new import__247.Ray( new import__247.Cartesian3(2, 0, 0), new import__247.Cartesian3(0, 0, -1) ); intersections = import__247.IntersectionTests.rayEllipsoid(ray, unitSphere); expect(intersections).not.toBeDefined(); ray = new import__247.Ray(new import__247.Cartesian3(2, 0, 0), new import__247.Cartesian3(0, 1, 0)); intersections = import__247.IntersectionTests.rayEllipsoid(ray, unitSphere); expect(intersections).not.toBeDefined(); ray = new import__247.Ray( new import__247.Cartesian3(2, 0, 0), new import__247.Cartesian3(0, -1, 0) ); intersections = import__247.IntersectionTests.rayEllipsoid(ray, unitSphere); expect(intersections).not.toBeDefined(); }); it("grazingAltitudeLocation throws without ray", function() { expect(function() { import__247.IntersectionTests.grazingAltitudeLocation(); }).toThrowDeveloperError(); }); it("grazingAltitudeLocation throws without ellipsoid", function() { expect(function() { import__247.IntersectionTests.grazingAltitudeLocation(new import__247.Ray()); }).toThrowDeveloperError(); }); it("grazingAltitudeLocation is origin of ray", function() { const ellipsoid = import__247.Ellipsoid.UNIT_SPHERE; const ray = new import__247.Ray(new import__247.Cartesian3(3, 0, 0), import__247.Cartesian3.UNIT_X); expect(import__247.IntersectionTests.grazingAltitudeLocation(ray, ellipsoid)).toEqual( ray.origin ); }); it("grazingAltitudeLocation outside ellipsoid", function() { const ellipsoid = import__247.Ellipsoid.UNIT_SPHERE; let ray = new import__247.Ray(new import__247.Cartesian3(-2, -2, 0), import__247.Cartesian3.UNIT_X); let expected = new import__247.Cartesian3(0, -2, 0); let actual = import__247.IntersectionTests.grazingAltitudeLocation(ray, ellipsoid); expect(actual).toEqualEpsilon(expected, import__248.Math.EPSILON15); ray = new import__247.Ray( new import__247.Cartesian3(0, 2, 2), import__247.Cartesian3.negate(import__247.Cartesian3.UNIT_Y, new import__247.Cartesian3()) ); expected = new import__247.Cartesian3(0, 0, 2); actual = import__247.IntersectionTests.grazingAltitudeLocation(ray, ellipsoid); expect(actual).toEqualEpsilon(expected, import__248.Math.EPSILON15); }); it("grazingAltitudeLocation outside ellipsoid 2", function() { const ellipsoid = import__247.Ellipsoid.WGS84; const origin = new import__247.Cartesian3( 6502435411150063e-9, -6350860759819263e-9, -7230794954832983e-9 ); const direction = new import__247.Cartesian3( -0.6053473557455881, 0.002372596412575323, 0.7959578818493397 ); const ray = new import__247.Ray(origin, direction); const expected = new import__247.Cartesian3( 628106.8386515155, -6327836936616249e-9, 493230.07552381355 ); const actual = import__247.IntersectionTests.grazingAltitudeLocation(ray, ellipsoid); expect(actual).toEqualEpsilon(expected, import__248.Math.EPSILON8); }); it("grazingAltitudeLocation outside ellipsoid 3", function() { const ellipsoid = import__247.Ellipsoid.WGS84; const origin = new import__247.Cartesian3( -6546204940468501e-9, -1062519562660887e-8, -693374582875373e-8 ); const direction = new import__247.Cartesian3( 0.5130076305689283, 0.38589525779680295, 0.766751603185799 ); const ray = new import__247.Ray(origin, direction); const expected = new import__247.Cartesian3( -125.9063174739769, -5701095640722358e-9, 285015657342018e-8 ); const actual = import__247.IntersectionTests.grazingAltitudeLocation(ray, ellipsoid); expect(actual).toEqualEpsilon(expected, import__248.Math.EPSILON10); }); it("grazingAltitudeLocation inside ellipsoid", function() { const ellipsoid = import__247.Ellipsoid.UNIT_SPHERE; const ray = new import__247.Ray(new import__247.Cartesian3(0.5, 0, 0), import__247.Cartesian3.UNIT_Z); const actual = import__247.IntersectionTests.grazingAltitudeLocation(ray, ellipsoid); expect(actual).toEqual(ray.origin); }); it("grazingAltitudeLocation is undefined", function() { const ellipsoid = import__247.Ellipsoid.UNIT_SPHERE; const ray = new import__247.Ray(import__247.Cartesian3.ZERO, import__247.Cartesian3.UNIT_Z); expect( import__247.IntersectionTests.grazingAltitudeLocation(ray, ellipsoid) ).not.toBeDefined(); }); it("lineSegmentPlane intersects", function() { const normal = import__247.Cartesian3.clone(import__247.Cartesian3.UNIT_Y); const point = new import__247.Cartesian3(0, 2, 0); const plane = import__247.Plane.fromPointNormal(point, normal); const endPoint0 = new import__247.Cartesian3(1, 1, 0); const endPoint1 = new import__247.Cartesian3(1, 3, 0); const intersectionPoint = import__247.IntersectionTests.lineSegmentPlane( endPoint0, endPoint1, plane ); expect(intersectionPoint).toEqual(new import__247.Cartesian3(1, 2, 0)); }); it("lineSegmentPlane misses (entire segment behind plane)", function() { const plane = new import__247.Plane(import__247.Cartesian3.UNIT_X, 0); const endPoint0 = new import__247.Cartesian3(-2, 0, 0); const endPoint1 = new import__247.Cartesian3(-5, 0, 0); const intersectionPoint = import__247.IntersectionTests.lineSegmentPlane( endPoint0, endPoint1, plane ); expect(intersectionPoint).not.toBeDefined(); }); it("lineSegmentPlane misses (entire segment in front of plane)", function() { const plane = new import__247.Plane(import__247.Cartesian3.UNIT_X, 0); const endPoint0 = new import__247.Cartesian3(5, 0, 0); const endPoint1 = new import__247.Cartesian3(2, 0, 0); const intersectionPoint = import__247.IntersectionTests.lineSegmentPlane( endPoint0, endPoint1, plane ); expect(intersectionPoint).not.toBeDefined(); }); it("lineSegmentPlane misses (parallel)", function() { const plane = new import__247.Plane(import__247.Cartesian3.UNIT_X, 0); const endPoint0 = new import__247.Cartesian3(0, -1, 0); const endPoint1 = new import__247.Cartesian3(0, 1, 0); const intersectionPoint = import__247.IntersectionTests.lineSegmentPlane( endPoint0, endPoint1, plane ); expect(intersectionPoint).not.toBeDefined(); }); it("lineSegmentPlane throws without endPoint0", function() { expect(function() { import__247.IntersectionTests.lineSegmentPlane(); }).toThrowDeveloperError(); }); it("lineSegmentPlane throws without endPoint1", function() { expect(function() { import__247.IntersectionTests.lineSegmentPlane(new import__247.Cartesian3()); }).toThrowDeveloperError(); }); it("lineSegmentPlane throws without plane", function() { expect(function() { import__247.IntersectionTests.lineSegmentPlane(new import__247.Cartesian3(), new import__247.Cartesian3()); }).toThrowDeveloperError(); }); it("triangle is front of a plane", function() { const plane = new import__247.Plane(import__247.Cartesian3.UNIT_Z, 0); const p0 = new import__247.Cartesian3(0, 0, 2); const p1 = new import__247.Cartesian3(0, 1, 2); const p2 = new import__247.Cartesian3(1, 0, 2); const triangles = import__247.IntersectionTests.trianglePlaneIntersection( p0, p1, p2, plane ); expect(triangles).not.toBeDefined(); }); it("triangle is behind a plane", function() { const plane = new import__247.Plane( import__247.Cartesian3.negate(import__247.Cartesian3.UNIT_Z, new import__247.Cartesian3()), 0 ); const p0 = new import__247.Cartesian3(0, 0, 2); const p1 = new import__247.Cartesian3(0, 1, 2); const p2 = new import__247.Cartesian3(1, 0, 2); const triangles = import__247.IntersectionTests.trianglePlaneIntersection( p0, p1, p2, plane ); expect(triangles).not.toBeDefined(); }); it("triangle intersects plane with p0 behind", function() { const plane = new import__247.Plane(import__247.Cartesian3.UNIT_Z, -1); const p0 = new import__247.Cartesian3(0, 0, 0); const p1 = new import__247.Cartesian3(0, 1, 2); const p2 = new import__247.Cartesian3(0, -1, 2); const triangles = import__247.IntersectionTests.trianglePlaneIntersection( p0, p1, p2, plane ); expect(triangles).toBeDefined(); expect(triangles.indices.length).toEqual(3 + 6); expect( import__247.Cartesian3.equals(triangles.positions[triangles.indices[0]], p0) ).toEqual(true); }); it("triangle intersects plane with p1 behind", function() { const plane = new import__247.Plane(import__247.Cartesian3.UNIT_Z, -1); const p0 = new import__247.Cartesian3(0, -1, 2); const p1 = new import__247.Cartesian3(0, 0, 0); const p2 = new import__247.Cartesian3(0, 1, 2); const triangles = import__247.IntersectionTests.trianglePlaneIntersection( p0, p1, p2, plane ); expect(triangles).toBeDefined(); expect(triangles.indices.length).toEqual(3 + 6); expect( import__247.Cartesian3.equals(triangles.positions[triangles.indices[0]], p1) ).toEqual(true); }); it("triangle intersects plane with p2 behind", function() { const plane = new import__247.Plane(import__247.Cartesian3.UNIT_Z, -1); const p0 = new import__247.Cartesian3(0, 1, 2); const p1 = new import__247.Cartesian3(0, -1, 2); const p2 = new import__247.Cartesian3(0, 0, 0); const triangles = import__247.IntersectionTests.trianglePlaneIntersection( p0, p1, p2, plane ); expect(triangles).toBeDefined(); expect(triangles.indices.length).toEqual(3 + 6); expect( import__247.Cartesian3.equals(triangles.positions[triangles.indices[0]], p2) ).toEqual(true); }); it("triangle intersects plane with p0 in front", function() { const plane = new import__247.Plane(import__247.Cartesian3.UNIT_Y, -1); const p0 = new import__247.Cartesian3(0, 2, 0); const p1 = new import__247.Cartesian3(1, 0, 0); const p2 = new import__247.Cartesian3(-1, 0, 0); const triangles = import__247.IntersectionTests.trianglePlaneIntersection( p0, p1, p2, plane ); expect(triangles).toBeDefined(); expect(triangles.indices.length).toEqual(6 + 3); expect( import__247.Cartesian3.equals(triangles.positions[triangles.indices[0]], p1) ).toEqual(true); expect( import__247.Cartesian3.equals(triangles.positions[triangles.indices[1]], p2) ).toEqual(true); }); it("triangle intersects plane with p1 in front", function() { const plane = new import__247.Plane(import__247.Cartesian3.UNIT_Y, -1); const p0 = new import__247.Cartesian3(-1, 0, 0); const p1 = new import__247.Cartesian3(0, 2, 0); const p2 = new import__247.Cartesian3(1, 0, 0); const triangles = import__247.IntersectionTests.trianglePlaneIntersection( p0, p1, p2, plane ); expect(triangles).toBeDefined(); expect(triangles.indices.length).toEqual(6 + 3); expect( import__247.Cartesian3.equals(triangles.positions[triangles.indices[0]], p2) ).toEqual(true); expect( import__247.Cartesian3.equals(triangles.positions[triangles.indices[1]], p0) ).toEqual(true); }); it("triangle intersects plane with p2 in front", function() { const plane = new import__247.Plane(import__247.Cartesian3.UNIT_Y, -1); const p0 = new import__247.Cartesian3(1, 0, 0); const p1 = new import__247.Cartesian3(-1, 0, 0); const p2 = new import__247.Cartesian3(0, 2, 0); const triangles = import__247.IntersectionTests.trianglePlaneIntersection( p0, p1, p2, plane ); expect(triangles).toBeDefined(); expect(triangles.indices.length).toEqual(6 + 3); expect( import__247.Cartesian3.equals(triangles.positions[triangles.indices[0]], p0), true ); expect( import__247.Cartesian3.equals(triangles.positions[triangles.indices[1]], p1) ).toEqual(true); }); it("trianglePlaneIntersection throws without p0", function() { expect(function() { return import__247.IntersectionTests.trianglePlaneIntersection(); }).toThrowDeveloperError(); }); it("trianglePlaneIntersection throws without p1", function() { const p = import__247.Cartesian3.UNIT_X; expect(function() { return import__247.IntersectionTests.trianglePlaneIntersection(p); }).toThrowDeveloperError(); }); it("trianglePlaneIntersection throws without p2", function() { const p = import__247.Cartesian3.UNIT_X; expect(function() { return import__247.IntersectionTests.trianglePlaneIntersection(p, p); }).toThrowDeveloperError(); }); it("trianglePlaneIntersection throws without plane", function() { const p = import__247.Cartesian3.UNIT_X; expect(function() { return import__247.IntersectionTests.trianglePlaneIntersection(p, p, p); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/Intersections2DSpec.js var import__249 = __toESM(require_Cesium(), 1); describe("Core/Intersections2D", function() { describe("clipTriangleAtAxisAlignedThreshold", function() { it("eliminates a triangle that is entirely on the wrong side of the threshold", function() { const result = import__249.Intersections2D.clipTriangleAtAxisAlignedThreshold( 0.1, false, 0.2, 0.3, 0.4 ); expect(result.length).toBe(0); }); it("keeps a triangle that is entirely on the correct side of the threshold", function() { const result = import__249.Intersections2D.clipTriangleAtAxisAlignedThreshold( 0.1, true, 0.2, 0.3, 0.4 ); expect(result.length).toBe(3); expect(result[0]).toBe(0); expect(result[1]).toBe(1); expect(result[2]).toBe(2); }); it("adds two vertices on threshold when point 0 is on the wrong side and above", function() { const result = import__249.Intersections2D.clipTriangleAtAxisAlignedThreshold( 0.5, false, 0.6, 0.4, 0.2 ); expect(result.length).toBe(10); expect(result[0]).toBe(1); expect(result[1]).toBe(2); expect(result[2]).toBe(-1); expect(result[3]).toBe(0); expect(result[4]).toBe(2); expect(result[5]).toEqualEpsilon(0.25, 1e-14); expect(result[6]).toBe(-1); expect(result[7]).toBe(0); expect(result[8]).toBe(1); expect(result[9]).toEqualEpsilon(0.5, 1e-14); }); it("adds two vertices on threshold when point 0 is on the wrong side and below", function() { const result = import__249.Intersections2D.clipTriangleAtAxisAlignedThreshold( 0.5, true, 0.4, 0.6, 0.8 ); expect(result.length).toBe(10); expect(result[0]).toBe(1); expect(result[1]).toBe(2); expect(result[2]).toBe(-1); expect(result[3]).toBe(0); expect(result[4]).toBe(2); expect(result[5]).toEqualEpsilon(0.25, 1e-14); expect(result[6]).toBe(-1); expect(result[7]).toBe(0); expect(result[8]).toBe(1); expect(result[9]).toEqualEpsilon(0.5, 1e-14); }); it("adds two vertices on threshold when point 1 is on the wrong side and above", function() { const result = import__249.Intersections2D.clipTriangleAtAxisAlignedThreshold( 0.5, false, 0.2, 0.6, 0.4 ); expect(result.length).toBe(10); expect(result[0]).toBe(2); expect(result[1]).toBe(0); expect(result[2]).toBe(-1); expect(result[3]).toBe(1); expect(result[4]).toBe(0); expect(result[5]).toEqualEpsilon(0.25, 1e-14); expect(result[6]).toBe(-1); expect(result[7]).toBe(1); expect(result[8]).toBe(2); expect(result[9]).toEqualEpsilon(0.5, 1e-14); }); it("adds two vertices on threshold when point 1 is on the wrong side and below", function() { const result = import__249.Intersections2D.clipTriangleAtAxisAlignedThreshold( 0.5, true, 0.8, 0.4, 0.6 ); expect(result.length).toBe(10); expect(result[0]).toBe(2); expect(result[1]).toBe(0); expect(result[2]).toBe(-1); expect(result[3]).toBe(1); expect(result[4]).toBe(0); expect(result[5]).toEqualEpsilon(0.25, 1e-14); expect(result[6]).toBe(-1); expect(result[7]).toBe(1); expect(result[8]).toBe(2); expect(result[9]).toEqualEpsilon(0.5, 1e-14); }); it("adds two vertices on threshold when point 2 is on the wrong side and above", function() { const result = import__249.Intersections2D.clipTriangleAtAxisAlignedThreshold( 0.5, false, 0.4, 0.2, 0.6 ); expect(result.length).toBe(10); expect(result[0]).toBe(0); expect(result[1]).toBe(1); expect(result[2]).toBe(-1); expect(result[3]).toBe(2); expect(result[4]).toBe(1); expect(result[5]).toEqualEpsilon(0.25, 1e-14); expect(result[6]).toBe(-1); expect(result[7]).toBe(2); expect(result[8]).toBe(0); expect(result[9]).toEqualEpsilon(0.5, 1e-14); }); it("adds two vertices on threshold when point 2 is on the wrong side and below", function() { const result = import__249.Intersections2D.clipTriangleAtAxisAlignedThreshold( 0.5, true, 0.6, 0.8, 0.4 ); expect(result.length).toBe(10); expect(result[0]).toBe(0); expect(result[1]).toBe(1); expect(result[2]).toBe(-1); expect(result[3]).toBe(2); expect(result[4]).toBe(1); expect(result[5]).toEqualEpsilon(0.25, 1e-14); expect(result[6]).toBe(-1); expect(result[7]).toBe(2); expect(result[8]).toBe(0); expect(result[9]).toEqualEpsilon(0.5, 1e-14); }); it("adds two vertices on threshold when only point 0 is on the right side and below", function() { const result = import__249.Intersections2D.clipTriangleAtAxisAlignedThreshold( 0.5, false, 0.4, 0.6, 0.8 ); expect(result.length).toBe(9); expect(result[0]).toBe(0); expect(result[1]).toBe(-1); expect(result[2]).toBe(1); expect(result[3]).toBe(0); expect(result[4]).toEqualEpsilon(0.5, 1e-14); expect(result[5]).toBe(-1); expect(result[6]).toBe(2); expect(result[7]).toBe(0); expect(result[8]).toEqualEpsilon(0.75, 1e-14); }); it("adds two vertices on threshold when only point 0 is on the right side and above", function() { const result = import__249.Intersections2D.clipTriangleAtAxisAlignedThreshold( 0.5, true, 0.6, 0.4, 0.2 ); expect(result.length).toBe(9); expect(result[0]).toBe(0); expect(result[1]).toBe(-1); expect(result[2]).toBe(1); expect(result[3]).toBe(0); expect(result[4]).toEqualEpsilon(0.5, 1e-14); expect(result[5]).toBe(-1); expect(result[6]).toBe(2); expect(result[7]).toBe(0); expect(result[8]).toEqualEpsilon(0.75, 1e-14); }); it("adds two vertices on threshold when only point 1 is on the right side and below", function() { const result = import__249.Intersections2D.clipTriangleAtAxisAlignedThreshold( 0.5, false, 0.8, 0.4, 0.6 ); expect(result.length).toBe(9); expect(result[0]).toBe(1); expect(result[1]).toBe(-1); expect(result[2]).toBe(2); expect(result[3]).toBe(1); expect(result[4]).toEqualEpsilon(0.5, 1e-14); expect(result[5]).toBe(-1); expect(result[6]).toBe(0); expect(result[7]).toBe(1); expect(result[8]).toEqualEpsilon(0.75, 1e-14); }); it("adds two vertices on threshold when only point 1 is on the right side and above", function() { const result = import__249.Intersections2D.clipTriangleAtAxisAlignedThreshold( 0.5, true, 0.2, 0.6, 0.4 ); expect(result.length).toBe(9); expect(result[0]).toBe(1); expect(result[1]).toBe(-1); expect(result[2]).toBe(2); expect(result[3]).toBe(1); expect(result[4]).toEqualEpsilon(0.5, 1e-14); expect(result[5]).toBe(-1); expect(result[6]).toBe(0); expect(result[7]).toBe(1); expect(result[8]).toEqualEpsilon(0.75, 1e-14); }); it("adds two vertices on threshold when only point 2 is on the right side and below", function() { const result = import__249.Intersections2D.clipTriangleAtAxisAlignedThreshold( 0.5, false, 0.6, 0.8, 0.4 ); expect(result.length).toBe(9); expect(result[0]).toBe(2); expect(result[1]).toBe(-1); expect(result[2]).toBe(0); expect(result[3]).toBe(2); expect(result[4]).toEqualEpsilon(0.5, 1e-14); expect(result[5]).toBe(-1); expect(result[6]).toBe(1); expect(result[7]).toBe(2); expect(result[8]).toEqualEpsilon(0.75, 1e-14); }); it("adds two vertices on threshold when only point 2 is on the right side and above", function() { const result = import__249.Intersections2D.clipTriangleAtAxisAlignedThreshold( 0.5, true, 0.4, 0.2, 0.6 ); expect(result.length).toBe(9); expect(result[0]).toBe(2); expect(result[1]).toBe(-1); expect(result[2]).toBe(0); expect(result[3]).toBe(2); expect(result[4]).toEqualEpsilon(0.5, 1e-14); expect(result[5]).toBe(-1); expect(result[6]).toBe(1); expect(result[7]).toBe(2); expect(result[8]).toEqualEpsilon(0.75, 1e-14); }); }); describe("computeBarycentricCoordinates", function() { it("returns the correct result for positions on a triangle vertex", function() { const ll = import__249.Intersections2D.computeBarycentricCoordinates( 0, 0, 0, 0, 1, 0, 0, 1 ); expect(ll.x).toEqualEpsilon(1, 1e-15); expect(ll.y).toEqualEpsilon(0, 1e-15); expect(ll.z).toEqualEpsilon(0, 1e-15); const lr = import__249.Intersections2D.computeBarycentricCoordinates( 1, 0, 0, 0, 1, 0, 0, 1 ); expect(lr.x).toEqualEpsilon(0, 1e-15); expect(lr.y).toEqualEpsilon(1, 1e-15); expect(lr.z).toEqualEpsilon(0, 1e-15); const ul = import__249.Intersections2D.computeBarycentricCoordinates( 0, 1, 0, 0, 1, 0, 0, 1 ); expect(ul.x).toEqualEpsilon(0, 1e-15); expect(ul.y).toEqualEpsilon(0, 1e-15); expect(ul.z).toEqualEpsilon(1, 1e-15); }); it("returns the correct result for a position in the barycenter of a triangle", function() { const result = import__249.Intersections2D.computeBarycentricCoordinates( 0, 0, 0, 1, -1, -0.5, 1, -0.5 ); expect(result.x).toEqualEpsilon(1 / 3, 1e-15); expect(result.y).toEqualEpsilon(1 / 3, 1e-15); expect(result.z).toEqualEpsilon(1 / 3, 1e-15); }); it("returns the correct result for a position on an edge between two vertices", function() { const e12 = import__249.Intersections2D.computeBarycentricCoordinates( 1.5, 1, 1, 1, 2, 1, 1, 2 ); expect(e12.x).toEqualEpsilon(0.5, 1e-15); expect(e12.y).toEqualEpsilon(0.5, 1e-15); expect(e12.z).toEqualEpsilon(0, 1e-15); const e23 = import__249.Intersections2D.computeBarycentricCoordinates( 1.5, 1.5, 1, 1, 2, 1, 1, 2 ); expect(e23.x).toEqualEpsilon(0, 1e-15); expect(e23.y).toEqualEpsilon(0.5, 1e-15); expect(e23.z).toEqualEpsilon(0.5, 1e-15); const e31 = import__249.Intersections2D.computeBarycentricCoordinates( 1, 1.5, 1, 1, 2, 1, 1, 2 ); expect(e31.x).toEqualEpsilon(0.5, 1e-15); expect(e31.y).toEqualEpsilon(0, 1e-15); expect(e31.z).toEqualEpsilon(0.5, 1e-15); }); it("returns the correct result for a position outside a triangle", function() { const result1 = import__249.Intersections2D.computeBarycentricCoordinates( 0.5, 0.5, 1, 1, 2, 1, 1, 2 ); expect(result1.x).toBeGreaterThan(0); expect(result1.y).toBeLessThan(0); expect(result1.z).toBeLessThan(0); const result2 = import__249.Intersections2D.computeBarycentricCoordinates( 2.1, 0.99, 1, 1, 2, 1, 1, 2 ); expect(result2.x).toBeLessThan(0); expect(result2.y).toBeGreaterThan(0); expect(result2.z).toBeLessThan(0); const result3 = import__249.Intersections2D.computeBarycentricCoordinates( 0.99, 2.1, 1, 1, 2, 1, 1, 2 ); expect(result3.x).toBeLessThan(0); expect(result3.y).toBeLessThan(0); expect(result3.z).toBeGreaterThan(0); }); }); describe("computeLineSegmentLineSegmentIntersection", function() { it("returns the correct result for intersection point", function() { const intersection0 = import__249.Intersections2D.computeLineSegmentLineSegmentIntersection( 0, 0, 0, 2, -1, 1, 1, 1 ); expect(intersection0.x).toEqualEpsilon(0, 1e-15); expect(intersection0.y).toEqualEpsilon(1, 1e-15); const intersection1 = import__249.Intersections2D.computeLineSegmentLineSegmentIntersection( 0, 0, 10, 5, 0, 5, 10, 0 ); expect(intersection1.x).toEqualEpsilon(5, 1e-15); expect(intersection1.y).toEqualEpsilon(2.5, 1e-15); const intersection2 = import__249.Intersections2D.computeLineSegmentLineSegmentIntersection( 0, -5, 4, 3, -2, 1, 4, -2 ); expect(intersection2.x).toEqualEpsilon(2, 1e-15); expect(intersection2.y).toEqualEpsilon(-1, 1e-15); }); it("returns the correct result for intersection point on a vertex", function() { const intersection0 = import__249.Intersections2D.computeLineSegmentLineSegmentIntersection( 0, 0, 0, 2, -1, 0, 1, 0 ); expect(intersection0.x).toEqualEpsilon(0, 1e-15); expect(intersection0.y).toEqualEpsilon(0, 1e-15); const intersection1 = import__249.Intersections2D.computeLineSegmentLineSegmentIntersection( 0, 0, 1, 1, 1, 1, 2, 0 ); expect(intersection1.x).toEqualEpsilon(1, 1e-15); expect(intersection1.y).toEqualEpsilon(1, 1e-15); const intersection2 = import__249.Intersections2D.computeLineSegmentLineSegmentIntersection( 0, 0, 4, 3, 5, 0, 4, 3 ); expect(intersection2.x).toEqualEpsilon(4, 1e-15); expect(intersection2.y).toEqualEpsilon(3, 1e-15); }); it("returns undefined for non-intersecting lines", function() { const intersection0 = import__249.Intersections2D.computeLineSegmentLineSegmentIntersection( 0, 0, 0, 5, 0.1, 4.8, 5, 0 ); expect(intersection0).toBeUndefined(); const intersection1 = import__249.Intersections2D.computeLineSegmentLineSegmentIntersection( 10, 0, 0, -10, 0, 0, -8, -8 ); expect(intersection1).toBeUndefined(); }); it("returns undefined for parallel lines", function() { const intersection0 = import__249.Intersections2D.computeLineSegmentLineSegmentIntersection( 0, 0, 0, 2, 1, 1, 1, 4 ); expect(intersection0).toBeUndefined(); const intersection1 = import__249.Intersections2D.computeLineSegmentLineSegmentIntersection( 1, 1, 4, 4, 0, 0, 3, 3 ); expect(intersection1).toBeUndefined(); }); it("returns undefined for coincident lines", function() { const intersection0 = import__249.Intersections2D.computeLineSegmentLineSegmentIntersection( 0, 0, 0, 2, 0, 1, 0, 4 ); expect(intersection0).toBeUndefined(); const intersection1 = import__249.Intersections2D.computeLineSegmentLineSegmentIntersection( 0, 0, 0, 2, 0, 0, 0, 2 ); expect(intersection1).toBeUndefined(); }); }); }); // packages/engine/Specs/Core/IntervalSpec.js var import__250 = __toESM(require_Cesium(), 1); describe("Core/Interval", function() { it("constructs without arguments", function() { const interval = new import__250.Interval(); expect(interval.start).toEqual(0); expect(interval.stop).toEqual(0); }); it("constructs with arguments", function() { const start = 1; const stop = 2; const interval = new import__250.Interval(start, stop); expect(interval.start).toEqual(start); expect(interval.stop).toEqual(stop); }); }); // packages/engine/Specs/Core/IonGeocoderServiceSpec.js var import__251 = __toESM(require_Cesium(), 1); describe("Core/IonGeocoderService", function() { let scene2; beforeEach(function() { scene2 = createScene_default(); }); afterEach(function() { scene2.destroyForSpecs(); }); it("conforms to GeocoderService interface", function() { expect(import__251.IonGeocoderService).toConformToInterface(import__251.GeocoderService); }); it("creates with default parameters", function() { const service = new import__251.IonGeocoderService({ scene: scene2 }); expect(service._accessToken).toEqual(import__251.Ion.defaultAccessToken); expect(service._server.url).toEqual(import__251.Ion.defaultServer.url); }); it("creates with specified parameters", function() { const accessToken = "123456"; const server = "http://not.ion.invalid/"; const service = new import__251.IonGeocoderService({ accessToken, server, scene: scene2 }); expect(service._accessToken).toEqual(accessToken); expect(service._server.url).toEqual(server); }); it("calls inner geocoder and returns result", async function() { const service = new import__251.IonGeocoderService({ scene: scene2 }); const expectedResult = ["results"]; spyOn(service._pelias, "geocode").and.returnValue( Promise.resolve(expectedResult) ); const query = "some query"; const result = await service.geocode(query, import__251.GeocodeType.SEARCH); expect(result).toEqual(expectedResult); expect(service._pelias.geocode).toHaveBeenCalledWith( query, import__251.GeocodeType.SEARCH ); }); it("credit returns expected value", async function() { const service = new import__251.IonGeocoderService({ scene: scene2 }); expect(service.credit).toBeUndefined(); }); }); // packages/engine/Specs/Core/IonResourceSpec.js var import__252 = __toESM(require_Cesium(), 1); describe("Core/IonResource", function() { const assetId = 123890213; const endpoint = { type: "3DTILES", url: `https://assets.cesium.com/${assetId}/tileset.json`, accessToken: "not_really_a_refresh_token", attributions: [] }; it("constructs with expected values", function() { spyOn(import__252.Resource, "call").and.callThrough(); const endpointResource = import__252.IonResource._createEndpointResource(assetId); const resource = new import__252.IonResource(endpoint, endpointResource); expect(resource).toBeInstanceOf(import__252.Resource); expect(resource._ionEndpoint).toEqual(endpoint); expect(import__252.Resource.call).toHaveBeenCalledWith(resource, { url: endpoint.url, retryCallback: resource.retryCallback, retryAttempts: 1 }); }); it("clone works", function() { const endpointResource = import__252.IonResource._createEndpointResource(assetId); const resource = new import__252.IonResource(endpoint, endpointResource); const cloned = resource.clone(); expect(cloned).not.toBe(resource); expect(cloned._ionRoot).toBe(resource); cloned._ionRoot = void 0; expect(cloned.retryCallback).toBe(resource.retryCallback); expect(cloned.headers.Authorization).toBe(resource.headers.Authorization); expect(cloned).toEqual(resource); }); it("create creates the expected resource", function() { const endpointResource = import__252.IonResource._createEndpointResource(assetId); const resource = new import__252.IonResource(endpoint, endpointResource); expect(resource.getUrlComponent()).toEqual(endpoint.url); expect(resource._ionEndpoint).toBe(endpoint); expect(resource._ionEndpointResource).toEqual(endpointResource); expect(resource.retryCallback).toBeDefined(); expect(resource.retryAttempts).toBe(1); }); it("fromAssetId calls constructor for non-external endpoint with expected parameters", function() { const tilesAssetId = 123890213; const tilesEndpoint = { type: "3DTILES", url: `https://assets.cesium.com/${tilesAssetId}/tileset.json`, accessToken: "not_really_a_refresh_token", attributions: [] }; const options = {}; const resourceEndpoint = import__252.IonResource._createEndpointResource( tilesAssetId, options ); spyOn(import__252.IonResource, "_createEndpointResource").and.returnValue( resourceEndpoint ); spyOn(resourceEndpoint, "fetchJson").and.returnValue( Promise.resolve(tilesEndpoint) ); return import__252.IonResource.fromAssetId(tilesAssetId, options).then(function(resource) { expect(import__252.IonResource._createEndpointResource).toHaveBeenCalledWith( tilesAssetId, options ); expect(resourceEndpoint.fetchJson).toHaveBeenCalled(); expect(resource._ionEndpointResource).toEqual(resourceEndpoint); expect(resource._ionEndpoint).toEqual(tilesEndpoint); }); }); function testNonImageryExternalResource(externalEndpoint) { const resourceEndpoint = import__252.IonResource._createEndpointResource(123890213); spyOn(import__252.IonResource, "_createEndpointResource").and.returnValue( resourceEndpoint ); spyOn(resourceEndpoint, "fetchJson").and.returnValue( Promise.resolve(externalEndpoint) ); return import__252.IonResource.fromAssetId(123890213).then(function(resource) { expect(resource.url).toEqual(externalEndpoint.options.url); expect(resource.headers.Authorization).toBeUndefined(); expect(resource.retryCallback).toBeUndefined(); }); } it("fromAssetId returns basic Resource for external 3D tilesets", function() { return testNonImageryExternalResource({ type: "3DTILES", externalType: "3DTILES", options: { url: "http://test.invalid/tileset.json" }, attributions: [] }); }); it("fromAssetId returns basic Resource for external 3D tilesets", function() { return testNonImageryExternalResource({ type: "TERRAIN", externalType: "STK_TERRAIN_SERVER", options: { url: "http://test.invalid/world" }, attributions: [] }); }); it("fromAssetId rejects for external imagery", function() { return testNonImageryExternalResource({ type: "IMAGERY", externalType: "URL_TEMPLATE", url: "http://test.invalid/world", attributions: [] }).then(fail).catch(function(e) { expect(e).toBeInstanceOf(import__252.RuntimeError); }); }); it("createEndpointResource creates expected values with default parameters", function() { const assetId2 = 2348234; const resource = import__252.IonResource._createEndpointResource(assetId2); expect(resource.url).toBe( `${import__252.Ion.defaultServer.url}v1/assets/${assetId2}/endpoint?access_token=${import__252.Ion.defaultAccessToken}` ); }); it("createEndpointResource creates expected values with overridden options", function() { const serverUrl = "https://api.cesium.test/"; const accessToken = "not_a_token"; const assetId2 = 2348234; const resource = import__252.IonResource._createEndpointResource(assetId2, { server: serverUrl, accessToken }); expect(resource.url).toBe( `${serverUrl}v1/assets/${assetId2}/endpoint?access_token=${accessToken}` ); }); it("createEndpointResource creates expected values with overridden defaults", function() { const defaultServer = import__252.Ion.defaultServer; const defaultAccessToken = import__252.Ion.defaultAccessToken; import__252.Ion.defaultServer = new import__252.Resource({ url: "https://api.cesium.test/" }); import__252.Ion.defaultAccessToken = "not_a_token"; const assetId2 = 2348234; const resource = import__252.IonResource._createEndpointResource(assetId2); expect(resource.url).toBe( `${import__252.Ion.defaultServer.url}v1/assets/${assetId2}/endpoint?access_token=${import__252.Ion.defaultAccessToken}` ); import__252.Ion.defaultServer = defaultServer; import__252.Ion.defaultAccessToken = defaultAccessToken; }); it("Calls base _makeRequest with expected options when resource no Authorization header is defined", function() { const originalOptions = {}; const expectedOptions = { headers: jasmine.objectContaining({ Authorization: `Bearer ${endpoint.accessToken}` }) }; const _makeRequest = spyOn(import__252.Resource.prototype, "_makeRequest"); const endpointResource = import__252.IonResource._createEndpointResource(assetId); const resource = new import__252.IonResource(endpoint, endpointResource); resource._makeRequest(originalOptions); expect(_makeRequest).toHaveBeenCalledWith(expectedOptions); }); it("Calls base _makeRequest with expected options when resource Authorization header is already defined", function() { const originalOptions = {}; const expectedOptions = { headers: jasmine.objectContaining({ Authorization: `Bearer ${endpoint.accessToken}` }) }; const _makeRequest = spyOn(import__252.Resource.prototype, "_makeRequest"); const endpointResource = import__252.IonResource._createEndpointResource(assetId); const resource = new import__252.IonResource(endpoint, endpointResource); resource.headers.Authorization = "Not valid"; resource._makeRequest(originalOptions); expect(_makeRequest).toHaveBeenCalledWith(expectedOptions); }); it("Calls base _makeRequest including X-Cesium-* headers", function() { const originalOptions = {}; const expectedOptions = { headers: jasmine.objectContaining({ "X-Cesium-Client": "CesiumJS", "X-Cesium-Client-Version": jasmine.stringContaining("1.") }) }; const _makeRequest = spyOn(import__252.Resource.prototype, "_makeRequest"); const endpointResource = import__252.IonResource._createEndpointResource(assetId); const resource = new import__252.IonResource(endpoint, endpointResource); resource._makeRequest(originalOptions); expect(_makeRequest).toHaveBeenCalledWith(expectedOptions); }); it("Calls base _makeRequest with no changes for external assets", function() { const externalEndpoint = { type: "3DTILES", externalType: "3DTILES", options: { url: "http://test.invalid/tileset.json" }, attributions: [] }; const options = {}; const _makeRequest = spyOn(import__252.Resource.prototype, "_makeRequest"); const endpointResource = import__252.IonResource._createEndpointResource(assetId); const resource = new import__252.IonResource(externalEndpoint, endpointResource); resource._makeRequest(options); expect(_makeRequest.calls.argsFor(0)[0]).toBe(options); }); it("Calls base _makeRequest with no changes for ion assets with external urls", function() { const originalOptions = {}; const expectedOptions = {}; const _makeRequest = spyOn(import__252.Resource.prototype, "_makeRequest"); const endpointResource = import__252.IonResource._createEndpointResource(assetId); const resource = new import__252.IonResource(endpoint, endpointResource); resource.url = "http://test.invalid"; resource._makeRequest(originalOptions); expect(_makeRequest).toHaveBeenCalledWith(expectedOptions); }); it("Calls base fetchImage with preferBlob for ion assets", function() { const fetchImage = spyOn(import__252.Resource.prototype, "fetchImage"); const endpointResource = import__252.IonResource._createEndpointResource(assetId); const resource = new import__252.IonResource(endpoint, endpointResource); resource.fetchImage(); expect(fetchImage).toHaveBeenCalledWith({ preferBlob: true }); }); it("Calls base fetchImage with no changes for external assets", function() { const externalEndpoint = { type: "3DTILES", externalType: "3DTILES", options: { url: "http://test.invalid/tileset.json" }, attributions: [] }; const fetchImage = spyOn(import__252.Resource.prototype, "fetchImage"); const endpointResource = import__252.IonResource._createEndpointResource(assetId); const resource = new import__252.IonResource(externalEndpoint, endpointResource); resource.fetchImage({ preferBlob: false }); expect(fetchImage).toHaveBeenCalledWith({ preferBlob: false }); }); describe("retryCallback", function() { let endpointResource; let resource; let retryCallback; beforeEach(function() { endpointResource = new import__252.Resource({ url: "https://api.test.invalid", access_token: "not_the_token" }); resource = new import__252.IonResource(endpoint, endpointResource); retryCallback = resource.retryCallback; }); it("returns false when error is undefined", function() { return retryCallback(resource, void 0).then(function(result) { expect(result).toBe(false); }); }); it("returns false when error is non-401", function() { const error = new import__252.RequestErrorEvent(404); return retryCallback(resource, error).then(function(result) { expect(result).toBe(false); }); }); it("returns false when error is event with non-Image target", function() { const event = { target: {} }; return retryCallback(resource, event).then(function(result) { expect(result).toBe(false); }); }); function testCallback(resource2, event) { const deferred = (0, import__252.defer)(); spyOn(endpointResource, "fetchJson").and.returnValue(deferred.promise); const newEndpoint = { type: "3DTILES", url: `https://assets.cesium.com/${assetId}`, accessToken: "not_not_really_a_refresh_token" }; const promise = retryCallback(resource2, event); const resultPromise = promise.then(function(result) { expect(result).toBe(true); expect(resource2._ionEndpoint).toBe(newEndpoint); }); expect(endpointResource.fetchJson).toHaveBeenCalledWith(); const promise2 = retryCallback(resource2, event); expect(promise._pendingPromise).toBe(promise2._pendingPromise); deferred.resolve(newEndpoint); return resultPromise; } it("works when error is a 401", function() { const error = new import__252.RequestErrorEvent(401); return testCallback(resource, error); }); it("works when error is event with Image target", function() { const event = { target: new Image() }; return testCallback(resource, event); }); it("works with derived resource and sets root access_token", function() { const derived = resource.getDerivedResource("1"); const error = new import__252.RequestErrorEvent(401); return testCallback(derived, error).then(function() { expect(derived._ionEndpoint).toBe(resource._ionEndpoint); expect(derived.headers.Authorization).toEqual( resource.headers.Authorization ); }); }); }); }); // packages/engine/Specs/Core/JulianDateSpec.js var import__253 = __toESM(require_Cesium(), 1); var import__254 = __toESM(require_Cesium(), 1); describe("Core/JulianDate", function() { it("Construct a default date", function() { const defaultDate = new import__253.JulianDate(); expect(defaultDate.dayNumber).toEqual(0); expect(defaultDate.secondsOfDay).toEqual(10); }); it("Construct a date with fractional day", function() { const julianDate = new import__253.JulianDate(244825775e-2, 0, import__253.TimeStandard.UTC); const expected = new import__253.JulianDate(2448257, 64826, import__253.TimeStandard.TAI); expect(julianDate).toEqual(expected); }); it("Construct a date at the current time", function() { const defaultDate = import__253.JulianDate.now(); const dateNow = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date()); expect(defaultDate.equalsEpsilon(dateNow, 5)).toEqual(true); }); it("Construct a date from basic TAI components", function() { const dayNumber = 12; const seconds = 12.5; const timeStandard = import__253.TimeStandard.TAI; const julianDate = new import__253.JulianDate(dayNumber, seconds, timeStandard); expect(julianDate.dayNumber).toEqual(dayNumber); expect(julianDate.secondsOfDay).toEqual(seconds); }); it("clone works without result parameter", function() { const julianDate = import__253.JulianDate.now(); const returnedResult = julianDate.clone(); expect(returnedResult).toEqual(julianDate); expect(returnedResult).not.toBe(julianDate); }); it("clone works with result parameter", function() { const julianDate = new import__253.JulianDate(1, 2); const result = import__253.JulianDate.now(); const returnedResult = julianDate.clone(result); expect(returnedResult).toBe(result); expect(returnedResult).not.toBe(julianDate); expect(returnedResult).toEqual(julianDate); }); it("Construct a date from UTC components just before a leap second", function() { const expected = new import__253.JulianDate(2443874, 43216, import__253.TimeStandard.TAI); const julianDate = new import__253.JulianDate(2443874, 43199, import__253.TimeStandard.UTC); expect(julianDate.dayNumber).toEqual(expected.dayNumber); expect(julianDate.secondsOfDay).toEqual(expected.secondsOfDay); }); it("Construct a date from UTC components equivalent to a LeapSecond table entry", function() { const expected = new import__253.JulianDate(2443874, 43218, import__253.TimeStandard.TAI); const julianDate = new import__253.JulianDate(2443874, 43200, import__253.TimeStandard.UTC); expect(julianDate.dayNumber).toEqual(expected.dayNumber); expect(julianDate.secondsOfDay).toEqual(expected.secondsOfDay); }); it("Construct a date from UTC components just after a leap second", function() { const expected = new import__253.JulianDate(2443874, 43219, import__253.TimeStandard.TAI); const julianDate = new import__253.JulianDate(2443874, 43201, import__253.TimeStandard.UTC); expect(julianDate.dayNumber).toEqual(expected.dayNumber); expect(julianDate.secondsOfDay).toEqual(expected.secondsOfDay); }); it("Construct a date from basic components with more seconds than a day", function() { const dayNumber = 12; const seconds = 86401; const timeStandard = import__253.TimeStandard.TAI; const julianDate = new import__253.JulianDate(dayNumber, seconds, timeStandard); expect(julianDate.dayNumber).toEqual(13); expect(julianDate.secondsOfDay).toEqual(1); }); it("Construct a date from basic components with negative seconds in a day", function() { const dayNumber = 12; const seconds = -1; const timeStandard = import__253.TimeStandard.TAI; const julianDate = new import__253.JulianDate(dayNumber, seconds, timeStandard); expect(julianDate.dayNumber).toEqual(11); expect(julianDate.secondsOfDay).toEqual(86399); }); it("Construct a date from basic components with partial day and seconds in a day", function() { const dayNumber = 12.5; const seconds = -1; const timeStandard = import__253.TimeStandard.TAI; const julianDate = new import__253.JulianDate(dayNumber, seconds, timeStandard); expect(julianDate.dayNumber).toEqual(12); expect(julianDate.secondsOfDay).toEqual(43199); }); it("Construct a date with default time standard", function() { const dayNumber = 12; const seconds = 12.5; const julianDateDefault = new import__253.JulianDate(dayNumber, seconds); const julianDateUtc = new import__253.JulianDate(dayNumber, seconds, import__253.TimeStandard.UTC); expect(julianDateDefault).toEqual(julianDateUtc); }); it("Construct a date from a JavaScript Date (1)", function() { const date = /* @__PURE__ */ new Date("January 1, 1991 06:00:00 UTC"); const julianDate = import__253.JulianDate.fromDate(date); expect(julianDate.dayNumber).toEqual(2448257); expect(julianDate.secondsOfDay).toEqual(64826); }); it("Construct a date from a JavaScript Date (2)", function() { const date = /* @__PURE__ */ new Date("July 4, 2011 12:00:00 UTC"); const julianDate = import__253.JulianDate.fromDate(date); expect(julianDate.dayNumber).toEqual(2455747); expect(julianDate.secondsOfDay).toEqual(34); }); it("Construct a date from a JavaScript Date (3)", function() { const date = /* @__PURE__ */ new Date("December 31, 2021 18:00:00 UTC"); const julianDate = import__253.JulianDate.fromDate(date); expect(julianDate.dayNumber).toEqual(2459580); expect(julianDate.secondsOfDay).toEqual(21637); }); it("Construct a date from a JavaScript Date (4)", function() { const jsDate = /* @__PURE__ */ new Date("September 1, 2011 12:00:00 UTC"); const julianDate = import__253.JulianDate.fromDate(jsDate); expect(julianDate.dayNumber).toEqual(2455806); expect(julianDate.secondsOfDay).toEqual(34); }); it("Construct a date from a JavaScript Date (5)", function() { const jsDate = /* @__PURE__ */ new Date("11/17/2039 12:00:00 AM UTC"); const julianDate = import__253.JulianDate.fromDate(jsDate); expect(julianDate.dayNumber).toEqual(2466109); expect(julianDate.secondsOfDay).toEqual(43237); }); it("Fail to construct from an undefined JavaScript Date", function() { expect(function() { return import__253.JulianDate.fromDate(void 0); }).toThrowDeveloperError(); }); it("Fail to construct from an invalid JavaScript Date", function() { expect(function() { return import__253.JulianDate.fromDate(new Date(Date.parse("garbage"))); }).toThrowDeveloperError(); }); it("Construct from ISO8601 calendar date, basic format", function() { const expectedDate = import__253.JulianDate.fromDate(new Date(Date.UTC(2009, 7, 1))); const computedDate = import__253.JulianDate.fromIso8601("20090801"); expect(computedDate).toEqual(expectedDate); }); it("Construct from ISO8601 calendar date, extended format", function() { const expectedDate = import__253.JulianDate.fromDate(new Date(Date.UTC(2009, 7, 1))); const computedDate = import__253.JulianDate.fromIso8601("2009-08-01"); expect(computedDate).toEqual(expectedDate); }); it("Construct from ISO8601 calendar date on Feb 29th, basic format", function() { const expectedDate = import__253.JulianDate.fromDate(new Date(Date.UTC(2e3, 1, 29))); const computedDate = import__253.JulianDate.fromIso8601("20000229"); expect(computedDate).toEqual(expectedDate); }); it("Construct from ISO8601 calendar date on Feb 29th, extended format", function() { const expectedDate = import__253.JulianDate.fromDate(new Date(Date.UTC(2e3, 1, 29))); const computedDate = import__253.JulianDate.fromIso8601("2000-02-29"); expect(computedDate).toEqual(expectedDate); }); it("Construct from an ISO8601 ordinal date, basic format", function() { const expectedDate = import__253.JulianDate.fromDate(new Date(Date.UTC(1985, 3, 12))); const computedDate = import__253.JulianDate.fromIso8601("1985102"); expect(computedDate).toEqual(expectedDate); }); it("Construct from an ISO8601 ordinal date, extended format", function() { const expectedDate = import__253.JulianDate.fromDate(new Date(Date.UTC(1985, 3, 12))); const computedDate = import__253.JulianDate.fromIso8601("1985-102"); expect(computedDate).toEqual(expectedDate); }); it("Construct an ISO8601 ordinal date on a leap year", function() { const expectedDate = import__253.JulianDate.fromDate(new Date(Date.UTC(2e3, 11, 31))); const computedDate = import__253.JulianDate.fromIso8601("2000-366"); expect(computedDate).toEqual(expectedDate); }); it("Construct from an ISO8601 week date, basic format", function() { const expectedDate = import__253.JulianDate.fromDate(new Date(Date.UTC(1985, 3, 12))); const computedDate = import__253.JulianDate.fromIso8601("1985W155"); expect(computedDate).toEqual(expectedDate); }); it("Construct from an ISO8601 week date, extended format", function() { const expectedDate = import__253.JulianDate.fromDate(new Date(Date.UTC(2008, 8, 27))); const computedDate = import__253.JulianDate.fromIso8601("2008-W39-6"); expect(computedDate).toEqual(expectedDate); }); it("Construct from an ISO8601 calendar week date, basic format", function() { const expectedDate = import__253.JulianDate.fromDate(new Date(Date.UTC(1985, 3, 7))); const computedDate = import__253.JulianDate.fromIso8601("1985W15"); expect(computedDate).toEqual(expectedDate); }); it("Construct from an ISO8601 calendar week date, extended format", function() { const expectedDate = import__253.JulianDate.fromDate(new Date(Date.UTC(2008, 8, 21))); const computedDate = import__253.JulianDate.fromIso8601("2008-W39"); expect(computedDate).toEqual(expectedDate); }); it("Construct from an ISO8601 calendar month, basic format", function() { const expectedDate = import__253.JulianDate.fromDate(new Date(Date.UTC(1985, 3, 1))); const computedDate = import__253.JulianDate.fromIso8601("1985-04"); expect(computedDate).toEqual(expectedDate); }); it("Construct from ISO8601 UTC calendar date and time, basic format", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 7, 1, 12, 30, 25)) ); const computedDate = import__253.JulianDate.fromIso8601("20090801T123025Z"); expect(computedDate).toEqual(expectedDate); }); it("Construct from ISO8601 UTC calendar date and time, extended format", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 7, 1, 12, 30, 25)) ); const computedDate = import__253.JulianDate.fromIso8601("2009-08-01T12:30:25Z"); expect(computedDate).toEqual(expectedDate); }); it("Construct from ISO8601 UTC calendar date and time fractional seconds, basic format", function() { const expectedDate = new import__253.JulianDate( 2455045, 1825.5125423, import__253.TimeStandard.UTC ); const computedDate = import__253.JulianDate.fromIso8601("20090801T123025.5125423Z"); expect(computedDate).toEqual(expectedDate); }); it("Construct from ISO8601 UTC calendar date and time fractional seconds, extended format", function() { const expectedDate = new import__253.JulianDate( 2455045, 1825.5125423, import__253.TimeStandard.UTC ); const computedDate = import__253.JulianDate.fromIso8601("2009-08-01T12:30:25.5125423Z"); expect(computedDate).toEqual(expectedDate); }); it('Construct from ISO8601 UTC calendar date and time fractional seconds, basic format, "," instead of "."', function() { const expectedDate = new import__253.JulianDate( 2455045, 1825.5125423, import__253.TimeStandard.UTC ); const computedDate = import__253.JulianDate.fromIso8601("20090801T123025,5125423Z"); expect(computedDate).toEqual(expectedDate); }); it('Construct from ISO8601 UTC calendar date and time fractional seconds, extended format, "," instead of "."', function() { const expectedDate = new import__253.JulianDate( 2455045, 1825.5125423, import__253.TimeStandard.UTC ); const computedDate = import__253.JulianDate.fromIso8601("2009-08-01T12:30:25,5125423Z"); expect(computedDate).toEqual(expectedDate); }); it("Construct from ISO8601 UTC calendar date and time no seconds, basic format", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 7, 1, 12, 30, 0)) ); const computedDate = import__253.JulianDate.fromIso8601("20090801T1230Z"); expect(computedDate).toEqual(expectedDate); }); it("Construct from ISO8601 UTC calendar date and time no seconds, extended format", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 7, 1, 12, 30, 0)) ); const computedDate = import__253.JulianDate.fromIso8601("2009-08-01T12:30Z"); expect(computedDate).toEqual(expectedDate); }); it("Construct from ISO8601 UTC calendar date and time fractional minutes, basic format", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 7, 1, 12, 30, 30)) ); const computedDate = import__253.JulianDate.fromIso8601("20090801T1230.5Z"); expect(computedDate).toEqual(expectedDate); }); it("Construct from ISO8601 UTC calendar date and time fractional minutes, extended format", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 7, 1, 12, 30, 30)) ); const computedDate = import__253.JulianDate.fromIso8601("2009-08-01T12:30.5Z"); expect(computedDate).toEqual(expectedDate); }); it('Construct from ISO8601 UTC calendar date and time fractional minutes, basic format, "," instead of "."', function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 7, 1, 12, 30, 30)) ); const computedDate = import__253.JulianDate.fromIso8601("20090801T1230,5Z"); expect(computedDate).toEqual(expectedDate); }); it('Construct from ISO8601 UTC calendar date and time fractional minutes, extended format, "," instead of "."', function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 7, 1, 12, 30, 30)) ); const computedDate = import__253.JulianDate.fromIso8601("2009-08-01T12:30,5Z"); expect(computedDate).toEqual(expectedDate); }); it("Construct from ISO8601 UTC calendar date and time no minutes/seconds, basic format", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 7, 1, 12, 0, 0)) ); const computedDate = import__253.JulianDate.fromIso8601("20090801T12Z"); expect(computedDate).toEqual(expectedDate); }); it("Construct from ISO8601 UTC calendar date and time no minutes/seconds, extended format", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 7, 1, 12, 0, 0)) ); const computedDate = import__253.JulianDate.fromIso8601("2009-08-01T12Z"); expect(computedDate).toEqual(expectedDate); }); it("Construct from ISO8601 UTC calendar date and time fractional hours, basic format", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 7, 1, 12, 30, 0)) ); const computedDate = import__253.JulianDate.fromIso8601("20090801T12.5Z"); expect(computedDate).toEqual(expectedDate); }); it("Construct from ISO8601 UTC calendar date and time fractional hours, extended format", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 7, 1, 12, 30, 0)) ); const computedDate = import__253.JulianDate.fromIso8601("2009-08-01T12.5Z"); expect(computedDate).toEqual(expectedDate); }); it('Construct from ISO8601 UTC calendar date and time fractional hours, basic format, "," instead of "."', function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 7, 1, 12, 30, 0)) ); const computedDate = import__253.JulianDate.fromIso8601("20090801T12,5Z"); expect(computedDate).toEqual(expectedDate); }); it('Construct from ISO8601 UTC calendar date and time fractional hours, extended format, "," instead of "."', function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 7, 1, 12, 30, 0)) ); const computedDate = import__253.JulianDate.fromIso8601("2009-08-01T12,5Z"); expect(computedDate).toEqual(expectedDate); }); it("Construct from an ISO8601 UTC calendar date and time on a leap second", function() { const computedDate = import__253.JulianDate.fromIso8601("2008-12-31T23:59:60Z"); const expectedDate = new import__253.JulianDate(2454832, 43233, import__253.TimeStandard.TAI); expect(computedDate).toEqual(expectedDate); }); it("Construct from an ISO8601 UTC calendar date and time within a leap second", function() { const computedDate = import__253.JulianDate.fromIso8601( "2008-12-31T23:59:60.123456789Z" ); const expectedDate = new import__253.JulianDate( 2454832, 43233.123456789, import__253.TimeStandard.TAI ); expect(computedDate).toEqual(expectedDate); }); it("Construct from an ISO8601 local calendar date and time on a leap second 1 hour behind UTC", function() { const computedDate = import__253.JulianDate.fromIso8601("2008-12-31T22:59:60-01"); const expectedDate = new import__253.JulianDate(2454832, 43233, import__253.TimeStandard.TAI); expect(computedDate).toEqual(expectedDate); }); it("Construct from an ISO8601 local calendar date and time on a leap second 1 hour ahead of UTC", function() { const computedDate = import__253.JulianDate.fromIso8601("2009-01-01T00:59:60+01"); const expectedDate = new import__253.JulianDate(2454832, 43233, import__253.TimeStandard.TAI); expect(computedDate).toEqual(expectedDate); }); it("Construct from an ISO8601 calendar date and time using 24:00:00 midnight notation", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 7, 2, 0, 0, 0)) ); const computedDate = import__253.JulianDate.fromIso8601("2009-08-01T24:00:00Z"); expect(computedDate).toEqual(expectedDate); }); it("Construct from an ISO8601 local calendar date with UTC offset that crosses into previous month", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(1985, 2, 31, 23, 59, 0)) ); const computedDate = import__253.JulianDate.fromIso8601("1985-04-01T00:59:00+01"); expect(computedDate).toEqual(expectedDate); }); it("Construct from an ISO8601 local calendar date with UTC offset that crosses into next month", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(1985, 3, 1, 0, 59, 0)) ); const computedDate = import__253.JulianDate.fromIso8601("1985-03-31T23:59:00-01"); expect(computedDate).toEqual(expectedDate); }); it("Construct from an ISO8601 local calendar date with UTC offset that crosses into next year", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2008, 11, 31, 23, 0, 0)) ); const julianDate = import__253.JulianDate.fromIso8601("2009-01-01T01:00:00+02"); expect(julianDate).toEqual(expectedDate); }); it("Construct from an ISO8601 local calendar date with UTC offset that crosses into previous year", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 0, 1, 1, 0, 0)) ); const julianDate = import__253.JulianDate.fromIso8601("2008-12-31T23:00:00-02"); expect(julianDate).toEqual(expectedDate); }); it("Construct from an ISO8601 local calendar date with UTC offset", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2008, 10, 10, 12, 0, 0)) ); const julianDate = import__253.JulianDate.fromIso8601("2008-11-10T14:00:00+02"); expect(julianDate).toEqual(expectedDate); }); it("Construct from an ISO8601 local calendar date with UTC offset in extended format", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2008, 10, 10, 11, 30, 0)) ); const julianDate = import__253.JulianDate.fromIso8601("2008-11-10T14:00:00+02:30"); expect(julianDate).toEqual(expectedDate); }); it("Construct from an ISO8601 local calendar date with zero UTC offset in extended format", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2008, 10, 10, 14, 0, 0)) ); const julianDate = import__253.JulianDate.fromIso8601("2008-11-10T14:00:00+00:00"); expect(julianDate).toEqual(expectedDate); }); it("Construct from an ISO8601 local calendar date with zero UTC offset in extended format", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2008, 10, 10, 14, 0, 0)) ); const julianDate = import__253.JulianDate.fromIso8601("2008-11-10T14:00:00+00"); expect(julianDate).toEqual(expectedDate); }); it("Construct from ISO8601 local calendar date and time with no seconds and UTC offset in basic format", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 7, 1, 12, 30, 0)) ); const computedDate = import__253.JulianDate.fromIso8601("20090801T0730-0500"); expect(computedDate).toEqual(expectedDate); }); it("Construct from ISO8601 local calendar date and time with no seconds and UTC offset in extended format", function() { const expectedDate = import__253.JulianDate.fromDate( new Date(Date.UTC(2009, 7, 1, 12, 30, 0)) ); const computedDate = import__253.JulianDate.fromIso8601("2009-08-01T07:30-05:00"); expect(computedDate).toEqual(expectedDate); }); it("Fails to construct an ISO8601 ordinal date with day less than 1", function() { expect(function() { return import__253.JulianDate.fromIso8601("2009-000"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 ordinal date with day more than 365 on non-leap year", function() { expect(function() { return import__253.JulianDate.fromIso8601("2001-366"); }).toThrowDeveloperError(); }); it("Fails to construct ISO8601 UTC calendar date of invalid YYMMDD format", function() { expect(function() { return import__253.JulianDate.fromIso8601("200905"); }).toThrowDeveloperError(); }); it("Fails to construct a complete ISO8601 date missing T delimeter", function() { expect(function() { return import__253.JulianDate.fromIso8601("2009-08-0112:30.5Z"); }).toThrowDeveloperError(); }); it("Fails to construct a complete ISO8601 date with delimeter other than T", function() { expect(function() { return import__253.JulianDate.fromIso8601("2009-08-01Q12:30.5Z"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 date from undefined", function() { expect(function() { return import__253.JulianDate.fromIso8601(void 0); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 from complete garbage", function() { expect(function() { return import__253.JulianDate.fromIso8601("this is not a date"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 date from a valid ISO8601 interval", function() { expect(function() { return import__253.JulianDate.fromIso8601( "2007-03-01T13:00:00Z/2008-05-11T15:30:00Z" ); }).toThrowDeveloperError(); }); it("Fails to construct from an ISO8601 with too many year digits", function() { expect(function() { return import__253.JulianDate.fromIso8601("20091-05-19"); }).toThrowDeveloperError(); }); it("Fails to construct from an ISO8601 with too many month digits", function() { expect(function() { return import__253.JulianDate.fromIso8601("2009-100-19"); }).toThrowDeveloperError(); }); it("Fails to construct from an ISO8601 with more than 12 months", function() { expect(function() { return import__253.JulianDate.fromIso8601("2009-13-19"); }).toThrowDeveloperError(); }); it("Fails to construct from an ISO8601 with less than 1 months", function() { expect(function() { return import__253.JulianDate.fromIso8601("2009-00-19"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 January date with more than 31 days", function() { expect(function() { return import__253.JulianDate.fromIso8601("2009-01-32"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 Febuary date with more than 28 days", function() { expect(function() { return import__253.JulianDate.fromIso8601("2009-02-29"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 Febuary leap year date with more than 29 days", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-02-30"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 March date with more than 29 days", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-03-32"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 April date with more than 29 days", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-04-31"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 May date with more than 29 days", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-05-32"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 June date with more than 29 days", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-06-31"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 July date with more than 29 days", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-07-32"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 August date with more than 29 days", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-08-32"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 September date with more than 29 days", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-09-31"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 October date with more than 29 days", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-10-32"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 November date with more than 29 days", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-11-31"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 December date with more than 29 days", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-12-32"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 date with more than 24 hours (extra seconds)", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-12-15T24:00:01"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 date with more than 24 hours (extra minutes)", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-12-15T24:01:00"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 date with more than 59 minutes", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-12-15T12:60"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 date with more than 60 seconds", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-12-15T12:59:61"); }).toThrowDeveloperError(); }); it("Fails to construct from an ISO8601 with less than 1 day", function() { expect(function() { return import__253.JulianDate.fromIso8601("2009-01-00"); }).toThrowDeveloperError(); }); it("Fails to construct from an ISO8601 with too many dashes", function() { expect(function() { return import__253.JulianDate.fromIso8601("2009--01-01"); }).toThrowDeveloperError(); }); it("Fails to construct from an ISO8601 with garbage offset", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-12-15T12:59:23ZZ+-050708::1234"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 date with more than one decimal place", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-12-15T12:59:22..2"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 calendar date mixing basic and extended format", function() { expect(function() { return import__253.JulianDate.fromIso8601("200108-01"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 calendar date mixing basic and extended format", function() { expect(function() { return import__253.JulianDate.fromIso8601("2001-0801"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 calendar week mixing basic and extended format", function() { expect(function() { return import__253.JulianDate.fromIso8601("2008-W396"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 calendar week mixing basic and extended format", function() { expect(function() { return import__253.JulianDate.fromIso8601("2008W39-6"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 date with trailing -", function() { expect(function() { return import__253.JulianDate.fromIso8601("2001-"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 time mixing basic and extended format", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-12-15T22:0100"); }).toThrowDeveloperError(); }); it("Fails to construct an ISO8601 time mixing basic and extended format", function() { expect(function() { return import__253.JulianDate.fromIso8601("2000-12-15T2201:00"); }).toThrowDeveloperError(); }); it("toDate works when using TAI", function() { const julianDateTai = new import__253.JulianDate(2455927157772e-6, 0, import__253.TimeStandard.UTC); const javascriptDate = import__253.JulianDate.toDate(julianDateTai); expect(javascriptDate.getUTCFullYear()).toEqual(2011); expect(javascriptDate.getUTCMonth()).toEqual(11); expect(javascriptDate.getUTCDate()).toEqual(31); expect(javascriptDate.getUTCHours()).toEqual(15); expect(javascriptDate.getUTCMinutes()).toEqual(47); expect(javascriptDate.getUTCSeconds()).toEqual(11); expect(javascriptDate.getUTCMilliseconds()).toEqualEpsilon(500, 10); }); it("toDate works a second before a leap second", function() { const expectedDate = /* @__PURE__ */ new Date("6/30/1997 11:59:59 PM UTC"); const date = import__253.JulianDate.toDate( new import__253.JulianDate(2450630, 43229, import__253.TimeStandard.TAI) ); expect(date).toEqual(expectedDate); }); it("toDate works on a leap second", function() { const expectedDate = /* @__PURE__ */ new Date("6/30/1997 11:59:59 PM UTC"); const date = import__253.JulianDate.toDate( new import__253.JulianDate(2450630, 43230, import__253.TimeStandard.TAI) ); expect(date).toEqual(expectedDate); }); it("toDate works a second after a leap second", function() { const expectedDate = /* @__PURE__ */ new Date("7/1/1997 12:00:00 AM UTC"); const date = import__253.JulianDate.toDate( new import__253.JulianDate(2450630, 43231, import__253.TimeStandard.TAI) ); expect(date).toEqual(expectedDate); }); it("toDate works on date before any leap seconds", function() { const expectedDate = /* @__PURE__ */ new Date("09/10/1968 12:00:00 AM UTC"); const date = import__253.JulianDate.toDate( new import__253.JulianDate(2440109, 43210, import__253.TimeStandard.TAI) ); expect(date).toEqual(expectedDate); }); it("toDate works on date later than all leap seconds", function() { const expectedDate = /* @__PURE__ */ new Date("11/17/2039 12:00:00 AM UTC"); const date = import__253.JulianDate.toDate( new import__253.JulianDate(2466109, 43237, import__253.TimeStandard.TAI) ); expect(date).toEqual(expectedDate); }); it("toIso8601 works a second before a leap second", function() { const expectedDate = "1997-06-30T23:59:59Z"; const date = import__253.JulianDate.toIso8601(import__253.JulianDate.fromIso8601(expectedDate)); expect(date).toEqual(expectedDate); }); it("toIso8601 works on a leap second", function() { const expectedDate = "1997-06-30T23:59:60Z"; const date = import__253.JulianDate.toIso8601(import__253.JulianDate.fromIso8601(expectedDate)); expect(date).toEqual(expectedDate); }); it("toIso8601 works a second after a leap second", function() { const expectedDate = "1997-07-01T00:00:00Z"; const date = import__253.JulianDate.toIso8601(import__253.JulianDate.fromIso8601(expectedDate)); expect(date).toEqual(expectedDate); }); it("toIso8601 works on date before any leap seconds", function() { const expectedDate = "1968-09-10T00:00:00Z"; const date = import__253.JulianDate.toIso8601(import__253.JulianDate.fromIso8601(expectedDate)); expect(date).toEqual(expectedDate); }); it("toIso8601 works on date later than all leap seconds", function() { const expectedDate = "2031-11-17T00:00:00Z"; const date = import__253.JulianDate.toIso8601(import__253.JulianDate.fromIso8601(expectedDate)); expect(date).toEqual(expectedDate); }); it("toIso8601 works without precision", function() { const expectedDate = "0950-01-02T03:04:05.5Z"; const date = import__253.JulianDate.toIso8601(import__253.JulianDate.fromIso8601(expectedDate)); expect(date).toEqual(expectedDate); }); it("toIso8601 pads zeros for year less than four digits or time components less than two digits", function() { const expectedDate = "0950-01-02T03:04:05.005Z"; const date = import__253.JulianDate.toIso8601(import__253.JulianDate.fromIso8601(expectedDate), 3); expect(date).toEqual(expectedDate); }); it("toIso8601 does not show milliseconds if they are 0", function() { const expectedDate = "0950-01-02T03:04:05Z"; const date = import__253.JulianDate.toIso8601(import__253.JulianDate.fromIso8601(expectedDate)); expect(date).toEqual(expectedDate); }); it("toIso8601 works with specified precision", function() { const isoDate = "0950-01-02T03:04:05.012345Z"; let date; date = import__253.JulianDate.toIso8601(import__253.JulianDate.fromIso8601(isoDate), 0); expect(date).toEqual("0950-01-02T03:04:05Z"); date = import__253.JulianDate.toIso8601(import__253.JulianDate.fromIso8601(isoDate), 1); expect(date).toEqual("0950-01-02T03:04:05.0Z"); date = import__253.JulianDate.toIso8601(import__253.JulianDate.fromIso8601(isoDate), 2); expect(date).toEqual("0950-01-02T03:04:05.01Z"); date = import__253.JulianDate.toIso8601(import__253.JulianDate.fromIso8601(isoDate), 3); expect(date).toEqual("0950-01-02T03:04:05.012Z"); date = import__253.JulianDate.toIso8601(import__253.JulianDate.fromIso8601(isoDate), 4); expect(date).toEqual("0950-01-02T03:04:05.0123Z"); date = import__253.JulianDate.toIso8601(import__253.JulianDate.fromIso8601(isoDate), 5); expect(date).toEqual("0950-01-02T03:04:05.01234Z"); date = import__253.JulianDate.toIso8601(import__253.JulianDate.fromIso8601(isoDate), 6); expect(date).toEqual("0950-01-02T03:04:05.012345Z"); date = import__253.JulianDate.toIso8601(import__253.JulianDate.fromIso8601(isoDate), 7); expect(date).toEqual("0950-01-02T03:04:05.0123450Z"); }); it("can format Iso8601.MINIMUM_VALUE and MAXIMUM_VALUE to ISO strings", function() { const minString = import__253.Iso8601.MINIMUM_VALUE.toString(); expect(minString).toEqual("0000-01-01T00:00:00Z"); expect(import__253.JulianDate.fromIso8601(minString)).toEqual(import__253.Iso8601.MINIMUM_VALUE); const maxString = import__253.Iso8601.MAXIMUM_VALUE.toString(); expect(maxString).toEqual("9999-12-31T24:00:00Z"); expect(import__253.JulianDate.fromIso8601(maxString)).toEqual(import__253.Iso8601.MAXIMUM_VALUE); }); it("secondsDifference works in UTC", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 4, 2011 12:00:00 UTC")); const end = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 5, 2011 12:01:00 UTC")); expect(import__253.JulianDate.secondsDifference(end, start)).toEqualEpsilon( import__253.TimeConstants.SECONDS_PER_DAY + import__253.TimeConstants.SECONDS_PER_MINUTE, import__254.Math.EPSILON5 ); }); it("secondsDifference works in TAI", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 4, 2011 12:00:00 UTC")); const end = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 5, 2011 12:01:00 UTC")); expect(import__253.JulianDate.secondsDifference(end, start)).toEqualEpsilon( import__253.TimeConstants.SECONDS_PER_DAY + import__253.TimeConstants.SECONDS_PER_MINUTE, import__254.Math.EPSILON5 ); }); it("secondsDifference works with mixed time standards", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 4, 2011 12:00:00 UTC")); const end = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 5, 2011 12:01:00 UTC")); expect(import__253.JulianDate.secondsDifference(end, start)).toEqualEpsilon( import__253.TimeConstants.SECONDS_PER_DAY + import__253.TimeConstants.SECONDS_PER_MINUTE, import__254.Math.EPSILON5 ); }); it("daysDifference works", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 4, 2011 12:00:00")); const end = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 5, 2011 14:24:00")); const difference = import__253.JulianDate.daysDifference(end, start); expect(difference).toEqual(1.1); }); it("daysDifference works with negative result", function() { const end = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 4, 2011 12:00:00")); const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 5, 2011 14:24:00")); const difference = import__253.JulianDate.daysDifference(end, start); expect(difference).toEqual(-1.1); }); it("addSeconds works with whole seconds", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 4, 2011 12:00:30 UTC")); const end = import__253.JulianDate.addSeconds(start, 95, new import__253.JulianDate()); expect(import__253.JulianDate.toDate(end).getUTCSeconds()).toEqualEpsilon( 5, import__254.Math.EPSILON5 ); expect(import__253.JulianDate.toDate(end).getUTCMinutes()).toEqualEpsilon( 2, import__254.Math.EPSILON5 ); }); it("addSeconds works with fractions (1)", function() { const start = new import__253.JulianDate(2454832, 0, import__253.TimeStandard.TAI); const end = import__253.JulianDate.addSeconds(start, 1.5, new import__253.JulianDate()); expect(import__253.JulianDate.secondsDifference(end, start)).toEqual(1.5); }); it("addSeconds works with fractions (2)", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("August 11 2011 6:00:00 UTC")); const end = import__253.JulianDate.addSeconds(start, 0.5, new import__253.JulianDate()); expect(import__253.JulianDate.secondsDifference(end, start, new import__253.JulianDate())).toEqual( 0.5 ); }); it("addSeconds works with fractions (3)", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("August 11 2011 11:59:59 UTC")); const end = import__253.JulianDate.addSeconds(start, 1.25, new import__253.JulianDate()); expect(import__253.JulianDate.secondsDifference(end, start, new import__253.JulianDate())).toEqual( 1.25 ); }); it("addSeconds works with negative numbers", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 4, 2011 12:01:30 UTC")); const end = import__253.JulianDate.addSeconds(start, -60, new import__253.JulianDate()); expect(import__253.JulianDate.secondsDifference(end, start)).toEqual(-60); }); it("addSeconds works with more seconds than in a day", function() { const seconds = import__253.TimeConstants.SECONDS_PER_DAY * 7 + 15; const start = new import__253.JulianDate(2448444, 0, import__253.TimeStandard.UTC); const end = import__253.JulianDate.addSeconds(start, seconds, new import__253.JulianDate()); expect(import__253.JulianDate.secondsDifference(end, start)).toEqual(seconds); }); it("addSeconds works with negative seconds more than in a day", function() { const seconds = -import__253.TimeConstants.SECONDS_PER_DAY * 7 - 15; const start = new import__253.JulianDate(2448444, 0, import__253.TimeStandard.UTC); const end = import__253.JulianDate.addSeconds(start, seconds, new import__253.JulianDate()); expect(import__253.JulianDate.secondsDifference(end, start)).toEqual(seconds); }); it("addSeconds fails with undefined input", function() { expect(function() { return import__253.JulianDate.addSeconds( import__253.JulianDate.now(), void 0, new import__253.JulianDate() ); }).toThrowDeveloperError(); }); it("addMinutes works", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 4, 2011 12:00:00 UTC")); const end = import__253.JulianDate.addMinutes(start, 65, new import__253.JulianDate()); expect(import__253.JulianDate.toDate(end).getUTCMinutes()).toEqualEpsilon( 5, import__254.Math.EPSILON5 ); expect(import__253.JulianDate.toDate(end).getUTCHours()).toEqualEpsilon( 13, import__254.Math.EPSILON5 ); }); it("addMinutes works with negative numbers", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 4, 2011 12:00:00 UTC")); const end = import__253.JulianDate.addMinutes(start, -35, new import__253.JulianDate()); expect(import__253.JulianDate.toDate(end).getUTCMinutes()).toEqualEpsilon( 25, import__254.Math.EPSILON5 ); expect(import__253.JulianDate.toDate(end).getUTCHours()).toEqualEpsilon( 11, import__254.Math.EPSILON5 ); }); it("addMinutes fails with undefined input", function() { expect(function() { return import__253.JulianDate.addMinutes( import__253.JulianDate.now(), void 0, new import__253.JulianDate() ); }).toThrowDeveloperError(); }); it("addHours works", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 4, 2011 12:00:00 UTC")); const end = import__253.JulianDate.addHours(start, 6, new import__253.JulianDate()); expect(import__253.JulianDate.toDate(end).getUTCHours()).toEqualEpsilon( 18, import__254.Math.EPSILON5 ); }); it("addHours works with negative numbers", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 4, 2011 12:00:00 UTC")); const end = import__253.JulianDate.addHours(start, -6, new import__253.JulianDate()); expect(import__253.JulianDate.toDate(end).getUTCHours()).toEqualEpsilon( 6, import__254.Math.EPSILON5 ); }); it("addHours fails with undefined input", function() { expect(function() { return import__253.JulianDate.addHours(import__253.JulianDate.now(), void 0, new import__253.JulianDate()); }).toThrowDeveloperError(); }); it("addDays works", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 4, 2011 12:00:00 UTC")); const end = import__253.JulianDate.addDays(start, 32, new import__253.JulianDate()); expect(import__253.JulianDate.toDate(end).getUTCDate()).toEqualEpsilon( 5, import__254.Math.EPSILON5 ); expect(import__253.JulianDate.toDate(end).getUTCMonth()).toEqualEpsilon( 7, import__254.Math.EPSILON5 ); }); it("addDays works with negative numbers", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 4, 2011 12:00:00 UTC")); const end = import__253.JulianDate.addDays(start, -4, new import__253.JulianDate()); expect(import__253.JulianDate.toDate(end).getUTCDate()).toEqualEpsilon( 30, import__254.Math.EPSILON5 ); expect(import__253.JulianDate.toDate(end).getUTCMonth()).toEqualEpsilon( 5, import__254.Math.EPSILON5 ); }); it("addDays fails with undefined input", function() { expect(function() { return import__253.JulianDate.addDays(import__253.JulianDate.now(), void 0, new import__253.JulianDate()); }).toThrowDeveloperError(); }); it("lessThan works", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 6, 1991 12:00:00")); const end = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 6, 2011 12:01:00")); expect(import__253.JulianDate.lessThan(start, end)).toEqual(true); }); it("lessThan works with equal values", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 6, 1991 12:00:00")); const end = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 6, 1991 12:00:00")); expect(import__253.JulianDate.lessThan(start, end)).toEqual(false); expect( import__253.JulianDate.lessThan( start, import__253.JulianDate.addSeconds(end, 1, new import__253.JulianDate()) ) ).toEqual(true); }); it("lessThan works with different time standards", function() { const start = new import__253.JulianDate(0, 0, import__253.TimeStandard.TAI); const end = new import__253.JulianDate(0, 0, import__253.TimeStandard.UTC); expect(import__253.JulianDate.lessThan(start, end)).toEqual(true); }); it("lessThanOrEquals works", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 6, 1991 12:00:00")); const end = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 6, 1991 12:00:00")); expect(import__253.JulianDate.lessThanOrEquals(start, end)).toEqual(true); expect( import__253.JulianDate.lessThanOrEquals( import__253.JulianDate.addSeconds(start, 1, new import__253.JulianDate()), end ) ).toEqual(false); expect( import__253.JulianDate.lessThanOrEquals( import__253.JulianDate.addSeconds(start, -1, new import__253.JulianDate()), end ) ).toEqual(true); }); it("greaterThan works", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 6, 2011 12:01:00")); const end = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 6, 1991 12:00:00")); expect(import__253.JulianDate.greaterThan(start, end)).toEqual(true); }); it("greaterThan works with equal values", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 6, 1991 12:00:00")); const end = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 6, 1991 12:00:00")); expect(import__253.JulianDate.greaterThan(start, end)).toEqual(false); expect( import__253.JulianDate.greaterThan( start, import__253.JulianDate.addSeconds(end, -1, new import__253.JulianDate()) ) ).toEqual(true); }); it("greaterThan works with different time standards", function() { const start = new import__253.JulianDate(0, 0, import__253.TimeStandard.UTC); const end = new import__253.JulianDate(0, 0, import__253.TimeStandard.TAI); expect(import__253.JulianDate.greaterThan(start, end)).toEqual(true); }); it("greaterThanOrEquals works", function() { const start = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 6, 1991 12:00:00")); const end = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("July 6, 1991 12:00:00")); expect(import__253.JulianDate.greaterThanOrEquals(start, end)).toEqual(true); expect( import__253.JulianDate.greaterThanOrEquals( import__253.JulianDate.addSeconds(start, -1, new import__253.JulianDate()), end ) ).toEqual(false); expect( import__253.JulianDate.greaterThanOrEquals( import__253.JulianDate.addSeconds(start, 1, new import__253.JulianDate()), end ) ).toEqual(true); }); it("can be equal to within an epsilon of another JulianDate", function() { const original = import__253.JulianDate.fromDate( /* @__PURE__ */ new Date("September 7, 2011 12:55:00 UTC") ); let clone24 = import__253.JulianDate.fromDate(/* @__PURE__ */ new Date("September 7, 2011 12:55:00 UTC")); clone24 = import__253.JulianDate.addSeconds(clone24, 1, new import__253.JulianDate()); expect(original.equalsEpsilon(clone24, 2)).toEqual(true); }); it("totalDays works", function() { const totalDays = 24557847500058e-7; const original = new import__253.JulianDate(totalDays, 0, import__253.TimeStandard.TAI); expect(totalDays).toEqual(import__253.JulianDate.totalDays(original)); }); it("equalsEpsilon works", function() { const date = import__253.JulianDate.now(); const datePlusOne = import__253.JulianDate.addSeconds(date, 0.01, new import__253.JulianDate()); expect(date.equalsEpsilon(datePlusOne, import__254.Math.EPSILON1)).toEqual(true); }); it("formats as ISO8601 with toString", function() { const date = import__253.JulianDate.now(); expect(date.toString()).toEqual(import__253.JulianDate.toIso8601(date)); }); it("computeTaiMinusUtc works before all leap seconds", function() { const date = /* @__PURE__ */ new Date("July 11, 1970 12:00:00 UTC"); const jd = import__253.JulianDate.fromDate(date); const difference = import__253.JulianDate.computeTaiMinusUtc(jd); expect(difference).toEqual(10); }); it("computeTaiMinusUtc works a second before a leap second", function() { const date = new import__253.JulianDate(2456109, 43233, import__253.TimeStandard.TAI); expect(import__253.JulianDate.computeTaiMinusUtc(date)).toEqual(34); }); it("computeTaiMinusUtc works on a leap second", function() { const date = new import__253.JulianDate(2456109, 43234, import__253.TimeStandard.TAI); expect(import__253.JulianDate.computeTaiMinusUtc(date)).toEqual(34); }); it("computeTaiMinusUtc works a second after a leap second", function() { const date = new import__253.JulianDate(2456109, 43235, import__253.TimeStandard.TAI); expect(import__253.JulianDate.computeTaiMinusUtc(date)).toEqual(35); }); it("computeTaiMinusUtc works after all leap seconds", function() { const date = new import__253.JulianDate(2556109, 43237, import__253.TimeStandard.TAI); expect(import__253.JulianDate.computeTaiMinusUtc(date)).toEqual(37); }); it("fromGregorianDate returns the same date", function() { const iso86011 = "2017-01-01T10:01:01.5Z"; const julian1 = import__253.JulianDate.fromIso8601(iso86011); const gregorian = import__253.JulianDate.toGregorianDate(julian1); const julian2 = import__253.JulianDate.fromGregorianDate(gregorian); const iso86012 = import__253.JulianDate.toIso8601(julian2); expect(iso86011).toEqual(iso86012); expect(import__253.JulianDate.compare(julian1, julian2)).toEqual(0); }); }); // packages/engine/Specs/Core/LagrangePolynomialApproximationSpec.js var import__255 = __toESM(require_Cesium(), 1); describe("Core/LagrangePolynomialApproximation", function() { const xTable = [0, 60, 120, 180, 240, 300, 360, 420]; const yTable = [ 13378137, 0, 0, 133741283576279e-7, 327475.593690065, 0, 133621048328212e-7, 654754.936954423, 0, 133420736310691e-7, 981641.896976832, 0, 133140467567223e-7, 130794057608951e-8, 0, 13278041005799e-6, 163345542917117e-8, 0, 132340779559193e-7, 195799138083385e-8, 0, 13182183953374e-6, 228135394232816e-8, 0 ]; const x = 100; it("interpolation produces correct results.", function() { const result = import__255.LagrangePolynomialApproximation.interpolateOrderZero( x, xTable, yTable, 3 ); const expectedResult = [13367002870928623e-9, 545695.7388100647, 0]; expect(result).toEqualEpsilon(expectedResult, 1e-15); }); it("interpolation produces correct results with a result parameter", function() { const result = new Array(3); const returnedResult = import__255.LagrangePolynomialApproximation.interpolateOrderZero( x, xTable, yTable, 3, result ); const expectedResult = [13367002870928623e-9, 545695.7388100647, 0]; expect(result).toBe(returnedResult); expect(result).toEqualEpsilon(expectedResult, 1e-15); }); it("getRequiredDataPoints should be 1 more than degree, except for 0, which requires 2", function() { expect(import__255.LagrangePolynomialApproximation.getRequiredDataPoints(0)).toEqual(2); expect(import__255.LagrangePolynomialApproximation.getRequiredDataPoints(1)).toEqual(2); expect(import__255.LagrangePolynomialApproximation.getRequiredDataPoints(2)).toEqual(3); expect(import__255.LagrangePolynomialApproximation.getRequiredDataPoints(3)).toEqual(4); }); }); // packages/engine/Specs/Core/LeapSecondSpec.js var import__256 = __toESM(require_Cesium(), 1); describe("Core/LeapSecond", function() { it("default constructor sets expected values", function() { const leapSecond = new import__256.LeapSecond(); expect(leapSecond.julianDate).toBeUndefined(); expect(leapSecond.offset).toBeUndefined(); }); it("constructor sets expected values", function() { const date = new import__256.JulianDate(); const offset = 12; const leapSecond = new import__256.LeapSecond(date, offset); expect(leapSecond.julianDate).toEqual(date); expect(leapSecond.offset).toEqual(offset); }); }); // packages/engine/Specs/Core/LinearApproximationSpec.js var import__257 = __toESM(require_Cesium(), 1); describe("Core/LinearApproximation", function() { it("should produce correct results", function() { const xTable = [2, 4]; const yTable = [2, 3, 4, 34]; const results = import__257.LinearApproximation.interpolateOrderZero( 3, xTable, yTable, 2 ); expect(results.length).toEqual(2); expect(results[0]).toEqual(3); expect(results[1]).toEqual(18.5); }); it("should produce correct results with a result parameter", function() { const xTable = [2, 4]; const yTable = [2, 3, 4, 34]; const result = new Array(2); const results = import__257.LinearApproximation.interpolateOrderZero( 3, xTable, yTable, 2, result ); expect(result).toBe(results); expect(results.length).toEqual(2); expect(results[0]).toEqual(3); expect(results[1]).toEqual(18.5); }); it("should produce correct results 2", function() { const xTable2 = [40, 120]; const yTable2 = [20, 40, 60, 80, 90, 100]; const results = import__257.LinearApproximation.interpolateOrderZero( 80, xTable2, yTable2, 3 ); expect(results.length).toEqual(3); expect(results[0]).toEqual(50); expect(results[1]).toEqual(65); expect(results[2]).toEqual(80); }); it("should produce correct results 3", function() { const xTable3 = [20, 30]; const yTable3 = [10, 20, 30, 20, 30, 40, 20, 40, 60, 80, 90, 100]; const results = import__257.LinearApproximation.interpolateOrderZero( 40, xTable3, yTable3, 1 ); expect(results.length).toEqual(1); expect(results[0]).toEqual(30); }); it("should throw if length is greater than 2", function() { const xTable = [44, 99, 230]; const yTable = [2.3, 4.5, 6.6, 3.2, 4.4, 12.23]; expect(function() { import__257.LinearApproximation.interpolateOrderZero(2.3, xTable, yTable, 3); }).toThrowDeveloperError(); }); it("should throw when yStride equals zero indicating that there are no dependent variables for interpolation", function() { const xTable = [4, 8]; const yTable = [4, 8]; expect(function() { import__257.LinearApproximation.interpolateOrderZero(6, xTable, yTable, 0); }).toThrowDeveloperError(); }); it("getRequiredDataPoints returns 2", function() { expect(import__257.LinearApproximation.getRequiredDataPoints(1)).toEqual(2); }); }); // packages/engine/Specs/Core/LinearSplineSpec.js var import__258 = __toESM(require_Cesium(), 1); describe("Core/LinearSpline", function() { let times; let cartesianPoints; let numberPoints; beforeEach(function() { times = [0, 1, 2, 3]; cartesianPoints = [ new import__258.Cartesian3(-1, -1, 0), new import__258.Cartesian3(-0.5, -0.125, 0), new import__258.Cartesian3(0.5, 0.125, 0), new import__258.Cartesian3(1, 1, 0) ]; numberPoints = [3, 5, 1, 10]; }); it("constructor throws without points or times", function() { expect(function() { return new import__258.LinearSpline(); }).toThrowDeveloperError(); }); it("constructor throws when control points length is less than 2", function() { expect(function() { return new import__258.LinearSpline({ points: [import__258.Cartesian3.ZERO] }); }).toThrowDeveloperError(); }); it("constructor throws when times.length is not equal to points.length", function() { expect(function() { return new import__258.LinearSpline({ points: numberPoints, times: [0, 1] }); }).toThrowDeveloperError(); }); it("evaluate throws without time", function() { const ls = new import__258.LinearSpline({ points: numberPoints, times }); expect(function() { ls.evaluate(); }).toThrowDeveloperError(); }); it("evaluate throws when time is out of range", function() { const ls = new import__258.LinearSpline({ points: numberPoints, times }); expect(function() { ls.evaluate(times[0] - 1); }).toThrowDeveloperError(); }); it("evaluate returns number value", function() { const ls = new import__258.LinearSpline({ points: numberPoints, times }); expect(ls.evaluate(times[0])).toEqual(numberPoints[0]); const time2 = (times[0] + times[1]) / 2; const t = (time2 - times[0]) / (times[1] - times[0]); const expected = (1 - t) * numberPoints[0] + t * numberPoints[1]; expect(ls.evaluate(time2)).toEqual(expected); }); const scratchCartesian = new import__258.Cartesian3(); it("evaluate returns cartesian3 value without result parameter", function() { const ls = new import__258.LinearSpline({ points: cartesianPoints, times }); expect(ls.evaluate(times[0])).toEqual(cartesianPoints[0]); const time2 = (times[0] + times[1]) / 2; const t = (time2 - times[0]) / (times[1] - times[0]); const expected = import__258.Cartesian3.lerp( cartesianPoints[0], cartesianPoints[1], t, scratchCartesian ); expect(ls.evaluate(time2)).toEqual(expected); }); it("evaluate returns cartesian3 value with result parameter", function() { const ls = new import__258.LinearSpline({ points: cartesianPoints, times }); const result = new import__258.Cartesian3(); const time2 = (times[0] + times[1]) / 2; const t = (time2 - times[0]) / (times[1] - times[0]); const point = ls.evaluate(time2, result); const expected = import__258.Cartesian3.lerp( cartesianPoints[0], cartesianPoints[1], t, scratchCartesian ); expect(point).toBe(result); expect(result).toEqual(expected); }); }); // packages/engine/Specs/Core/ManagedArraySpec.js var import__259 = __toESM(require_Cesium(), 1); describe("Core/ManagedArray", function() { function expectTrailingReferenceToBeRemoved(managedArray) { const array = managedArray._array; const length2 = managedArray._length; const reservedLength = array.length; for (let i = length2; i < reservedLength; ++i) { expect(array[i]).toBeUndefined(); } } it("constructor has expected default values", function() { const array = new import__259.ManagedArray(); expect(array.length).toEqual(0); }); it("constructor initializes length", function() { const array = new import__259.ManagedArray(10); expect(array.length).toEqual(10); expect(array.values.length).toEqual(10); }); it("can get and set values", function() { const length2 = 10; const array = new import__259.ManagedArray(length2); let i; for (i = 0; i < length2; ++i) { array.set(i, i * i); } for (i = 0; i < length2; ++i) { expect(array.get(i)).toEqual(i * i); expect(array.values[i]).toEqual(i * i); } }); it("get throws if index does not exist", function() { const array = new import__259.ManagedArray(); array.reserve(5); expect(array.values.length).toEqual(5); expect(function() { array.get(5); }).toThrowDeveloperError(); }); it("set throws if index invalid", function() { const array = new import__259.ManagedArray(); array.resize(10); expect(function() { array.set(void 0, 5); }).toThrowDeveloperError(); }); it("length setter throws if length is less than 0", function() { const array = new import__259.ManagedArray(); expect(function() { array.length = -1; }).toThrowDeveloperError(); }); it("set resizes array", function() { const array = new import__259.ManagedArray(); array.set(0, "a"); expect(array.length).toEqual(1); array.set(5, "b"); expect(array.length).toEqual(6); array.set(2, "c"); expect(array.length).toEqual(6); }); it("peeks at the last element of the array", function() { const array = new import__259.ManagedArray(); expect(array.peek()).toBeUndefined(); array.push(0); expect(array.peek()).toBe(0); array.push(1); array.push(2); expect(array.peek()).toBe(2); }); it("can push values", function() { const array = new import__259.ManagedArray(); const length2 = 10; for (let i = 0; i < length2; ++i) { const val = Math.random(); array.push(val); expect(array.length).toEqual(i + 1); expect(array.values.length).toEqual(i + 1); expect(array.get(i)).toEqual(val); expect(array.values[i]).toEqual(val); } }); it("can pop values", function() { const length2 = 10; const array = new import__259.ManagedArray(length2); let i; for (i = 0; i < length2; ++i) { array.set(i, Math.random()); } for (i = length2 - 1; i >= 0; --i) { const val = array.get(i); expect(array.pop()).toEqual(val); expect(array.length).toEqual(i); expect(array.values.length).toEqual(length2); } }); it("pop removes trailing references", function() { const length2 = 10; const array = new import__259.ManagedArray(length2); array.set(0, Math.random()); array.set(1, Math.random()); array.set(2, Math.random()); array.pop(); array.pop(); expectTrailingReferenceToBeRemoved(array); }); it("pop returns undefined if array is empty", function() { const array = new import__259.ManagedArray(); array.push(1); expect(array.pop()).toBe(1); expect(array.pop()).toBeUndefined(); }); it("reserve throws if length is less than 0", function() { const array = new import__259.ManagedArray(); expect(function() { array.reserve(-1); }).toThrowDeveloperError(); }); it("reserve", function() { const array = new import__259.ManagedArray(2); array.reserve(10); expect(array.values.length).toEqual(10); expect(array.length).toEqual(2); array.reserve(20); expect(array.values.length).toEqual(20); expect(array.length).toEqual(2); array.reserve(5); expect(array.values.length).toEqual(20); expect(array.length).toEqual(2); }); it("resize throws if length is less than 0", function() { const array = new import__259.ManagedArray(); expect(function() { array.resize(-1); }).toThrowDeveloperError(); }); it("resize", function() { const array = new import__259.ManagedArray(2); array.resize(10); expect(array.values.length).toEqual(10); expect(array.length).toEqual(10); array.resize(20); expect(array.values.length).toEqual(20); expect(array.length).toEqual(20); array.resize(5); expect(array.values.length).toEqual(20); expect(array.length).toEqual(5); }); it("resize removes trailing references", function() { const length2 = 10; const array = new import__259.ManagedArray(length2); array.set(0, Math.random()); array.set(1, Math.random()); array.set(2, Math.random()); array.resize(1); expectTrailingReferenceToBeRemoved(array); }); it("trim", function() { const array = new import__259.ManagedArray(2); array.reserve(10); expect(array.length).toEqual(2); expect(array.values.length).toEqual(10); array.trim(); expect(array.values.length).toEqual(2); array.trim(5); expect(array.length).toEqual(2); expect(array.values.length).toEqual(5); array.trim(3); expect(array.length).toEqual(2); expect(array.values.length).toEqual(3); }); }); // packages/engine/Specs/Core/MathSpec.js var import__260 = __toESM(require_Cesium(), 1); describe("Core/Math", function() { it("sign of -2", function() { expect(import__260.Math.sign(-2)).toEqual(-1); }); it("sign of 2", function() { expect(import__260.Math.sign(2)).toEqual(1); }); it("sign of 0", function() { expect(import__260.Math.sign(0)).toEqual(0); }); it("sign of -0", function() { expect(import__260.Math.sign(-0)).toEqual(-0); }); it("sign of NaN", function() { expect(import__260.Math.sign(NaN)).toBeNaN(); }); it("signNotZero of -2", function() { expect(import__260.Math.signNotZero(-2)).toEqual(-1); }); it("signNotZero of 2", function() { expect(import__260.Math.signNotZero(2)).toEqual(1); }); it("signNotZero of 0", function() { expect(import__260.Math.signNotZero(0)).toEqual(1); }); it("toSNorm -1.0", function() { expect(import__260.Math.toSNorm(-1)).toEqual(0); }); it("toSNorm 1.0", function() { expect(import__260.Math.toSNorm(1)).toEqual(255); }); it("toSNorm -1.0001", function() { expect(import__260.Math.toSNorm(-1.0001)).toEqual(0); }); it("toSNorm 1.0001", function() { expect(import__260.Math.toSNorm(1.0001)).toEqual(255); }); it("toSNorm 0.0", function() { expect(import__260.Math.toSNorm(0)).toEqual(128); }); it("fromSNorm 0", function() { expect(import__260.Math.fromSNorm(0)).toEqual(-1); }); it("fromSNorm 255", function() { expect(import__260.Math.fromSNorm(255)).toEqual(1); }); it("fromSNorm -0.0001", function() { expect(import__260.Math.fromSNorm(-1e-4)).toEqual(-1); }); it("fromSNorm 255.00001", function() { expect(import__260.Math.fromSNorm(255.00001)).toEqual(1); }); it("fromSNorm 128", function() { expect(import__260.Math.fromSNorm(255 / 2)).toEqual(0); }); it("normalize 0 with max 10 min -10", function() { expect(import__260.Math.normalize(0, -10, 10)).toEqual(0.5); }); it("normalize 10 with max 10 min -10", function() { expect(import__260.Math.normalize(10, -10, 10)).toEqual(1); }); it("normalize -10 with max 10 min -10", function() { expect(import__260.Math.normalize(-10, -10, 10)).toEqual(0); }); it("normalize -10.0001 with max 10 min -10", function() { expect(import__260.Math.normalize(-10.0001, -10, 10)).toEqual(0); }); it("normalize 10.00001 with max 10 min -10", function() { expect(import__260.Math.normalize(10.00001, -10, 10)).toEqual(1); }); it("cosh", function() { expect(import__260.Math.cosh(0)).toEqual(1); expect(import__260.Math.cosh(-1)).toBeGreaterThan(1); expect(import__260.Math.cosh(1)).toBeGreaterThan(1); }); it("cosh NaN", function() { expect(isNaN(import__260.Math.cosh(NaN))).toEqual(true); }); it("cosh infinity", function() { expect(import__260.Math.cosh(Infinity)).toEqual(Infinity); expect(import__260.Math.cosh(-Infinity)).toEqual(Infinity); }); it("sinh", function() { expect(import__260.Math.sinh(0)).toEqual(0); expect(import__260.Math.sinh(-1)).toBeLessThan(1); expect(import__260.Math.sinh(1)).toBeGreaterThan(1); }); it("sinh NaN", function() { expect(isNaN(import__260.Math.sinh(NaN))).toEqual(true); }); it("sinh infinity", function() { expect(import__260.Math.sinh(Infinity)).toEqual(Infinity); expect(import__260.Math.sinh(-Infinity)).toEqual(-Infinity); }); it("lerps at time 0", function() { expect(import__260.Math.lerp(1, 2, 0)).toEqual(1); }); it("lerps at time 0.5", function() { expect(import__260.Math.lerp(1, 2, 0.5)).toEqual(1.5); }); it("lerps at time 1", function() { expect(import__260.Math.lerp(1, 2, 1)).toEqual(2); }); it("toRadians", function() { expect(import__260.Math.toRadians(360)).toEqual(2 * Math.PI); }); it("toRadians throws for undefined", function() { expect(function() { import__260.Math.toRadians(); }).toThrowDeveloperError(); }); it("toDegrees", function() { expect(import__260.Math.toDegrees(Math.PI)).toEqual(180); }); it("toDegrees throws for undefined", function() { expect(function() { import__260.Math.toDegrees(); }).toThrowDeveloperError(); }); it("convertLongitudeRange (1)", function() { expect( import__260.Math.convertLongitudeRange(import__260.Math.THREE_PI_OVER_TWO) ).toEqualEpsilon(-import__260.Math.PI_OVER_TWO, import__260.Math.EPSILON16); }); it("convertLongitudeRange (2)", function() { expect(import__260.Math.convertLongitudeRange(-Math.PI)).toEqualEpsilon( -Math.PI, import__260.Math.EPSILON16 ); }); it("convertLongitudeRange (3)", function() { expect(import__260.Math.convertLongitudeRange(Math.PI)).toEqualEpsilon( -Math.PI, import__260.Math.EPSILON16 ); }); it("convertLongitudeRange throws for undefined", function() { expect(function() { import__260.Math.convertLongitudeRange(); }).toThrowDeveloperError(); }); it("clampToLatitudeRange (1)", function() { expect(import__260.Math.clampToLatitudeRange(Math.PI)).toEqual( import__260.Math.PI_OVER_TWO ); }); it("clampToLatitudeRange (2)", function() { expect(import__260.Math.clampToLatitudeRange(-Math.PI)).toEqual( -import__260.Math.PI_OVER_TWO ); }); it("clampToLatitudeRange throws for undefined", function() { expect(function() { import__260.Math.clampToLatitudeRange(); }).toThrowDeveloperError(); }); it("negativePiToPi", function() { expect(import__260.Math.negativePiToPi(0)).toEqual(0); expect(import__260.Math.negativePiToPi(+Math.PI)).toEqual(+Math.PI); expect(import__260.Math.negativePiToPi(-Math.PI)).toEqual(-Math.PI); expect(import__260.Math.negativePiToPi(+Math.PI - 1)).toEqual(+Math.PI - 1); expect(import__260.Math.negativePiToPi(-Math.PI + 1)).toEqual(-Math.PI + 1); expect(import__260.Math.negativePiToPi(+Math.PI - 0.1)).toEqual(+Math.PI - 0.1); expect(import__260.Math.negativePiToPi(-Math.PI + 0.1)).toEqual(-Math.PI + 0.1); expect(import__260.Math.negativePiToPi(+Math.PI + 0.1)).toEqualEpsilon( -Math.PI + 0.1, import__260.Math.EPSILON15 ); expect(import__260.Math.negativePiToPi(-Math.PI - 0.1)).toEqualEpsilon( +Math.PI - 0.1, import__260.Math.EPSILON15 ); expect(import__260.Math.negativePiToPi(2 * Math.PI)).toEqual(0); expect(import__260.Math.negativePiToPi(-2 * Math.PI)).toEqual(0); expect(import__260.Math.negativePiToPi(3 * Math.PI)).toEqual(Math.PI); expect(import__260.Math.negativePiToPi(-3 * Math.PI)).toEqual(Math.PI); expect(import__260.Math.negativePiToPi(4 * Math.PI)).toEqual(0); expect(import__260.Math.negativePiToPi(-4 * Math.PI)).toEqual(0); expect(import__260.Math.negativePiToPi(5 * Math.PI)).toEqual(Math.PI); expect(import__260.Math.negativePiToPi(-5 * Math.PI)).toEqual(Math.PI); expect(import__260.Math.negativePiToPi(6 * Math.PI)).toEqual(0); expect(import__260.Math.negativePiToPi(-6 * Math.PI)).toEqual(0); }); it("negativePiToPi throws for undefined", function() { expect(function() { import__260.Math.negativePiToPi(); }).toThrowDeveloperError(); }); it("zeroToTwoPi", function() { expect(import__260.Math.zeroToTwoPi(0)).toEqual(0); expect(import__260.Math.zeroToTwoPi(+Math.PI)).toEqual(+Math.PI); expect(import__260.Math.zeroToTwoPi(-Math.PI)).toEqual(+Math.PI); expect(import__260.Math.zeroToTwoPi(+Math.PI - 1)).toEqual(+Math.PI - 1); expect(import__260.Math.zeroToTwoPi(-Math.PI + 1)).toEqualEpsilon( +Math.PI + 1, import__260.Math.EPSILON15 ); expect(import__260.Math.zeroToTwoPi(+Math.PI - 0.1)).toEqual(+Math.PI - 0.1); expect(import__260.Math.zeroToTwoPi(-Math.PI + 0.1)).toEqualEpsilon( +Math.PI + 0.1, import__260.Math.EPSILON15 ); expect(import__260.Math.zeroToTwoPi(+Math.PI + 0.1)).toEqual(+Math.PI + 0.1); expect(import__260.Math.zeroToTwoPi(-Math.PI - 0.1)).toEqualEpsilon( +Math.PI - 0.1, import__260.Math.EPSILON15 ); expect(import__260.Math.zeroToTwoPi(2 * Math.PI)).toEqual(2 * Math.PI); expect(import__260.Math.zeroToTwoPi(-2 * Math.PI)).toEqual(2 * Math.PI); expect(import__260.Math.zeroToTwoPi(3 * Math.PI)).toEqual(Math.PI); expect(import__260.Math.zeroToTwoPi(-3 * Math.PI)).toEqual(Math.PI); expect(import__260.Math.zeroToTwoPi(4 * Math.PI)).toEqual(2 * Math.PI); expect(import__260.Math.zeroToTwoPi(-4 * Math.PI)).toEqual(2 * Math.PI); expect(import__260.Math.zeroToTwoPi(5 * Math.PI)).toEqual(Math.PI); expect(import__260.Math.zeroToTwoPi(-5 * Math.PI)).toEqual(Math.PI); expect(import__260.Math.zeroToTwoPi(6 * Math.PI)).toEqual(2 * Math.PI); expect(import__260.Math.zeroToTwoPi(-6 * Math.PI)).toEqual(2 * Math.PI); }); it("zeroToTwoPi throws for undefined", function() { expect(function() { import__260.Math.zeroToTwoPi(); }).toThrowDeveloperError(); }); it("mod", function() { expect(import__260.Math.mod(0, 1)).toEqual(0); expect(import__260.Math.mod(0.1, 1)).toEqual(0.1); expect(import__260.Math.mod(0.5, 1)).toEqual(0.5); expect(import__260.Math.mod(1, 1)).toEqual(0); expect(import__260.Math.mod(1.1, 1)).toEqualEpsilon(0.1, import__260.Math.EPSILON15); expect(import__260.Math.mod(-0, 1)).toEqual(0); expect(import__260.Math.mod(-0.1, 1)).toEqual(0.9); expect(import__260.Math.mod(-0.5, 1)).toEqual(0.5); expect(import__260.Math.mod(-1, 1)).toEqual(0); expect(import__260.Math.mod(-1.1, 1)).toEqualEpsilon(0.9, import__260.Math.EPSILON15); expect(import__260.Math.mod(0, -1)).toEqual(-0); expect(import__260.Math.mod(0.1, -1)).toEqual(-0.9); expect(import__260.Math.mod(0.5, -1)).toEqual(-0.5); expect(import__260.Math.mod(1, -1)).toEqual(-0); expect(import__260.Math.mod(1.1, -1)).toEqualEpsilon( -0.9, import__260.Math.EPSILON15 ); expect(import__260.Math.mod(-0, -1)).toEqual(-0); expect(import__260.Math.mod(-0.1, -1)).toEqual(-0.1); expect(import__260.Math.mod(-0.5, -1)).toEqual(-0.5); expect(import__260.Math.mod(-1, -1)).toEqual(-0); expect(import__260.Math.mod(-1.1, -1)).toEqualEpsilon( -0.1, import__260.Math.EPSILON15 ); }); it("mod throws for divisor of 0", function() { expect(function() { import__260.Math.mod(1, 0); }).toThrowDeveloperError(); }); it("equalsEpsilon", function() { expect(import__260.Math.equalsEpsilon(1, 1, 0)).toEqual(true); expect(import__260.Math.equalsEpsilon(1, 1, 1)).toEqual(true); expect( import__260.Math.equalsEpsilon( 1, 1 + import__260.Math.EPSILON7, import__260.Math.EPSILON7 ) ).toEqual(true); expect( import__260.Math.equalsEpsilon( 1, 1 + import__260.Math.EPSILON7, import__260.Math.EPSILON9 ) ).toEqual(false); expect(import__260.Math.equalsEpsilon(3e6, 3e6, 0)).toEqual(true); expect( import__260.Math.equalsEpsilon(3e6, 3e6, import__260.Math.EPSILON7) ).toEqual(true); expect( import__260.Math.equalsEpsilon(3e6, 30000002e-1, import__260.Math.EPSILON7) ).toEqual(true); expect( import__260.Math.equalsEpsilon(3e6, 30000002e-1, import__260.Math.EPSILON9) ).toEqual(false); }); it("equalsEpsilon throws for undefined left", function() { expect(function() { import__260.Math.equalsEpsilon(void 0, 5, import__260.Math.EPSILON16); }).toThrowDeveloperError(); }); it("equalsEpsilon throws for undefined right", function() { expect(function() { import__260.Math.equalsEpsilon(1, void 0, import__260.Math.EPSILON16); }).toThrowDeveloperError(); }); it("equalsEpsilon throws for undefined", function() { expect(function() { import__260.Math.equalsEpsilon(); }).toThrowDeveloperError(); }); it("lessThan works", function() { expect(import__260.Math.lessThan(1, 2, 0.2)).toBe(true); expect(import__260.Math.lessThan(2, 1, 0.2)).toBe(false); expect(import__260.Math.lessThan(1, 1, 0.2)).toBe(false); expect(import__260.Math.lessThan(1, 1.2, 0.2)).toBe(false); expect(import__260.Math.lessThan(1.2, 1, 0.2)).toBe(false); }); it("lessThan throws for undefined left", function() { expect(function() { import__260.Math.lessThan(void 0, 5, import__260.Math.EPSILON16); }).toThrowDeveloperError(); }); it("lessThan throws for undefined right", function() { expect(function() { import__260.Math.lessThan(1, void 0, import__260.Math.EPSILON16); }).toThrowDeveloperError(); }); it("lessThan throws for undefined absoluteEpsilon", function() { expect(function() { import__260.Math.lessThan(1, 5, void 0); }).toThrowDeveloperError(); }); it("lessThanOrEquals works", function() { expect(import__260.Math.lessThanOrEquals(1, 2, 0.2)).toBe(true); expect(import__260.Math.lessThanOrEquals(2, 1, 0.2)).toBe(false); expect(import__260.Math.lessThanOrEquals(1, 1, 0.2)).toBe(true); expect(import__260.Math.lessThanOrEquals(1, 1.2, 0.2)).toBe(true); expect(import__260.Math.lessThanOrEquals(1.2, 1, 0.2)).toBe(true); }); it("lessThanOrEquals throws for undefined left", function() { expect(function() { import__260.Math.lessThanOrEquals(void 0, 5, import__260.Math.EPSILON16); }).toThrowDeveloperError(); }); it("lessThanOrEquals throws for undefined right", function() { expect(function() { import__260.Math.lessThanOrEquals(1, void 0, import__260.Math.EPSILON16); }).toThrowDeveloperError(); }); it("lessThanOrEquals throws for undefined absoluteEpsilon", function() { expect(function() { import__260.Math.lessThanOrEquals(1, 5, void 0); }).toThrowDeveloperError(); }); it("greaterThan works", function() { expect(import__260.Math.greaterThan(1, 2, 0.2)).toBe(false); expect(import__260.Math.greaterThan(2, 1, 0.2)).toBe(true); expect(import__260.Math.greaterThan(1, 1, 0.2)).toBe(false); expect(import__260.Math.greaterThan(1, 1.2, 0.2)).toBe(false); expect(import__260.Math.greaterThan(1.2, 1, 0.2)).toBe(false); }); it("greaterThan throws for undefined left", function() { expect(function() { import__260.Math.greaterThan(void 0, 5, import__260.Math.EPSILON16); }).toThrowDeveloperError(); }); it("greaterThan throws for undefined right", function() { expect(function() { import__260.Math.greaterThan(1, void 0, import__260.Math.EPSILON16); }).toThrowDeveloperError(); }); it("greaterThan throws for undefined absoluteEpsilon", function() { expect(function() { import__260.Math.greaterThan(1, 5, void 0); }).toThrowDeveloperError(); }); it("greaterThanOrEquals works", function() { expect(import__260.Math.greaterThanOrEquals(1, 2, 0.2)).toBe(false); expect(import__260.Math.greaterThanOrEquals(2, 1, 0.2)).toBe(true); expect(import__260.Math.greaterThanOrEquals(1, 1, 0.2)).toBe(true); expect(import__260.Math.greaterThanOrEquals(1, 1.2, 0.2)).toBe(true); expect(import__260.Math.greaterThanOrEquals(1.2, 1, 0.2)).toBe(true); }); it("greaterThanOrEquals throws for undefined left", function() { expect(function() { import__260.Math.greaterThanOrEquals(void 0, 5, import__260.Math.EPSILON16); }).toThrowDeveloperError(); }); it("greaterThanOrEquals throws for undefined right", function() { expect(function() { import__260.Math.greaterThanOrEquals(1, void 0, import__260.Math.EPSILON16); }).toThrowDeveloperError(); }); it("greaterThanOrEquals throws for undefined absoluteEpsilon", function() { expect(function() { import__260.Math.greaterThanOrEquals(1, 5, void 0); }).toThrowDeveloperError(); }); it("factorial produces the correct results", function() { const factorials2 = [ 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368e3, 20922789888e3, 355687428096e3, 6402373705728e3, 121645100408832e3, 243290200817664e4, 5109094217170944e4, 11240007277776077e5, // eslint-disable-next-line no-loss-of-precision 2585201673888498e7, // eslint-disable-next-line no-loss-of-precision 6204484017332394e8 ]; const length2 = factorials2.length; let i; const indices = []; for (i = 0; i < length2; i++) { indices.push(i); } for (i = 0; i < length2; i++) { const tmp = indices[i]; const randomIndex = Math.floor(Math.random() * length2); indices[i] = indices[randomIndex]; indices[randomIndex] = tmp; } for (i = 0; i < length2; i++) { const index = indices[i]; expect(import__260.Math.factorial(index)).toEqual(factorials2[index]); } }); it("incrementWrap correctly increments and wraps", function() { expect(import__260.Math.incrementWrap(5, 10, 0)).toEqual(6); expect(import__260.Math.incrementWrap(10, 10, 0)).toEqual(0); expect(import__260.Math.incrementWrap(10, 10)).toEqual(0); }); it("incrementWrap throws for undefined", function() { expect(function() { import__260.Math.incrementWrap(); }).toThrowDeveloperError(); }); it("isPowerOfTwo finds powers of two", function() { for (let i = 0; i < 32; i++) { const powerOfTwo = 1 << i >>> 0; expect(import__260.Math.isPowerOfTwo(powerOfTwo)).toEqual(true); } }); it("isPowerOfTwo does not find powers of two", function() { expect(import__260.Math.isPowerOfTwo(0)).toEqual(false); expect(import__260.Math.isPowerOfTwo(3)).toEqual(false); expect(import__260.Math.isPowerOfTwo(5)).toEqual(false); expect(import__260.Math.isPowerOfTwo(12)).toEqual(false); expect(import__260.Math.isPowerOfTwo(4294967295)).toEqual(false); }); it("nextPowerOfTwo finds next power of two", function() { expect(import__260.Math.nextPowerOfTwo(0)).toEqual(0); expect(import__260.Math.nextPowerOfTwo(1)).toEqual(1); expect(import__260.Math.nextPowerOfTwo(2)).toEqual(2); expect(import__260.Math.nextPowerOfTwo(3)).toEqual(4); expect(import__260.Math.nextPowerOfTwo(257)).toEqual(512); expect(import__260.Math.nextPowerOfTwo(512)).toEqual(512); expect(import__260.Math.nextPowerOfTwo(1023)).toEqual(1024); expect(import__260.Math.nextPowerOfTwo(1073741825)).toEqual(2147483648); expect(import__260.Math.nextPowerOfTwo(2147483647)).toEqual(2147483648); expect(import__260.Math.nextPowerOfTwo(2147483648)).toEqual(2147483648); }); it("previousPowerOfTwo finds previous power of two", function() { expect(import__260.Math.previousPowerOfTwo(0)).toEqual(0); expect(import__260.Math.previousPowerOfTwo(1)).toEqual(1); expect(import__260.Math.previousPowerOfTwo(2)).toEqual(2); expect(import__260.Math.previousPowerOfTwo(3)).toEqual(2); expect(import__260.Math.previousPowerOfTwo(257)).toEqual(256); expect(import__260.Math.previousPowerOfTwo(512)).toEqual(512); expect(import__260.Math.previousPowerOfTwo(1023)).toEqual(512); expect(import__260.Math.previousPowerOfTwo(2147483648)).toEqual(2147483648); expect(import__260.Math.previousPowerOfTwo(2147483649)).toEqual(2147483648); expect(import__260.Math.previousPowerOfTwo(4294967295)).toEqual(2147483648); }); it("factorial throws for non-numbers", function() { expect(function() { import__260.Math.factorial({}); }).toThrowDeveloperError(); }); it("factorial throws for negative numbers", function() { expect(function() { import__260.Math.factorial(-1); }).toThrowDeveloperError(); }); it("factorial throws for undefined", function() { expect(function() { import__260.Math.factorial(); }).toThrowDeveloperError(); }); it("incrementWrap throws for minimum value >= maximum value", function() { expect(function() { import__260.Math.incrementWrap(5, 0, 10); }).toThrowDeveloperError(); expect(function() { import__260.Math.incrementWrap(5, 10, 10); }).toThrowDeveloperError(); }); it("isPowerOfTwo throws for non-numbers", function() { expect(function() { import__260.Math.isPowerOfTwo({}); }).toThrowDeveloperError(); }); it("isPowerOfTwo throws for negative numbers", function() { expect(function() { import__260.Math.isPowerOfTwo(-1); }).toThrowDeveloperError(); }); it("isPowerOfTwo throws for numbers that exceed maximum 32-bit unsigned int", function() { expect(function() { return import__260.Math.isPowerOfTwo(4294967296); }).toThrowDeveloperError(); }); it("isPowerOfTwo throws for undefined", function() { expect(function() { import__260.Math.isPowerOfTwo(); }).toThrowDeveloperError(); }); it("nextPowerOfTwo throws for non-numbers", function() { expect(function() { import__260.Math.nextPowerOfTwo({}); }).toThrowDeveloperError(); }); it("nextPowerOfTwo throws for negative numbers", function() { expect(function() { import__260.Math.nextPowerOfTwo(-1); }).toThrowDeveloperError(); }); it("nextPowerOfTwo throws for results that would exceed maximum 32-bit unsigned int", function() { expect(function() { return import__260.Math.nextPowerOfTwo(2147483649); }).toThrowDeveloperError(); }); it("nextPowerOfTwo throws for undefined", function() { expect(function() { import__260.Math.nextPowerOfTwo(); }).toThrowDeveloperError(); }); it("previousPowerOfTwo throws for non-numbers", function() { expect(function() { import__260.Math.previousPowerOfTwo({}); }).toThrowDeveloperError(); }); it("previousPowerOfTwo throws for negative numbers", function() { expect(function() { import__260.Math.previousPowerOfTwo(-1); }).toThrowDeveloperError(); }); it("previousPowerOfTwo throws for results that would exceed maximum 32-bit unsigned int", function() { expect(function() { return import__260.Math.previousPowerOfTwo(4294967296); }).toThrowDeveloperError(); }); it("previousPowerOfTwo throws for undefined", function() { expect(function() { import__260.Math.previousPowerOfTwo(); }).toThrowDeveloperError(); }); it("clamp throws for undefined", function() { expect(function() { import__260.Math.clamp(); }).toThrowDeveloperError(); }); it("acosClamped returns acos for normal values", function() { expect(import__260.Math.acosClamped(0.5)).toBe(Math.acos(0.5)); expect(import__260.Math.acosClamped(0.123)).toBe(Math.acos(0.123)); expect(import__260.Math.acosClamped(-0.123)).toBe(Math.acos(-0.123)); expect(import__260.Math.acosClamped(-1)).toBe(Math.acos(-1)); expect(import__260.Math.acosClamped(1)).toBe(Math.acos(1)); }); it("acosClamped returns acos of clamped value when value is outside the valid range", function() { expect(import__260.Math.acosClamped(-1.01)).toBe(Math.acos(-1)); expect(import__260.Math.acosClamped(1.01)).toBe(Math.acos(1)); }); it("acosClamped throws without value", function() { expect(function() { import__260.Math.acosClamped(); }).toThrowDeveloperError(); }); it("asinClamped returns asin for normal values", function() { expect(import__260.Math.asinClamped(0.5)).toBe(Math.asin(0.5)); expect(import__260.Math.asinClamped(0.123)).toBe(Math.asin(0.123)); expect(import__260.Math.asinClamped(-0.123)).toBe(Math.asin(-0.123)); expect(import__260.Math.asinClamped(-1)).toBe(Math.asin(-1)); expect(import__260.Math.asinClamped(1)).toBe(Math.asin(1)); }); it("asinClamped returns asin of clamped value when value is outside the valid range", function() { expect(import__260.Math.asinClamped(-1.01)).toBe(Math.asin(-1)); expect(import__260.Math.asinClamped(1.01)).toBe(Math.asin(1)); }); it("asinClamped throws without value", function() { expect(function() { import__260.Math.asinClamped(); }).toThrowDeveloperError(); }); it("chordLength finds the chord length", function() { expect( import__260.Math.chordLength(import__260.Math.PI_OVER_THREE, 1) ).toEqualEpsilon(1, import__260.Math.EPSILON14); expect( import__260.Math.chordLength(import__260.Math.PI_OVER_THREE, 5) ).toEqualEpsilon(5, import__260.Math.EPSILON14); expect( import__260.Math.chordLength(2 * import__260.Math.PI_OVER_THREE, 1) ).toEqualEpsilon(Math.sqrt(3), import__260.Math.EPSILON14); expect( import__260.Math.chordLength(2 * import__260.Math.PI_OVER_THREE, 5) ).toEqualEpsilon(5 * Math.sqrt(3), import__260.Math.EPSILON14); expect(import__260.Math.chordLength(import__260.Math.PI, 10)).toEqualEpsilon( 2 * 10, import__260.Math.EPSILON14 ); }); it("chordLength throws without angle", function() { expect(function() { import__260.Math.chordLength(void 0, 1); }).toThrowDeveloperError(); }); it("chordLength throws without radius", function() { expect(function() { import__260.Math.chordLength(0, void 0); }).toThrowDeveloperError(); }); it("logBase", function() { expect(import__260.Math.logBase(64, 4)).toEqual(3); }); it("logBase throws without number", function() { expect(function() { import__260.Math.logBase(void 0); }).toThrowDeveloperError(); }); it("logBase throws without base", function() { expect(function() { import__260.Math.logBase(64, void 0); }).toThrowDeveloperError(); }); it("cbrt", function() { expect(import__260.Math.cbrt(27)).toEqual(3); expect(import__260.Math.cbrt(-27)).toEqual(-3); expect(import__260.Math.cbrt(0)).toEqual(0); expect(import__260.Math.cbrt(1)).toEqual(1); expect(import__260.Math.cbrt()).toEqual(NaN); }); it("fastApproximateAtan", function() { expect(import__260.Math.fastApproximateAtan(0)).toEqualEpsilon( 0, import__260.Math.EPSILON3 ); expect(import__260.Math.fastApproximateAtan(1)).toEqualEpsilon( import__260.Math.PI_OVER_FOUR, import__260.Math.EPSILON3 ); expect(import__260.Math.fastApproximateAtan(-1)).toEqualEpsilon( -import__260.Math.PI_OVER_FOUR, import__260.Math.EPSILON3 ); }); it("fastApproximateAtan2", function() { expect(import__260.Math.fastApproximateAtan2(1, 0)).toEqualEpsilon( 0, import__260.Math.EPSILON3 ); expect(import__260.Math.fastApproximateAtan2(1, 1)).toEqualEpsilon( import__260.Math.PI_OVER_FOUR, import__260.Math.EPSILON3 ); expect(import__260.Math.fastApproximateAtan2(-1, 1)).toEqualEpsilon( import__260.Math.PI_OVER_FOUR + import__260.Math.PI_OVER_TWO, import__260.Math.EPSILON3 ); }); it("fastApproximateAtan2 throws if both arguments are zero", function() { expect(function() { import__260.Math.fastApproximateAtan2(0, 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/Matrix2Spec.js var import__261 = __toESM(require_Cesium(), 1); var import__262 = __toESM(require_Cesium(), 1); describe("Core/Matrix2", function() { it("default constructor creates values array with all zeros.", function() { const matrix = new import__261.Matrix2(); expect(matrix[import__261.Matrix2.COLUMN0ROW0]).toEqual(0); expect(matrix[import__261.Matrix2.COLUMN1ROW0]).toEqual(0); expect(matrix[import__261.Matrix2.COLUMN0ROW1]).toEqual(0); expect(matrix[import__261.Matrix2.COLUMN1ROW1]).toEqual(0); }); it("constructor sets properties from parameters.", function() { const matrix = new import__261.Matrix2(1, 2, 3, 4); expect(matrix[import__261.Matrix2.COLUMN0ROW0]).toEqual(1); expect(matrix[import__261.Matrix2.COLUMN1ROW0]).toEqual(2); expect(matrix[import__261.Matrix2.COLUMN0ROW1]).toEqual(3); expect(matrix[import__261.Matrix2.COLUMN1ROW1]).toEqual(4); }); it("fromArray works without a result parameter", function() { const expected = new import__261.Matrix2(1, 2, 3, 4); const matrix = import__261.Matrix2.fromArray([1, 3, 2, 4]); expect(matrix).toEqual(expected); }); it("fromArray works with a result parameter", function() { const expected = new import__261.Matrix2(1, 2, 3, 4); const result = new import__261.Matrix2(); const matrix = import__261.Matrix2.fromArray([1, 3, 2, 4], 0, result); expect(matrix).toBe(result); expect(matrix).toEqual(expected); }); it("fromArray works with a starting index", function() { const expected = new import__261.Matrix2(1, 2, 3, 4); const result = new import__261.Matrix2(); const matrix = import__261.Matrix2.fromArray( [0, 0, 0, 1, 3, 2, 4], 3, result ); expect(matrix).toBe(result); expect(matrix).toEqual(expected); }); it("fromRowMajorArray works without a result parameter", function() { const expected = new import__261.Matrix2(1, 2, 3, 4); const matrix = import__261.Matrix2.fromRowMajorArray([1, 2, 3, 4]); expect(matrix).toEqual(expected); }); it("fromRowMajorArray works with a result parameter", function() { const expected = new import__261.Matrix2(1, 2, 3, 4); const result = new import__261.Matrix2(); const matrix = import__261.Matrix2.fromRowMajorArray([1, 2, 3, 4], result); expect(matrix).toBe(result); expect(matrix).toEqual(expected); }); it("fromColumnMajorArray works without a result parameter", function() { const expected = new import__261.Matrix2(1, 2, 3, 4); const matrix = import__261.Matrix2.fromColumnMajorArray([1, 3, 2, 4]); expect(matrix).toEqual(expected); }); it("fromColumnMajorArray works with a result parameter", function() { const expected = new import__261.Matrix2(1, 2, 3, 4); const result = new import__261.Matrix2(); const matrix = import__261.Matrix2.fromColumnMajorArray([1, 3, 2, 4], result); expect(matrix).toBe(result); expect(matrix).toEqual(expected); }); it("fromScale works without a result parameter", function() { const expected = new import__261.Matrix2(7, 0, 0, 8); const returnedResult = import__261.Matrix2.fromScale(new import__261.Cartesian2(7, 8)); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("fromScale works with a result parameter", function() { const expected = new import__261.Matrix2(7, 0, 0, 8); const result = new import__261.Matrix2(); const returnedResult = import__261.Matrix2.fromScale(new import__261.Cartesian2(7, 8), result); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expected); }); it("fromUniformScale works without a result parameter", function() { const expected = new import__261.Matrix2(2, 0, 0, 2); const returnedResult = import__261.Matrix2.fromUniformScale(2); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("fromUniformScale works with a result parameter", function() { const expected = new import__261.Matrix2(2, 0, 0, 2); const result = new import__261.Matrix2(); const returnedResult = import__261.Matrix2.fromUniformScale(2, result); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expected); }); it("fromRotation works without a result parameter", function() { const matrix = import__261.Matrix2.fromRotation(0); expect(matrix).toEqual(import__261.Matrix2.IDENTITY); }); it("fromRotation works with a result parameter", function() { const expected = new import__261.Matrix2(0, -1, 1, 0); const result = new import__261.Matrix2(); const matrix = import__261.Matrix2.fromRotation(import__262.Math.toRadians(90), result); expect(matrix).toBe(result); expect(matrix).toEqualEpsilon(expected, import__262.Math.EPSILON15); }); it("clone works without a result parameter", function() { const expected = new import__261.Matrix2(1, 2, 3, 4); const returnedResult = expected.clone(); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("clone works with a result parameter", function() { const expected = new import__261.Matrix2(1, 2, 3, 4); const result = new import__261.Matrix2(); const returnedResult = expected.clone(result); expect(returnedResult).toBe(result); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("toArray works without a result parameter", function() { const expected = [1, 2, 3, 4]; const returnedResult = import__261.Matrix2.toArray( import__261.Matrix2.fromColumnMajorArray(expected) ); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("toArray works with a result parameter", function() { const expected = [1, 2, 3, 4]; const result = []; const returnedResult = import__261.Matrix2.toArray( import__261.Matrix2.fromColumnMajorArray(expected), result ); expect(returnedResult).toBe(result); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("getElementIndex works", function() { let i = 0; for (let col = 0; col < 2; col++) { for (let row = 0; row < 2; row++) { const index = import__261.Matrix2.getElementIndex(col, row); expect(index).toEqual(i); i++; } } }); it("getColumn works", function() { const matrix = new import__261.Matrix2(1, 2, 3, 4); const expectedColumn0 = new import__261.Cartesian2(1, 3); const expectedColumn1 = new import__261.Cartesian2(2, 4); const resultColumn0 = new import__261.Cartesian2(); const resultColumn1 = new import__261.Cartesian2(); const returnedResultColumn0 = import__261.Matrix2.getColumn(matrix, 0, resultColumn0); const returnedResultColumn1 = import__261.Matrix2.getColumn(matrix, 1, resultColumn1); expect(resultColumn0).toBe(returnedResultColumn0); expect(resultColumn0).toEqual(expectedColumn0); expect(resultColumn1).toBe(returnedResultColumn1); expect(resultColumn1).toEqual(expectedColumn1); }); it("setColumn works", function() { const matrix = new import__261.Matrix2(1, 2, 3, 4); const result = new import__261.Matrix2(); let expected = new import__261.Matrix2(5, 2, 6, 4); let returnedResult = import__261.Matrix2.setColumn( matrix, 0, new import__261.Cartesian2(5, 6), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); expected = new import__261.Matrix2(1, 7, 3, 8); returnedResult = import__261.Matrix2.setColumn( matrix, 1, new import__261.Cartesian2(7, 8), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); }); it("getRow works", function() { const matrix = new import__261.Matrix2(1, 2, 3, 4); const expectedRow0 = new import__261.Cartesian2(1, 2); const expectedRow1 = new import__261.Cartesian2(3, 4); const resultRow0 = new import__261.Cartesian2(); const resultRow1 = new import__261.Cartesian2(); const returnedResultRow0 = import__261.Matrix2.getRow(matrix, 0, resultRow0); const returnedResultRow1 = import__261.Matrix2.getRow(matrix, 1, resultRow1); expect(resultRow0).toBe(returnedResultRow0); expect(resultRow0).toEqual(expectedRow0); expect(resultRow1).toBe(returnedResultRow1); expect(resultRow1).toEqual(expectedRow1); }); it("setRow works", function() { const matrix = new import__261.Matrix2(1, 2, 3, 4); const result = new import__261.Matrix2(); let expected = new import__261.Matrix2(5, 6, 3, 4); let returnedResult = import__261.Matrix2.setRow( matrix, 0, new import__261.Cartesian2(5, 6), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); expected = new import__261.Matrix2(1, 2, 7, 8); returnedResult = import__261.Matrix2.setRow( matrix, 1, new import__261.Cartesian2(7, 8), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); }); it("setScale works", function() { const oldScale = new import__261.Cartesian2(2, 3); const newScale = new import__261.Cartesian2(4, 5); const matrix = import__261.Matrix2.fromScale(oldScale, new import__261.Matrix2()); const result = new import__261.Matrix2(); expect(import__261.Matrix2.getScale(matrix, new import__261.Cartesian2())).toEqual(oldScale); const returnedResult = import__261.Matrix2.setScale(matrix, newScale, result); expect(import__261.Matrix2.getScale(returnedResult, new import__261.Cartesian2())).toEqual( newScale ); expect(result).toBe(returnedResult); }); it("setUniformScale works", function() { const oldScale = new import__261.Cartesian2(2, 3); const newScale = 4; const matrix = import__261.Matrix2.fromScale(oldScale, new import__261.Matrix2()); const result = new import__261.Matrix2(); expect(import__261.Matrix2.getScale(matrix, new import__261.Cartesian2())).toEqual(oldScale); const returnedResult = import__261.Matrix2.setUniformScale(matrix, newScale, result); expect(import__261.Matrix2.getScale(returnedResult, new import__261.Cartesian2())).toEqual( new import__261.Cartesian2(newScale, newScale) ); expect(result).toBe(returnedResult); }); it("getScale works", function() { const scale = new import__261.Cartesian2(2, 3); const result = new import__261.Cartesian2(); const computedScale = import__261.Matrix2.getScale(import__261.Matrix2.fromScale(scale), result); expect(computedScale).toBe(result); expect(computedScale).toEqualEpsilon(scale, import__262.Math.EPSILON14); }); it("getMaximumScale works", function() { const m = import__261.Matrix2.fromScale(new import__261.Cartesian2(2, 3)); expect(import__261.Matrix2.getMaximumScale(m)).toEqualEpsilon( 3, import__262.Math.EPSILON14 ); }); it("setRotation works", function() { const scaleVec = new import__261.Cartesian2(2, 3); const scale = import__261.Matrix2.fromScale(scaleVec, new import__261.Matrix2()); const rotation = import__261.Matrix2.fromRotation(0.5, new import__261.Matrix2()); const scaleRotation = import__261.Matrix2.setRotation(scale, rotation, new import__261.Matrix2()); const extractedScale = import__261.Matrix2.getScale(scaleRotation, new import__261.Cartesian2()); const extractedRotation = import__261.Matrix2.getRotation(scaleRotation, new import__261.Matrix2()); expect(extractedScale).toEqualEpsilon(scaleVec, import__262.Math.EPSILON14); expect(extractedRotation).toEqualEpsilon(rotation, import__262.Math.EPSILON14); }); it("getRotation returns matrix without scale", function() { const matrix = import__261.Matrix2.fromColumnMajorArray([1, 2, 3, 4]); const expectedRotation = import__261.Matrix2.fromArray([ 1 / Math.sqrt(1 * 1 + 2 * 2), 2 / Math.sqrt(1 * 1 + 2 * 2), 3 / Math.sqrt(3 * 3 + 4 * 4), 4 / Math.sqrt(3 * 3 + 4 * 4) ]); const rotation = import__261.Matrix2.getRotation(matrix, new import__261.Matrix2()); expect(rotation).toEqualEpsilon(expectedRotation, import__262.Math.EPSILON14); }); it("getRotation does not modify rotation matrix", function() { const matrix = import__261.Matrix2.fromColumnMajorArray([1, 2, 3, 4]); const duplicateMatrix = import__261.Matrix2.clone(matrix, new import__261.Matrix2()); const expectedRotation = import__261.Matrix2.fromArray([ 1 / Math.sqrt(1 * 1 + 2 * 2), 2 / Math.sqrt(1 * 1 + 2 * 2), 3 / Math.sqrt(3 * 3 + 4 * 4), 4 / Math.sqrt(3 * 3 + 4 * 4) ]); const result = import__261.Matrix2.getRotation(matrix, new import__261.Matrix2()); expect(result).toEqualEpsilon(expectedRotation, import__262.Math.EPSILON14); expect(matrix).toEqual(duplicateMatrix); expect(matrix).not.toBe(result); }); it("multiply works", function() { const left = new import__261.Matrix2(1, 2, 3, 4); const right = new import__261.Matrix2(5, 6, 7, 8); const expected = new import__261.Matrix2(19, 22, 43, 50); const result = new import__261.Matrix2(); const returnedResult = import__261.Matrix2.multiply(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("multiply works with a result parameter that is an input result parameter", function() { const left = new import__261.Matrix2(1, 2, 3, 4); const right = new import__261.Matrix2(5, 6, 7, 8); const expected = new import__261.Matrix2(19, 22, 43, 50); const returnedResult = import__261.Matrix2.multiply(left, right, left); expect(returnedResult).toBe(left); expect(left).toEqual(expected); }); it("add works", function() { const left = new import__261.Matrix2(1, 2, 3, 4); const right = new import__261.Matrix2(10, 11, 12, 13); const expected = new import__261.Matrix2(11, 13, 15, 17); const result = new import__261.Matrix2(); const returnedResult = import__261.Matrix2.add(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("add works with a result parameter that is an input result parameter", function() { const left = new import__261.Matrix2(1, 2, 3, 4); const right = new import__261.Matrix2(10, 11, 12, 13); const expected = new import__261.Matrix2(11, 13, 15, 17); const returnedResult = import__261.Matrix2.add(left, right, left); expect(returnedResult).toBe(left); expect(left).toEqual(expected); }); it("subtract works", function() { const left = new import__261.Matrix2(11, 13, 15, 17); const right = new import__261.Matrix2(10, 11, 12, 13); const expected = new import__261.Matrix2(1, 2, 3, 4); const result = new import__261.Matrix2(); const returnedResult = import__261.Matrix2.subtract(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("subtract works with a result parameter that is an input result parameter", function() { const left = new import__261.Matrix2(11, 13, 15, 17); const right = new import__261.Matrix2(10, 11, 12, 13); const expected = new import__261.Matrix2(1, 2, 3, 4); const returnedResult = import__261.Matrix2.subtract(left, right, left); expect(returnedResult).toBe(left); expect(left).toEqual(expected); }); it("multiplyByScale works", function() { const m = new import__261.Matrix2(2, 3, 6, 7); const scale = new import__261.Cartesian2(2, 3); const expected = import__261.Matrix2.multiply( m, import__261.Matrix2.fromScale(scale), new import__261.Matrix2() ); const result = new import__261.Matrix2(); const returnedResult = import__261.Matrix2.multiplyByScale(m, scale, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it('multiplyByScale works with "this" result parameter', function() { const m = new import__261.Matrix2(1, 2, 5, 6); const scale = new import__261.Cartesian2(1, 2); const expected = import__261.Matrix2.multiply( m, import__261.Matrix2.fromScale(scale), new import__261.Matrix2() ); const returnedResult = import__261.Matrix2.multiplyByScale(m, scale, m); expect(returnedResult).toBe(m); expect(m).toEqual(expected); }); it("multiplyByUniformScale works", function() { const m = new import__261.Matrix2(2, 3, 4, 5); const scale = 2; const expected = import__261.Matrix2.multiply( m, import__261.Matrix2.fromUniformScale(scale), new import__261.Matrix2() ); const result = new import__261.Matrix2(); const returnedResult = import__261.Matrix2.multiplyByUniformScale(m, scale, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it('multiplyByUniformScale works with "this" result parameter', function() { const m = new import__261.Matrix2(2, 3, 4, 5); const scale = 2; const expected = import__261.Matrix2.multiply( m, import__261.Matrix2.fromUniformScale(scale), new import__261.Matrix2() ); const returnedResult = import__261.Matrix2.multiplyByUniformScale(m, scale, m); expect(returnedResult).toBe(m); expect(m).toEqual(expected); }); it("multiplyByVector works", function() { const left = new import__261.Matrix2(1, 2, 3, 4); const right = new import__261.Cartesian2(5, 6); const expected = new import__261.Cartesian2(17, 39); const result = new import__261.Cartesian2(); const returnedResult = import__261.Matrix2.multiplyByVector(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("multiplyByScalar works", function() { const left = new import__261.Matrix2(1, 2, 3, 4); const right = 2; const expected = new import__261.Matrix2(2, 4, 6, 8); const result = new import__261.Matrix2(); const returnedResult = import__261.Matrix2.multiplyByScalar(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("negate works", function() { const matrix = new import__261.Matrix2(1, 2, 3, 4); const expected = new import__261.Matrix2(-1, -2, -3, -4); const result = new import__261.Matrix2(); const returnedResult = import__261.Matrix2.negate(matrix, result); expect(result).toBe(returnedResult); expect(result).toEqual(expected); }); it("negate works with a result parameter that is an input parameter", function() { const matrix = new import__261.Matrix2(1, 2, 3, 4); const expected = new import__261.Matrix2(-1, -2, -3, -4); const returnedResult = import__261.Matrix2.negate(matrix, matrix); expect(matrix).toBe(returnedResult); expect(matrix).toEqual(expected); }); it("transpose works", function() { const matrix = new import__261.Matrix2(1, 2, 3, 4); const expected = new import__261.Matrix2(1, 3, 2, 4); const result = new import__261.Matrix2(); const returnedResult = import__261.Matrix2.transpose(matrix, result); expect(result).toBe(returnedResult); expect(result).toEqual(expected); }); it("transpose works with a result parameter that is an input result parameter", function() { const matrix = new import__261.Matrix2(1, 2, 3, 4); const expected = new import__261.Matrix2(1, 3, 2, 4); const returnedResult = import__261.Matrix2.transpose(matrix, matrix); expect(matrix).toBe(returnedResult); expect(matrix).toEqual(expected); }); it("abs works", function() { let matrix = new import__261.Matrix2(-1, -2, -3, -4); const expected = new import__261.Matrix2(1, 2, 3, 4); const result = new import__261.Matrix2(); let returnedResult = import__261.Matrix2.abs(matrix, result); expect(returnedResult).toEqual(expected); matrix = new import__261.Matrix2(1, 2, 3, 4); returnedResult = import__261.Matrix2.abs(matrix, result); expect(returnedResult).toEqual(expected); matrix = new import__261.Matrix2(1, -2, -3, 4); returnedResult = import__261.Matrix2.abs(matrix, result); expect(returnedResult).toEqual(expected); }); it("abs works with a result parameter that is an input result parameter", function() { const matrix = new import__261.Matrix2(-1, -2, -3, -4); const expected = new import__261.Matrix2(1, 2, 3, 4); const returnedResult = import__261.Matrix2.abs(matrix, matrix); expect(matrix).toBe(returnedResult); expect(matrix).toEqual(expected); }); it("equals works in all cases", function() { let left = new import__261.Matrix2(1, 2, 3, 4); let right = new import__261.Matrix2(1, 2, 3, 4); expect(import__261.Matrix2.equals(left, right)).toEqual(true); left = new import__261.Matrix2(1, 2, 3, 4); right = new import__261.Matrix2(5, 2, 3, 4); expect(import__261.Matrix2.equals(left, right)).toEqual(false); left = new import__261.Matrix2(1, 2, 3, 4); right = new import__261.Matrix2(1, 6, 3, 4); expect(import__261.Matrix2.equals(left, right)).toEqual(false); left = new import__261.Matrix2(1, 2, 3, 4); right = new import__261.Matrix2(1, 2, 7, 4); expect(import__261.Matrix2.equals(left, right)).toEqual(false); left = new import__261.Matrix2(1, 2, 3, 4); right = new import__261.Matrix2(1, 2, 3, 8); expect(import__261.Matrix2.equals(left, right)).toEqual(false); }); it("equals works with undefined", function() { expect(import__261.Matrix2.equals(void 0, void 0)).toEqual(true); expect(import__261.Matrix2.equals(new import__261.Matrix2(), void 0)).toEqual(false); expect(import__261.Matrix2.equals(void 0, new import__261.Matrix2())).toEqual(false); }); it("equalsEpsilon works in all cases", function() { let left = new import__261.Matrix2(1, 2, 3, 4); let right = new import__261.Matrix2(1, 2, 3, 4); expect(import__261.Matrix2.equalsEpsilon(left, right, 1)).toEqual(true); left = new import__261.Matrix2(1, 2, 3, 4); right = new import__261.Matrix2(5, 2, 3, 4); expect(import__261.Matrix2.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__261.Matrix2.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__261.Matrix2(1, 2, 3, 4); right = new import__261.Matrix2(1, 6, 3, 4); expect(import__261.Matrix2.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__261.Matrix2.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__261.Matrix2(1, 2, 3, 4); right = new import__261.Matrix2(1, 2, 7, 4); expect(import__261.Matrix2.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__261.Matrix2.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__261.Matrix2(1, 2, 3, 4); right = new import__261.Matrix2(1, 2, 3, 8); expect(import__261.Matrix2.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__261.Matrix2.equalsEpsilon(left, right, 4)).toEqual(true); }); it("equalsEpsilon works with undefined", function() { expect(import__261.Matrix2.equalsEpsilon(void 0, void 0, 1)).toEqual(true); expect(import__261.Matrix2.equalsEpsilon(new import__261.Matrix2(), void 0, 1)).toEqual(false); expect(import__261.Matrix2.equalsEpsilon(void 0, new import__261.Matrix2(), 1)).toEqual(false); }); it("toString", function() { const matrix = new import__261.Matrix2(1, 2, 3, 4); expect(matrix.toString()).toEqual("(1, 2)\n(3, 4)"); }); it("fromArray throws without an array", function() { expect(function() { import__261.Matrix2.fromArray(); }).toThrowDeveloperError(); }); it("fromRowMajorArray throws with undefined parameter", function() { expect(function() { import__261.Matrix2.fromRowMajorArray(void 0); }).toThrowDeveloperError(); }); it("fromColumnMajorArray throws with undefined parameter", function() { expect(function() { import__261.Matrix2.fromColumnMajorArray(void 0); }).toThrowDeveloperError(); }); it("fromScale throws without scale parameter", function() { expect(function() { import__261.Matrix2.fromScale(void 0); }).toThrowDeveloperError(); }); it("fromUniformScale throws without scale parameter", function() { expect(function() { import__261.Matrix2.fromUniformScale(void 0); }).toThrowDeveloperError(); }); it("fromRotation throws without angle", function() { expect(function() { import__261.Matrix2.fromRotation(); }).toThrowDeveloperError(); }); it("clone returns undefined without matrix parameter", function() { expect(import__261.Matrix2.clone(void 0)).toBeUndefined(); }); it("toArray throws without matrix parameter", function() { expect(function() { import__261.Matrix2.toArray(void 0); }).toThrowDeveloperError(); }); it("getColumn throws without matrix parameter", function() { expect(function() { import__261.Matrix2.getColumn(void 0, 1); }).toThrowDeveloperError(); }); it("getElement throws without row parameter", function() { let row; const col = 0; expect(function() { import__261.Matrix2.getElementIndex(col, row); }).toThrowDeveloperError(); }); it("getElement throws without column parameter", function() { const row = 0; let col; expect(function() { import__261.Matrix2.getElementIndex(col, row); }).toThrowDeveloperError(); }); it("getColumn throws with out of range index parameter", function() { const matrix = new import__261.Matrix2(); expect(function() { import__261.Matrix2.getColumn(matrix, 2); }).toThrowDeveloperError(); }); it("setColumn throws without matrix parameter", function() { const cartesian = new import__261.Cartesian2(); expect(function() { import__261.Matrix2.setColumn(void 0, 2, cartesian); }).toThrowDeveloperError(); }); it("setColumn throws without cartesian parameter", function() { const matrix = new import__261.Matrix2(); expect(function() { import__261.Matrix2.setColumn(matrix, 1, void 0); }).toThrowDeveloperError(); }); it("setColumn throws with out of range index parameter", function() { const matrix = new import__261.Matrix2(); const cartesian = new import__261.Cartesian2(); expect(function() { import__261.Matrix2.setColumn(matrix, 2, cartesian); }).toThrowDeveloperError(); }); it("getRow throws without matrix parameter", function() { expect(function() { import__261.Matrix2.getRow(void 0, 1); }).toThrowDeveloperError(); }); it("getRow throws with out of range index parameter", function() { const matrix = new import__261.Matrix2(); expect(function() { import__261.Matrix2.getRow(matrix, 2); }).toThrowDeveloperError(); }); it("setRow throws without matrix parameter", function() { const cartesian = new import__261.Cartesian2(); expect(function() { import__261.Matrix2.setRow(void 0, 2, cartesian); }).toThrowDeveloperError(); }); it("setRow throws without cartesian parameter", function() { const matrix = new import__261.Matrix2(); expect(function() { import__261.Matrix2.setRow(matrix, 1, void 0); }).toThrowDeveloperError(); }); it("setRow throws with out of range index parameter", function() { const matrix = new import__261.Matrix2(); const cartesian = new import__261.Cartesian2(); expect(function() { import__261.Matrix2.setRow(matrix, 2, cartesian); }).toThrowDeveloperError(); }); it("setScale throws without a matrix", function() { expect(function() { import__261.Matrix2.setScale(); }).toThrowDeveloperError(); }); it("setScale throws without a scale", function() { expect(function() { import__261.Matrix2.setScale(new import__261.Matrix2()); }).toThrowDeveloperError(); }); it("setUniformScale throws without a matrix", function() { expect(function() { import__261.Matrix2.setUniformScale(); }).toThrowDeveloperError(); }); it("setUniformScale throws without a scale", function() { expect(function() { import__261.Matrix2.setUniformScale(new import__261.Matrix2()); }).toThrowDeveloperError(); }); it("getScale throws without a matrix", function() { expect(function() { import__261.Matrix2.getScale(); }).toThrowDeveloperError(); }); it("getMaximumScale throws without a matrix", function() { expect(function() { import__261.Matrix2.getMaximumScale(); }).toThrowDeveloperError(); }); it("setRotation throws without a matrix", function() { expect(function() { return import__261.Matrix2.setRotation(); }).toThrowDeveloperError(); }); it("setRotation throws without a rotation", function() { expect(function() { return import__261.Matrix2.setRotation(new import__261.Matrix2()); }).toThrowDeveloperError(); }); it("getRotation throws without a matrix", function() { expect(function() { return import__261.Matrix2.getRotation(); }).toThrowDeveloperError(); }); it("multiply throws with no left parameter", function() { const right = new import__261.Matrix2(); expect(function() { import__261.Matrix2.multiply(void 0, right); }).toThrowDeveloperError(); }); it("multiply throws with no right parameter", function() { const left = new import__261.Matrix2(); expect(function() { import__261.Matrix2.multiply(left, void 0); }).toThrowDeveloperError(); }); it("multiplyByScale throws with no matrix parameter", function() { expect(function() { import__261.Matrix2.multiplyByScale(void 0, new import__261.Cartesian2()); }).toThrowDeveloperError(); }); it("multiplyByScale throws with no scale parameter", function() { const m = new import__261.Matrix2(); expect(function() { import__261.Matrix2.multiplyByScale(m, void 0); }).toThrowDeveloperError(); }); it("multiplyByUniformScale throws with no matrix parameter", function() { expect(function() { import__261.Matrix2.multiplyByUniformScale(void 0, new import__261.Cartesian2()); }).toThrowDeveloperError(); }); it("multiplyByUniformScale throws with no scale parameter", function() { const m = new import__261.Matrix2(); expect(function() { import__261.Matrix2.multiplyByUniformScale(m, void 0); }).toThrowDeveloperError(); }); it("multiplyByVector throws with no matrix parameter", function() { const cartesian = new import__261.Cartesian2(); expect(function() { import__261.Matrix2.multiplyByVector(void 0, cartesian); }).toThrowDeveloperError(); }); it("multiplyByVector throws with no cartesian parameter", function() { const matrix = new import__261.Matrix2(); expect(function() { import__261.Matrix2.multiplyByVector(matrix, void 0); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with no matrix parameter", function() { expect(function() { import__261.Matrix2.multiplyByScalar(void 0, 2); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with non-numeric scalar parameter", function() { const matrix = new import__261.Matrix2(); expect(function() { import__261.Matrix2.multiplyByScalar(matrix, {}); }).toThrowDeveloperError(); }); it("negate throws with matrix parameter", function() { expect(function() { import__261.Matrix2.negate(void 0); }).toThrowDeveloperError(); }); it("transpose throws with matrix parameter", function() { expect(function() { import__261.Matrix2.transpose(void 0); }).toThrowDeveloperError(); }); it("abs throws without a matrix", function() { expect(function() { return import__261.Matrix2.abs(); }).toThrowDeveloperError(); }); it("getColumn throws without a result parameter", function() { expect(function() { import__261.Matrix2.getColumn(new import__261.Matrix2(), 1); }).toThrowDeveloperError(); }); it("setColumn throws without a result parameter", function() { expect(function() { import__261.Matrix2.setColumn(new import__261.Matrix2(), 1, new import__261.Cartesian2()); }).toThrowDeveloperError(); }); it("getRow throws without a result parameter", function() { expect(function() { import__261.Matrix2.getRow(new import__261.Matrix2(), 1); }).toThrowDeveloperError(); }); it("setRow throws without a result parameter", function() { expect(function() { import__261.Matrix2.setRow(new import__261.Matrix2(), 1, new import__261.Cartesian2()); }).toThrowDeveloperError(); }); it("setScale throws without a result parameter", function() { expect(function() { import__261.Matrix2.setScale(new import__261.Matrix2(), new import__261.Cartesian2()); }).toThrowDeveloperError(); }); it("setUniformScale throws without a result parameter", function() { expect(function() { import__261.Matrix2.setUniformScale(new import__261.Matrix2(), 1); }).toThrowDeveloperError(); }); it("getScale throws without a result parameter", function() { expect(function() { import__261.Matrix2.getScale(new import__261.Matrix2()); }).toThrowDeveloperError(); }); it("setRotation throws without a result parameter", function() { expect(function() { return import__261.Matrix2.setRotation(new import__261.Matrix2(), new import__261.Matrix2()); }).toThrowDeveloperError(); }); it("getRotation throws without a result parameter", function() { expect(function() { return import__261.Matrix2.getRotation(new import__261.Matrix2()); }).toThrowDeveloperError(); }); it("multiply throws without a result parameter", function() { expect(function() { import__261.Matrix2.multiply(new import__261.Matrix2(), new import__261.Matrix2()); }).toThrowDeveloperError(); }); it("multiplyByScale throws without a result parameter", function() { expect(function() { import__261.Matrix2.multiplyByScale(new import__261.Matrix2(), new import__261.Cartesian2()); }).toThrowDeveloperError(); }); it("multiplyByUniformScale throws without a result parameter", function() { expect(function() { import__261.Matrix2.multiplyByUniformScale(new import__261.Matrix2(), new import__261.Cartesian2()); }).toThrowDeveloperError(); }); it("multiplyByVector throws without a result parameter", function() { expect(function() { import__261.Matrix2.multiplyByVector(new import__261.Matrix2(), new import__261.Cartesian2()); }).toThrowDeveloperError(); }); it("multiplyByScalar throws without a result parameter", function() { expect(function() { import__261.Matrix2.multiplyByScalar(new import__261.Matrix2(), 2); }).toThrowDeveloperError(); }); it("negate throws without a result parameter", function() { expect(function() { import__261.Matrix2.negate(new import__261.Matrix2()); }).toThrowDeveloperError(); }); it("transpose throws without a result parameter", function() { expect(function() { import__261.Matrix2.transpose(new import__261.Matrix2()); }).toThrowDeveloperError(); }); it("abs throws without a result parameter", function() { expect(function() { import__261.Matrix2.abs(new import__261.Matrix2()); }).toThrowDeveloperError(); }); it("Matrix2 objects can be used as array like objects", function() { const matrix = new import__261.Matrix2(1, 3, 2, 4); expect(matrix.length).toEqual(4); const intArray = new Uint32Array(matrix.length); intArray.set(matrix); for (let index = 0; index < matrix.length; index++) { expect(intArray[index]).toEqual(index + 1); } }); createPackableSpecs_default(import__261.Matrix2, new import__261.Matrix2(0, -1, 1, 0), [0, 1, -1, 0]); createPackableArraySpecs_default( import__261.Matrix2, [ new import__261.Matrix2(1, 0, 0, 1), new import__261.Matrix2(1, 2, 3, 4), new import__261.Matrix2(0, 1, -1, 0) ], [1, 0, 0, 1, 1, 3, 2, 4, 0, -1, 1, 0], 4 ); }); // packages/engine/Specs/Core/Matrix3Spec.js var import__263 = __toESM(require_Cesium(), 1); var import__264 = __toESM(require_Cesium(), 1); describe("Core/Matrix3", function() { it("default constructor creates values array with all zeros.", function() { const matrix = new import__263.Matrix3(); expect(matrix[import__263.Matrix3.COLUMN0ROW0]).toEqual(0); expect(matrix[import__263.Matrix3.COLUMN1ROW0]).toEqual(0); expect(matrix[import__263.Matrix3.COLUMN2ROW0]).toEqual(0); expect(matrix[import__263.Matrix3.COLUMN0ROW1]).toEqual(0); expect(matrix[import__263.Matrix3.COLUMN1ROW1]).toEqual(0); expect(matrix[import__263.Matrix3.COLUMN2ROW1]).toEqual(0); expect(matrix[import__263.Matrix3.COLUMN0ROW2]).toEqual(0); expect(matrix[import__263.Matrix3.COLUMN1ROW2]).toEqual(0); expect(matrix[import__263.Matrix3.COLUMN2ROW2]).toEqual(0); }); it("constructor sets properties from parameters.", function() { const matrix = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); expect(matrix[import__263.Matrix3.COLUMN0ROW0]).toEqual(1); expect(matrix[import__263.Matrix3.COLUMN1ROW0]).toEqual(2); expect(matrix[import__263.Matrix3.COLUMN2ROW0]).toEqual(3); expect(matrix[import__263.Matrix3.COLUMN0ROW1]).toEqual(4); expect(matrix[import__263.Matrix3.COLUMN1ROW1]).toEqual(5); expect(matrix[import__263.Matrix3.COLUMN2ROW1]).toEqual(6); expect(matrix[import__263.Matrix3.COLUMN0ROW2]).toEqual(7); expect(matrix[import__263.Matrix3.COLUMN1ROW2]).toEqual(8); expect(matrix[import__263.Matrix3.COLUMN2ROW2]).toEqual(9); }); it("fromQuaternion works without a result parameter", function() { const sPiOver4 = Math.sin(import__264.Math.PI_OVER_FOUR); const cPiOver4 = Math.cos(import__264.Math.PI_OVER_FOUR); const sPiOver2 = Math.sin(import__264.Math.PI_OVER_TWO); const cPiOver2 = Math.cos(import__264.Math.PI_OVER_TWO); const tmp = import__263.Cartesian3.multiplyByScalar( new import__263.Cartesian3(0, 0, 1), sPiOver4, new import__263.Cartesian3() ); const quaternion = new import__263.Quaternion(tmp.x, tmp.y, tmp.z, cPiOver4); const expected = new import__263.Matrix3( cPiOver2, -sPiOver2, 0, sPiOver2, cPiOver2, 0, 0, 0, 1 ); const returnedResult = import__263.Matrix3.fromQuaternion(quaternion); expect(returnedResult).toEqualEpsilon(expected, import__264.Math.EPSILON15); }); it("fromQuaternion works with a result parameter", function() { const sPiOver4 = Math.sin(import__264.Math.PI_OVER_FOUR); const cPiOver4 = Math.cos(import__264.Math.PI_OVER_FOUR); const sPiOver2 = Math.sin(import__264.Math.PI_OVER_TWO); const cPiOver2 = Math.cos(import__264.Math.PI_OVER_TWO); const tmp = import__263.Cartesian3.multiplyByScalar( new import__263.Cartesian3(0, 0, 1), sPiOver4, new import__263.Cartesian3() ); const quaternion = new import__263.Quaternion(tmp.x, tmp.y, tmp.z, cPiOver4); const expected = new import__263.Matrix3( cPiOver2, -sPiOver2, 0, sPiOver2, cPiOver2, 0, 0, 0, 1 ); const result = new import__263.Matrix3(); const returnedResult = import__263.Matrix3.fromQuaternion(quaternion, result); expect(result).toBe(returnedResult); expect(returnedResult).toEqualEpsilon(expected, import__264.Math.EPSILON15); }); it("fromHeadingPitchRoll works without a result parameter", function() { const sPiOver4 = Math.sin(import__264.Math.PI_OVER_FOUR); const cPiOver4 = Math.cos(import__264.Math.PI_OVER_FOUR); const sPiOver2 = Math.sin(import__264.Math.PI_OVER_TWO); const cPiOver2 = Math.cos(import__264.Math.PI_OVER_TWO); const tmp = import__263.Cartesian3.multiplyByScalar( new import__263.Cartesian3(0, 0, 1), sPiOver4, new import__263.Cartesian3() ); const quaternion = new import__263.Quaternion(tmp.x, tmp.y, tmp.z, cPiOver4); const headingPitchRoll = import__263.HeadingPitchRoll.fromQuaternion(quaternion); const expected = new import__263.Matrix3( cPiOver2, -sPiOver2, 0, sPiOver2, cPiOver2, 0, 0, 0, 1 ); const returnedResult = import__263.Matrix3.fromHeadingPitchRoll(headingPitchRoll); expect(returnedResult).toEqualEpsilon(expected, import__264.Math.EPSILON15); }); it("fromHeadingPitchRoll works with a result parameter", function() { const sPiOver4 = Math.sin(import__264.Math.PI_OVER_FOUR); const cPiOver4 = Math.cos(import__264.Math.PI_OVER_FOUR); const sPiOver2 = Math.sin(import__264.Math.PI_OVER_TWO); const cPiOver2 = Math.cos(import__264.Math.PI_OVER_TWO); const tmp = import__263.Cartesian3.multiplyByScalar( new import__263.Cartesian3(0, 0, 1), sPiOver4, new import__263.Cartesian3() ); const quaternion = new import__263.Quaternion(tmp.x, tmp.y, tmp.z, cPiOver4); const headingPitchRoll = import__263.HeadingPitchRoll.fromQuaternion(quaternion); const expected = new import__263.Matrix3( cPiOver2, -sPiOver2, 0, sPiOver2, cPiOver2, 0, 0, 0, 1 ); const result = new import__263.Matrix3(); const returnedResult = import__263.Matrix3.fromHeadingPitchRoll( headingPitchRoll, result ); expect(result).toBe(returnedResult); expect(returnedResult).toEqualEpsilon(expected, import__264.Math.EPSILON15); }); it("fromHeadingPitchRoll computed correctly", function() { const expected = new import__263.Matrix3( 0.754406506735489, 0.418940943945763, 0.505330889696038, 0.133022221559489, 0.656295369162553, -0.742685314912828, -0.642787609686539, 0.627506871597133, 0.439385041770705 ); const headingPitchRoll = new import__263.HeadingPitchRoll( -import__264.Math.toRadians(10), -import__264.Math.toRadians(40), import__264.Math.toRadians(55) ); const result = new import__263.Matrix3(); const returnedResult = import__263.Matrix3.fromHeadingPitchRoll( headingPitchRoll, result ); expect(result).toBe(returnedResult); expect(returnedResult).toEqualEpsilon(expected, import__264.Math.EPSILON15); }); it("fromScale works without a result parameter", function() { const expected = new import__263.Matrix3(7, 0, 0, 0, 8, 0, 0, 0, 9); const returnedResult = import__263.Matrix3.fromScale(new import__263.Cartesian3(7, 8, 9)); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("fromScale works with a result parameter", function() { const expected = new import__263.Matrix3(7, 0, 0, 0, 8, 0, 0, 0, 9); const result = new import__263.Matrix3(); const returnedResult = import__263.Matrix3.fromScale( new import__263.Cartesian3(7, 8, 9), result ); expect(returnedResult).toBe(result); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("fromUniformScale works without a result parameter", function() { const expected = new import__263.Matrix3(2, 0, 0, 0, 2, 0, 0, 0, 2); const returnedResult = import__263.Matrix3.fromUniformScale(2); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("fromUniformScale works with a result parameter", function() { const expected = new import__263.Matrix3(2, 0, 0, 0, 2, 0, 0, 0, 2); const result = new import__263.Matrix3(); const returnedResult = import__263.Matrix3.fromUniformScale(2, result); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expected); }); it("fromCrossProduct works without a result parameter", function() { const expected = new import__263.Matrix3( 0, -3, -2, 3, 0, -1, 2, 1, 0 ); const left = new import__263.Cartesian3(1, -2, 3); const returnedResult = import__263.Matrix3.fromCrossProduct(left); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); const right = new import__263.Cartesian3(2, 3, 4); const crossProductExpected = new import__263.Cartesian3(-17, 2, 7); let crossProductResult = new import__263.Cartesian3(); crossProductResult = import__263.Cartesian3.cross(left, right, crossProductResult); expect(crossProductResult).toEqual(crossProductExpected); crossProductResult = import__263.Matrix3.multiply( returnedResult, right, crossProductResult ); expect(crossProductResult).toEqual(crossProductExpected); }); it("fromCrossProduct works with a result parameter", function() { const expected = new import__263.Matrix3( 0, -3, -2, 3, 0, -1, 2, 1, 0 ); const left = new import__263.Cartesian3(1, -2, 3); const result = new import__263.Matrix3(); const returnedResult = import__263.Matrix3.fromCrossProduct(left, result); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expected); const right = new import__263.Cartesian3(2, 3, 4); const crossProductExpected = new import__263.Cartesian3(-17, 2, 7); let crossProductResult = new import__263.Cartesian3(); crossProductResult = import__263.Cartesian3.cross(left, right, crossProductResult); expect(crossProductResult).toEqual(crossProductExpected); crossProductResult = import__263.Matrix3.multiply( returnedResult, right, crossProductResult ); expect(crossProductResult).toEqual(crossProductExpected); }); it("fromArray works without a result parameter", function() { const expected = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const matrix = import__263.Matrix3.fromArray([ 1, 4, 7, 2, 5, 8, 3, 6, 9 ]); expect(matrix).toEqual(expected); }); it("fromArray works with a result parameter", function() { const expected = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const result = new import__263.Matrix3(); const matrix = import__263.Matrix3.fromArray( [1, 4, 7, 2, 5, 8, 3, 6, 9], 0, result ); expect(matrix).toBe(result); expect(matrix).toEqual(expected); }); it("fromArray works with an offset", function() { const expected = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const result = new import__263.Matrix3(); const matrix = import__263.Matrix3.fromArray( [0, 0, 0, 1, 4, 7, 2, 5, 8, 3, 6, 9], 3, result ); expect(matrix).toBe(result); expect(matrix).toEqual(expected); }); it("fromRowMajorArray works without a result parameter", function() { const expected = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const matrix = import__263.Matrix3.fromRowMajorArray([ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]); expect(matrix).toEqual(expected); }); it("fromRowMajorArray works with a result parameter", function() { const expected = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const result = new import__263.Matrix3(); const matrix = import__263.Matrix3.fromRowMajorArray( [1, 2, 3, 4, 5, 6, 7, 8, 9], result ); expect(matrix).toBe(result); expect(matrix).toEqual(expected); }); it("fromColumnMajorArray works without a result parameter", function() { const expected = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const matrix = import__263.Matrix3.fromColumnMajorArray([ 1, 4, 7, 2, 5, 8, 3, 6, 9 ]); expect(matrix).toEqual(expected); }); it("fromColumnMajorArray works with a result parameter", function() { const expected = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const result = new import__263.Matrix3(); const matrix = import__263.Matrix3.fromColumnMajorArray( [1, 4, 7, 2, 5, 8, 3, 6, 9], result ); expect(matrix).toBe(result); expect(matrix).toEqual(expected); }); it("fromRotationX works without a result parameter", function() { const matrix = import__263.Matrix3.fromRotationX(0); expect(matrix).toEqual(import__263.Matrix3.IDENTITY); }); it("fromRotationX works with a result parameter", function() { const expected = new import__263.Matrix3(1, 0, 0, 0, 0, -1, 0, 1, 0); const result = new import__263.Matrix3(); const matrix = import__263.Matrix3.fromRotationX(import__264.Math.toRadians(90), result); expect(matrix).toBe(result); expect(matrix).toEqualEpsilon(expected, import__264.Math.EPSILON15); }); it("fromRotationY works without a result parameter", function() { const matrix = import__263.Matrix3.fromRotationY(0); expect(matrix).toEqual(import__263.Matrix3.IDENTITY); }); it("fromRotationY works with a result parameter", function() { const expected = new import__263.Matrix3(0, 0, 1, 0, 1, 0, -1, 0, 0); const result = new import__263.Matrix3(); const matrix = import__263.Matrix3.fromRotationY(import__264.Math.toRadians(90), result); expect(matrix).toBe(result); expect(matrix).toEqualEpsilon(expected, import__264.Math.EPSILON15); }); it("fromRotationZ works without a result parameter", function() { const matrix = import__263.Matrix3.fromRotationZ(0); expect(matrix).toEqual(import__263.Matrix3.IDENTITY); }); it("fromRotationZ works with a result parameter", function() { const expected = new import__263.Matrix3(0, -1, 0, 1, 0, 0, 0, 0, 1); const result = new import__263.Matrix3(); const matrix = import__263.Matrix3.fromRotationZ(import__264.Math.toRadians(90), result); expect(matrix).toBe(result); expect(matrix).toEqualEpsilon(expected, import__264.Math.EPSILON15); }); it("clone works without a result parameter", function() { const expected = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const returnedResult = expected.clone(); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("clone works with a result parameter", function() { const expected = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const result = new import__263.Matrix3(); const returnedResult = expected.clone(result); expect(returnedResult).toBe(result); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("toArray works without a result parameter", function() { const expected = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const returnedResult = import__263.Matrix3.toArray( import__263.Matrix3.fromColumnMajorArray(expected) ); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("toArray works with a result parameter", function() { const expected = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const result = []; const returnedResult = import__263.Matrix3.toArray( import__263.Matrix3.fromColumnMajorArray(expected), result ); expect(returnedResult).toBe(result); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("getElementIndex works", function() { let i = 0; for (let col = 0; col < 3; col++) { for (let row = 0; row < 3; row++) { const index = import__263.Matrix3.getElementIndex(col, row); expect(index).toEqual(i); i++; } } }); it("getColumn works", function() { const matrix = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const expectedColumn0 = new import__263.Cartesian3(1, 4, 7); const expectedColumn1 = new import__263.Cartesian3(2, 5, 8); const expectedColumn2 = new import__263.Cartesian3(3, 6, 9); const resultColumn0 = new import__263.Cartesian3(); const resultColumn1 = new import__263.Cartesian3(); const resultColumn2 = new import__263.Cartesian3(); const returnedResultColumn0 = import__263.Matrix3.getColumn(matrix, 0, resultColumn0); const returnedResultColumn1 = import__263.Matrix3.getColumn(matrix, 1, resultColumn1); const returnedResultColumn2 = import__263.Matrix3.getColumn(matrix, 2, resultColumn2); expect(resultColumn0).toBe(returnedResultColumn0); expect(resultColumn0).toEqual(expectedColumn0); expect(resultColumn1).toBe(returnedResultColumn1); expect(resultColumn1).toEqual(expectedColumn1); expect(resultColumn2).toBe(returnedResultColumn2); expect(resultColumn2).toEqual(expectedColumn2); }); it("setColumn works", function() { const matrix = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const result = new import__263.Matrix3(); let expected = new import__263.Matrix3(10, 2, 3, 11, 5, 6, 12, 8, 9); let returnedResult = import__263.Matrix3.setColumn( matrix, 0, new import__263.Cartesian3(10, 11, 12), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); expected = new import__263.Matrix3(1, 13, 3, 4, 14, 6, 7, 15, 9); returnedResult = import__263.Matrix3.setColumn( matrix, 1, new import__263.Cartesian3(13, 14, 15), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); expected = new import__263.Matrix3(1, 2, 16, 4, 5, 17, 7, 8, 18); returnedResult = import__263.Matrix3.setColumn( matrix, 2, new import__263.Cartesian3(16, 17, 18), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); }); it("getRow works", function() { const matrix = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const expectedRow0 = new import__263.Cartesian3(1, 2, 3); const expectedRow1 = new import__263.Cartesian3(4, 5, 6); const expectedRow2 = new import__263.Cartesian3(7, 8, 9); const resultRow0 = new import__263.Cartesian3(); const resultRow1 = new import__263.Cartesian3(); const resultRow2 = new import__263.Cartesian3(); const returnedResultRow0 = import__263.Matrix3.getRow(matrix, 0, resultRow0); const returnedResultRow1 = import__263.Matrix3.getRow(matrix, 1, resultRow1); const returnedResultRow2 = import__263.Matrix3.getRow(matrix, 2, resultRow2); expect(resultRow0).toBe(returnedResultRow0); expect(resultRow0).toEqual(expectedRow0); expect(resultRow1).toBe(returnedResultRow1); expect(resultRow1).toEqual(expectedRow1); expect(resultRow2).toBe(returnedResultRow2); expect(resultRow2).toEqual(expectedRow2); }); it("setRow works", function() { const matrix = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const result = new import__263.Matrix3(); let expected = new import__263.Matrix3(10, 11, 12, 4, 5, 6, 7, 8, 9); let returnedResult = import__263.Matrix3.setRow( matrix, 0, new import__263.Cartesian3(10, 11, 12), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); expected = new import__263.Matrix3(1, 2, 3, 13, 14, 15, 7, 8, 9); returnedResult = import__263.Matrix3.setRow( matrix, 1, new import__263.Cartesian3(13, 14, 15), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); expected = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 16, 17, 18); returnedResult = import__263.Matrix3.setRow( matrix, 2, new import__263.Cartesian3(16, 17, 18), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); }); it("setScale works", function() { const oldScale = new import__263.Cartesian3(2, 3, 4); const newScale = new import__263.Cartesian3(5, 6, 7); const matrix = import__263.Matrix3.fromScale(oldScale, new import__263.Matrix3()); const result = new import__263.Matrix3(); expect(import__263.Matrix3.getScale(matrix, new import__263.Cartesian3())).toEqual(oldScale); const returnedResult = import__263.Matrix3.setScale(matrix, newScale, result); expect(import__263.Matrix3.getScale(returnedResult, new import__263.Cartesian3())).toEqual( newScale ); expect(result).toBe(returnedResult); }); it("setUniformScale works", function() { const oldScale = new import__263.Cartesian3(2, 3, 4); const newScale = 5; const matrix = import__263.Matrix3.fromScale(oldScale, new import__263.Matrix3()); const result = new import__263.Matrix3(); expect(import__263.Matrix3.getScale(matrix, new import__263.Cartesian3())).toEqual(oldScale); const returnedResult = import__263.Matrix3.setUniformScale(matrix, newScale, result); expect(import__263.Matrix3.getScale(returnedResult, new import__263.Cartesian3())).toEqual( new import__263.Cartesian3(newScale, newScale, newScale) ); expect(result).toBe(returnedResult); }); it("getScale works", function() { const scale = new import__263.Cartesian3(2, 3, 4); const result = new import__263.Cartesian3(); const computedScale = import__263.Matrix3.getScale(import__263.Matrix3.fromScale(scale), result); expect(computedScale).toBe(result); expect(computedScale).toEqualEpsilon(scale, import__264.Math.EPSILON14); }); it("getMaximumScale works", function() { const m = import__263.Matrix3.fromScale(new import__263.Cartesian3(2, 3, 4)); expect(import__263.Matrix3.getMaximumScale(m)).toEqualEpsilon( 4, import__264.Math.EPSILON14 ); }); it("setRotation works", function() { const scaleVec = new import__263.Cartesian3(2, 3, 4); const scale = import__263.Matrix3.fromScale(scaleVec, new import__263.Matrix3()); const rotation = import__263.Matrix3.fromRotationX(0.5, new import__263.Matrix3()); const scaleRotation = import__263.Matrix3.setRotation(scale, rotation, new import__263.Matrix3()); const extractedScale = import__263.Matrix3.getScale(scaleRotation, new import__263.Cartesian3()); const extractedRotation = import__263.Matrix3.getRotation(scaleRotation, new import__263.Matrix3()); expect(extractedScale).toEqualEpsilon(scaleVec, import__264.Math.EPSILON14); expect(extractedRotation).toEqualEpsilon(rotation, import__264.Math.EPSILON14); }); it("getRotation returns matrix without scale", function() { const matrix = import__263.Matrix3.fromColumnMajorArray([ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]); const expectedRotation = import__263.Matrix3.fromArray([ 1 / Math.sqrt(1 * 1 + 2 * 2 + 3 * 3), 2 / Math.sqrt(1 * 1 + 2 * 2 + 3 * 3), 3 / Math.sqrt(1 * 1 + 2 * 2 + 3 * 3), 4 / Math.sqrt(4 * 4 + 5 * 5 + 6 * 6), 5 / Math.sqrt(4 * 4 + 5 * 5 + 6 * 6), 6 / Math.sqrt(4 * 4 + 5 * 5 + 6 * 6), 7 / Math.sqrt(7 * 7 + 8 * 8 + 9 * 9), 8 / Math.sqrt(7 * 7 + 8 * 8 + 9 * 9), 9 / Math.sqrt(7 * 7 + 8 * 8 + 9 * 9) ]); const rotation = import__263.Matrix3.getRotation(matrix, new import__263.Matrix3()); expect(rotation).toEqualEpsilon(expectedRotation, import__264.Math.EPSILON14); }); it("getRotation does not modify rotation matrix", function() { const matrix = import__263.Matrix3.fromColumnMajorArray([ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]); const duplicateMatrix = import__263.Matrix3.clone(matrix, new import__263.Matrix3()); const expectedRotation = import__263.Matrix3.fromArray([ 1 / Math.sqrt(1 * 1 + 2 * 2 + 3 * 3), 2 / Math.sqrt(1 * 1 + 2 * 2 + 3 * 3), 3 / Math.sqrt(1 * 1 + 2 * 2 + 3 * 3), 4 / Math.sqrt(4 * 4 + 5 * 5 + 6 * 6), 5 / Math.sqrt(4 * 4 + 5 * 5 + 6 * 6), 6 / Math.sqrt(4 * 4 + 5 * 5 + 6 * 6), 7 / Math.sqrt(7 * 7 + 8 * 8 + 9 * 9), 8 / Math.sqrt(7 * 7 + 8 * 8 + 9 * 9), 9 / Math.sqrt(7 * 7 + 8 * 8 + 9 * 9) ]); const result = import__263.Matrix3.getRotation(matrix, new import__263.Matrix3()); expect(result).toEqualEpsilon(expectedRotation, import__264.Math.EPSILON14); expect(matrix).toEqual(duplicateMatrix); expect(matrix).not.toBe(result); }); it("multiply works", function() { const left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const right = new import__263.Matrix3(10, 11, 12, 13, 14, 15, 16, 17, 18); const expected = new import__263.Matrix3(84, 90, 96, 201, 216, 231, 318, 342, 366); const result = new import__263.Matrix3(); const returnedResult = import__263.Matrix3.multiply(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("multiply works with a result parameter that is an input result parameter", function() { const left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const right = new import__263.Matrix3(10, 11, 12, 13, 14, 15, 16, 17, 18); const expected = new import__263.Matrix3(84, 90, 96, 201, 216, 231, 318, 342, 366); const returnedResult = import__263.Matrix3.multiply(left, right, left); expect(returnedResult).toBe(left); expect(left).toEqual(expected); }); it("add works", function() { const left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const right = new import__263.Matrix3(10, 11, 12, 13, 14, 15, 16, 17, 18); const expected = new import__263.Matrix3(11, 13, 15, 17, 19, 21, 23, 25, 27); const result = new import__263.Matrix3(); const returnedResult = import__263.Matrix3.add(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("add works with a result parameter that is an input result parameter", function() { const left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const right = new import__263.Matrix3(10, 11, 12, 13, 14, 15, 16, 17, 18); const expected = new import__263.Matrix3(11, 13, 15, 17, 19, 21, 23, 25, 27); const returnedResult = import__263.Matrix3.add(left, right, left); expect(returnedResult).toBe(left); expect(left).toEqual(expected); }); it("subtract works", function() { const left = new import__263.Matrix3(11, 13, 15, 17, 19, 21, 23, 25, 27); const right = new import__263.Matrix3(10, 11, 12, 13, 14, 15, 16, 17, 18); const expected = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const result = new import__263.Matrix3(); const returnedResult = import__263.Matrix3.subtract(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("subtract works with a result parameter that is an input result parameter", function() { const left = new import__263.Matrix3(11, 13, 15, 17, 19, 21, 23, 25, 27); const right = new import__263.Matrix3(10, 11, 12, 13, 14, 15, 16, 17, 18); const expected = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const returnedResult = import__263.Matrix3.subtract(left, right, left); expect(returnedResult).toBe(left); expect(left).toEqual(expected); }); it("multiplyByScale works", function() { const m = new import__263.Matrix3(2, 3, 4, 6, 7, 8, 10, 11, 12); const scale = new import__263.Cartesian3(2, 3, 4); const expected = import__263.Matrix3.multiply( m, import__263.Matrix3.fromScale(scale), new import__263.Matrix3() ); const result = new import__263.Matrix3(); const returnedResult = import__263.Matrix3.multiplyByScale(m, scale, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it('multiplyByScale works with "this" result parameter', function() { const m = new import__263.Matrix3(1, 2, 3, 5, 6, 7, 9, 10, 11); const scale = new import__263.Cartesian3(1, 2, 3); const expected = import__263.Matrix3.multiply( m, import__263.Matrix3.fromScale(scale), new import__263.Matrix3() ); const returnedResult = import__263.Matrix3.multiplyByScale(m, scale, m); expect(returnedResult).toBe(m); expect(m).toEqual(expected); }); it("multiplyByUniformScale works", function() { const m = new import__263.Matrix3(2, 3, 4, 5, 6, 7, 8, 9, 10); const scale = 2; const expected = import__263.Matrix3.multiply( m, import__263.Matrix3.fromUniformScale(scale), new import__263.Matrix3() ); const result = new import__263.Matrix3(); const returnedResult = import__263.Matrix3.multiplyByUniformScale(m, scale, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it('multiplyByUniformScale works with "this" result parameter', function() { const m = new import__263.Matrix3(2, 3, 4, 5, 6, 7, 8, 9, 10); const scale = 2; const expected = import__263.Matrix3.multiply( m, import__263.Matrix3.fromUniformScale(scale), new import__263.Matrix3() ); const returnedResult = import__263.Matrix3.multiplyByUniformScale(m, scale, m); expect(returnedResult).toBe(m); expect(m).toEqual(expected); }); it("multiplyByVector works", function() { const left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const right = new import__263.Cartesian3(10, 11, 12); const expected = new import__263.Cartesian3(68, 167, 266); const result = new import__263.Cartesian3(); const returnedResult = import__263.Matrix3.multiplyByVector(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("multiplyByScalar works", function() { const left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const right = 2; const expected = new import__263.Matrix3(2, 4, 6, 8, 10, 12, 14, 16, 18); const result = new import__263.Matrix3(); const returnedResult = import__263.Matrix3.multiplyByScalar(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("negate works", function() { const matrix = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const expected = new import__263.Matrix3( -1, -2, -3, -4, -5, -6, -7, -8, -9 ); const result = new import__263.Matrix3(); const returnedResult = import__263.Matrix3.negate(matrix, result); expect(result).toBe(returnedResult); expect(result).toEqual(expected); }); it("negate works with a result parameter that is an input result parameter", function() { const matrix = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const expected = new import__263.Matrix3( -1, -2, -3, -4, -5, -6, -7, -8, -9 ); const returnedResult = import__263.Matrix3.negate(matrix, matrix); expect(matrix).toBe(returnedResult); expect(matrix).toEqual(expected); }); it("transpose works", function() { const matrix = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const expected = new import__263.Matrix3(1, 4, 7, 2, 5, 8, 3, 6, 9); const result = new import__263.Matrix3(); const returnedResult = import__263.Matrix3.transpose(matrix, result); expect(result).toBe(returnedResult); expect(result).toEqual(expected); }); it("inverseTranspose works", function() { const matrix = new import__263.Matrix3(1, 5, 2, 1, 1, 7, 0, -3, 4); const expectedInverse = import__263.Matrix3.inverse(matrix, new import__263.Matrix3()); const expectedInverseTranspose = import__263.Matrix3.transpose( expectedInverse, new import__263.Matrix3() ); const result = import__263.Matrix3.inverseTranspose(matrix, new import__263.Matrix3()); expect(result).toEqual(expectedInverseTranspose); }); it("transpose works with a result parameter that is an input result parameter", function() { const matrix = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const expected = new import__263.Matrix3(1, 4, 7, 2, 5, 8, 3, 6, 9); const returnedResult = import__263.Matrix3.transpose(matrix, matrix); expect(matrix).toBe(returnedResult); expect(matrix).toEqual(expected); }); it("determinant works", function() { const matrix = new import__263.Matrix3(1, 5, 2, 1, 1, 7, 0, -3, 4); const expected = -1; const result = import__263.Matrix3.determinant(matrix); expect(result).toEqual(expected); }); it("inverse works", function() { const matrix = new import__263.Matrix3(1, 5, 2, 1, 1, 7, 0, -3, 4); const expected = new import__263.Matrix3( -25, 26, -33, 4, -4, 5, 3, -3, 4 ); const result = new import__263.Matrix3(); const returnedResult = import__263.Matrix3.inverse(matrix, result); expect(result).toBe(returnedResult); expect(result).toEqual(expected); }); it("inverse works with a result parameter that is an input result parameter", function() { const matrix = new import__263.Matrix3(1, 5, 2, 1, 1, 7, 0, -3, 4); const expected = new import__263.Matrix3( -25, 26, -33, 4, -4, 5, 3, -3, 4 ); const returnedResult = import__263.Matrix3.inverse(matrix, matrix); expect(matrix).toBe(returnedResult); expect(matrix).toEqual(expected); }); it("computes eigenvalues and eigenvectors", function() { const a = new import__263.Matrix3(4, -1, 1, -1, 3, -2, 1, -2, 3); const expectedDiagonal = new import__263.Matrix3( 3, 0, 0, 0, 6, 0, 0, 0, 1 ); const decomposition = import__263.Matrix3.computeEigenDecomposition(a); expect(decomposition.diagonal).toEqualEpsilon( expectedDiagonal, import__264.Math.EPSILON14 ); let v = import__263.Matrix3.getColumn(decomposition.unitary, 0, new import__263.Cartesian3()); let lambda = import__263.Matrix3.getColumn(decomposition.diagonal, 0, new import__263.Cartesian3()).x; expect( import__263.Cartesian3.multiplyByScalar(v, lambda, new import__263.Cartesian3()) ).toEqualEpsilon( import__263.Matrix3.multiplyByVector(a, v, new import__263.Cartesian3()), import__264.Math.EPSILON14 ); v = import__263.Matrix3.getColumn(decomposition.unitary, 1, new import__263.Cartesian3()); lambda = import__263.Matrix3.getColumn(decomposition.diagonal, 1, new import__263.Cartesian3()).y; expect( import__263.Cartesian3.multiplyByScalar(v, lambda, new import__263.Cartesian3()) ).toEqualEpsilon( import__263.Matrix3.multiplyByVector(a, v, new import__263.Cartesian3()), import__264.Math.EPSILON14 ); v = import__263.Matrix3.getColumn(decomposition.unitary, 2, new import__263.Cartesian3()); lambda = import__263.Matrix3.getColumn(decomposition.diagonal, 2, new import__263.Cartesian3()).z; expect( import__263.Cartesian3.multiplyByScalar(v, lambda, new import__263.Cartesian3()) ).toEqualEpsilon( import__263.Matrix3.multiplyByVector(a, v, new import__263.Cartesian3()), import__264.Math.EPSILON14 ); }); it("computes eigenvalues and eigenvectors with result parameters", function() { const a = new import__263.Matrix3(4, -1, 1, -1, 3, -2, 1, -2, 3); const expectedDiagonal = new import__263.Matrix3( 3, 0, 0, 0, 6, 0, 0, 0, 1 ); const result = { unitary: new import__263.Matrix3(), diagonal: new import__263.Matrix3() }; const decomposition = import__263.Matrix3.computeEigenDecomposition(a, result); expect(decomposition).toBe(result); expect(decomposition.diagonal).toEqualEpsilon( expectedDiagonal, import__264.Math.EPSILON14 ); let v = import__263.Matrix3.getColumn(decomposition.unitary, 0, new import__263.Cartesian3()); let lambda = import__263.Matrix3.getColumn(decomposition.diagonal, 0, new import__263.Cartesian3()).x; expect( import__263.Cartesian3.multiplyByScalar(v, lambda, new import__263.Cartesian3()) ).toEqualEpsilon( import__263.Matrix3.multiplyByVector(a, v, new import__263.Cartesian3()), import__264.Math.EPSILON14 ); v = import__263.Matrix3.getColumn(decomposition.unitary, 1, new import__263.Cartesian3()); lambda = import__263.Matrix3.getColumn(decomposition.diagonal, 1, new import__263.Cartesian3()).y; expect( import__263.Cartesian3.multiplyByScalar(v, lambda, new import__263.Cartesian3()) ).toEqualEpsilon( import__263.Matrix3.multiplyByVector(a, v, new import__263.Cartesian3()), import__264.Math.EPSILON14 ); v = import__263.Matrix3.getColumn(decomposition.unitary, 2, new import__263.Cartesian3()); lambda = import__263.Matrix3.getColumn(decomposition.diagonal, 2, new import__263.Cartesian3()).z; expect( import__263.Cartesian3.multiplyByScalar(v, lambda, new import__263.Cartesian3()) ).toEqualEpsilon( import__263.Matrix3.multiplyByVector(a, v, new import__263.Cartesian3()), import__264.Math.EPSILON14 ); }); it("abs works", function() { let matrix = new import__263.Matrix3( -1, -2, -3, -4, -5, -6, -7, -8, -9 ); const expected = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const result = new import__263.Matrix3(); let returnedResult = import__263.Matrix3.abs(matrix, result); expect(returnedResult).toEqual(expected); matrix = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); returnedResult = import__263.Matrix3.abs(matrix, result); expect(returnedResult).toEqual(expected); matrix = new import__263.Matrix3(1, -2, -3, 4, 5, -6, 7, -8, 9); returnedResult = import__263.Matrix3.abs(matrix, result); expect(returnedResult).toEqual(expected); }); it("abs works with a result parameter that is an input result parameter", function() { const matrix = new import__263.Matrix3( -1, -2, -3, -4, -5, -6, -7, -8, -9 ); const expected = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); const returnedResult = import__263.Matrix3.abs(matrix, matrix); expect(matrix).toBe(returnedResult); expect(matrix).toEqual(expected); }); it("equals works in all cases", function() { let left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); let right = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); expect(import__263.Matrix3.equals(left, right)).toEqual(true); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(5, 2, 3, 4, 5, 6, 7, 8, 9); expect(import__263.Matrix3.equals(left, right)).toEqual(false); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(1, 6, 3, 4, 5, 6, 7, 8, 9); expect(import__263.Matrix3.equals(left, right)).toEqual(false); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(1, 2, 7, 4, 5, 6, 7, 8, 9); expect(import__263.Matrix3.equals(left, right)).toEqual(false); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(1, 2, 3, 8, 5, 6, 7, 8, 9); expect(import__263.Matrix3.equals(left, right)).toEqual(false); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(1, 2, 3, 4, 9, 6, 7, 8, 9); expect(import__263.Matrix3.equals(left, right)).toEqual(false); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(1, 2, 3, 4, 5, 10, 7, 8, 9); expect(import__263.Matrix3.equals(left, right)).toEqual(false); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 11, 8, 9); expect(import__263.Matrix3.equals(left, right)).toEqual(false); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 12, 9); expect(import__263.Matrix3.equals(left, right)).toEqual(false); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 13); expect(import__263.Matrix3.equals(left, right)).toEqual(false); }); it("equals works with undefined", function() { expect(import__263.Matrix3.equals(void 0, void 0)).toEqual(true); expect(import__263.Matrix3.equals(new import__263.Matrix3(), void 0)).toEqual(false); expect(import__263.Matrix3.equals(void 0, new import__263.Matrix3())).toEqual(false); }); it("equalsEpsilon works in all cases", function() { let left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); let right = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); expect(import__263.Matrix3.equalsEpsilon(left, right, 1)).toEqual(true); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(5, 2, 3, 4, 5, 6, 7, 8, 9); expect(import__263.Matrix3.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__263.Matrix3.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(1, 6, 3, 4, 5, 6, 7, 8, 9); expect(import__263.Matrix3.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__263.Matrix3.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(1, 2, 7, 4, 5, 6, 7, 8, 9); expect(import__263.Matrix3.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__263.Matrix3.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(1, 2, 3, 8, 5, 6, 7, 8, 9); expect(import__263.Matrix3.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__263.Matrix3.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(1, 2, 3, 4, 9, 6, 7, 8, 9); expect(import__263.Matrix3.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__263.Matrix3.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(1, 2, 3, 4, 5, 10, 7, 8, 9); expect(import__263.Matrix3.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__263.Matrix3.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 11, 8, 9); expect(import__263.Matrix3.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__263.Matrix3.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 12, 9); expect(import__263.Matrix3.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__263.Matrix3.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); right = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 13); expect(import__263.Matrix3.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__263.Matrix3.equalsEpsilon(left, right, 4)).toEqual(true); }); it("equalsEpsilon works with undefined", function() { expect(import__263.Matrix3.equalsEpsilon(void 0, void 0, 1)).toEqual(true); expect(import__263.Matrix3.equalsEpsilon(new import__263.Matrix3(), void 0, 1)).toEqual(false); expect(import__263.Matrix3.equalsEpsilon(void 0, new import__263.Matrix3(), 1)).toEqual(false); }); it("toString", function() { const matrix = new import__263.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9); expect(matrix.toString()).toEqual("(1, 2, 3)\n(4, 5, 6)\n(7, 8, 9)"); }); it("fromArray throws without an array", function() { expect(function() { import__263.Matrix3.fromArray(); }).toThrowDeveloperError(); }); it("fromRowMajorArray throws with undefined parameter", function() { expect(function() { import__263.Matrix3.fromRowMajorArray(void 0); }).toThrowDeveloperError(); }); it("fromColumnMajorArray throws with undefined parameter", function() { expect(function() { import__263.Matrix3.fromColumnMajorArray(void 0); }).toThrowDeveloperError(); }); it("fromRotationX throws without angle", function() { expect(function() { import__263.Matrix3.fromRotationX(); }).toThrowDeveloperError(); }); it("fromRotationY throws without angle", function() { expect(function() { import__263.Matrix3.fromRotationY(); }).toThrowDeveloperError(); }); it("fromRotationZ throws without angle", function() { expect(function() { import__263.Matrix3.fromRotationZ(); }).toThrowDeveloperError(); }); it("clone returns undefined without matrix parameter", function() { expect(import__263.Matrix3.clone(void 0)).toBeUndefined(); }); it("toArray throws without matrix parameter", function() { expect(function() { import__263.Matrix3.toArray(void 0); }).toThrowDeveloperError(); }); it("getElement throws without row parameter", function() { let row; const col = 0; expect(function() { import__263.Matrix3.getElementIndex(col, row); }).toThrowDeveloperError(); }); it("getElement throws without column parameter", function() { const row = 0; let col; expect(function() { import__263.Matrix3.getElementIndex(col, row); }).toThrowDeveloperError(); }); it("getColumn throws without matrix parameter", function() { expect(function() { import__263.Matrix3.getColumn(void 0, 1); }).toThrowDeveloperError(); }); it("getColumn throws with out of range index parameter", function() { const matrix = new import__263.Matrix3(); expect(function() { import__263.Matrix3.getColumn(matrix, 3); }).toThrowDeveloperError(); }); it("setColumn throws without matrix parameter", function() { const cartesian = new import__263.Cartesian3(); expect(function() { import__263.Matrix3.setColumn(void 0, 2, cartesian); }).toThrowDeveloperError(); }); it("setColumn throws without cartesian parameter", function() { const matrix = new import__263.Matrix3(); expect(function() { import__263.Matrix3.setColumn(matrix, 1, void 0); }).toThrowDeveloperError(); }); it("setColumn throws with out of range index parameter", function() { const matrix = new import__263.Matrix3(); const cartesian = new import__263.Cartesian3(); expect(function() { import__263.Matrix3.setColumn(matrix, 3, cartesian); }).toThrowDeveloperError(); }); it("getRow throws without matrix parameter", function() { expect(function() { import__263.Matrix3.getRow(void 0, 1); }).toThrowDeveloperError(); }); it("getRow throws with out of range index parameter", function() { const matrix = new import__263.Matrix3(); expect(function() { import__263.Matrix3.getRow(matrix, 3); }).toThrowDeveloperError(); }); it("setRow throws without matrix parameter", function() { const cartesian = new import__263.Cartesian3(); expect(function() { import__263.Matrix3.setRow(void 0, 2, cartesian); }).toThrowDeveloperError(); }); it("setRow throws without cartesian parameter", function() { const matrix = new import__263.Matrix3(); expect(function() { import__263.Matrix3.setRow(matrix, 1, void 0); }).toThrowDeveloperError(); }); it("setRow throws with out of range index parameter", function() { const matrix = new import__263.Matrix3(); const cartesian = new import__263.Cartesian3(); expect(function() { import__263.Matrix3.setRow(matrix, 3, cartesian); }).toThrowDeveloperError(); }); it("setScale throws without a matrix", function() { expect(function() { import__263.Matrix3.setScale(); }).toThrowDeveloperError(); }); it("setScale throws without a scale", function() { expect(function() { import__263.Matrix3.setScale(new import__263.Matrix3()); }).toThrowDeveloperError(); }); it("setUniformScale throws without a matrix", function() { expect(function() { import__263.Matrix3.setUniformScale(); }).toThrowDeveloperError(); }); it("setUniformScale throws without a scale", function() { expect(function() { import__263.Matrix3.setUniformScale(new import__263.Matrix3()); }).toThrowDeveloperError(); }); it("getScale throws without a matrix", function() { expect(function() { import__263.Matrix3.getScale(); }).toThrowDeveloperError(); }); it("getMaximumScale throws without a matrix", function() { expect(function() { import__263.Matrix3.getMaximumScale(); }).toThrowDeveloperError(); }); it("setRotation throws without a matrix", function() { expect(function() { return import__263.Matrix3.setRotation(); }).toThrowDeveloperError(); }); it("setRotation throws without a rotation", function() { expect(function() { return import__263.Matrix3.setRotation(new import__263.Matrix3()); }).toThrowDeveloperError(); }); it("getRotation throws without a matrix", function() { expect(function() { return import__263.Matrix3.getRotation(); }).toThrowDeveloperError(); }); it("multiply throws with no left parameter", function() { const right = new import__263.Matrix3(); expect(function() { import__263.Matrix3.multiply(void 0, right); }).toThrowDeveloperError(); }); it("multiply throws with no right parameter", function() { const left = new import__263.Matrix3(); expect(function() { import__263.Matrix3.multiply(left, void 0); }).toThrowDeveloperError(); }); it("multiplyByScale throws with no matrix parameter", function() { expect(function() { import__263.Matrix3.multiplyByScale(void 0, new import__263.Cartesian3()); }).toThrowDeveloperError(); }); it("multiplyByScale throws with no scale parameter", function() { const m = new import__263.Matrix3(); expect(function() { import__263.Matrix3.multiplyByScale(m, void 0); }).toThrowDeveloperError(); }); it("multiplyByUniformScale throws with no matrix parameter", function() { expect(function() { import__263.Matrix3.multiplyByUniformScale(void 0, new import__263.Cartesian3()); }).toThrowDeveloperError(); }); it("multiplyByUniformScale throws with no scale parameter", function() { expect(function() { import__263.Matrix3.multiplyByUniformScale(new import__263.Matrix3(), void 0); }).toThrowDeveloperError(); }); it("multiplyByVector throws with no matrix parameter", function() { const cartesian = new import__263.Cartesian3(); expect(function() { import__263.Matrix3.multiplyByVector(void 0, cartesian); }).toThrowDeveloperError(); }); it("multiplyByVector throws with no cartesian parameter", function() { const matrix = new import__263.Matrix3(); expect(function() { import__263.Matrix3.multiplyByVector(matrix, void 0); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with no matrix parameter", function() { expect(function() { import__263.Matrix3.multiplyByScalar(void 0, 2); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with non-numeric scalar parameter", function() { const matrix = new import__263.Matrix3(); expect(function() { import__263.Matrix3.multiplyByScalar(matrix, {}); }).toThrowDeveloperError(); }); it("negate throws without matrix parameter", function() { expect(function() { import__263.Matrix3.negate(void 0); }).toThrowDeveloperError(); }); it("transpose throws without matrix parameter", function() { expect(function() { import__263.Matrix3.transpose(void 0); }).toThrowDeveloperError(); }); it("abs throws without a matrix", function() { expect(function() { return import__263.Matrix3.abs(); }).toThrowDeveloperError(); }); it("determinant throws without matrix parameter", function() { expect(function() { import__263.Matrix3.determinant(void 0); }).toThrowDeveloperError(); }); it("inverse throws without matrix parameter", function() { expect(function() { import__263.Matrix3.inverse(void 0); }).toThrowDeveloperError(); }); it("inverse throws when matrix is not invertible", function() { expect(function() { import__263.Matrix3.inverse( new import__263.Matrix3(0, 0, 0, 0, 0, 0, 0, 0, 0), new import__263.Matrix3() ); }).toThrowDeveloperError(); }); it("computeEigenDecomposition throws without a matrix", function() { expect(function() { return import__263.Matrix3.computeEigenDecomposition(); }).toThrowDeveloperError(); }); it("fromQuaternion throws without quaternion parameter", function() { expect(function() { import__263.Matrix3.fromQuaternion(void 0); }).toThrowDeveloperError(); }); it("fromHeadingPitchRoll throws without quaternion parameter", function() { expect(function() { import__263.Matrix3.fromHeadingPitchRoll(void 0); }).toThrowDeveloperError(); }); it("fromScale throws without scale parameter", function() { expect(function() { import__263.Matrix3.fromScale(void 0); }).toThrowDeveloperError(); }); it("fromUniformScale throws without scale parameter", function() { expect(function() { import__263.Matrix3.fromUniformScale(void 0); }).toThrowDeveloperError(); }); it("getColumn throws without a result parameter", function() { expect(function() { import__263.Matrix3.getColumn(new import__263.Matrix3(), 2); }).toThrowDeveloperError(); }); it("setColumn throws without a result parameter", function() { expect(function() { import__263.Matrix3.setColumn(new import__263.Matrix3(), 2, new import__263.Cartesian3()); }).toThrowDeveloperError(); }); it("getRow throws without a result parameter", function() { expect(function() { import__263.Matrix3.getRow(new import__263.Matrix3(), 2); }).toThrowDeveloperError(); }); it("setRow throws without a result parameter", function() { expect(function() { import__263.Matrix3.setRow(new import__263.Matrix3(), 2, new import__263.Cartesian3()); }).toThrowDeveloperError(); }); it("setScale throws without a result parameter", function() { expect(function() { import__263.Matrix3.setScale(new import__263.Matrix3(), new import__263.Cartesian3()); }).toThrowDeveloperError(); }); it("setUniformScale throws without a result parameter", function() { expect(function() { import__263.Matrix3.setUniformScale(new import__263.Matrix3(), 1); }).toThrowDeveloperError(); }); it("getScale throws without a result parameter", function() { expect(function() { import__263.Matrix3.getScale(new import__263.Matrix3()); }).toThrowDeveloperError(); }); it("setRotation throws without a result parameter", function() { expect(function() { return import__263.Matrix3.setRotation(new import__263.Matrix3(), new import__263.Matrix3()); }).toThrowDeveloperError(); }); it("getRotation throws without a result parameter", function() { expect(function() { return import__263.Matrix3.getRotation(new import__263.Matrix3()); }).toThrowDeveloperError(); }); it("multiply throws without a result parameter", function() { expect(function() { import__263.Matrix3.multiply(new import__263.Matrix3(), new import__263.Matrix3()); }).toThrowDeveloperError(); }); it("multiplyByScale throws without a result parameter", function() { expect(function() { import__263.Matrix3.multiplyByScale(new import__263.Matrix3(), new import__263.Cartesian3()); }).toThrowDeveloperError(); }); it("multiplyByUniformScale throws without a result parameter", function() { expect(function() { import__263.Matrix3.multiplyByUniformScale(new import__263.Matrix3(), new import__263.Cartesian3()); }).toThrowDeveloperError(); }); it("multiplyByVector throws without a result parameter", function() { expect(function() { import__263.Matrix3.multiplyByVector(new import__263.Matrix3(), new import__263.Cartesian3()); }).toThrowDeveloperError(); }); it("multiplyByScalar throws without a result parameter", function() { expect(function() { import__263.Matrix3.multiplyByScalar(new import__263.Matrix3(), 2); }).toThrowDeveloperError(); }); it("negate throws without a result parameter", function() { expect(function() { import__263.Matrix3.negate(new import__263.Matrix3()); }).toThrowDeveloperError(); }); it("transpose throws without a result parameter", function() { expect(function() { import__263.Matrix3.transpose(new import__263.Matrix3()); }).toThrowDeveloperError(); }); it("abs throws without a result parameter", function() { expect(function() { import__263.Matrix3.abs(new import__263.Matrix3()); }).toThrowDeveloperError(); }); it("inverse throws without a result parameter", function() { expect(function() { import__263.Matrix3.inverse(new import__263.Matrix3()); }).toThrowDeveloperError(); }); it("Matrix3 objects can be used as array like objects", function() { const matrix = new import__263.Matrix3(1, 4, 7, 2, 5, 8, 3, 6, 9); expect(matrix.length).toEqual(9); const intArray = new Uint32Array(matrix.length); intArray.set(matrix); for (let index = 0; index < matrix.length; index++) { expect(intArray[index]).toEqual(index + 1); } }); createPackableSpecs_default( import__263.Matrix3, new import__263.Matrix3( 1, 2, 3, 4, 5, 6, 7, 8, 9 ), [1, 4, 7, 2, 5, 8, 3, 6, 9] ); createPackableArraySpecs_default( import__263.Matrix3, [ new import__263.Matrix3( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), new import__263.Matrix3( 1, 2, 3, 4, 5, 6, 7, 8, 9 ), new import__263.Matrix3( 1, 2, 3, 1, 2, 3, 1, 2, 3 ) ], [ 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 4, 7, 2, 5, 8, 3, 6, 9, 1, 1, 1, 2, 2, 2, 3, 3, 3 ], 9 ); }); // packages/engine/Specs/Core/Matrix4Spec.js var import__265 = __toESM(require_Cesium(), 1); var import__266 = __toESM(require_Cesium(), 1); describe("Core/Matrix4", function() { it("default constructor creates values array with all zeros.", function() { const matrix = new import__265.Matrix4(); expect(matrix[import__265.Matrix4.COLUMN0ROW0]).toEqual(0); expect(matrix[import__265.Matrix4.COLUMN1ROW0]).toEqual(0); expect(matrix[import__265.Matrix4.COLUMN2ROW0]).toEqual(0); expect(matrix[import__265.Matrix4.COLUMN3ROW0]).toEqual(0); expect(matrix[import__265.Matrix4.COLUMN0ROW1]).toEqual(0); expect(matrix[import__265.Matrix4.COLUMN1ROW1]).toEqual(0); expect(matrix[import__265.Matrix4.COLUMN2ROW1]).toEqual(0); expect(matrix[import__265.Matrix4.COLUMN3ROW1]).toEqual(0); expect(matrix[import__265.Matrix4.COLUMN0ROW2]).toEqual(0); expect(matrix[import__265.Matrix4.COLUMN1ROW2]).toEqual(0); expect(matrix[import__265.Matrix4.COLUMN2ROW2]).toEqual(0); expect(matrix[import__265.Matrix4.COLUMN3ROW2]).toEqual(0); expect(matrix[import__265.Matrix4.COLUMN0ROW3]).toEqual(0); expect(matrix[import__265.Matrix4.COLUMN1ROW3]).toEqual(0); expect(matrix[import__265.Matrix4.COLUMN2ROW3]).toEqual(0); expect(matrix[import__265.Matrix4.COLUMN3ROW3]).toEqual(0); }); it("constructor sets properties from parameters.", function() { const matrix = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); expect(matrix[import__265.Matrix4.COLUMN0ROW0]).toEqual(1); expect(matrix[import__265.Matrix4.COLUMN1ROW0]).toEqual(2); expect(matrix[import__265.Matrix4.COLUMN2ROW0]).toEqual(3); expect(matrix[import__265.Matrix4.COLUMN3ROW0]).toEqual(4); expect(matrix[import__265.Matrix4.COLUMN0ROW1]).toEqual(5); expect(matrix[import__265.Matrix4.COLUMN1ROW1]).toEqual(6); expect(matrix[import__265.Matrix4.COLUMN2ROW1]).toEqual(7); expect(matrix[import__265.Matrix4.COLUMN3ROW1]).toEqual(8); expect(matrix[import__265.Matrix4.COLUMN0ROW2]).toEqual(9); expect(matrix[import__265.Matrix4.COLUMN1ROW2]).toEqual(10); expect(matrix[import__265.Matrix4.COLUMN2ROW2]).toEqual(11); expect(matrix[import__265.Matrix4.COLUMN3ROW2]).toEqual(12); expect(matrix[import__265.Matrix4.COLUMN0ROW3]).toEqual(13); expect(matrix[import__265.Matrix4.COLUMN1ROW3]).toEqual(14); expect(matrix[import__265.Matrix4.COLUMN2ROW3]).toEqual(15); expect(matrix[import__265.Matrix4.COLUMN3ROW3]).toEqual(16); }); it("fromArray works without a result parameter", function() { const expected = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const matrix = import__265.Matrix4.fromArray([ 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16 ]); expect(matrix).toEqual(expected); }); it("fromArray works with a result parameter", function() { const expected = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const result = new import__265.Matrix4(); const matrix = import__265.Matrix4.fromArray( [ 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16 ], 0, result ); expect(matrix).toBe(result); expect(matrix).toEqual(expected); }); it("fromArray works with a starting index", function() { const expected = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const result = new import__265.Matrix4(); const matrix = import__265.Matrix4.fromArray( [ 0, 0, 0, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16 ], 3, result ); expect(matrix).toBe(result); expect(matrix).toEqual(expected); }); it("fromRowMajorArray works without a result parameter", function() { const expected = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const matrix = import__265.Matrix4.fromRowMajorArray([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]); expect(matrix).toEqual(expected); }); it("fromRowMajorArray works with a result parameter", function() { const expected = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const result = new import__265.Matrix4(); const matrix = import__265.Matrix4.fromRowMajorArray( [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ], result ); expect(matrix).toBe(result); expect(matrix).toEqual(expected); }); it("fromColumnMajorArray works without a result parameter", function() { const expected = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const matrix = import__265.Matrix4.fromColumnMajorArray([ 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16 ]); expect(matrix).toEqual(expected); }); it("fromColumnMajorArray works with a result parameter", function() { const expected = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const result = new import__265.Matrix4(); const matrix = import__265.Matrix4.fromColumnMajorArray( [ 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16 ], result ); expect(matrix).toBe(result); expect(matrix).toEqual(expected); }); it("clone works without a result parameter", function() { const expected = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const returnedResult = expected.clone(); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("clone works with a result parameter", function() { const expected = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const result = new import__265.Matrix4(); const returnedResult = expected.clone(result); expect(returnedResult).toBe(result); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("fromRotationTranslation works without a result parameter", function() { const expected = new import__265.Matrix4( 1, 2, 3, 10, 4, 5, 6, 11, 7, 8, 9, 12, 0, 0, 0, 1 ); const returnedResult = import__265.Matrix4.fromRotationTranslation( new import__265.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9), new import__265.Cartesian3(10, 11, 12) ); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("fromRotationTranslation works with a result parameter", function() { const expected = new import__265.Matrix4( 1, 2, 3, 10, 4, 5, 6, 11, 7, 8, 9, 12, 0, 0, 0, 1 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.fromRotationTranslation( new import__265.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9), new import__265.Cartesian3(10, 11, 12), result ); expect(returnedResult).toBe(result); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("fromTranslation works without a result parameter", function() { const expected = new import__265.Matrix4( 1, 0, 0, 10, 0, 1, 0, 11, 0, 0, 1, 12, 0, 0, 0, 1 ); const returnedResult = import__265.Matrix4.fromTranslation( new import__265.Cartesian3(10, 11, 12) ); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("fromTranslationQuaternionRotationScale works without a result parameter", function() { const expected = new import__265.Matrix4( 7, 0, 0, 1, 0, 0, 9, 2, 0, -8, 0, 3, 0, 0, 0, 1 ); const returnedResult = import__265.Matrix4.fromTranslationQuaternionRotationScale( new import__265.Cartesian3(1, 2, 3), // translation import__265.Quaternion.fromAxisAngle(import__265.Cartesian3.UNIT_X, import__266.Math.toRadians(-90)), // rotation new import__265.Cartesian3(7, 8, 9) ); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqualEpsilon(expected, import__266.Math.EPSILON14); }); it("fromTranslationQuaternionRotationScale works with a result parameter", function() { const expected = new import__265.Matrix4( 7, 0, 0, 1, 0, 0, 9, 2, 0, -8, 0, 3, 0, 0, 0, 1 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.fromTranslationQuaternionRotationScale( new import__265.Cartesian3(1, 2, 3), // translation import__265.Quaternion.fromAxisAngle(import__265.Cartesian3.UNIT_X, import__266.Math.toRadians(-90)), // rotation new import__265.Cartesian3(7, 8, 9), // scale result ); expect(returnedResult).toBe(result); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqualEpsilon(expected, import__266.Math.EPSILON14); }); it("fromTranslationRotationScale works without a result parameter", function() { const expected = new import__265.Matrix4( 7, 0, 0, 1, 0, 0, 9, 2, 0, -8, 0, 3, 0, 0, 0, 1 ); const trs = new import__265.TranslationRotationScale( new import__265.Cartesian3(1, 2, 3), import__265.Quaternion.fromAxisAngle(import__265.Cartesian3.UNIT_X, import__266.Math.toRadians(-90)), new import__265.Cartesian3(7, 8, 9) ); const returnedResult = import__265.Matrix4.fromTranslationRotationScale(trs); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqualEpsilon(expected, import__266.Math.EPSILON14); }); it("fromTranslationRotationScale works with a result parameter", function() { const expected = new import__265.Matrix4( 7, 0, 0, 1, 0, 0, 9, 2, 0, -8, 0, 3, 0, 0, 0, 1 ); const trs = new import__265.TranslationRotationScale( new import__265.Cartesian3(1, 2, 3), import__265.Quaternion.fromAxisAngle(import__265.Cartesian3.UNIT_X, import__266.Math.toRadians(-90)), new import__265.Cartesian3(7, 8, 9) ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.fromTranslationRotationScale(trs, result); expect(returnedResult).toBe(result); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqualEpsilon(expected, import__266.Math.EPSILON14); }); it("fromTranslation works with a result parameter", function() { const expected = new import__265.Matrix4( 1, 0, 0, 10, 0, 1, 0, 11, 0, 0, 1, 12, 0, 0, 0, 1 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.fromTranslation( new import__265.Cartesian3(10, 11, 12), result ); expect(returnedResult).toBe(result); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("fromScale works without a result parameter", function() { const expected = new import__265.Matrix4( 7, 0, 0, 0, 0, 8, 0, 0, 0, 0, 9, 0, 0, 0, 0, 1 ); const returnedResult = import__265.Matrix4.fromScale(new import__265.Cartesian3(7, 8, 9)); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("fromScale works with a result parameter", function() { const expected = new import__265.Matrix4( 7, 0, 0, 0, 0, 8, 0, 0, 0, 0, 9, 0, 0, 0, 0, 1 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.fromScale( new import__265.Cartesian3(7, 8, 9), result ); expect(returnedResult).toBe(result); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("fromUniformScale works without a result parameter", function() { const expected = new import__265.Matrix4( 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1 ); const returnedResult = import__265.Matrix4.fromUniformScale(2); expect(returnedResult).toEqual(expected); }); it("fromUniformScale works with a result parameter", function() { const expected = new import__265.Matrix4( 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.fromUniformScale(2, result); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expected); }); it("fromRotation works without a result parameter", function() { const expected = import__265.Matrix4.fromColumnMajorArray([ 1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9, 0, 0, 0, 0, 1 ]); const returnedResult = import__265.Matrix4.fromRotation( import__265.Matrix3.fromColumnMajorArray([ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]) ); expect(returnedResult).toEqual(expected); }); it("fromRotation works with a result parameter", function() { const expected = import__265.Matrix4.fromColumnMajorArray([ 1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9, 0, 0, 0, 0, 1 ]); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.fromRotation( import__265.Matrix3.fromColumnMajorArray([ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]), result ); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expected); }); it("computePerspectiveFieldOfView works", function() { const expected = new import__265.Matrix4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1.222222222222222, -2.222222222222222, 0, 0, -1, 0 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.computePerspectiveFieldOfView( import__266.Math.PI_OVER_TWO, 1, 1, 10, result ); expect(returnedResult).toEqualEpsilon(expected, import__266.Math.EPSILON15); }); it("fromCamera works without a result parameter", function() { const expected = import__265.Matrix4.IDENTITY; const returnedResult = import__265.Matrix4.fromCamera({ position: import__265.Cartesian3.ZERO, direction: import__265.Cartesian3.negate(import__265.Cartesian3.UNIT_Z, new import__265.Cartesian3()), up: import__265.Cartesian3.UNIT_Y }); expect(expected).toEqual(returnedResult); }); it("fromCamera works with a result parameter", function() { const expected = import__265.Matrix4.IDENTITY; const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.fromCamera( { position: import__265.Cartesian3.ZERO, direction: import__265.Cartesian3.negate(import__265.Cartesian3.UNIT_Z, new import__265.Cartesian3()), up: import__265.Cartesian3.UNIT_Y }, result ); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expected); }); it("computeOrthographicOffCenter works", function() { const expected = new import__265.Matrix4( 2, 0, 0, -1, 0, 2, 0, -5, 0, 0, -2, -1, 0, 0, 0, 1 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.computeOrthographicOffCenter( 0, 1, 2, 3, 0, 1, result ); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(expected); }); it("computeViewportTransformation works without a result parameter", function() { const expected = new import__265.Matrix4( 2, 0, 0, 2, 0, 3, 0, 3, 0, 0, 1, 1, 0, 0, 0, 1 ); const returnedResult = import__265.Matrix4.computeViewportTransformation( { x: 0, y: 0, width: 4, height: 6 }, 0, 2 ); expect(returnedResult).toEqual(expected); }); it("computeViewportTransformation works with a result parameter", function() { const expected = new import__265.Matrix4( 2, 0, 0, 2, 0, 3, 0, 3, 0, 0, 1, 1, 0, 0, 0, 1 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.computeViewportTransformation( { x: 0, y: 0, width: 4, height: 6 }, 0, 2, result ); expect(returnedResult).toEqual(expected); expect(returnedResult).toBe(result); }); it("computePerspectiveOffCenter works", function() { const expected = new import__265.Matrix4( 2, 0, 3, 0, 0, 2, 5, 0, 0, 0, -3, -4, 0, 0, -1, 0 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.computePerspectiveOffCenter( 1, 2, 2, 3, 1, 2, result ); expect(returnedResult).toEqual(expected); expect(returnedResult).toBe(result); }); it("computeInfinitePerspectiveOffCenter works", function() { const expected = new import__265.Matrix4( 2, 0, 3, 0, 0, 2, 5, 0, 0, 0, -1, -2, 0, 0, -1, 0 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.computeInfinitePerspectiveOffCenter( 1, 2, 2, 3, 1, result ); expect(returnedResult).toEqual(expected); }); it("toArray works without a result parameter", function() { const expected = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]; const returnedResult = import__265.Matrix4.toArray( import__265.Matrix4.fromColumnMajorArray(expected) ); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("toArray works with a result parameter", function() { const expected = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]; const result = []; const returnedResult = import__265.Matrix4.toArray( import__265.Matrix4.fromColumnMajorArray(expected), result ); expect(returnedResult).toBe(result); expect(returnedResult).not.toBe(expected); expect(returnedResult).toEqual(expected); }); it("getElementIndex works", function() { let i = 0; for (let col = 0; col < 4; col++) { for (let row = 0; row < 4; row++) { const index = import__265.Matrix4.getElementIndex(col, row); expect(index).toEqual(i); i++; } } }); it("getColumn works for each column", function() { const matrix = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const expectedColumn0 = new import__265.Cartesian4(1, 5, 9, 13); const expectedColumn1 = new import__265.Cartesian4(2, 6, 10, 14); const expectedColumn2 = new import__265.Cartesian4(3, 7, 11, 15); const expectedColumn3 = new import__265.Cartesian4(4, 8, 12, 16); const resultColumn0 = new import__265.Cartesian4(); const resultColumn1 = new import__265.Cartesian4(); const resultColumn2 = new import__265.Cartesian4(); const resultColumn3 = new import__265.Cartesian4(); const returnedResultColumn0 = import__265.Matrix4.getColumn(matrix, 0, resultColumn0); const returnedResultColumn1 = import__265.Matrix4.getColumn(matrix, 1, resultColumn1); const returnedResultColumn2 = import__265.Matrix4.getColumn(matrix, 2, resultColumn2); const returnedResultColumn3 = import__265.Matrix4.getColumn(matrix, 3, resultColumn3); expect(resultColumn0).toBe(returnedResultColumn0); expect(resultColumn0).toEqual(expectedColumn0); expect(resultColumn1).toBe(returnedResultColumn1); expect(resultColumn1).toEqual(expectedColumn1); expect(resultColumn2).toBe(returnedResultColumn2); expect(resultColumn2).toEqual(expectedColumn2); expect(resultColumn3).toBe(returnedResultColumn3); expect(resultColumn3).toEqual(expectedColumn3); }); it("setColumn works for each column", function() { const matrix = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const result = new import__265.Matrix4(); let expected = new import__265.Matrix4( 17, 2, 3, 4, 18, 6, 7, 8, 19, 10, 11, 12, 20, 14, 15, 16 ); let returnedResult = import__265.Matrix4.setColumn( matrix, 0, new import__265.Cartesian4(17, 18, 19, 20), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); expected = new import__265.Matrix4( 1, 17, 3, 4, 5, 18, 7, 8, 9, 19, 11, 12, 13, 20, 15, 16 ); returnedResult = import__265.Matrix4.setColumn( matrix, 1, new import__265.Cartesian4(17, 18, 19, 20), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); expected = new import__265.Matrix4( 1, 2, 17, 4, 5, 6, 18, 8, 9, 10, 19, 12, 13, 14, 20, 16 ); returnedResult = import__265.Matrix4.setColumn( matrix, 2, new import__265.Cartesian4(17, 18, 19, 20), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); expected = new import__265.Matrix4( 1, 2, 3, 17, 5, 6, 7, 18, 9, 10, 11, 19, 13, 14, 15, 20 ); returnedResult = import__265.Matrix4.setColumn( matrix, 3, new import__265.Cartesian4(17, 18, 19, 20), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); }); it("setTranslation works", function() { const matrix = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const translation = new import__265.Cartesian3(-1, -2, -3); const result = new import__265.Matrix4(); const expected = new import__265.Matrix4( 1, 2, 3, -1, 5, 6, 7, -2, 9, 10, 11, -3, 13, 14, 15, 16 ); const returnedResult = import__265.Matrix4.setTranslation(matrix, translation, result); expect(result).toBe(returnedResult); expect(result).toEqual(expected); }); it("getRow works for each row", function() { const matrix = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const expectedRow0 = new import__265.Cartesian4(1, 2, 3, 4); const expectedRow1 = new import__265.Cartesian4(5, 6, 7, 8); const expectedRow2 = new import__265.Cartesian4(9, 10, 11, 12); const expectedRow3 = new import__265.Cartesian4(13, 14, 15, 16); const resultRow0 = new import__265.Cartesian4(); const resultRow1 = new import__265.Cartesian4(); const resultRow2 = new import__265.Cartesian4(); const resultRow3 = new import__265.Cartesian4(); const returnedResultRow0 = import__265.Matrix4.getRow(matrix, 0, resultRow0); const returnedResultRow1 = import__265.Matrix4.getRow(matrix, 1, resultRow1); const returnedResultRow2 = import__265.Matrix4.getRow(matrix, 2, resultRow2); const returnedResultRow3 = import__265.Matrix4.getRow(matrix, 3, resultRow3); expect(resultRow0).toBe(returnedResultRow0); expect(resultRow0).toEqual(expectedRow0); expect(resultRow1).toBe(returnedResultRow1); expect(resultRow1).toEqual(expectedRow1); expect(resultRow2).toBe(returnedResultRow2); expect(resultRow2).toEqual(expectedRow2); expect(resultRow3).toBe(returnedResultRow3); expect(resultRow3).toEqual(expectedRow3); }); it("setRow works for each row", function() { const matrix = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const result = new import__265.Matrix4(); let expected = new import__265.Matrix4( 91, 92, 93, 94, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); let returnedResult = import__265.Matrix4.setRow( matrix, 0, new import__265.Cartesian4(91, 92, 93, 94), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); expected = new import__265.Matrix4( 1, 2, 3, 4, 95, 96, 97, 98, 9, 10, 11, 12, 13, 14, 15, 16 ); returnedResult = import__265.Matrix4.setRow( matrix, 1, new import__265.Cartesian4(95, 96, 97, 98), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); expected = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 99, 910, 911, 912, 13, 14, 15, 16 ); returnedResult = import__265.Matrix4.setRow( matrix, 2, new import__265.Cartesian4(99, 910, 911, 912), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); expected = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 913, 914, 915, 916 ); returnedResult = import__265.Matrix4.setRow( matrix, 3, new import__265.Cartesian4(913, 914, 915, 916), result ); expect(result).toBe(returnedResult); expect(result).toEqual(expected); }); it("setScale works", function() { const oldScale = new import__265.Cartesian3(2, 3, 4); const newScale = new import__265.Cartesian3(5, 6, 7); const matrix = import__265.Matrix4.fromScale(oldScale, new import__265.Matrix4()); const result = new import__265.Matrix4(); expect(import__265.Matrix4.getScale(matrix, new import__265.Cartesian3())).toEqual(oldScale); const returnedResult = import__265.Matrix4.setScale(matrix, newScale, result); expect(import__265.Matrix4.getScale(returnedResult, new import__265.Cartesian3())).toEqual( newScale ); expect(result).toBe(returnedResult); }); it("setUniformScale works", function() { const oldScale = new import__265.Cartesian3(2, 3, 4); const newScale = 5; const matrix = import__265.Matrix4.fromScale(oldScale, new import__265.Matrix4()); const result = new import__265.Matrix4(); expect(import__265.Matrix4.getScale(matrix, new import__265.Cartesian3())).toEqual(oldScale); const returnedResult = import__265.Matrix4.setUniformScale(matrix, newScale, result); expect(import__265.Matrix4.getScale(returnedResult, new import__265.Cartesian3())).toEqual( new import__265.Cartesian3(newScale, newScale, newScale) ); expect(result).toBe(returnedResult); }); it("getScale works", function() { const scale = new import__265.Cartesian3(2, 3, 4); const result = new import__265.Cartesian3(); const computedScale = import__265.Matrix4.getScale(import__265.Matrix4.fromScale(scale), result); expect(computedScale).toBe(result); expect(computedScale).toEqualEpsilon(scale, import__266.Math.EPSILON14); }); it("getMaximumScale works", function() { const m = import__265.Matrix4.fromScale(new import__265.Cartesian3(2, 3, 4)); expect(import__265.Matrix4.getMaximumScale(m)).toEqualEpsilon( 4, import__266.Math.EPSILON14 ); }); it("setRotation works", function() { const scaleVec = new import__265.Cartesian3(2, 3, 4); const scale = import__265.Matrix4.fromScale(scaleVec, new import__265.Matrix3()); const rotation = import__265.Matrix3.fromRotationX(0.5, new import__265.Matrix3()); const scaleRotation = import__265.Matrix4.setRotation(scale, rotation, new import__265.Matrix4()); const extractedScale = import__265.Matrix4.getScale(scaleRotation, new import__265.Cartesian3()); const extractedRotation = import__265.Matrix4.getRotation(scaleRotation, new import__265.Matrix3()); expect(extractedScale).toEqualEpsilon(scaleVec, import__266.Math.EPSILON14); expect(extractedRotation).toEqualEpsilon(rotation, import__266.Math.EPSILON14); }); it("getRotation returns matrix without scale", function() { const matrix = import__265.Matrix4.fromRotation( import__265.Matrix3.fromColumnMajorArray([ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]) ); const expectedRotation = import__265.Matrix3.fromColumnMajorArray([ 1 / Math.sqrt(1 * 1 + 2 * 2 + 3 * 3), 2 / Math.sqrt(1 * 1 + 2 * 2 + 3 * 3), 3 / Math.sqrt(1 * 1 + 2 * 2 + 3 * 3), 4 / Math.sqrt(4 * 4 + 5 * 5 + 6 * 6), 5 / Math.sqrt(4 * 4 + 5 * 5 + 6 * 6), 6 / Math.sqrt(4 * 4 + 5 * 5 + 6 * 6), 7 / Math.sqrt(7 * 7 + 8 * 8 + 9 * 9), 8 / Math.sqrt(7 * 7 + 8 * 8 + 9 * 9), 9 / Math.sqrt(7 * 7 + 8 * 8 + 9 * 9) ]); const rotation = import__265.Matrix4.getRotation(matrix, new import__265.Matrix3()); expect(rotation).toEqualEpsilon(expectedRotation, import__266.Math.EPSILON14); }); it("getRotation does not modify rotation matrix", function() { const matrix = import__265.Matrix4.fromRotation( import__265.Matrix3.fromColumnMajorArray([ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]) ); const duplicateMatrix = import__265.Matrix4.clone(matrix, new import__265.Matrix4()); const expectedRotation = import__265.Matrix3.fromColumnMajorArray([ 1 / Math.sqrt(1 * 1 + 2 * 2 + 3 * 3), 2 / Math.sqrt(1 * 1 + 2 * 2 + 3 * 3), 3 / Math.sqrt(1 * 1 + 2 * 2 + 3 * 3), 4 / Math.sqrt(4 * 4 + 5 * 5 + 6 * 6), 5 / Math.sqrt(4 * 4 + 5 * 5 + 6 * 6), 6 / Math.sqrt(4 * 4 + 5 * 5 + 6 * 6), 7 / Math.sqrt(7 * 7 + 8 * 8 + 9 * 9), 8 / Math.sqrt(7 * 7 + 8 * 8 + 9 * 9), 9 / Math.sqrt(7 * 7 + 8 * 8 + 9 * 9) ]); const result = import__265.Matrix4.getRotation(matrix, new import__265.Matrix3()); expect(result).toEqualEpsilon(expectedRotation, import__266.Math.EPSILON14); expect(matrix).toEqual(duplicateMatrix); expect(matrix).not.toBe(result); }); it("multiply works", function() { const left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const right = new import__265.Matrix4( 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 ); const expected = new import__265.Matrix4( 250, 260, 270, 280, 618, 644, 670, 696, 986, 1028, 1070, 1112, 1354, 1412, 1470, 1528 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.multiply(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("multiply works with a result parameter that is an input result parameter", function() { const left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const right = new import__265.Matrix4( 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 ); const expected = new import__265.Matrix4( 250, 260, 270, 280, 618, 644, 670, 696, 986, 1028, 1070, 1112, 1354, 1412, 1470, 1528 ); const returnedResult = import__265.Matrix4.multiply(left, right, left); expect(returnedResult).toBe(left); expect(left).toEqual(expected); }); it("add works", function() { const left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const right = new import__265.Matrix4( 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 ); const expected = new import__265.Matrix4( 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.add(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("add works with a result parameter that is an input result parameter", function() { const left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const right = new import__265.Matrix4( 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 ); const expected = new import__265.Matrix4( 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48 ); const returnedResult = import__265.Matrix4.add(left, right, left); expect(returnedResult).toBe(left); expect(left).toEqual(expected); }); it("subtract works", function() { const left = new import__265.Matrix4( 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48 ); const right = new import__265.Matrix4( 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 ); const expected = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.subtract(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("subtract works with a result parameter that is an input result parameter", function() { const left = new import__265.Matrix4( 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48 ); const right = new import__265.Matrix4( 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 ); const expected = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const returnedResult = import__265.Matrix4.subtract(left, right, left); expect(returnedResult).toBe(left); expect(left).toEqual(expected); }); it("multiplyTransformation works", function() { const left = new import__265.Matrix4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 1); const right = new import__265.Matrix4( 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 0, 0, 0, 1 ); const expected = new import__265.Matrix4( 134, 140, 146, 156, 386, 404, 422, 448, 638, 668, 698, 740, 0, 0, 0, 1 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.multiplyTransformation(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("multiplyTransformation works with a result parameter that is an input result parameter", function() { const left = new import__265.Matrix4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 1); const right = new import__265.Matrix4( 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 0, 0, 0, 1 ); const expected = new import__265.Matrix4( 134, 140, 146, 156, 386, 404, 422, 448, 638, 668, 698, 740, 0, 0, 0, 1 ); const returnedResult = import__265.Matrix4.multiplyTransformation(left, right, left); expect(returnedResult).toBe(left); expect(left).toEqual(expected); }); it("multiplyByMatrix3 works", function() { const left = import__265.Matrix4.fromRotationTranslation( import__265.Matrix3.fromRotationZ(import__266.Math.toRadians(45)), new import__265.Cartesian3(1, 2, 3) ); const rightRotation = import__265.Matrix3.fromRotationX(import__266.Math.toRadians(30)); const right = import__265.Matrix4.fromRotationTranslation(rightRotation); const expected = new import__265.Matrix4.multiplyTransformation( left, right, new import__265.Matrix4() ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.multiplyByMatrix3( left, rightRotation, result ); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("multiplyByMatrix3 works with a result parameter that is an input result parameter", function() { const left = import__265.Matrix4.fromRotationTranslation( import__265.Matrix3.fromRotationZ(import__266.Math.toRadians(45)), new import__265.Cartesian3(1, 2, 3) ); const rightRotation = import__265.Matrix3.fromRotationX(import__266.Math.toRadians(30)); const right = import__265.Matrix4.fromRotationTranslation(rightRotation); const expected = new import__265.Matrix4.multiplyTransformation( left, right, new import__265.Matrix4() ); const returnedResult = import__265.Matrix4.multiplyByMatrix3(left, rightRotation, left); expect(returnedResult).toBe(left); expect(left).toEqual(expected); }); it("multiplyByTranslation works", function() { const m = new import__265.Matrix4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 1); const translation = new import__265.Cartesian3(17, 18, 19); const expected = import__265.Matrix4.multiply( m, import__265.Matrix4.fromTranslation(translation), new import__265.Matrix4() ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.multiplyByTranslation( m, translation, result ); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("multiplyByTranslation works with a result parameter that is an input result parameter", function() { const m = new import__265.Matrix4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 1); const translation = new import__265.Cartesian3(17, 18, 19); const expected = import__265.Matrix4.multiply( m, import__265.Matrix4.fromTranslation(translation), new import__265.Matrix4() ); const returnedResult = import__265.Matrix4.multiplyByTranslation(m, translation, m); expect(returnedResult).toBe(m); expect(m).toEqual(expected); }); it("multiplyByUniformScale works", function() { const m = import__265.Matrix4.fromColumnMajorArray([ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]); const scale = 2; const expected = import__265.Matrix4.fromColumnMajorArray([ 2 * scale, 3 * scale, 4 * scale, 5, 6 * scale, 7 * scale, 8 * scale, 9, 10 * scale, 11 * scale, 12 * scale, 13, 14, 15, 16, 17 ]); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.multiplyByUniformScale(m, scale, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("multiplyByUniformScale works with a result parameter that is an input result parameter", function() { const m = import__265.Matrix4.fromColumnMajorArray([ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]); const scale = 2; const expected = import__265.Matrix4.fromColumnMajorArray([ 2 * scale, 3 * scale, 4 * scale, 5, 6 * scale, 7 * scale, 8 * scale, 9, 10 * scale, 11 * scale, 12 * scale, 13, 14, 15, 16, 17 ]); const returnedResult = import__265.Matrix4.multiplyByUniformScale(m, scale, m); expect(returnedResult).toBe(m); expect(m).toEqual(expected); }); it("multiplyByScale works", function() { let m = new import__265.Matrix4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 1); let scale = new import__265.Cartesian3(1, 1, 1); let expected = import__265.Matrix4.multiply(m, import__265.Matrix4.fromScale(scale), new import__265.Matrix4()); let result = new import__265.Matrix4(); let returnedResult = import__265.Matrix4.multiplyByScale(m, scale, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); m = new import__265.Matrix4(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0, 0, 0, 1); scale = new import__265.Cartesian3(2, 3, 4); expected = import__265.Matrix4.multiply(m, import__265.Matrix4.fromScale(scale), new import__265.Matrix4()); result = new import__265.Matrix4(); returnedResult = import__265.Matrix4.multiplyByScale(m, scale, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it('multiplyByScale works with "this" result parameter', function() { const m = new import__265.Matrix4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 1); const scale = new import__265.Cartesian3(1, 2, 3); const expected = import__265.Matrix4.multiply( m, import__265.Matrix4.fromScale(scale), new import__265.Matrix4() ); const returnedResult = import__265.Matrix4.multiplyByScale(m, scale, m); expect(returnedResult).toBe(m); expect(m).toEqual(expected); }); it("multiplyByUniformScale works", function() { const m = import__265.Matrix4.fromColumnMajorArray([ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]); const scale = 2; const expected = import__265.Matrix4.fromColumnMajorArray([ 2 * scale, 3 * scale, 4 * scale, 5, 6 * scale, 7 * scale, 8 * scale, 9, 10 * scale, 11 * scale, 12 * scale, 13, 14, 15, 16, 17 ]); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.multiplyByUniformScale(m, scale, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it('multiplyByUniformScale works with "this" result parameter', function() { const m = import__265.Matrix4.fromColumnMajorArray([ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]); const scale = 2; const expected = import__265.Matrix4.fromColumnMajorArray([ 2 * scale, 3 * scale, 4 * scale, 5, 6 * scale, 7 * scale, 8 * scale, 9, 10 * scale, 11 * scale, 12 * scale, 13, 14, 15, 16, 17 ]); const returnedResult = import__265.Matrix4.multiplyByUniformScale(m, scale, m); expect(returnedResult).toBe(m); expect(m).toEqual(expected); }); it("multiplyByVector works", function() { const left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const right = new import__265.Cartesian4(17, 18, 19, 20); const expected = new import__265.Cartesian4(190, 486, 782, 1078); const result = new import__265.Cartesian4(); const returnedResult = import__265.Matrix4.multiplyByVector(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("multiplyByPoint works", function() { const left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const right = new import__265.Cartesian3(17, 18, 19); const expected = new import__265.Cartesian3(114, 334, 554); const result = new import__265.Cartesian3(); const returnedResult = import__265.Matrix4.multiplyByPoint(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("multiplyByPointAsVector works", function() { const left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const right = new import__265.Cartesian3(17, 18, 19); const expected = new import__265.Cartesian3(110, 326, 542); const result = new import__265.Cartesian3(); const returnedResult = import__265.Matrix4.multiplyByPointAsVector(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("multiplyByScalar works", function() { const left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const right = 2; const expected = new import__265.Matrix4( 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.multiplyByScalar(left, right, result); expect(returnedResult).toBe(result); expect(result).toEqual(expected); }); it("negate works", function() { const matrix = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const expected = new import__265.Matrix4( -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.negate(matrix, result); expect(result).toBe(returnedResult); expect(result).toEqual(expected); }); it("negate works with a result parameter that is an input result parameter", function() { const matrix = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const expected = new import__265.Matrix4( -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16 ); const returnedResult = import__265.Matrix4.negate(matrix, matrix); expect(matrix).toBe(returnedResult); expect(matrix).toEqual(expected); }); it("transpose works", function() { const matrix = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const expected = new import__265.Matrix4( 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.transpose(matrix, result); expect(result).toBe(returnedResult); expect(result).toEqual(expected); }); it("inverseTranspose works", function() { const matrix = new import__265.Matrix4( 1, 2, 6, 4, 8, 6, -7, 8, 9, -20, -11, 12, 13, -27, 15, 16 ); const expectedInverse = import__265.Matrix4.inverse(matrix, new import__265.Matrix4()); const expectedInverseTranspose = import__265.Matrix4.transpose( expectedInverse, new import__265.Matrix4() ); const result = import__265.Matrix4.inverseTranspose(matrix, new import__265.Matrix4()); expect(result).toEqual(expectedInverseTranspose); }); it("transpose works with a result parameter that is an input result parameter", function() { const matrix = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const expected = new import__265.Matrix4( 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16 ); const returnedResult = import__265.Matrix4.transpose(matrix, matrix); expect(matrix).toBe(returnedResult); expect(matrix).toEqual(expected); }); it("equals works in all cases", function() { let left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); let right = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); expect(import__265.Matrix4.equals(left, right)).toEqual(true); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4(5, 2, 3, 4, 5, 6, 7, 8, 9); expect(import__265.Matrix4.equals(left, right)).toEqual(false); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4(1, 6, 3, 4, 5, 6, 7, 8, 9); expect(import__265.Matrix4.equals(left, right)).toEqual(false); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4(1, 2, 7, 4, 5, 6, 7, 8, 9); expect(import__265.Matrix4.equals(left, right)).toEqual(false); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4(1, 2, 3, 8, 5, 6, 7, 8, 9); expect(import__265.Matrix4.equals(left, right)).toEqual(false); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4(1, 2, 3, 4, 9, 6, 7, 8, 9); expect(import__265.Matrix4.equals(left, right)).toEqual(false); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4(1, 2, 3, 4, 5, 10, 7, 8, 9); expect(import__265.Matrix4.equals(left, right)).toEqual(false); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4(1, 2, 3, 4, 5, 6, 11, 8, 9); expect(import__265.Matrix4.equals(left, right)).toEqual(false); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4(1, 2, 3, 4, 5, 6, 7, 12, 9); expect(import__265.Matrix4.equals(left, right)).toEqual(false); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4(1, 2, 3, 4, 5, 6, 7, 8, 13); expect(import__265.Matrix4.equals(left, right)).toEqual(false); }); it("equals works with undefined", function() { expect(import__265.Matrix4.equals(void 0, void 0)).toEqual(true); expect(import__265.Matrix4.equals(new import__265.Matrix4(), void 0)).toEqual(false); expect(import__265.Matrix4.equals(void 0, new import__265.Matrix4())).toEqual(false); }); it("equalsEpsilon works in all cases", function() { let left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); let right = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); expect(import__265.Matrix4.equalsEpsilon(left, right, 1)).toEqual(true); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4( 5, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); expect(import__265.Matrix4.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__265.Matrix4.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4( 1, 6, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); expect(import__265.Matrix4.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__265.Matrix4.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4( 1, 2, 7, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); expect(import__265.Matrix4.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__265.Matrix4.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4( 1, 2, 3, 8, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); expect(import__265.Matrix4.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__265.Matrix4.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4( 1, 2, 3, 4, 9, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); expect(import__265.Matrix4.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__265.Matrix4.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4( 1, 2, 3, 4, 5, 10, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); expect(import__265.Matrix4.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__265.Matrix4.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 11, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); expect(import__265.Matrix4.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__265.Matrix4.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 12, 9, 10, 11, 12, 13, 14, 15, 16 ); expect(import__265.Matrix4.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__265.Matrix4.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 13, 10, 11, 12, 13, 14, 15, 16 ); expect(import__265.Matrix4.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__265.Matrix4.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 14, 11, 12, 13, 14, 15, 16 ); expect(import__265.Matrix4.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__265.Matrix4.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 12, 13, 14, 15, 16 ); expect(import__265.Matrix4.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__265.Matrix4.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 16, 13, 14, 15, 16 ); expect(import__265.Matrix4.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__265.Matrix4.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 17, 14, 15, 16 ); expect(import__265.Matrix4.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__265.Matrix4.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 18, 15, 16 ); expect(import__265.Matrix4.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__265.Matrix4.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 19, 16 ); expect(import__265.Matrix4.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__265.Matrix4.equalsEpsilon(left, right, 4)).toEqual(true); left = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); right = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 20 ); expect(import__265.Matrix4.equalsEpsilon(left, right, 3.9)).toEqual(false); expect(import__265.Matrix4.equalsEpsilon(left, right, 4)).toEqual(true); }); it("equalsEpsilon works with undefined", function() { expect(import__265.Matrix4.equalsEpsilon(void 0, void 0, 1)).toEqual(true); expect(import__265.Matrix4.equalsEpsilon(new import__265.Matrix4(), void 0, 1)).toEqual(false); expect(import__265.Matrix4.equalsEpsilon(void 0, new import__265.Matrix4(), 1)).toEqual(false); }); it("toString", function() { const matrix = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); expect(matrix.toString()).toEqual( "(1, 2, 3, 4)\n(5, 6, 7, 8)\n(9, 10, 11, 12)\n(13, 14, 15, 16)" ); }); it("getTranslation works", function() { const matrix = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const expected = new import__265.Cartesian3(4, 8, 12); const result = new import__265.Cartesian3(); const returnedResult = import__265.Matrix4.getTranslation(matrix, result); expect(returnedResult).toBe(result); expect(expected).toEqual(returnedResult); }); it("getMatrix3 works", function() { const matrix = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const expected = new import__265.Matrix3(1, 2, 3, 5, 6, 7, 9, 10, 11); const result = new import__265.Matrix3(); const returnedResult = import__265.Matrix4.getMatrix3(matrix, result); expect(returnedResult).toBe(result); expect(expected).toEqual(returnedResult); }); it("inverse works", function() { const matrix = new import__265.Matrix4( 0.72, 0.7, 0, 0, -0.4, 0.41, 0.82, 0, 0.57, -0.59, 0.57, -3.86, 0, 0, 0, 1 ); const expected = new import__265.Matrix4( 0.7150830193944467, -0.3976559229803265, 0.5720664155155574, 2.2081763638900513, 0.6930574657657118, 0.40901752077976433, -0.5884111702445733, -2.271267117144053, 0.0022922521876059163, 0.8210249357172755, 0.5732623731786561, 2.2127927604696125, 0, 0, 0, 1 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.inverse(matrix, result); expect(returnedResult).toBe(result); expect(expected).toEqualEpsilon(returnedResult, import__266.Math.EPSILON20); expect( import__265.Matrix4.multiply(returnedResult, matrix, new import__265.Matrix4()) ).toEqualEpsilon(import__265.Matrix4.IDENTITY, import__266.Math.EPSILON15); }); it("inverse translates zero scale matrix", function() { let matrix = import__265.Matrix4.fromTranslation(new import__265.Cartesian3(1, 2, 3)); matrix = import__265.Matrix4.multiplyByUniformScale(matrix, 0, matrix); let expected = import__265.Matrix4.fromTranslation(new import__265.Cartesian3(-1, -2, -3)); expected = import__265.Matrix4.multiplyByUniformScale(expected, 0, expected); const result = import__265.Matrix4.inverse(matrix, new import__265.Matrix4()); expect(expected).toEqualEpsilon(result, import__266.Math.EPSILON20); }); it("inverse behaves acceptably with near single precision zero scale matrix", function() { const trs = new import__265.TranslationRotationScale( new import__265.Cartesian3(0, 0, 0), import__265.Quaternion.fromAxisAngle(import__265.Cartesian3.UNIT_X, 0), new import__265.Cartesian3(1e-7, 1e-7, 11e-8) ); const matrix = import__265.Matrix4.fromTranslationRotationScale(trs); const expected = new import__265.Matrix4( 1e7, 0, 0, 0, 0, 1e7, 0, 0, 0, 0, 1 / 1.1 * 1e7, 0, 0, 0, 0, 1 ); const result = import__265.Matrix4.inverse(matrix, new import__265.Matrix4()); expect(expected).toEqualEpsilon(result, import__266.Math.EPSILON15); }); it("inverse behaves acceptably with single precision zero scale matrix", function() { const trs = new import__265.TranslationRotationScale( new import__265.Cartesian3(0, 0, 0), import__265.Quaternion.fromAxisAngle(import__265.Cartesian3.UNIT_X, 0), new import__265.Cartesian3(18e-9, 12e-9, 12e-9) ); const matrix = import__265.Matrix4.fromTranslationRotationScale(trs); const expected = new import__265.Matrix4( 0, 0, 0, -matrix[12], 0, 0, 0, -matrix[13], 0, 0, 0, -matrix[14], 0, 0, 0, 1 ); const result = import__265.Matrix4.inverse(matrix, new import__265.Matrix4()); expect(expected).toEqualEpsilon(result, import__266.Math.EPSILON20); }); it("inverseTransformation works", function() { const matrix = new import__265.Matrix4( 1, 0, 0, 10, 0, 0, 1, 20, 0, 1, 0, 30, 0, 0, 0, 1 ); const expected = new import__265.Matrix4( 1, 0, 0, -10, 0, 0, 1, -30, 0, 1, 0, -20, 0, 0, 0, 1 ); const result = new import__265.Matrix4(); const returnedResult = import__265.Matrix4.inverseTransformation(matrix, result); expect(returnedResult).toBe(result); expect(expected).toEqual(returnedResult); expect(import__265.Matrix4.multiply(returnedResult, matrix, new import__265.Matrix4())).toEqual( import__265.Matrix4.IDENTITY ); }); it("abs throws without a matrix", function() { expect(function() { return import__265.Matrix4.abs(); }).toThrowDeveloperError(); }); it("abs works", function() { let matrix = new import__265.Matrix4( -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16 ); const expected = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const result = new import__265.Matrix4(); let returnedResult = import__265.Matrix4.abs(matrix, result); expect(returnedResult).toEqual(expected); matrix = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); returnedResult = import__265.Matrix4.abs(matrix, result); expect(returnedResult).toEqual(expected); matrix = new import__265.Matrix4( 1, -2, -3, 4, 5, -6, 7, -8, 9, -10, 11, -12, 13, -14, 15, -16 ); returnedResult = import__265.Matrix4.abs(matrix, result); expect(returnedResult).toEqual(expected); }); it("abs works with a result parameter that is an input result parameter", function() { const matrix = new import__265.Matrix4( -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16 ); const expected = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); const returnedResult = import__265.Matrix4.abs(matrix, matrix); expect(matrix).toBe(returnedResult); expect(matrix).toEqual(expected); }); it("fromArray throws without an array", function() { expect(function() { return import__265.Matrix4.fromArray(); }).toThrowDeveloperError(); }); it("fromRowMajorArray throws with undefined parameter", function() { expect(function() { import__265.Matrix4.fromRowMajorArray(void 0); }).toThrowDeveloperError(); }); it("fromColumnMajorArray throws with undefined parameter", function() { expect(function() { import__265.Matrix4.fromColumnMajorArray(void 0); }).toThrowDeveloperError(); }); it("fromRotationTranslation throws without rotation parameter", function() { expect(function() { import__265.Matrix4.fromRotationTranslation(void 0, new import__265.Cartesian3()); }).toThrowDeveloperError(); }); it("fromTranslationQuaternionRotationScale throws without translation parameter", function() { expect(function() { import__265.Matrix4.fromTranslationQuaternionRotationScale( void 0, new import__265.Quaternion(), new import__265.Cartesian3() ); }).toThrowDeveloperError(); }); it("fromTranslationQuaternionRotationScale throws without rotation parameter", function() { expect(function() { import__265.Matrix4.fromTranslationQuaternionRotationScale( new import__265.Matrix3(), void 0, new import__265.Cartesian3() ); }).toThrowDeveloperError(); }); it("fromTranslationQuaternionRotationScale throws without scale parameter", function() { expect(function() { import__265.Matrix4.fromTranslationQuaternionRotationScale( new import__265.Matrix3(), new import__265.Quaternion(), void 0 ); }).toThrowDeveloperError(); }); it("fromTranslation throws without translation parameter", function() { expect(function() { import__265.Matrix4.fromTranslation(void 0); }).toThrowDeveloperError(); }); it("fromScale throws without scale parameter", function() { expect(function() { import__265.Matrix4.fromScale(void 0); }).toThrowDeveloperError(); }); it("fromUniformScale throws without scale parameter", function() { expect(function() { import__265.Matrix4.fromUniformScale(void 0); }).toThrowDeveloperError(); }); it("fromRotation throws without rotation parameter", function() { expect(function() { import__265.Matrix4.fromRotation(void 0); }).toThrowDeveloperError(); }); it("fromCamera throws without camera", function() { expect(function() { import__265.Matrix4.fromCamera(void 0); }).toThrowDeveloperError(); }); it("fromCamera throws without position", function() { expect(function() { import__265.Matrix4.fromCamera({ direction: import__265.Cartesian3.negate(import__265.Cartesian3.UNIT_Z, new import__265.Cartesian3()), up: import__265.Cartesian3.UNIT_Y }); }).toThrowDeveloperError(); }); it("fromCamera throws without direction", function() { expect(function() { import__265.Matrix4.fromCamera({ position: import__265.Cartesian3.ZERO, up: import__265.Cartesian3.UNIT_Y }); }).toThrowDeveloperError(); }); it("fromCamera throws without up", function() { expect(function() { import__265.Matrix4.fromCamera({ position: import__265.Cartesian3.ZERO, direction: import__265.Cartesian3.negate(import__265.Cartesian3.UNIT_Z, new import__265.Cartesian3()) }); }).toThrowDeveloperError(); }); it("computePerspectiveFieldOfView throws with out of range y field of view", function() { expect(function() { import__265.Matrix4.computePerspectiveFieldOfView(0, 1, 2, 3); }).toThrowDeveloperError(); }); it("computePerspectiveFieldOfView throws with out of range aspect", function() { expect(function() { import__265.Matrix4.computePerspectiveFieldOfView(1, 0, 2, 3); }).toThrowDeveloperError(); }); it("computePerspectiveFieldOfView throws with out of range near", function() { expect(function() { import__265.Matrix4.computePerspectiveFieldOfView(1, 1, 0, 3); }).toThrowDeveloperError(); }); it("computePerspectiveFieldOfView throws with out of range far", function() { expect(function() { import__265.Matrix4.computePerspectiveFieldOfView(1, 1, 2, 0); }).toThrowDeveloperError(); }); it("computeOrthographicOffCenter throws without left", function() { expect(function() { const right = 0, bottom = 0, top = 0, near = 0, far = 0; import__265.Matrix4.computeOrthographicOffCenter( void 0, right, bottom, top, near, far ); }).toThrowDeveloperError(); }); it("computeOrthographicOffCenter throws without right", function() { expect(function() { const left = 0, bottom = 0, top = 0, near = 0, far = 0; import__265.Matrix4.computeOrthographicOffCenter( left, void 0, bottom, top, near, far ); }).toThrowDeveloperError(); }); it("computeOrthographicOffCenter throws without bottom", function() { expect(function() { const left = 0, right = 0, top = 0, near = 0, far = 0; import__265.Matrix4.computeOrthographicOffCenter( left, right, void 0, top, near, far ); }).toThrowDeveloperError(); }); it("computeOrthographicOffCenter throws without top", function() { expect(function() { const left = 0, right = 0, bottom = 0, near = 0, far = 0; import__265.Matrix4.computeOrthographicOffCenter( left, right, bottom, void 0, near, far ); }).toThrowDeveloperError(); }); it("computeOrthographicOffCenter throws without near", function() { expect(function() { const left = 0, right = 0, bottom = 0, top = 0, far = 0; import__265.Matrix4.computeOrthographicOffCenter( left, right, bottom, top, void 0, far ); }).toThrowDeveloperError(); }); it("computeOrthographicOffCenter throws without far", function() { expect(function() { const left = 0, right = 0, bottom = 0, top = 0, near = 0; import__265.Matrix4.computeOrthographicOffCenter( left, right, bottom, top, near, void 0 ); }).toThrowDeveloperError(); }); it("computePerspectiveOffCenter throws without left", function() { expect(function() { const right = 0, bottom = 0, top = 0, near = 0, far = 0; import__265.Matrix4.computePerspectiveOffCenter( void 0, right, bottom, top, near, far ); }).toThrowDeveloperError(); }); it("computePerspectiveOffCenter throws without right", function() { expect(function() { const left = 0, bottom = 0, top = 0, near = 0, far = 0; import__265.Matrix4.computePerspectiveOffCenter( left, void 0, bottom, top, near, far ); }).toThrowDeveloperError(); }); it("computePerspectiveOffCenter throws without bottom", function() { expect(function() { const left = 0, right = 0, top = 0, near = 0, far = 0; import__265.Matrix4.computePerspectiveOffCenter( left, right, void 0, top, near, far ); }).toThrowDeveloperError(); }); it("computePerspectiveOffCenter throws without top", function() { expect(function() { const left = 0, right = 0, bottom = 0, near = 0, far = 0; import__265.Matrix4.computePerspectiveOffCenter( left, right, bottom, void 0, near, far ); }).toThrowDeveloperError(); }); it("computePerspectiveOffCenter throws without near", function() { expect(function() { const left = 0, right = 0, bottom = 0, top = 0, far = 0; import__265.Matrix4.computePerspectiveOffCenter( left, right, bottom, top, void 0, far ); }).toThrowDeveloperError(); }); it("computePerspectiveOffCenter throws without far", function() { expect(function() { const left = 0, right = 0, bottom = 0, top = 0, near = 0; import__265.Matrix4.computePerspectiveOffCenter( left, right, bottom, top, near, void 0 ); }).toThrowDeveloperError(); }); it("computeInfinitePerspectiveOffCenter throws without left", function() { expect(function() { const right = 0, bottom = 0, top = 0, near = 0, far = 0; import__265.Matrix4.computeInfinitePerspectiveOffCenter( void 0, right, bottom, top, near, far ); }).toThrowDeveloperError(); }); it("computeInfinitePerspectiveOffCenter throws without right", function() { expect(function() { const left = 0, bottom = 0, top = 0, near = 0, far = 0; import__265.Matrix4.computeInfinitePerspectiveOffCenter( left, void 0, bottom, top, near, far ); }).toThrowDeveloperError(); }); it("computeInfinitePerspectiveOffCenter throws without bottom", function() { expect(function() { const left = 0, right = 0, top = 0, near = 0, far = 0; import__265.Matrix4.computeInfinitePerspectiveOffCenter( left, right, void 0, top, near, far ); }).toThrowDeveloperError(); }); it("computeInfinitePerspectiveOffCenter throws without top", function() { expect(function() { const left = 0, right = 0, bottom = 0, near = 0, far = 0; import__265.Matrix4.computeInfinitePerspectiveOffCenter( left, right, bottom, void 0, near, far ); }).toThrowDeveloperError(); }); it("computeInfinitePerspectiveOffCenter throws without near", function() { expect(function() { const left = 0, right = 0, bottom = 0, top = 0, far = 0; import__265.Matrix4.computeInfinitePerspectiveOffCenter( left, right, bottom, top, void 0, far ); }).toThrowDeveloperError(); }); it("computeView throws without position", function() { expect(function() { const direction = import__265.Cartesian3.UNIT_Z; const up = import__265.Cartesian3.UNIT_Y; const right = import__265.Cartesian3.UNIT_X; import__265.Matrix4.computeView(void 0, direction, up, right, new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("computeView throws without direction", function() { expect(function() { const position = import__265.Cartesian3.ZERO; const up = import__265.Cartesian3.UNIT_Y; const right = import__265.Cartesian3.UNIT_X; import__265.Matrix4.computeView(position, void 0, up, right, new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("computeView throws without up", function() { expect(function() { const position = import__265.Cartesian3.ZERO; const direction = import__265.Cartesian3.UNIT_Z; const right = import__265.Cartesian3.UNIT_X; import__265.Matrix4.computeView(position, direction, void 0, right, new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("computeView throws without right", function() { expect(function() { const position = import__265.Cartesian3.ZERO; const direction = import__265.Cartesian3.UNIT_Z; const up = import__265.Cartesian3.UNIT_Y; import__265.Matrix4.computeView(position, direction, up, void 0, new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("clone returns undefined without matrix parameter", function() { expect(import__265.Matrix4.clone(void 0)).toBeUndefined(); }); it("toArray throws without matrix parameter", function() { expect(function() { import__265.Matrix4.toArray(void 0); }).toThrowDeveloperError(); }); it("getElement throws without row parameter", function() { let row; const col = 0; expect(function() { import__265.Matrix4.getElementIndex(col, row); }).toThrowDeveloperError(); }); it("getElement throws without column parameter", function() { const row = 0; let col; expect(function() { import__265.Matrix4.getElementIndex(col, row); }).toThrowDeveloperError(); }); it("getColumn throws without matrix parameter", function() { expect(function() { import__265.Matrix4.getColumn(void 0, 1); }).toThrowDeveloperError(); }); it("getColumn throws with out of range index parameter", function() { const matrix = new import__265.Matrix4(); expect(function() { import__265.Matrix4.getColumn(matrix, 4); }).toThrowDeveloperError(); }); it("setColumn throws without matrix parameter", function() { const cartesian = new import__265.Cartesian4(); expect(function() { import__265.Matrix4.setColumn(void 0, 2, cartesian); }).toThrowDeveloperError(); }); it("setColumn throws without cartesian parameter", function() { const matrix = new import__265.Matrix4(); expect(function() { import__265.Matrix4.setColumn(matrix, 1, void 0); }).toThrowDeveloperError(); }); it("setColumn throws with out of range index parameter", function() { const matrix = new import__265.Matrix4(); const cartesian = new import__265.Cartesian4(); expect(function() { import__265.Matrix4.setColumn(matrix, 4, cartesian); }).toThrowDeveloperError(); }); it("setColumn throws without matrix parameter", function() { const cartesian = new import__265.Cartesian4(); expect(function() { import__265.Matrix4.setColumn(void 0, 2, cartesian); }).toThrowDeveloperError(); }); it("setTranslation throws without matrix parameter", function() { expect(function() { import__265.Matrix4.setTranslation(void 0, new import__265.Cartesian3(), new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("setTranslation throws without translation parameter", function() { expect(function() { import__265.Matrix4.setTranslation(new import__265.Matrix4(), void 0, new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("setTranslation throws without a result parameter", function() { expect(function() { import__265.Matrix4.setTranslation(new import__265.Matrix4(), new import__265.Cartesian3(), void 0); }).toThrowDeveloperError(); }); it("getRow throws with out of range index parameter", function() { const matrix = new import__265.Matrix4(); expect(function() { import__265.Matrix4.getRow(matrix, 4); }).toThrowDeveloperError(); }); it("setRow throws without matrix parameter", function() { const cartesian = new import__265.Cartesian4(); expect(function() { import__265.Matrix4.setRow(void 0, 2, cartesian); }).toThrowDeveloperError(); }); it("setRow throws without cartesian parameter", function() { const matrix = new import__265.Matrix4(); expect(function() { import__265.Matrix4.setRow(matrix, 1, void 0); }).toThrowDeveloperError(); }); it("setRow throws with out of range index parameter", function() { const matrix = new import__265.Matrix4(); const cartesian = new import__265.Cartesian4(); expect(function() { import__265.Matrix4.setRow(matrix, 4, cartesian); }).toThrowDeveloperError(); }); it("setScale throws without a matrix", function() { expect(function() { import__265.Matrix4.setScale(); }).toThrowDeveloperError(); }); it("setScale throws without a scale", function() { expect(function() { import__265.Matrix4.setScale(new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("setUniformScale throws without a matrix", function() { expect(function() { import__265.Matrix4.setUniformScale(); }).toThrowDeveloperError(); }); it("setUniformScale throws without a scale", function() { expect(function() { import__265.Matrix4.setUniformScale(new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("getScale throws without a matrix", function() { expect(function() { import__265.Matrix4.getScale(); }).toThrowDeveloperError(); }); it("getMaximumScale throws without a matrix", function() { expect(function() { import__265.Matrix4.getMaximumScale(); }).toThrowDeveloperError(); }); it("setRotation throws without a matrix", function() { expect(function() { return import__265.Matrix4.setRotation(); }).toThrowDeveloperError(); }); it("setRotation throws without a rotation", function() { expect(function() { return import__265.Matrix4.setRotation(new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("getRotation throws without a matrix", function() { expect(function() { return import__265.Matrix4.getRotation(); }).toThrowDeveloperError(); }); it("multiply throws with no left parameter", function() { const right = new import__265.Matrix4(); expect(function() { import__265.Matrix4.multiply(void 0, right); }).toThrowDeveloperError(); }); it("multiply throws with no right parameter", function() { const left = new import__265.Matrix4(); expect(function() { import__265.Matrix4.multiply(left, void 0); }).toThrowDeveloperError(); }); it("multiplyByTranslation throws with no matrix parameter", function() { const translation = new import__265.Cartesian3(); expect(function() { import__265.Matrix4.multiplyByTranslation(void 0, translation); }).toThrowDeveloperError(); }); it("multiplyByTranslation throws with no translation parameter", function() { const m = new import__265.Matrix4(); expect(function() { import__265.Matrix4.multiplyByTranslation(m, void 0); }).toThrowDeveloperError(); }); it("multiplyByScale throws with no matrix parameter", function() { expect(function() { import__265.Matrix4.multiplyByScale(); }).toThrowDeveloperError(); }); it("multiplyByScale throws with no scale parameter", function() { expect(function() { import__265.Matrix4.multiplyByScale(new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("multiplyByUniformScale throws with no matrix parameter", function() { expect(function() { import__265.Matrix4.multiplyByUniformScale(); }).toThrowDeveloperError(); }); it("multiplyByUniformScale throws with no scale parameter", function() { expect(function() { import__265.Matrix4.multiplyByUniformScale(new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("multiplyByVector throws with no matrix parameter", function() { const cartesian = new import__265.Cartesian4(); expect(function() { import__265.Matrix4.multiplyByVector(void 0, cartesian); }).toThrowDeveloperError(); }); it("multiplyByVector throws with no cartesian parameter", function() { const matrix = new import__265.Matrix4(); expect(function() { import__265.Matrix4.multiplyByVector(matrix, void 0); }).toThrowDeveloperError(); }); it("multiplyByPoint throws with no matrix parameter", function() { const cartesian = new import__265.Cartesian4(); expect(function() { import__265.Matrix4.multiplyByPoint(void 0, cartesian); }).toThrowDeveloperError(); }); it("multiplyByPoint throws with no cartesian parameter", function() { const matrix = new import__265.Matrix4(); expect(function() { import__265.Matrix4.multiplyByPoint(matrix, void 0); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with no matrix parameter", function() { expect(function() { import__265.Matrix4.multiplyByScalar(void 0, 2); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with non-numeric scalar parameter", function() { const matrix = new import__265.Matrix4(); expect(function() { import__265.Matrix4.multiplyByScalar(matrix, {}); }).toThrowDeveloperError(); }); it("negate throws without matrix parameter", function() { expect(function() { import__265.Matrix4.negate(void 0); }).toThrowDeveloperError(); }); it("transpose throws without matrix parameter", function() { expect(function() { import__265.Matrix4.transpose(void 0); }).toThrowDeveloperError(); }); it("getTranslation throws without matrix parameter", function() { expect(function() { import__265.Matrix4.getTranslation(void 0); }).toThrowDeveloperError(); }); it("getMatrix3 throws without matrix parameter", function() { expect(function() { import__265.Matrix4.getMatrix3(void 0); }).toThrowDeveloperError(); }); it("inverse throws without matrix parameter", function() { expect(function() { import__265.Matrix4.inverse(void 0); }).toThrowDeveloperError(); }); it("inverse throws with non-inversable matrix", function() { const matrix = new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ); expect(function() { import__265.Matrix4.inverse(matrix, new import__265.Matrix4()); }).toThrowError(import__265.RuntimeError); }); it("inverseTransformation throws without matrix parameter", function() { expect(function() { import__265.Matrix4.inverseTransformation(void 0); }).toThrowDeveloperError(); }); it("getColumn throws without a result parameter", function() { expect(function() { import__265.Matrix4.getColumn(new import__265.Matrix4(), 2); }).toThrowDeveloperError(); }); it("setColumn throws without a result parameter", function() { expect(function() { import__265.Matrix4.setColumn(new import__265.Matrix4(), 2, new import__265.Cartesian4()); }).toThrowDeveloperError(); }); it("getRow throws without a result parameter", function() { expect(function() { import__265.Matrix4.getRow(new import__265.Matrix4(), 2); }).toThrowDeveloperError(); }); it("setRow throws without a result parameter", function() { expect(function() { import__265.Matrix4.setRow(new import__265.Matrix4(), 2, new import__265.Cartesian4()); }).toThrowDeveloperError(); }); it("setScale throws without a result parameter", function() { expect(function() { import__265.Matrix4.setScale(new import__265.Matrix4(), new import__265.Cartesian3()); }).toThrowDeveloperError(); }); it("setUniformScale throws without a result parameter", function() { expect(function() { import__265.Matrix4.setUniformScale(new import__265.Matrix4(), 1); }).toThrowDeveloperError(); }); it("getScale throws without a result parameter", function() { expect(function() { import__265.Matrix4.getScale(new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("setRotation throws without a result parameter", function() { expect(function() { return import__265.Matrix4.setRotation(new import__265.Matrix4(), new import__265.Matrix3()); }).toThrowDeveloperError(); }); it("getRotation throws without a result parameter", function() { expect(function() { return import__265.Matrix4.getRotation(new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("multiply throws without a result parameter", function() { expect(function() { import__265.Matrix4.multiply(new import__265.Matrix4(), new import__265.Matrix3()); }).toThrowDeveloperError(); }); it("multiplyByVector throws without a result parameter", function() { expect(function() { import__265.Matrix4.multiplyByVector(new import__265.Matrix4(), new import__265.Cartesian4()); }).toThrowDeveloperError(); }); it("multiplyByScalar throws without a result parameter", function() { expect(function() { import__265.Matrix4.multiplyByScalar(new import__265.Matrix4(), 2); }).toThrowDeveloperError(); }); it("negate throws without a result parameter", function() { expect(function() { import__265.Matrix4.negate(new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("transpose throws without a result parameter", function() { expect(function() { import__265.Matrix4.transpose(new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("abs throws without a result parameter", function() { expect(function() { import__265.Matrix4.abs(new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("inverse throws without a result parameter", function() { expect(function() { import__265.Matrix4.inverse(new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("multiplyTransformation throws without left parameter", function() { expect(function() { import__265.Matrix4.multiplyTransformation(); }).toThrowDeveloperError(); }); it("multiplyTransformation throws without right parameter", function() { expect(function() { import__265.Matrix4.multiplyTransformation(new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("multiplyTransformation throws without a result parameter", function() { expect(function() { import__265.Matrix4.multiplyTransformation(new import__265.Matrix4(), new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("multiplyByMatrix3 throws without left parameter", function() { expect(function() { import__265.Matrix4.multiplyByMatrix3(); }).toThrowDeveloperError(); }); it("multiplyByMatrix3 throws without matrix parameter", function() { expect(function() { import__265.Matrix4.multiplyByMatrix3(new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("multiplyByMatrix3 throws without rotation parameter", function() { expect(function() { import__265.Matrix4.multiplyByMatrix3(new import__265.Matrix4(), new import__265.Matrix3()); }).toThrowDeveloperError(); }); it("multiplyByScale throws without a result parameter", function() { expect(function() { import__265.Matrix4.multiplyByScale(new import__265.Matrix4(), new import__265.Cartesian3()); }).toThrowDeveloperError(); }); it("multiplyByUniformScale throws without a result parameter", function() { expect(function() { import__265.Matrix4.multiplyByUniformScale(new import__265.Matrix4(), 2); }).toThrowDeveloperError(); }); it("multiplyByPointAsVector throws without matrix parameter", function() { expect(function() { import__265.Matrix4.multiplyByPointAsVector(); }).toThrowDeveloperError(); }); it("multiplyByPointAsVector throws without cartesian parameter", function() { expect(function() { import__265.Matrix4.multiplyByPointAsVector(new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("multiplyByPointAsVector throws without a result parameter", function() { expect(function() { import__265.Matrix4.multiplyByPointAsVector(new import__265.Matrix4(), new import__265.Cartesian3()); }).toThrowDeveloperError(); }); it("multiplyByPoint throws without matrix parameter", function() { expect(function() { import__265.Matrix4.multiplyByPoint(new import__265.Matrix4(), new import__265.Cartesian3()); }).toThrowDeveloperError(); }); it("getTranslation throws without a result parameter", function() { expect(function() { import__265.Matrix4.getTranslation(new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("getMatrix3 throws without a result parameter", function() { expect(function() { import__265.Matrix4.getMatrix3(new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("inverseTransformtation throws without a result parameter", function() { expect(function() { import__265.Matrix4.inverseTransformation(new import__265.Matrix4()); }).toThrowDeveloperError(); }); it("multiplyByTranslation throws without a result parameter", function() { expect(function() { import__265.Matrix4.multiplyByTranslation(new import__265.Matrix4(), new import__265.Cartesian3()); }).toThrowDeveloperError(); }); it("computePerspectiveFieldOfView throws without a result parameter", function() { expect(function() { import__265.Matrix4.computePerspectiveFieldOfView(import__266.Math.PI_OVER_TWO, 1, 1, 10); }).toThrowDeveloperError(); }); it("computeOrthographicOffCenter throws without a result parameter", function() { expect(function() { const left = 0, right = 0, bottom = 0, top = 0, near = 0, far = 0; import__265.Matrix4.computeOrthographicOffCenter(left, right, bottom, top, near, far); }).toThrowDeveloperError(); }); it("computePerspectiveOffCenter throws without a result parameter", function() { expect(function() { const left = 0, right = 0, bottom = 0, top = 0, near = 0, far = 0; import__265.Matrix4.computePerspectiveOffCenter(left, right, bottom, top, near, far); }).toThrowDeveloperError(); }); it("computeInfinitePerspectiveOffCenter throws without a result parameter", function() { expect(function() { const left = 0, right = 0, bottom = 0, top = 0, near = 0; import__265.Matrix4.computeInfinitePerspectiveOffCenter( left, right, bottom, top, near ); }).toThrowDeveloperError(); }); it("computeView throws without a result parameter", function() { expect(function() { const position = import__265.Cartesian3.ONE; const direction = import__265.Cartesian3.UNIT_Z; const up = import__265.Cartesian3.UNIT_Y; const right = import__265.Cartesian3.UNIT_X; import__265.Matrix4.computeView(position, direction, up, right); }).toThrowDeveloperError(); }); it("Matrix4 objects can be used as array like objects", function() { const matrix = new import__265.Matrix4( 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16 ); expect(matrix.length).toEqual(16); const intArray = new Uint32Array(matrix.length); intArray.set(matrix); for (let index = 0; index < matrix.length; index++) { expect(intArray[index]).toEqual(index + 1); } }); createPackableSpecs_default( import__265.Matrix4, new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ), [1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16] ); createPackableArraySpecs_default( import__265.Matrix4, [ new import__265.Matrix4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ), new import__265.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ), new import__265.Matrix4( 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4 ) ], [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4 ], 16 ); }); // packages/engine/Specs/Core/MortonOrderSpec.js var import__267 = __toESM(require_Cesium(), 1); describe("Core/MortonOrder", function() { it("encode2D throws for undefined inputs", function() { expect(function() { return import__267.MortonOrder.encode2D(void 0, 0); }).toThrowDeveloperError(); expect(function() { return import__267.MortonOrder.encode2D(0, void 0); }).toThrowDeveloperError(); }); it("encode2D throws for out of range inputs", function() { expect(function() { return import__267.MortonOrder.encode2D(-1, 0); }).toThrowDeveloperError(); expect(function() { return import__267.MortonOrder.encode2D(0, -1); }).toThrowDeveloperError(); expect(function() { return import__267.MortonOrder.encode2D(65536, 0); }).toThrowDeveloperError(); expect(function() { return import__267.MortonOrder.encode2D(0, 65536); }).toThrowDeveloperError(); }); it("encode2D works", function() { expect(import__267.MortonOrder.encode2D(0, 0)).toEqual(0); expect(import__267.MortonOrder.encode2D(1, 0)).toEqual(1); expect(import__267.MortonOrder.encode2D(0, 1)).toEqual(2); expect(import__267.MortonOrder.encode2D(1, 1)).toEqual(3); expect(import__267.MortonOrder.encode2D(2, 0)).toEqual(4); expect(import__267.MortonOrder.encode2D(3, 0)).toEqual(5); expect(import__267.MortonOrder.encode2D(2, 1)).toEqual(6); expect(import__267.MortonOrder.encode2D(3, 1)).toEqual(7); expect(import__267.MortonOrder.encode2D(7, 5)).toEqual(55); expect(import__267.MortonOrder.encode2D(65535, 65535)).toEqual(4294967295); expect(import__267.MortonOrder.encode2D(65535, 0)).toEqual(1431655765); expect(import__267.MortonOrder.encode2D(0, 65535)).toEqual(2863311530); }); it("decode2D throws for undefined input", function() { expect(function() { return import__267.MortonOrder.decode2D(void 0); }).toThrowDeveloperError(); }); it("decode2D throws for out of range input", function() { expect(function() { return import__267.MortonOrder.decode2D(-1); }).toThrowDeveloperError(); expect(function() { return import__267.MortonOrder.decode2D(4294967296); }).toThrowDeveloperError(); }); it("decode2D uses result parameter", function() { const array = new Array(2); const result = import__267.MortonOrder.decode2D(0, array); expect(result).toBe(array); }); it("decode2D works", function() { expect(import__267.MortonOrder.decode2D(0)).toEqual([0, 0]); expect(import__267.MortonOrder.decode2D(1)).toEqual([1, 0]); expect(import__267.MortonOrder.decode2D(2)).toEqual([0, 1]); expect(import__267.MortonOrder.decode2D(3)).toEqual([1, 1]); expect(import__267.MortonOrder.decode2D(4)).toEqual([2, 0]); expect(import__267.MortonOrder.decode2D(5)).toEqual([3, 0]); expect(import__267.MortonOrder.decode2D(6)).toEqual([2, 1]); expect(import__267.MortonOrder.decode2D(7)).toEqual([3, 1]); expect(import__267.MortonOrder.decode2D(55)).toEqual([7, 5]); expect(import__267.MortonOrder.decode2D(4294967295)).toEqual([65535, 65535]); expect(import__267.MortonOrder.decode2D(1431655765)).toEqual([65535, 0]); expect(import__267.MortonOrder.decode2D(2863311530)).toEqual([0, 65535]); }); it("encode3D throws for undefined inputs", function() { expect(function() { return import__267.MortonOrder.encode3D(void 0, 0, 0); }).toThrowDeveloperError(); expect(function() { return import__267.MortonOrder.encode3D(0, void 0, 0); }).toThrowDeveloperError(); expect(function() { return import__267.MortonOrder.encode3D(0, 0, void 0); }).toThrowDeveloperError(); }); it("encode3D throws for out of range inputs", function() { expect(function() { return import__267.MortonOrder.encode3D(-1, 0, 0); }).toThrowDeveloperError(); expect(function() { return import__267.MortonOrder.encode3D(0, -1, 0); }).toThrowDeveloperError(); expect(function() { return import__267.MortonOrder.encode3D(0, 0, -1); }).toThrowDeveloperError(); expect(function() { return import__267.MortonOrder.encode3D(1024, 0, 0); }).toThrowDeveloperError(); expect(function() { return import__267.MortonOrder.encode3D(0, 1024, 0); }).toThrowDeveloperError(); expect(function() { return import__267.MortonOrder.encode3D(0, 0, 1024); }).toThrowDeveloperError(); }); it("encode3D works", function() { expect(import__267.MortonOrder.encode3D(0, 0, 0)).toEqual(0); expect(import__267.MortonOrder.encode3D(1, 0, 0)).toEqual(1); expect(import__267.MortonOrder.encode3D(0, 1, 0)).toEqual(2); expect(import__267.MortonOrder.encode3D(1, 1, 0)).toEqual(3); expect(import__267.MortonOrder.encode3D(0, 0, 1)).toEqual(4); expect(import__267.MortonOrder.encode3D(1, 0, 1)).toEqual(5); expect(import__267.MortonOrder.encode3D(0, 1, 1)).toEqual(6); expect(import__267.MortonOrder.encode3D(1, 1, 1)).toEqual(7); expect(import__267.MortonOrder.encode3D(1, 3, 3)).toEqual(55); expect(import__267.MortonOrder.encode3D(1023, 1023, 1023)).toEqual(1073741823); expect(import__267.MortonOrder.encode3D(1023, 0, 0)).toEqual(153391689); expect(import__267.MortonOrder.encode3D(0, 1023, 0)).toEqual(306783378); expect(import__267.MortonOrder.encode3D(0, 0, 1023)).toEqual(613566756); }); it("decode3D throws for undefined input", function() { expect(function() { return import__267.MortonOrder.decode3D(void 0); }).toThrowDeveloperError(); }); it("decode3D throws for out of range input", function() { expect(function() { return import__267.MortonOrder.decode3D(-1); }).toThrowDeveloperError(); expect(function() { return import__267.MortonOrder.decode3D(1073741824); }).toThrowDeveloperError(); }); it("decode3D uses result parameter", function() { const array = new Array(3); const result = import__267.MortonOrder.decode3D(0, array); expect(result).toBe(array); }); it("decode3D works", function() { expect(import__267.MortonOrder.decode3D(0)).toEqual([0, 0, 0]); expect(import__267.MortonOrder.decode3D(1)).toEqual([1, 0, 0]); expect(import__267.MortonOrder.decode3D(2)).toEqual([0, 1, 0]); expect(import__267.MortonOrder.decode3D(3)).toEqual([1, 1, 0]); expect(import__267.MortonOrder.decode3D(4)).toEqual([0, 0, 1]); expect(import__267.MortonOrder.decode3D(5)).toEqual([1, 0, 1]); expect(import__267.MortonOrder.decode3D(6)).toEqual([0, 1, 1]); expect(import__267.MortonOrder.decode3D(7)).toEqual([1, 1, 1]); expect(import__267.MortonOrder.decode3D(55)).toEqual([1, 3, 3]); expect(import__267.MortonOrder.decode3D(1073741823)).toEqual([1023, 1023, 1023]); expect(import__267.MortonOrder.decode3D(153391689)).toEqual([1023, 0, 0]); expect(import__267.MortonOrder.decode3D(306783378)).toEqual([0, 1023, 0]); expect(import__267.MortonOrder.decode3D(613566756)).toEqual([0, 0, 1023]); }); }); // packages/engine/Specs/Core/NearFarScalarSpec.js var import__268 = __toESM(require_Cesium(), 1); describe("Core/NearFarScalar", function() { it("constructs without arguments", function() { const scalar = new import__268.NearFarScalar(); expect(scalar.near).toEqual(0); expect(scalar.nearValue).toEqual(0); expect(scalar.far).toEqual(1); expect(scalar.farValue).toEqual(0); }); it("constructs with arguments", function() { const scalar = new import__268.NearFarScalar(1, 1, 1e6, 0.5); expect(scalar.near).toEqual(1); expect(scalar.nearValue).toEqual(1); expect(scalar.far).toEqual(1e6); expect(scalar.farValue).toEqual(0.5); }); it("clone with a result parameter", function() { const scalar = new import__268.NearFarScalar(1, 2, 3, 4); const result = new import__268.NearFarScalar(); const returnedResult = import__268.NearFarScalar.clone(scalar, result); expect(scalar).not.toBe(result); expect(result).toBe(returnedResult); expect(scalar).toEqual(result); }); it("clone without a result parameter", function() { const scalar = new import__268.NearFarScalar(1, 2, 3, 4); const result = import__268.NearFarScalar.clone(scalar); expect(scalar).not.toBe(result); expect(scalar).toEqual(result); }); it('clone works with "this" result parameter', function() { const scalar = new import__268.NearFarScalar(1, 2, 3, 4); const returnedResult = import__268.NearFarScalar.clone(scalar, scalar); expect(scalar).toBe(returnedResult); }); createPackableSpecs_default(import__268.NearFarScalar, new import__268.NearFarScalar(1, 2, 3, 4), [ 1, 2, 3, 4 ]); }); // packages/engine/Specs/Core/OccluderSpec.js var import__269 = __toESM(require_Cesium(), 1); var import__270 = __toESM(require_Cesium(), 1); describe("Core/Occluder", function() { it("throws an exception during construction (1 of 3)", function() { expect(function() { return new import__269.Occluder(); }).toThrowDeveloperError(); }); it("throws an exception during construction (2 of 3)", function() { expect(function() { return new import__269.Occluder(new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, 0))); }).toThrowDeveloperError(); }); it("throws an exception during construction (3 of 3)", function() { expect(function() { return new import__269.Occluder(new import__269.Cartesian3(0, 0, 0)); }).toThrowDeveloperError(); }); it("can entirely eclipse a smaller occludee", function() { const giantSphere = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -1.5), 0.5); const littleSphere = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -2.75), 0.25); const cameraPosition = import__269.Cartesian3.ZERO; const occluder = new import__269.Occluder(giantSphere, cameraPosition); expect(occluder.isBoundingSphereVisible(littleSphere)).toEqual(false); expect(occluder.computeVisibility(littleSphere)).toEqual(import__269.Visibility.NONE); }); it("can have a fully visible occludee", function() { const bigSphere = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -1.5), 0.5); const littleSphere = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -2.75), 0.25); const cameraPosition = import__269.Cartesian3.ZERO; const occluder = new import__269.Occluder(littleSphere, cameraPosition); expect(occluder.radius).toBeLessThan(bigSphere.radius); expect(occluder.isBoundingSphereVisible(bigSphere)).toEqual(true); expect(occluder.computeVisibility(bigSphere)).toEqual(import__269.Visibility.FULL); }); it("blocks the occludee when both are aligned and the same size", function() { const sphere1 = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -1.5), 0.5); const sphere2 = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -2.5), 0.5); const cameraPosition = import__269.Cartesian3.ZERO; const occluder = new import__269.Occluder(sphere1, cameraPosition); expect(occluder.isBoundingSphereVisible(sphere2)).toEqual(false); expect(occluder.computeVisibility(sphere2)).toEqual(import__269.Visibility.NONE); }); it("can have a fully visible occludee", function() { const sphere1 = new import__269.BoundingSphere(new import__269.Cartesian3(-1.25, 0, -1.5), 0.5); const sphere2 = new import__269.BoundingSphere(new import__269.Cartesian3(1.25, 0, -1.5), 0.5); const cameraPosition = import__269.Cartesian3.ZERO; const occluder = new import__269.Occluder(sphere1, cameraPosition); expect(occluder.computeVisibility(sphere2)).toEqual(import__269.Visibility.FULL); }); it("can partially block an occludee without intersecting", function() { const cameraPosition = import__269.Cartesian3.ZERO; const occluderBS = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -2), 1); const occluder = new import__269.Occluder(occluderBS, cameraPosition); const occludeeBS = new import__269.BoundingSphere(new import__269.Cartesian3(0.5, 0.5, -3), 1); expect(occluder.computeVisibility(occludeeBS)).toEqual(import__269.Visibility.PARTIAL); }); it("can partially block an occludee when it intersects laterally", function() { const cameraPosition = import__269.Cartesian3.ZERO; const occluderBS = new import__269.BoundingSphere(new import__269.Cartesian3(-0.5, 0, -1), 1); const occluder = new import__269.Occluder(occluderBS, cameraPosition); const occludeeBS = new import__269.BoundingSphere(new import__269.Cartesian3(0.5, 0, -1), 1); expect(occluder.computeVisibility(occludeeBS)).toEqual(import__269.Visibility.PARTIAL); }); it("can partially block an occludee when it intersects vertically", function() { const cameraPosition = import__269.Cartesian3.ZERO; const occluderBS = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -2), 1); const occluder = new import__269.Occluder(occluderBS, cameraPosition); const occludeeBS = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0.5, -2.5), 1); expect(occluder.computeVisibility(occludeeBS)).toEqual(import__269.Visibility.PARTIAL); }); it("reports full visibility when occludee is larger than occluder", function() { const littleSphere = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -1.5), 0.5); const bigSphere = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -3), 1); const cameraPosition = import__269.Cartesian3.ZERO; const occluder = new import__269.Occluder(littleSphere, cameraPosition); expect(occluder.computeVisibility(bigSphere)).toEqual(import__269.Visibility.FULL); }); it("computeVisibility throws without a bounding sphere", function() { const sphere = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -1.5), 0.5); const cameraPosition = import__269.Cartesian3.ZERO; const occluder = new import__269.Occluder(sphere, cameraPosition); expect(function() { occluder.computeVisibility(); }).toThrowDeveloperError(); }); it("can throw errors during computeOccludeePoint (1 of 5)", function() { expect(function() { import__269.Occluder.computeOccludeePoint(); }).toThrowDeveloperError(); }); it("can throw errors during computeOccludeePoint (2 of 5)", function() { const occluderBS = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -5), 1); const occludeePosition = new import__269.Cartesian3(0, 0, -5); const positions = []; expect(function() { import__269.Occluder.computeOccludeePoint(occluderBS, occludeePosition, positions); }).toThrowDeveloperError(); }); it("can throw errors during computeOccludeePoint (3 of 5)", function() { const occluderBS = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -5), 1); const positions = []; expect(function() { import__269.Occluder.computeOccludeePoint( occluderBS, new import__269.Cartesian3(0, 0, -3), positions ); }).toThrowDeveloperError(); }); it("can throw errors during computeOccludeePoint (4 of 5)", function() { const occluderBS = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -5), 1); expect(function() { import__269.Occluder.computeOccludeePoint(occluderBS, new import__269.Cartesian3(0, 0, -3)); }).toThrowDeveloperError(); }); it("can throw errors during computeOccludeePoint (5 of 5)", function() { const occluderBS = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -5), 1); expect(function() { import__269.Occluder.computeOccludeePoint( occluderBS, new import__269.Cartesian3(0, 0, -5), new import__269.Cartesian3(0, 0, -3) ); }).toThrowDeveloperError(); }); it("can compute an occludee point", function() { const occluderBS = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -8), 2); const positions = [ new import__269.Cartesian3(-1.085, 0, -6.221), new import__269.Cartesian3(1.085, 0, -6.221) ]; const tileOccluderSphere = import__269.BoundingSphere.fromPoints(positions); const occludeePosition = tileOccluderSphere.center; const result = import__269.Occluder.computeOccludeePoint( occluderBS, occludeePosition, positions ); expect(result).toEqualEpsilon( new import__269.Cartesian3(0, 0, -5), import__270.Math.EPSILON1 ); }); it("can compute a rotation vector (major axis = 0)", function() { const cameraPosition = import__269.Cartesian3.ZERO; const occluderBS = new import__269.BoundingSphere(new import__269.Cartesian3(5, 0, 0), 2); const occluder = new import__269.Occluder(occluderBS, cameraPosition); const occludeeBS = new import__269.BoundingSphere(new import__269.Cartesian3(8, 0, 0), 1); const occludee = new import__269.Occluder(occludeeBS, cameraPosition); const occluderPosition = occluder.position; const occludeePosition = occludee.position; const occluderPlaneNormal = import__269.Cartesian3.normalize( import__269.Cartesian3.subtract(occludeePosition, occluderPosition, new import__269.Cartesian3()), new import__269.Cartesian3() ); const occluderPlaneD = -import__269.Cartesian3.dot( occluderPlaneNormal, occluderPosition ); const tempVec0 = import__269.Cartesian3.abs( import__269.Cartesian3.clone(occluderPlaneNormal), new import__269.Cartesian3() ); let majorAxis = tempVec0.x > tempVec0.y ? 0 : 1; if (majorAxis === 0 && tempVec0.z > tempVec0.x || majorAxis === 1 && tempVec0.z > tempVec0.y) { majorAxis = 2; } expect(majorAxis).toEqual(0); const aRotationVector = import__269.Occluder._anyRotationVector( occluderPosition, occluderPlaneNormal, occluderPlaneD ); expect(aRotationVector).toBeTruthy(); }); it("can compute a rotation vector (major axis = 1)", function() { const cameraPosition = import__269.Cartesian3.ZERO; const occluderBS = new import__269.BoundingSphere(new import__269.Cartesian3(5, 0, 0), 2); const occluder = new import__269.Occluder(occluderBS, cameraPosition); const occludeeBS = new import__269.BoundingSphere(new import__269.Cartesian3(7, 2, 0), 1); const occludee = new import__269.Occluder(occludeeBS, cameraPosition); const occluderPosition = occluder.position; const occludeePosition = occludee.position; const occluderPlaneNormal = import__269.Cartesian3.normalize( import__269.Cartesian3.subtract(occludeePosition, occluderPosition, new import__269.Cartesian3()), new import__269.Cartesian3() ); const occluderPlaneD = -import__269.Cartesian3.dot( occluderPlaneNormal, occluderPosition ); const tempVec0 = import__269.Cartesian3.abs( import__269.Cartesian3.clone(occluderPlaneNormal), new import__269.Cartesian3() ); let majorAxis = tempVec0.x > tempVec0.y ? 0 : 1; if (majorAxis === 0 && tempVec0.z > tempVec0.x || majorAxis === 1 && tempVec0.z > tempVec0.y) { majorAxis = 2; } expect(majorAxis).toEqual(1); const aRotationVector = import__269.Occluder._anyRotationVector( occluderPosition, occluderPlaneNormal, occluderPlaneD ); expect(aRotationVector).toBeTruthy(); }); it("can compute a rotation vector (major axis = 2)", function() { const cameraPosition = import__269.Cartesian3.ZERO; const occluderBS = new import__269.BoundingSphere(new import__269.Cartesian3(5, 0, 0), 2); const occluder = new import__269.Occluder(occluderBS, cameraPosition); const occludeeBS = new import__269.BoundingSphere(new import__269.Cartesian3(6, 0, 2), 1); const occludee = new import__269.Occluder(occludeeBS, cameraPosition); const occluderPosition = occluder.position; const occludeePosition = occludee.position; const occluderPlaneNormal = import__269.Cartesian3.normalize( import__269.Cartesian3.subtract(occludeePosition, occluderPosition, new import__269.Cartesian3()), new import__269.Cartesian3() ); const occluderPlaneD = -import__269.Cartesian3.dot( occluderPlaneNormal, occluderPosition ); const tempVec0 = import__269.Cartesian3.abs( import__269.Cartesian3.clone(occluderPlaneNormal), new import__269.Cartesian3() ); let majorAxis = tempVec0.x > tempVec0.y ? 0 : 1; if (majorAxis === 0 && tempVec0.z > tempVec0.x || majorAxis === 1 && tempVec0.z > tempVec0.y) { majorAxis = 2; } expect(majorAxis).toEqual(2); const aRotationVector = import__269.Occluder._anyRotationVector( occluderPosition, occluderPlaneNormal, occluderPlaneD ); expect(aRotationVector).toBeTruthy(); }); it("can have an invisible occludee point", function() { const cameraPosition = new import__269.Cartesian3(0, 0, -8); const occluderBS = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -8), 2); const occluder = new import__269.Occluder(occluderBS, cameraPosition); const positions = [ new import__269.Cartesian3(-0.25, 0, -5.3), new import__269.Cartesian3(0.25, 0, -5.3) ]; const tileOccluderSphere = import__269.BoundingSphere.fromPoints(positions); const occludeePosition = tileOccluderSphere.center; const result = import__269.Occluder.computeOccludeePoint( occluderBS, occludeePosition, positions ); const bs = new import__269.BoundingSphere(result, 0); expect(occluder.isBoundingSphereVisible(bs)).toEqual(false); expect(occluder.computeVisibility(bs)).toEqual(import__269.Visibility.NONE); }); it("can have a visible occludee point", function() { const cameraPosition = new import__269.Cartesian3(3, 0, -8); const occluderBS = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -8), 2); const occluder = new import__269.Occluder(occluderBS, cameraPosition); const positions = [ new import__269.Cartesian3(-0.25, 0, -5.3), new import__269.Cartesian3(0.25, 0, -5.3) ]; const tileOccluderSphere = import__269.BoundingSphere.fromPoints(positions); const occludeePosition = tileOccluderSphere.center; const result = import__269.Occluder.computeOccludeePoint( occluderBS, occludeePosition, positions ); expect( occluder.isBoundingSphereVisible(new import__269.BoundingSphere(result, 0)) ).toEqual(true); }); it("compute occludee point from rectangle throws without a rectangle", function() { expect(function() { return import__269.Occluder.computeOccludeePointFromRectangle(); }).toThrowDeveloperError(); }); it("compute invalid occludee point from rectangle", function() { const rectangle = import__269.Rectangle.MAX_VALUE; expect(import__269.Occluder.computeOccludeePointFromRectangle(rectangle)).toEqual( void 0 ); }); it("compute valid occludee point from rectangle", function() { const edge = Math.PI / 32; const rectangle = new import__269.Rectangle(-edge, -edge, edge, edge); const ellipsoid = import__269.Ellipsoid.WGS84; const positions = import__269.Rectangle.subsample(rectangle, ellipsoid); const bs = import__269.BoundingSphere.fromPoints(positions); const point = import__269.Occluder.computeOccludeePoint( new import__269.BoundingSphere(import__269.Cartesian3.ZERO, ellipsoid.minimumRadius), bs.center, positions ); const actual = import__269.Occluder.computeOccludeePointFromRectangle(rectangle); expect(actual).toEqual(point); }); it("fromBoundingSphere throws without a bounding sphere", function() { expect(function() { import__269.Occluder.fromBoundingSphere(); }).toThrowDeveloperError(); }); it("fromBoundingSphere throws without camera position", function() { expect(function() { import__269.Occluder.fromBoundingSphere(new import__269.BoundingSphere()); }).toThrowDeveloperError(); }); it("fromBoundingSphere without result parameter", function() { const cameraPosition = new import__269.Cartesian3(3, 0, -8); const occluderBS = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -8), 2); const occluder0 = new import__269.Occluder(occluderBS, cameraPosition); const occluder1 = import__269.Occluder.fromBoundingSphere(occluderBS, cameraPosition); expect(occluder1.position).toEqual(occluder0.position); expect(occluder1.radius).toEqual(occluder0.radius); }); it("fromBoundingSphere with result parameter", function() { const cameraPosition = new import__269.Cartesian3(3, 0, -8); const occluderBS = new import__269.BoundingSphere(new import__269.Cartesian3(0, 0, -8), 2); const occluder0 = new import__269.Occluder(occluderBS, cameraPosition); const result = new import__269.Occluder(occluderBS, import__269.Cartesian3.ZERO); const occluder1 = import__269.Occluder.fromBoundingSphere( occluderBS, cameraPosition, result ); expect(occluder1).toBe(result); expect(occluder1.position).toEqual(occluder0.position); expect(occluder1.radius).toEqual(occluder0.radius); }); }); // packages/engine/Specs/Core/OpenCageGeocoderServiceSpec.js var import__271 = __toESM(require_Cesium(), 1); describe("Core/OpenCageGeocoderService", function() { const endpoint = "https://api.opencagedata.com/geocode/v1/"; const apiKey = "c2a490d593b14612aefa6ec2e6b77c47"; it("conforms to GeocoderService interface", function() { expect(import__271.OpenCageGeocoderService).toConformToInterface(import__271.GeocoderService); }); it("constructor throws without url", function() { expect(function() { return new import__271.OpenCageGeocoderService(void 0); }).toThrowDeveloperError(); }); it("constructor throws without API Key", function() { expect(function() { return new import__271.OpenCageGeocoderService(endpoint, void 0); }).toThrowDeveloperError(); }); it("returns geocoder results", async function() { const service = new import__271.OpenCageGeocoderService(endpoint, apiKey); const query = "-22.6792,+14.5272"; const data = { results: [ { bounds: { northeast: { lat: -22.6790826, lng: 14.5269016 }, southwest: { lat: -22.6792826, lng: 14.5267016 } }, formatted: "Beryl's Restaurant, Woermann St, Swakopmund, Namibia", geometry: { lat: -22.6795394, lng: 14.5276006 } } ] }; spyOn(import__271.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(data) ); const results = await service.geocode(query); expect(results.length).toEqual(1); expect(results[0].displayName).toEqual(data.results[0].formatted); expect(results[0].destination).toBeDefined(); }); it("returns no geocoder results if OpenCage has no results", async function() { const service = new import__271.OpenCageGeocoderService(endpoint, apiKey); const query = ""; const data = { results: [] }; spyOn(import__271.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(data) ); const results = await service.geocode(query); expect(results.length).toEqual(0); }); it("credit returns expected value", async function() { const service = new import__271.OpenCageGeocoderService(endpoint, apiKey); expect(service.credit).toBeInstanceOf(import__271.Credit); expect(service.credit.html).toEqual( `Geodata copyright OpenStreetMap contributors` ); expect(service.credit.showOnScreen).toBe(false); }); }); // packages/engine/Specs/Core/OrientedBoundingBoxSpec.js var import__272 = __toESM(require_Cesium(), 1); var import__273 = __toESM(require_Cesium(), 1); describe("Core/OrientedBoundingBox", function() { const positions = [ new import__272.Cartesian3(2, 0, 0), new import__272.Cartesian3(0, 3, 0), new import__272.Cartesian3(0, 0, 4), new import__272.Cartesian3(-2, 0, 0), new import__272.Cartesian3(0, -3, 0), new import__272.Cartesian3(0, 0, -4) ]; function rotatePositions(positions2, axis, angle) { const points = []; const quaternion = import__272.Quaternion.fromAxisAngle(axis, angle); const rotation = import__272.Matrix3.fromQuaternion(quaternion); for (let i = 0; i < positions2.length; ++i) { points.push( import__272.Matrix3.multiplyByVector(rotation, positions2[i], new import__272.Cartesian3()) ); } return { points, rotation }; } function translatePositions(positions2, translation) { const points = []; for (let i = 0; i < positions2.length; ++i) { points.push(import__272.Cartesian3.add(translation, positions2[i], new import__272.Cartesian3())); } return points; } it("constructor sets expected default values", function() { const box = new import__272.OrientedBoundingBox(); expect(box.center).toEqual(import__272.Cartesian3.ZERO); expect(box.halfAxes).toEqual(import__272.Matrix3.ZERO); }); it("fromPoints constructs empty box with undefined positions", function() { const box = import__272.OrientedBoundingBox.fromPoints(void 0); expect(box.halfAxes).toEqual(import__272.Matrix3.ZERO); expect(box.center).toEqual(import__272.Cartesian3.ZERO); }); it("fromPoints constructs empty box with empty positions", function() { const box = import__272.OrientedBoundingBox.fromPoints([]); expect(box.halfAxes).toEqual(import__272.Matrix3.ZERO); expect(box.center).toEqual(import__272.Cartesian3.ZERO); }); it("fromPoints correct scale", function() { const box = import__272.OrientedBoundingBox.fromPoints(positions); expect(box.halfAxes).toEqual( import__272.Matrix3.fromScale(new import__272.Cartesian3(2, 3, 4)) ); expect(box.center).toEqual(import__272.Cartesian3.ZERO); }); it("fromPoints correct translation", function() { const translation = new import__272.Cartesian3(10, -20, 30); const points = translatePositions(positions, translation); const box = import__272.OrientedBoundingBox.fromPoints(points); expect(box.halfAxes).toEqual( import__272.Matrix3.fromScale(new import__272.Cartesian3(2, 3, 4)) ); expect(box.center).toEqual(translation); }); it("fromPoints rotation about z", function() { const result = rotatePositions( positions, import__272.Cartesian3.UNIT_Z, import__273.Math.PI_OVER_FOUR ); const points = result.points; const rotation = result.rotation; rotation[1] = -rotation[1]; rotation[3] = -rotation[3]; const box = import__272.OrientedBoundingBox.fromPoints(points); expect(box.halfAxes).toEqualEpsilon( import__272.Matrix3.multiplyByScale( rotation, new import__272.Cartesian3(3, 2, 4), new import__272.Matrix3() ), import__273.Math.EPSILON15 ); expect(box.center).toEqualEpsilon(import__272.Cartesian3.ZERO, import__273.Math.EPSILON15); }); it("fromPoints rotation about y", function() { const result = rotatePositions( positions, import__272.Cartesian3.UNIT_Y, import__273.Math.PI_OVER_FOUR ); const points = result.points; const rotation = result.rotation; rotation[2] = -rotation[2]; rotation[6] = -rotation[6]; const box = import__272.OrientedBoundingBox.fromPoints(points); expect(box.halfAxes).toEqualEpsilon( import__272.Matrix3.multiplyByScale( rotation, new import__272.Cartesian3(4, 3, 2), new import__272.Matrix3() ), import__273.Math.EPSILON15 ); expect(box.center).toEqualEpsilon(import__272.Cartesian3.ZERO, import__273.Math.EPSILON15); }); it("fromPoints rotation about x", function() { const result = rotatePositions( positions, import__272.Cartesian3.UNIT_X, import__273.Math.PI_OVER_FOUR ); const points = result.points; const rotation = result.rotation; rotation[5] = -rotation[5]; rotation[7] = -rotation[7]; const box = import__272.OrientedBoundingBox.fromPoints(points); expect(box.halfAxes).toEqualEpsilon( import__272.Matrix3.multiplyByScale( rotation, new import__272.Cartesian3(2, 4, 3), new import__272.Matrix3() ), import__273.Math.EPSILON15 ); expect(box.center).toEqualEpsilon(import__272.Cartesian3.ZERO, import__273.Math.EPSILON15); }); it("fromPoints rotation and translation", function() { const result = rotatePositions( positions, import__272.Cartesian3.UNIT_Z, import__273.Math.PI_OVER_FOUR ); let points = result.points; const rotation = result.rotation; rotation[1] = -rotation[1]; rotation[3] = -rotation[3]; const translation = new import__272.Cartesian3(-40, 20, -30); points = translatePositions(points, translation); const box = import__272.OrientedBoundingBox.fromPoints(points); expect(box.halfAxes).toEqualEpsilon( import__272.Matrix3.multiplyByScale( rotation, new import__272.Cartesian3(3, 2, 4), new import__272.Matrix3() ), import__273.Math.EPSILON14 ); expect(box.center).toEqualEpsilon(translation, import__273.Math.EPSILON15); }); it("fromRectangle sets correct default ellipsoid", function() { const rectangle = new import__272.Rectangle(-0.9, -1.2, 0.5, 0.7); const box1 = import__272.OrientedBoundingBox.fromRectangle(rectangle, 0, 0); const box2 = import__272.OrientedBoundingBox.fromRectangle( rectangle, 0, 0, import__272.Ellipsoid.WGS84 ); expect(box1.center).toEqualEpsilon(box2.center, import__273.Math.EPSILON15); expect(box1.halfAxes).toEqualEpsilon(box2.halfAxes, import__273.Math.EPSILON15); }); it("fromRectangle sets correct default heights", function() { const rectangle = new import__272.Rectangle(0, 0, 0, 0); const box = import__272.OrientedBoundingBox.fromRectangle( rectangle, void 0, void 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(1, 0, 0), import__273.Math.EPSILON15 ); const rotScale = import__272.Matrix3.ZERO; expect(box.halfAxes).toEqualEpsilon(rotScale, import__273.Math.EPSILON15); }); it("fromRectangle throws without rectangle", function() { const ellipsoid = import__272.Ellipsoid.UNIT_SPHERE; expect(function() { import__272.OrientedBoundingBox.fromRectangle(void 0, 0, 0, ellipsoid); }).toThrowDeveloperError(); }); it("fromRectangle throws with invalid rectangles", function() { const ellipsoid = import__272.Ellipsoid.UNIT_SPHERE; expect(function() { return import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-1, 1, 1, -1), 0, 0, ellipsoid ); }).toThrowDeveloperError(); expect(function() { return import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-2, 2, -1, 1), 0, 0, ellipsoid ); }).toThrowDeveloperError(); expect(function() { return import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-4, -2, 4, 1), 0, 0, ellipsoid ); }).toThrowDeveloperError(); expect(function() { return import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-2, -2, 1, 2), 0, 0, ellipsoid ); }).toThrowDeveloperError(); expect(function() { return import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-1, -2, 2, 2), 0, 0, ellipsoid ); }).toThrowDeveloperError(); expect(function() { return import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-4, -1, 4, 2), 0, 0, ellipsoid ); }).toThrowDeveloperError(); }); it("fromRectangle throws with non-revolution ellipsoids", function() { const rectangle = new import__272.Rectangle(0, 0, 0, 0); expect(function() { return import__272.OrientedBoundingBox.fromRectangle( rectangle, 0, 0, new import__272.Ellipsoid(1.01, 1, 1.01) ); }).toThrowDeveloperError(); expect(function() { return import__272.OrientedBoundingBox.fromRectangle( rectangle, 0, 0, new import__272.Ellipsoid(1, 1.01, 1.01) ); }).toThrowDeveloperError(); }); it("fromRectangle creates an OrientedBoundingBox without a result parameter", function() { const ellipsoid = import__272.Ellipsoid.UNIT_SPHERE; const rectangle = new import__272.Rectangle(0, 0, 0, 0); const box = import__272.OrientedBoundingBox.fromRectangle( rectangle, 0, 0, ellipsoid ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(1, 0, 0), import__273.Math.EPSILON15 ); const rotScale = import__272.Matrix3.ZERO; expect(box.halfAxes).toEqualEpsilon(rotScale, import__273.Math.EPSILON15); }); it("fromRectangle creates an OrientedBoundingBox with a result parameter", function() { const ellipsoid = import__272.Ellipsoid.UNIT_SPHERE; const rectangle = new import__272.Rectangle(0, 0, 0, 0); const result = new import__272.OrientedBoundingBox(); const box = import__272.OrientedBoundingBox.fromRectangle( rectangle, 0, 0, ellipsoid, result ); expect(box).toBe(result); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(1, 0, 0), import__273.Math.EPSILON15 ); const rotScale = import__272.Matrix3.ZERO; expect(box.halfAxes).toEqualEpsilon(rotScale, import__273.Math.EPSILON15); }); it("fromRectangle for rectangles with heights", function() { const d90 = import__273.Math.PI_OVER_TWO; let box; box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(0, 0, 0, 0), 1, 1, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(2, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon(import__272.Matrix3.ZERO, import__273.Math.EPSILON15); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(0, 0, 0, 0), -1, -1, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon(import__272.Matrix3.ZERO, import__273.Math.EPSILON15); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(0, 0, 0, 0), -1, 1, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(1, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(0, 0, 1, 0, 0, 0, 0, 0, 0), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d90, -d90, d90, d90), 0, 1, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(1, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(0, 0, 1, 2, 0, 0, 0, 2, 0), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d90, -d90, d90, d90), -1, -1, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon(import__272.Matrix3.ZERO, import__273.Math.EPSILON15); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d90, -d90, d90, d90), -1, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0.5, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(0, 0, 0.5, 1, 0, 0, 0, 1, 0), import__273.Math.EPSILON15 ); }); it("fromRectangle for rectangles that span over half the ellipsoid", function() { const d90 = import__273.Math.PI_OVER_TWO; const d180 = import__273.Math.PI; const d135 = 3 / 4 * import__273.Math.PI; const d45 = import__273.Math.PI_OVER_FOUR; const onePlusSqrtHalfDivTwo = (1 + Math.SQRT1_2) / 2; const oneMinusOnePlusSqrtHalfDivTwo = 1 - onePlusSqrtHalfDivTwo; const sqrtTwoMinusOneDivFour = (Math.SQRT2 - 1) / 4; const sqrtTwoPlusOneDivFour = (Math.SQRT2 + 1) / 4; let box; box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d180, -d90, d180, d90), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(0, 0, 1, 1, 0, 0, 0, 1, 0), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d135, -d90, d135, d90), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(oneMinusOnePlusSqrtHalfDivTwo, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(0, 0, onePlusSqrtHalfDivTwo, 1, 0, 0, 0, 1, 0), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d135, -d45, d135, d45), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(oneMinusOnePlusSqrtHalfDivTwo, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(0, 0, onePlusSqrtHalfDivTwo, 1, 0, 0, 0, Math.SQRT1_2, 0), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(d180, -d45, d90, d45), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(sqrtTwoMinusOneDivFour, -sqrtTwoMinusOneDivFour, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3( Math.SQRT1_2, 0, sqrtTwoPlusOneDivFour, Math.SQRT1_2, 0, -sqrtTwoPlusOneDivFour, 0, Math.SQRT1_2, 0 ), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d180, -d45, d180, d45), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(0, 0, 1, 1, 0, 0, 0, Math.SQRT1_2, 0), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d180, d45, d180, d90), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0, 0, onePlusSqrtHalfDivTwo), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3( 0, 0, Math.SQRT1_2, Math.SQRT1_2, 0, 0, 0, oneMinusOnePlusSqrtHalfDivTwo, 0 ), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d180, -d90, d180, -d45), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0, 0, -onePlusSqrtHalfDivTwo), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3( 0, 0, Math.SQRT1_2, Math.SQRT1_2, 0, 0, 0, oneMinusOnePlusSqrtHalfDivTwo, 0 ), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d180, d90, d180, d90), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0, 0, 1), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(0, 0, 0, 0, 0, 0, 0, 0, 0), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d135, d90, d135, d90), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0, 0, 1), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(0, 0, 0, 0, 0, 0, 0, 0, 0), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d180, -d90, d180, -d90), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0, 0, -1), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(0, 0, 0, 0, 0, 0, 0, 0, 0), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d135, -d90, d135, -d90), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0, 0, -1), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(0, 0, 0, 0, 0, 0, 0, 0, 0), import__273.Math.EPSILON15 ); }); it("fromRectangle for interesting, degenerate, and edge-case rectangles", function() { const d45 = import__273.Math.PI_OVER_FOUR; const d30 = import__273.Math.PI_OVER_SIX; const d90 = import__273.Math.PI_OVER_TWO; const d135 = 3 * import__273.Math.PI_OVER_FOUR; const d180 = import__273.Math.PI; const sqrt3 = Math.sqrt(3); let box; box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(0, 0, 0, 0), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(1, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon(import__272.Matrix3.ZERO, import__273.Math.EPSILON15); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(d180, 0, -d180, 0), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(-1, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon(import__272.Matrix3.ZERO, import__273.Math.EPSILON15); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(d180, 0, d180, 0), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(-1, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon(import__272.Matrix3.ZERO, import__273.Math.EPSILON15); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(0, d90, 0, d90), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0, 0, 1), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon(import__272.Matrix3.ZERO, import__273.Math.EPSILON15); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(0, 0, d180, 0), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0, 0.5, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(-1, 0, 0, 0, 0, 0.5, 0, 0, 0), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d90, -d90, d90, d90), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0.5, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(0, 0, 0.5, 1, 0, 0, 0, 1, 0), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d90, -d30, d90, d90), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0.1875 * sqrt3, 0, 0.1875), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(0, -sqrt3 / 4, 5 * sqrt3 / 16, 1, 0, 0, 0, 3 / 4, 5 / 16), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d90, -d90, d90, d30), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0.1875 * sqrt3, 0, -0.1875), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(0, sqrt3 / 4, 5 * sqrt3 / 16, 1, 0, 0, 0, 3 / 4, -5 / 16), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(0, -d30, d180, d90), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0, 0.1875 * sqrt3, 0.1875), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(-1, 0, 0, 0, -sqrt3 / 4, 5 * sqrt3 / 16, 0, 3 / 4, 5 / 16), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(0, -d90, d180, d30), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0, 0.1875 * sqrt3, -0.1875), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(-1, 0, 0, 0, sqrt3 / 4, 5 * sqrt3 / 16, 0, 3 / 4, -5 / 16), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d45, 0, d45, 0), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3((1 + Math.SQRT1_2) / 2, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3( 0, 0, 0.5 * (1 - Math.SQRT1_2), Math.SQRT1_2, 0, 0, 0, 0, 0 ), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(d135, 0, -d135, 0), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(-(1 + Math.SQRT1_2) / 2, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3( 0, 0, -0.5 * (1 - Math.SQRT1_2), -Math.SQRT1_2, 0, 0, 0, 0, 0 ), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(0, -d45, 0, d45), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3((1 + Math.SQRT1_2) / 2, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3( 0, 0, 0.5 * (1 - Math.SQRT1_2), 0, 0, 0, 0, Math.SQRT1_2, 0 ), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(-d90, 0, d90, 0), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0.5, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(0, 0, 0.5, 1, 0, 0, 0, 0, 0), import__273.Math.EPSILON15 ); box = import__272.OrientedBoundingBox.fromRectangle( new import__272.Rectangle(0, -d90, 0, d90), 0, 0, import__272.Ellipsoid.UNIT_SPHERE ); expect(box.center).toEqualEpsilon( new import__272.Cartesian3(0.5, 0, 0), import__273.Math.EPSILON15 ); expect(box.halfAxes).toEqualEpsilon( new import__272.Matrix3(0, 0, 0.5, 0, 0, 0, 0, 1, 0), import__273.Math.EPSILON15 ); }); it("fromTransformation works with a result parameter", function() { const translation = new import__272.Cartesian3(1, 2, 3); const rotation = import__272.Quaternion.fromAxisAngle(import__272.Cartesian3.UNIT_Z, 0.4); const scale = new import__272.Cartesian3(1, 2, 3); const transformation = import__272.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const box = new import__272.OrientedBoundingBox(); import__272.OrientedBoundingBox.fromTransformation(transformation, box); expect(box.center).toEqual(translation); expect(box.halfAxes).toEqualEpsilon( import__272.Matrix3.multiplyByUniformScale( import__272.Matrix4.getMatrix3(transformation, new import__272.Matrix3()), 0.5, new import__272.Matrix3() ), import__273.Math.EPSILON14 ); }); it("fromTransformation works without a result parameter", function() { const translation = new import__272.Cartesian3(1, 2, 3); const rotation = import__272.Quaternion.fromAxisAngle(import__272.Cartesian3.UNIT_Z, 0.4); const scale = new import__272.Cartesian3(1, 2, 3); const transformation = import__272.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const box = import__272.OrientedBoundingBox.fromTransformation(transformation); expect(box.center).toEqual(translation); expect(box.halfAxes).toEqualEpsilon( import__272.Matrix3.multiplyByUniformScale( import__272.Matrix4.getMatrix3(transformation, new import__272.Matrix3()), 0.5, new import__272.Matrix3() ), import__273.Math.EPSILON14 ); }); it("fromTransformation works with a transformation that has zero scale", function() { const transformation = import__272.Matrix4.fromScale(import__272.Cartesian3.ZERO); const box = import__272.OrientedBoundingBox.fromTransformation(transformation); expect(box.center).toEqual(import__272.Cartesian3.ZERO); expect(box.halfAxes).toEqual(import__272.Matrix3.ZERO); }); it("fromTransformation throws with no transformation parameter", function() { expect(function() { import__272.OrientedBoundingBox.fromTransformation(void 0); }).toThrowDeveloperError(); }); const intersectPlaneTestCornersEdgesFaces = function(center, axes) { const SQRT1_2 = Math.pow(1 / 2, 1 / 2); const SQRT3_4 = Math.pow(3 / 4, 1 / 2); const box = new import__272.OrientedBoundingBox( center, import__272.Matrix3.multiplyByScalar(axes, 0.5, new import__272.Matrix3()) ); const planeNormXform = function(nx, ny, nz, dist) { const n = new import__272.Cartesian3(nx, ny, nz); const arb = new import__272.Cartesian3(357, 924, 258); const p0 = import__272.Cartesian3.normalize(n, new import__272.Cartesian3()); import__272.Cartesian3.multiplyByScalar(p0, -dist, p0); const tang = import__272.Cartesian3.cross(n, arb, new import__272.Cartesian3()); import__272.Cartesian3.normalize(tang, tang); const binorm = import__272.Cartesian3.cross(n, tang, new import__272.Cartesian3()); import__272.Cartesian3.normalize(binorm, binorm); import__272.Matrix3.multiplyByVector(axes, p0, p0); import__272.Matrix3.multiplyByVector(axes, tang, tang); import__272.Matrix3.multiplyByVector(axes, binorm, binorm); import__272.Cartesian3.cross(tang, binorm, n); if (import__272.Cartesian3.magnitude(n) === 0) { return void 0; } import__272.Cartesian3.normalize(n, n); import__272.Cartesian3.add(p0, center, p0); const d = -import__272.Cartesian3.dot(p0, n); if (Math.abs(d) > 1e-4 && import__272.Cartesian3.magnitudeSquared(n) > 1e-4) { return new import__272.Plane(n, d); } return void 0; }; let pl; pl = planeNormXform(1, 0, 0, 0.50001); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(-1, 0, 0, 0.50001); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(0, 1, 0, 0.50001); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(0, -1, 0, 0.50001); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(0, 0, 1, 0.50001); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(0, 0, -1, 0.50001); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(1, 0, 0, 0.49999); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, 0, 0, 0.49999); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(0, 1, 0, 0.49999); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(0, -1, 0, 0.49999); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(0, 0, 1, 0.49999); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(0, 0, -1, 0.49999); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, 0, 0, -0.49999); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, 0, 0, -0.49999); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(0, 1, 0, -0.49999); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(0, -1, 0, -0.49999); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(0, 0, 1, -0.49999); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(0, 0, -1, -0.49999); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, 0, 0, -0.50001); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(-1, 0, 0, -0.50001); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(0, 1, 0, -0.50001); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(0, -1, 0, -0.50001); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(0, 0, 1, -0.50001); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(0, 0, -1, -0.50001); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(1, 1, 0, SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(1, -1, 0, SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(-1, 1, 0, SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(-1, -1, 0, SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(1, 0, 1, SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(1, 0, -1, SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(-1, 0, 1, SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(-1, 0, -1, SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(0, 1, 1, SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(0, 1, -1, SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(0, -1, 1, SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(0, -1, -1, SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(1, 1, 0, SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, -1, 0, SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, 1, 0, SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, -1, 0, SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, 0, 1, SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, 0, -1, SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, 0, 1, SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, 0, -1, SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(0, 1, 1, SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(0, 1, -1, SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(0, -1, 1, SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(0, -1, -1, SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, 1, 0, -SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, -1, 0, -SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, 1, 0, -SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, -1, 0, -SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, 0, 1, -SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, 0, -1, -SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, 0, 1, -SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, 0, -1, -SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(0, 1, 1, -SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(0, 1, -1, -SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(0, -1, 1, -SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(0, -1, -1, -SQRT1_2 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, 1, 0, -SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(1, -1, 0, -SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(-1, 1, 0, -SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(-1, -1, 0, -SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(1, 0, 1, -SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(1, 0, -1, -SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(-1, 0, 1, -SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(-1, 0, -1, -SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(0, 1, 1, -SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(0, 1, -1, -SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(0, -1, 1, -SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(0, -1, -1, -SQRT1_2 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(1, 1, 1, SQRT3_4 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(1, 1, -1, SQRT3_4 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(1, -1, 1, SQRT3_4 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(1, -1, -1, SQRT3_4 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(-1, 1, 1, SQRT3_4 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(-1, 1, -1, SQRT3_4 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(-1, -1, 1, SQRT3_4 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(-1, -1, -1, SQRT3_4 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INSIDE); } pl = planeNormXform(1, 1, 1, SQRT3_4 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, 1, -1, SQRT3_4 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, -1, 1, SQRT3_4 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, -1, -1, SQRT3_4 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, 1, 1, SQRT3_4 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, 1, -1, SQRT3_4 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, -1, 1, SQRT3_4 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, -1, -1, SQRT3_4 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, 1, 1, -SQRT3_4 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, 1, -1, -SQRT3_4 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, -1, 1, -SQRT3_4 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, -1, -1, -SQRT3_4 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, 1, 1, -SQRT3_4 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, 1, -1, -SQRT3_4 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, -1, 1, -SQRT3_4 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(-1, -1, -1, -SQRT3_4 + 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.INTERSECTING); } pl = planeNormXform(1, 1, 1, -SQRT3_4 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(1, 1, -1, -SQRT3_4 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(1, -1, 1, -SQRT3_4 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(1, -1, -1, -SQRT3_4 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(-1, 1, 1, -SQRT3_4 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(-1, 1, -1, -SQRT3_4 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(-1, -1, 1, -SQRT3_4 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } pl = planeNormXform(-1, -1, -1, -SQRT3_4 - 1e-5); if (pl) { expect(box.intersectPlane(pl)).toEqual(import__272.Intersect.OUTSIDE); } }; it("intersectPlane works with untransformed box", function() { intersectPlaneTestCornersEdgesFaces(import__272.Cartesian3.ZERO, import__272.Matrix3.IDENTITY); }); it("intersectPlane works with off-center box", function() { intersectPlaneTestCornersEdgesFaces( new import__272.Cartesian3(1, 0, 0), import__272.Matrix3.IDENTITY ); intersectPlaneTestCornersEdgesFaces( new import__272.Cartesian3(0.7, -1.8, 12), import__272.Matrix3.IDENTITY ); }); it("intersectPlane works with rotated box", function() { intersectPlaneTestCornersEdgesFaces( import__272.Cartesian3.ZERO, import__272.Matrix3.fromQuaternion( import__272.Quaternion.fromAxisAngle(new import__272.Cartesian3(0.5, 1.5, -1.2), 1.2), new import__272.Matrix3() ) ); }); it("intersectPlane works with scaled box", function() { const m = new import__272.Matrix3(); intersectPlaneTestCornersEdgesFaces( import__272.Cartesian3.ZERO, import__272.Matrix3.fromScale(new import__272.Cartesian3(1.5, 0.4, 20.6), m) ); intersectPlaneTestCornersEdgesFaces( import__272.Cartesian3.ZERO, import__272.Matrix3.fromScale(new import__272.Cartesian3(0, 0.4, 20.6), m) ); intersectPlaneTestCornersEdgesFaces( import__272.Cartesian3.ZERO, import__272.Matrix3.fromScale(new import__272.Cartesian3(1.5, 0, 20.6), m) ); intersectPlaneTestCornersEdgesFaces( import__272.Cartesian3.ZERO, import__272.Matrix3.fromScale(new import__272.Cartesian3(1.5, 0.4, 0), m) ); intersectPlaneTestCornersEdgesFaces( import__272.Cartesian3.ZERO, import__272.Matrix3.fromScale(new import__272.Cartesian3(0, 0, 0), m) ); }); it("intersectPlane works with this arbitrary box", function() { const m = import__272.Matrix3.fromScale(new import__272.Cartesian3(1.5, 80.4, 2.6), new import__272.Matrix3()); const n = import__272.Matrix3.fromQuaternion( import__272.Quaternion.fromAxisAngle(new import__272.Cartesian3(0.5, 1.5, -1.2), 1.2), new import__272.Matrix3() ); import__272.Matrix3.multiply(m, n, n); intersectPlaneTestCornersEdgesFaces(new import__272.Cartesian3(-5.1, 0, 0.1), n); }); it("intersectPlane fails without box parameter", function() { const plane = new import__272.Cartesian4(1, 0, 0, 0); expect(function() { import__272.OrientedBoundingBox.intersectPlane(void 0, plane); }).toThrowDeveloperError(); }); it("intersectPlane fails without plane parameter", function() { const box = new import__272.OrientedBoundingBox(import__272.Cartesian3.IDENTITY, import__272.Matrix3.ZERO); expect(function() { import__272.OrientedBoundingBox.intersectPlane(box, void 0); }).toThrowDeveloperError(); }); it("distanceSquaredTo", function() { const r0 = import__272.Matrix3.fromRotationZ(import__273.Math.toRadians(-45)); const r1 = import__272.Matrix3.fromRotationY(import__273.Math.toRadians(45)); const rotation = import__272.Matrix3.multiply(r1, r0, r0); const scale = new import__272.Cartesian3(2, 3, 4); const rotationScale = import__272.Matrix3.multiplyByScale( rotation, scale, new import__272.Matrix3() ); const center = new import__272.Cartesian3(4, 3, 2); const obb = new import__272.OrientedBoundingBox(center, rotationScale); const halfAxes = obb.halfAxes; const xAxis = import__272.Matrix3.getColumn(halfAxes, 0, new import__272.Cartesian3()); const yAxis = import__272.Matrix3.getColumn(halfAxes, 1, new import__272.Cartesian3()); const zAxis = import__272.Matrix3.getColumn(halfAxes, 2, new import__272.Cartesian3()); const cartesian = import__272.Cartesian3.multiplyByScalar(xAxis, 2, new import__272.Cartesian3()); import__272.Cartesian3.add(cartesian, center, cartesian); let d = import__272.Cartesian3.distance(cartesian, center) - scale.x; let expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(xAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.x; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(yAxis, 2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.y; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(yAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.y; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(zAxis, 2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.z; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(zAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.z; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.add(xAxis, yAxis, cartesian); import__272.Cartesian3.add(zAxis, cartesian, cartesian); const cornerDistance = import__272.Cartesian3.magnitude(cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - cornerDistance; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); const offset = import__272.Cartesian3.multiplyByScalar(scale, 0.25, new import__272.Cartesian3()); import__272.Matrix3.multiplyByVector(rotation, offset, offset); import__272.Cartesian3.add(center, offset, cartesian); expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( 0, import__273.Math.EPSILON10 ); }); it("distanceSquaredTo handles one degenerate axis - X", function() { const rotation = import__272.Matrix3.fromRotationX(import__273.Math.toRadians(45)); const scale = new import__272.Cartesian3(0, 4, 3); const rotationScale = import__272.Matrix3.multiplyByScale( rotation, scale, new import__272.Matrix3() ); const center = new import__272.Cartesian3(4, 3, 2); const obb = new import__272.OrientedBoundingBox(center, rotationScale); const halfAxes = obb.halfAxes; let xAxis = import__272.Matrix3.getColumn(halfAxes, 0, new import__272.Cartesian3()); const yAxis = import__272.Matrix3.getColumn(halfAxes, 1, new import__272.Cartesian3()); const zAxis = import__272.Matrix3.getColumn(halfAxes, 2, new import__272.Cartesian3()); expect(xAxis).toEqual(import__272.Cartesian3.ZERO); xAxis = new import__272.Cartesian3(1, 0, 0); const cartesian = import__272.Cartesian3.multiplyByScalar(xAxis, 2, new import__272.Cartesian3()); import__272.Cartesian3.add(cartesian, center, cartesian); let d = import__272.Cartesian3.distance(cartesian, center); let expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(xAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(yAxis, 2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.y; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(yAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.y; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(zAxis, 2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.z; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(zAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.z; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.add(yAxis, zAxis, cartesian); const cornerDistance = import__272.Cartesian3.magnitude(cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - cornerDistance; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); const offset = import__272.Cartesian3.multiplyByScalar(scale, 0.25, new import__272.Cartesian3()); import__272.Matrix3.multiplyByVector(rotation, offset, offset); import__272.Cartesian3.add(center, offset, cartesian); expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( 0, import__273.Math.EPSILON10 ); }); it("distanceSquaredTo handles one degenerate axis - Y", function() { const rotation = import__272.Matrix3.fromRotationY(import__273.Math.toRadians(45)); const scale = new import__272.Cartesian3(2, 0, 3); const rotationScale = import__272.Matrix3.multiplyByScale( rotation, scale, new import__272.Matrix3() ); const center = new import__272.Cartesian3(4, 3, 2); const obb = new import__272.OrientedBoundingBox(center, rotationScale); const halfAxes = obb.halfAxes; const xAxis = import__272.Matrix3.getColumn(halfAxes, 0, new import__272.Cartesian3()); let yAxis = import__272.Matrix3.getColumn(halfAxes, 1, new import__272.Cartesian3()); const zAxis = import__272.Matrix3.getColumn(halfAxes, 2, new import__272.Cartesian3()); expect(yAxis).toEqual(import__272.Cartesian3.ZERO); yAxis = new import__272.Cartesian3(0, 1, 0); const cartesian = import__272.Cartesian3.multiplyByScalar(xAxis, 2, new import__272.Cartesian3()); import__272.Cartesian3.add(cartesian, center, cartesian); let d = import__272.Cartesian3.distance(cartesian, center) - scale.x; let expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(xAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.x; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(yAxis, 2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(yAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(zAxis, 2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.z; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(zAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.z; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.add(xAxis, zAxis, cartesian); const cornerDistance = import__272.Cartesian3.magnitude(cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - cornerDistance; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); const offset = import__272.Cartesian3.multiplyByScalar(scale, 0.25, new import__272.Cartesian3()); import__272.Matrix3.multiplyByVector(rotation, offset, offset); import__272.Cartesian3.add(center, offset, cartesian); expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( 0, import__273.Math.EPSILON10 ); }); it("distanceSquaredTo handles one degenerate axis - Z", function() { const rotation = import__272.Matrix3.fromRotationZ(import__273.Math.toRadians(45)); const scale = new import__272.Cartesian3(2, 4, 0); const rotationScale = import__272.Matrix3.multiplyByScale(rotation, scale, rotation); const center = new import__272.Cartesian3(4, 3, 2); const obb = new import__272.OrientedBoundingBox(center, rotationScale); const halfAxes = obb.halfAxes; const xAxis = import__272.Matrix3.getColumn(halfAxes, 0, new import__272.Cartesian3()); const yAxis = import__272.Matrix3.getColumn(halfAxes, 1, new import__272.Cartesian3()); let zAxis = import__272.Matrix3.getColumn(halfAxes, 2, new import__272.Cartesian3()); expect(zAxis).toEqual(import__272.Cartesian3.ZERO); zAxis = new import__272.Cartesian3(0, 0, 1); const cartesian = import__272.Cartesian3.multiplyByScalar(xAxis, 2, new import__272.Cartesian3()); import__272.Cartesian3.add(cartesian, center, cartesian); let d = import__272.Cartesian3.distance(cartesian, center) - scale.x; let expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(xAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.x; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(yAxis, 2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.y; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(yAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.y; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(zAxis, 2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(zAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.add(xAxis, yAxis, cartesian); const cornerDistance = import__272.Cartesian3.magnitude(cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - cornerDistance; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); const offset = import__272.Cartesian3.multiplyByScalar(scale, 0.25, new import__272.Cartesian3()); import__272.Cartesian3.add(center, offset, cartesian); expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( 0, import__273.Math.EPSILON10 ); }); it("distanceSquaredTo handles two degenerate axes - XY", function() { const r0 = import__272.Matrix3.fromRotationY(import__273.Math.toRadians(45)); const r1 = import__272.Matrix3.fromRotationX(import__273.Math.toRadians(-45)); const rotation = import__272.Matrix3.multiply(r1, r0, r0); const scale = new import__272.Cartesian3(0, 0, 3); const rotationScale = import__272.Matrix3.multiplyByScale( rotation, scale, new import__272.Matrix3() ); const center = new import__272.Cartesian3(4, 3, 2); const obb = new import__272.OrientedBoundingBox(center, rotationScale); const halfAxes = obb.halfAxes; let xAxis = import__272.Matrix3.getColumn(halfAxes, 0, new import__272.Cartesian3()); let yAxis = import__272.Matrix3.getColumn(halfAxes, 1, new import__272.Cartesian3()); const zAxis = import__272.Matrix3.getColumn(halfAxes, 2, new import__272.Cartesian3()); expect(xAxis).toEqual(import__272.Cartesian3.ZERO); expect(yAxis).toEqual(import__272.Cartesian3.ZERO); xAxis = new import__272.Cartesian3(1, 0, 0); yAxis = new import__272.Cartesian3(0, 1, 0); import__272.Matrix3.multiplyByVector(rotation, xAxis, xAxis); import__272.Matrix3.multiplyByVector(rotation, yAxis, yAxis); const cartesian = import__272.Cartesian3.multiplyByScalar(xAxis, 2, new import__272.Cartesian3()); import__272.Cartesian3.add(cartesian, center, cartesian); let d = import__272.Cartesian3.distance(cartesian, center); let expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(xAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(yAxis, 2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(yAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(zAxis, 2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.z; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(zAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.z; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.clone(zAxis, cartesian); let endpointDistance = import__272.Cartesian3.magnitude(cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - endpointDistance; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.clone(zAxis, cartesian); import__272.Cartesian3.multiplyByScalar(cartesian, -1, cartesian); endpointDistance = import__272.Cartesian3.magnitude(cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - endpointDistance; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); const offset = import__272.Cartesian3.multiplyByScalar(scale, 0.25, new import__272.Cartesian3()); import__272.Matrix3.multiplyByVector(rotation, offset, offset); import__272.Cartesian3.add(center, offset, cartesian); expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( 0, import__273.Math.EPSILON10 ); }); it("distanceSquaredTo handles two degenerate axes - XZ", function() { const r0 = import__272.Matrix3.fromRotationZ(import__273.Math.toRadians(45)); const r1 = import__272.Matrix3.fromRotationX(import__273.Math.toRadians(-45)); const rotation = import__272.Matrix3.multiply(r1, r0, r0); const scale = new import__272.Cartesian3(0, 4, 0); const rotationScale = import__272.Matrix3.multiplyByScale( rotation, scale, new import__272.Matrix3() ); const center = new import__272.Cartesian3(4, 3, 2); const obb = new import__272.OrientedBoundingBox(center, rotationScale); const halfAxes = obb.halfAxes; let xAxis = import__272.Matrix3.getColumn(halfAxes, 0, new import__272.Cartesian3()); const yAxis = import__272.Matrix3.getColumn(halfAxes, 1, new import__272.Cartesian3()); let zAxis = import__272.Matrix3.getColumn(halfAxes, 2, new import__272.Cartesian3()); expect(xAxis).toEqual(import__272.Cartesian3.ZERO); expect(zAxis).toEqual(import__272.Cartesian3.ZERO); xAxis = new import__272.Cartesian3(1, 0, 0); zAxis = new import__272.Cartesian3(0, 0, 1); import__272.Matrix3.multiplyByVector(rotation, xAxis, xAxis); import__272.Matrix3.multiplyByVector(rotation, zAxis, zAxis); const cartesian = import__272.Cartesian3.multiplyByScalar(xAxis, 2, new import__272.Cartesian3()); import__272.Cartesian3.add(cartesian, center, cartesian); let d = import__272.Cartesian3.distance(cartesian, center); let expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(xAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(yAxis, 2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.y; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(yAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.y; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(zAxis, 2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(zAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.clone(yAxis, cartesian); let endpointDistance = import__272.Cartesian3.magnitude(cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - endpointDistance; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.clone(yAxis, cartesian); import__272.Cartesian3.multiplyByScalar(cartesian, -1, cartesian); endpointDistance = import__272.Cartesian3.magnitude(cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - endpointDistance; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); const offset = import__272.Cartesian3.multiplyByScalar(scale, 0.25, new import__272.Cartesian3()); import__272.Matrix3.multiplyByVector(rotation, offset, offset); import__272.Cartesian3.add(center, offset, cartesian); expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( 0, import__273.Math.EPSILON10 ); }); it("distanceSquaredTo handles two degenerate axes - YZ", function() { const r0 = import__272.Matrix3.fromRotationZ(import__273.Math.toRadians(45)); const r1 = import__272.Matrix3.fromRotationY(import__273.Math.toRadians(-45)); const rotation = import__272.Matrix3.multiply(r1, r0, r0); const scale = new import__272.Cartesian3(2, 0, 0); const rotationScale = import__272.Matrix3.multiplyByScale( rotation, scale, new import__272.Matrix3() ); const center = new import__272.Cartesian3(4, 3, 2); const obb = new import__272.OrientedBoundingBox(center, rotationScale); const halfAxes = obb.halfAxes; const xAxis = import__272.Matrix3.getColumn(halfAxes, 0, new import__272.Cartesian3()); let yAxis = import__272.Matrix3.getColumn(halfAxes, 1, new import__272.Cartesian3()); let zAxis = import__272.Matrix3.getColumn(halfAxes, 2, new import__272.Cartesian3()); expect(yAxis).toEqual(import__272.Cartesian3.ZERO); expect(zAxis).toEqual(import__272.Cartesian3.ZERO); yAxis = new import__272.Cartesian3(0, 1, 0); zAxis = new import__272.Cartesian3(0, 0, 1); import__272.Matrix3.multiplyByVector(rotation, yAxis, yAxis); import__272.Matrix3.multiplyByVector(rotation, zAxis, zAxis); const cartesian = import__272.Cartesian3.multiplyByScalar(xAxis, 2, new import__272.Cartesian3()); import__272.Cartesian3.add(cartesian, center, cartesian); let d = import__272.Cartesian3.distance(cartesian, center) - scale.x; let expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(xAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - scale.x; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(yAxis, 2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(yAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(zAxis, 2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(zAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.clone(xAxis, cartesian); let endpointDistance = import__272.Cartesian3.magnitude(cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - endpointDistance; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.clone(xAxis, cartesian); import__272.Cartesian3.multiplyByScalar(cartesian, -1, cartesian); endpointDistance = import__272.Cartesian3.magnitude(cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center) - endpointDistance; expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); const offset = import__272.Cartesian3.multiplyByScalar(scale, 0.25, new import__272.Cartesian3()); import__272.Matrix3.multiplyByVector(rotation, offset, offset); import__272.Cartesian3.add(center, offset, cartesian); expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( 0, import__273.Math.EPSILON10 ); }); it("distanceSquaredTo handles three degenerate axes", function() { const scale = new import__272.Cartesian3(0, 0, 0); const center = new import__272.Cartesian3(4, 3, 2); const obb = new import__272.OrientedBoundingBox(center, scale); const halfAxes = obb.halfAxes; let xAxis = import__272.Matrix3.getColumn(halfAxes, 0, new import__272.Cartesian3()); let yAxis = import__272.Matrix3.getColumn(halfAxes, 1, new import__272.Cartesian3()); let zAxis = import__272.Matrix3.getColumn(halfAxes, 2, new import__272.Cartesian3()); expect(xAxis).toEqual(import__272.Cartesian3.ZERO); expect(yAxis).toEqual(import__272.Cartesian3.ZERO); expect(zAxis).toEqual(import__272.Cartesian3.ZERO); xAxis = new import__272.Cartesian3(1, 0, 0); yAxis = new import__272.Cartesian3(0, 1, 0); zAxis = new import__272.Cartesian3(0, 0, 1); let cartesian = import__272.Cartesian3.multiplyByScalar(xAxis, 2, new import__272.Cartesian3()); import__272.Cartesian3.add(cartesian, center, cartesian); let d = import__272.Cartesian3.distance(cartesian, center); let expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(xAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(yAxis, 2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(yAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(zAxis, 2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); import__272.Cartesian3.multiplyByScalar(zAxis, -2, cartesian); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); cartesian = new import__272.Cartesian3(5, 10, 15); import__272.Cartesian3.add(cartesian, center, cartesian); d = import__272.Cartesian3.distance(cartesian, center); expected = d * d; expect(obb.distanceSquaredTo(cartesian)).toEqualEpsilon( expected, import__273.Math.EPSILON10 ); cartesian = center; expect(obb.distanceSquaredTo(center)).toEqualEpsilon( 0, import__273.Math.EPSILON10 ); }); it("distanceSquaredTo throws without box", function() { expect(function() { import__272.OrientedBoundingBox.distanceSquaredTo(void 0, new import__272.Cartesian3()); }).toThrowDeveloperError(); }); it("distanceSquaredTo throws without cartesian", function() { expect(function() { import__272.OrientedBoundingBox.distanceSquaredTo( new import__272.OrientedBoundingBox(), void 0 ); }).toThrowDeveloperError(); }); it("computePlaneDistances", function() { const r0 = import__272.Matrix3.fromRotationZ(import__273.Math.toRadians(-45)); const r1 = import__272.Matrix3.fromRotationY(import__273.Math.toRadians(45)); const rotation = import__272.Matrix3.multiply(r1, r0, r0); const scale = new import__272.Cartesian3(2, 3, 4); const rotationScale = import__272.Matrix3.multiplyByScale(rotation, scale, rotation); const center = new import__272.Cartesian3(4, 3, 2); const obb = new import__272.OrientedBoundingBox(center, rotationScale); const halfAxes = obb.halfAxes; const xAxis = import__272.Matrix3.getColumn(halfAxes, 0, new import__272.Cartesian3()); const yAxis = import__272.Matrix3.getColumn(halfAxes, 1, new import__272.Cartesian3()); const zAxis = import__272.Matrix3.getColumn(halfAxes, 2, new import__272.Cartesian3()); const position = import__272.Cartesian3.multiplyByScalar(xAxis, 2, new import__272.Cartesian3()); import__272.Cartesian3.add(position, center, position); const direction = import__272.Cartesian3.negate(xAxis, new import__272.Cartesian3()); import__272.Cartesian3.normalize(direction, direction); let d = import__272.Cartesian3.distance(position, center); let expectedNear = d - scale.x; let expectedFar = d + scale.x; const distances = obb.computePlaneDistances(position, direction); expect(distances.start).toEqualEpsilon(expectedNear, import__273.Math.EPSILON14); expect(distances.stop).toEqualEpsilon(expectedFar, import__273.Math.EPSILON14); import__272.Cartesian3.multiplyByScalar(yAxis, 2, position); import__272.Cartesian3.add(position, center, position); import__272.Cartesian3.negate(yAxis, direction); import__272.Cartesian3.normalize(direction, direction); d = import__272.Cartesian3.distance(position, center); expectedNear = d - scale.y; expectedFar = d + scale.y; obb.computePlaneDistances(position, direction, distances); expect(distances.start).toEqualEpsilon(expectedNear, import__273.Math.EPSILON14); expect(distances.stop).toEqualEpsilon(expectedFar, import__273.Math.EPSILON14); import__272.Cartesian3.multiplyByScalar(zAxis, 2, position); import__272.Cartesian3.add(position, center, position); import__272.Cartesian3.negate(zAxis, direction); import__272.Cartesian3.normalize(direction, direction); d = import__272.Cartesian3.distance(position, center); expectedNear = d - scale.z; expectedFar = d + scale.z; obb.computePlaneDistances(position, direction, distances); expect(distances.start).toEqualEpsilon(expectedNear, import__273.Math.EPSILON14); expect(distances.stop).toEqualEpsilon(expectedFar, import__273.Math.EPSILON14); import__272.Cartesian3.add(xAxis, yAxis, position); import__272.Cartesian3.add(zAxis, position, position); import__272.Cartesian3.negate(position, direction); import__272.Cartesian3.normalize(direction, direction); const cornerDistance = import__272.Cartesian3.magnitude(position); import__272.Cartesian3.add(position, center, position); d = import__272.Cartesian3.distance(position, center); expectedNear = d - cornerDistance; expectedFar = d + cornerDistance; obb.computePlaneDistances(position, direction, distances); expect(distances.start).toEqualEpsilon(expectedNear, import__273.Math.EPSILON14); expect(distances.stop).toEqualEpsilon(expectedFar, import__273.Math.EPSILON14); }); it("computePlaneDistances throws without a box", function() { expect(function() { import__272.OrientedBoundingBox.computePlaneDistances( void 0, new import__272.Cartesian3(), new import__272.Cartesian3() ); }).toThrowDeveloperError(); }); it("computePlaneDistances throws without a position", function() { expect(function() { import__272.OrientedBoundingBox.computePlaneDistances( new import__272.OrientedBoundingBox(), void 0, new import__272.Cartesian3() ); }).toThrowDeveloperError(); }); it("computePlaneDistances throws without a direction", function() { expect(function() { import__272.OrientedBoundingBox.computePlaneDistances( new import__272.OrientedBoundingBox(), new import__272.Cartesian3(), void 0 ); }).toThrowDeveloperError(); }); it("computeCorners works with a result parameter", function() { const center = new import__272.Cartesian3(1, 2, 3); const halfScale = new import__272.Cartesian3(1, 2, 3); const halfAxes = import__272.Matrix3.fromScale(halfScale); const box = new import__272.OrientedBoundingBox(center, halfAxes); const corners = new Array( new import__272.Cartesian3(), new import__272.Cartesian3(), new import__272.Cartesian3(), new import__272.Cartesian3(), new import__272.Cartesian3(), new import__272.Cartesian3(), new import__272.Cartesian3(), new import__272.Cartesian3() ); const result = box.computeCorners(corners); expect(result[0]).toEqual(new import__272.Cartesian3(0, 0, 0)); expect(result[1]).toEqual(new import__272.Cartesian3(0, 0, 6)); expect(result[2]).toEqual(new import__272.Cartesian3(0, 4, 0)); expect(result[3]).toEqual(new import__272.Cartesian3(0, 4, 6)); expect(result[4]).toEqual(new import__272.Cartesian3(2, 0, 0)); expect(result[5]).toEqual(new import__272.Cartesian3(2, 0, 6)); expect(result[6]).toEqual(new import__272.Cartesian3(2, 4, 0)); expect(result[7]).toEqual(new import__272.Cartesian3(2, 4, 6)); expect(result).toBe(corners); }); it("computeCorners works without a result parameter", function() { const center = new import__272.Cartesian3(1, 2, 3); const halfScale = new import__272.Cartesian3(1, 2, 3); const halfAxes = import__272.Matrix3.fromScale(halfScale); const box = new import__272.OrientedBoundingBox(center, halfAxes); const corners = box.computeCorners(); expect(corners[0]).toEqual(new import__272.Cartesian3(0, 0, 0)); expect(corners[1]).toEqual(new import__272.Cartesian3(0, 0, 6)); expect(corners[2]).toEqual(new import__272.Cartesian3(0, 4, 0)); expect(corners[3]).toEqual(new import__272.Cartesian3(0, 4, 6)); expect(corners[4]).toEqual(new import__272.Cartesian3(2, 0, 0)); expect(corners[5]).toEqual(new import__272.Cartesian3(2, 0, 6)); expect(corners[6]).toEqual(new import__272.Cartesian3(2, 4, 0)); expect(corners[7]).toEqual(new import__272.Cartesian3(2, 4, 6)); }); it("computeCorners works with a box that has zero scale", function() { const center = new import__272.Cartesian3(0, 0, 0); const halfScale = new import__272.Cartesian3(0, 0, 0); const halfAxes = import__272.Matrix3.fromScale(halfScale); const box = new import__272.OrientedBoundingBox(center, halfAxes); const corners = box.computeCorners(); expect(corners[0]).toEqual(import__272.Cartesian3.ZERO); expect(corners[1]).toEqual(import__272.Cartesian3.ZERO); expect(corners[2]).toEqual(import__272.Cartesian3.ZERO); expect(corners[3]).toEqual(import__272.Cartesian3.ZERO); expect(corners[4]).toEqual(import__272.Cartesian3.ZERO); expect(corners[5]).toEqual(import__272.Cartesian3.ZERO); expect(corners[6]).toEqual(import__272.Cartesian3.ZERO); expect(corners[7]).toEqual(import__272.Cartesian3.ZERO); }); it("computeCorners throws with no box parameter", function() { expect(function() { import__272.OrientedBoundingBox.computeCorners(); }).toThrowDeveloperError(); }); it("computeTransformation works with a result parameter", function() { const center = new import__272.Cartesian3(1, 2, 3); const halfScale = new import__272.Cartesian3(1, 2, 3); const expectedScale = new import__272.Cartesian3(2, 4, 6); const halfAxes = import__272.Matrix3.fromScale(halfScale); const box = new import__272.OrientedBoundingBox(center, halfAxes); const transformation = new import__272.Matrix4(); const result = box.computeTransformation(transformation); const extractedTranslation = import__272.Matrix4.getTranslation( result, new import__272.Cartesian3() ); const extractedScale = import__272.Matrix4.getScale(result, new import__272.Cartesian3()); expect(extractedTranslation).toEqual(center); expect(extractedScale).toEqual(expectedScale); expect(result).toBe(transformation); }); it("computeTransformation works without a result parameter", function() { const center = new import__272.Cartesian3(1, 2, 3); const halfScale = new import__272.Cartesian3(1, 2, 3); const expectedScale = new import__272.Cartesian3(2, 4, 6); const halfAxes = import__272.Matrix3.fromScale(halfScale); const box = new import__272.OrientedBoundingBox(center, halfAxes); const transformation = box.computeTransformation(); const extractedTranslation = import__272.Matrix4.getTranslation( transformation, new import__272.Cartesian3() ); const extractedScale = import__272.Matrix4.getScale(transformation, new import__272.Cartesian3()); expect(extractedTranslation).toEqual(center); expect(extractedScale).toEqual(expectedScale); }); it("computeTransformation works with box that has zero scale", function() { const center = new import__272.Cartesian3(0, 0, 0); const halfScale = new import__272.Cartesian3(0, 0, 0); const halfAxes = import__272.Matrix3.fromScale(halfScale); const box = new import__272.OrientedBoundingBox(center, halfAxes); const expectedTransformation = import__272.Matrix4.fromScale(import__272.Cartesian3.ZERO); const transformation = box.computeTransformation(); expect(transformation).toEqual(expectedTransformation); }); it("computeTransformation throws with no box parameter", function() { expect(function() { import__272.OrientedBoundingBox.computeTransformation(); }).toThrowDeveloperError(); }); it("isOccluded", function() { let occluderSphere = new import__272.BoundingSphere(new import__272.Cartesian3(0, 0, -1.5), 0.5); let occluder = new import__272.Occluder(occluderSphere, import__272.Cartesian3.ZERO); let radius = 0.25 / Math.sqrt(2); let halfAxes = import__272.Matrix3.multiplyByScale( import__272.Matrix3.IDENTITY, new import__272.Cartesian3(radius, radius, radius), new import__272.Matrix3() ); let obb = new import__272.OrientedBoundingBox(new import__272.Cartesian3(0, 0, -2.75), halfAxes); expect(obb.isOccluded(occluder)).toEqual(true); occluderSphere = new import__272.BoundingSphere(new import__272.Cartesian3(0, 0, -2.75), 0.25); occluder = new import__272.Occluder(occluderSphere, import__272.Cartesian3.ZERO); radius = 0.5 / Math.sqrt(2); halfAxes = import__272.Matrix3.multiplyByScale( import__272.Matrix3.IDENTITY, new import__272.Cartesian3(radius, radius, radius), new import__272.Matrix3() ); obb = new import__272.OrientedBoundingBox(new import__272.Cartesian3(0, 0, -1.5), halfAxes); expect(obb.isOccluded(occluder)).toEqual(false); }); it("isOccluded throws without a box", function() { expect(function() { import__272.OrientedBoundingBox.isOccluded( void 0, new import__272.Occluder(new import__272.BoundingSphere(), new import__272.Cartesian3()) ); }).toThrowDeveloperError(); }); it("isOccluded throws without a occluder", function() { expect(function() { import__272.OrientedBoundingBox.isOccluded(new import__272.OrientedBoundingBox(), void 0); }).toThrowDeveloperError(); }); it("clone without a result parameter", function() { const box = new import__272.OrientedBoundingBox(); const result = import__272.OrientedBoundingBox.clone(box); expect(box).not.toBe(result); expect(box).toEqual(result); expect(box.clone()).toEqual(box); }); it("clone with a result parameter", function() { const box = new import__272.OrientedBoundingBox(); const box2 = new import__272.OrientedBoundingBox(); const result = new import__272.OrientedBoundingBox(); const returnedResult = import__272.OrientedBoundingBox.clone(box, result); expect(result).toBe(returnedResult); expect(box).not.toBe(result); expect(box).toEqual(result); expect(box.clone(box2)).toBe(box2); expect(box.clone(box2)).toEqual(box2); }); it("clone undefined OBB with a result parameter", function() { const box = new import__272.OrientedBoundingBox(); expect(import__272.OrientedBoundingBox.clone(void 0, box)).toBe(void 0); }); it("clone undefined OBB without a result parameter", function() { expect(import__272.OrientedBoundingBox.clone(void 0)).toBe(void 0); }); it("equals works in all cases", function() { const box = new import__272.OrientedBoundingBox(); expect(box.equals(new import__272.OrientedBoundingBox())).toEqual(true); expect(box.equals(void 0)).toEqual(false); }); it("is a rotated/scaled 2x2x2 cube centered at the origin", function() { const box = new import__272.OrientedBoundingBox(import__272.Cartesian3.ZERO, import__272.Matrix3.IDENTITY); const corners = box.computeCorners(); for (const corner of corners) { expect(Math.abs(corner.x)).toEqual(1); expect(Math.abs(corner.y)).toEqual(1); expect(Math.abs(corner.z)).toEqual(1); } }); createPackableSpecs_default( import__272.OrientedBoundingBox, new import__272.OrientedBoundingBox(new import__272.Cartesian3(1, 2, 3), import__272.Matrix3.IDENTITY), [1, 2, 3, 1, 0, 0, 0, 1, 0, 0, 0, 1] ); }); // packages/engine/Specs/Core/OrthographicFrustumSpec.js var import__274 = __toESM(require_Cesium(), 1); var import__275 = __toESM(require_Cesium(), 1); describe("Core/OrthographicFrustum", function() { let frustum, planes; beforeEach(function() { frustum = new import__274.OrthographicFrustum(); frustum.near = 1; frustum.far = 3; frustum.width = 2; frustum.aspectRatio = 1; planes = frustum.computeCullingVolume( new import__274.Cartesian3(), import__274.Cartesian3.negate(import__274.Cartesian3.UNIT_Z, new import__274.Cartesian3()), import__274.Cartesian3.UNIT_Y ).planes; }); it("constructs", function() { const options = { width: 1, aspectRatio: 2, near: 3, far: 4, xOffset: 5, yOffset: 6 }; const f = new import__274.OrthographicFrustum(options); expect(f.width).toEqual(options.width); expect(f.aspectRatio).toEqual(options.aspectRatio); expect(f.near).toEqual(options.near); expect(f.far).toEqual(options.far); }); it("default constructs", function() { const f = new import__274.OrthographicFrustum(); expect(f.width).toBeUndefined(); expect(f.aspectRatio).toBeUndefined(); expect(f.near).toEqual(1); expect(f.far).toEqual(5e8); }); it("undefined width causes an exception", function() { frustum.width = void 0; expect(function() { return frustum.projectionMatrix; }).toThrowDeveloperError(); }); it("undefined aspectRatio throws an exception", function() { frustum.aspectRatio = void 0; expect(function() { return frustum.projectionMatrix; }).toThrowDeveloperError(); }); it("out of range near plane throws an exception", function() { frustum.near = -1; expect(function() { return frustum.projectionMatrix; }).toThrowDeveloperError(); frustum.far = 3; expect(function() { return frustum.projectionMatrix; }).toThrowDeveloperError(); }); it("negative far plane throws an exception", function() { frustum.far = -1; expect(function() { return frustum.projectionMatrix; }).toThrowDeveloperError(); }); it("computeCullingVolume with no position throws an exception", function() { expect(function() { return frustum.computeCullingVolume(); }).toThrowDeveloperError(); }); it("computeCullingVolume with no direction throws an exception", function() { expect(function() { return frustum.computeCullingVolume(new import__274.Cartesian3()); }).toThrowDeveloperError(); }); it("computeCullingVolume with no up throws an exception", function() { expect(function() { return frustum.computeCullingVolume(new import__274.Cartesian3(), new import__274.Cartesian3()); }).toThrowDeveloperError(); }); it("get frustum left plane", function() { const leftPlane = planes[0]; const expectedResult = new import__274.Cartesian4(1, 0, 0, 1); expect(leftPlane).toEqualEpsilon(expectedResult, import__275.Math.EPSILON4); }); it("get frustum right plane", function() { const rightPlane = planes[1]; const expectedResult = new import__274.Cartesian4(-1, 0, 0, 1); expect(rightPlane).toEqualEpsilon(expectedResult, import__275.Math.EPSILON4); }); it("get frustum bottom plane", function() { const bottomPlane = planes[2]; const expectedResult = new import__274.Cartesian4(0, 1, 0, 1); expect(bottomPlane).toEqualEpsilon(expectedResult, import__275.Math.EPSILON4); }); it("get frustum top plane", function() { const topPlane = planes[3]; const expectedResult = new import__274.Cartesian4(0, -1, 0, 1); expect(topPlane).toEqual(expectedResult, import__275.Math.EPSILON4); }); it("get frustum near plane", function() { const nearPlane = planes[4]; const expectedResult = new import__274.Cartesian4(0, 0, -1, -1); expect(nearPlane).toEqualEpsilon(expectedResult, import__275.Math.EPSILON4); }); it("get frustum far plane", function() { const farPlane = planes[5]; const expectedResult = new import__274.Cartesian4(0, 0, 1, 3); expect(farPlane).toEqualEpsilon(expectedResult, import__275.Math.EPSILON4); }); it("get orthographic projection matrix", function() { frustum = frustum.offCenterFrustum; const expected = import__274.Matrix4.computeOrthographicOffCenter( frustum.left, frustum.right, frustum.bottom, frustum.top, frustum.near, frustum.far, new import__274.Matrix4() ); const projectionMatrix = frustum.projectionMatrix; expect(projectionMatrix).toEqualEpsilon(expected, import__275.Math.EPSILON6); }); it("get pixel dimensions throws without canvas height", function() { expect(function() { return frustum.getPixelDimensions( 1, void 0, 0, 1, new import__274.Cartesian2() ); }).toThrowDeveloperError(); }); it("get pixel dimensions throws without canvas width", function() { expect(function() { return frustum.getPixelDimensions( void 0, 1, 0, 1, new import__274.Cartesian2() ); }).toThrowDeveloperError(); }); it("get pixel dimensions throws with canvas width less than or equal to zero", function() { expect(function() { return frustum.getPixelDimensions(0, 1, 0, 1, new import__274.Cartesian2()); }).toThrowDeveloperError(); }); it("get pixel dimensions throws with canvas height less than or equal to zero", function() { expect(function() { return frustum.getPixelDimensions(1, 0, 0, 1, new import__274.Cartesian2()); }).toThrowDeveloperError(); }); it("get pixel dimensions throws without pixel ratio", function() { expect(function() { return frustum.getPixelDimensions( 1, 1, 0, void 0, new import__274.Cartesian2() ); }).toThrowDeveloperError(); }); it("get pixel dimensions throws with pixel ratio less than or equal to zero", function() { expect(function() { return frustum.getPixelDimensions(1, 1, 0, 0, new import__274.Cartesian2()); }).toThrowDeveloperError(); }); it("get pixel dimensions", function() { const dimensions = new import__274.Cartesian2(1, 1); const pixelRatio = 1; const distance = 1; const pixelSize = frustum.getPixelDimensions( dimensions.x, dimensions.y, distance, pixelRatio, new import__274.Cartesian2() ); const expected = frustum.offCenterFrustum.getPixelDimensions( dimensions.x, dimensions.y, distance, pixelRatio, new import__274.Cartesian2() ); expect(pixelSize.x).toEqual(expected.x); expect(pixelSize.y).toEqual(expected.y); }); it("get pixel dimensions with pixel ratio", function() { const dimensions = new import__274.Cartesian2(1, 1); const pixelRatio = 2; const distance = 1; const pixelSize = frustum.getPixelDimensions( dimensions.x, dimensions.y, distance, pixelRatio, new import__274.Cartesian2() ); const expected = frustum.offCenterFrustum.getPixelDimensions( dimensions.x, dimensions.y, distance, pixelRatio, new import__274.Cartesian2() ); expect(pixelSize.x).toEqual(expected.x); expect(pixelSize.y).toEqual(expected.y); }); it("equals", function() { const frustum2 = new import__274.OrthographicFrustum(); frustum2.near = 1; frustum2.far = 3; frustum2.width = 2; frustum2.aspectRatio = 1; expect(frustum.equals(frustum2)).toEqual(true); }); it("equals epsilon", function() { const frustum2 = new import__274.OrthographicFrustum(); frustum2.near = 1; frustum2.far = 3; frustum2.width = 2; frustum2.aspectRatio = 1; expect(frustum.equalsEpsilon(frustum2, import__275.Math.EPSILON7)).toEqual(true); const frustum3 = new import__274.OrthographicFrustum(); frustum3.near = 1.01; frustum3.far = 3.01; frustum3.width = 2.01; frustum3.aspectRatio = 1.01; expect(frustum.equalsEpsilon(frustum3, import__275.Math.EPSILON1)).toEqual(true); const frustum4 = new import__274.OrthographicFrustum(); frustum4.near = 1; frustum4.far = 3; frustum4.width = 2; frustum4.aspectRatio = 1.1; expect(frustum.equalsEpsilon(frustum4, import__275.Math.EPSILON2)).toEqual(false); }); it("equals undefined", function() { expect(frustum.equals()).toEqual(false); }); it("throws with undefined frustum parameters", function() { const frustum2 = new import__274.OrthographicFrustum(); expect(function() { return frustum2.projectionMatrix; }).toThrowDeveloperError(); }); it("clone", function() { const frustum2 = frustum.clone(); expect(frustum).toEqual(frustum2); }); it("clone with result parameter", function() { const result = new import__274.OrthographicFrustum(); const frustum2 = frustum.clone(result); expect(frustum2).toBe(result); expect(frustum).toEqual(frustum2); }); createPackableSpecs_default( import__274.OrthographicFrustum, new import__274.OrthographicFrustum({ width: 1, aspectRatio: 2, near: 3, far: 4 }), [1, 2, 3, 4] ); }); // packages/engine/Specs/Core/OrthographicOffCenterFrustumSpec.js var import__276 = __toESM(require_Cesium(), 1); var import__277 = __toESM(require_Cesium(), 1); describe("Core/OrthographicOffCenterFrustum", function() { let frustum, planes; beforeEach(function() { frustum = new import__276.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 3; frustum.right = 1; frustum.left = -1; frustum.top = 1; frustum.bottom = -1; planes = frustum.computeCullingVolume( new import__276.Cartesian3(), import__276.Cartesian3.negate(import__276.Cartesian3.UNIT_Z, new import__276.Cartesian3()), import__276.Cartesian3.UNIT_Y ).planes; }); it("constructs", function() { const options = { left: -1, right: 2, top: 5, bottom: -1, near: 3, far: 4 }; const f = new import__276.OrthographicOffCenterFrustum(options); expect(f.width).toEqual(options.width); expect(f.aspectRatio).toEqual(options.aspectRatio); expect(f.near).toEqual(options.near); expect(f.far).toEqual(options.far); }); it("default constructs", function() { const f = new import__276.OrthographicOffCenterFrustum(); expect(f.left).toBeUndefined(); expect(f.right).toBeUndefined(); expect(f.top).toBeUndefined(); expect(f.bottom).toBeUndefined(); expect(f.near).toEqual(1); expect(f.far).toEqual(5e8); }); it("left greater than right causes an exception", function() { frustum.left = frustum.right + 1; expect(function() { return frustum.projectionMatrix; }).toThrowDeveloperError(); }); it("bottom greater than top throws an exception", function() { frustum.bottom = frustum.top + 1; expect(function() { return frustum.projectionMatrix; }).toThrowDeveloperError(); }); it("out of range near plane throws an exception", function() { frustum.near = -1; expect(function() { return frustum.projectionMatrix; }).toThrowDeveloperError(); frustum.far = 3; expect(function() { return frustum.projectionMatrix; }).toThrowDeveloperError(); }); it("negative far plane throws an exception", function() { frustum.far = -1; expect(function() { return frustum.projectionMatrix; }).toThrowDeveloperError(); }); it("computeCullingVolume with no position throws an exception", function() { expect(function() { return frustum.computeCullingVolume(); }).toThrowDeveloperError(); }); it("computeCullingVolume with no direction throws an exception", function() { expect(function() { return frustum.computeCullingVolume(new import__276.Cartesian3()); }).toThrowDeveloperError(); }); it("computeCullingVolume with no up throws an exception", function() { expect(function() { return frustum.computeCullingVolume(new import__276.Cartesian3(), new import__276.Cartesian3()); }).toThrowDeveloperError(); }); it("get frustum left plane", function() { const leftPlane = planes[0]; const expectedResult = new import__276.Cartesian4(1, 0, 0, 1); expect(leftPlane).toEqualEpsilon(expectedResult, import__277.Math.EPSILON4); }); it("get frustum right plane", function() { const rightPlane = planes[1]; const expectedResult = new import__276.Cartesian4(-1, 0, 0, 1); expect(rightPlane).toEqualEpsilon(expectedResult, import__277.Math.EPSILON4); }); it("get frustum bottom plane", function() { const bottomPlane = planes[2]; const expectedResult = new import__276.Cartesian4(0, 1, 0, 1); expect(bottomPlane).toEqualEpsilon(expectedResult, import__277.Math.EPSILON4); }); it("get frustum top plane", function() { const topPlane = planes[3]; const expectedResult = new import__276.Cartesian4(0, -1, 0, 1); expect(topPlane).toEqual(expectedResult, import__277.Math.EPSILON4); }); it("get frustum near plane", function() { const nearPlane = planes[4]; const expectedResult = new import__276.Cartesian4(0, 0, -1, -1); expect(nearPlane).toEqualEpsilon(expectedResult, import__277.Math.EPSILON4); }); it("get frustum far plane", function() { const farPlane = planes[5]; const expectedResult = new import__276.Cartesian4(0, 0, 1, 3); expect(farPlane).toEqualEpsilon(expectedResult, import__277.Math.EPSILON4); }); it("get orthographic projection matrix", function() { const projectionMatrix = frustum.projectionMatrix; const expected = import__276.Matrix4.computeOrthographicOffCenter( frustum.left, frustum.right, frustum.bottom, frustum.top, frustum.near, frustum.far, new import__276.Matrix4() ); expect(projectionMatrix).toEqualEpsilon(expected, import__277.Math.EPSILON6); }); it("get pixel dimensions throws without canvas height", function() { expect(function() { return frustum.getPixelDimensions( 1, void 0, 0, 1, new import__276.Cartesian2() ); }).toThrowDeveloperError(); }); it("get pixel dimensions throws without canvas width", function() { expect(function() { return frustum.getPixelDimensions( void 0, 1, 0, 1, new import__276.Cartesian2() ); }).toThrowDeveloperError(); }); it("get pixel dimensions throws with canvas width less than or equal to zero", function() { expect(function() { return frustum.getPixelDimensions(0, 1, 0, 1, new import__276.Cartesian2()); }).toThrowDeveloperError(); }); it("get pixel dimensions throws with canvas height less than or equal to zero", function() { expect(function() { return frustum.getPixelDimensions(1, 0, 0, 1, new import__276.Cartesian2()); }).toThrowDeveloperError(); }); it("get pixel dimensions throws without pixel ratio", function() { expect(function() { return frustum.getPixelDimensions( 1, 1, 0, void 0, new import__276.Cartesian2() ); }).toThrowDeveloperError(); }); it("get pixel dimensions throws with pixel ratio less than or equal to zero", function() { expect(function() { return frustum.getPixelDimensions(1, 1, 0, 0, new import__276.Cartesian2()); }).toThrowDeveloperError(); }); it("get pixel dimensions", function() { const pixelSize = frustum.getPixelDimensions( 1, 1, 0, 1, new import__276.Cartesian2() ); expect(pixelSize.x).toEqual(2); expect(pixelSize.y).toEqual(2); }); it("get pixel dimensions with pixel ratio", function() { const pixelSize = frustum.getPixelDimensions( 1, 1, 0, 2, new import__276.Cartesian2() ); expect(pixelSize.x).toEqual(4); expect(pixelSize.y).toEqual(4); }); it("equals", function() { const frustum2 = new import__276.OrthographicOffCenterFrustum(); frustum2.near = 1; frustum2.far = 3; frustum2.right = 1; frustum2.left = -1; frustum2.top = 1; frustum2.bottom = -1; expect(frustum).toEqual(frustum2); }); it("equals epsilon", function() { const frustum2 = new import__276.OrthographicOffCenterFrustum(); frustum2.near = 1; frustum2.far = 3; frustum2.right = 1; frustum2.left = -1; frustum2.top = 1; frustum2.bottom = -1; expect(frustum.equalsEpsilon(frustum2, import__277.Math.EPSILON7)).toEqual(true); const frustum3 = new import__276.OrthographicOffCenterFrustum(); frustum3.near = 1.01; frustum3.far = 2.98; frustum3.right = 1.02; frustum3.left = -0.99; frustum3.top = 0.99; frustum3.bottom = -1.05; expect(frustum.equalsEpsilon(frustum3, import__277.Math.EPSILON1)).toEqual(true); const frustum4 = new import__276.OrthographicOffCenterFrustum(); frustum4.near = 1.1; frustum4.far = 2.9; frustum4.right = 0; frustum4.left = -1.02; frustum4.top = 1.02; frustum4.bottom = -1.005; expect(frustum.equalsEpsilon(frustum4, import__277.Math.EPSILON2)).toEqual(false); }); it("equals undefined", function() { expect(frustum.equals()).toEqual(false); }); it("throws with undefined frustum parameters", function() { const frustum2 = new import__276.OrthographicOffCenterFrustum(); expect(function() { return frustum2.projectionMatrix; }).toThrowDeveloperError(); }); it("clone", function() { const frustum2 = frustum.clone(); expect(frustum).toEqual(frustum2); }); it("clone with result parameter", function() { const result = new import__276.OrthographicOffCenterFrustum(); const frustum2 = frustum.clone(result); expect(frustum2).toBe(result); expect(frustum).toEqual(frustum2); }); }); // packages/engine/Specs/Core/PeliasGeocoderServiceSpec.js var import__278 = __toESM(require_Cesium(), 1); describe("Core/PeliasGeocoderService", function() { it("conforms to GeocoderService interface", function() { expect(import__278.PeliasGeocoderService).toConformToInterface(import__278.GeocoderService); }); it("constructor throws without url", function() { expect(function() { return new import__278.PeliasGeocoderService(void 0); }).toThrowDeveloperError(); }); it("returns geocoder results", async function() { const service = new import__278.PeliasGeocoderService("http://test.invalid/v1/"); const query = "some query"; const data = { features: [ { type: "Feature", geometry: { type: "Point", coordinates: [-75.172489, 39.927828] }, properties: { label: "1826 S 16th St, Philadelphia, PA, USA" } } ] }; spyOn(import__278.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(data) ); const results = await service.geocode(query); expect(results.length).toEqual(1); expect(results[0].displayName).toEqual(data.features[0].properties.label); expect(results[0].destination).toBeInstanceOf(import__278.Cartesian3); }); it("returns geocoder results with attributions", async function() { const service = new import__278.PeliasGeocoderService("http://test.invalid/v1/"); const query = "some query"; const data = { attributions: [ { html: `Credit`, collapsible: true } ], features: [ { type: "Feature", geometry: { type: "Point", coordinates: [-75.172489, 39.927828] }, properties: { label: "1826 S 16th St, Philadelphia, PA, USA" } } ] }; spyOn(import__278.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(data) ); const results = await service.geocode(query); expect(results.length).toEqual(1); expect(results[0].displayName).toEqual(data.features[0].properties.label); expect(results[0].destination).toBeInstanceOf(import__278.Cartesian3); expect(results[0].attributions.length).toBe(1); expect(results[0].attributions[0].html).toEqual("Credit"); }); it("returns no geocoder results if Pelias has no results", async function() { const service = new import__278.PeliasGeocoderService("http://test.invalid/v1/"); const query = "some query"; const data = { features: [] }; spyOn(import__278.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(data) ); const results = await service.geocode(query); expect(results.length).toEqual(0); }); it("calls search endpoint if specified", async function() { const service = new import__278.PeliasGeocoderService("http://test.invalid/v1/"); const query = "some query"; const data = { features: [] }; spyOn(import__278.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(data) ); const getDerivedResource = spyOn( service._url, "getDerivedResource" ).and.callThrough(); await service.geocode(query, import__278.GeocodeType.SEARCH); expect(getDerivedResource).toHaveBeenCalledWith({ url: "search", queryParameters: { text: query } }); }); it("calls autocomplete endpoint if specified", async function() { const service = new import__278.PeliasGeocoderService("http://test.invalid/v1/"); const query = "some query"; const data = { features: [] }; spyOn(import__278.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(data) ); const getDerivedResource = spyOn( service._url, "getDerivedResource" ).and.callThrough(); await service.geocode(query, import__278.GeocodeType.AUTOCOMPLETE); expect(getDerivedResource).toHaveBeenCalledWith({ url: "autocomplete", queryParameters: { text: query } }); }); }); // packages/engine/Specs/Core/PerspectiveFrustumSpec.js var import__279 = __toESM(require_Cesium(), 1); var import__280 = __toESM(require_Cesium(), 1); describe("Core/PerspectiveFrustum", function() { let frustum, planes; beforeEach(function() { frustum = new import__279.PerspectiveFrustum(); frustum.near = 1; frustum.far = 2; frustum.aspectRatio = 1; frustum.fov = Math.PI / 3; planes = frustum.computeCullingVolume( new import__279.Cartesian3(), import__279.Cartesian3.negate(import__279.Cartesian3.UNIT_Z, new import__279.Cartesian3()), import__279.Cartesian3.UNIT_Y ).planes; }); it("constructs", function() { const options = { fov: 1, aspectRatio: 2, near: 3, far: 4, xOffset: 5, yOffset: 6 }; const f = new import__279.PerspectiveFrustum(options); expect(f.fov).toEqual(options.fov); expect(f.aspectRatio).toEqual(options.aspectRatio); expect(f.near).toEqual(options.near); expect(f.far).toEqual(options.far); expect(f.xOffset).toEqual(options.xOffset); expect(f.yOffset).toEqual(options.yOffset); }); it("default constructs", function() { const f = new import__279.PerspectiveFrustum(); expect(f.fov).toBeUndefined(); expect(f.aspectRatio).toBeUndefined(); expect(f.near).toEqual(1); expect(f.far).toEqual(5e8); expect(f.xOffset).toEqual(0); expect(f.yOffset).toEqual(0); }); it("out of range fov causes an exception", function() { frustum.fov = -1; expect(function() { return frustum.projectionMatrix; }).toThrowDeveloperError(); frustum.fov = import__280.Math.TWO_PI; expect(function() { return frustum.projectionMatrix; }).toThrowDeveloperError(); }); it("negative aspect ratio throws an exception", function() { frustum.aspectRatio = -1; expect(function() { return frustum.projectionMatrix; }).toThrowDeveloperError(); }); it("out of range near plane throws an exception", function() { frustum.near = -1; expect(function() { return frustum.projectionMatrix; }).toThrowDeveloperError(); }); it("negative far plane throws an exception", function() { frustum.far = -1; expect(function() { return frustum.projectionMatrix; }).toThrowDeveloperError(); }); it("computeCullingVolume with no position throws an exception", function() { expect(function() { return frustum.computeCullingVolume(); }).toThrowDeveloperError(); }); it("computeCullingVolume with no direction throws an exception", function() { expect(function() { return frustum.computeCullingVolume(new import__279.Cartesian3()); }).toThrowDeveloperError(); }); it("computeCullingVolume with no up throws an exception", function() { expect(function() { return frustum.computeCullingVolume(new import__279.Cartesian3(), new import__279.Cartesian3()); }).toThrowDeveloperError(); }); it("get frustum left plane", function() { const leftPlane = planes[0]; const expectedResult = new import__279.Cartesian4(Math.sqrt(3) / 2, 0, -0.5, 0); expect(leftPlane).toEqualEpsilon(expectedResult, import__280.Math.EPSILON14); }); it("get frustum right plane", function() { const rightPlane = planes[1]; const expectedResult = new import__279.Cartesian4( -Math.sqrt(3) / 2, 0, -0.5, 0 ); expect(rightPlane).toEqualEpsilon(expectedResult, import__280.Math.EPSILON14); }); it("get frustum bottom plane", function() { const bottomPlane = planes[2]; const expectedResult = new import__279.Cartesian4(0, Math.sqrt(3) / 2, -0.5, 0); expect(bottomPlane).toEqualEpsilon(expectedResult, import__280.Math.EPSILON14); }); it("get frustum top plane", function() { const topPlane = planes[3]; const expectedResult = new import__279.Cartesian4( 0, -Math.sqrt(3) / 2, -0.5, 0 ); expect(topPlane).toEqualEpsilon(expectedResult, import__280.Math.EPSILON14); }); it("get frustum near plane", function() { const nearPlane = planes[4]; const expectedResult = new import__279.Cartesian4(0, 0, -1, -1); expect(nearPlane).toEqual(expectedResult); }); it("get frustum far plane", function() { const farPlane = planes[5]; const expectedResult = new import__279.Cartesian4(0, 0, 1, 2); expect(farPlane).toEqual(expectedResult); }); it("get sseDenominator", function() { expect(frustum.sseDenominator).toEqualEpsilon(1.1547, import__280.Math.EPSILON5); }); it("get perspective projection matrix", function() { const projectionMatrix = frustum.projectionMatrix; const expected = import__279.Matrix4.computePerspectiveFieldOfView( frustum.fovy, frustum.aspectRatio, frustum.near, frustum.far, new import__279.Matrix4() ); expect(projectionMatrix).toEqualEpsilon(expected, import__280.Math.EPSILON6); }); it("get infinite perspective matrix", function() { const top = frustum.near * Math.tan(0.5 * frustum.fovy); const bottom = -top; const right = frustum.aspectRatio * top; const left = -right; const near = frustum.near; const expected = import__279.Matrix4.computeInfinitePerspectiveOffCenter( left, right, bottom, top, near, new import__279.Matrix4() ); expect(frustum.infiniteProjectionMatrix).toEqual(expected); }); it("get pixel dimensions throws without canvas height", function() { expect(function() { return frustum.getPixelDimensions( 1, void 0, 1, 1, new import__279.Cartesian2() ); }).toThrowDeveloperError(); }); it("get pixel dimensions throws without canvas width", function() { expect(function() { return frustum.getPixelDimensions( void 0, 1, 1, 1, new import__279.Cartesian2() ); }).toThrowDeveloperError(); }); it("get pixel dimensions throws with canvas width less than or equal to zero", function() { expect(function() { return frustum.getPixelDimensions(0, 1, 1, 1, new import__279.Cartesian2()); }).toThrowDeveloperError(); }); it("get pixel dimensions throws with canvas height less than or equal to zero", function() { expect(function() { return frustum.getPixelDimensions(1, 0, 1, 1, new import__279.Cartesian2()); }).toThrowDeveloperError(); }); it("get pixel dimensions throws without pixel ratio", function() { expect(function() { return frustum.getPixelDimensions( 1, 1, 1, void 0, new import__279.Cartesian2() ); }).toThrowDeveloperError(); }); it("get pixel dimensions throws with pixel ratio less than or equal to zero", function() { expect(function() { return frustum.getPixelDimensions(1, 1, 1, 0, new import__279.Cartesian2()); }).toThrowDeveloperError(); }); it("get pixel dimensions", function() { const dimensions = new import__279.Cartesian2(1, 1); const pixelRatio = 1; const distance = 1; const pixelSize = frustum.getPixelDimensions( dimensions.x, dimensions.y, distance, pixelRatio, new import__279.Cartesian2() ); const expected = frustum.offCenterFrustum.getPixelDimensions( dimensions.x, dimensions.y, distance, pixelRatio, new import__279.Cartesian2() ); expect(pixelSize.x).toEqual(expected.x); expect(pixelSize.y).toEqual(expected.y); }); it("get pixel dimensions with pixel ratio", function() { const dimensions = new import__279.Cartesian2(1, 1); const pixelRatio = 2; const distance = 1; const pixelSize = frustum.getPixelDimensions( dimensions.x, dimensions.y, distance, pixelRatio, new import__279.Cartesian2() ); const expected = frustum.offCenterFrustum.getPixelDimensions( dimensions.x, dimensions.y, distance, pixelRatio, new import__279.Cartesian2() ); expect(pixelSize.x).toEqual(expected.x); expect(pixelSize.y).toEqual(expected.y); }); it("equals", function() { const frustum2 = new import__279.PerspectiveFrustum(); frustum2.near = 1; frustum2.far = 2; frustum2.fov = Math.PI / 3; frustum2.aspectRatio = 1; expect(frustum.equals(frustum2)).toEqual(true); }); it("equals epsilon", function() { const frustum2 = new import__279.PerspectiveFrustum(); frustum2.near = 1; frustum2.far = 2; frustum2.fov = Math.PI / 3; frustum2.aspectRatio = 1; expect(frustum.equalsEpsilon(frustum2, import__280.Math.EPSILON7)).toEqual(true); const frustum3 = new import__279.PerspectiveFrustum(); frustum3.near = 1.01; frustum3.far = 2.01; frustum3.fov = Math.PI / 3 + 0.01; frustum3.aspectRatio = 1.01; expect(frustum.equalsEpsilon(frustum3, import__280.Math.EPSILON1)).toEqual(true); const frustum4 = new import__279.PerspectiveFrustum(); frustum4.near = 1; frustum4.far = 2; frustum4.fov = Math.PI / 3; frustum4.aspectRatio = 1.1; expect(frustum.equalsEpsilon(frustum4, import__280.Math.EPSILON2)).toEqual(false); }); it("equals undefined", function() { expect(frustum.equals()).toEqual(false); }); it("throws with undefined frustum parameters", function() { const frustum2 = new import__279.PerspectiveFrustum(); expect(function() { return frustum2.infiniteProjectionMatrix; }).toThrowDeveloperError(); }); it("clone", function() { const frustum2 = frustum.clone(); expect(frustum).toEqual(frustum2); }); it("clone with result parameter", function() { const result = new import__279.PerspectiveFrustum(); const frustum2 = frustum.clone(result); expect(frustum2).toBe(result); expect(frustum).toEqual(frustum2); }); createPackableSpecs_default( import__279.PerspectiveFrustum, new import__279.PerspectiveFrustum({ fov: 1, aspectRatio: 2, near: 3, far: 4, xOffset: 5, yOffset: 6 }), [1, 2, 3, 4, 5, 6] ); }); // packages/engine/Specs/Core/PerspectiveOffCenterFrustumSpec.js var import__281 = __toESM(require_Cesium(), 1); var import__282 = __toESM(require_Cesium(), 1); describe("Core/PerspectiveOffCenterFrustum", function() { let frustum, planes; beforeEach(function() { frustum = new import__281.PerspectiveOffCenterFrustum(); frustum.right = 1; frustum.left = -frustum.right; frustum.top = 1; frustum.bottom = -frustum.top; frustum.near = 1; frustum.far = 2; planes = frustum.computeCullingVolume( new import__281.Cartesian3(), import__281.Cartesian3.negate(import__281.Cartesian3.UNIT_Z, new import__281.Cartesian3()), import__281.Cartesian3.UNIT_Y ).planes; }); it("constructs", function() { const options = { left: -1, right: 2, top: 5, bottom: -1, near: 3, far: 4 }; const f = new import__281.PerspectiveOffCenterFrustum(options); expect(f.width).toEqual(options.width); expect(f.aspectRatio).toEqual(options.aspectRatio); expect(f.near).toEqual(options.near); expect(f.far).toEqual(options.far); }); it("default constructs", function() { const f = new import__281.PerspectiveOffCenterFrustum(); expect(f.left).toBeUndefined(); expect(f.right).toBeUndefined(); expect(f.top).toBeUndefined(); expect(f.bottom).toBeUndefined(); expect(f.near).toEqual(1); expect(f.far).toEqual(5e8); }); it("out of range near plane throws an exception", function() { frustum.near = -1; expect(function() { return frustum.projectionMatrix; }).toThrowDeveloperError(); }); it("negative far plane throws an exception", function() { frustum.far = -1; expect(function() { return frustum.projectionMatrix; }).toThrowDeveloperError(); }); it("computeCullingVolume with no position throws an exception", function() { expect(function() { return frustum.computeCullingVolume(); }).toThrowDeveloperError(); }); it("computeCullingVolume with no direction throws an exception", function() { expect(function() { return frustum.computeCullingVolume(new import__281.Cartesian3()); }).toThrowDeveloperError(); }); it("computeCullingVolume with no up throws an exception", function() { expect(function() { return frustum.computeCullingVolume(new import__281.Cartesian3(), new import__281.Cartesian3()); }).toThrowDeveloperError(); }); it("get frustum left plane", function() { const leftPlane = planes[0]; const x = 1 / Math.sqrt(2); const expectedResult = new import__281.Cartesian4(x, 0, -x, 0); expect(leftPlane).toEqualEpsilon(expectedResult, import__282.Math.EPSILON15); }); it("get frustum right plane", function() { const rightPlane = planes[1]; const x = 1 / Math.sqrt(2); const expectedResult = new import__281.Cartesian4(-x, 0, -x, 0); expect(rightPlane).toEqualEpsilon(expectedResult, import__282.Math.EPSILON15); }); it("get frustum bottom plane", function() { const bottomPlane = planes[2]; const x = 1 / Math.sqrt(2); const expectedResult = new import__281.Cartesian4(0, x, -x, 0); expect(bottomPlane).toEqualEpsilon(expectedResult, import__282.Math.EPSILON15); }); it("get frustum top plane", function() { const topPlane = planes[3]; const x = 1 / Math.sqrt(2); const expectedResult = new import__281.Cartesian4(0, -x, -x, 0); expect(topPlane).toEqualEpsilon(expectedResult, import__282.Math.EPSILON15); }); it("get frustum near plane", function() { const nearPlane = planes[4]; const expectedResult = new import__281.Cartesian4(0, 0, -1, -1); expect(nearPlane).toEqualEpsilon(expectedResult, import__282.Math.EPSILON15); }); it("get frustum far plane", function() { const farPlane = planes[5]; const expectedResult = new import__281.Cartesian4(0, 0, 1, 2); expect(farPlane).toEqualEpsilon(expectedResult, import__282.Math.EPSILON15); }); it("get perspective projection matrix", function() { const projectionMatrix = frustum.projectionMatrix; const top = frustum.top; const bottom = frustum.bottom; const right = frustum.right; const left = frustum.left; const near = frustum.near; const far = frustum.far; const expected = import__281.Matrix4.computePerspectiveOffCenter( left, right, bottom, top, near, far, new import__281.Matrix4() ); expect(projectionMatrix).toEqualEpsilon(expected, import__282.Math.EPSILON6); }); it("get infinite perspective matrix", function() { const top = frustum.top; const bottom = frustum.bottom; const right = frustum.right; const left = frustum.left; const near = frustum.near; const expected = import__281.Matrix4.computeInfinitePerspectiveOffCenter( left, right, bottom, top, near, new import__281.Matrix4() ); expect(expected).toEqual(frustum.infiniteProjectionMatrix); }); it("get pixel dimensions throws without canvas height", function() { expect(function() { return frustum.getPixelDimensions( 1, void 0, 1, 1, new import__281.Cartesian2() ); }).toThrowDeveloperError(); }); it("get pixel dimensions throws without canvas width", function() { expect(function() { return frustum.getPixelDimensions( void 0, 1, 1, 1, new import__281.Cartesian2() ); }).toThrowDeveloperError(); }); it("get pixel dimensions throws with canvas width less than or equal to zero", function() { expect(function() { return frustum.getPixelDimensions(0, 1, 1, 1, new import__281.Cartesian2()); }).toThrowDeveloperError(); }); it("get pixel dimensions throws with canvas height less than or equal to zero", function() { expect(function() { return frustum.getPixelDimensions(1, 0, 1, 1, new import__281.Cartesian2()); }).toThrowDeveloperError(); }); it("get pixel dimensions throws without pixel ratio", function() { expect(function() { return frustum.getPixelDimensions( 1, 1, 1, void 0, new import__281.Cartesian2() ); }).toThrowDeveloperError(); }); it("get pixel dimensions throws with pixel ratio less than or equal to zero", function() { expect(function() { return frustum.getPixelDimensions(1, 1, 1, 0, new import__281.Cartesian2()); }).toThrowDeveloperError(); }); it("get pixel dimensions", function() { const pixelSize = frustum.getPixelDimensions( 1, 1, 1, 1, new import__281.Cartesian2() ); expect(pixelSize.x).toEqual(2); expect(pixelSize.y).toEqual(2); }); it("get pixel dimensions with pixel ratio", function() { const pixelSize = frustum.getPixelDimensions( 1, 1, 1, 2, new import__281.Cartesian2() ); expect(pixelSize.x).toEqual(4); expect(pixelSize.y).toEqual(4); }); it("equals", function() { const frustum2 = new import__281.PerspectiveOffCenterFrustum(); frustum2.right = 1; frustum2.left = -frustum.right; frustum2.top = 1; frustum2.bottom = -frustum.top; frustum2.near = 1; frustum2.far = 2; frustum2.position = new import__281.Cartesian3(); frustum2.direction = import__281.Cartesian3.negate(import__281.Cartesian3.UNIT_Z, new import__281.Cartesian3()); frustum2.up = import__281.Cartesian3.UNIT_Y; expect(frustum).toEqual(frustum2); }); it("equals epsilon", function() { const frustum2 = new import__281.PerspectiveOffCenterFrustum(); frustum2.right = 1; frustum2.left = -frustum.right; frustum2.top = 1; frustum2.bottom = -frustum.top; frustum2.near = 1; frustum2.far = 2; expect(frustum.equalsEpsilon(frustum2, import__282.Math.EPSILON7)).toEqual(true); const frustum3 = new import__281.PerspectiveOffCenterFrustum(); frustum3.right = 1.01; frustum3.left = -frustum.right; frustum3.top = 1.01; frustum3.bottom = -frustum.top; frustum3.near = 1.01; frustum3.far = 1.99; expect(frustum.equalsEpsilon(frustum3, import__282.Math.EPSILON1)).toEqual(true); const frustum4 = new import__281.PerspectiveOffCenterFrustum(); frustum4.right = 1.1; frustum4.left = -frustum.right; frustum4.top = 1; frustum4.bottom = -frustum.top; frustum4.near = 1; frustum4.far = 2; expect(frustum.equalsEpsilon(frustum4, import__282.Math.EPSILON2)).toEqual(false); }); it("equals undefined", function() { expect(frustum.equals()).toEqual(false); }); it("throws with undefined frustum parameters", function() { const frustum2 = new import__281.PerspectiveOffCenterFrustum(); expect(function() { return frustum2.infiniteProjectionMatrix; }).toThrowDeveloperError(); }); it("clone", function() { const frustum2 = frustum.clone(); expect(frustum).toEqual(frustum2); }); it("clone with result parameter", function() { const result = new import__281.PerspectiveOffCenterFrustum(); const frustum2 = frustum.clone(result); expect(frustum2).toBe(result); expect(frustum).toEqual(frustum2); }); }); // packages/engine/Specs/Core/PinBuilderSpec.js var import__283 = __toESM(require_Cesium(), 1); describe("Core/PinBuilder", function() { function getPinColor(canvas) { const context2D = canvas.getContext("2d"); const data = context2D.getImageData(64, 5, 1, 1).data; return import__283.Color.fromBytes(data[0], data[1], data[2]); } function getIconColor(canvas) { const context2D = canvas.getContext("2d"); const data = context2D.getImageData(64, 32, 1, 1).data; return import__283.Color.fromBytes(data[0], data[1], data[2]); } it("fromColor creates icon of correct color", function() { const builder = new import__283.PinBuilder(); const canvas = builder.fromColor(import__283.Color.GREEN, 128); expect(getPinColor(canvas)).toEqual(import__283.Color.GREEN); }); it("fromText creates icon of correct color with symbol", function() { const builder = new import__283.PinBuilder(); const canvas = builder.fromText("\u25A0", import__283.Color.BLUE, 128); expect(getPinColor(canvas)).toEqual(import__283.Color.BLUE); expect(getIconColor(canvas)).toEqual(import__283.Color.WHITE); }); it("fromUrl creates icon of correct color with symbol", function() { const builder = new import__283.PinBuilder(); return Promise.resolve( builder.fromUrl( (0, import__283.buildModuleUrl)("Assets/Textures/maki/square.png"), import__283.Color.RED, 128 ) ).then(function(canvas) { expect(getPinColor(canvas)).toEqual(import__283.Color.RED); expect(getIconColor(canvas)).toEqual(import__283.Color.WHITE); }); }); it("fromMakiIconId creates icon of correct color with symbol", function() { const builder = new import__283.PinBuilder(); return Promise.resolve( builder.fromMakiIconId("square", import__283.Color.YELLOW, 128) ).then(function(canvas) { expect(getPinColor(canvas)).toEqual(import__283.Color.YELLOW); expect(getIconColor(canvas)).toEqual(import__283.Color.WHITE); }); }); it("caches and returns existing canvas", function() { const builder = new import__283.PinBuilder(); const canvas = builder.fromColor(import__283.Color.GREEN, 128); const canvas2 = builder.fromColor(import__283.Color.GREEN, 128); expect(canvas).toBe(canvas2); }); it("fromColor throws without color", function() { const builder = new import__283.PinBuilder(); expect(function() { builder.fromColor(void 0, 128); }).toThrowDeveloperError(); }); it("fromColor throws without size", function() { const builder = new import__283.PinBuilder(); expect(function() { builder.fromColor(import__283.Color.RED, void 0); }).toThrowDeveloperError(); }); it("fromText throws without text", function() { const builder = new import__283.PinBuilder(); expect(function() { builder.fromText(void 0, import__283.Color.RED, 128); }).toThrowDeveloperError(); }); it("fromText throws without color", function() { const builder = new import__283.PinBuilder(); expect(function() { builder.fromText("text", void 0, 128); }).toThrowDeveloperError(); }); it("fromText throws without size", function() { const builder = new import__283.PinBuilder(); expect(function() { builder.fromText("text", import__283.Color.RED, void 0); }).toThrowDeveloperError(); }); it("fromUrl throws without url", function() { const builder = new import__283.PinBuilder(); expect(function() { builder.fromUrl(void 0, import__283.Color.RED, 128); }).toThrowDeveloperError(); }); it("fromUrl throws without color", function() { const builder = new import__283.PinBuilder(); expect(function() { builder.fromUrl("http://someUrl.invalid/some.png", void 0, 128); }).toThrowDeveloperError(); }); it("fromUrl throws without size", function() { const builder = new import__283.PinBuilder(); expect(function() { builder.fromUrl("http://someUrl.invalid/some.png", import__283.Color.RED, void 0); }).toThrowDeveloperError(); }); it("fromMakiIconId throws without id", function() { const builder = new import__283.PinBuilder(); expect(function() { builder.fromMakiIconId(void 0, import__283.Color.RED, 128); }).toThrowDeveloperError(); }); it("fromMakiIconId throws without color", function() { const builder = new import__283.PinBuilder(); expect(function() { builder.fromMakiIconId("hospital", void 0, 128); }).toThrowDeveloperError(); }); it("fromMakiIconId throws without size", function() { const builder = new import__283.PinBuilder(); expect(function() { builder.fromMakiIconId("hospital", import__283.Color.RED, void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/PixelFormatSpec.js var import__284 = __toESM(require_Cesium(), 1); describe("Core/PixelFormat", function() { it("flipY works", function() { const width = 1; const height = 2; const values = [255, 0, 0, 0, 255, 0]; const expectedValues = [0, 255, 0, 255, 0, 0]; const dataBuffer = new Uint8Array(values); const expectedDataBuffer = new Uint8Array(expectedValues); const flipped = import__284.PixelFormat.flipY( dataBuffer, import__284.PixelFormat.RGB, import__284.PixelDatatype.UNSIGNED_BYTE, width, height ); expect(flipped).toEqual(expectedDataBuffer); }); it("flipY returns early if height is 1", function() { const width = 1; const height = 1; const values = [255, 255, 255]; const dataBuffer = new Uint8Array(values); const flipped = import__284.PixelFormat.flipY( dataBuffer, import__284.PixelFormat.RGB, import__284.PixelDatatype.UNSIGNED_BYTE, width, height ); expect(flipped).toBe(dataBuffer); }); }); // packages/engine/Specs/Core/PlaneGeometrySpec.js var import__285 = __toESM(require_Cesium(), 1); describe("Core/PlaneGeometry", function() { it("constructor creates optimized number of positions for VertexFormat.POSITIONS_ONLY", function() { const m = import__285.PlaneGeometry.createGeometry( new import__285.PlaneGeometry({ vertexFormat: import__285.VertexFormat.POSITION_ONLY }) ); expect(m.attributes.position.values.length).toEqual(4 * 3); expect(m.indices.length).toEqual(2 * 3); }); it("constructor computes all vertex attributes", function() { const m = import__285.PlaneGeometry.createGeometry( new import__285.PlaneGeometry({ vertexFormat: import__285.VertexFormat.ALL }) ); const numVertices = 4; const numTriangles = 2; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.attributes.normal.values.length).toEqual(numVertices * 3); expect(m.attributes.tangent.values.length).toEqual(numVertices * 3); expect(m.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(m.attributes.st.values.length).toEqual(numVertices * 2); expect(m.indices.length).toEqual(numTriangles * 3); expect(m.boundingSphere.center).toEqual(import__285.Cartesian3.ZERO); expect(m.boundingSphere.radius).toEqual(Math.sqrt(2)); }); createPackableSpecs_default( import__285.PlaneGeometry, new import__285.PlaneGeometry({ vertexFormat: import__285.VertexFormat.POSITION_AND_NORMAL }), [1, 1, 0, 0, 0, 0] ); }); // packages/engine/Specs/Core/PlaneOutlineGeometrySpec.js var import__286 = __toESM(require_Cesium(), 1); describe("Core/PlaneOutlineGeometry", function() { it("constructor creates positions", function() { const m = import__286.PlaneOutlineGeometry.createGeometry(new import__286.PlaneOutlineGeometry()); expect(m.attributes.position.values.length).toEqual(4 * 3); expect(m.indices.length).toEqual(4 * 2); }); createPackableSpecs_default(import__286.PlaneOutlineGeometry, new import__286.PlaneOutlineGeometry(), []); }); // packages/engine/Specs/Core/PlaneSpec.js var import__287 = __toESM(require_Cesium(), 1); var import__288 = __toESM(require_Cesium(), 1); describe("Core/Plane", function() { it("constructs", function() { const normal = import__287.Cartesian3.UNIT_X; const distance = 1; const plane = new import__287.Plane(normal, distance); expect(plane.normal).toEqual(normal); expect(plane.distance).toEqual(distance); }); it("constructor throws without a normal", function() { expect(function() { return new import__287.Plane(void 0, 0); }).toThrowDeveloperError(); }); it("constructor throws if normal is not normalized", function() { expect(function() { return new import__287.Plane(new import__287.Cartesian3(1, 2, 3), 0); }).toThrowDeveloperError(); }); it("constructor throws without a distance", function() { expect(function() { return new import__287.Plane(import__287.Cartesian3.UNIT_X, void 0); }).toThrowDeveloperError(); }); it("constructs from a point and a normal", function() { let normal = new import__287.Cartesian3(1, 2, 3); normal = import__287.Cartesian3.normalize(normal, normal); const point = new import__287.Cartesian3(4, 5, 6); const plane = import__287.Plane.fromPointNormal(point, normal); expect(plane.normal).toEqual(normal); expect(plane.distance).toEqual(-import__287.Cartesian3.dot(normal, point)); }); it("constructs from a point and a normal with result", function() { let normal = new import__287.Cartesian3(1, 2, 3); normal = import__287.Cartesian3.normalize(normal, normal); const point = new import__287.Cartesian3(4, 5, 6); const plane = new import__287.Plane(import__287.Cartesian3.UNIT_X, 0); import__287.Plane.fromPointNormal(point, normal, plane); expect(plane.normal).toEqual(normal); expect(plane.distance).toEqual(-import__287.Cartesian3.dot(normal, point)); }); it("constructs from a Cartesian4 without result", function() { const result = import__287.Plane.fromCartesian4(import__287.Cartesian4.UNIT_X); expect(result.normal).toEqual(import__287.Cartesian3.UNIT_X); expect(result.distance).toEqual(0); }); it("constructs from a Cartesian4 with result", function() { const result = new import__287.Plane(import__287.Cartesian3.UNIT_X, 0); import__287.Plane.fromCartesian4(import__287.Cartesian4.UNIT_X, result); expect(result.normal).toEqual(import__287.Cartesian3.UNIT_X); expect(result.distance).toEqual(0); }); it("fromPointNormal throws without a point", function() { expect(function() { return import__287.Plane.fromPointNormal(void 0, import__287.Cartesian3.UNIT_X); }).toThrowDeveloperError(); }); it("fromPointNormal throws without a normal", function() { expect(function() { return import__287.Plane.fromPointNormal(import__287.Cartesian3.UNIT_X, void 0); }).toThrowDeveloperError(); }); it("fromPointNormal throws if normal is not normalized", function() { expect(function() { return import__287.Plane.fromPointNormal(import__287.Cartesian3.ZERO, import__287.Cartesian3.ZERO); }).toThrowDeveloperError(); }); it("fromCartesian4 throws without coefficients", function() { expect(function() { return import__287.Plane.fromCartesian4(void 0); }).toThrowDeveloperError(); }); it("fromCartesian4 throws if normal is not normalized", function() { expect(function() { return import__287.Plane.fromCartesian4(new import__287.Cartesian4(1, 2, 3, 4)); }).toThrowDeveloperError(); }); it("gets the distance to a point", function() { let normal = new import__287.Cartesian3(1, 2, 3); normal = import__287.Cartesian3.normalize(normal, normal); const plane = new import__287.Plane(normal, 12.34); const point = new import__287.Cartesian3(4, 5, 6); expect(import__287.Plane.getPointDistance(plane, point)).toEqual( import__287.Cartesian3.dot(plane.normal, point) + plane.distance ); }); it("getPointDistance throws without a plane", function() { const point = import__287.Cartesian3.ZERO; expect(function() { return import__287.Plane.getPointDistance(void 0, point); }).toThrowDeveloperError(); }); it("getPointDistance throws without a point", function() { const plane = new import__287.Plane(import__287.Cartesian3.UNIT_X, 0); expect(function() { return import__287.Plane.getPointDistance(plane, void 0); }).toThrowDeveloperError(); }); it("projects a point onto the plane", function() { let plane = new import__287.Plane(import__287.Cartesian3.UNIT_X, 0); const point = new import__287.Cartesian3(1, 1, 0); let result = import__287.Plane.projectPointOntoPlane(plane, point); expect(result).toEqual(new import__287.Cartesian3(0, 1, 0)); plane = new import__287.Plane(import__287.Cartesian3.UNIT_Y, 0); result = import__287.Plane.projectPointOntoPlane(plane, point); expect(result).toEqual(new import__287.Cartesian3(1, 0, 0)); }); it("projectPointOntoPlane uses result parameter", function() { const plane = new import__287.Plane(import__287.Cartesian3.UNIT_X, 0); const point = new import__287.Cartesian3(1, 1, 0); const result = new import__287.Cartesian3(); const returnedResult = import__287.Plane.projectPointOntoPlane(plane, point, result); expect(result).toBe(returnedResult); expect(result).toEqual(new import__287.Cartesian3(0, 1, 0)); }); it("projectPointOntoPlane requires the plane and point parameters", function() { expect(function() { return import__287.Plane.projectPointOntoPlane( new import__287.Plane(import__287.Cartesian3.UNIT_X, 0), void 0 ); }).toThrowDeveloperError(); expect(function() { return import__287.Plane.projectPointOntoPlane(void 0, new import__287.Cartesian3()); }).toThrowDeveloperError(); }); it("clone throws without a plane", function() { expect(function() { import__287.Plane.clone(void 0); }).toThrowDeveloperError(); }); it("clones a plane instance", function() { let normal = new import__287.Cartesian3(1, 2, 3); normal = import__287.Cartesian3.normalize(normal, normal); const distance = 4; const plane = new import__287.Plane(normal, distance); const result = import__287.Plane.clone(plane); expect(result.normal).toEqual(normal); expect(result.distance).toEqual(distance); }); it("clones a plane instance into a result parameter", function() { let normal = new import__287.Cartesian3(1, 2, 3); normal = import__287.Cartesian3.normalize(normal, normal); const distance = 4; const plane = new import__287.Plane(normal, distance); const result = new import__287.Plane(import__287.Cartesian3.UNIT_X, 1); import__287.Plane.clone(plane, result); expect(result.normal).toEqual(normal); expect(result.distance).toEqual(distance); }); it("equals returns true only if two planes are equal by normal and distance", function() { const left = new import__287.Plane(import__287.Cartesian3.UNIT_X, 0); const right = new import__287.Plane(import__287.Cartesian3.UNIT_Y, 1); expect(import__287.Plane.equals(left, right)).toBe(false); right.distance = 0; expect(import__287.Plane.equals(left, right)).toBe(false); right.normal = import__287.Cartesian3.UNIT_X; expect(import__287.Plane.equals(left, right)).toBe(true); right.distance = 1; expect(import__287.Plane.equals(left, right)).toBe(false); }); it("equals throws developer error is left is undefined", function() { const plane = new import__287.Plane(import__287.Cartesian3.UNIT_X, 0); expect(function() { return import__287.Plane.equals(void 0, plane); }).toThrowDeveloperError(); }); it("equals throws developer error is right is undefined", function() { const plane = new import__287.Plane(import__287.Cartesian3.UNIT_X, 0); expect(function() { return import__287.Plane.equals(plane, void 0); }).toThrowDeveloperError(); }); it("transforms a plane according to a transform", function() { let normal = new import__287.Cartesian3(1, 2, 3); normal = import__287.Cartesian3.normalize(normal, normal); const plane = new import__287.Plane(normal, 12.34); let transform = import__287.Matrix4.fromUniformScale(2); transform = import__287.Matrix4.multiplyByMatrix3( transform, import__287.Matrix3.fromRotationY(Math.PI), transform ); const transformedPlane = import__287.Plane.transform(plane, transform); expect(transformedPlane.distance).toEqual(plane.distance * 2); expect(transformedPlane.normal.x).toEqualEpsilon( -plane.normal.x, import__288.Math.EPSILON10 ); expect(transformedPlane.normal.y).toEqual(plane.normal.y); expect(transformedPlane.normal.z).toEqual(-plane.normal.z); }); it("transforms a plane according to a non-uniform scale transform", function() { let normal = new import__287.Cartesian3(1, 0, 1); normal = import__287.Cartesian3.normalize(normal, normal); const plane = new import__287.Plane(normal, 0); const planeOrigin = new import__287.Cartesian3(0, 0, 0); const planePosition = new import__287.Cartesian3(1, 0, -1); const planeDiff = import__287.Cartesian3.subtract( planePosition, planeOrigin, new import__287.Cartesian3() ); expect(import__287.Cartesian3.dot(planeDiff, plane.normal)).toEqualEpsilon( 0, import__288.Math.EPSILON16 ); const transform = import__287.Matrix4.fromScale( new import__287.Cartesian3(4, 1, 10), new import__287.Matrix4() ); const transformPlane = import__287.Plane.transform(plane, transform); const transformPlaneDiff = import__287.Matrix4.multiplyByPointAsVector( transform, planeDiff, new import__287.Cartesian3() ); expect( import__287.Cartesian3.dot(transformPlaneDiff, transformPlane.normal) ).toEqualEpsilon(0, import__288.Math.EPSILON16); }); it("transform throws without a plane", function() { const transform = import__287.Matrix4.IDENTITY; expect(function() { return import__287.Plane.transform(void 0, transform); }).toThrowDeveloperError(); }); it("transform throws without a transform", function() { const plane = new import__287.Plane(import__287.Cartesian3.UNIT_X, 0); expect(function() { return import__287.Plane.transform(plane, void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/PolygonGeometryLibrarySpec.js var import__289 = __toESM(require_Cesium(), 1); describe("Core/PolygonGeometryLibrary", function() { describe("splitPolygonByPlane", function() { it("splits a simple polygon at the equator", function() { const positions = import__289.Cartesian3.unpackArray([ 3813220, -5085291, 527179, 3701301, -5097773, -993503, 5037375, -3776794, -1017021, 5049166, -3865306, 494270 ]); const polygons = import__289.PolygonGeometryLibrary.splitPolygonsOnEquator( [positions], import__289.Ellipsoid.WGS84, import__289.ArcType.GEODESIC ); const expectedIntersection1 = new import__289.Cartesian3( 3.7992586687873346e6, -5123110886796548e-9, 0 ); const expectedIntersection2 = new import__289.Cartesian3( 5077099353935631e-9, -3860530240917096e-9, 0 ); expect(polygons.length).toBe(2); expect(polygons[0].length).toBe(4); expect(polygons[0][0]).toEqual(positions[0]); expect(polygons[0][1]).toEqualEpsilon( expectedIntersection1, import__289.Math.EPSILON7 ); expect(polygons[0][2]).toEqualEpsilon( expectedIntersection2, import__289.Math.EPSILON7 ); expect(polygons[0][3]).toEqual(positions[3]); expect(polygons[1].length).toBe(4); expect(polygons[1][0]).toEqualEpsilon( expectedIntersection1, import__289.Math.EPSILON7 ); expect(polygons[1][1]).toEqual(positions[1]); expect(polygons[1][2]).toEqual(positions[2]); expect(polygons[1][3]).toEqualEpsilon( expectedIntersection2, import__289.Math.EPSILON7 ); }); it("does not split a simple polygon with one position touching the equator", function() { const positions = import__289.Cartesian3.unpackArray([ 3813220, -5085291, 527179, 3701301, -5097773, 0, 5049166, -3865306, 494270 ]); const polygons = import__289.PolygonGeometryLibrary.splitPolygonsOnEquator( [positions], import__289.Ellipsoid.WGS84, import__289.ArcType.GEODESIC ); expect(polygons.length).toBe(1); expect(polygons[0].length).toBe(3); expect(polygons[0][0]).toEqual(positions[0]); expect(polygons[0][1]).toEqual(positions[1]); expect(polygons[0][2]).toEqual(positions[2]); }); it("does not split a simple polygon with one edge on the equator, starting above the equator", function() { const positions = import__289.Cartesian3.unpackArray([ -3219367, -5491259, 401098, -3217795, -5506913, 0, -2713036, -5772334, 0, -2713766, -5757498, 406910 ]); const polygons = import__289.PolygonGeometryLibrary.splitPolygonsOnEquator( [positions], import__289.Ellipsoid.WGS84, import__289.ArcType.GEODESIC ); expect(polygons.length).toBe(1); expect(polygons[0].length).toBe(4); expect(polygons[0][0]).toEqual(positions[0]); expect(polygons[0][1]).toEqual(positions[1]); expect(polygons[0][2]).toEqual(positions[2]); expect(polygons[0][3]).toEqual(positions[3]); }); it("does not split a simple polygon with one edge on the equator, starting below the equator", function() { const positions = import__289.Cartesian3.unpackArray([ -3180138, -5441382, -974441, -3186540, -5525048, 0, -2198716, -5986569, 0, -2135113, -5925878, -996868 ]); const polygons = import__289.PolygonGeometryLibrary.splitPolygonsOnEquator( [positions], import__289.Ellipsoid.WGS84, import__289.ArcType.GEODESIC ); expect(polygons.length).toBe(1); expect(polygons[0].length).toBe(4); expect(polygons[0][0]).toEqual(positions[0]); expect(polygons[0][1]).toEqual(positions[1]); expect(polygons[0][2]).toEqual(positions[2]); expect(polygons[0][3]).toEqual(positions[3]); }); it("splits a positively concave polygon at the equator", function() { const positions = import__289.Cartesian3.unpackArray([ -3723536687096985e-9, -5140643423654287e-9, 622159.6094790212, -3.7064439124709764e6, -5089398802336418e-9, -1016836564118223e-9, -1.8183463577937474e6, -5988204417556031e-9, -1.2269920906221648e6, -1.9497282308330906e6, -6022778780648997e-9, 775419.1678640501, -2891108934831509e-9, -5659936656854747e-9, -534148.7427656263 ]); const polygons = import__289.PolygonGeometryLibrary.splitPolygonsOnEquator( [positions], import__289.Ellipsoid.WGS84, import__289.ArcType.GEODESIC ); const expectedIntersection1 = new import__289.Cartesian3( -3.7465237934060274e6, -5161801144582336e-9, 0 ); const expectedIntersection2 = new import__289.Cartesian3( -3.2989928935172106e6, -5.4586882562839165e6, 0 ); const expectedIntersection3 = new import__289.Cartesian3( -2527814313071595e-9, -5855833534980258e-9, 0 ); const expectedIntersection4 = new import__289.Cartesian3( -1921714863778476e-9, -6081746753450187e-9, 0 ); expect(polygons.length).toBe(3); expect(polygons[0].length).toBe(3); expect(polygons[0][0]).toEqual(positions[0]); expect(polygons[0][1]).toEqualEpsilon( expectedIntersection1, import__289.Math.EPSILON7 ); expect(polygons[0][2]).toEqualEpsilon( expectedIntersection2, import__289.Math.EPSILON7 ); expect(polygons[1].length).toBe(7); expect(polygons[1][0]).toEqualEpsilon( expectedIntersection1, import__289.Math.EPSILON7 ); expect(polygons[1][1]).toEqual(positions[1]); expect(polygons[1][2]).toEqual(positions[2]); expect(polygons[1][3]).toEqualEpsilon( expectedIntersection4, import__289.Math.EPSILON7 ); expect(polygons[1][4]).toEqualEpsilon( expectedIntersection3, import__289.Math.EPSILON7 ); expect(polygons[1][5]).toEqual(positions[4]); expect(polygons[1][6]).toEqualEpsilon( expectedIntersection2, import__289.Math.EPSILON7 ); expect(polygons[2].length).toBe(3); expect(polygons[2][0]).toEqualEpsilon( expectedIntersection4, import__289.Math.EPSILON7 ); expect(polygons[2][1]).toEqual(positions[3]); expect(polygons[2][2]).toEqualEpsilon( expectedIntersection3, import__289.Math.EPSILON7 ); }); it("splits a negatively concave polygon at the equator", function() { const positions = import__289.Cartesian3.unpackArray([ -4.1640727435535816e6, -4.7915715503237555e6, 605958.8290040599, -4.1675077232260685e6, -480049702674794e-8, -508272.2109012767, -3.7121726000501625e6, -5184159589216706e-9, 116723.13202563708, -3.2596460020361557e6, -5455158378873343e-9, -532227.4715966922, -3.2837173855494126e6, -5434359545068984e-9, 592819.1229613343 ]); const polygons = import__289.PolygonGeometryLibrary.splitPolygonsOnEquator( [positions], import__289.Ellipsoid.WGS84, import__289.ArcType.GEODESIC ); const expectedIntersection1 = new import__289.Cartesian3( -4.1824163757553473e6, -4815394568525253e-9, 0 ); const expectedIntersection2 = new import__289.Cartesian3( -3.8030151382151386e6, -5120322982906009e-9, 0 ); const expectedIntersection3 = new import__289.Cartesian3( -3.6359132183307745e6, -5240302153458e-6, 0 ); const expectedIntersection4 = new import__289.Cartesian3( -3.2843605276909056e6, -5467504688147503e-9, 0 ); expect(polygons.length).toBe(3); expect(polygons[0].length).toBe(7); expect(polygons[0][0]).toEqual(positions[0]); expect(polygons[0][1]).toEqualEpsilon( expectedIntersection1, import__289.Math.EPSILON7 ); expect(polygons[0][2]).toEqualEpsilon( expectedIntersection2, import__289.Math.EPSILON7 ); expect(polygons[0][3]).toEqual(positions[2]); expect(polygons[0][4]).toEqualEpsilon( expectedIntersection3, import__289.Math.EPSILON7 ); expect(polygons[0][5]).toEqualEpsilon( expectedIntersection4, import__289.Math.EPSILON7 ); expect(polygons[0][6]).toEqual(positions[4]); expect(polygons[1].length).toBe(3); expect(polygons[1][0]).toEqualEpsilon( expectedIntersection1, import__289.Math.EPSILON7 ); expect(polygons[1][1]).toEqual(positions[1]); expect(polygons[1][2]).toEqualEpsilon( expectedIntersection2, import__289.Math.EPSILON7 ); expect(polygons[2].length).toBe(3); expect(polygons[2][0]).toEqualEpsilon( expectedIntersection3, import__289.Math.EPSILON7 ); expect(polygons[2][1]).toEqual(positions[3]); expect(polygons[2][2]).toEqualEpsilon( expectedIntersection4, import__289.Math.EPSILON7 ); }); it("splits a positively concave polygon with a point on the equator", function() { const positions = import__289.Cartesian3.unpackArray([ -3592289, -5251493, 433532, -3568746, -5245699, -646544, -2273628, -5915229, -715098, -2410175, -5885323, 475855, -3012338, -5621469, 0 ]); const polygons = import__289.PolygonGeometryLibrary.splitPolygonsOnEquator( [positions], import__289.Ellipsoid.WGS84, import__289.ArcType.GEODESIC ); const expectedIntersection1 = new import__289.Cartesian3( -3.5956843882232937e6, -5.2679868423389485e6, 0 ); const expectedIntersection2 = new import__289.Cartesian3( -2.3659296862513637e6, -5923091111107741e-9, 0 ); expect(polygons.length).toBe(3); expect(polygons[0].length).toBe(3); expect(polygons[0][0]).toEqual(positions[0]); expect(polygons[0][1]).toEqualEpsilon( expectedIntersection1, import__289.Math.EPSILON7 ); expect(polygons[0][2]).toEqual(positions[4]); expect(polygons[1].length).toBe(5); expect(polygons[1][0]).toEqualEpsilon( expectedIntersection1, import__289.Math.EPSILON7 ); expect(polygons[1][1]).toEqual(positions[1]); expect(polygons[1][2]).toEqual(positions[2]); expect(polygons[1][3]).toEqualEpsilon( expectedIntersection2, import__289.Math.EPSILON7 ); expect(polygons[1][4]).toEqual(positions[4]); expect(polygons[2].length).toBe(3); expect(polygons[2][0]).toEqualEpsilon( expectedIntersection2, import__289.Math.EPSILON7 ); expect(polygons[2][1]).toEqual(positions[3]); expect(polygons[2][2]).toEqual(positions[4]); }); it("splits a negatively concave polygon with a point on the equator", function() { const positions = import__289.Cartesian3.unpackArray([ -3774632, -5136123, 222459, -3714187, -5173580, -341046, -3516544, -5320967, 0, -3304860, -5444086, -342567, -3277484, -5466977, 218213 ]); const polygons = import__289.PolygonGeometryLibrary.splitPolygonsOnEquator( [positions], import__289.Ellipsoid.WGS84, import__289.ArcType.GEODESIC ); const expectedIntersection1 = new import__289.Cartesian3( -3754485468265927e-9, -5156013039098039e-9, 0 ); const expectedIntersection2 = new import__289.Cartesian3( -3291304258941832e-9, -5463327545172482e-9, 0 ); expect(polygons.length).toBe(3); expect(polygons[0].length).toBe(5); expect(polygons[0][0]).toEqual(positions[0]); expect(polygons[0][1]).toEqualEpsilon( expectedIntersection1, import__289.Math.EPSILON7 ); expect(polygons[0][2]).toEqual(positions[2]); expect(polygons[0][3]).toEqualEpsilon( expectedIntersection2, import__289.Math.EPSILON7 ); expect(polygons[0][4]).toEqual(positions[4]); expect(polygons[1].length).toBe(3); expect(polygons[1][0]).toEqualEpsilon( expectedIntersection1, import__289.Math.EPSILON7 ); expect(polygons[1][1]).toEqual(positions[1]); expect(polygons[1][2]).toEqual(positions[2]); expect(polygons[2].length).toBe(3); expect(polygons[2][0]).toEqual(positions[2]); expect(polygons[2][1]).toEqual(positions[3]); expect(polygons[2][2]).toEqualEpsilon( expectedIntersection2, import__289.Math.EPSILON7 ); }); it("splits a polygon with an edge equator", function() { const positions = import__289.Cartesian3.unpackArray([ -3227931, -5469496, 584508, -3150093, -5488360, -792747, -1700622, -6089685, -835364, -1786389, -6122714, 0, -2593600, -5826977, 0, -2609132, -5790155, 584508 ]); const polygons = import__289.PolygonGeometryLibrary.splitPolygonsOnEquator( [positions], import__289.Ellipsoid.WGS84, import__289.ArcType.GEODESIC ); const expectedIntersection = new import__289.Cartesian3( -3213523577073882e-9, -5509437159126084e-9, 0 ); expect(polygons.length).toBe(2); expect(polygons[0].length).toBe(4); expect(polygons[0][0]).toEqual(positions[0]); expect(polygons[0][1]).toEqualEpsilon( expectedIntersection, import__289.Math.EPSILON7 ); expect(polygons[0][2]).toEqual(positions[4]); expect(polygons[0][3]).toEqual(positions[5]); expect(polygons[1].length).toBe(5); expect(polygons[1][0]).toEqualEpsilon( expectedIntersection, import__289.Math.EPSILON7 ); expect(polygons[1][1]).toEqual(positions[1]); expect(polygons[1][2]).toEqual(positions[2]); expect(polygons[1][3]).toEqual(positions[3]); expect(polygons[1][4]).toEqual(positions[4]); }); it("splits a polygon with a backtracking edge on the equator", function() { const positions = import__289.Cartesian3.unpackArray([ -3491307, -5296123, 650596, -3495031, -5334507, 0, -4333607, -4677312, 0, -4275491, -4629182, -968553, -2403691, -5827997, -943662, -2484409, -5837281, 631344 ]); const polygons = import__289.PolygonGeometryLibrary.splitPolygonsOnEquator( [positions], import__289.Ellipsoid.WGS84, import__289.ArcType.GEODESIC ); const expectedIntersection = new import__289.Cartesian3( -2.4714993842933537e6, -587982332933623e-8, 0 ); expect(polygons.length).toBe(2); expect(polygons[0].length).toBe(4); expect(polygons[0][0]).toEqual(positions[0]); expect(polygons[0][1]).toEqual(positions[1]); expect(polygons[0][2]).toEqualEpsilon( expectedIntersection, import__289.Math.EPSILON7 ); expect(polygons[0][3]).toEqual(positions[5]); expect(polygons[1].length).toBe(5); expect(polygons[1][0]).toEqual(positions[1]); expect(polygons[1][1]).toEqual(positions[2]); expect(polygons[1][2]).toEqual(positions[3]); expect(polygons[1][3]).toEqual(positions[4]); expect(polygons[1][4]).toEqualEpsilon( expectedIntersection, import__289.Math.EPSILON7 ); }); it("splits a simple rhumb polygon at the equator", function() { const positions = import__289.Cartesian3.unpackArray([ 3813220, -5085291, 527179, 3701301, -5097773, -993503, 5037375, -3776794, -1017021, 5049166, -3865306, 494270 ]); const polygons = import__289.PolygonGeometryLibrary.splitPolygonsOnEquator( [positions], import__289.Ellipsoid.WGS84, import__289.ArcType.RHUMB ); const expectedIntersection1 = new import__289.Cartesian3( 3799205595277112e-9, -5123150245267465e-9, 0 ); const expectedIntersection2 = new import__289.Cartesian3( 5077127456540122e-9, -3.8604932820580625e6, 0 ); expect(polygons.length).toBe(2); expect(polygons[0].length).toBe(4); expect(polygons[0][0]).toEqual(positions[0]); expect(polygons[0][1]).toEqualEpsilon( expectedIntersection1, import__289.Math.EPSILON7 ); expect(polygons[0][2]).toEqualEpsilon( expectedIntersection2, import__289.Math.EPSILON7 ); expect(polygons[0][3]).toEqual(positions[3]); expect(polygons[1].length).toBe(4); expect(polygons[1][0]).toEqualEpsilon( expectedIntersection1, import__289.Math.EPSILON7 ); expect(polygons[1][1]).toEqual(positions[1]); expect(polygons[1][2]).toEqual(positions[2]); expect(polygons[1][3]).toEqualEpsilon( expectedIntersection2, import__289.Math.EPSILON7 ); }); it("splits a simple rhumb polygon at the equator across the IDL", function() { const positions = import__289.Cartesian3.fromDegreesArray([ 30, -30, 20, 30, -20, 30, -30, -30 ]); const polygons = import__289.PolygonGeometryLibrary.splitPolygonsOnEquator( [positions], import__289.Ellipsoid.WGS84, import__289.ArcType.RHUMB ); const expectedIntersection1 = new import__289.Cartesian3( 5780555229886577e-9, 2.6955171720840395e6, 0 ); const expectedIntersection2 = new import__289.Cartesian3( 5780555229886577e-9, -2.6955171720840395e6, 0 ); expect(polygons.length).toBe(2); expect(polygons[0].length).toBe(4); expect(polygons[0][0]).toEqual(positions[0]); expect(polygons[0][1]).toEqualEpsilon( expectedIntersection1, import__289.Math.EPSILON7 ); expect(polygons[0][2]).toEqualEpsilon( expectedIntersection2, import__289.Math.EPSILON7 ); expect(polygons[0][3]).toEqual(positions[3]); expect(polygons[1].length).toBe(4); expect(polygons[1][0]).toEqualEpsilon( expectedIntersection1, import__289.Math.EPSILON7 ); expect(polygons[1][1]).toEqual(positions[1]); expect(polygons[1][2]).toEqual(positions[2]); expect(polygons[1][3]).toEqualEpsilon( expectedIntersection2, import__289.Math.EPSILON7 ); }); it("splits an array of polygons", function() { const positions = import__289.Cartesian3.unpackArray([ 3813220, -5085291, 527179, 3701301, -5097773, -993503, 5037375, -3776794, -1017021, 5049166, -3865306, 494270 ]); const polygons = import__289.PolygonGeometryLibrary.splitPolygonsOnEquator( [positions, positions], import__289.Ellipsoid.WGS84, import__289.ArcType.GEODESIC ); expect(polygons.length).toBe(4); }); }); }); // packages/engine/Specs/Core/PolygonGeometrySpec.js var import__290 = __toESM(require_Cesium(), 1); var import__291 = __toESM(require_Cesium(), 1); describe("Core/PolygonGeometry", function() { it("throws without hierarchy", function() { expect(function() { return new import__290.PolygonGeometry(); }).toThrowDeveloperError(); }); it("throws with height when perPositionHeight is true", function() { expect(function() { return new import__290.PolygonGeometry({ height: 30, perPositionHeight: true }); }).toThrowDeveloperError(); }); it("throws without positions", function() { expect(function() { return import__290.PolygonGeometry.fromPositions(); }).toThrowDeveloperError(); }); it("returns undefined with less than three positions", function() { expect( import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ positions: [new import__290.Cartesian3()] }) ) ).toBeUndefined(); }); it("returns undefined with polygon hierarchy with less than three positions", function() { expect( import__290.PolygonGeometry.createGeometry( new import__290.PolygonGeometry({ polygonHierarchy: { positions: [import__290.Cartesian3.fromDegrees(0, 0)] } }) ) ).toBeUndefined(); }); it("throws if arcType is not valid", function() { expect(function() { return new import__290.PolygonGeometry({ positions: [ import__290.Cartesian3.fromDegrees(0, 0), import__290.Cartesian3.fromDegrees(1, 0), import__290.Cartesian3.fromDegrees(1, 1) ], arcType: import__290.ArcType.NONE }); }).toThrowDeveloperError(); }); it("createGeometry returns undefined due to duplicate positions", function() { const geometry = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ positions: import__290.Cartesian3.fromDegreesArray([0, 0, 0, 0, 0, 0]) }) ); expect(geometry).toBeUndefined(); }); it("createGeometry returns undefined due to duplicate positions extruded", function() { const geometry = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ positions: import__290.Cartesian3.fromDegreesArray([0, 0, 0, 0, 0, 0]), extrudedHeight: 2 }) ); expect(geometry).toBeUndefined(); }); it("createGeometry returns undefined due to duplicate hierarchy positions", function() { const hierarchy2 = { positions: import__290.Cartesian3.fromDegreesArray([1, 1, 1, 1, 1, 1]), holes: [ { positions: import__290.Cartesian3.fromDegreesArray([ 0, 0, 0, 0, 0, 0 ]) } ] }; const geometry = import__290.PolygonGeometry.createGeometry( new import__290.PolygonGeometry({ polygonHierarchy: hierarchy2 }) ); expect(geometry).toBeUndefined(); }); it("createGeometry returns undefined due to duplicate hierarchy positions with different heights", function() { const hierarchy2 = { positions: import__290.Cartesian3.fromDegreesArrayHeights([ 1, 1, 10, 1, 1, 20, 1, 1, 30 ]), holes: [ { positions: import__290.Cartesian3.fromDegreesArrayHeights([ 0, 0, 10, 0, 0, 20, 0, 0, 30 ]) } ] }; const geometry = import__290.PolygonGeometry.createGeometry( new import__290.PolygonGeometry({ polygonHierarchy: hierarchy2 }) ); expect(geometry).toBeUndefined(); }); it("createGeometry returns geometry if duplicate hierarchy positions with different heights and perPositionHeight is true", function() { const hierarchy2 = { positions: import__290.Cartesian3.fromDegreesArrayHeights([ 1, 1, 10, 1, 1, 20, 1, 1, 30 ]), holes: [ { positions: import__290.Cartesian3.fromDegreesArrayHeights([ 0, 0, 10, 0, 0, 20, 0, 0, 30 ]) } ] }; const geometry = import__290.PolygonGeometry.createGeometry( new import__290.PolygonGeometry({ polygonHierarchy: hierarchy2, perPositionHeight: true }) ); expect(geometry).toBeDefined(); }); it("computes positions", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), granularity: import__291.Math.RADIANS_PER_DEGREE }) ); expect(p.attributes.position.values.length).toEqual(13 * 3); expect(p.indices.length).toEqual(16 * 3); }); it("computes positions with per position heights", function() { const ellipsoid = import__290.Ellipsoid.WGS84; const height = 100; const positions2 = import__290.Cartesian3.fromDegreesArrayHeights([ -1, -1, height, 1, -1, 0, 1, 1, 0, -1, 1, 0 ]); const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ positions: positions2, perPositionHeight: true }) ); expect( ellipsoid.cartesianToCartographic( import__290.Cartesian3.fromArray(p.attributes.position.values, 0) ).height ).toEqualEpsilon(height, import__291.Math.EPSILON6); expect( ellipsoid.cartesianToCartographic( import__290.Cartesian3.fromArray(p.attributes.position.values, 3) ).height ).toEqualEpsilon(0, import__291.Math.EPSILON6); }); it("create geometry creates with rhumb lines", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), granularity: import__291.Math.RADIANS_PER_DEGREE, arcType: import__290.ArcType.RHUMB }) ); expect(p.attributes.position.values.length).toEqual(15 * 3); expect(p.indices.length).toEqual(20 * 3); }); it("create geometry throws if arcType is STRAIGHT", function() { expect(function() { import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), granularity: import__291.Math.RADIANS_PER_DEGREE, arcType: import__290.ArcType.NONE }) ); }).toThrowDeveloperError(); }); it("create geometry creates with lines with different number of subdivisions for geodesic and rhumb", function() { const positions2 = import__290.Cartesian3.fromDegreesArray([ -30, -30, 30, -30, 30, 30, -30, 30 ]); const geodesic = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: positions2, granularity: import__291.Math.RADIANS_PER_DEGREE, arcType: import__290.ArcType.GEODESIC }) ); const rhumb = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: positions2, granularity: import__291.Math.RADIANS_PER_DEGREE, arcType: import__290.ArcType.RHUMB }) ); expect(geodesic.attributes.position.values.length).not.toEqual( rhumb.attributes.position.values.length ); expect(geodesic.indices.length).not.toEqual(rhumb.indices.length); }); it("computes positions with per position heights for rhumb lines", function() { const ellipsoid = import__290.Ellipsoid.WGS84; const height = 100; const positions2 = import__290.Cartesian3.fromDegreesArrayHeights([ -1, -1, height, 1, -1, 0, 1, 1, 0, -1, 1, 0 ]); const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ positions: positions2, perPositionHeight: true, arcType: import__290.ArcType.RHUMB }) ); expect( ellipsoid.cartesianToCartographic( import__290.Cartesian3.fromArray(p.attributes.position.values, 0) ).height ).toEqualEpsilon(height, import__291.Math.EPSILON6); expect( ellipsoid.cartesianToCartographic( import__290.Cartesian3.fromArray(p.attributes.position.values, 3) ).height ).toEqualEpsilon(0, import__291.Math.EPSILON6); }); it("computes all attributes", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.ALL, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]) }) ); const numVertices = 13; const numTriangles = 16; expect(p.attributes.position.values.length).toEqual(numVertices * 3); expect(p.attributes.st.values.length).toEqual(numVertices * 2); expect(p.attributes.normal.values.length).toEqual(numVertices * 3); expect(p.attributes.tangent.values.length).toEqual(numVertices * 3); expect(p.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(p.indices.length).toEqual(numTriangles * 3); }); it("creates a polygon from hierarchy", function() { const hierarchy2 = { positions: import__290.Cartesian3.fromDegreesArray([ -124, 35, -110, 35, -110, 40, -124, 40 ]), holes: [ { positions: import__290.Cartesian3.fromDegreesArray([ -122, 36, -122, 39, -112, 39, -112, 36 ]), holes: [ { positions: import__290.Cartesian3.fromDegreesArray([ -120, 36.5, -114, 36.5, -114, 38.5, -120, 38.5 ]) } ] } ] }; const p = import__290.PolygonGeometry.createGeometry( new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, polygonHierarchy: hierarchy2, granularity: import__291.Math.PI_OVER_THREE }) ); expect(p.attributes.position.values.length).toEqual(12 * 3); expect(p.indices.length).toEqual(10 * 3); }); it("creates a polygon from hierarchy with rhumb lines", function() { const hierarchy2 = { positions: import__290.Cartesian3.fromDegreesArray([ -124, 35, -110, 35, -110, 40, -124, 40 ]), holes: [ { positions: import__290.Cartesian3.fromDegreesArray([ -122, 36, -122, 39, -112, 39, -112, 36 ]), holes: [ { positions: import__290.Cartesian3.fromDegreesArray([ -120, 36.5, -114, 36.5, -114, 38.5, -120, 38.5 ]) } ] } ] }; const p = import__290.PolygonGeometry.createGeometry( new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, polygonHierarchy: hierarchy2, granularity: import__291.Math.PI_OVER_THREE, arcType: import__290.ArcType.RHUMB }) ); expect(p.attributes.position.values.length).toEqual(12 * 3); expect(p.indices.length).toEqual(10 * 3); }); it("removes duplicates in polygon hierarchy", function() { const hierarchy2 = { positions: import__290.Cartesian3.fromDegreesArray([ -124, 35, -110, 35, -110, 35, -110, 40, -124, 40 ]), holes: [ { positions: import__290.Cartesian3.fromDegreesArray([ -122, 36, -122, 39, -122, 39, -112, 39, -112, 36 ]), holes: [ { positions: import__290.Cartesian3.fromDegreesArray([ -120, 36.5, -114, 36.5, -114, 36.5, -114, 38.5, -120, 38.5 ]) } ] } ] }; const p = import__290.PolygonGeometry.createGeometry( new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, polygonHierarchy: hierarchy2, granularity: import__291.Math.PI_OVER_THREE }) ); expect(p.attributes.position.values.length).toEqual(12 * 3); expect(p.indices.length).toEqual(10 * 3); }); it("creates a polygon from clockwise hierarchy", function() { const hierarchy2 = { positions: import__290.Cartesian3.fromDegreesArray([ -124, 35, -124, 40, -110, 40, -110, 35 ]), holes: [ { positions: import__290.Cartesian3.fromDegreesArray([ -122, 36, -112, 36, -112, 39, -122, 39 ]), holes: [ { positions: import__290.Cartesian3.fromDegreesArray([ -120, 36.5, -120, 38.5, -114, 38.5, -114, 36.5 ]) } ] } ] }; const p = import__290.PolygonGeometry.createGeometry( new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, polygonHierarchy: hierarchy2, granularity: import__291.Math.PI_OVER_THREE }) ); expect(p.attributes.position.values.length).toEqual(12 * 3); expect(p.indices.length).toEqual(10 * 3); }); it("doesn't reverse clockwise input array", function() { const p = import__290.Cartesian3.fromDegreesArray([ -124, 35, -124, 40, -110, 40, -110, 35 ]); const h1 = import__290.Cartesian3.fromDegreesArray([ -122, 36, -112, 36, -112, 39, -122, 39 ]); const h2 = import__290.Cartesian3.fromDegreesArray([ -120, 36.5, -120, 38.5, -114, 38.5, -114, 36.5 ]); const hierarchy2 = { positions: p, holes: [ { positions: h1, holes: [ { positions: h2 } ] } ] }; import__290.PolygonGeometry.createGeometry( new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, polygonHierarchy: hierarchy2, granularity: import__291.Math.PI_OVER_THREE }) ); let i; const pExpected = import__290.Cartesian3.fromDegreesArray([ -124, 35, -124, 40, -110, 40, -110, 35 ]); for (i = 0; i < p.length; i++) { expect(p[i]).toEqualEpsilon(pExpected[i], import__291.Math.EPSILON7); } const h1Expected = import__290.Cartesian3.fromDegreesArray([ -122, 36, -112, 36, -112, 39, -122, 39 ]); for (i = 0; i < h1.length; i++) { expect(h1[i]).toEqualEpsilon(h1Expected[i], import__291.Math.EPSILON7); } const h2Expected = import__290.Cartesian3.fromDegreesArray([ -120, 36.5, -120, 38.5, -114, 38.5, -114, 36.5 ]); for (i = 0; i < h2.length; i++) { expect(h2[i]).toEqualEpsilon(h2Expected[i], import__291.Math.EPSILON7); } }); it("computes correct bounding sphere at height 0", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.ALL, positions: import__290.Cartesian3.fromDegreesArray([ -108, 1, -108, -1, -106, -1, -106, 1 ]), granularity: import__291.Math.PI_OVER_THREE }) ); const bs = import__290.BoundingSphere.fromVertices(p.attributes.position.values); expect(p.boundingSphere.center).toEqualEpsilon( bs.center, import__291.Math.EPSILON9 ); expect(p.boundingSphere.radius).toEqualEpsilon( bs.radius, import__291.Math.EPSILON9 ); }); it("computes correct bounding sphere at height >>> 0", function() { const height = 4e7; const positions2 = import__290.Cartesian3.fromDegreesArray([ -108, 1, -108, -1, -106, -1, -106, 1 ]); const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITIONS_ONLY, positions: positions2, height }) ); const bs = import__290.BoundingSphere.fromPoints( import__290.Cartesian3.fromDegreesArrayHeights([ -108, 1, height, -108, -1, height, -106, -1, height, -106, 1, height ]) ); expect(Math.abs(p.boundingSphere.radius - bs.radius)).toBeLessThan(100); }); it("computes positions extruded", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), extrudedHeight: 3e4 }) ); const numVertices = 50; const numTriangles = 48; expect(p.attributes.position.values.length).toEqual(numVertices * 3); expect(p.indices.length).toEqual(numTriangles * 3); }); it("computes positions extruded and not closeTop", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), extrudedHeight: 3e4, closeTop: false }) ); const numVertices = 37; const numTriangles = 32; expect(p.attributes.position.values.length).toEqual(numVertices * 3); expect(p.indices.length).toEqual(numTriangles * 3); }); it("computes positions extruded and not closeBottom", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), extrudedHeight: 3e4, closeBottom: false }) ); const numVertices = 37; const numTriangles = 32; expect(p.attributes.position.values.length).toEqual(numVertices * 3); expect(p.indices.length).toEqual(numTriangles * 3); }); it("computes positions extruded and not closeBottom or closeTop", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), extrudedHeight: 3e4, closeTop: false, closeBottom: false }) ); const numVertices = 24; const numTriangles = 16; expect(p.attributes.position.values.length).toEqual(numVertices * 3); expect(p.indices.length).toEqual(numTriangles * 3); }); it("computes offset attribute", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), granularity: import__291.Math.RADIANS_PER_DEGREE, offsetAttribute: import__290.GeometryOffsetAttribute.TOP }) ); const numVertices = 13; expect(p.attributes.position.values.length).toEqual(numVertices * 3); const offset = p.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("computes offset attribute extruded for top vertices", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), extrudedHeight: 3e4, offsetAttribute: import__290.GeometryOffsetAttribute.TOP }) ); const numVertices = 50; expect(p.attributes.position.values.length).toEqual(numVertices * 3); const offset = p.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(0).fill(1, 0, 13).fill(1, 26, 38); expect(offset).toEqual(expected); }); it("computes offset attribute extruded and not closeTop for top vertices", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), extrudedHeight: 3e4, closeTop: false, offsetAttribute: import__290.GeometryOffsetAttribute.TOP }) ); const numVertices = 37; expect(p.attributes.position.values.length).toEqual(numVertices * 3); const offset = p.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(0).fill(1, 13, 25); expect(offset).toEqual(expected); }); it("computes offset attribute extruded and not closeBottom for top vertcies", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), extrudedHeight: 3e4, closeBottom: false, offsetAttribute: import__290.GeometryOffsetAttribute.TOP }) ); const numVertices = 37; expect(p.attributes.position.values.length).toEqual(numVertices * 3); const offset = p.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(0).fill(1, 0, 25); expect(offset).toEqual(expected); }); it("computes offset attribute extruded and not closeBottom or closeTop for top vertices", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), extrudedHeight: 3e4, closeTop: false, closeBottom: false, offsetAttribute: import__290.GeometryOffsetAttribute.TOP }) ); const numVertices = 24; expect(p.attributes.position.values.length).toEqual(numVertices * 3); const offset = p.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(0).fill(1, 0, 12); expect(offset).toEqual(expected); }); it("computes offset attribute extruded for all vertices", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), extrudedHeight: 3e4, offsetAttribute: import__290.GeometryOffsetAttribute.ALL }) ); const numVertices = 50; expect(p.attributes.position.values.length).toEqual(numVertices * 3); const offset = p.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("computes offset attribute extruded and not closeTop for all vertices", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), extrudedHeight: 3e4, closeTop: false, offsetAttribute: import__290.GeometryOffsetAttribute.ALL }) ); const numVertices = 37; expect(p.attributes.position.values.length).toEqual(numVertices * 3); const offset = p.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("computes offset attribute extruded and not closeBottom for all vertcies", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), extrudedHeight: 3e4, closeBottom: false, offsetAttribute: import__290.GeometryOffsetAttribute.ALL }) ); const numVertices = 37; expect(p.attributes.position.values.length).toEqual(numVertices * 3); const offset = p.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("computes offset attribute extruded and not closeBottom or closeTop for all vertices", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), extrudedHeight: 3e4, closeTop: false, closeBottom: false, offsetAttribute: import__290.GeometryOffsetAttribute.ALL }) ); const numVertices = 24; expect(p.attributes.position.values.length).toEqual(numVertices * 3); const offset = p.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("removes duplicates extruded", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1, -1, -1 ]), extrudedHeight: 3e4 }) ); expect(p.attributes.position.values.length).toEqual(50 * 3); expect(p.indices.length).toEqual(48 * 3); }); it("Ignores extrudedHeight if it equals height.", function() { const p = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), height: 0, extrudedHeight: import__291.Math.EPSILON7 }) ); expect(p.attributes.position.values.length).toEqual(13 * 3); expect(p.indices.length).toEqual(16 * 3); }); it("computes all attributes extruded", function() { const p = import__290.PolygonGeometry.createGeometry( new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.ALL, polygonHierarchy: { positions: import__290.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]) }, extrudedHeight: 3e4 }) ); const numVertices = 50; const numTriangles = 48; expect(p.attributes.position.values.length).toEqual(numVertices * 3); expect(p.attributes.st.values.length).toEqual(numVertices * 2); expect(p.attributes.normal.values.length).toEqual(numVertices * 3); expect(p.attributes.tangent.values.length).toEqual(numVertices * 3); expect(p.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(p.indices.length).toEqual(numTriangles * 3); }); it("computes correct texture coordinates for polygon with height", function() { const p = import__290.PolygonGeometry.createGeometry( new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_AND_ST, polygonHierarchy: { positions: import__290.Cartesian3.fromDegreesArray([ -100.5, 30, -100, 30, -100, 30.5, -100.5, 30.5 ]) }, height: 15e4, granularity: import__291.Math.PI }) ); const st = p.attributes.st.values; for (let i = 0; i < st.length; i++) { expect(st[i]).toBeGreaterThanOrEqual(0); expect(st[i]).toBeLessThanOrEqual(1); } }); it("computes correct texture coordinates for polygon with position heights", function() { const p = import__290.PolygonGeometry.createGeometry( new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_AND_ST, polygonHierarchy: { positions: import__290.Cartesian3.fromDegreesArrayHeights([ -100.5, 30, 92, -100, 30, 92, -100, 30.5, 92, -100.5, 30.5, 92 ]) }, granularity: import__291.Math.PI }) ); const st = p.attributes.st.values; for (let i = 0; i < st.length; i++) { expect(st[i]).toBeGreaterThanOrEqual(0); expect(st[i]).toBeLessThanOrEqual(1); } }); it("uses explicit texture coordinates if defined in options", function() { const textureCoordinates2 = { positions: [ new import__290.Cartesian2(0, 0), new import__290.Cartesian2(1, 0), new import__290.Cartesian2(1, 1), new import__290.Cartesian2(0, 1) ] }; const p = import__290.PolygonGeometry.createGeometry( new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_AND_ST, polygonHierarchy: { positions: import__290.Cartesian3.fromDegreesArray([ -100.5, 30, -100, 30, -100, 30.5, -100.5, 30.5 ]) }, textureCoordinates: textureCoordinates2, height: 15e4, granularity: import__291.Math.PI }) ); const st = p.attributes.st.values; for (let i = 0; i < textureCoordinates2.positions.length; i++) { expect(st[i * 2 + 0]).toEqual(textureCoordinates2.positions[i].x); expect(st[i * 2 + 1]).toEqual(textureCoordinates2.positions[i].y); } }); it("creates a polygon from hierarchy extruded", function() { const hierarchy2 = { positions: import__290.Cartesian3.fromDegreesArray([ -124, 35, -110, 35, -110, 40, -124, 40 ]), holes: [ { positions: import__290.Cartesian3.fromDegreesArray([ -122, 36, -122, 39, -112, 39, -112, 36 ]), holes: [ { positions: import__290.Cartesian3.fromDegreesArray([ -120, 36.5, -114, 36.5, -114, 38.5, -120, 38.5 ]) } ] } ] }; const p = import__290.PolygonGeometry.createGeometry( new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, polygonHierarchy: hierarchy2, granularity: import__291.Math.PI_OVER_THREE, extrudedHeight: 3e4 }) ); expect(p.attributes.position.values.length).toEqual(72 * 3); expect(p.indices.length).toEqual(44 * 3); }); it("undefined is returned if there are less than 3 positions", function() { const polygon2 = import__290.PolygonGeometry.fromPositions({ positions: import__290.Cartesian3.fromDegreesArray([-72, 40, -68, 40]) }); const geometry = import__290.PolygonGeometry.createGeometry(polygon2); expect(geometry).toBeUndefined(); }); it("computes normals for perPositionHeight", function() { let geometry = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ positions: [ new import__290.Cartesian3( 1333485211963876e-9, -4654510505548239e-9, 4.1385575850382405e6 ), new import__290.Cartesian3( 1.3334413994441305e6, -4654261147368878e-9, 4138322784348336e-9 ), new import__290.Cartesian3( 1.3335219333286814e6, -4654490298890729e-9, 4138567564118971e-9 ) ], extrudedHeight: 56, vertexFormat: import__290.VertexFormat.POSITION_AND_NORMAL, perPositionHeight: true, closeBottom: false }) ); const normals = geometry.attributes.normal.values; geometry = import__290.GeometryPipeline.computeNormal(geometry); const expectedNormals = geometry.attributes.normal.values; let notEqualCount = 0; for (let i = 0; i < expectedNormals.length; i++) { if (!import__291.Math.equalsEpsilon( normals[i], expectedNormals[i], import__291.Math.EPSILON6 )) { notEqualCount++; } } expect(notEqualCount).toEqual(6); }); it("computes geometry with position only vertex format with perPositionHeight and extrudedHeight", function() { const positions2 = import__290.Cartesian3.fromDegreesArrayHeights([ -1, -1, 100, 1, -1, 0, 1, 1, 100, -1, 1, 0 ]); const geometry = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ positions: positions2, extrudedHeight: 0, vertexFormat: import__290.VertexFormat.POSITION_ONLY, perPositionHeight: true }) ); expect(geometry).toBeDefined(); expect(geometry.attributes.position).toBeDefined(); expect(geometry.attributes.normal).toBeUndefined(); }); it("does not include indices for extruded walls that are too small", function() { const positions2 = import__290.Cartesian3.fromDegreesArray([ 7.757161063097392, 48.568676799636634, 7.753968290229146, 48.57179646709908, 7.755340073906587, 48.57194885406795, 7.756263393414589, 48.57194795160971, 7.756894446412183, 48.56939670304399 ]); const pRhumb = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: positions2, extrudedHeight: 1e3, closeTop: false, closeBottom: false, arcType: import__290.ArcType.RHUMB }) ); let numVertices = 20; let numTriangles = 10; expect(pRhumb.attributes.position.values.length).toEqual(numVertices * 3); expect(pRhumb.indices.length).toEqual(numTriangles * 3); const pGeodesic = import__290.PolygonGeometry.createGeometry( import__290.PolygonGeometry.fromPositions({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, positions: positions2, extrudedHeight: 1e3, closeTop: false, closeBottom: false, arcType: import__290.ArcType.GEODESIC }) ); numVertices = 20; numTriangles = 10; expect(pGeodesic.attributes.position.values.length).toEqual( numVertices * 3 ); expect(pGeodesic.indices.length).toEqual(numTriangles * 3); }); it("computing rectangle property", function() { const p = new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_AND_ST, polygonHierarchy: { positions: import__290.Cartesian3.fromDegreesArrayHeights([ -100.5, 30, 92, -100, 30, 92, -100, 30.5, 92, -100.5, 30.5, 92 ]) }, granularity: import__291.Math.PI }); const r = p.rectangle; expect(import__291.Math.toDegrees(r.north)).toBeGreaterThan(30.5); expect(import__291.Math.toDegrees(r.north)).toBeLessThan(30.5999); expect(import__291.Math.toDegrees(r.south)).toEqualEpsilon( 30, import__291.Math.EPSILON5 ); expect(import__291.Math.toDegrees(r.east)).toEqualEpsilon( -100, import__291.Math.EPSILON13 ); expect(import__291.Math.toDegrees(r.west)).toEqualEpsilon( -100.5, import__291.Math.EPSILON13 ); }); it("computes rectangle according to arctype", function() { const pGeodesic = new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_AND_ST, polygonHierarchy: { positions: import__290.Cartesian3.fromDegreesArrayHeights([ -90, 30, 0, -80, 30, 0, -80, 40, 0, -90, 40, 0 ]) }, granularity: import__291.Math.RADIANS_PER_DEGREE, arcType: import__290.ArcType.GEODESIC }); const boundingGeodesic = pGeodesic.rectangle; expect(import__291.Math.toDegrees(boundingGeodesic.north)).toBeGreaterThan(40); expect(import__291.Math.toDegrees(boundingGeodesic.south)).toEqualEpsilon( 30, import__291.Math.EPSILON10 ); expect(import__291.Math.toDegrees(boundingGeodesic.east)).toEqualEpsilon( -80, import__291.Math.EPSILON10 ); expect(import__291.Math.toDegrees(boundingGeodesic.west)).toEqualEpsilon( -90, import__291.Math.EPSILON10 ); const pRhumb = new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_AND_ST, polygonHierarchy: { positions: import__290.Cartesian3.fromDegreesArrayHeights([ -90, 30, 0, -80, 30, 0, -80, 40, 0, -90, 40, 0 ]) }, granularity: import__291.Math.RADIANS_PER_DEGREE, arcType: import__290.ArcType.RHUMB }); const boundingRhumb = pRhumb.rectangle; expect(import__291.Math.toDegrees(boundingRhumb.north)).toEqualEpsilon( 40, import__291.Math.EPSILON10 ); expect(import__291.Math.toDegrees(boundingRhumb.south)).toEqualEpsilon( 30, import__291.Math.EPSILON10 ); expect(import__291.Math.toDegrees(boundingRhumb.east)).toEqualEpsilon( -80, import__291.Math.EPSILON10 ); expect(import__291.Math.toDegrees(boundingRhumb.west)).toEqualEpsilon( -90, import__291.Math.EPSILON10 ); }); it("computes rectangles for rhumbline polygons that cross the IDL", function() { const pRhumb = new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_AND_ST, polygonHierarchy: { positions: import__290.Cartesian3.fromDegreesArray([ 175, 30, -170, 30, -170, 40, 175, 40 ]) }, granularity: import__291.Math.RADIANS_PER_DEGREE, arcType: import__290.ArcType.RHUMB }); const boundingRhumb = pRhumb.rectangle; expect(import__291.Math.toDegrees(boundingRhumb.north)).toEqualEpsilon( 40, import__291.Math.EPSILON10 ); expect(import__291.Math.toDegrees(boundingRhumb.south)).toEqualEpsilon( 30, import__291.Math.EPSILON10 ); expect(import__291.Math.toDegrees(boundingRhumb.east)).toEqualEpsilon( -170, import__291.Math.EPSILON10 ); expect(import__291.Math.toDegrees(boundingRhumb.west)).toEqualEpsilon( 175, import__291.Math.EPSILON10 ); }); it("computes rectangles for geodesic polygons that cross the IDL", function() { const minLon = import__290.Cartographic.fromDegrees(-178, 3); const minLat = import__290.Cartographic.fromDegrees(-179, -4); const maxLon = import__290.Cartographic.fromDegrees(178, 3); const maxLat = import__290.Cartographic.fromDegrees(179, 4); const cartesianArray = import__290.Ellipsoid.WGS84.cartographicArrayToCartesianArray([ minLat, minLon, maxLat, maxLon ]); const pGeodesic = new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_AND_ST, polygonHierarchy: { positions: cartesianArray }, granularity: import__291.Math.RADIANS_PER_DEGREE, arcType: import__290.ArcType.GEODESIC }); const boundingGeodesic = pGeodesic.rectangle; expect(boundingGeodesic.east).toEqualEpsilon( minLon.longitude, import__291.Math.EPSILON10 ); expect(boundingGeodesic.south).toEqualEpsilon( minLat.latitude, import__291.Math.EPSILON10 ); expect(boundingGeodesic.west).toEqualEpsilon( maxLon.longitude, import__291.Math.EPSILON10 ); expect(boundingGeodesic.north).toEqualEpsilon( maxLat.latitude, import__291.Math.EPSILON10 ); }); describe("computeRectangleFromPositions", function() { it("computeRectangle with result parameter", function() { const positions2 = import__290.Cartesian3.fromDegreesArray([30, 30, 60, 60, 30, 60]); const result = new import__290.Rectangle(); const returned = import__290.PolygonGeometry.computeRectangleFromPositions( positions2, import__290.Ellipsoid.WGS84, import__290.ArcType.GEODESIC, result ); expect(returned).toBe(result); }); it("computes a rectangle enclosing a simple geodesic polygon in the northern hemisphere", function() { const positions2 = import__290.Cartesian3.fromDegreesArray([30, 30, 60, 60, 30, 60]); const result = import__290.PolygonGeometry.computeRectangleFromPositions( positions2, import__290.Ellipsoid.WGS84 ); expect(result).toBeInstanceOf(import__290.Rectangle); expect(result.west).toEqualEpsilon( import__291.Math.toRadians(30), import__291.Math.EPSILON7 ); expect(result.south).toEqualEpsilon( import__291.Math.toRadians(30), import__291.Math.EPSILON7 ); expect(result.east).toEqualEpsilon( import__291.Math.toRadians(60), import__291.Math.EPSILON7 ); expect(result.north).toBeGreaterThan(import__291.Math.toRadians(60)); expect(result.north).toBeLessThan(import__291.Math.toRadians(70)); }); it("computes a rectangle enclosing a simple rhumb polygon in the northern hemisphere", function() { const positions2 = import__290.Cartesian3.fromDegreesArray([30, 30, 60, 60, 30, 60]); const result = import__290.PolygonGeometry.computeRectangleFromPositions( positions2, import__290.Ellipsoid.WGS84, import__290.ArcType.RHUMB ); expect(result).toBeInstanceOf(import__290.Rectangle); expect(result.west).toEqualEpsilon( import__291.Math.toRadians(30), import__291.Math.EPSILON7 ); expect(result.south).toEqualEpsilon( import__291.Math.toRadians(30), import__291.Math.EPSILON7 ); expect(result.east).toEqualEpsilon( import__291.Math.toRadians(60), import__291.Math.EPSILON7 ); expect(result.north).toEqualEpsilon( import__291.Math.toRadians(60), import__291.Math.EPSILON7 ); }); it("computes a rectangle enclosing a simple geodesic polygon in the southern hemisphere", function() { const positions2 = import__290.Cartesian3.fromDegreesArray([ -30, -30, -60, -60, -30, -60 ]); const result = import__290.PolygonGeometry.computeRectangleFromPositions( positions2, import__290.Ellipsoid.WGS84 ); expect(result).toBeInstanceOf(import__290.Rectangle); expect(result.west).toEqualEpsilon( import__291.Math.toRadians(-60), import__291.Math.EPSILON7 ); expect(result.south).toBeLessThan(import__291.Math.toRadians(-60)); expect(result.south).toBeGreaterThan(import__291.Math.toRadians(-70)); expect(result.east).toEqualEpsilon( import__291.Math.toRadians(-30), import__291.Math.EPSILON7 ); expect(result.north).toEqualEpsilon( import__291.Math.toRadians(-30), import__291.Math.EPSILON7 ); }); it("computes a rectangle enclosing a simple rhumb polygon in the southern hemisphere", function() { const positions2 = import__290.Cartesian3.fromDegreesArray([ -30, -30, -60, -60, -30, -60 ]); const result = import__290.PolygonGeometry.computeRectangleFromPositions( positions2, import__290.Ellipsoid.WGS84, import__290.ArcType.RHUMB ); expect(result).toBeInstanceOf(import__290.Rectangle); expect(result.west).toEqualEpsilon( import__291.Math.toRadians(-60), import__291.Math.EPSILON7 ); expect(result.south).toEqualEpsilon( import__291.Math.toRadians(-60), import__291.Math.EPSILON7 ); expect(result.east).toEqualEpsilon( import__291.Math.toRadians(-30), import__291.Math.EPSILON7 ); expect(result.north).toEqualEpsilon( import__291.Math.toRadians(-30), import__291.Math.EPSILON7 ); }); it("computes a rectangle enclosing a simple polygon across the IDL", function() { const positions2 = import__290.Cartesian3.fromDegreesArray([ 170, 60, 170, 30, -170, 30 ]); const result = import__290.PolygonGeometry.computeRectangleFromPositions( positions2, import__290.Ellipsoid.WGS84 ); expect(result).toBeInstanceOf(import__290.Rectangle); expect(result.west).toEqualEpsilon( import__291.Math.toRadians(170), import__291.Math.EPSILON7 ); expect(result.south).toEqualEpsilon( import__291.Math.toRadians(30), import__291.Math.EPSILON7 ); expect(result.east).toEqualEpsilon( import__291.Math.toRadians(-170), import__291.Math.EPSILON7 ); expect(result.north).toEqualEpsilon( import__291.Math.toRadians(60), import__291.Math.EPSILON7 ); }); it("computes a rectangle enclosing a simple polygon across the equator", function() { const positions2 = import__290.Cartesian3.fromDegreesArray([ 30, 30, -30, 30, -30, -30, 30, -30 ]); const result = import__290.PolygonGeometry.computeRectangleFromPositions( positions2, import__290.Ellipsoid.WGS84, import__290.ArcType.RHUMB ); expect(result).toBeInstanceOf(import__290.Rectangle); expect(result.west).toEqualEpsilon( import__291.Math.toRadians(-30), import__291.Math.EPSILON7 ); expect(result.south).toEqualEpsilon( import__291.Math.toRadians(-30), import__291.Math.EPSILON7 ); expect(result.east).toEqualEpsilon( import__291.Math.toRadians(30), import__291.Math.EPSILON7 ); expect(result.north).toEqualEpsilon( import__291.Math.toRadians(30), import__291.Math.EPSILON7 ); }); it("computes a rectangle enclosing a simple convex polygon around the north pole", function() { const positions2 = import__290.Cartesian3.fromDegreesArray([ 45, 60, -45, 60, -135, 60, 140, 60 ]); const result = import__290.PolygonGeometry.computeRectangleFromPositions( positions2, import__290.Ellipsoid.WGS84 ); expect(result).toBeInstanceOf(import__290.Rectangle); expect(result.west).toEqualEpsilon( import__291.Math.toRadians(-180), import__291.Math.EPSILON7 ); expect(result.south).toEqualEpsilon( import__291.Math.toRadians(60), import__291.Math.EPSILON7 ); expect(result.east).toEqualEpsilon( import__291.Math.toRadians(180), import__291.Math.EPSILON7 ); expect(result.north).toEqualEpsilon( import__291.Math.toRadians(90), import__291.Math.EPSILON7 ); }); it("computes a rectangle enclosing a simple concave polygon around the north pole", function() { const positions2 = import__290.Cartesian3.fromDegreesArray([ 45, 60, -45, 60, -135, 60, -45, 80 ]); const result = import__290.PolygonGeometry.computeRectangleFromPositions( positions2, import__290.Ellipsoid.WGS84 ); expect(result).toBeInstanceOf(import__290.Rectangle); expect(result.west).toEqualEpsilon( import__291.Math.toRadians(-135), import__291.Math.EPSILON7 ); expect(result.south).toEqualEpsilon( import__291.Math.toRadians(60), import__291.Math.EPSILON7 ); expect(result.east).toEqualEpsilon( import__291.Math.toRadians(45), import__291.Math.EPSILON7 ); expect(result.north).toEqualEpsilon(1.40485733, import__291.Math.EPSILON7); }); it("computes a rectangle enclosing a simple clockwise convex polygon around the north pole", function() { const positions2 = import__290.Cartesian3.fromDegreesArray([ 140, 60, -135, 60, -45, 60, 45, 60 ]); const result = import__290.PolygonGeometry.computeRectangleFromPositions( positions2, import__290.Ellipsoid.WGS84 ); expect(result).toBeInstanceOf(import__290.Rectangle); expect(result.west).toEqualEpsilon( import__291.Math.toRadians(-180), import__291.Math.EPSILON7 ); expect(result.south).toEqualEpsilon( import__291.Math.toRadians(60), import__291.Math.EPSILON7 ); expect(result.east).toEqualEpsilon( import__291.Math.toRadians(180), import__291.Math.EPSILON7 ); expect(result.north).toEqualEpsilon( import__291.Math.toRadians(90), import__291.Math.EPSILON7 ); }); it("computes a rectangle enclosing a simple convex polygon around the south pole", function() { const positions2 = import__290.Cartesian3.fromDegreesArray([ 140, -60, -135, -60, -45, -60, 45, -60 ]); const result = import__290.PolygonGeometry.computeRectangleFromPositions( positions2, import__290.Ellipsoid.WGS84 ); expect(result).toBeInstanceOf(import__290.Rectangle); expect(result.west).toEqualEpsilon( import__291.Math.toRadians(-180), import__291.Math.EPSILON7 ); expect(result.south).toEqualEpsilon( import__291.Math.toRadians(-90), import__291.Math.EPSILON7 ); expect(result.east).toEqualEpsilon( import__291.Math.toRadians(180), import__291.Math.EPSILON7 ); expect(result.north).toEqualEpsilon( import__291.Math.toRadians(-60), import__291.Math.EPSILON7 ); }); it("computes a rectangle enclosing a simple concave rhumb polygon around the south pole", function() { const positions2 = import__290.Cartesian3.fromDegreesArray([ 45, -60, -45, -60, -135, -60, -45, -80 ]); const result = import__290.PolygonGeometry.computeRectangleFromPositions( positions2, import__290.Ellipsoid.WGS84, import__290.ArcType.RHUMB ); expect(result).toBeInstanceOf(import__290.Rectangle); expect(result.west).toEqualEpsilon( import__291.Math.toRadians(-135), import__291.Math.EPSILON7 ); expect(result.south).toEqualEpsilon( import__291.Math.toRadians(-80), import__291.Math.EPSILON7 ); expect(result.east).toEqualEpsilon( import__291.Math.toRadians(45), import__291.Math.EPSILON7 ); expect(result.north).toEqualEpsilon( import__291.Math.toRadians(-60), import__291.Math.EPSILON7 ); }); it("computes a rectangle enclosing a simple concave geodesic polygon around the south pole", function() { const positions2 = import__290.Cartesian3.fromDegreesArray([ 45, -60, -45, -60, -135, -60, -45, -80 ]); const result = import__290.PolygonGeometry.computeRectangleFromPositions( positions2, import__290.Ellipsoid.WGS84 ); expect(result).toBeInstanceOf(import__290.Rectangle); expect(result.west).toEqualEpsilon( import__291.Math.toRadians(-135), import__291.Math.EPSILON7 ); expect(result.south).toBeLessThan(import__291.Math.toRadians(-80)); expect(result.south).toBeGreaterThan(import__291.Math.toRadians(-90)); expect(result.east).toEqualEpsilon( import__291.Math.toRadians(45), import__291.Math.EPSILON7 ); expect(result.north).toEqualEpsilon( import__291.Math.toRadians(-60), import__291.Math.EPSILON7 ); }); it("computes a rectangle enclosing a simple clockwise convex polygon around the south pole", function() { const positions2 = import__290.Cartesian3.fromDegreesArray([ 45, -60, -45, -60, -135, -60, 140, -60 ]); const result = import__290.PolygonGeometry.computeRectangleFromPositions( positions2, import__290.Ellipsoid.WGS84 ); expect(result).toBeInstanceOf(import__290.Rectangle); expect(result.west).toEqualEpsilon( import__291.Math.toRadians(-180), import__291.Math.EPSILON7 ); expect(result.south).toEqualEpsilon( import__291.Math.toRadians(-90), import__291.Math.EPSILON7 ); expect(result.east).toEqualEpsilon( import__291.Math.toRadians(180), import__291.Math.EPSILON7 ); expect(result.north).toEqualEpsilon( import__291.Math.toRadians(-60), import__291.Math.EPSILON7 ); }); }); it("computing textureCoordinateRotationPoints property", function() { let p = new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_AND_ST, polygonHierarchy: { positions: import__290.Cartesian3.fromDegreesArrayHeights([ -10, -10, 0, -10, 10, 0, 10, -10, 0, 10, 10, 0 ]) }, granularity: import__291.Math.PI, stRotation: import__291.Math.toRadians(90), arcType: import__290.ArcType.RHUMB }); let textureCoordinateRotationPoints = p.textureCoordinateRotationPoints; expect(textureCoordinateRotationPoints.length).toEqual(6); expect(textureCoordinateRotationPoints[0]).toEqualEpsilon( 0, import__291.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[1]).toEqualEpsilon( 1, import__291.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[2]).toEqualEpsilon( 1, import__291.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[3]).toEqualEpsilon( 1, import__291.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[4]).toEqualEpsilon( 0, import__291.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[5]).toEqualEpsilon( 0, import__291.Math.EPSILON7 ); p = new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_AND_ST, polygonHierarchy: { positions: import__290.Cartesian3.fromDegreesArrayHeights([ -10, -10, 0, -10, 10, 0, 10, -10, 0, 10, 10, 0 ]) }, granularity: import__291.Math.PI, stRotation: import__291.Math.toRadians(0) }); textureCoordinateRotationPoints = p.textureCoordinateRotationPoints; expect(textureCoordinateRotationPoints.length).toEqual(6); expect(textureCoordinateRotationPoints[0]).toEqualEpsilon( 0, import__291.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[1]).toEqualEpsilon( 0, import__291.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[2]).toEqualEpsilon( 0, import__291.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[3]).toEqualEpsilon( 1, import__291.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[4]).toEqualEpsilon( 1, import__291.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[5]).toEqualEpsilon( 0, import__291.Math.EPSILON7 ); }); const positions = import__290.Cartesian3.fromDegreesArray([ -12.4, 3.5, -12, 3.5, -12, 4 ]); const holePositions0 = import__290.Cartesian3.fromDegreesArray([ -12.2, 3.5, -12.2, 3.6, -12.3, 3.6 ]); const holePositions1 = import__290.Cartesian3.fromDegreesArray([ -12.2, 3.5, -12.25, 3.5, -12.25, 3.55 ]); const hierarchy = { positions, holes: [ { positions: holePositions0, holes: [ { positions: holePositions1, holes: void 0 } ] } ] }; const polygon = new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, polygonHierarchy: hierarchy, granularity: import__291.Math.PI_OVER_THREE, perPositionHeight: true, closeTop: false, closeBottom: true }); function addPositions(array, positions2) { for (let i = 0; i < positions2.length; ++i) { array.push(positions2[i].x, positions2[i].y, positions2[i].z); } } function addPositions2D(array, positions2) { for (let i = 0; i < positions2.length; ++i) { array.push(positions2[i].x, positions2[i].y); } } const packedInstance = [3, 1]; addPositions(packedInstance, positions); packedInstance.push(3, 1); addPositions(packedInstance, holePositions0); packedInstance.push(3, 0); addPositions(packedInstance, holePositions1); packedInstance.push( import__290.Ellipsoid.WGS84.radii.x, import__290.Ellipsoid.WGS84.radii.y, import__290.Ellipsoid.WGS84.radii.z ); packedInstance.push(1, 0, 0, 0, 0, 0); packedInstance.push( 0, 0, import__291.Math.PI_OVER_THREE, 0, 0, 1, 0, 1, 0, -1, import__290.ArcType.GEODESIC, -1, 55 ); createPackableSpecs_default(import__290.PolygonGeometry, polygon, packedInstance); const textureCoordinates = { positions: [ new import__290.Cartesian2(0, 0), new import__290.Cartesian2(1, 0), new import__290.Cartesian2(0, 1), new import__290.Cartesian2(0.1, 0.1), new import__290.Cartesian2(0.5, 0.1), new import__290.Cartesian2(0.1, 0.5), new import__290.Cartesian2(0.2, 0.2), new import__290.Cartesian2(0.3, 0.2), new import__290.Cartesian2(0.2, 0.3) ], holes: void 0 }; const polygonTextured = new import__290.PolygonGeometry({ vertexFormat: import__290.VertexFormat.POSITION_ONLY, polygonHierarchy: hierarchy, textureCoordinates, granularity: import__291.Math.PI_OVER_THREE, perPositionHeight: true, closeTop: false, closeBottom: true }); const packedInstanceTextured = [3, 1]; addPositions(packedInstanceTextured, positions); packedInstanceTextured.push(3, 1); addPositions(packedInstanceTextured, holePositions0); packedInstanceTextured.push(3, 0); addPositions(packedInstanceTextured, holePositions1); packedInstanceTextured.push( import__290.Ellipsoid.WGS84.radii.x, import__290.Ellipsoid.WGS84.radii.y, import__290.Ellipsoid.WGS84.radii.z ); packedInstanceTextured.push(1, 0, 0, 0, 0, 0); packedInstanceTextured.push( 0, 0, import__291.Math.PI_OVER_THREE, 0, 0, 1, 0, 1, 0, -1, import__290.ArcType.GEODESIC ); packedInstanceTextured.push(9, 0); addPositions2D(packedInstanceTextured, textureCoordinates.positions); packedInstanceTextured.push(74); createPackableSpecs_default(import__290.PolygonGeometry, polygonTextured, packedInstanceTextured); }); // packages/engine/Specs/Core/PolygonOutlineGeometrySpec.js var import__292 = __toESM(require_Cesium(), 1); var import__293 = __toESM(require_Cesium(), 1); describe("Core/PolygonOutlineGeometry", function() { it("throws without hierarchy", function() { expect(function() { return new import__292.PolygonOutlineGeometry(); }).toThrowDeveloperError(); }); it("throws with height when perPositionHeight is true", function() { expect(function() { return new import__292.PolygonOutlineGeometry({ height: 30, perPositionHeight: true }); }).toThrowDeveloperError(); }); it("throws without positions", function() { expect(function() { return import__292.PolygonOutlineGeometry.fromPositions(); }).toThrowDeveloperError(); }); it("returns undefined with less than three positions", function() { expect( import__292.PolygonOutlineGeometry.createGeometry( import__292.PolygonOutlineGeometry.fromPositions({ positions: [new import__292.Cartesian3()] }) ) ).toBeUndefined(); }); it("returns undefined with polygon hierarchy with less than three positions", function() { expect( import__292.PolygonOutlineGeometry.createGeometry( new import__292.PolygonOutlineGeometry({ polygonHierarchy: { positions: [import__292.Cartesian3.fromDegrees(0, 0)] } }) ) ).toBeUndefined(); }); it("throws if arcType is not valid", function() { expect(function() { return new import__292.PolygonOutlineGeometry({ positions: [ import__292.Cartesian3.fromDegrees(0, 0), import__292.Cartesian3.fromDegrees(1, 0), import__292.Cartesian3.fromDegrees(1, 1) ], arcType: import__292.ArcType.NONE }); }).toThrowDeveloperError(); }); it("createGeometry returns undefined due to duplicate positions", function() { const geometry = import__292.PolygonOutlineGeometry.createGeometry( import__292.PolygonOutlineGeometry.fromPositions({ positions: import__292.Cartesian3.fromDegreesArray([0, 0, 0, 0, 0, 0]) }) ); expect(geometry).toBeUndefined(); }); it("createGeometry returns undefined due to duplicate positions extruded", function() { const geometry = import__292.PolygonOutlineGeometry.createGeometry( import__292.PolygonOutlineGeometry.fromPositions({ positions: import__292.Cartesian3.fromDegreesArray([0, 0, 0, 0, 0, 0]), extrudedHeight: 2 }) ); expect(geometry).toBeUndefined(); }); it("createGeometry returns undefined due to duplicate hierarchy positions", function() { const hierarchy2 = { positions: import__292.Cartesian3.fromDegreesArray([1, 1, 1, 1, 1, 1]), holes: [ { positions: import__292.Cartesian3.fromDegreesArray([ 0, 0, 0, 0, 0, 0 ]) } ] }; const geometry = import__292.PolygonOutlineGeometry.createGeometry( new import__292.PolygonOutlineGeometry({ polygonHierarchy: hierarchy2 }) ); expect(geometry).toBeUndefined(); }); it("createGeometry returns undefined due to duplicate hierarchy positions with different heights", function() { const hierarchy2 = { positions: import__292.Cartesian3.fromDegreesArrayHeights([ 1, 1, 10, 1, 1, 20, 1, 1, 30 ]), holes: [ { positions: import__292.Cartesian3.fromDegreesArrayHeights([ 0, 0, 10, 0, 0, 20, 0, 0, 30 ]) } ] }; const geometry = import__292.PolygonOutlineGeometry.createGeometry( new import__292.PolygonOutlineGeometry({ polygonHierarchy: hierarchy2 }) ); expect(geometry).toBeUndefined(); }); it("createGeometry returns geometry if duplicate hierarchy positions with different heights and perPositionHeight is true", function() { const hierarchy2 = { positions: import__292.Cartesian3.fromDegreesArrayHeights([ 1, 1, 10, 1, 1, 20, 1, 1, 30 ]), holes: [ { positions: import__292.Cartesian3.fromDegreesArrayHeights([ 0, 0, 10, 0, 0, 20, 0, 0, 30 ]) } ] }; const geometry = import__292.PolygonOutlineGeometry.createGeometry( new import__292.PolygonOutlineGeometry({ polygonHierarchy: hierarchy2, perPositionHeight: true }) ); expect(geometry).toBeDefined(); }); it("computes positions", function() { const p = import__292.PolygonOutlineGeometry.createGeometry( import__292.PolygonOutlineGeometry.fromPositions({ positions: import__292.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]) }) ); expect(p.attributes.position.values.length).toEqual(8 * 3); expect(p.indices.length).toEqual(8 * 2); }); it("computes positions with per position heights", function() { const ellipsoid = import__292.Ellipsoid.WGS84; const height = 100; const positions2 = import__292.Cartesian3.fromDegreesArrayHeights([ -1, -1, height, 1, -1, 0, 1, 1, 0, -1, 1, 0 ]); const p = import__292.PolygonOutlineGeometry.createGeometry( import__292.PolygonOutlineGeometry.fromPositions({ positions: positions2, perPositionHeight: true }) ); expect( ellipsoid.cartesianToCartographic( import__292.Cartesian3.fromArray(p.attributes.position.values, 0) ).height ).toEqualEpsilon(height, import__293.Math.EPSILON6); expect( ellipsoid.cartesianToCartographic( import__292.Cartesian3.fromArray(p.attributes.position.values, 3) ).height ).toEqualEpsilon(0, import__293.Math.EPSILON6); }); it("create geometry creates with rhumb lines", function() { const p = import__292.PolygonOutlineGeometry.createGeometry( import__292.PolygonOutlineGeometry.fromPositions({ positions: import__292.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), granularity: import__293.Math.RADIANS_PER_DEGREE, arcType: import__292.ArcType.RHUMB }) ); expect(p.attributes.position.values.length).toEqual(8 * 3); expect(p.indices.length).toEqual(16); }); it("create geometry throws if arcType is STRAIGHT", function() { expect(function() { import__292.PolygonOutlineGeometry.createGeometry( import__292.PolygonOutlineGeometry.fromPositions({ positions: import__292.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), granularity: import__293.Math.RADIANS_PER_DEGREE, arcType: import__292.ArcType.NONE }) ); }).toThrowDeveloperError(); }); it("create geometry creates with lines with different number of subdivisions for geodesic and rhumb", function() { const positions2 = import__292.Cartesian3.fromDegreesArray([ -80, 75, 80, 75, 80, 45, -80, 45 ]); const geodesic = import__292.PolygonOutlineGeometry.createGeometry( import__292.PolygonOutlineGeometry.fromPositions({ positions: positions2, granularity: import__293.Math.RADIANS_PER_DEGREE, arcType: import__292.ArcType.GEODESIC }) ); const rhumb = import__292.PolygonOutlineGeometry.createGeometry( import__292.PolygonOutlineGeometry.fromPositions({ positions: positions2, granularity: import__293.Math.RADIANS_PER_DEGREE, arcType: import__292.ArcType.RHUMB }) ); expect(geodesic.attributes.position.values.length).not.toEqual( rhumb.attributes.position.values.length ); expect(geodesic.indices.length).not.toEqual(rhumb.indices.length); }); it("computes positions with per position heights for rhumb lines", function() { const ellipsoid = import__292.Ellipsoid.WGS84; const height = 100; const positions2 = import__292.Cartesian3.fromDegreesArrayHeights([ -1, -1, height, 1, -1, 0, 1, 1, 0, -1, 1, 0 ]); const p = import__292.PolygonOutlineGeometry.createGeometry( import__292.PolygonOutlineGeometry.fromPositions({ positions: positions2, perPositionHeight: true, arcType: import__292.ArcType.RHUMB }) ); expect( ellipsoid.cartesianToCartographic( import__292.Cartesian3.fromArray(p.attributes.position.values, 0) ).height ).toEqualEpsilon(height, import__293.Math.EPSILON6); expect( ellipsoid.cartesianToCartographic( import__292.Cartesian3.fromArray(p.attributes.position.values, 3) ).height ).toEqualEpsilon(0, import__293.Math.EPSILON6); }); it("uses correct value with extrudedHeight and perPositionHeight", function() { const ellipsoid = import__292.Ellipsoid.WGS84; const maxHeight = 100; const minHeight = 60; const extrudedHeight = 50; const positions2 = import__292.Cartesian3.fromDegreesArrayHeights([ -1, -1, maxHeight, 1, -1, minHeight, 1, 1, minHeight, -1, 1, minHeight ]); const p = import__292.PolygonOutlineGeometry.createGeometry( import__292.PolygonOutlineGeometry.fromPositions({ positions: positions2, perPositionHeight: true, extrudedHeight }) ); expect( ellipsoid.cartesianToCartographic( import__292.Cartesian3.fromArray(p.attributes.position.values, 0) ).height ).toEqualEpsilon(maxHeight, import__293.Math.EPSILON6); expect( ellipsoid.cartesianToCartographic( import__292.Cartesian3.fromArray(p.attributes.position.values, 3) ).height ).toEqualEpsilon(minHeight, import__293.Math.EPSILON6); expect( ellipsoid.cartesianToCartographic( import__292.Cartesian3.fromArray(p.attributes.position.values, 24) ).height ).toEqualEpsilon(extrudedHeight, import__293.Math.EPSILON6); }); it("creates a polygon from hierarchy", function() { const hierarchy2 = { positions: import__292.Cartesian3.fromDegreesArray([ -124, 35, -110, 35, -110, 40, -124, 40 ]), holes: [ { positions: import__292.Cartesian3.fromDegreesArray([ -122, 36, -122, 39, -112, 39, -112, 36 ]), holes: [ { positions: import__292.Cartesian3.fromDegreesArray([ -120, 36.5, -114, 36.5, -114, 38.5, -120, 38.5 ]) } ] } ] }; const p = import__292.PolygonOutlineGeometry.createGeometry( new import__292.PolygonOutlineGeometry({ polygonHierarchy: hierarchy2, granularity: import__293.Math.PI_OVER_THREE }) ); expect(p.attributes.position.values.length).toEqual(12 * 3); expect(p.indices.length).toEqual(12 * 2); }); it("creates a polygon from clockwise hierarchy", function() { const hierarchy2 = { positions: import__292.Cartesian3.fromDegreesArray([ -124, 35, -124, 40, -110, 40, -110, 35 ]), holes: [ { positions: import__292.Cartesian3.fromDegreesArray([ -122, 36, -112, 36, -112, 39, -122, 39 ]), holes: [ { positions: import__292.Cartesian3.fromDegreesArray([ -120, 36.5, -120, 38.5, -114, 38.5, -114, 36.5 ]) } ] } ] }; const p = import__292.PolygonOutlineGeometry.createGeometry( new import__292.PolygonOutlineGeometry({ polygonHierarchy: hierarchy2, granularity: import__293.Math.PI_OVER_THREE }) ); expect(p.attributes.position.values.length).toEqual(12 * 3); expect(p.indices.length).toEqual(12 * 2); }); it("doesn't reverse clockwise input array", function() { const p = import__292.Cartesian3.fromDegreesArray([ -124, 35, -124, 40, -110, 40, -110, 35 ]); const h1 = import__292.Cartesian3.fromDegreesArray([ -122, 36, -112, 36, -112, 39, -122, 39 ]); const h2 = import__292.Cartesian3.fromDegreesArray([ -120, 36.5, -120, 38.5, -114, 38.5, -114, 36.5 ]); const hierarchy2 = { positions: p, holes: [ { positions: h1, holes: [ { positions: h2 } ] } ] }; import__292.PolygonOutlineGeometry.createGeometry( new import__292.PolygonOutlineGeometry({ polygonHierarchy: hierarchy2, granularity: import__293.Math.PI_OVER_THREE }) ); expect(p).toEqualEpsilon( import__292.Cartesian3.fromDegreesArray([ -124, 35, -124, 40, -110, 40, -110, 35 ]), import__293.Math.EPSILON9 ); expect(h1).toEqualEpsilon( import__292.Cartesian3.fromDegreesArray([ -122, 36, -112, 36, -112, 39, -122, 39 ]), import__293.Math.EPSILON9 ); expect(h2).toEqualEpsilon( import__292.Cartesian3.fromDegreesArray([ -120, 36.5, -120, 38.5, -114, 38.5, -114, 36.5 ]), import__293.Math.EPSILON9 ); }); it("computes correct bounding sphere at height 0", function() { const p = import__292.PolygonOutlineGeometry.createGeometry( import__292.PolygonOutlineGeometry.fromPositions({ positions: import__292.Cartesian3.fromDegreesArray([ -108, 1, -108, -1, -106, -1, -106, 1 ]), granularity: import__293.Math.PI_OVER_THREE }) ); const bs = import__292.BoundingSphere.fromVertices(p.attributes.position.values); expect(p.boundingSphere.center).toEqualEpsilon( bs.center, import__293.Math.EPSILON9 ); expect(p.boundingSphere.radius).toEqualEpsilon( bs.radius, import__293.Math.EPSILON9 ); }); it("computes correct bounding sphere at height >>> 0", function() { const height = 4e7; const positions2 = import__292.Cartesian3.fromDegreesArray([ -108, 1, -108, -1, -106, -1, -106, 1 ]); const p = import__292.PolygonOutlineGeometry.createGeometry( import__292.PolygonOutlineGeometry.fromPositions({ positions: positions2, height }) ); const bs = import__292.BoundingSphere.fromPoints( import__292.Cartesian3.fromDegreesArrayHeights([ -108, 1, height, -108, -1, height, -106, -1, height, -106, 1, height ]) ); expect(Math.abs(p.boundingSphere.radius - bs.radius)).toBeLessThan(100); }); it("computes positions extruded", function() { const p = import__292.PolygonOutlineGeometry.createGeometry( import__292.PolygonOutlineGeometry.fromPositions({ positions: import__292.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), extrudedHeight: 3e4 }) ); expect(p.attributes.position.values.length).toEqual(16 * 3); expect(p.indices.length).toEqual(20 * 2); }); it("creates a polygon from hierarchy extruded", function() { const hierarchy2 = { positions: import__292.Cartesian3.fromDegreesArray([ -124, 35, -110, 35, -110, 40, -124, 40 ]), holes: [ { positions: import__292.Cartesian3.fromDegreesArray([ -122, 36, -122, 39, -112, 39, -112, 36 ]), holes: [ { positions: import__292.Cartesian3.fromDegreesArray([ -120, 36.5, -114, 36.5, -114, 38.5, -120, 38.5 ]) } ] } ] }; const p = import__292.PolygonOutlineGeometry.createGeometry( new import__292.PolygonOutlineGeometry({ polygonHierarchy: hierarchy2, granularity: import__293.Math.PI_OVER_THREE, extrudedHeight: 3e4 }) ); expect(p.attributes.position.values.length).toEqual(24 * 3); expect(p.indices.length).toEqual(36 * 2); }); it("computes offset attribute", function() { const p = import__292.PolygonOutlineGeometry.createGeometry( import__292.PolygonOutlineGeometry.fromPositions({ positions: import__292.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), offsetAttribute: import__292.GeometryOffsetAttribute.TOP }) ); const numVertices = 8; expect(p.attributes.position.values.length).toEqual(numVertices * 3); const offset = p.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("computes offset attribute extruded for top vertices", function() { const p = import__292.PolygonOutlineGeometry.createGeometry( import__292.PolygonOutlineGeometry.fromPositions({ positions: import__292.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), extrudedHeight: 3e4, offsetAttribute: import__292.GeometryOffsetAttribute.TOP }) ); const numVertices = 16; expect(p.attributes.position.values.length).toEqual(numVertices * 3); const offset = p.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(0).fill(1, 0, 8); expect(offset).toEqual(expected); }); it("computes offset attribute extruded for all vertices", function() { const p = import__292.PolygonOutlineGeometry.createGeometry( import__292.PolygonOutlineGeometry.fromPositions({ positions: import__292.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), extrudedHeight: 3e4, offsetAttribute: import__292.GeometryOffsetAttribute.ALL }) ); const numVertices = 16; expect(p.attributes.position.values.length).toEqual(numVertices * 3); const offset = p.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("undefined is returned if there are less than 3 positions", function() { const polygonOutline = import__292.PolygonOutlineGeometry.fromPositions({ positions: import__292.Cartesian3.fromDegreesArray([-72, 40, -68, 40]) }); const geometry = import__292.PolygonOutlineGeometry.createGeometry(polygonOutline); expect(geometry).toBeUndefined(); }); const positions = import__292.Cartesian3.fromDegreesArray([ -124, 35, -110, 35, -110, 40 ]); const holePositions0 = import__292.Cartesian3.fromDegreesArray([ -122, 36, -122, 39, -112, 39 ]); const holePositions1 = import__292.Cartesian3.fromDegreesArray([ -120, 36.5, -114, 36.5, -114, 38.5 ]); const hierarchy = { positions, holes: [ { positions: holePositions0, holes: [ { positions: holePositions1, holes: void 0 } ] } ] }; const polygon = new import__292.PolygonOutlineGeometry({ polygonHierarchy: hierarchy, granularity: import__293.Math.PI_OVER_THREE, perPositionHeight: true }); function addPositions(array, positions2) { for (let i = 0; i < positions2.length; ++i) { array.push(positions2[i].x, positions2[i].y, positions2[i].z); } } const packedInstance = [3, 1]; addPositions(packedInstance, positions); packedInstance.push(3, 1); addPositions(packedInstance, holePositions0); packedInstance.push(3, 0); addPositions(packedInstance, holePositions1); packedInstance.push( import__292.Ellipsoid.WGS84.radii.x, import__292.Ellipsoid.WGS84.radii.y, import__292.Ellipsoid.WGS84.radii.z ); packedInstance.push( 0, 0, import__293.Math.PI_OVER_THREE, 0, 1, import__292.ArcType.GEODESIC, -1, 44 ); createPackableSpecs_default(import__292.PolygonOutlineGeometry, polygon, packedInstance); }); // packages/engine/Specs/Core/PolygonPipelineSpec.js var import__294 = __toESM(require_Cesium(), 1); var import__295 = __toESM(require_Cesium(), 1); describe("Core/PolygonPipeline", function() { beforeEach(function() { import__295.Math.setRandomNumberSeed(0); }); it("computeArea2D computes a positive area", function() { const area = import__294.PolygonPipeline.computeArea2D([ new import__294.Cartesian2(0, 0), new import__294.Cartesian2(2, 0), new import__294.Cartesian2(2, 1), new import__294.Cartesian2(0, 1) ]); expect(area).toEqual(2); }); it("computeArea2D computes a negative area", function() { const area = import__294.PolygonPipeline.computeArea2D([ new import__294.Cartesian2(0, 0), new import__294.Cartesian2(0, 2), new import__294.Cartesian2(1, 2), new import__294.Cartesian2(1, 0) ]); expect(area).toEqual(-2); }); it("computeArea2D throws without positions", function() { expect(function() { import__294.PolygonPipeline.computeArea2D(); }).toThrowDeveloperError(); }); it("computeArea2D throws without three positions", function() { expect(function() { import__294.PolygonPipeline.computeArea2D([import__294.Cartesian3.ZERO, import__294.Cartesian3.ZERO]); }).toThrowDeveloperError(); }); it("computeWindingOrder2D computes counter-clockwise", function() { const area = import__294.PolygonPipeline.computeWindingOrder2D([ new import__294.Cartesian2(0, 0), new import__294.Cartesian2(2, 0), new import__294.Cartesian2(2, 1), new import__294.Cartesian2(0, 1) ]); expect(area).toEqual(import__294.WindingOrder.COUNTER_CLOCKWISE); }); it("computeWindingOrder2D computes clockwise", function() { const area = import__294.PolygonPipeline.computeWindingOrder2D([ new import__294.Cartesian2(0, 0), new import__294.Cartesian2(0, 2), new import__294.Cartesian2(1, 2), new import__294.Cartesian2(1, 0) ]); expect(area).toEqual(import__294.WindingOrder.CLOCKWISE); }); it("computeWindingOrder2D throws without positions", function() { expect(function() { import__294.PolygonPipeline.computeWindingOrder2D(); }).toThrowDeveloperError(); }); it("computeWindingOrder2D throws without three positions", function() { expect(function() { import__294.PolygonPipeline.computeWindingOrder2D([import__294.Cartesian3.ZERO, import__294.Cartesian3.ZERO]); }).toThrowDeveloperError(); }); describe("triangulate", function() { it("throws without positions", function() { expect(function() { import__294.PolygonPipeline.triangulate(void 0, []); }).toThrowDeveloperError(); }); it("a triangle", function() { const positions = [ new import__294.Cartesian2(0, 0), new import__294.Cartesian2(1, 0), new import__294.Cartesian2(0, 1) ]; const indices = import__294.PolygonPipeline.triangulate(positions, []); expect(indices).toEqual([1, 2, 0]); }); it("a square", function() { const positions = [ new import__294.Cartesian2(0, 0), new import__294.Cartesian2(1, 0), new import__294.Cartesian2(1, 1), new import__294.Cartesian2(0, 1) ]; const indices = import__294.PolygonPipeline.triangulate(positions, []); expect(indices).toEqual([2, 3, 0, 0, 1, 2]); }); it("eliminates holes", function() { const positions = [ new import__294.Cartesian2(0, 0), new import__294.Cartesian2(3, 0), new import__294.Cartesian2(3, 3), new import__294.Cartesian2(0, 3) ]; const hole = [ new import__294.Cartesian2(1, 1), new import__294.Cartesian2(2, 1), new import__294.Cartesian2(2, 2), new import__294.Cartesian2(1, 2) ]; const combinedPositions = positions.concat(hole); const indices = import__294.PolygonPipeline.triangulate(combinedPositions, [4]); expect(indices).toEqual([ 0, 4, 7, 5, 4, 0, 3, 0, 7, 5, 0, 1, 2, 3, 7, 6, 5, 1, 2, 7, 6, 6, 1, 2 ]); }); it("eliminates multiple holes", function() { const positions = [ new import__294.Cartesian2(0, 0), new import__294.Cartesian2(3, 0), new import__294.Cartesian2(3, 5), new import__294.Cartesian2(0, 5) ]; const bottomHole = [ new import__294.Cartesian2(1, 1), new import__294.Cartesian2(2, 1), new import__294.Cartesian2(2, 2), new import__294.Cartesian2(1, 2) ]; const topHole = [ new import__294.Cartesian2(1, 3), new import__294.Cartesian2(2, 3), new import__294.Cartesian2(2, 4), new import__294.Cartesian2(1, 4) ]; const combinedPositions = positions.concat(bottomHole).concat(topHole); const indices = import__294.PolygonPipeline.triangulate(combinedPositions, [4, 8]); expect(indices).toEqual([ 0, 8, 11, 0, 4, 7, 5, 4, 0, 3, 0, 11, 8, 0, 7, 5, 0, 1, 2, 3, 11, 9, 8, 7, 6, 5, 1, 2, 11, 10, 9, 7, 6, 6, 1, 2, 2, 10, 9, 9, 6, 2 ]); }); }); it("computeSubdivision throws without ellipsoid", function() { expect(function() { import__294.PolygonPipeline.computeSubdivision(); }).toThrowDeveloperError(); }); it("computeSubdivision throws without positions", function() { expect(function() { import__294.PolygonPipeline.computeSubdivision(import__294.Ellipsoid.WGS84); }).toThrowDeveloperError(); }); it("computeSubdivision throws without indices", function() { expect(function() { import__294.PolygonPipeline.computeSubdivision(import__294.Ellipsoid.WGS84, []); }).toThrowDeveloperError(); }); it("computeSubdivision throws with less than 3 indices", function() { expect(function() { import__294.PolygonPipeline.computeSubdivision(import__294.Ellipsoid.WGS84, [], [1, 2]); }).toThrowDeveloperError(); }); it("computeSubdivision throws without a multiple of 3 indices", function() { expect(function() { import__294.PolygonPipeline.computeSubdivision(import__294.Ellipsoid.WGS84, [], [1, 2, 3, 4]); }).toThrowDeveloperError(); }); it("computeSubdivision throws with negative granularity", function() { expect(function() { import__294.PolygonPipeline.computeSubdivision( import__294.Ellipsoid.WGS84, [], [1, 2, 3], void 0, -1 ); }).toThrowDeveloperError(); }); it("computeSubdivision without subdivisions", function() { const positions = [ new import__294.Cartesian3(0, 0, 90), new import__294.Cartesian3(0, 90, 0), new import__294.Cartesian3(90, 0, 0) ]; const indices = [0, 1, 2]; const subdivision = import__294.PolygonPipeline.computeSubdivision( import__294.Ellipsoid.WGS84, positions, indices, void 0, 60 ); expect(subdivision.attributes.position.values[0]).toEqual(0); expect(subdivision.attributes.position.values[1]).toEqual(0); expect(subdivision.attributes.position.values[2]).toEqual(90); expect(subdivision.attributes.position.values[3]).toEqual(0); expect(subdivision.attributes.position.values[4]).toEqual(90); expect(subdivision.attributes.position.values[5]).toEqual(0); expect(subdivision.attributes.position.values[6]).toEqual(90); expect(subdivision.attributes.position.values[7]).toEqual(0); expect(subdivision.attributes.position.values[8]).toEqual(0); expect(subdivision.indices[0]).toEqual(0); expect(subdivision.indices[1]).toEqual(1); expect(subdivision.indices[2]).toEqual(2); }); it("computeSubdivision with subdivisions", function() { const positions = [ new import__294.Cartesian3(6377802759444977e-9, -58441.30561735455, 29025.647900582237), new import__294.Cartesian3( 6377802759444977e-9, -58441.30561735455, -29025.647900582237 ), new import__294.Cartesian3(6378137, 0, 0), new import__294.Cartesian3(6377802759444977e-9, 58441.30561735455, -29025.647900582237), new import__294.Cartesian3(6377802759444977e-9, 58441.30561735455, 29025.647900582237) ]; const indices = [0, 1, 2, 2, 3, 4, 4, 0, 2]; const subdivision = import__294.PolygonPipeline.computeSubdivision( import__294.Ellipsoid.WGS84, positions, indices ); expect(subdivision.attributes.position.values[0]).toEqual( 6377802759444977e-9 ); expect(subdivision.attributes.position.values[1]).toEqual( -58441.30561735455 ); expect(subdivision.attributes.position.values[2]).toEqual( 29025.647900582237 ); expect(subdivision.attributes.position.values[3]).toEqual( 6377802759444977e-9 ); expect(subdivision.attributes.position.values[4]).toEqual( -58441.30561735455 ); expect(subdivision.attributes.position.values[5]).toEqual( -29025.647900582237 ); expect(subdivision.attributes.position.values[6]).toEqual(6378137); expect(subdivision.attributes.position.values[7]).toEqual(0); expect(subdivision.attributes.position.values[8]).toEqual(0); expect(subdivision.attributes.position.values[9]).toEqual( 6377802759444977e-9 ); expect(subdivision.attributes.position.values[10]).toEqual( 58441.30561735455 ); expect(subdivision.attributes.position.values[11]).toEqual( -29025.647900582237 ); expect(subdivision.attributes.position.values[12]).toEqual( 6377802759444977e-9 ); expect(subdivision.attributes.position.values[13]).toEqual( 58441.30561735455 ); expect(subdivision.attributes.position.values[14]).toEqual( 29025.647900582237 ); expect(subdivision.attributes.position.values[15]).toEqual( 6377802759444977e-9 ); expect(subdivision.attributes.position.values[16]).toEqual(0); expect(subdivision.attributes.position.values[17]).toEqual( 29025.647900582237 ); expect(subdivision.indices[0]).toEqual(5); expect(subdivision.indices[1]).toEqual(0); expect(subdivision.indices[2]).toEqual(2); expect(subdivision.indices[3]).toEqual(4); expect(subdivision.indices[4]).toEqual(5); expect(subdivision.indices[5]).toEqual(2); expect(subdivision.indices[6]).toEqual(2); expect(subdivision.indices[7]).toEqual(3); expect(subdivision.indices[8]).toEqual(4); expect(subdivision.indices[9]).toEqual(0); expect(subdivision.indices[10]).toEqual(1); expect(subdivision.indices[11]).toEqual(2); }); it("computeSubdivision with subdivisions with texcoords", function() { const positions = [ new import__294.Cartesian3(6377802759444977e-9, -58441.30561735455, 29025.647900582237), new import__294.Cartesian3( 6377802759444977e-9, -58441.30561735455, -29025.647900582237 ), new import__294.Cartesian3(6378137, 0, 0), new import__294.Cartesian3(6377802759444977e-9, 58441.30561735455, -29025.647900582237), new import__294.Cartesian3(6377802759444977e-9, 58441.30561735455, 29025.647900582237) ]; const indices = [0, 1, 2, 2, 3, 4, 4, 0, 2]; const texcoords = [ new import__294.Cartesian2(0, 1), new import__294.Cartesian2(0, 0), new import__294.Cartesian2(0.5, 0), new import__294.Cartesian2(1, 0), new import__294.Cartesian2(1, 1) ]; const subdivision = import__294.PolygonPipeline.computeSubdivision( import__294.Ellipsoid.WGS84, positions, indices, texcoords ); expect(subdivision.attributes.position.values[0]).toEqual( 6377802759444977e-9 ); expect(subdivision.attributes.position.values[1]).toEqual( -58441.30561735455 ); expect(subdivision.attributes.position.values[2]).toEqual( 29025.647900582237 ); expect(subdivision.attributes.position.values[3]).toEqual( 6377802759444977e-9 ); expect(subdivision.attributes.position.values[4]).toEqual( -58441.30561735455 ); expect(subdivision.attributes.position.values[5]).toEqual( -29025.647900582237 ); expect(subdivision.attributes.position.values[6]).toEqual(6378137); expect(subdivision.attributes.position.values[7]).toEqual(0); expect(subdivision.attributes.position.values[8]).toEqual(0); expect(subdivision.attributes.position.values[9]).toEqual( 6377802759444977e-9 ); expect(subdivision.attributes.position.values[10]).toEqual( 58441.30561735455 ); expect(subdivision.attributes.position.values[11]).toEqual( -29025.647900582237 ); expect(subdivision.attributes.position.values[12]).toEqual( 6377802759444977e-9 ); expect(subdivision.attributes.position.values[13]).toEqual( 58441.30561735455 ); expect(subdivision.attributes.position.values[14]).toEqual( 29025.647900582237 ); expect(subdivision.attributes.position.values[15]).toEqual( 6377802759444977e-9 ); expect(subdivision.attributes.position.values[16]).toEqual(0); expect(subdivision.attributes.position.values[17]).toEqual( 29025.647900582237 ); expect(subdivision.indices[0]).toEqual(5); expect(subdivision.indices[1]).toEqual(0); expect(subdivision.indices[2]).toEqual(2); expect(subdivision.indices[3]).toEqual(4); expect(subdivision.indices[4]).toEqual(5); expect(subdivision.indices[5]).toEqual(2); expect(subdivision.indices[6]).toEqual(2); expect(subdivision.indices[7]).toEqual(3); expect(subdivision.indices[8]).toEqual(4); expect(subdivision.indices[9]).toEqual(0); expect(subdivision.indices[10]).toEqual(1); expect(subdivision.indices[11]).toEqual(2); expect(subdivision.attributes.st.values[0]).toEqual(0); expect(subdivision.attributes.st.values[1]).toEqual(1); expect(subdivision.attributes.st.values[2]).toEqual(0); expect(subdivision.attributes.st.values[3]).toEqual(0); expect(subdivision.attributes.st.values[4]).toEqual(0.5); expect(subdivision.attributes.st.values[5]).toEqual(0); expect(subdivision.attributes.st.values[6]).toEqual(1); expect(subdivision.attributes.st.values[7]).toEqual(0); expect(subdivision.attributes.st.values[8]).toEqual(1); expect(subdivision.attributes.st.values[9]).toEqual(1); expect(subdivision.attributes.st.values[10]).toEqual(0.5); expect(subdivision.attributes.st.values[11]).toEqual(1); }); it("computeRhumbLineSubdivision throws without ellipsoid", function() { expect(function() { import__294.PolygonPipeline.computeRhumbLineSubdivision(); }).toThrowDeveloperError(); }); it("computeRhumbLineSubdivision throws without positions", function() { expect(function() { import__294.PolygonPipeline.computeRhumbLineSubdivision(import__294.Ellipsoid.WGS84); }).toThrowDeveloperError(); }); it("computeRhumbLineSubdivision throws without indices", function() { expect(function() { import__294.PolygonPipeline.computeRhumbLineSubdivision(import__294.Ellipsoid.WGS84, []); }).toThrowDeveloperError(); }); it("computeRhumbLineSubdivision throws with less than 3 indices", function() { expect(function() { import__294.PolygonPipeline.computeRhumbLineSubdivision(import__294.Ellipsoid.WGS84, [], [1, 2]); }).toThrowDeveloperError(); }); it("computeRhumbLineSubdivision throws without a multiple of 3 indices", function() { expect(function() { import__294.PolygonPipeline.computeRhumbLineSubdivision( import__294.Ellipsoid.WGS84, [], [1, 2, 3, 4] ); }).toThrowDeveloperError(); }); it("computeRhumbLineSubdivision throws with negative granularity", function() { expect(function() { import__294.PolygonPipeline.computeRhumbLineSubdivision( import__294.Ellipsoid.WGS84, [], [1, 2, 3], void 0, -1 ); }).toThrowDeveloperError(); }); it("computeRhumbLineSubdivision without subdivisions", function() { const positions = import__294.Cartesian3.fromDegreesArray([0, 0, 1, 0, 1, 1]); const indices = [0, 1, 2]; const subdivision = import__294.PolygonPipeline.computeRhumbLineSubdivision( import__294.Ellipsoid.WGS84, positions, indices, void 0, 2 * import__295.Math.RADIANS_PER_DEGREE ); expect(subdivision.attributes.position.values[0]).toEqual(positions[0].x); expect(subdivision.attributes.position.values[1]).toEqual(positions[0].y); expect(subdivision.attributes.position.values[2]).toEqual(positions[0].y); expect(subdivision.attributes.position.values[3]).toEqual(positions[1].x); expect(subdivision.attributes.position.values[4]).toEqual(positions[1].y); expect(subdivision.attributes.position.values[5]).toEqual(positions[1].z); expect(subdivision.attributes.position.values[6]).toEqual(positions[2].x); expect(subdivision.attributes.position.values[7]).toEqual(positions[2].y); expect(subdivision.attributes.position.values[8]).toEqual(positions[2].z); expect(subdivision.indices[0]).toEqual(0); expect(subdivision.indices[1]).toEqual(1); expect(subdivision.indices[2]).toEqual(2); }); it("computeRhumbLineSubdivision with subdivisions", function() { const positions = import__294.Cartesian3.fromDegreesArray([0, 0, 1, 0, 1, 1]); const indices = [0, 1, 2]; const subdivision = import__294.PolygonPipeline.computeRhumbLineSubdivision( import__294.Ellipsoid.WGS84, positions, indices, void 0, 0.5 * import__295.Math.RADIANS_PER_DEGREE ); expect(subdivision.attributes.position.values.length).toEqual(36); expect(subdivision.indices.length).toEqual(36); }); it("computeRhumbLineSubdivision with subdivisions across the IDL", function() { const positions = import__294.Cartesian3.fromDegreesArray([178, 0, -178, 0, -178, 1]); const indices = [0, 1, 2]; const subdivision = import__294.PolygonPipeline.computeRhumbLineSubdivision( import__294.Ellipsoid.WGS84, positions, indices, void 0, 0.5 * import__295.Math.RADIANS_PER_DEGREE ); expect(subdivision.attributes.position.values.length).toEqual(180); expect(subdivision.indices.length).toEqual(252); }); it("computeRhumbLineSubdivision with subdivisions with texcoords", function() { const positions = [ new import__294.Cartesian3(6377802759444977e-9, -58441.30561735455, 29025.647900582237), new import__294.Cartesian3( 6377802759444977e-9, -58441.30561735455, -29025.647900582237 ), new import__294.Cartesian3(6378137, 0, 0), new import__294.Cartesian3(6377802759444977e-9, 58441.30561735455, -29025.647900582237), new import__294.Cartesian3(6377802759444977e-9, 58441.30561735455, 29025.647900582237) ]; const indices = [0, 1, 2, 2, 3, 4, 4, 0, 2]; const texcoords = [ new import__294.Cartesian2(0, 1), new import__294.Cartesian2(0, 0), new import__294.Cartesian2(0.5, 0), new import__294.Cartesian2(1, 0), new import__294.Cartesian2(1, 1) ]; const subdivision = import__294.PolygonPipeline.computeRhumbLineSubdivision( import__294.Ellipsoid.WGS84, positions, indices, texcoords ); expect(subdivision.attributes.position.values[0]).toEqual( 6377802759444977e-9 ); expect(subdivision.attributes.position.values[1]).toEqual( -58441.30561735455 ); expect(subdivision.attributes.position.values[2]).toEqual( 29025.647900582237 ); expect(subdivision.attributes.position.values[3]).toEqual( 6377802759444977e-9 ); expect(subdivision.attributes.position.values[4]).toEqual( -58441.30561735455 ); expect(subdivision.attributes.position.values[5]).toEqual( -29025.647900582237 ); expect(subdivision.attributes.position.values[6]).toEqual(6378137); expect(subdivision.attributes.position.values[7]).toEqual(0); expect(subdivision.attributes.position.values[8]).toEqual(0); expect(subdivision.attributes.position.values[9]).toEqual( 6377802759444977e-9 ); expect(subdivision.attributes.position.values[10]).toEqual( 58441.30561735455 ); expect(subdivision.attributes.position.values[11]).toEqual( -29025.647900582237 ); expect(subdivision.attributes.position.values[12]).toEqual( 6377802759444977e-9 ); expect(subdivision.attributes.position.values[13]).toEqual( 58441.30561735455 ); expect(subdivision.attributes.position.values[14]).toEqual( 29025.647900582237 ); expect(subdivision.attributes.position.values[15]).toEqual( 6378070509533917e-9 ); expect(subdivision.attributes.position.values[16]).toEqual( 11064188644323841e-27 ); expect(subdivision.attributes.position.values[17]).toEqual( 29025.64790058224 ); expect(subdivision.indices[0]).toEqual(5); expect(subdivision.indices[1]).toEqual(0); expect(subdivision.indices[2]).toEqual(2); expect(subdivision.indices[3]).toEqual(4); expect(subdivision.indices[4]).toEqual(5); expect(subdivision.indices[5]).toEqual(2); expect(subdivision.indices[6]).toEqual(2); expect(subdivision.indices[7]).toEqual(3); expect(subdivision.indices[8]).toEqual(4); expect(subdivision.indices[9]).toEqual(0); expect(subdivision.indices[10]).toEqual(1); expect(subdivision.indices[11]).toEqual(2); expect(subdivision.attributes.st.values[0]).toEqual(0); expect(subdivision.attributes.st.values[1]).toEqual(1); expect(subdivision.attributes.st.values[2]).toEqual(0); expect(subdivision.attributes.st.values[3]).toEqual(0); expect(subdivision.attributes.st.values[4]).toEqual(0.5); expect(subdivision.attributes.st.values[5]).toEqual(0); expect(subdivision.attributes.st.values[6]).toEqual(1); expect(subdivision.attributes.st.values[7]).toEqual(0); expect(subdivision.attributes.st.values[8]).toEqual(1); expect(subdivision.attributes.st.values[9]).toEqual(1); expect(subdivision.attributes.st.values[10]).toEqual(0.5); expect(subdivision.attributes.st.values[11]).toEqual(1); }); }); // packages/engine/Specs/Core/PolylineGeometrySpec.js var import__296 = __toESM(require_Cesium(), 1); var import__297 = __toESM(require_Cesium(), 1); // packages/engine/Source/Core/Math.js var import_mersenne_twister = __toESM(require_mersenne_twister(), 1); // packages/engine/Source/Core/defined.js function defined22(value) { return value !== void 0 && value !== null; } var defined_default = defined22; // packages/engine/Source/Core/DeveloperError.js function DeveloperError4(message) { this.name = "DeveloperError"; this.message = message; let stack; try { throw new Error(); } catch (e) { stack = e.stack; } this.stack = stack; } if (defined_default(Object.create)) { DeveloperError4.prototype = Object.create(Error.prototype); DeveloperError4.prototype.constructor = DeveloperError4; } DeveloperError4.prototype.toString = function() { let str = `${this.name}: ${this.message}`; if (defined_default(this.stack)) { str += ` ${this.stack.toString()}`; } return str; }; DeveloperError4.throwInstantiationError = function() { throw new DeveloperError4( "This function defines an interface and should not be called directly." ); }; var DeveloperError_default = DeveloperError4; // packages/engine/Source/Core/Check.js var Check2 = {}; Check2.typeOf = {}; function getUndefinedErrorMessage(name) { return `${name} is required, actual value was undefined`; } function getFailedTypeErrorMessage(actual, expected, name) { return `Expected ${name} to be typeof ${expected}, actual typeof was ${actual}`; } Check2.defined = function(name, test) { if (!defined_default(test)) { throw new DeveloperError_default(getUndefinedErrorMessage(name)); } }; Check2.typeOf.func = function(name, test) { if (typeof test !== "function") { throw new DeveloperError_default( getFailedTypeErrorMessage(typeof test, "function", name) ); } }; Check2.typeOf.string = function(name, test) { if (typeof test !== "string") { throw new DeveloperError_default( getFailedTypeErrorMessage(typeof test, "string", name) ); } }; Check2.typeOf.number = function(name, test) { if (typeof test !== "number") { throw new DeveloperError_default( getFailedTypeErrorMessage(typeof test, "number", name) ); } }; Check2.typeOf.number.lessThan = function(name, test, limit) { Check2.typeOf.number(name, test); if (test >= limit) { throw new DeveloperError_default( `Expected ${name} to be less than ${limit}, actual value was ${test}` ); } }; Check2.typeOf.number.lessThanOrEquals = function(name, test, limit) { Check2.typeOf.number(name, test); if (test > limit) { throw new DeveloperError_default( `Expected ${name} to be less than or equal to ${limit}, actual value was ${test}` ); } }; Check2.typeOf.number.greaterThan = function(name, test, limit) { Check2.typeOf.number(name, test); if (test <= limit) { throw new DeveloperError_default( `Expected ${name} to be greater than ${limit}, actual value was ${test}` ); } }; Check2.typeOf.number.greaterThanOrEquals = function(name, test, limit) { Check2.typeOf.number(name, test); if (test < limit) { throw new DeveloperError_default( `Expected ${name} to be greater than or equal to ${limit}, actual value was ${test}` ); } }; Check2.typeOf.object = function(name, test) { if (typeof test !== "object") { throw new DeveloperError_default( getFailedTypeErrorMessage(typeof test, "object", name) ); } }; Check2.typeOf.bool = function(name, test) { if (typeof test !== "boolean") { throw new DeveloperError_default( getFailedTypeErrorMessage(typeof test, "boolean", name) ); } }; Check2.typeOf.bigint = function(name, test) { if (typeof test !== "bigint") { throw new DeveloperError_default( getFailedTypeErrorMessage(typeof test, "bigint", name) ); } }; Check2.typeOf.number.equals = function(name1, name2, test1, test2) { Check2.typeOf.number(name1, test1); Check2.typeOf.number(name2, test2); if (test1 !== test2) { throw new DeveloperError_default( `${name1} must be equal to ${name2}, the actual values are ${test1} and ${test2}` ); } }; var Check_default = Check2; // packages/engine/Source/Core/defaultValue.js function defaultValue15(a, b) { if (a !== void 0 && a !== null) { return a; } return b; } defaultValue15.EMPTY_OBJECT = Object.freeze({}); var defaultValue_default = defaultValue15; // packages/engine/Source/Core/Math.js var CesiumMath75 = {}; CesiumMath75.EPSILON1 = 0.1; CesiumMath75.EPSILON2 = 0.01; CesiumMath75.EPSILON3 = 1e-3; CesiumMath75.EPSILON4 = 1e-4; CesiumMath75.EPSILON5 = 1e-5; CesiumMath75.EPSILON6 = 1e-6; CesiumMath75.EPSILON7 = 1e-7; CesiumMath75.EPSILON8 = 1e-8; CesiumMath75.EPSILON9 = 1e-9; CesiumMath75.EPSILON10 = 1e-10; CesiumMath75.EPSILON11 = 1e-11; CesiumMath75.EPSILON12 = 1e-12; CesiumMath75.EPSILON13 = 1e-13; CesiumMath75.EPSILON14 = 1e-14; CesiumMath75.EPSILON15 = 1e-15; CesiumMath75.EPSILON16 = 1e-16; CesiumMath75.EPSILON17 = 1e-17; CesiumMath75.EPSILON18 = 1e-18; CesiumMath75.EPSILON19 = 1e-19; CesiumMath75.EPSILON20 = 1e-20; CesiumMath75.EPSILON21 = 1e-21; CesiumMath75.GRAVITATIONALPARAMETER = 3986004418e5; CesiumMath75.SOLAR_RADIUS = 6955e5; CesiumMath75.LUNAR_RADIUS = 1737400; CesiumMath75.SIXTY_FOUR_KILOBYTES = 64 * 1024; CesiumMath75.FOUR_GIGABYTES = 4 * 1024 * 1024 * 1024; CesiumMath75.sign = defaultValue_default(Math.sign, function sign(value) { value = +value; if (value === 0 || value !== value) { return value; } return value > 0 ? 1 : -1; }); CesiumMath75.signNotZero = function(value) { return value < 0 ? -1 : 1; }; CesiumMath75.toSNorm = function(value, rangeMaximum) { rangeMaximum = defaultValue_default(rangeMaximum, 255); return Math.round( (CesiumMath75.clamp(value, -1, 1) * 0.5 + 0.5) * rangeMaximum ); }; CesiumMath75.fromSNorm = function(value, rangeMaximum) { rangeMaximum = defaultValue_default(rangeMaximum, 255); return CesiumMath75.clamp(value, 0, rangeMaximum) / rangeMaximum * 2 - 1; }; CesiumMath75.normalize = function(value, rangeMinimum, rangeMaximum) { rangeMaximum = Math.max(rangeMaximum - rangeMinimum, 0); return rangeMaximum === 0 ? 0 : CesiumMath75.clamp((value - rangeMinimum) / rangeMaximum, 0, 1); }; CesiumMath75.sinh = defaultValue_default(Math.sinh, function sinh(value) { return (Math.exp(value) - Math.exp(-value)) / 2; }); CesiumMath75.cosh = defaultValue_default(Math.cosh, function cosh(value) { return (Math.exp(value) + Math.exp(-value)) / 2; }); CesiumMath75.lerp = function(p, q, time2) { return (1 - time2) * p + time2 * q; }; CesiumMath75.PI = Math.PI; CesiumMath75.ONE_OVER_PI = 1 / Math.PI; CesiumMath75.PI_OVER_TWO = Math.PI / 2; CesiumMath75.PI_OVER_THREE = Math.PI / 3; CesiumMath75.PI_OVER_FOUR = Math.PI / 4; CesiumMath75.PI_OVER_SIX = Math.PI / 6; CesiumMath75.THREE_PI_OVER_TWO = 3 * Math.PI / 2; CesiumMath75.TWO_PI = 2 * Math.PI; CesiumMath75.ONE_OVER_TWO_PI = 1 / (2 * Math.PI); CesiumMath75.RADIANS_PER_DEGREE = Math.PI / 180; CesiumMath75.DEGREES_PER_RADIAN = 180 / Math.PI; CesiumMath75.RADIANS_PER_ARCSECOND = CesiumMath75.RADIANS_PER_DEGREE / 3600; CesiumMath75.toRadians = function(degrees) { if (!defined_default(degrees)) { throw new DeveloperError_default("degrees is required."); } return degrees * CesiumMath75.RADIANS_PER_DEGREE; }; CesiumMath75.toDegrees = function(radians) { if (!defined_default(radians)) { throw new DeveloperError_default("radians is required."); } return radians * CesiumMath75.DEGREES_PER_RADIAN; }; CesiumMath75.convertLongitudeRange = function(angle) { if (!defined_default(angle)) { throw new DeveloperError_default("angle is required."); } const twoPi = CesiumMath75.TWO_PI; const simplified = angle - Math.floor(angle / twoPi) * twoPi; if (simplified < -Math.PI) { return simplified + twoPi; } if (simplified >= Math.PI) { return simplified - twoPi; } return simplified; }; CesiumMath75.clampToLatitudeRange = function(angle) { if (!defined_default(angle)) { throw new DeveloperError_default("angle is required."); } return CesiumMath75.clamp( angle, -1 * CesiumMath75.PI_OVER_TWO, CesiumMath75.PI_OVER_TWO ); }; CesiumMath75.negativePiToPi = function(angle) { if (!defined_default(angle)) { throw new DeveloperError_default("angle is required."); } if (angle >= -CesiumMath75.PI && angle <= CesiumMath75.PI) { return angle; } return CesiumMath75.zeroToTwoPi(angle + CesiumMath75.PI) - CesiumMath75.PI; }; CesiumMath75.zeroToTwoPi = function(angle) { if (!defined_default(angle)) { throw new DeveloperError_default("angle is required."); } if (angle >= 0 && angle <= CesiumMath75.TWO_PI) { return angle; } const mod = CesiumMath75.mod(angle, CesiumMath75.TWO_PI); if (Math.abs(mod) < CesiumMath75.EPSILON14 && Math.abs(angle) > CesiumMath75.EPSILON14) { return CesiumMath75.TWO_PI; } return mod; }; CesiumMath75.mod = function(m, n) { if (!defined_default(m)) { throw new DeveloperError_default("m is required."); } if (!defined_default(n)) { throw new DeveloperError_default("n is required."); } if (n === 0) { throw new DeveloperError_default("divisor cannot be 0."); } if (CesiumMath75.sign(m) === CesiumMath75.sign(n) && Math.abs(m) < Math.abs(n)) { return m; } return (m % n + n) % n; }; CesiumMath75.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) { if (!defined_default(left)) { throw new DeveloperError_default("left is required."); } if (!defined_default(right)) { throw new DeveloperError_default("right is required."); } relativeEpsilon = defaultValue_default(relativeEpsilon, 0); absoluteEpsilon = defaultValue_default(absoluteEpsilon, relativeEpsilon); const absDiff = Math.abs(left - right); return absDiff <= absoluteEpsilon || absDiff <= relativeEpsilon * Math.max(Math.abs(left), Math.abs(right)); }; CesiumMath75.lessThan = function(left, right, absoluteEpsilon) { if (!defined_default(left)) { throw new DeveloperError_default("first is required."); } if (!defined_default(right)) { throw new DeveloperError_default("second is required."); } if (!defined_default(absoluteEpsilon)) { throw new DeveloperError_default("absoluteEpsilon is required."); } return left - right < -absoluteEpsilon; }; CesiumMath75.lessThanOrEquals = function(left, right, absoluteEpsilon) { if (!defined_default(left)) { throw new DeveloperError_default("first is required."); } if (!defined_default(right)) { throw new DeveloperError_default("second is required."); } if (!defined_default(absoluteEpsilon)) { throw new DeveloperError_default("absoluteEpsilon is required."); } return left - right < absoluteEpsilon; }; CesiumMath75.greaterThan = function(left, right, absoluteEpsilon) { if (!defined_default(left)) { throw new DeveloperError_default("first is required."); } if (!defined_default(right)) { throw new DeveloperError_default("second is required."); } if (!defined_default(absoluteEpsilon)) { throw new DeveloperError_default("absoluteEpsilon is required."); } return left - right > absoluteEpsilon; }; CesiumMath75.greaterThanOrEquals = function(left, right, absoluteEpsilon) { if (!defined_default(left)) { throw new DeveloperError_default("first is required."); } if (!defined_default(right)) { throw new DeveloperError_default("second is required."); } if (!defined_default(absoluteEpsilon)) { throw new DeveloperError_default("absoluteEpsilon is required."); } return left - right > -absoluteEpsilon; }; var factorials = [1]; CesiumMath75.factorial = function(n) { if (typeof n !== "number" || n < 0) { throw new DeveloperError_default( "A number greater than or equal to 0 is required." ); } const length2 = factorials.length; if (n >= length2) { let sum = factorials[length2 - 1]; for (let i = length2; i <= n; i++) { const next = sum * i; factorials.push(next); sum = next; } } return factorials[n]; }; CesiumMath75.incrementWrap = function(n, maximumValue, minimumValue) { minimumValue = defaultValue_default(minimumValue, 0); if (!defined_default(n)) { throw new DeveloperError_default("n is required."); } if (maximumValue <= minimumValue) { throw new DeveloperError_default("maximumValue must be greater than minimumValue."); } ++n; if (n > maximumValue) { n = minimumValue; } return n; }; CesiumMath75.isPowerOfTwo = function(n) { if (typeof n !== "number" || n < 0 || n > 4294967295) { throw new DeveloperError_default("A number between 0 and (2^32)-1 is required."); } return n !== 0 && (n & n - 1) === 0; }; CesiumMath75.nextPowerOfTwo = function(n) { if (typeof n !== "number" || n < 0 || n > 2147483648) { throw new DeveloperError_default("A number between 0 and 2^31 is required."); } --n; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; ++n; return n; }; CesiumMath75.previousPowerOfTwo = function(n) { if (typeof n !== "number" || n < 0 || n > 4294967295) { throw new DeveloperError_default("A number between 0 and (2^32)-1 is required."); } n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; n |= n >> 32; n = (n >>> 0) - (n >>> 1); return n; }; CesiumMath75.clamp = function(value, min, max) { Check_default.typeOf.number("value", value); Check_default.typeOf.number("min", min); Check_default.typeOf.number("max", max); return value < min ? min : value > max ? max : value; }; var randomNumberGenerator = new import_mersenne_twister.default(); CesiumMath75.setRandomNumberSeed = function(seed) { if (!defined_default(seed)) { throw new DeveloperError_default("seed is required."); } randomNumberGenerator = new import_mersenne_twister.default(seed); }; CesiumMath75.nextRandomNumber = function() { return randomNumberGenerator.random(); }; CesiumMath75.randomBetween = function(min, max) { return CesiumMath75.nextRandomNumber() * (max - min) + min; }; CesiumMath75.acosClamped = function(value) { if (!defined_default(value)) { throw new DeveloperError_default("value is required."); } return Math.acos(CesiumMath75.clamp(value, -1, 1)); }; CesiumMath75.asinClamped = function(value) { if (!defined_default(value)) { throw new DeveloperError_default("value is required."); } return Math.asin(CesiumMath75.clamp(value, -1, 1)); }; CesiumMath75.chordLength = function(angle, radius) { if (!defined_default(angle)) { throw new DeveloperError_default("angle is required."); } if (!defined_default(radius)) { throw new DeveloperError_default("radius is required."); } return 2 * radius * Math.sin(angle * 0.5); }; CesiumMath75.logBase = function(number, base) { if (!defined_default(number)) { throw new DeveloperError_default("number is required."); } if (!defined_default(base)) { throw new DeveloperError_default("base is required."); } return Math.log(number) / Math.log(base); }; CesiumMath75.cbrt = defaultValue_default(Math.cbrt, function cbrt(number) { const result = Math.pow(Math.abs(number), 1 / 3); return number < 0 ? -result : result; }); CesiumMath75.log2 = defaultValue_default(Math.log2, function log2(number) { return Math.log(number) * Math.LOG2E; }); CesiumMath75.fog = function(distanceToCamera, density) { const scalar = distanceToCamera * density; return 1 - Math.exp(-(scalar * scalar)); }; CesiumMath75.fastApproximateAtan = function(x) { Check_default.typeOf.number("x", x); return x * (-0.1784 * Math.abs(x) - 0.0663 * x * x + 1.0301); }; CesiumMath75.fastApproximateAtan2 = function(x, y) { Check_default.typeOf.number("x", x); Check_default.typeOf.number("y", y); let opposite; let t = Math.abs(x); opposite = Math.abs(y); const adjacent = Math.max(t, opposite); opposite = Math.min(t, opposite); const oppositeOverAdjacent = opposite / adjacent; if (isNaN(oppositeOverAdjacent)) { throw new DeveloperError_default("either x or y must be nonzero"); } t = CesiumMath75.fastApproximateAtan(oppositeOverAdjacent); t = Math.abs(y) > Math.abs(x) ? CesiumMath75.PI_OVER_TWO - t : t; t = x < 0 ? CesiumMath75.PI - t : t; t = y < 0 ? -t : t; return t; }; var Math_default = CesiumMath75; // packages/engine/Specs/Core/PolylineGeometrySpec.js describe("Core/PolylineGeometry", function() { it("constructor throws with no positions", function() { expect(function() { return new import__296.PolylineGeometry(); }).toThrowDeveloperError(); }); it("constructor throws with less than two positions", function() { expect(function() { return new import__296.PolylineGeometry({ positions: [import__296.Cartesian3.ZERO] }); }).toThrowDeveloperError(); }); it("constructor throws with invalid number of colors", function() { expect(function() { return new import__296.PolylineGeometry({ positions: [import__296.Cartesian3.ZERO, import__296.Cartesian3.UNIT_X, import__296.Cartesian3.UNIT_Y], colors: [] }); }).toThrowDeveloperError(); }); it("constructor returns undefined when line width is negative", function() { const positions2 = [ new import__296.Cartesian3(1, 0, 0), new import__296.Cartesian3(0, 1, 0), new import__296.Cartesian3(0, 0, 1) ]; const line2 = import__296.PolylineGeometry.createGeometry( new import__296.PolylineGeometry({ positions: positions2, width: -1, vertexFormat: import__296.VertexFormat.ALL, granularity: Math.PI, ellipsoid: import__296.Ellipsoid.UNIT_SPHERE }) ); expect(line2).toBeUndefined(); }); it("constructor computes all vertex attributes", function() { const positions2 = [ new import__296.Cartesian3(1, 0, 0), new import__296.Cartesian3(0, 1, 0), new import__296.Cartesian3(0, 0, 1) ]; const line2 = import__296.PolylineGeometry.createGeometry( new import__296.PolylineGeometry({ positions: positions2, width: 10, vertexFormat: import__296.VertexFormat.ALL, granularity: Math.PI, ellipsoid: import__296.Ellipsoid.UNIT_SPHERE }) ); expect(line2.attributes.position).toBeDefined(); expect(line2.attributes.prevPosition).toBeDefined(); expect(line2.attributes.nextPosition).toBeDefined(); expect(line2.attributes.expandAndWidth).toBeDefined(); expect(line2.attributes.st).toBeDefined(); const numVertices = positions2.length * 4 - 4; expect(line2.attributes.position.values.length).toEqual(numVertices * 3); expect(line2.attributes.prevPosition.values.length).toEqual(numVertices * 3); expect(line2.attributes.nextPosition.values.length).toEqual(numVertices * 3); expect(line2.attributes.expandAndWidth.values.length).toEqual( numVertices * 2 ); expect(line2.attributes.st.values.length).toEqual(numVertices * 2); expect(line2.indices.length).toEqual(positions2.length * 6 - 6); }); it("constructor computes all vertex attributes for rhumb lines", function() { const positions2 = import__296.Cartesian3.fromDegreesArray([30, 30, 30, 60, 60, 60]); const line2 = import__296.PolylineGeometry.createGeometry( new import__296.PolylineGeometry({ positions: positions2, width: 10, vertexFormat: import__296.VertexFormat.ALL, granularity: Math.PI, ellipsoid: import__296.Ellipsoid.UNIT_SPHERE, arcType: import__297.ArcType.RHUMB }) ); expect(line2.attributes.position).toBeDefined(); expect(line2.attributes.prevPosition).toBeDefined(); expect(line2.attributes.nextPosition).toBeDefined(); expect(line2.attributes.expandAndWidth).toBeDefined(); expect(line2.attributes.st).toBeDefined(); const numVertices = positions2.length * 4 - 4; expect(line2.attributes.position.values.length).toEqual(numVertices * 3); expect(line2.attributes.prevPosition.values.length).toEqual(numVertices * 3); expect(line2.attributes.nextPosition.values.length).toEqual(numVertices * 3); expect(line2.attributes.expandAndWidth.values.length).toEqual( numVertices * 2 ); expect(line2.attributes.st.values.length).toEqual(numVertices * 2); expect(line2.indices.length).toEqual(positions2.length * 6 - 6); }); it("constructor computes per segment colors", function() { const positions2 = [ new import__296.Cartesian3(1, 0, 0), new import__296.Cartesian3(0, 1, 0), new import__296.Cartesian3(0, 0, 1) ]; const colors = [ new import__296.Color(1, 0, 0, 1), new import__296.Color(0, 1, 0, 1), new import__296.Color(0, 0, 1, 1) ]; const line2 = import__296.PolylineGeometry.createGeometry( new import__296.PolylineGeometry({ positions: positions2, colors, width: 10, vertexFormat: import__296.VertexFormat.ALL, granularity: Math.PI, ellipsoid: import__296.Ellipsoid.UNIT_SPHERE }) ); expect(line2.attributes.color).toBeDefined(); const numVertices = positions2.length * 4 - 4; expect(line2.attributes.color.values.length).toEqual(numVertices * 4); }); it("constructor computes per vertex colors", function() { const positions2 = [ new import__296.Cartesian3(1, 0, 0), new import__296.Cartesian3(0, 1, 0), new import__296.Cartesian3(0, 0, 1) ]; const colors = [ new import__296.Color(1, 0, 0, 1), new import__296.Color(0, 1, 0, 1), new import__296.Color(0, 0, 1, 1) ]; const line2 = import__296.PolylineGeometry.createGeometry( new import__296.PolylineGeometry({ positions: positions2, colors, colorsPerVertex: true, width: 10, vertexFormat: import__296.VertexFormat.ALL, granularity: Math.PI, ellipsoid: import__296.Ellipsoid.UNIT_SPHERE }) ); expect(line2.attributes.color).toBeDefined(); const numVertices = positions2.length * 4 - 4; expect(line2.attributes.color.values.length).toEqual(numVertices * 4); }); it("createGeometry returns undefined without at least 2 unique positions", function() { const position = new import__296.Cartesian3(1e5, -2e5, 3e5); const positions2 = [position, import__296.Cartesian3.clone(position)]; const geometry = import__296.PolylineGeometry.createGeometry( new import__296.PolylineGeometry({ positions: positions2, width: 10, vertexFormat: import__296.VertexFormat.POSITION_ONLY, arcType: import__297.ArcType.NONE }) ); expect(geometry).not.toBeDefined(); }); it("createGeometry returns positions if their endpoints'longtitude and latitude are the same for rhumb line", function() { const positions2 = import__296.Cartesian3.fromDegreesArrayHeights([ 30, 30, 10, 30, 30, 5 ]); const geometry = import__296.PolylineGeometry.createGeometry( new import__296.PolylineGeometry({ positions: positions2, width: 10, vertexFormat: import__296.VertexFormat.POSITION_ONLY, arcType: import__297.ArcType.RHUMB }) ); const attributePositions = geometry.attributes.position.values; const geometryPosition = new import__296.Cartesian3(); import__296.Cartesian3.fromArray(attributePositions, 0, geometryPosition); expect( import__296.Cartesian3.equalsEpsilon( geometryPosition, positions2[0], Math_default.EPSILON7 ) ).toBe(true); import__296.Cartesian3.fromArray(attributePositions, 3, geometryPosition); expect( import__296.Cartesian3.equalsEpsilon( geometryPosition, positions2[0], Math_default.EPSILON7 ) ).toBe(true); import__296.Cartesian3.fromArray(attributePositions, 6, geometryPosition); expect( import__296.Cartesian3.equalsEpsilon( geometryPosition, positions2[1], Math_default.EPSILON7 ) ).toBe(true); import__296.Cartesian3.fromArray(attributePositions, 9, geometryPosition); expect( import__296.Cartesian3.equalsEpsilon( geometryPosition, positions2[1], Math_default.EPSILON7 ) ).toBe(true); }); it("createGeometry removes duplicate positions", function() { const positions2 = [ new import__296.Cartesian3(1, 2, 3), new import__296.Cartesian3(2, 2, 3), new import__296.Cartesian3(2, 2, 3), new import__296.Cartesian3(3, 2, 3), new import__296.Cartesian3(4, 2, 3), new import__296.Cartesian3(4, 2, 3), new import__296.Cartesian3(4, 2, 3), new import__296.Cartesian3(5, 2, 3) ]; const expectedPositions = [ new import__296.Cartesian3(1, 2, 3), new import__296.Cartesian3(2, 2, 3), new import__296.Cartesian3(3, 2, 3), new import__296.Cartesian3(4, 2, 3), new import__296.Cartesian3(5, 2, 3) ]; const line2 = import__296.PolylineGeometry.createGeometry( new import__296.PolylineGeometry({ positions: positions2, width: 10, vertexFormat: import__296.VertexFormat.POSITION_ONLY, arcType: import__297.ArcType.NONE }) ); const numVertices = expectedPositions.length * 4 - 4; expect(line2.attributes.position.values.length).toEqual(numVertices * 3); expect(line2.attributes.prevPosition.values.length).toEqual(numVertices * 3); expect(line2.attributes.nextPosition.values.length).toEqual(numVertices * 3); }); function attributeArrayEqualsColorArray(attributeArray, colorArray, colorsPerVertex) { colorsPerVertex = (0, import__297.defaultValue)(colorsPerVertex, false); let i; let j; let color; let color2; const reconstructedColor = new import__296.Color(); let attrArrayIndex; const length2 = colorsPerVertex ? colorArray.length - 1 : colorArray.length; for (i = 0; i < length2; i++) { color = colorArray[i]; color2 = colorArray[i + 1]; attrArrayIndex = 16 * i; for (j = 0; j < 4; j++) { reconstructedColor.red = attributeArray[attrArrayIndex + 4 * j] / 255; reconstructedColor.green = attributeArray[attrArrayIndex + 4 * j + 1] / 255; reconstructedColor.blue = attributeArray[attrArrayIndex + 4 * j + 2] / 255; reconstructedColor.alpha = attributeArray[attrArrayIndex + 4 * j + 3] / 255; if (colorsPerVertex && j > 1) { if (!reconstructedColor.equalsEpsilon(color2, Math_default.EPSILON2)) { return false; } } else if (!reconstructedColor.equalsEpsilon(color, Math_default.EPSILON2)) { return false; } } } return true; } it("createGeometry removes segment colors corresponding to duplicate positions", function() { const positions2 = [ new import__296.Cartesian3(1, 2, 3), new import__296.Cartesian3(2, 2, 3), new import__296.Cartesian3(2, 2, 3), new import__296.Cartesian3(3, 2, 3), new import__296.Cartesian3(4, 2, 3), new import__296.Cartesian3(4, 2, 3), new import__296.Cartesian3(4, 2, 3), new import__296.Cartesian3(5, 2, 3) ]; const colors = [ new import__296.Color(0, 1, 0, 1), new import__296.Color(1, 0, 0, 1), new import__296.Color(0, 0, 1, 1), new import__296.Color(0, 1, 0, 1), new import__296.Color(1, 0, 0, 1), new import__296.Color(1, 0, 0, 1), new import__296.Color(0, 0, 1, 1) ]; const expectedPositions = [ new import__296.Cartesian3(1, 2, 3), new import__296.Cartesian3(2, 2, 3), new import__296.Cartesian3(3, 2, 3), new import__296.Cartesian3(4, 2, 3), new import__296.Cartesian3(5, 2, 3) ]; const expectedColors = [ new import__296.Color(0, 1, 0, 1), new import__296.Color(0, 0, 1, 1), new import__296.Color(0, 1, 0, 1), new import__296.Color(0, 0, 1, 1) ]; const line2 = import__296.PolylineGeometry.createGeometry( new import__296.PolylineGeometry({ positions: positions2, colors, width: 10, vertexFormat: import__296.VertexFormat.POSITION_ONLY, arcType: import__297.ArcType.NONE }) ); const numVertices = expectedPositions.length * 4 - 4; expect(line2.attributes.color.values.length).toEqual(numVertices * 4); expect( attributeArrayEqualsColorArray( line2.attributes.color.values, expectedColors ) ).toBe(true); }); it("createGeometry removes per-vertex colors corresponding to duplicate positions", function() { const positions2 = [ new import__296.Cartesian3(1, 2, 3), new import__296.Cartesian3(2, 2, 3), new import__296.Cartesian3(2, 2, 3), new import__296.Cartesian3(3, 2, 3), new import__296.Cartesian3(3, 2, 3), new import__296.Cartesian3(4, 2, 3), new import__296.Cartesian3(5, 2, 3), new import__296.Cartesian3(5, 2, 3), new import__296.Cartesian3(6, 2, 3) ]; const colors = [ new import__296.Color(1, 0, 0, 1), new import__296.Color(1, 0.5, 0, 1), new import__296.Color(0, 0, 0, 1), new import__296.Color(1, 1, 0, 1), new import__296.Color(0, 0, 0, 1), new import__296.Color(0, 1, 0, 1), new import__296.Color(0, 1, 1, 1), new import__296.Color(0, 0, 0, 1), new import__296.Color(0, 0, 1, 1) ]; const expectedPositions = [ new import__296.Cartesian3(1, 2, 3), new import__296.Cartesian3(2, 2, 3), new import__296.Cartesian3(3, 2, 3), new import__296.Cartesian3(4, 2, 3), new import__296.Cartesian3(5, 2, 3), new import__296.Cartesian3(6, 2, 3) ]; const expectedColors = [ new import__296.Color(1, 0, 0, 1), new import__296.Color(1, 0.5, 0, 1), new import__296.Color(1, 1, 0, 1), new import__296.Color(0, 1, 0, 1), new import__296.Color(0, 1, 1, 1), new import__296.Color(0, 0, 1, 1) ]; const line2 = import__296.PolylineGeometry.createGeometry( new import__296.PolylineGeometry({ positions: positions2, colors, colorsPerVertex: true, width: 10, vertexFormat: import__296.VertexFormat.DEFAULT, arcType: import__297.ArcType.NONE }) ); const numVertices = expectedPositions.length * 4 - 4; expect(line2.attributes.color.values.length).toEqual(numVertices * 4); expect( attributeArrayEqualsColorArray( line2.attributes.color.values, expectedColors, true ) ).toBe(true); }); it("createGeometry removes first color corresponding to endpoint with duplicate position", function() { const positions2 = [ new import__296.Cartesian3(1, 2, 3), new import__296.Cartesian3(1, 2, 3), new import__296.Cartesian3(2, 2, 3), new import__296.Cartesian3(3, 2, 3) ]; const colors = [ new import__296.Color(0, 0, 0, 1), new import__296.Color(1, 1, 1, 1), new import__296.Color(0, 1, 0, 1), new import__296.Color(0, 0, 1, 1) ]; const expectedPositions = [ new import__296.Cartesian3(1, 2, 3), new import__296.Cartesian3(2, 2, 3), new import__296.Cartesian3(3, 2, 3) ]; const expectedColors = [ new import__296.Color(1, 1, 1, 1), new import__296.Color(0, 1, 0, 1), new import__296.Color(0, 0, 1, 1) ]; const line2 = import__296.PolylineGeometry.createGeometry( new import__296.PolylineGeometry({ positions: positions2, colors, colorsPerVertex: true, width: 10, vertexFormat: import__296.VertexFormat.DEFAULT, arcType: import__297.ArcType.NONE }) ); const numVertices = expectedPositions.length * 4 - 4; expect(line2.attributes.color.values.length).toEqual(numVertices * 4); expect( attributeArrayEqualsColorArray( line2.attributes.color.values, expectedColors, true ) ).toBe(true); }); const positions = [ new import__296.Cartesian3(1, 2, 3), new import__296.Cartesian3(4, 5, 6), new import__296.Cartesian3(7, 8, 9) ]; let line = new import__296.PolylineGeometry({ positions, width: 10, colors: [import__296.Color.RED, import__296.Color.LIME, import__296.Color.BLUE], colorsPerVertex: true, arcType: import__297.ArcType.NONE, granularity: 11, vertexFormat: import__296.VertexFormat.POSITION_ONLY, ellipsoid: new import__296.Ellipsoid(12, 13, 14) }); let packedInstance = [ 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 12, 13, 14, 1, 0, 0, 0, 0, 0, 10, 1, 0, 11 ]; createPackableSpecs_default( import__296.PolylineGeometry, line, packedInstance, "per vertex colors" ); line = new import__296.PolylineGeometry({ positions, width: 10, colorsPerVertex: false, arcType: import__297.ArcType.NONE, granularity: 11, vertexFormat: import__296.VertexFormat.POSITION_ONLY, ellipsoid: new import__296.Ellipsoid(12, 13, 14) }); packedInstance = [ 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 12, 13, 14, 1, 0, 0, 0, 0, 0, 10, 0, 0, 11 ]; createPackableSpecs_default(import__296.PolylineGeometry, line, packedInstance, "straight line"); line = new import__296.PolylineGeometry({ positions, width: 10, colorsPerVertex: false, arcType: import__297.ArcType.GEODESIC, granularity: 11, vertexFormat: import__296.VertexFormat.POSITION_ONLY, ellipsoid: new import__296.Ellipsoid(12, 13, 14) }); packedInstance = [ 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 12, 13, 14, 1, 0, 0, 0, 0, 0, 10, 0, 1, 11 ]; createPackableSpecs_default(import__296.PolylineGeometry, line, packedInstance, "geodesic line"); line = new import__296.PolylineGeometry({ positions, width: 10, colorsPerVertex: false, arcType: import__297.ArcType.RHUMB, granularity: 11, vertexFormat: import__296.VertexFormat.POSITION_ONLY, ellipsoid: new import__296.Ellipsoid(12, 13, 14) }); packedInstance = [ 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 12, 13, 14, 1, 0, 0, 0, 0, 0, 10, 0, 2, 11 ]; createPackableSpecs_default(import__296.PolylineGeometry, line, packedInstance, "rhumb line"); }); // packages/engine/Specs/Core/PolylinePipelineSpec.js var import__298 = __toESM(require_Cesium(), 1); var import__299 = __toESM(require_Cesium(), 1); describe("Core/PolylinePipeline", function() { it("wrapLongitude", function() { const positions = import__298.Cartesian3.fromDegreesArray([ -75.163789, 39.952335, -80.2264393, 25.7889689 ]); const segments = import__298.PolylinePipeline.wrapLongitude(positions); expect(segments.lengths.length).toEqual(1); expect(segments.lengths[0]).toEqual(2); }); it("wrapLongitude works with empty array", function() { const segments = import__298.PolylinePipeline.wrapLongitude([]); expect(segments.lengths.length).toEqual(0); }); it("wrapLongitude breaks polyline into segments", function() { const positions = import__298.Cartesian3.fromDegreesArray([-179, 39, 2, 25]); const segments = import__298.PolylinePipeline.wrapLongitude(positions); expect(segments.lengths.length).toEqual(2); expect(segments.lengths[0]).toEqual(2); expect(segments.lengths[1]).toEqual(2); }); it("wrapLongitude breaks polyline into segments with model matrix", function() { const center = import__298.Cartesian3.fromDegrees(-179, 39); const matrix = import__298.Transforms.eastNorthUpToFixedFrame(center, import__298.Ellipsoid.WGS84); const positions = [ new import__298.Cartesian3(0, 0, 0), new import__298.Cartesian3(0, 1e8, 0) ]; const segments = import__298.PolylinePipeline.wrapLongitude(positions, matrix); expect(segments.lengths.length).toEqual(2); expect(segments.lengths[0]).toEqual(2); expect(segments.lengths[1]).toEqual(2); }); it("generateArc throws without positions", function() { expect(function() { import__298.PolylinePipeline.generateArc(); }).toThrowDeveloperError(); }); it("generateArc accepts a height array for single value", function() { const positions = [import__298.Cartesian3.fromDegrees(0, 0)]; const height = [30]; const newPositions = import__298.PolylinePipeline.generateArc({ positions, height }); expect(newPositions.length).toEqual(3); expect(import__298.Cartesian3.fromArray(newPositions, 0)).toEqualEpsilon( import__298.Cartesian3.fromDegrees(0, 0, 30), import__299.Math.EPSILON6 ); }); it("generateArc subdivides in half", function() { const p1 = import__298.Cartesian3.fromDegrees(0, 0); const p2 = import__298.Cartesian3.fromDegrees(90, 0); const p3 = import__298.Cartesian3.fromDegrees(45, 0); const positions = [p1, p2]; const newPositions = import__298.PolylinePipeline.generateArc({ positions, granularity: import__299.Math.PI_OVER_TWO / 2, ellipsoid: import__298.Ellipsoid.WGS84 }); expect(newPositions.length).toEqual(3 * 3); const p1n = import__298.Cartesian3.fromArray(newPositions, 0); const p3n = import__298.Cartesian3.fromArray(newPositions, 3); const p2n = import__298.Cartesian3.fromArray(newPositions, 6); expect(import__298.Cartesian3.equalsEpsilon(p1, p1n, import__299.Math.EPSILON4)).toEqual( true ); expect(import__298.Cartesian3.equalsEpsilon(p2, p2n, import__299.Math.EPSILON4)).toEqual( true ); expect(import__298.Cartesian3.equalsEpsilon(p3, p3n, import__299.Math.EPSILON4)).toEqual( true ); }); it("generateArc works with empty array", function() { const newPositions = import__298.PolylinePipeline.generateArc({ positions: [] }); expect(newPositions.length).toEqual(0); }); it("generateArc works one position", function() { const newPositions = import__298.PolylinePipeline.generateArc({ positions: [import__298.Cartesian3.UNIT_Z], ellipsoid: import__298.Ellipsoid.UNIT_SPHERE }); expect(newPositions.length).toEqual(3); expect(newPositions).toEqual([0, 0, 1]); }); it("generateRhumbArc throws without positions", function() { expect(function() { import__298.PolylinePipeline.generateRhumbArc(); }).toThrowDeveloperError(); }); it("generateRhumbArc accepts a height array for single value", function() { const positions = [import__298.Cartesian3.fromDegrees(0, 0)]; const height = [30]; const newPositions = import__298.PolylinePipeline.generateRhumbArc({ positions, height }); expect(newPositions.length).toEqual(3); expect(import__298.Cartesian3.fromArray(newPositions, 0)).toEqualEpsilon( import__298.Cartesian3.fromDegrees(0, 0, 30), import__299.Math.EPSILON6 ); }); it("generateRhumbArc subdivides in half", function() { const p1 = import__298.Cartesian3.fromDegrees(0, 30); const p2 = import__298.Cartesian3.fromDegrees(90, 30); const p3 = import__298.Cartesian3.fromDegrees(45, 30); const positions = [p1, p2]; const newPositions = import__298.PolylinePipeline.generateRhumbArc({ positions, granularity: import__299.Math.PI_OVER_FOUR, ellipsoid: import__298.Ellipsoid.WGS84 }); expect(newPositions.length).toEqual(3 * 3); const p1n = import__298.Cartesian3.fromArray(newPositions, 0); const p3n = import__298.Cartesian3.fromArray(newPositions, 3); const p2n = import__298.Cartesian3.fromArray(newPositions, 6); expect(import__298.Cartesian3.equalsEpsilon(p1, p1n, import__299.Math.EPSILON4)).toEqual( true ); expect(import__298.Cartesian3.equalsEpsilon(p2, p2n, import__299.Math.EPSILON4)).toEqual( true ); expect(import__298.Cartesian3.equalsEpsilon(p3, p3n, import__299.Math.EPSILON4)).toEqual( true ); }); it("generateRhumbArc works with empty array", function() { const newPositions = import__298.PolylinePipeline.generateRhumbArc({ positions: [] }); expect(newPositions.length).toEqual(0); }); it("generateRhumbArc works one position", function() { const newPositions = import__298.PolylinePipeline.generateRhumbArc({ positions: [import__298.Cartesian3.UNIT_Z], ellipsoid: import__298.Ellipsoid.UNIT_SPHERE }); expect(newPositions.length).toEqual(3); expect(newPositions).toEqual([0, 0, 1]); }); it("generateRhumbArc return values for each position", function() { const newPositions = import__298.PolylinePipeline.generateRhumbArc({ positions: import__298.Cartesian3.fromDegreesArray([0, 0, 10, 0, 10, 5]) }); for (let i = 0; i < newPositions.length; i++) { expect(newPositions[i]).toBeDefined(); } }); }); // packages/engine/Specs/Core/PolylineVolumeGeometrySpec.js var import__300 = __toESM(require_Cesium(), 1); describe("Core/PolylineVolumeGeometry", function() { let shape; beforeAll(function() { shape = [ new import__300.Cartesian2(-100, -100), new import__300.Cartesian2(100, -100), new import__300.Cartesian2(100, 100), new import__300.Cartesian2(-100, 100) ]; }); it("throws without polyline positions", function() { expect(function() { return new import__300.PolylineVolumeGeometry({}); }).toThrowDeveloperError(); }); it("throws without shape positions", function() { expect(function() { return new import__300.PolylineVolumeGeometry({ polylinePositions: [new import__300.Cartesian3()] }); }).toThrowDeveloperError(); }); it("createGeometry returnes undefined without 2 unique polyline positions", function() { const geometry = import__300.PolylineVolumeGeometry.createGeometry( new import__300.PolylineVolumeGeometry({ polylinePositions: [new import__300.Cartesian3()], shapePositions: shape }) ); expect(geometry).toBeUndefined(); }); it("createGeometry returnes undefined without 3 unique shape positions", function() { const geometry = import__300.PolylineVolumeGeometry.createGeometry( new import__300.PolylineVolumeGeometry({ polylinePositions: [import__300.Cartesian3.UNIT_X, import__300.Cartesian3.UNIT_Y], shapePositions: [ import__300.Cartesian2.UNIT_X, import__300.Cartesian2.UNIT_X, import__300.Cartesian2.UNIT_X ] }) ); expect(geometry).toBeUndefined(); }); it("computes positions", function() { const m = import__300.PolylineVolumeGeometry.createGeometry( new import__300.PolylineVolumeGeometry({ vertexFormat: import__300.VertexFormat.POSITION_ONLY, polylinePositions: import__300.Cartesian3.fromDegreesArray([ 90, -30, 90, -35 ]), cornerType: import__300.CornerType.MITERED, shapePositions: shape }) ); expect(m.attributes.position.values.length).toEqual(56 * 3); expect(m.indices.length).toEqual(44 * 3); }); it("computes positions, clockwise shape", function() { const m = import__300.PolylineVolumeGeometry.createGeometry( new import__300.PolylineVolumeGeometry({ vertexFormat: import__300.VertexFormat.POSITION_ONLY, polylinePositions: import__300.Cartesian3.fromDegreesArray([ 90, -30, 90, -35 ]), cornerType: import__300.CornerType.MITERED, shapePositions: shape.reverse() }) ); expect(m.attributes.position.values.length).toEqual(56 * 3); expect(m.indices.length).toEqual(44 * 3); }); it("computes most vertex attributes", function() { const m = import__300.PolylineVolumeGeometry.createGeometry( new import__300.PolylineVolumeGeometry({ vertexFormat: import__300.VertexFormat.POSITION_NORMAL_AND_ST, polylinePositions: import__300.Cartesian3.fromDegreesArray([ 90, -30, 90, -35 ]), cornerType: import__300.CornerType.MITERED, shapePositions: shape }) ); const numVertices = 56; const numTriangles = 44; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.attributes.st.values.length).toEqual(numVertices * 2); expect(m.attributes.normal.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); xit("compute all vertex attributes", function() { const m = import__300.PolylineVolumeGeometry.createGeometry( new import__300.PolylineVolumeGeometry({ vertexFormat: import__300.VertexFormat.ALL, polylinePositions: import__300.Cartesian3.fromDegreesArray([ 90, -30, 90, -35 ]), cornerType: import__300.CornerType.MITERED, shapePositions: shape }) ); const numVertices = 56; const numTriangles = 44; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.attributes.st.values.length).toEqual(numVertices * 2); expect(m.attributes.normal.values.length).toEqual(numVertices * 3); expect(m.attributes.tangent.values.length).toEqual(numVertices * 3); expect(m.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("computes right turn", function() { const m = import__300.PolylineVolumeGeometry.createGeometry( new import__300.PolylineVolumeGeometry({ vertexFormat: import__300.VertexFormat.POSITION_ONLY, polylinePositions: import__300.Cartesian3.fromDegreesArray([ 90, -30, 90, -31, 91, -31 ]), cornerType: import__300.CornerType.MITERED, shapePositions: shape }) ); expect(m.attributes.position.values.length).toEqual(56 * 3); expect(m.indices.length).toEqual(44 * 3); }); it("computes left turn", function() { const m = import__300.PolylineVolumeGeometry.createGeometry( new import__300.PolylineVolumeGeometry({ vertexFormat: import__300.VertexFormat.POSITION_ONLY, polylinePositions: import__300.Cartesian3.fromDegreesArray([ 90, -30, 90, -31, 89, -31 ]), cornerType: import__300.CornerType.MITERED, shapePositions: shape }) ); expect(m.attributes.position.values.length).toEqual(56 * 3); expect(m.indices.length).toEqual(44 * 3); }); it("computes with rounded corners", function() { const m = import__300.PolylineVolumeGeometry.createGeometry( new import__300.PolylineVolumeGeometry({ vertexFormat: import__300.VertexFormat.POSITION_ONLY, polylinePositions: import__300.Cartesian3.fromDegreesArray([ 90, -30, 90, -31, 89, -31, 89, -32 ]), cornerType: import__300.CornerType.ROUNDED, shapePositions: shape }) ); const corners = 36 * 4 * 4; const numVertices = corners + 72; const numTriangles = corners + 60; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("computes with beveled corners", function() { const m = import__300.PolylineVolumeGeometry.createGeometry( new import__300.PolylineVolumeGeometry({ vertexFormat: import__300.VertexFormat.POSITION_ONLY, polylinePositions: import__300.Cartesian3.fromDegreesArray([ 90, -30, 90, -31, 89, -31, 89, -32 ]), cornerType: import__300.CornerType.BEVELED, shapePositions: shape }) ); const corners = 4 * 4; const numVertices = corners + 72; const numTriangles = corners + 60; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(3 * numTriangles); }); it("computes sharp turns", function() { const m = import__300.PolylineVolumeGeometry.createGeometry( new import__300.PolylineVolumeGeometry({ vertexFormat: import__300.VertexFormat.POSITION_ONLY, polylinePositions: import__300.Cartesian3.fromDegreesArrayHeights([ 2.00571672577652, 52.7781459942399, 500, 1.99188457974115, 52.7764958852886, 500, 2.01325961458495, 52.7674170680511, 500, 1.98708058340534, 52.7733979856253, 500, 2.00634853946644, 52.7650460748473, 500 ]), cornerType: import__300.CornerType.BEVELED, shapePositions: shape }) ); expect(m.attributes.position.values.length).toEqual(120 * 3); expect(m.indices.length).toEqual(108 * 3); }); it("computes straight volume", function() { const m = import__300.PolylineVolumeGeometry.createGeometry( new import__300.PolylineVolumeGeometry({ vertexFormat: import__300.VertexFormat.POSITION_ONLY, polylinePositions: import__300.Cartesian3.fromDegreesArray([ -67.655, 0, -67.655, 15, -67.655, 20 ]), cornerType: import__300.CornerType.BEVELED, shapePositions: shape, granularity: Math.PI / 6 }) ); expect(m.attributes.position.values.length).toEqual(32 * 3); expect(m.indices.length).toEqual(20 * 3); }); const positions = [ new import__300.Cartesian3(1, 0, 0), new import__300.Cartesian3(0, 1, 0), new import__300.Cartesian3(0, 0, 1) ]; const volumeShape = [ new import__300.Cartesian2(0, 0), new import__300.Cartesian2(1, 0), new import__300.Cartesian2(0, 1) ]; const volume = new import__300.PolylineVolumeGeometry({ vertexFormat: import__300.VertexFormat.POSITION_ONLY, polylinePositions: positions, cornerType: import__300.CornerType.BEVELED, shapePositions: volumeShape, ellipsoid: import__300.Ellipsoid.UNIT_SPHERE, granularity: 0.1 }); const packedInstance = [ 3, 1, 0, 0, 0, 1, 0, 0, 0, 1, 3, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 2, 0.1 ]; createPackableSpecs_default(import__300.PolylineVolumeGeometry, volume, packedInstance); }); // packages/engine/Specs/Core/PolylineVolumeOutlineGeometrySpec.js var import__301 = __toESM(require_Cesium(), 1); describe("Core/PolylineVolumeOutlineGeometry", function() { let shape; beforeAll(function() { shape = [ new import__301.Cartesian2(-100, -100), new import__301.Cartesian2(100, -100), new import__301.Cartesian2(100, 100), new import__301.Cartesian2(-100, 100) ]; }); it("throws without polyline positions", function() { expect(function() { return new import__301.PolylineVolumeOutlineGeometry({}); }).toThrowDeveloperError(); }); it("throws without shape positions", function() { expect(function() { return new import__301.PolylineVolumeOutlineGeometry({ polylinePositions: [new import__301.Cartesian3()] }); }).toThrowDeveloperError(); }); it("createGeometry returnes undefined without 2 unique polyline positions", function() { const geometry = import__301.PolylineVolumeOutlineGeometry.createGeometry( new import__301.PolylineVolumeOutlineGeometry({ polylinePositions: [new import__301.Cartesian3()], shapePositions: shape }) ); expect(geometry).toBeUndefined(); }); it("createGeometry returnes undefined without 3 unique shape positions", function() { const geometry = import__301.PolylineVolumeOutlineGeometry.createGeometry( new import__301.PolylineVolumeOutlineGeometry({ polylinePositions: [import__301.Cartesian3.UNIT_X, import__301.Cartesian3.UNIT_Y], shapePositions: [ import__301.Cartesian2.UNIT_X, import__301.Cartesian2.UNIT_X, import__301.Cartesian2.UNIT_X ] }) ); expect(geometry).toBeUndefined(); }); it("computes positions", function() { const m = import__301.PolylineVolumeOutlineGeometry.createGeometry( new import__301.PolylineVolumeOutlineGeometry({ polylinePositions: import__301.Cartesian3.fromDegreesArray([ 90, -30, 90, -35 ]), shapePositions: shape, cornerType: import__301.CornerType.MITERED }) ); expect(m.attributes.position.values.length).toEqual(24 * 3); expect(m.indices.length).toEqual(28 * 2); }); it("computes positions, clockwise shape", function() { const m = import__301.PolylineVolumeOutlineGeometry.createGeometry( new import__301.PolylineVolumeOutlineGeometry({ polylinePositions: import__301.Cartesian3.fromDegreesArray([ 90, -30, 90, -35 ]), shapePositions: shape.reverse(), cornerType: import__301.CornerType.MITERED }) ); expect(m.attributes.position.values.length).toEqual(24 * 3); expect(m.indices.length).toEqual(28 * 2); }); it("computes right turn", function() { const m = import__301.PolylineVolumeOutlineGeometry.createGeometry( new import__301.PolylineVolumeOutlineGeometry({ polylinePositions: import__301.Cartesian3.fromDegreesArray([ 90, -30, 90, -31, 91, -31 ]), cornerType: import__301.CornerType.MITERED, shapePositions: shape }) ); expect(m.attributes.position.values.length).toEqual(20 * 3); expect(m.indices.length).toEqual(24 * 2); }); it("computes left turn", function() { const m = import__301.PolylineVolumeOutlineGeometry.createGeometry( new import__301.PolylineVolumeOutlineGeometry({ polylinePositions: import__301.Cartesian3.fromDegreesArray([ 90, -30, 90, -31, 89, -31 ]), cornerType: import__301.CornerType.MITERED, shapePositions: shape }) ); expect(m.attributes.position.values.length).toEqual(20 * 3); expect(m.indices.length).toEqual(24 * 2); }); it("computes with rounded corners", function() { const m = import__301.PolylineVolumeOutlineGeometry.createGeometry( new import__301.PolylineVolumeOutlineGeometry({ polylinePositions: import__301.Cartesian3.fromDegreesArray([ 90, -30, 90, -31, 89, -31, 89, -32 ]), cornerType: import__301.CornerType.ROUNDED, shapePositions: shape }) ); const corners = 36 * 4; const numVertices = corners + 28; const numLines = corners + 32; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numLines * 2); }); it("computes with beveled corners", function() { const m = import__301.PolylineVolumeOutlineGeometry.createGeometry( new import__301.PolylineVolumeOutlineGeometry({ polylinePositions: import__301.Cartesian3.fromDegreesArray([ 90, -30, 90, -31, 89, -31, 89, -32 ]), cornerType: import__301.CornerType.BEVELED, shapePositions: shape }) ); expect(m.attributes.position.values.length).toEqual(40 * 3); expect(m.indices.length).toEqual(44 * 2); }); const positions = [ new import__301.Cartesian3(1, 0, 0), new import__301.Cartesian3(0, 1, 0), new import__301.Cartesian3(0, 0, 1) ]; const volumeShape = [ new import__301.Cartesian2(0, 0), new import__301.Cartesian2(1, 0), new import__301.Cartesian2(0, 1) ]; const volume = new import__301.PolylineVolumeOutlineGeometry({ polylinePositions: positions, cornerType: import__301.CornerType.BEVELED, shapePositions: volumeShape, ellipsoid: import__301.Ellipsoid.UNIT_SPHERE, granularity: 0.1 }); const packedInstance = [ 3, 1, 0, 0, 0, 1, 0, 0, 0, 1, 3, 0, 0, 1, 0, 0, 1, 1, 1, 1, 2, 0.1 ]; createPackableSpecs_default(import__301.PolylineVolumeOutlineGeometry, volume, packedInstance); }); // packages/engine/Specs/Core/PrimitiveTypeSpec.js var import__302 = __toESM(require_Cesium(), 1); describe("Core/PrimitiveType", function() { it("validate works", function() { expect(import__302.PrimitiveType.validate(import__302.PrimitiveType.POINTS)).toBe(true); expect(import__302.PrimitiveType.validate(import__302.PrimitiveType.LINES)).toBe(true); expect(import__302.PrimitiveType.validate(import__302.PrimitiveType.LINE_LOOP)).toBe(true); expect(import__302.PrimitiveType.validate(import__302.PrimitiveType.LINE_STRIP)).toBe(true); expect(import__302.PrimitiveType.validate(import__302.PrimitiveType.TRIANGLES)).toBe(true); expect(import__302.PrimitiveType.validate(import__302.PrimitiveType.TRIANGLE_STRIP)).toBe(true); expect(import__302.PrimitiveType.validate(import__302.PrimitiveType.TRIANGLE_FAN)).toBe(true); expect(import__302.PrimitiveType.validate(void 0)).toBe(false); }); it("isLines works", function() { expect(import__302.PrimitiveType.isLines(import__302.PrimitiveType.POINTS)).toBe(false); expect(import__302.PrimitiveType.isLines(import__302.PrimitiveType.LINES)).toBe(true); expect(import__302.PrimitiveType.isLines(import__302.PrimitiveType.LINE_LOOP)).toBe(true); expect(import__302.PrimitiveType.isLines(import__302.PrimitiveType.LINE_STRIP)).toBe(true); expect(import__302.PrimitiveType.isLines(import__302.PrimitiveType.TRIANGLES)).toBe(false); expect(import__302.PrimitiveType.isLines(import__302.PrimitiveType.TRIANGLE_STRIP)).toBe(false); expect(import__302.PrimitiveType.isLines(import__302.PrimitiveType.TRIANGLE_FAN)).toBe(false); expect(import__302.PrimitiveType.isLines(void 0)).toBe(false); }); it("isTriangles works", function() { expect(import__302.PrimitiveType.isTriangles(import__302.PrimitiveType.POINTS)).toBe(false); expect(import__302.PrimitiveType.isTriangles(import__302.PrimitiveType.LINES)).toBe(false); expect(import__302.PrimitiveType.isTriangles(import__302.PrimitiveType.LINE_LOOP)).toBe(false); expect(import__302.PrimitiveType.isTriangles(import__302.PrimitiveType.LINE_STRIP)).toBe(false); expect(import__302.PrimitiveType.isTriangles(import__302.PrimitiveType.TRIANGLES)).toBe(true); expect(import__302.PrimitiveType.isTriangles(import__302.PrimitiveType.TRIANGLE_STRIP)).toBe(true); expect(import__302.PrimitiveType.isTriangles(import__302.PrimitiveType.TRIANGLE_FAN)).toBe(true); expect(import__302.PrimitiveType.isTriangles(void 0)).toBe(false); }); }); // packages/engine/Specs/Core/QuadraticRealPolynomialSpec.js var import__303 = __toESM(require_Cesium(), 1); var import__304 = __toESM(require_Cesium(), 1); describe("Core/QuadraticRealPolynomial", function() { it("discriminant throws without a", function() { expect(function() { import__303.QuadraticRealPolynomial.computeDiscriminant(); }).toThrowDeveloperError(); }); it("discriminant throws without b", function() { expect(function() { import__303.QuadraticRealPolynomial.computeDiscriminant(1); }).toThrowDeveloperError(); }); it("discriminant throws without c", function() { expect(function() { import__303.QuadraticRealPolynomial.computeDiscriminant(1, 1); }).toThrowDeveloperError(); }); it("discriminant", function() { const discriminant = import__303.QuadraticRealPolynomial.computeDiscriminant( 1, 2, 3 ); expect(discriminant).toEqual(-8); }); it("real roots throws without a", function() { expect(function() { import__303.QuadraticRealPolynomial.computeRealRoots(); }).toThrowDeveloperError(); }); it("real roots throws without b", function() { expect(function() { import__303.QuadraticRealPolynomial.computeRealRoots(1); }).toThrowDeveloperError(); }); it("real roots throws without c", function() { expect(function() { import__303.QuadraticRealPolynomial.computeRealRoots(1, 1); }).toThrowDeveloperError(); }); it("negative b", function() { const roots = import__303.QuadraticRealPolynomial.computeRealRoots(2, -4, -6); expect(roots.length).toEqual(2); expect(roots[0]).toEqual(-1); expect(roots[1]).toEqual(3); }); it("positive b", function() { const roots = import__303.QuadraticRealPolynomial.computeRealRoots(2, 4, -6); expect(roots.length).toEqual(2); expect(roots[0]).toEqual(-3); expect(roots[1]).toEqual(1); }); it("marginally negative radical case", function() { const roots = import__303.QuadraticRealPolynomial.computeRealRoots( 2, -3.999999999999999, 2 ); expect(roots.length).toEqual(2); expect(roots[0]).toEqualEpsilon(1, import__304.Math.EPSILON15); expect(roots[1]).toEqualEpsilon(1, import__304.Math.EPSILON15); }); it("complex roots", function() { const roots = import__303.QuadraticRealPolynomial.computeRealRoots(2, -4, 6); expect(roots.length).toEqual(0); }); it("intractable case", function() { const roots = import__303.QuadraticRealPolynomial.computeRealRoots(0, 0, -3); expect(roots.length).toEqual(0); }); it("linear case", function() { const roots = import__303.QuadraticRealPolynomial.computeRealRoots(0, 2, 8); expect(roots.length).toEqual(1); expect(roots[0]).toEqual(-4); }); it("2nd order monomial case", function() { const roots = import__303.QuadraticRealPolynomial.computeRealRoots(3, 0, 0); expect(roots.length).toEqual(2); expect(roots[0]).toEqual(0); expect(roots[1]).toEqual(0); }); it("parabolic case with complex roots", function() { const roots = import__303.QuadraticRealPolynomial.computeRealRoots(3, 0, 18); expect(roots.length).toEqual(0); }); it("parabolic case with real roots", function() { const roots = import__303.QuadraticRealPolynomial.computeRealRoots(2, 0, -18); expect(roots.length).toEqual(2); expect(roots[0]).toEqual(-3); expect(roots[1]).toEqual(3); }); it("zero and negative root case", function() { const roots = import__303.QuadraticRealPolynomial.computeRealRoots(2, 6, 0); expect(roots.length).toEqual(2); expect(roots[0]).toEqual(-3); expect(roots[1]).toEqual(0); }); it("zero and positive root case", function() { const roots = import__303.QuadraticRealPolynomial.computeRealRoots(2, -6, 0); expect(roots.length).toEqual(2); expect(roots[0]).toEqual(0); expect(roots[1]).toEqual(3); }); }); // packages/engine/Specs/Core/QuantizedMeshTerrainDataSpec.js var import__305 = __toESM(require_Cesium(), 1); var import__306 = __toESM(require_Cesium(), 1); describe("Core/QuantizedMeshTerrainData", function() { it("conforms to TerrainData interface", function() { expect(import__305.QuantizedMeshTerrainData).toConformToInterface(import__305.TerrainData); }); describe("upsample", function() { function findVertexWithCoordinates(uBuffer, vBuffer, u, v) { u *= 32767; u |= 0; v *= 32767; v |= 0; for (let i = 0; i < uBuffer.length; ++i) { if (Math.abs(uBuffer[i] - u) <= 1 && Math.abs(vBuffer[i] - v) <= 1) { return i; } } return -1; } function hasTriangle(ib, i0, i1, i2) { for (let i = 0; i < ib.length; i += 3) { if (ib[i] === i0 && ib[i + 1] === i1 && ib[i + 2] === i2 || ib[i] === i1 && ib[i + 1] === i2 && ib[i + 2] === i0 || ib[i] === i2 && ib[i + 1] === i0 && ib[i + 2] === i1) { return true; } } return false; } function intercept(interceptCoordinate1, interceptCoordinate2, otherCoordinate1, otherCoordinate2) { return import__306.Math.lerp( otherCoordinate1, otherCoordinate2, (0.5 - interceptCoordinate1) / (interceptCoordinate2 - interceptCoordinate1) ); } function horizontalIntercept(u1, v1, u2, v2) { return intercept(v1, v2, u1, u2); } function verticalIntercept(u1, v1, u2, v2) { return intercept(u1, u2, v1, v2); } it("works for all four children of a simple quad", function() { const data = new import__305.QuantizedMeshTerrainData({ minimumHeight: 0, maximumHeight: 4, quantizedVertices: new Uint16Array([ // order is sw nw se ne // u 0, 0, 32767, 32767, // v 0, 32767, 0, 32767, // heights 32767 / 4, 2 * 32767 / 4, 3 * 32767 / 4, 32767 ]), indices: new Uint16Array([0, 3, 1, 0, 2, 3]), boundingSphere: new import__305.BoundingSphere(), horizonOcclusionPoint: new import__305.Cartesian3(), westIndices: [], southIndices: [], eastIndices: [], northIndices: [], westSkirtHeight: 1, southSkirtHeight: 1, eastSkirtHeight: 1, northSkirtHeight: 1, childTileMask: 15 }); const tilingScheme = new import__305.GeographicTilingScheme(); return Promise.resolve( data.createMesh({ tilingScheme, x: 0, y: 0, level: 0 }) ).then(function() { const swPromise = data.upsample(tilingScheme, 0, 0, 0, 0, 0, 1); const sePromise = data.upsample(tilingScheme, 0, 0, 0, 1, 0, 1); const nwPromise = data.upsample(tilingScheme, 0, 0, 0, 0, 1, 1); const nePromise = data.upsample(tilingScheme, 0, 0, 0, 1, 1, 1); return Promise.all([swPromise, sePromise, nwPromise, nePromise]); }).then(function(upsampleResults) { expect(upsampleResults.length).toBe(4); for (let i = 0; i < upsampleResults.length; ++i) { const upsampled = upsampleResults[i]; expect(upsampled).toBeDefined(); const uBuffer = upsampled._uValues; const vBuffer = upsampled._vValues; const ib = upsampled._indices; expect(uBuffer.length).toBe(4); expect(vBuffer.length).toBe(4); expect(upsampled._heightValues.length).toBe(4); expect(ib.length).toBe(6); const sw = findVertexWithCoordinates(uBuffer, vBuffer, 0, 0); expect(sw).not.toBe(-1); const nw = findVertexWithCoordinates(uBuffer, vBuffer, 0, 1); expect(nw).not.toBe(-1); const se = findVertexWithCoordinates(uBuffer, vBuffer, 1, 0); expect(se).not.toBe(-1); const ne = findVertexWithCoordinates(uBuffer, vBuffer, 1, 1); expect(ne).not.toBe(-1); const nwToSe = hasTriangle(ib, sw, se, nw) && hasTriangle(ib, nw, se, ne); const swToNe = hasTriangle(ib, sw, ne, nw) && hasTriangle(ib, sw, se, ne); expect(nwToSe || swToNe).toBe(true); } }); }); it("oct-encoded normals works for all four children of a simple quad", function() { const data = new import__305.QuantizedMeshTerrainData({ minimumHeight: 0, maximumHeight: 4, quantizedVertices: new Uint16Array([ // order is sw nw se ne // u 0, 0, 32767, 32767, // v 0, 32767, 0, 32767, // heights 32767 / 4, 2 * 32767 / 4, 3 * 32767 / 4, 32767 ]), encodedNormals: new Uint8Array([ // fun property of oct-encoded normals: the octrahedron is projected onto a plane // and unfolded into a unit square. The 4 corners of this unit square are encoded values // of the same Cartesian normal, vec3(0.0, 0.0, 1.0). // Therefore, all 4 normals below are actually oct-encoded representations of vec3(0.0, 0.0, 1.0) 255, 0, // sw 255, 255, // nw 255, 0, // se 255, 255 // ne ]), indices: new Uint16Array([0, 3, 1, 0, 2, 3]), boundingSphere: new import__305.BoundingSphere(), horizonOcclusionPoint: new import__305.Cartesian3(), westIndices: [], southIndices: [], eastIndices: [], northIndices: [], westSkirtHeight: 1, southSkirtHeight: 1, eastSkirtHeight: 1, northSkirtHeight: 1, childTileMask: 15 }); const tilingScheme = new import__305.GeographicTilingScheme(); return Promise.resolve( data.createMesh({ tilingScheme, x: 0, y: 0, level: 0 }) ).then(function() { const swPromise = data.upsample(tilingScheme, 0, 0, 0, 0, 0, 1); const sePromise = data.upsample(tilingScheme, 0, 0, 0, 1, 0, 1); const nwPromise = data.upsample(tilingScheme, 0, 0, 0, 0, 1, 1); const nePromise = data.upsample(tilingScheme, 0, 0, 0, 1, 1, 1); return Promise.all([swPromise, sePromise, nwPromise, nePromise]); }).then(function(upsampleResults) { expect(upsampleResults.length).toBe(4); for (let i = 0; i < upsampleResults.length; ++i) { const upsampled = upsampleResults[i]; expect(upsampled).toBeDefined(); const encodedNormals = upsampled._encodedNormals; expect(encodedNormals.length).toBe(8); for (let n = 0; n < encodedNormals.length; ++n) { expect(encodedNormals[i]).toBe(255); } } }); }); it("works for a quad with an extra vertex in the northwest child", function() { const data = new import__305.QuantizedMeshTerrainData({ minimumHeight: 0, maximumHeight: 6, quantizedVertices: new Uint16Array([ // order is sw, nw, se, ne, extra vertex in nw quadrant // u 0, 0, 32767, 32767, 0.125 * 32767, // v 0, 32767, 0, 32767, 0.75 * 32767, // heights 32767 / 6, 2 * 32767 / 6, 3 * 32767 / 6, 4 * 32767 / 6, 32767 ]), indices: new Uint16Array([0, 4, 1, 0, 2, 4, 1, 4, 3, 3, 4, 2]), boundingSphere: new import__305.BoundingSphere(), horizonOcclusionPoint: new import__305.Cartesian3(), westIndices: [], southIndices: [], eastIndices: [], northIndices: [], westSkirtHeight: 1, southSkirtHeight: 1, eastSkirtHeight: 1, northSkirtHeight: 1, childTileMask: 15 }); const tilingScheme = new import__305.GeographicTilingScheme(); return Promise.resolve( data.createMesh({ tilingScheme, x: 0, y: 0, level: 0 }) ).then(function() { return data.upsample(tilingScheme, 0, 0, 0, 0, 0, 1); }).then(function(upsampled) { const uBuffer = upsampled._uValues; const vBuffer = upsampled._vValues; const ib = upsampled._indices; expect(uBuffer.length).toBe(9); expect(vBuffer.length).toBe(9); expect(upsampled._heightValues.length).toBe(9); expect(ib.length).toBe(8 * 3); const sw = findVertexWithCoordinates(uBuffer, vBuffer, 0, 0); expect(sw).not.toBe(-1); const nw = findVertexWithCoordinates(uBuffer, vBuffer, 0, 1); expect(nw).not.toBe(-1); const se = findVertexWithCoordinates(uBuffer, vBuffer, 1, 0); expect(se).not.toBe(-1); const ne = findVertexWithCoordinates(uBuffer, vBuffer, 1, 1); expect(ne).not.toBe(-1); const extra = findVertexWithCoordinates(uBuffer, vBuffer, 0.25, 0.5); expect(extra).not.toBe(-1); const v40 = findVertexWithCoordinates( uBuffer, vBuffer, horizontalIntercept(0, 0, 0.125, 0.75) * 2, 0 ); expect(v40).not.toBe(-1); const v42 = findVertexWithCoordinates( uBuffer, vBuffer, horizontalIntercept( 0.5, verticalIntercept(1, 0, 0.125, 0.75), 0.125, 0.75 ) * 2, 0 ); expect(v42).not.toBe(-1); const v402 = findVertexWithCoordinates( uBuffer, vBuffer, horizontalIntercept(0.5, 0, 0.125, 0.75) * 2, 0 ); expect(v402).not.toBe(-1); const v43 = findVertexWithCoordinates( uBuffer, vBuffer, 1, verticalIntercept(1, 1, 0.125, 0.75) * 2 - 1 ); expect(v43).not.toBe(-1); expect(hasTriangle(ib, sw, extra, nw)).toBe(true); expect(hasTriangle(ib, sw, v40, extra)).toBe(true); expect(hasTriangle(ib, v40, v402, extra)).toBe(true); expect(hasTriangle(ib, v402, v42, extra)).toBe(true); expect(hasTriangle(ib, extra, v42, v43)).toBe(true); expect(hasTriangle(ib, v42, se, v43)).toBe(true); expect(hasTriangle(ib, nw, v43, ne)).toBe(true); expect(hasTriangle(ib, nw, extra, v43)).toBe(true); }); }); it("works for a quad with an extra vertex on the splitting plane", function() { const data = new import__305.QuantizedMeshTerrainData({ minimumHeight: 0, maximumHeight: 6, quantizedVertices: new Uint16Array([ // order is sw, nw, se, ne, extra vertex in nw quadrant // u 0, 0, 32767, 32767, 0.5 * 32767, // v 0, 32767, 0, 32767, 0.75 * 32767, // heights 32767 / 6, 2 * 32767 / 6, 3 * 32767 / 6, 4 * 32767 / 6, 32767 ]), indices: new Uint16Array([0, 4, 1, 1, 4, 3, 0, 2, 4, 3, 4, 2]), boundingSphere: new import__305.BoundingSphere(), horizonOcclusionPoint: new import__305.Cartesian3(), westIndices: [], southIndices: [], eastIndices: [], northIndices: [], westSkirtHeight: 1, southSkirtHeight: 1, eastSkirtHeight: 1, northSkirtHeight: 1, childTileMask: 15 }); const tilingScheme = new import__305.GeographicTilingScheme(); return Promise.resolve( data.createMesh({ tilingScheme, x: 0, y: 0, level: 0 }) ).then(function() { const nwPromise = data.upsample(tilingScheme, 0, 0, 0, 0, 0, 1); const nePromise = data.upsample(tilingScheme, 0, 0, 0, 1, 0, 1); return Promise.all([nwPromise, nePromise]); }).then(function(upsampleResults) { expect(upsampleResults.length).toBe(2); let uBuffer, vBuffer; for (let i = 0; i < upsampleResults.length; i++) { const upsampled = upsampleResults[i]; expect(upsampled).toBeDefined(); uBuffer = upsampled._uValues; vBuffer = upsampled._vValues; const ib = upsampled._indices; expect(uBuffer.length).toBe(6); expect(vBuffer.length).toBe(6); expect(upsampled._heightValues.length).toBe(6); expect(ib.length).toBe(4 * 3); const sw = findVertexWithCoordinates(uBuffer, vBuffer, 0, 0); expect(sw).not.toBe(-1); const nw = findVertexWithCoordinates(uBuffer, vBuffer, 0, 1); expect(nw).not.toBe(-1); const se = findVertexWithCoordinates(uBuffer, vBuffer, 1, 0); expect(se).not.toBe(-1); const ne = findVertexWithCoordinates(uBuffer, vBuffer, 1, 1); expect(ne).not.toBe(-1); } uBuffer = upsampleResults[0]._uValues; vBuffer = upsampleResults[0]._vValues; let extra = findVertexWithCoordinates(uBuffer, vBuffer, 1, 0.5); expect(extra).not.toBe(-1); const v40 = findVertexWithCoordinates( uBuffer, vBuffer, horizontalIntercept(0, 0, 0.5, 0.75) * 2, 0 ); expect(v40).not.toBe(-1); expect(upsampleResults[0]._westIndices.length).toBe(2); expect(upsampleResults[0]._eastIndices.length).toBe(3); expect(upsampleResults[0]._northIndices.length).toBe(2); expect(upsampleResults[0]._southIndices.length).toBe(3); uBuffer = upsampleResults[1]._uValues; vBuffer = upsampleResults[1]._vValues; extra = findVertexWithCoordinates(uBuffer, vBuffer, 0, 0.5); expect(extra).not.toBe(-1); const v42 = findVertexWithCoordinates( uBuffer, vBuffer, horizontalIntercept(1, 0, 0.5, 0.75) * 0.5, 0 ); expect(v42).not.toBe(-1); expect(upsampleResults[1]._westIndices.length).toBe(3); expect(upsampleResults[1]._eastIndices.length).toBe(2); expect(upsampleResults[1]._northIndices.length).toBe(2); expect(upsampleResults[1]._southIndices.length).toBe(3); }); }); }); describe("createMesh", function() { let data; let tilingScheme; function createSampleTerrainData() { return new import__305.QuantizedMeshTerrainData({ minimumHeight: 0, maximumHeight: 4, quantizedVertices: new Uint16Array([ // order is sw nw se ne // u 0, 0, 32767, 32767, // v 0, 32767, 0, 32767, // heights 32767 / 4, 2 * 32767 / 4, 3 * 32767 / 4, 32767 ]), indices: new Uint16Array([0, 3, 1, 0, 2, 3]), boundingSphere: new import__305.BoundingSphere(), horizonOcclusionPoint: new import__305.Cartesian3(), westIndices: [0, 1], southIndices: [0, 1], eastIndices: [2, 3], northIndices: [1, 3], westSkirtHeight: 1, southSkirtHeight: 1, eastSkirtHeight: 1, northSkirtHeight: 1, childTileMask: 15 }); } beforeEach(function() { tilingScheme = new import__305.GeographicTilingScheme(); data = createSampleTerrainData(); }); it("requires tilingScheme", function() { expect(function() { data.createMesh({ tilingScheme: void 0, x: 0, y: 0, level: 0 }); }).toThrowDeveloperError(); }); it("requires x", function() { expect(function() { data.createMesh({ tilingScheme, x: void 0, y: 0, level: 0 }); }).toThrowDeveloperError(); }); it("requires y", function() { expect(function() { data.createMesh({ tilingScheme, x: 0, y: void 0, level: 0 }); }).toThrowDeveloperError(); }); it("requires level", function() { expect(function() { data.createMesh({ tilingScheme, x: 0, y: 0, level: void 0 }); }).toThrowDeveloperError(); }); it("creates specified vertices plus skirt vertices", function() { return data.createMesh({ tilingScheme, x: 0, y: 0, level: 0 }).then(function(mesh) { expect(mesh).toBeInstanceOf(import__305.TerrainMesh); expect(mesh.vertices.length).toBe(12 * mesh.encoding.stride); expect(mesh.indices.length).toBe(10 * 3); expect(mesh.minimumHeight).toBe(data._minimumHeight); expect(mesh.maximumHeight).toBe(data._maximumHeight); expect(mesh.boundingSphere3D).toEqual(data._boundingSphere); }); }); it("exaggerates mesh", function() { return data.createMesh({ tilingScheme, x: 0, y: 0, level: 0, exaggeration: 2 }).then(function(mesh) { expect(mesh).toBeInstanceOf(import__305.TerrainMesh); expect(mesh.vertices.length).toBe(12 * mesh.encoding.stride); expect(mesh.indices.length).toBe(10 * 3); expect(mesh.minimumHeight).toBe(data._minimumHeight); expect(mesh.maximumHeight).toBe(data._maximumHeight); expect(mesh.boundingSphere3D.radius).toBe( data._boundingSphere.radius ); expect(mesh.encoding.exaggeration).toBe(2); }); }); it("requires 32bit indices for large meshes", function() { const tilingScheme2 = new import__305.GeographicTilingScheme(); const quantizedVertices = []; let i; for (i = 0; i < 65 * 1024; i++) { quantizedVertices.push(i % 32767); } for (i = 0; i < 65 * 1024; i++) { quantizedVertices.push(Math.floor(i / 32767)); } for (i = 0; i < 65 * 1024; i++) { quantizedVertices.push(0); } const data2 = new import__305.QuantizedMeshTerrainData({ minimumHeight: 0, maximumHeight: 4, quantizedVertices: new Uint16Array(quantizedVertices), indices: new Uint32Array([0, 3, 1, 0, 2, 3, 65e3, 65002, 65003]), boundingSphere: new import__305.BoundingSphere(), horizonOcclusionPoint: new import__305.Cartesian3(), westIndices: [0, 1], southIndices: [0, 1], eastIndices: [2, 3], northIndices: [1, 3], westSkirtHeight: 1, southSkirtHeight: 1, eastSkirtHeight: 1, northSkirtHeight: 1, childTileMask: 15 }); return data2.createMesh({ tilingScheme: tilingScheme2, x: 0, y: 0, level: 0 }).then(function(mesh) { expect(mesh).toBeInstanceOf(import__305.TerrainMesh); expect(mesh.indices.BYTES_PER_ELEMENT).toBe(4); }); }); it("enables throttling for asynchronous tasks", function() { const options = { tilingScheme, x: 0, y: 0, level: 0, throttle: true }; const taskCount = import__305.TerrainData.maximumAsynchronousTasks + 1; const promises = new Array(); for (let i = 0; i < taskCount; i++) { const tempData = createSampleTerrainData(); const promise = tempData.createMesh(options); if ((0, import__305.defined)(promise)) { promises.push(promise); } } expect(promises.length).toBe(import__305.TerrainData.maximumAsynchronousTasks); return Promise.all(promises); }); it("disables throttling for asynchronous tasks", function() { const options = { tilingScheme, x: 0, y: 0, level: 0, throttle: false }; const taskCount = import__305.TerrainData.maximumAsynchronousTasks + 1; const promises = new Array(); for (let i = 0; i < taskCount; i++) { const tempData = createSampleTerrainData(); const promise = tempData.createMesh(options); if ((0, import__305.defined)(promise)) { promises.push(promise); } } expect(promises.length).toBe(taskCount); return Promise.all(promises); }); }); describe("interpolateHeight", function() { let tilingScheme; let rectangle; beforeEach(function() { tilingScheme = new import__305.GeographicTilingScheme(); rectangle = tilingScheme.tileXYToRectangle(7, 6, 5); }); it("clamps coordinates if given a position outside the mesh", function() { const mesh = new import__305.QuantizedMeshTerrainData({ minimumHeight: 0, maximumHeight: 4, quantizedVertices: new Uint16Array([ // order is sw nw se ne // u 0, 0, 32767, 32767, // v 0, 32767, 0, 32767, // heights 32767 / 4, 2 * 32767 / 4, 3 * 32767 / 4, 32767 ]), indices: new Uint16Array([0, 3, 1, 0, 2, 3]), boundingSphere: new import__305.BoundingSphere(), horizonOcclusionPoint: new import__305.Cartesian3(), westIndices: [0, 1], southIndices: [0, 1], eastIndices: [2, 3], northIndices: [1, 3], westSkirtHeight: 1, southSkirtHeight: 1, eastSkirtHeight: 1, northSkirtHeight: 1, childTileMask: 15 }); expect(mesh.interpolateHeight(rectangle, 0, 0)).toBe( mesh.interpolateHeight(rectangle, rectangle.east, rectangle.south) ); }); it("returns a height interpolated from the correct triangle", function() { const mesh = new import__305.QuantizedMeshTerrainData({ minimumHeight: -16384, maximumHeight: 16383, quantizedVertices: new Uint16Array([ // order is sw nw se ne // u 0, 0, 32767, 32767, // v 0, 32767, 0, 32767, // heights 16384, 0, 32767, 16384 ]), indices: new Uint16Array([0, 3, 1, 0, 2, 3]), boundingSphere: new import__305.BoundingSphere(), horizonOcclusionPoint: new import__305.Cartesian3(), westIndices: [0, 1], southIndices: [0, 1], eastIndices: [2, 3], northIndices: [1, 3], westSkirtHeight: 1, southSkirtHeight: 1, eastSkirtHeight: 1, northSkirtHeight: 1, childTileMask: 15 }); let longitude = rectangle.west + (rectangle.east - rectangle.west) * 0.25; let latitude = rectangle.south + (rectangle.north - rectangle.south) * 0.75; let result = mesh.interpolateHeight(rectangle, longitude, latitude); expect(result).toBeLessThan(0); longitude = rectangle.west + (rectangle.east - rectangle.west) * 0.75; latitude = rectangle.south + (rectangle.north - rectangle.south) * 0.25; result = mesh.interpolateHeight(rectangle, longitude, latitude); expect(result).toBeGreaterThan(0); longitude = rectangle.west + (rectangle.east - rectangle.west) * 0.5; latitude = rectangle.south + (rectangle.north - rectangle.south) * 0.5; result = mesh.interpolateHeight(rectangle, longitude, latitude); expect(result).toEqualEpsilon(0, 1e-10); }); }); describe("isChildAvailable", function() { let data; beforeEach(function() { data = new import__305.QuantizedMeshTerrainData({ minimumHeight: -16384, maximumHeight: 16383, quantizedVertices: new Uint16Array([ // order is sw nw se ne // u 0, 0, 32767, 32767, // v 0, 32767, 0, 32767, // heights 16384, 0, 32767, 16384 ]), indices: new Uint16Array([0, 3, 1, 0, 2, 3]), boundingSphere: new import__305.BoundingSphere(), horizonOcclusionPoint: new import__305.Cartesian3(), westIndices: [0, 1], southIndices: [0, 1], eastIndices: [2, 3], northIndices: [1, 3], westSkirtHeight: 1, southSkirtHeight: 1, eastSkirtHeight: 1, northSkirtHeight: 1, childTileMask: 15 }); }); it("requires thisX", function() { expect(function() { data.isChildAvailable(void 0, 0, 0, 0); }).toThrowDeveloperError(); }); it("requires thisY", function() { expect(function() { data.isChildAvailable(0, void 0, 0, 0); }).toThrowDeveloperError(); }); it("requires childX", function() { expect(function() { data.isChildAvailable(0, 0, void 0, 0); }).toThrowDeveloperError(); }); it("requires childY", function() { expect(function() { data.isChildAvailable(0, 0, 0, void 0); }).toThrowDeveloperError(); }); it("returns true for all children when child mask is not explicitly specified", function() { data = new import__305.QuantizedMeshTerrainData({ minimumHeight: -16384, maximumHeight: 16383, quantizedVertices: new Uint16Array([ // order is sw nw se ne // u 0, 0, 32767, 32767, // v 0, 32767, 0, 32767, // heights 16384, 0, 32767, 16384 ]), indices: new Uint16Array([0, 3, 1, 0, 2, 3]), boundingSphere: new import__305.BoundingSphere(), horizonOcclusionPoint: new import__305.Cartesian3(), westIndices: [0, 1], southIndices: [0, 1], eastIndices: [2, 3], northIndices: [1, 3], westSkirtHeight: 1, southSkirtHeight: 1, eastSkirtHeight: 1, northSkirtHeight: 1 }); expect(data.isChildAvailable(10, 20, 20, 40)).toBe(true); expect(data.isChildAvailable(10, 20, 21, 40)).toBe(true); expect(data.isChildAvailable(10, 20, 20, 41)).toBe(true); expect(data.isChildAvailable(10, 20, 21, 41)).toBe(true); }); it("works when only southwest child is available", function() { data = new import__305.QuantizedMeshTerrainData({ minimumHeight: -16384, maximumHeight: 16383, quantizedVertices: new Uint16Array([ // order is sw nw se ne // u 0, 0, 32767, 32767, // v 0, 32767, 0, 32767, // heights 16384, 0, 32767, 16384 ]), indices: new Uint16Array([0, 3, 1, 0, 2, 3]), boundingSphere: new import__305.BoundingSphere(), horizonOcclusionPoint: new import__305.Cartesian3(), westIndices: [0, 1], southIndices: [0, 1], eastIndices: [2, 3], northIndices: [1, 3], westSkirtHeight: 1, southSkirtHeight: 1, eastSkirtHeight: 1, northSkirtHeight: 1, childTileMask: 1 }); expect(data.isChildAvailable(10, 20, 20, 40)).toBe(false); expect(data.isChildAvailable(10, 20, 21, 40)).toBe(false); expect(data.isChildAvailable(10, 20, 20, 41)).toBe(true); expect(data.isChildAvailable(10, 20, 21, 41)).toBe(false); }); it("works when only southeast child is available", function() { data = new import__305.QuantizedMeshTerrainData({ minimumHeight: -16384, maximumHeight: 16383, quantizedVertices: new Uint16Array([ // order is sw nw se ne // u 0, 0, 32767, 32767, // v 0, 32767, 0, 32767, // heights 16384, 0, 32767, 16384 ]), indices: new Uint16Array([0, 3, 1, 0, 2, 3]), boundingSphere: new import__305.BoundingSphere(), horizonOcclusionPoint: new import__305.Cartesian3(), westIndices: [0, 1], southIndices: [0, 1], eastIndices: [2, 3], northIndices: [1, 3], westSkirtHeight: 1, southSkirtHeight: 1, eastSkirtHeight: 1, northSkirtHeight: 1, childTileMask: 2 }); expect(data.isChildAvailable(10, 20, 20, 40)).toBe(false); expect(data.isChildAvailable(10, 20, 21, 40)).toBe(false); expect(data.isChildAvailable(10, 20, 20, 41)).toBe(false); expect(data.isChildAvailable(10, 20, 21, 41)).toBe(true); }); it("works when only northwest child is available", function() { data = new import__305.QuantizedMeshTerrainData({ minimumHeight: -16384, maximumHeight: 16383, quantizedVertices: new Uint16Array([ // order is sw nw se ne // u 0, 0, 32767, 32767, // v 0, 32767, 0, 32767, // heights 16384, 0, 32767, 16384 ]), indices: new Uint16Array([0, 3, 1, 0, 2, 3]), boundingSphere: new import__305.BoundingSphere(), horizonOcclusionPoint: new import__305.Cartesian3(), westIndices: [0, 1], southIndices: [0, 1], eastIndices: [2, 3], northIndices: [1, 3], westSkirtHeight: 1, southSkirtHeight: 1, eastSkirtHeight: 1, northSkirtHeight: 1, childTileMask: 4 }); expect(data.isChildAvailable(10, 20, 20, 40)).toBe(true); expect(data.isChildAvailable(10, 20, 21, 40)).toBe(false); expect(data.isChildAvailable(10, 20, 20, 41)).toBe(false); expect(data.isChildAvailable(10, 20, 21, 41)).toBe(false); }); it("works when only northeast child is available", function() { data = new import__305.QuantizedMeshTerrainData({ minimumHeight: -16384, maximumHeight: 16383, quantizedVertices: new Uint16Array([ // order is sw nw se ne // u 0, 0, 32767, 32767, // v 0, 32767, 0, 32767, // heights 16384, 0, 32767, 16384 ]), indices: new Uint16Array([0, 3, 1, 0, 2, 3]), boundingSphere: new import__305.BoundingSphere(), horizonOcclusionPoint: new import__305.Cartesian3(), westIndices: [0, 1], southIndices: [0, 1], eastIndices: [2, 3], northIndices: [1, 3], westSkirtHeight: 1, southSkirtHeight: 1, eastSkirtHeight: 1, northSkirtHeight: 1, childTileMask: 8 }); expect(data.isChildAvailable(10, 20, 20, 40)).toBe(false); expect(data.isChildAvailable(10, 20, 21, 40)).toBe(true); expect(data.isChildAvailable(10, 20, 20, 41)).toBe(false); expect(data.isChildAvailable(10, 20, 21, 41)).toBe(false); }); }); }); // packages/engine/Specs/Core/QuarticRealPolynomialSpec.js var import__307 = __toESM(require_Cesium(), 1); var import__308 = __toESM(require_Cesium(), 1); describe("Core/QuarticRealPolynomial", function() { it("discriminant throws without a", function() { expect(function() { import__307.QuarticRealPolynomial.computeDiscriminant(); }).toThrowDeveloperError(); }); it("discriminant throws without b", function() { expect(function() { import__307.QuarticRealPolynomial.computeDiscriminant(1); }).toThrowDeveloperError(); }); it("discriminant throws without c", function() { expect(function() { import__307.QuarticRealPolynomial.computeDiscriminant(1, 1); }).toThrowDeveloperError(); }); it("discriminant throws without d", function() { expect(function() { import__307.QuarticRealPolynomial.computeDiscriminant(1, 1, 1); }).toThrowDeveloperError(); }); it("discriminant throws without e", function() { expect(function() { import__307.QuarticRealPolynomial.computeDiscriminant(1, 1, 1, 1); }).toThrowDeveloperError(); }); it("discriminant", function() { const a = 1; const b = 2; const c = 3; const d = 4; const e = 5; const a2 = a * a; const a3 = a2 * a; const b2 = b * b; const b3 = b2 * b; const c2 = c * c; const c3 = c2 * c; const d2 = d * d; const d3 = d2 * d; const e2 = e * e; const e3 = e2 * e; const expected = b2 * c2 * d2 - 4 * b3 * d3 - 4 * a * c3 * d2 + 18 * a * b * c * d3 - 27 * a2 * d2 * d2 + 256 * a3 * e3 + e * (18 * b3 * c * d - 4 * b2 * c3 + 16 * a * c2 * c2 - 80 * a * b * c2 * d - 6 * a * b2 * d2 + 144 * a2 * c * d2) + e2 * (144 * a * b2 * c - 27 * b2 * b2 - 128 * a2 * c2 - 192 * a2 * b * d); const actual = import__307.QuarticRealPolynomial.computeDiscriminant(a, b, c, d, e); expect(actual).toEqual(expected); }); it("real roots throws without a", function() { expect(function() { import__307.QuarticRealPolynomial.computeRealRoots(); }).toThrowDeveloperError(); }); it("real roots throws without b", function() { expect(function() { import__307.QuarticRealPolynomial.computeRealRoots(1); }).toThrowDeveloperError(); }); it("real roots throws without c", function() { expect(function() { import__307.QuarticRealPolynomial.computeRealRoots(1, 1); }).toThrowDeveloperError(); }); it("real roots throws without d", function() { expect(function() { import__307.QuarticRealPolynomial.computeRealRoots(1, 1, 1); }).toThrowDeveloperError(); }); it("real roots throws without e", function() { expect(function() { import__307.QuarticRealPolynomial.computeRealRoots(1, 1, 1, 1); }).toThrowDeveloperError(); }); it("four repeated roots", function() { const roots = import__307.QuarticRealPolynomial.computeRealRoots( 2, -16, 48, -64, 32 ); expect(roots.length).toEqual(4); expect(roots[0]).toEqualEpsilon(2, import__308.Math.EPSILON15); expect(roots[1]).toEqualEpsilon(2, import__308.Math.EPSILON15); expect(roots[2]).toEqualEpsilon(2, import__308.Math.EPSILON15); expect(roots[3]).toEqualEpsilon(2, import__308.Math.EPSILON15); }); it("two pairs of repeated roots", function() { const roots = import__307.QuarticRealPolynomial.computeRealRoots( 2, 0, -4, 0, 2 ); expect(roots.length).toEqual(4); expect(roots[0]).toEqualEpsilon(-1, import__308.Math.EPSILON15); expect(roots[1]).toEqualEpsilon(-1, import__308.Math.EPSILON15); expect(roots[2]).toEqualEpsilon(1, import__308.Math.EPSILON15); expect(roots[3]).toEqualEpsilon(1, import__308.Math.EPSILON15); }); it("one pair of repeated roots", function() { const roots = import__307.QuarticRealPolynomial.computeRealRoots( 2, -8, 16, -16, 6 ); expect(roots.length).toEqual(2); expect(roots[0]).toEqualEpsilon(1, import__308.Math.EPSILON14); expect(roots[1]).toEqualEpsilon(1, import__308.Math.EPSILON14); }); it("two unique and one pair of repeated roots", function() { const roots = import__307.QuarticRealPolynomial.computeRealRoots( 2, 8, -6, -20, 16 ); expect(roots.length).toEqual(4); expect(roots[0]).toEqualEpsilon(-4, import__308.Math.EPSILON15); expect(roots[1]).toEqualEpsilon(-2, import__308.Math.EPSILON15); expect(roots[2]).toEqualEpsilon(1, import__308.Math.EPSILON15); expect(roots[3]).toEqualEpsilon(1, import__308.Math.EPSILON15); }); it("four unique roots", function() { const roots = import__307.QuarticRealPolynomial.computeRealRoots( 2, 4, -26, -28, 48 ); expect(roots.length).toEqual(4); expect(roots[0]).toEqualEpsilon(-4, import__308.Math.EPSILON15); expect(roots[1]).toEqualEpsilon(-2, import__308.Math.EPSILON15); expect(roots[2]).toEqualEpsilon(1, import__308.Math.EPSILON15); expect(roots[3]).toEqualEpsilon(3, import__308.Math.EPSILON15); }); it("complex roots", function() { const roots = import__307.QuarticRealPolynomial.computeRealRoots( 3, -8, 14, -8, 3 ); expect(roots.length).toEqual(0); }); it("cubic case", function() { const roots = import__307.QuarticRealPolynomial.computeRealRoots( 0, 2, 6, -26, -30 ); expect(roots.length).toEqual(3); expect(roots[0]).toEqualEpsilon(-5, import__308.Math.EPSILON15); expect(roots[1]).toEqualEpsilon(-1, import__308.Math.EPSILON15); expect(roots[2]).toEqualEpsilon(3, import__308.Math.EPSILON15); }); it("stability 1", function() { const a = 1; const b = -27121.309311434146; const c = 0; const d = -26760.571078686513; const e = -1; const expected = [-37368410630733706e-21, 27121.3093478151]; const actual = import__307.QuarticRealPolynomial.computeRealRoots(a, b, c, d, e); expect(actual.length).toEqual(expected.length); expect(actual[0]).toEqualEpsilon(expected[0], import__308.Math.EPSILON12); expect(actual[1]).toEqualEpsilon(expected[1], import__308.Math.EPSILON12); }); it("stability 2", function() { const a = -1; const b = -26959.661445199898; const c = 0; const d = -26675.609408851604; const e = 1; const expected = [-26959.661481901538, 3748742710740771e-20]; const actual = import__307.QuarticRealPolynomial.computeRealRoots(a, b, c, d, e); expect(actual.length).toEqual(expected.length); expect(actual[0]).toEqualEpsilon(expected[0], import__308.Math.EPSILON11); expect(actual[1]).toEqualEpsilon(expected[1], import__308.Math.EPSILON11); }); it("stability 3", function() { const a = -1; const b = 20607.27053937226; const c = 0; const d = 20333.159863900513; const e = 1; const expected = [-4918074773740955e-20, 20607.27058725334]; const actual = import__307.QuarticRealPolynomial.computeRealRoots(a, b, c, d, e); expect(actual.length).toEqual(expected.length); expect(actual[0]).toEqualEpsilon(expected[0], import__308.Math.EPSILON11); expect(actual[1]).toEqualEpsilon(expected[1], import__308.Math.EPSILON11); }); }); // packages/engine/Specs/Core/QuaternionSpec.js var import__309 = __toESM(require_Cesium(), 1); var import__310 = __toESM(require_Cesium(), 1); describe("Core/Quaternion", function() { it("construct with default values", function() { const quaternion = new import__309.Quaternion(); expect(quaternion.x).toEqual(0); expect(quaternion.y).toEqual(0); expect(quaternion.z).toEqual(0); expect(quaternion.w).toEqual(0); }); it("construct with all values", function() { const quaternion = new import__309.Quaternion(1, 2, 3, 4); expect(quaternion.x).toEqual(1); expect(quaternion.y).toEqual(2); expect(quaternion.z).toEqual(3); expect(quaternion.w).toEqual(4); }); it("fromAxisAngle works without a result parameter", function() { const axis = new import__309.Cartesian3(0, 0, 1); const angle = import__310.Math.PI_OVER_TWO; const s = Math.sin(angle / 2); const c = Math.cos(angle / 2); const a = import__309.Cartesian3.multiplyByScalar(axis, s, new import__309.Cartesian3()); const expected = new import__309.Quaternion(a.x, a.y, a.z, c); const returnedResult = import__309.Quaternion.fromAxisAngle(axis, angle); expect(returnedResult).toEqual(expected); }); it("fromAxisAngle works with a result parameter", function() { const axis = new import__309.Cartesian3(0, 0, 1); const angle = import__310.Math.PI_OVER_TWO; const s = Math.sin(angle / 2); const c = Math.cos(angle / 2); const a = import__309.Cartesian3.multiplyByScalar(axis, s, new import__309.Cartesian3()); const result = new import__309.Quaternion(); const expected = new import__309.Quaternion(a.x, a.y, a.z, c); const returnedResult = import__309.Quaternion.fromAxisAngle(axis, angle, result); expect(result).toBe(returnedResult); expect(returnedResult).toEqual(expected); }); it("fromRotationMatrix works when m22 is max", function() { const q2 = import__309.Quaternion.fromAxisAngle( import__309.Cartesian3.negate(import__309.Cartesian3.UNIT_Z, new import__309.Cartesian3()), Math.PI ); const rotation = new import__309.Matrix3(-1, 0, 0, 0, -1, 0, 0, 0, 1); expect(import__309.Quaternion.fromRotationMatrix(rotation)).toEqualEpsilon( q2, import__310.Math.EPSILON15 ); }); it("fromRotationMatrix works when m11 is max", function() { const q2 = import__309.Quaternion.fromAxisAngle( import__309.Cartesian3.negate(import__309.Cartesian3.UNIT_Y, new import__309.Cartesian3()), Math.PI ); const rotation = new import__309.Matrix3(-1, 0, 0, 0, 1, 0, 0, 0, -1); expect(import__309.Quaternion.fromRotationMatrix(rotation)).toEqualEpsilon( q2, import__310.Math.EPSILON15 ); }); it("fromRotationMatrix works when m00 is max", function() { const q2 = import__309.Quaternion.fromAxisAngle( import__309.Cartesian3.negate(import__309.Cartesian3.UNIT_X, new import__309.Cartesian3()), Math.PI ); const rotation = new import__309.Matrix3(1, 0, 0, 0, -1, 0, 0, 0, -1); expect(import__309.Quaternion.fromRotationMatrix(rotation)).toEqualEpsilon( q2, import__310.Math.EPSILON15 ); }); it("fromRotationMatrix works when trace is greater than zero", function() { const rotation = new import__309.Matrix3(1, 0, 0, 0, 1, 0, 0, 0, 1); const q2 = new import__309.Quaternion(0, 0, 0, 1); expect(import__309.Quaternion.fromRotationMatrix(rotation)).toEqualEpsilon( q2, import__310.Math.EPSILON15 ); }); it("fromRotationMatrix works with result parameter", function() { const rotation = new import__309.Matrix3(1, 0, 0, 0, 1, 0, 0, 0, 1); const q2 = new import__309.Quaternion(0, 0, 0, 1); const result = new import__309.Quaternion(); const returnedResult = import__309.Quaternion.fromRotationMatrix(rotation, result); expect(returnedResult).toEqualEpsilon(q2, import__310.Math.EPSILON15); expect(returnedResult).toBe(result); }); it("fromRotationMatrix using a view matrix", function() { const direction = new import__309.Cartesian3( -0.2349326833984488, 0.8513513009480378, 0.46904967396353314 ); const up = new import__309.Cartesian3( 0.12477198625717335, -0.4521499177166376, 0.8831717858696695 ); const right = new import__309.Cartesian3( 0.9639702203483635, 0.26601017702986895, 6456422901079747e-25 ); const matrix = new import__309.Matrix3( right.x, right.y, right.z, up.x, up.y, up.z, -direction.x, -direction.y, -direction.z ); const quaternion = import__309.Quaternion.fromRotationMatrix(matrix); expect(import__309.Matrix3.fromQuaternion(quaternion)).toEqualEpsilon( matrix, import__310.Math.EPSILON12 ); }); it("fromHeadingPitchRoll with just heading", function() { const angle = import__310.Math.toRadians(20); const hpr = new import__309.HeadingPitchRoll(angle, 0, 0); const quaternion = import__309.Quaternion.fromHeadingPitchRoll(hpr); expect(import__309.Matrix3.fromQuaternion(quaternion)).toEqualEpsilon( import__309.Matrix3.fromRotationZ(-angle), import__310.Math.EPSILON11 ); }); it("fromHeadingPitchRoll with just pitch", function() { const angle = import__310.Math.toRadians(20); const hpr = new import__309.HeadingPitchRoll(0, angle, 0); const quaternion = import__309.Quaternion.fromHeadingPitchRoll(hpr); expect(import__309.Matrix3.fromQuaternion(quaternion)).toEqualEpsilon( import__309.Matrix3.fromRotationY(-angle), import__310.Math.EPSILON11 ); }); it("fromHeadingPitchRoll with just roll", function() { const angle = import__310.Math.toRadians(20); const hpr = new import__309.HeadingPitchRoll(0, 0, angle); const quaternion = import__309.Quaternion.fromHeadingPitchRoll(hpr); expect(import__309.Matrix3.fromQuaternion(quaternion)).toEqualEpsilon( import__309.Matrix3.fromRotationX(angle), import__310.Math.EPSILON11 ); }); it("fromHeadingPitchRoll with all angles (1)", function() { const angle = import__310.Math.toRadians(20); const hpr = new import__309.HeadingPitchRoll(angle, angle, angle); const quaternion = import__309.Quaternion.fromHeadingPitchRoll(hpr); const expected = import__309.Matrix3.fromRotationX(angle); import__309.Matrix3.multiply(import__309.Matrix3.fromRotationY(-angle), expected, expected); import__309.Matrix3.multiply(import__309.Matrix3.fromRotationZ(-angle), expected, expected); expect(import__309.Matrix3.fromQuaternion(quaternion)).toEqualEpsilon( expected, import__310.Math.EPSILON11 ); }); it("fromHeadingPitchRoll with all angles (2)", function() { const heading = import__310.Math.toRadians(180); const pitch = import__310.Math.toRadians(-45); const roll = import__310.Math.toRadians(45); const hpr = new import__309.HeadingPitchRoll(heading, pitch, roll); const quaternion = import__309.Quaternion.fromHeadingPitchRoll(hpr); const expected = import__309.Matrix3.fromRotationX(roll); import__309.Matrix3.multiply(import__309.Matrix3.fromRotationY(-pitch), expected, expected); import__309.Matrix3.multiply(import__309.Matrix3.fromRotationZ(-heading), expected, expected); expect(import__309.Matrix3.fromQuaternion(quaternion)).toEqualEpsilon( expected, import__310.Math.EPSILON11 ); }); it("fromHeadingPitchRoll works with result parameter", function() { const angle = import__310.Math.toRadians(20); const hpr = new import__309.HeadingPitchRoll(0, 0, angle); const result = new import__309.Quaternion(); const quaternion = import__309.Quaternion.fromHeadingPitchRoll(hpr, result); const expected = import__309.Quaternion.fromRotationMatrix( import__309.Matrix3.fromRotationX(angle) ); expect(quaternion).toBe(result); expect(quaternion).toEqualEpsilon(expected, import__310.Math.EPSILON11); }); it("clone without a result parameter", function() { const quaternion = new import__309.Quaternion(1, 2, 3, 4); const result = quaternion.clone(); expect(quaternion).not.toBe(result); expect(quaternion).toEqual(result); }); it("clone with a result parameter", function() { const quaternion = new import__309.Quaternion(1, 2, 3, 4); const result = new import__309.Quaternion(); const returnedResult = quaternion.clone(result); expect(quaternion).not.toBe(result); expect(result).toBe(returnedResult); expect(quaternion).toEqual(result); }); it("clone works with a result parameter that is an input parameter", function() { const quaternion = new import__309.Quaternion(1, 2, 3, 4); const returnedResult = quaternion.clone(quaternion); expect(quaternion).toBe(returnedResult); }); it("conjugate works", function() { const expected = new import__309.Quaternion(-1, -2, -3, 4); const quaternion = new import__309.Quaternion(1, 2, 3, 4); const result = new import__309.Quaternion(); const returnedResult = import__309.Quaternion.conjugate(quaternion, result); expect(result).toBe(returnedResult); expect(returnedResult).toEqual(expected); }); it("conjugate works with a result parameter that is an input parameter", function() { const expected = new import__309.Quaternion(-1, -2, -3, 4); const quaternion = new import__309.Quaternion(1, 2, 3, 4); const returnedResult = import__309.Quaternion.conjugate(quaternion, quaternion); expect(quaternion).toBe(returnedResult); expect(quaternion).toEqual(expected); }); it("magnitudeSquared computes correct result", function() { const expected = 2 * 2 + 3 * 3 + 4 * 4 + 5 * 5; const quaternion = new import__309.Quaternion(2, 3, 4, 5); const result = import__309.Quaternion.magnitudeSquared(quaternion); expect(result).toEqual(expected); }); it("norm computes correct result", function() { const expected = Math.sqrt(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5); const quaternion = new import__309.Quaternion(2, 3, 4, 5); const result = import__309.Quaternion.magnitude(quaternion); expect(result).toEqual(expected); }); it("normalize works", function() { const quaternion = new import__309.Quaternion(2, 0, 0, 0); const expectedResult = new import__309.Quaternion(1, 0, 0, 0); const result = new import__309.Quaternion(); const returnedResult = import__309.Quaternion.normalize(quaternion, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("normalize works with a result parameter that is an input parameter", function() { const quaternion = new import__309.Quaternion(2, 0, 0, 0); const expectedResult = new import__309.Quaternion(1, 0, 0, 0); const returnedResult = import__309.Quaternion.normalize(quaternion, quaternion); expect(quaternion).toBe(returnedResult); expect(quaternion).toEqual(expectedResult); }); it("inverse works", function() { const quaternion = new import__309.Quaternion(2, 3, 4, 5); const magnitudeSquared = import__309.Quaternion.magnitudeSquared(quaternion); const expected = new import__309.Quaternion( -2 / magnitudeSquared, -3 / magnitudeSquared, -4 / magnitudeSquared, 5 / magnitudeSquared ); const result = new import__309.Quaternion(); const returnedResult = import__309.Quaternion.inverse(quaternion, result); expect(returnedResult).toEqual(expected); expect(returnedResult).toBe(result); }); it("inverse works with a result parameter that is an input parameter", function() { const quaternion = new import__309.Quaternion(2, 3, 4, 5); const magnitudeSquared = import__309.Quaternion.magnitudeSquared(quaternion); const expected = new import__309.Quaternion( -2 / magnitudeSquared, -3 / magnitudeSquared, -4 / magnitudeSquared, 5 / magnitudeSquared ); const returnedResult = import__309.Quaternion.inverse(quaternion, quaternion); expect(returnedResult).toEqual(expected); expect(returnedResult).toBe(quaternion); }); it("dot", function() { const left = new import__309.Quaternion(2, 3, 6, 8); const right = new import__309.Quaternion(4, 5, 7, 9); const expectedResult = 137; const result = import__309.Quaternion.dot(left, right); expect(result).toEqual(expectedResult); }); it("multiply works", function() { const left = new import__309.Quaternion(1, 2, 3, 4); const right = new import__309.Quaternion(8, 7, 6, 5); const expected = new import__309.Quaternion(28, 56, 30, -20); const result = new import__309.Quaternion(); const returnedResult = import__309.Quaternion.multiply(left, right, result); expect(returnedResult).toEqual(expected); expect(result).toBe(returnedResult); }); it("multiply works with a result parameter that is an input parameter", function() { const left = new import__309.Quaternion(1, 2, 3, 4); const right = new import__309.Quaternion(8, 7, 6, 5); const expected = new import__309.Quaternion(28, 56, 30, -20); const returnedResult = import__309.Quaternion.multiply(left, right, left); expect(returnedResult).toEqual(expected); expect(left).toBe(returnedResult); }); it("add works", function() { const left = new import__309.Quaternion(2, 3, 6, 8); const right = new import__309.Quaternion(4, 5, 7, 9); const result = new import__309.Quaternion(); const expectedResult = new import__309.Quaternion(6, 8, 13, 17); const returnedResult = import__309.Quaternion.add(left, right, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("add works with a result parameter that is an input parameter", function() { const left = new import__309.Quaternion(2, 3, 6, 8); const right = new import__309.Quaternion(4, 5, 7, 9); const expectedResult = new import__309.Quaternion(6, 8, 13, 17); const returnedResult = import__309.Quaternion.add(left, right, left); expect(left).toBe(returnedResult); expect(left).toEqual(expectedResult); }); it("subtract works", function() { const left = new import__309.Quaternion(2, 3, 4, 8); const right = new import__309.Quaternion(1, 5, 7, 9); const result = new import__309.Quaternion(); const expectedResult = new import__309.Quaternion(1, -2, -3, -1); const returnedResult = import__309.Quaternion.subtract(left, right, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("subtract works with this result parameter", function() { const left = new import__309.Quaternion(2, 3, 4, 8); const right = new import__309.Quaternion(1, 5, 7, 9); const expectedResult = new import__309.Quaternion(1, -2, -3, -1); const returnedResult = import__309.Quaternion.subtract(left, right, left); expect(returnedResult).toBe(left); expect(left).toEqual(expectedResult); }); it("multiplyByScalar works ", function() { const quaternion = new import__309.Quaternion(1, 2, 3, 4); const result = new import__309.Quaternion(); const scalar = 2; const expectedResult = new import__309.Quaternion(2, 4, 6, 8); const returnedResult = import__309.Quaternion.multiplyByScalar( quaternion, scalar, result ); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("multiplyByScalar works with a result parameter that is an input parameter", function() { const quaternion = new import__309.Quaternion(1, 2, 3, 4); const scalar = 2; const expectedResult = new import__309.Quaternion(2, 4, 6, 8); const returnedResult = import__309.Quaternion.multiplyByScalar( quaternion, scalar, quaternion ); expect(quaternion).toBe(returnedResult); expect(quaternion).toEqual(expectedResult); }); it("divideByScalar works", function() { const quaternion = new import__309.Quaternion(1, 2, 3, 4); const result = new import__309.Quaternion(); const scalar = 2; const expectedResult = new import__309.Quaternion(0.5, 1, 1.5, 2); const returnedResult = import__309.Quaternion.divideByScalar( quaternion, scalar, result ); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("divideByScalar works with a result parameter that is an input parameter", function() { const quaternion = new import__309.Quaternion(1, 2, 3, 4); const scalar = 2; const expectedResult = new import__309.Quaternion(0.5, 1, 1.5, 2); const returnedResult = import__309.Quaternion.divideByScalar( quaternion, scalar, quaternion ); expect(quaternion).toBe(returnedResult); expect(quaternion).toEqual(expectedResult); }); it("axis works", function() { const angle = Math.PI / 3; const cos = Math.cos(angle / 2); const sin = Math.sin(angle / 2); const expected = import__309.Cartesian3.normalize( new import__309.Cartesian3(2, 3, 6), new import__309.Cartesian3() ); const quaternion = new import__309.Quaternion( sin * expected.x, sin * expected.y, sin * expected.z, cos ); const result = new import__309.Cartesian3(); const returnedResult = import__309.Quaternion.computeAxis(quaternion, result); expect(returnedResult).toEqualEpsilon(expected, import__310.Math.EPSILON15); expect(result).toBe(returnedResult); }); it("axis returns Cartesian3 (1,0,0) when w equals 1.0", function() { const expected = new import__309.Cartesian3(1, 0, 0); const quaternion = new import__309.Quaternion(4, 2, 3, 1); const result = new import__309.Cartesian3(1, 2, 3); const returnedResult = import__309.Quaternion.computeAxis(quaternion, result); expect(returnedResult).toEqual(expected); expect(result).toBe(returnedResult); }); it("axis returns Cartesian3 (1,0,0) when w equals -1.0", function() { const expected = new import__309.Cartesian3(1, 0, 0); const quaternion = new import__309.Quaternion(4, 2, 3, -1); const result = new import__309.Cartesian3(1, 2, 3); const returnedResult = import__309.Quaternion.computeAxis(quaternion, result); expect(returnedResult).toEqual(expected); expect(result).toBe(returnedResult); }); it("angle works", function() { const angle = Math.PI / 3; const cos = Math.cos(angle / 2); const sin = Math.sin(angle / 2); const axis = import__309.Cartesian3.normalize( new import__309.Cartesian3(2, 3, 6), new import__309.Cartesian3() ); const quaternion = new import__309.Quaternion( sin * axis.x, sin * axis.y, sin * axis.z, cos ); const result = import__309.Quaternion.computeAngle(quaternion); expect(result).toEqualEpsilon(angle, import__310.Math.EPSILON15); }); it("negate works", function() { const quaternion = new import__309.Quaternion(1, -2, -5, 4); const result = new import__309.Quaternion(); const expectedResult = new import__309.Quaternion(-1, 2, 5, -4); const returnedResult = import__309.Quaternion.negate(quaternion, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("negate works with a result parameter that is an input parameter", function() { const quaternion = new import__309.Quaternion(1, -2, -5); const expectedResult = new import__309.Quaternion(-1, 2, 5); const returnedResult = import__309.Quaternion.negate(quaternion, quaternion); expect(quaternion).toBe(returnedResult); expect(quaternion).toEqual(expectedResult); }); it("lerp works", function() { const start = new import__309.Quaternion(4, 8, 10, 20); const end = new import__309.Quaternion(8, 20, 20, 30); const t = 0.25; const result = new import__309.Quaternion(); const expectedResult = new import__309.Quaternion(5, 11, 12.5, 22.5); const returnedResult = import__309.Quaternion.lerp(start, end, t, result); expect(result).toBe(returnedResult); expect(result).toEqual(expectedResult); }); it("lerp works with a result parameter that is an input parameter", function() { const start = new import__309.Quaternion(4, 8, 10, 20); const end = new import__309.Quaternion(8, 20, 20, 30); const t = 0.25; const expectedResult = new import__309.Quaternion(5, 11, 12.5, 22.5); const returnedResult = import__309.Quaternion.lerp(start, end, t, start); expect(start).toBe(returnedResult); expect(start).toEqual(expectedResult); }); it("lerp extrapolate forward", function() { const start = new import__309.Quaternion(4, 8, 10, 20); const end = new import__309.Quaternion(8, 20, 20, 30); const t = 2; const expectedResult = new import__309.Quaternion(12, 32, 30, 40); const result = import__309.Quaternion.lerp(start, end, t, new import__309.Quaternion()); expect(result).toEqual(expectedResult); }); it("lerp extrapolate backward", function() { const start = new import__309.Quaternion(4, 8, 10, 20); const end = new import__309.Quaternion(8, 20, 20, 30); const t = -1; const expectedResult = new import__309.Quaternion(0, -4, 0, 10); const result = import__309.Quaternion.lerp(start, end, t, new import__309.Quaternion()); expect(result).toEqual(expectedResult); }); it("slerp works", function() { const start = import__309.Quaternion.normalize( new import__309.Quaternion(0, 0, 0, 1), new import__309.Quaternion() ); const end = new import__309.Quaternion( 0, 0, Math.sin(import__310.Math.PI_OVER_FOUR), Math.cos(import__310.Math.PI_OVER_FOUR) ); const expected = new import__309.Quaternion( 0, 0, Math.sin(Math.PI / 8), Math.cos(Math.PI / 8) ); const result = new import__309.Quaternion(); const returnedResult = import__309.Quaternion.slerp(start, end, 0.5, result); expect(result).toEqualEpsilon(expected, import__310.Math.EPSILON15); expect(result).toBe(returnedResult); }); it("slerp works with a result parameter that is an input parameter", function() { const start = import__309.Quaternion.normalize( new import__309.Quaternion(0, 0, 0, 1), new import__309.Quaternion() ); const end = new import__309.Quaternion( 0, 0, Math.sin(import__310.Math.PI_OVER_FOUR), Math.cos(import__310.Math.PI_OVER_FOUR) ); const expected = new import__309.Quaternion( 0, 0, Math.sin(Math.PI / 8), Math.cos(Math.PI / 8) ); const returnedResult = import__309.Quaternion.slerp(start, end, 0.5, start); expect(start).toEqualEpsilon(expected, import__310.Math.EPSILON15); expect(start).toBe(returnedResult); }); it("slerp works with obtuse angles", function() { const start = import__309.Quaternion.normalize( new import__309.Quaternion(0, 0, 0, -1), new import__309.Quaternion() ); const end = new import__309.Quaternion( 0, 0, Math.sin(import__310.Math.PI_OVER_FOUR), Math.cos(import__310.Math.PI_OVER_FOUR) ); const expected = new import__309.Quaternion( 0, 0, -Math.sin(Math.PI / 8), -Math.cos(Math.PI / 8) ); expect(import__309.Quaternion.slerp(start, end, 0.5, new import__309.Quaternion())).toEqualEpsilon( expected, import__310.Math.EPSILON15 ); }); it("slerp uses lerp when dot product is close to 1", function() { const start = new import__309.Quaternion(0, 0, 0, 1); const end = new import__309.Quaternion(1, 2, 3, 1); const expected = new import__309.Quaternion(0.5, 1, 1.5, 1); const result = new import__309.Quaternion(); expect(import__309.Quaternion.slerp(start, end, 0, result)).toEqual(start); expect(import__309.Quaternion.slerp(start, end, 1, result)).toEqual(end); expect(import__309.Quaternion.slerp(start, end, 0.5, result)).toEqual(expected); }); it("slerp uses lerp when dot product is close to 1 and a result parameter", function() { const start = new import__309.Quaternion(0, 0, 0, 1); const end = new import__309.Quaternion(1, 2, 3, 1); const result = new import__309.Quaternion(); const actual = import__309.Quaternion.slerp(start, end, 0, result); expect(actual).toBe(result); expect(result).toEqual(start); }); it("log works", function() { const axis = import__309.Cartesian3.normalize( new import__309.Cartesian3(1, -1, 1), new import__309.Cartesian3() ); const angle = import__310.Math.PI_OVER_FOUR; const quat = import__309.Quaternion.fromAxisAngle(axis, angle); const result = new import__309.Cartesian3(); const log = import__309.Quaternion.log(quat, result); const expected = import__309.Cartesian3.multiplyByScalar( axis, angle * 0.5, new import__309.Cartesian3() ); expect(log).toBe(result); expect(log).toEqualEpsilon(expected, import__310.Math.EPSILON15); }); it("exp works", function() { const axis = import__309.Cartesian3.normalize( new import__309.Cartesian3(1, -1, 1), new import__309.Cartesian3() ); const angle = import__310.Math.PI_OVER_FOUR; const cartesian = import__309.Cartesian3.multiplyByScalar( axis, angle * 0.5, new import__309.Cartesian3() ); const result = new import__309.Quaternion(); const exp = import__309.Quaternion.exp(cartesian, result); const expected = import__309.Quaternion.fromAxisAngle(axis, angle); expect(exp).toBe(result); expect(exp).toEqualEpsilon(expected, import__310.Math.EPSILON15); }); it("squad and computeInnerQuadrangle work", function() { const q0 = import__309.Quaternion.fromAxisAngle(import__309.Cartesian3.UNIT_X, 0); const q1 = import__309.Quaternion.fromAxisAngle( import__309.Cartesian3.UNIT_X, import__310.Math.PI_OVER_FOUR ); const q2 = import__309.Quaternion.fromAxisAngle( import__309.Cartesian3.UNIT_Z, import__310.Math.PI_OVER_FOUR ); const q3 = import__309.Quaternion.fromAxisAngle( import__309.Cartesian3.UNIT_X, -import__310.Math.PI_OVER_FOUR ); const s1Result = new import__309.Quaternion(); const s1 = import__309.Quaternion.computeInnerQuadrangle(q0, q1, q2, s1Result); expect(s1).toBe(s1Result); const s2 = import__309.Quaternion.computeInnerQuadrangle(q1, q2, q3, new import__309.Quaternion()); const squadResult = new import__309.Quaternion(); const squad = import__309.Quaternion.squad(q1, q2, s1, s2, 0, squadResult); expect(squad).toBe(squadResult); expect(squad).toEqualEpsilon(q1, import__310.Math.EPSILON15); }); it("fastSlerp works", function() { const start = import__309.Quaternion.normalize( new import__309.Quaternion(0, 0, 0, 1), new import__309.Quaternion() ); const end = new import__309.Quaternion( 0, 0, Math.sin(import__310.Math.PI_OVER_FOUR), Math.cos(import__310.Math.PI_OVER_FOUR) ); const expected = new import__309.Quaternion( 0, 0, Math.sin(Math.PI / 8), Math.cos(Math.PI / 8) ); const result = new import__309.Quaternion(); const returnedResult = import__309.Quaternion.fastSlerp(start, end, 0.5, result); expect(result).toEqualEpsilon(expected, import__310.Math.EPSILON6); expect(result).toBe(returnedResult); }); it("fastSlerp works with a result parameter that is an input parameter", function() { const start = import__309.Quaternion.normalize( new import__309.Quaternion(0, 0, 0, 1), new import__309.Quaternion() ); const end = new import__309.Quaternion( 0, 0, Math.sin(import__310.Math.PI_OVER_FOUR), Math.cos(import__310.Math.PI_OVER_FOUR) ); const expected = new import__309.Quaternion( 0, 0, Math.sin(Math.PI / 8), Math.cos(Math.PI / 8) ); const returnedResult = import__309.Quaternion.fastSlerp(start, end, 0.5, start); expect(start).toEqualEpsilon(expected, import__310.Math.EPSILON6); expect(start).toBe(returnedResult); }); it("fastSlerp works with obtuse angles", function() { const start = import__309.Quaternion.normalize( new import__309.Quaternion(0, 0, 0, -1), new import__309.Quaternion() ); const end = new import__309.Quaternion( 0, 0, Math.sin(import__310.Math.PI_OVER_FOUR), Math.cos(import__310.Math.PI_OVER_FOUR) ); const expected = new import__309.Quaternion( 0, 0, -Math.sin(Math.PI / 8), -Math.cos(Math.PI / 8) ); expect( import__309.Quaternion.fastSlerp(start, end, 0.5, new import__309.Quaternion()) ).toEqualEpsilon(expected, import__310.Math.EPSILON6); }); it("fastSlerp vs slerp", function() { const start = import__309.Quaternion.normalize( new import__309.Quaternion(0, 0, 0, 1), new import__309.Quaternion() ); const end = new import__309.Quaternion( 0, 0, Math.sin(import__310.Math.PI_OVER_FOUR), Math.cos(import__310.Math.PI_OVER_FOUR) ); let expected = import__309.Quaternion.slerp(start, end, 0.25, new import__309.Quaternion()); let actual = import__309.Quaternion.fastSlerp(start, end, 0.25, new import__309.Quaternion()); expect(actual).toEqualEpsilon(expected, import__310.Math.EPSILON6); expected = import__309.Quaternion.slerp(start, end, 0.5, new import__309.Quaternion()); actual = import__309.Quaternion.fastSlerp(start, end, 0.5, new import__309.Quaternion()); expect(actual).toEqualEpsilon(expected, import__310.Math.EPSILON6); expected = import__309.Quaternion.slerp(start, end, 0.75, new import__309.Quaternion()); actual = import__309.Quaternion.fastSlerp(start, end, 0.75, new import__309.Quaternion()); expect(actual).toEqualEpsilon(expected, import__310.Math.EPSILON6); }); it("fastSquad works", function() { const q0 = import__309.Quaternion.fromAxisAngle(import__309.Cartesian3.UNIT_X, 0); const q1 = import__309.Quaternion.fromAxisAngle( import__309.Cartesian3.UNIT_X, import__310.Math.PI_OVER_FOUR ); const q2 = import__309.Quaternion.fromAxisAngle( import__309.Cartesian3.UNIT_Z, import__310.Math.PI_OVER_FOUR ); const q3 = import__309.Quaternion.fromAxisAngle( import__309.Cartesian3.UNIT_X, -import__310.Math.PI_OVER_FOUR ); const s1 = import__309.Quaternion.computeInnerQuadrangle(q0, q1, q2, new import__309.Quaternion()); const s2 = import__309.Quaternion.computeInnerQuadrangle(q1, q2, q3, new import__309.Quaternion()); const squadResult = new import__309.Quaternion(); const squad = import__309.Quaternion.fastSquad(q1, q2, s1, s2, 0, squadResult); expect(squad).toBe(squadResult); expect(squad).toEqualEpsilon(q1, import__310.Math.EPSILON6); }); it("fastSquad vs squad", function() { const q0 = import__309.Quaternion.fromAxisAngle(import__309.Cartesian3.UNIT_X, 0); const q1 = import__309.Quaternion.fromAxisAngle( import__309.Cartesian3.UNIT_X, import__310.Math.PI_OVER_FOUR ); const q2 = import__309.Quaternion.fromAxisAngle( import__309.Cartesian3.UNIT_Z, import__310.Math.PI_OVER_FOUR ); const q3 = import__309.Quaternion.fromAxisAngle( import__309.Cartesian3.UNIT_X, -import__310.Math.PI_OVER_FOUR ); const s1 = import__309.Quaternion.computeInnerQuadrangle(q0, q1, q2, new import__309.Quaternion()); const s2 = import__309.Quaternion.computeInnerQuadrangle(q1, q2, q3, new import__309.Quaternion()); let actual = import__309.Quaternion.fastSquad(q1, q2, s1, s2, 0.25, new import__309.Quaternion()); let expected = import__309.Quaternion.squad(q1, q2, s1, s2, 0.25, new import__309.Quaternion()); expect(actual).toEqualEpsilon(expected, import__310.Math.EPSILON6); actual = import__309.Quaternion.fastSquad(q1, q2, s1, s2, 0.5, new import__309.Quaternion()); expected = import__309.Quaternion.squad(q1, q2, s1, s2, 0.5, new import__309.Quaternion()); expect(actual).toEqualEpsilon(expected, import__310.Math.EPSILON6); actual = import__309.Quaternion.fastSquad(q1, q2, s1, s2, 0.75, new import__309.Quaternion()); expected = import__309.Quaternion.squad(q1, q2, s1, s2, 0.75, new import__309.Quaternion()); expect(actual).toEqualEpsilon(expected, import__310.Math.EPSILON6); }); it("equals", function() { const quaternion = new import__309.Quaternion(1, 2, 3, 4); expect( import__309.Quaternion.equals(quaternion, new import__309.Quaternion(1, 2, 3, 4)) ).toEqual(true); expect( import__309.Quaternion.equals(quaternion, new import__309.Quaternion(2, 2, 3, 4)) ).toEqual(false); expect( import__309.Quaternion.equals(quaternion, new import__309.Quaternion(2, 1, 3, 4)) ).toEqual(false); expect( import__309.Quaternion.equals(quaternion, new import__309.Quaternion(1, 2, 4, 4)) ).toEqual(false); expect( import__309.Quaternion.equals(quaternion, new import__309.Quaternion(1, 2, 3, 5)) ).toEqual(false); expect(import__309.Quaternion.equals(quaternion, void 0)).toEqual(false); }); it("equalsEpsilon", function() { const quaternion = new import__309.Quaternion(1, 2, 3, 4); expect( import__309.Quaternion.equalsEpsilon( quaternion, new import__309.Quaternion(1, 2, 3, 4), 0 ) ).toEqual(true); expect( import__309.Quaternion.equalsEpsilon( quaternion, new import__309.Quaternion(1, 2, 3, 4), 1 ) ).toEqual(true); expect( import__309.Quaternion.equalsEpsilon( quaternion, new import__309.Quaternion(2, 2, 3, 4), 1 ) ).toEqual(true); expect( import__309.Quaternion.equalsEpsilon( quaternion, new import__309.Quaternion(1, 3, 3, 4), 1 ) ).toEqual(true); expect( import__309.Quaternion.equalsEpsilon( quaternion, new import__309.Quaternion(1, 2, 4, 4), 1 ) ).toEqual(true); expect( import__309.Quaternion.equalsEpsilon( quaternion, new import__309.Quaternion(1, 2, 3, 5), 1 ) ).toEqual(true); expect( import__309.Quaternion.equalsEpsilon( quaternion, new import__309.Quaternion(2, 2, 3, 4), 0.99999 ) ).toEqual(false); expect( import__309.Quaternion.equalsEpsilon( quaternion, new import__309.Quaternion(1, 3, 3, 4), 0.99999 ) ).toEqual(false); expect( import__309.Quaternion.equalsEpsilon( quaternion, new import__309.Quaternion(1, 2, 4, 4), 0.99999 ) ).toEqual(false); expect( import__309.Quaternion.equalsEpsilon( quaternion, new import__309.Quaternion(1, 2, 3, 5), 0.99999 ) ).toEqual(false); expect(import__309.Quaternion.equalsEpsilon(quaternion, void 0, 1)).toEqual(false); }); it("toString", function() { const quaternion = new import__309.Quaternion(1.123, 2.345, 6.789, 6.123); expect(quaternion.toString()).toEqual("(1.123, 2.345, 6.789, 6.123)"); }); it("fromAxisAngle throws with undefined axis", function() { expect(function() { import__309.Quaternion.fromAxisAngle(void 0, 1); }).toThrowDeveloperError(); }); it("fromAxisAngle throws with non-numeric angle", function() { expect(function() { import__309.Quaternion.fromAxisAngle(import__309.Cartesian3.UNIT_X, {}); }).toThrowDeveloperError(); }); it("fromRotationMatrix throws with undefined matrix", function() { expect(function() { import__309.Quaternion.fromRotationMatrix(void 0); }).toThrowDeveloperError(); }); it("clone returns undefined with no parameter", function() { expect(import__309.Quaternion.clone()).toBeUndefined(); }); it("conjugate throws with no parameter", function() { expect(function() { import__309.Quaternion.conjugate(); }).toThrowDeveloperError(); }); it("magnitudeSquared throws with no parameter", function() { expect(function() { import__309.Quaternion.magnitudeSquared(); }).toThrowDeveloperError(); }); it("magnitude throws with no parameter", function() { expect(function() { import__309.Quaternion.magnitude(); }).toThrowDeveloperError(); }); it("normalize throws with no parameter", function() { expect(function() { import__309.Quaternion.normalize(); }).toThrowDeveloperError(); }); it("inverse throws with no parameter", function() { expect(function() { import__309.Quaternion.inverse(); }).toThrowDeveloperError(); }); it("dot throws with no left parameter", function() { expect(function() { import__309.Quaternion.dot(void 0, new import__309.Quaternion()); }).toThrowDeveloperError(); }); it("dot throws with no right parameter", function() { expect(function() { import__309.Quaternion.dot(new import__309.Quaternion(), void 0); }).toThrowDeveloperError(); }); it("multiply throws with no right parameter", function() { expect(function() { import__309.Quaternion.multiply(new import__309.Quaternion(), void 0); }).toThrowDeveloperError(); }); it("multiply throws with no left parameter", function() { expect(function() { import__309.Quaternion.multiply(void 0, new import__309.Quaternion()); }).toThrowDeveloperError(); }); it("add throws with no left parameter", function() { expect(function() { import__309.Quaternion.add(void 0, new import__309.Quaternion()); }).toThrowDeveloperError(); }); it("add throws with no right parameter", function() { expect(function() { import__309.Quaternion.add(new import__309.Quaternion(), void 0); }).toThrowDeveloperError(); }); it("subtract throws with no left parameter", function() { expect(function() { import__309.Quaternion.subtract(void 0, new import__309.Quaternion()); }).toThrowDeveloperError(); }); it("subtract throws with no right parameter", function() { expect(function() { import__309.Quaternion.subtract(new import__309.Quaternion(), void 0); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with no quaternion parameter", function() { expect(function() { import__309.Quaternion.multiplyByScalar(void 0, 2); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with no scalar parameter", function() { expect(function() { import__309.Quaternion.multiplyByScalar(new import__309.Quaternion(), void 0); }).toThrowDeveloperError(); }); it("divideByScalar throws with no quaternion parameter", function() { expect(function() { import__309.Quaternion.divideByScalar(void 0, 2); }).toThrowDeveloperError(); }); it("divideByScalar throws with no scalar parameter", function() { expect(function() { import__309.Quaternion.divideByScalar(new import__309.Quaternion(), void 0); }).toThrowDeveloperError(); }); it("axis throws with no parameter", function() { expect(function() { import__309.Quaternion.computeAxis(void 0); }).toThrowDeveloperError(); }); it("angle throws with no parameter", function() { expect(function() { import__309.Quaternion.computeAngle(void 0); }).toThrowDeveloperError(); }); it("negate throws with no quaternion parameter", function() { expect(function() { import__309.Quaternion.negate(void 0); }).toThrowDeveloperError(); }); it("lerp throws with no start parameter", function() { const end = new import__309.Quaternion(8, 20, 6); const t = 0.25; expect(function() { import__309.Quaternion.lerp(void 0, end, t); }).toThrowDeveloperError(); }); it("lerp throws with no end parameter", function() { const start = new import__309.Quaternion(4, 8, 6); const t = 0.25; expect(function() { import__309.Quaternion.lerp(start, void 0, t); }).toThrowDeveloperError(); }); it("lerp throws with no t parameter", function() { const start = new import__309.Quaternion(4, 8, 6, 7); const end = new import__309.Quaternion(8, 20, 6, 7); expect(function() { import__309.Quaternion.lerp(start, end, void 0); }).toThrowDeveloperError(); }); it("slerp throws with no start parameter", function() { const end = new import__309.Quaternion(8, 20, 6); const t = 0.25; expect(function() { import__309.Quaternion.slerp(void 0, end, t); }).toThrowDeveloperError(); }); it("slerp throws with no end parameter", function() { const start = new import__309.Quaternion(4, 8, 6); const t = 0.25; expect(function() { import__309.Quaternion.slerp(start, void 0, t); }).toThrowDeveloperError(); }); it("slerp throws with no t parameter", function() { const start = new import__309.Quaternion(4, 8, 6, 7); const end = new import__309.Quaternion(8, 20, 6, 7); expect(function() { import__309.Quaternion.slerp(start, end, void 0); }).toThrowDeveloperError(); }); it("log throws with no quaternion parameter", function() { expect(function() { import__309.Quaternion.log(); }).toThrowDeveloperError(); }); it("exp throws with no cartesian parameter", function() { expect(function() { import__309.Quaternion.exp(); }).toThrowDeveloperError(); }); it("computeInnerQuadrangle throws without q0, q1, or q2 parameter", function() { expect(function() { import__309.Quaternion.computeInnerQuadrangle(); }).toThrowDeveloperError(); }); it("squad throws without q0, q1, s0, or s1 parameter", function() { expect(function() { import__309.Quaternion.squad(); }).toThrowDeveloperError(); }); it("squad throws without t parameter", function() { expect(function() { import__309.Quaternion.squad( new import__309.Quaternion(), new import__309.Quaternion(), new import__309.Quaternion(), new import__309.Quaternion() ); }).toThrowDeveloperError(); }); it("conjugate throws with no result", function() { expect(function() { import__309.Quaternion.conjugate(new import__309.Quaternion()); }).toThrowDeveloperError(); }); it("add throws with no result", function() { expect(function() { import__309.Quaternion.add(new import__309.Quaternion(), new import__309.Quaternion()); }).toThrowDeveloperError(); }); it("subtract throws with no result", function() { expect(function() { import__309.Quaternion.subtract(new import__309.Quaternion(), new import__309.Quaternion()); }).toThrowDeveloperError(); }); it("negate throws with no result", function() { expect(function() { import__309.Quaternion.negate(new import__309.Quaternion()); }).toThrowDeveloperError(); }); it("multiply throws with no result", function() { expect(function() { import__309.Quaternion.multiply(new import__309.Quaternion(), new import__309.Quaternion()); }).toThrowDeveloperError(); }); it("multiplyByScalar throws with no result", function() { expect(function() { import__309.Quaternion.multiplyByScalar(new import__309.Quaternion(), 3); }).toThrowDeveloperError(); }); it("divideByScalar throws with no result", function() { expect(function() { import__309.Quaternion.divideByScalar(new import__309.Quaternion(), 3); }).toThrowDeveloperError(); }); it("axis throws with no result", function() { expect(function() { import__309.Quaternion.computeAxis(new import__309.Quaternion()); }).toThrowDeveloperError(); }); it("lerp throws with no result", function() { expect(function() { import__309.Quaternion.lerp(new import__309.Quaternion(), new import__309.Quaternion(), 2); }).toThrowDeveloperError(); }); it("slerp throws with no result", function() { expect(function() { import__309.Quaternion.slerp(new import__309.Quaternion(), new import__309.Quaternion(), 2); }).toThrowDeveloperError(); }); it("log throws with no result", function() { expect(function() { import__309.Quaternion.log(new import__309.Quaternion()); }).toThrowDeveloperError(); }); it("exp throws with no result", function() { expect(function() { import__309.Quaternion.exp(new import__309.Cartesian3()); }).toThrowDeveloperError(); }); it("computeInnerQuadrangle throws with no result", function() { expect(function() { import__309.Quaternion.computeInnerQuadrangle( new import__309.Quaternion(), new import__309.Quaternion(), new import__309.Quaternion() ); }).toThrowDeveloperError(); }); it("squad throws with no result", function() { expect(function() { import__309.Quaternion.squad( new import__309.Quaternion(), new import__309.Quaternion(), new import__309.Quaternion(), new import__309.Quaternion(), 3 ); }).toThrowDeveloperError(); }); it("fastSlerp throws with no start", function() { expect(function() { import__309.Quaternion.fastSlerp(); }).toThrowDeveloperError(); }); it("fastSlerp throws with no end", function() { expect(function() { import__309.Quaternion.fastSlerp(new import__309.Quaternion()); }).toThrowDeveloperError(); }); it("fastSlerp throws with no t", function() { expect(function() { import__309.Quaternion.fastSlerp(new import__309.Quaternion(), new import__309.Quaternion()); }).toThrowDeveloperError(); }); it("fastSlerp throws with no result", function() { expect(function() { import__309.Quaternion.fastSlerp(new import__309.Quaternion(), new import__309.Quaternion(), 2); }).toThrowDeveloperError(); }); it("fastSquad throws with no q0", function() { expect(function() { import__309.Quaternion.fastSquad(); }).toThrowDeveloperError(); }); it("fastSquad throws with no q1", function() { expect(function() { import__309.Quaternion.fastSquad(new import__309.Quaternion()); }).toThrowDeveloperError(); }); it("fastSquad throws with no s0", function() { expect(function() { import__309.Quaternion.fastSquad(new import__309.Quaternion(), new import__309.Quaternion()); }).toThrowDeveloperError(); }); it("fastSquad throws with no s1", function() { expect(function() { import__309.Quaternion.fastSquad( new import__309.Quaternion(), new import__309.Quaternion(), new import__309.Quaternion() ); }).toThrowDeveloperError(); }); it("fastSquad throws with no t", function() { expect(function() { import__309.Quaternion.fastSquad( new import__309.Quaternion(), new import__309.Quaternion(), new import__309.Quaternion(), new import__309.Quaternion() ); }).toThrowDeveloperError(); }); it("fastSquad throws with no result", function() { expect(function() { import__309.Quaternion.fastSquad( new import__309.Quaternion(), new import__309.Quaternion(), new import__309.Quaternion(), new import__309.Quaternion(), 3 ); }).toThrowDeveloperError(); }); const q = new import__309.Quaternion(1, 2, 3, 4); import__309.Quaternion.normalize(q, q); createPackableSpecs_default(import__309.Quaternion, q, [q.x, q.y, q.z, q.w]); }); // packages/engine/Specs/Core/QuaternionSplineSpec.js var import__311 = __toESM(require_Cesium(), 1); var import__312 = __toESM(require_Cesium(), 1); describe("Core/QuaternionSpline", function() { let points; let times; beforeEach(function() { points = [ import__311.Quaternion.fromAxisAngle(import__311.Cartesian3.UNIT_X, import__312.Math.PI_OVER_FOUR), import__311.Quaternion.fromAxisAngle(import__311.Cartesian3.UNIT_Z, import__312.Math.PI_OVER_FOUR), import__311.Quaternion.fromAxisAngle(import__311.Cartesian3.UNIT_X, -import__312.Math.PI_OVER_FOUR), import__311.Quaternion.fromAxisAngle(import__311.Cartesian3.UNIT_Y, import__312.Math.PI_OVER_FOUR) ]; times = [0, 1, 2, 3]; }); it("constructor throws without points or times", function() { expect(function() { return new import__311.QuaternionSpline(); }).toThrowDeveloperError(); }); it("constructor throws when control points length is less than 2", function() { expect(function() { return new import__311.QuaternionSpline({ points: [import__311.Quaternion.ZERO] }); }).toThrowDeveloperError(); }); it("constructor throws when times.length is not equal to points.length", function() { expect(function() { return new import__311.QuaternionSpline({ points, times: [0, 1] }); }).toThrowDeveloperError(); }); it("evaluate throws without time", function() { const qs = new import__311.QuaternionSpline({ points, times }); expect(function() { qs.evaluate(); }).toThrowDeveloperError(); }); it("evaluate throws when time is out of range", function() { const qs = new import__311.QuaternionSpline({ points, times }); expect(function() { qs.evaluate(times[0] - 1); }).toThrowDeveloperError(); }); it("evaluate without result parameter", function() { const qs = new import__311.QuaternionSpline({ points, times }); expect(qs.evaluate(times[0])).toEqual(points[0]); const time2 = (times[2] + times[1]) * 0.5; const t = (time2 - times[1]) / (times[2] - times[1]); const actual = qs.evaluate(time2); const expected = import__311.Quaternion.slerp( points[1], points[2], t, new import__311.Quaternion() ); expect(actual).toEqualEpsilon(expected, import__312.Math.EPSILON6); }); it("evaluate with result parameter", function() { const qs = new import__311.QuaternionSpline({ points, times }); const result = new import__311.Quaternion(); const point = qs.evaluate(times[0], result); expect(point).toBe(result); expect(result).toEqual(points[0]); }); it("spline with 2 control points defaults to slerp", function() { points = points.slice(0, 2); times = times.slice(0, 2); const qs = new import__311.QuaternionSpline({ points, times }); const t = (times[0] + times[1]) * 0.5; const actual = qs.evaluate(t); const expected = import__311.Quaternion.slerp( points[0], points[1], t, new import__311.Quaternion() ); expect(actual).toEqualEpsilon(expected, import__312.Math.EPSILON6); }); it("spline with 2 control points defaults to slerp and result parameter", function() { points = points.slice(0, 2); times = times.slice(0, 2); const qs = new import__311.QuaternionSpline({ points, times }); const t = (times[0] + times[1]) * 0.5; const result = new import__311.Cartesian3(); const actual = qs.evaluate(t, result); const expected = import__311.Quaternion.slerp( points[0], points[1], t, new import__311.Quaternion() ); expect(actual).toBe(result); expect(actual).toEqualEpsilon(expected, import__312.Math.EPSILON6); }); }); // packages/engine/Specs/Core/QueueSpec.js var import__313 = __toESM(require_Cesium(), 1); describe("Core/Queue", function() { let queue; beforeEach(function() { queue = new import__313.Queue(); }); it("can enqueue and dequeue items", function() { queue.enqueue(1); queue.enqueue("a"); queue.enqueue(null); expect(queue.dequeue()).toEqual(1); expect(queue.dequeue()).toEqual("a"); expect(queue.dequeue()).toEqual(null); }); it("returns undefined when dequeueing while empty", function() { expect(queue.dequeue()).toBeUndefined(); }); it("updates length when enqueuing and dequeuing", function() { expect(queue.length).toEqual(0); queue.enqueue("a"); expect(queue.length).toEqual(1); queue.dequeue(); expect(queue.length).toEqual(0); }); it("compacts underlying array", function() { let i; for (i = 0; i < 1e3; i++) { queue.enqueue(i); } for (i = 0; i < 1e3; i++) { queue.dequeue(); } expect(queue._array.length).toBeLessThan(1e3); }); it("can peek at the item at the head of the queue", function() { queue.enqueue(1); queue.enqueue(2); expect(queue.peek()).toEqual(1); expect(queue.length).toEqual(2); }); it("returns undefined when peeking while empty", function() { expect(queue.peek()).toBeUndefined(); }); it("can check if it contains an item", function() { queue.enqueue(1); expect(queue.contains(1)).toEqual(true); expect(queue.contains(2)).toEqual(false); }); it("can clear items", function() { queue.enqueue(1); queue.enqueue(2); queue.clear(); expect(queue.length).toEqual(0); }); it("can sort items", function() { queue.enqueue(99); queue.enqueue(6); queue.enqueue(1); queue.enqueue(53); queue.enqueue(4); queue.enqueue(0); queue.dequeue(); queue.sort(function(a, b) { return a - b; }); expect(queue.dequeue()).toEqual(0); expect(queue.dequeue()).toEqual(1); expect(queue.dequeue()).toEqual(4); expect(queue.dequeue()).toEqual(6); expect(queue.dequeue()).toEqual(53); }); }); // packages/engine/Specs/Core/RaySpec.js var import__314 = __toESM(require_Cesium(), 1); describe("Core/Ray", function() { it("default constructor create zero valued Ray", function() { const ray = new import__314.Ray(); expect(ray.origin).toEqual(import__314.Cartesian3.ZERO); expect(ray.direction).toEqual(import__314.Cartesian3.ZERO); }); it("constructor sets expected properties", function() { const origin = import__314.Cartesian3.UNIT_Y; const direction = import__314.Cartesian3.UNIT_X; const ray = new import__314.Ray(origin, direction); expect(ray.origin).toEqual(origin); expect(ray.direction).toEqual(direction); }); it("constructor normalizes direction", function() { const origin = import__314.Cartesian3.UNIT_Y; const direction = import__314.Cartesian3.multiplyByScalar( import__314.Cartesian3.UNIT_X, 18, new import__314.Cartesian3() ); const ray = new import__314.Ray(origin, direction); expect(ray.origin).toEqual(origin); expect(ray.direction).toEqual(import__314.Cartesian3.UNIT_X); }); it("clone without a result parameter", function() { const direction = import__314.Cartesian3.normalize( new import__314.Cartesian3(1, 2, 3), new import__314.Cartesian3() ); const ray = new import__314.Ray(import__314.Cartesian3.UNIT_X, direction); const returnedResult = import__314.Ray.clone(ray); expect(ray).not.toBe(returnedResult); expect(ray.origin).not.toBe(returnedResult.origin); expect(ray.direction).not.toBe(returnedResult.direction); expect(ray).toEqual(returnedResult); }); it("clone with a result parameter", function() { const direction = import__314.Cartesian3.normalize( new import__314.Cartesian3(1, 2, 3), new import__314.Cartesian3() ); const ray = new import__314.Ray(import__314.Cartesian3.UNIT_X, direction); const result = new import__314.Ray(); const returnedResult = import__314.Ray.clone(ray, result); expect(ray).not.toBe(result); expect(ray.origin).not.toBe(returnedResult.origin); expect(ray.direction).not.toBe(returnedResult.direction); expect(result).toBe(returnedResult); expect(ray).toEqual(result); }); it("clone works with a result parameter that is an input parameter", function() { const direction = import__314.Cartesian3.normalize( new import__314.Cartesian3(1, 2, 3), new import__314.Cartesian3() ); const ray = new import__314.Ray(import__314.Cartesian3.UNIT_X, direction); const returnedResult = import__314.Ray.clone(ray, ray); expect(ray).toBe(returnedResult); }); it("clone returns undefined if ray is undefined", function() { expect(import__314.Ray.clone()).toBeUndefined(); }); it("getPoint along ray works without a result parameter", function() { const direction = import__314.Cartesian3.normalize( new import__314.Cartesian3(1, 2, 3), new import__314.Cartesian3() ); const ray = new import__314.Ray(import__314.Cartesian3.UNIT_X, direction); for (let i = -10; i < 11; i++) { const expectedResult = import__314.Cartesian3.add( import__314.Cartesian3.multiplyByScalar(direction, i, new import__314.Cartesian3()), import__314.Cartesian3.UNIT_X, new import__314.Cartesian3() ); const returnedResult = import__314.Ray.getPoint(ray, i); expect(returnedResult).toEqual(expectedResult); } }); it("getPoint works with a result parameter", function() { const direction = import__314.Cartesian3.normalize( new import__314.Cartesian3(1, 2, 3), new import__314.Cartesian3() ); const ray = new import__314.Ray(import__314.Cartesian3.UNIT_X, direction); const result = new import__314.Cartesian3(); for (let i = -10; i < 11; i++) { const expectedResult = import__314.Cartesian3.add( import__314.Cartesian3.multiplyByScalar(direction, i, new import__314.Cartesian3()), import__314.Cartesian3.UNIT_X, new import__314.Cartesian3() ); const returnedResult = import__314.Ray.getPoint(ray, i, result); expect(result).toBe(returnedResult); expect(returnedResult).toEqual(expectedResult); } }); it("getPoint throws without a point", function() { const direction = import__314.Cartesian3.normalize( new import__314.Cartesian3(1, 2, 3), new import__314.Cartesian3() ); const ray = new import__314.Ray(import__314.Cartesian3.UNIT_X, direction); expect(function() { import__314.Ray.getPoint(ray, void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/RectangleCollisionCheckerSpec.js var import__315 = __toESM(require_Cesium(), 1); describe("Core/RectangleCollisionChecker", function() { const testRectangle1 = new import__315.Rectangle(0, 0, 1, 1); const testRectangle2 = new import__315.Rectangle(1.1, 1.1, 2.1, 2.1); const testRectangle3 = new import__315.Rectangle(1.1, 1.1, 1.2, 1.2); it("Checks for collisions with contained rectangles", function() { const collisionChecker = new import__315.RectangleCollisionChecker(); collisionChecker.insert("test1", testRectangle1); expect(collisionChecker.collides(testRectangle2)).toBe(false); collisionChecker.insert("test3", testRectangle3); expect(collisionChecker.collides(testRectangle2)).toBe(true); }); it("removes rectangles", function() { const collisionChecker = new import__315.RectangleCollisionChecker(); collisionChecker.insert("test1", testRectangle1); collisionChecker.insert("test3", testRectangle3); expect(collisionChecker.collides(testRectangle2)).toBe(true); collisionChecker.remove("test3", testRectangle3); expect(collisionChecker.collides(testRectangle2)).toBe(false); }); }); // packages/engine/Specs/Core/RectangleGeometrySpec.js var import__316 = __toESM(require_Cesium(), 1); var import__317 = __toESM(require_Cesium(), 1); describe("Core/RectangleGeometry", function() { it("computes positions", function() { const rectangle2 = new import__316.Rectangle(-2, -1, 0, 1); const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: rectangle2, granularity: 1 }) ); const positions = m.attributes.position.values; const length2 = positions.length; expect(positions.length).toEqual(9 * 3); expect(m.indices.length).toEqual(8 * 3); const expectedNWCorner = import__316.Ellipsoid.WGS84.cartographicToCartesian( import__316.Rectangle.northwest(rectangle2) ); const expectedSECorner = import__316.Ellipsoid.WGS84.cartographicToCartesian( import__316.Rectangle.southeast(rectangle2) ); expect( new import__316.Cartesian3(positions[0], positions[1], positions[2]) ).toEqualEpsilon(expectedNWCorner, import__317.Math.EPSILON9); expect( new import__316.Cartesian3( positions[length2 - 3], positions[length2 - 2], positions[length2 - 1] ) ).toEqualEpsilon(expectedSECorner, import__317.Math.EPSILON9); }); it("computes positions across IDL", function() { const rectangle2 = import__316.Rectangle.fromDegrees(179, -1, -179, 1); const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: rectangle2 }) ); const positions = m.attributes.position.values; const length2 = positions.length; expect(positions.length).toEqual(9 * 3); expect(m.indices.length).toEqual(8 * 3); const expectedNWCorner = import__316.Ellipsoid.WGS84.cartographicToCartesian( import__316.Rectangle.northwest(rectangle2) ); const expectedSECorner = import__316.Ellipsoid.WGS84.cartographicToCartesian( import__316.Rectangle.southeast(rectangle2) ); expect( new import__316.Cartesian3(positions[0], positions[1], positions[2]) ).toEqualEpsilon(expectedNWCorner, import__317.Math.EPSILON8); expect( new import__316.Cartesian3( positions[length2 - 3], positions[length2 - 2], positions[length2 - 1] ) ).toEqualEpsilon(expectedSECorner, import__317.Math.EPSILON8); }); it("computes positions at north pole", function() { const rectangle2 = import__316.Rectangle.fromDegrees(-180, 89, -179, 90); const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: rectangle2 }) ); const positions = m.attributes.position.values; expect(positions.length).toEqual(5 * 3); expect(m.indices.length).toEqual(3 * 3); }); it("computes positions at south pole", function() { const rectangle2 = import__316.Rectangle.fromDegrees(-180, -90, -179, -89); const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: rectangle2 }) ); const positions = m.attributes.position.values; expect(positions.length).toEqual(5 * 3); expect(m.indices.length).toEqual(3 * 3); }); it("computes all attributes", function() { const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.ALL, rectangle: new import__316.Rectangle(-2, -1, 0, 1), granularity: 1 }) ); const numVertices = 9; const numTriangles = 8; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.attributes.st.values.length).toEqual(numVertices * 2); expect(m.attributes.normal.values.length).toEqual(numVertices * 3); expect(m.attributes.tangent.values.length).toEqual(numVertices * 3); expect(m.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("compute positions with rotation", function() { const rectangle2 = new import__316.Rectangle(-1, -1, 1, 1); const angle = import__317.Math.PI_OVER_TWO; const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITIONS_ONLY, rectangle: rectangle2, rotation: angle, granularity: 1 }) ); const positions = m.attributes.position.values; const length2 = positions.length; expect(length2).toEqual(9 * 3); expect(m.indices.length).toEqual(8 * 3); const unrotatedSECorner = import__316.Rectangle.southeast(rectangle2); const projection = new import__316.GeographicProjection(); const projectedSECorner = projection.project(unrotatedSECorner); const rotation = import__316.Matrix2.fromRotation(angle); const rotatedSECornerCartographic = projection.unproject( import__316.Matrix2.multiplyByVector(rotation, projectedSECorner, new import__316.Cartesian2()) ); const rotatedSECorner = import__316.Ellipsoid.WGS84.cartographicToCartesian( rotatedSECornerCartographic ); const actual = new import__316.Cartesian3( positions[length2 - 3], positions[length2 - 2], positions[length2 - 1] ); expect(actual).toEqualEpsilon(rotatedSECorner, import__317.Math.EPSILON6); }); it("compute vertices with PI rotation", function() { const rectangle2 = new import__316.Rectangle(-1, -1, 1, 1); const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ rectangle: rectangle2, rotation: import__317.Math.PI, granularity: 1 }) ); const positions = m.attributes.position.values; const length2 = positions.length; expect(length2).toEqual(9 * 3); expect(m.indices.length).toEqual(8 * 3); const unrotatedNWCorner = import__316.Ellipsoid.WGS84.cartographicToCartesian( import__316.Rectangle.northwest(rectangle2) ); const unrotatedSECorner = import__316.Ellipsoid.WGS84.cartographicToCartesian( import__316.Rectangle.southeast(rectangle2) ); let actual = new import__316.Cartesian3(positions[0], positions[1], positions[2]); expect(actual).toEqualEpsilon(unrotatedSECorner, import__317.Math.EPSILON8); actual = new import__316.Cartesian3( positions[length2 - 3], positions[length2 - 2], positions[length2 - 1] ); expect(actual).toEqualEpsilon(unrotatedNWCorner, import__317.Math.EPSILON8); }); it("compute texture coordinates with rotation", function() { const rectangle2 = new import__316.Rectangle(-1, -1, 1, 1); const angle = import__317.Math.PI_OVER_TWO; const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_AND_ST, rectangle: rectangle2, stRotation: angle, granularity: 1 }) ); const positions = m.attributes.position.values; const st = m.attributes.st.values; const length2 = st.length; expect(positions.length).toEqual(9 * 3); expect(length2).toEqual(9 * 2); expect(m.indices.length).toEqual(8 * 3); expect(st[length2 - 2]).toEqualEpsilon(0, import__317.Math.EPSILON14); expect(st[length2 - 1]).toEqualEpsilon(0, import__317.Math.EPSILON14); }); it("compute texture coordinate rotation with rectangle rotation", function() { const rectangle2 = new import__316.Rectangle(-1, -1, 1, 1); const angle = import__317.Math.toRadians(30); const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_AND_ST, rectangle: rectangle2, rotation: angle, stRotation: angle, granularity: 1 }) ); const st = m.attributes.st.values; expect(st[0]).toEqual(0); expect(st[1]).toEqual(1); expect(st[4]).toEqual(1); expect(st[5]).toEqual(1); expect(st[12]).toEqual(0); expect(st[13]).toEqual(0); expect(st[16]).toEqual(1); expect(st[17]).toEqual(0); }); it("throws without rectangle", function() { expect(function() { return new import__316.RectangleGeometry({}); }).toThrowDeveloperError(); }); it("throws if rotated rectangle is invalid", function() { expect(function() { return import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ rectangle: new import__316.Rectangle( -import__317.Math.PI_OVER_TWO, 1, import__317.Math.PI_OVER_TWO, import__317.Math.PI_OVER_TWO ), rotation: import__317.Math.PI_OVER_TWO }) ); }).toThrowDeveloperError(); }); it("throws if north is less than south", function() { expect(function() { return new import__316.RectangleGeometry({ rectangle: new import__316.Rectangle( -import__317.Math.PI_OVER_TWO, import__317.Math.PI_OVER_TWO, import__317.Math.PI_OVER_TWO, -import__317.Math.PI_OVER_TWO ) }); }).toThrowDeveloperError(); }); it("computes positions extruded", function() { const rectangle2 = new import__316.Rectangle(-2, -1, 0, 1); const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: rectangle2, granularity: 1, extrudedHeight: 2 }) ); const positions = m.attributes.position.values; expect(positions.length).toEqual(42 * 3); expect(m.indices.length).toEqual(32 * 3); }); it("computes positions extruded at the north pole", function() { const rectangle2 = import__316.Rectangle.fromDegrees(-180, 89, -179, 90); const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: rectangle2, extrudedHeight: 2 }) ); const positions = m.attributes.position.values; expect(positions.length).toEqual(26 * 3); expect(m.indices.length).toEqual(16 * 3); }); it("computes positions extruded at the south pole", function() { const rectangle2 = import__316.Rectangle.fromDegrees(-180, -90, -179, -89); const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: rectangle2, extrudedHeight: 2 }) ); const positions = m.attributes.position.values; expect(positions.length).toEqual(26 * 3); expect(m.indices.length).toEqual(16 * 3); }); it("computes all attributes extruded", function() { const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.ALL, rectangle: new import__316.Rectangle(-2, -1, 0, 1), granularity: 1, extrudedHeight: 2 }) ); const numVertices = 42; const numTriangles = 32; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.attributes.st.values.length).toEqual(numVertices * 2); expect(m.attributes.normal.values.length).toEqual(numVertices * 3); expect(m.attributes.tangent.values.length).toEqual(numVertices * 3); expect(m.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("compute positions with rotation extruded", function() { const rectangle2 = new import__316.Rectangle(-1, -1, 1, 1); const angle = import__317.Math.PI_OVER_TWO; const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITIONS_ONLY, rectangle: rectangle2, rotation: angle, granularity: 1, extrudedHeight: 2 }) ); const positions = m.attributes.position.values; const length2 = positions.length; expect(length2).toEqual(42 * 3); expect(m.indices.length).toEqual(32 * 3); const unrotatedSECorner = import__316.Rectangle.southeast(rectangle2); const projection = new import__316.GeographicProjection(); const projectedSECorner = projection.project(unrotatedSECorner); const rotation = import__316.Matrix2.fromRotation(angle); const rotatedSECornerCartographic = projection.unproject( import__316.Matrix2.multiplyByVector(rotation, projectedSECorner, new import__316.Cartesian2()) ); const rotatedSECorner = import__316.Ellipsoid.WGS84.cartographicToCartesian( rotatedSECornerCartographic ); const actual = new import__316.Cartesian3(positions[51], positions[52], positions[53]); expect(actual).toEqualEpsilon(rotatedSECorner, import__317.Math.EPSILON6); }); it("computes non-extruded rectangle if height is small", function() { const rectangle2 = new import__316.Rectangle(-2, -1, 0, 1); const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: rectangle2, granularity: 1, extrudedHeight: import__317.Math.EPSILON14 }) ); const positions = m.attributes.position.values; const numVertices = 9; const numTriangles = 8; expect(positions.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("computes offset attribute", function() { const rectangle2 = new import__316.Rectangle(-2, -1, 0, 1); const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: rectangle2, granularity: 1, offsetAttribute: import__316.GeometryOffsetAttribute.TOP }) ); const positions = m.attributes.position.values; const numVertices = 9; expect(positions.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("computes offset attribute extruded for top vertices", function() { const rectangle2 = new import__316.Rectangle(-2, -1, 0, 1); const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: rectangle2, granularity: 1, extrudedHeight: 2, offsetAttribute: import__316.GeometryOffsetAttribute.TOP }) ); const positions = m.attributes.position.values; const numVertices = 42; expect(positions.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(0).fill(1, 0, 9); for (let i = 18; i < offset.length; i += 2) { expected[i] = 1; } expect(offset).toEqual(expected); }); it("computes offset attribute extruded for all vertices", function() { const rectangle2 = new import__316.Rectangle(-2, -1, 0, 1); const m = import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: rectangle2, granularity: 1, extrudedHeight: 2, offsetAttribute: import__316.GeometryOffsetAttribute.ALL }) ); const positions = m.attributes.position.values; const numVertices = 42; expect(positions.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); for (let i = 18; i < offset.length; i += 2) { expected[i] = 1; } expect(offset).toEqual(expected); }); it("undefined is returned if any side are of length zero", function() { const rectangle0 = new import__316.RectangleGeometry({ rectangle: import__316.Rectangle.fromDegrees(-80, 39, -80, 42) }); const rectangle1 = new import__316.RectangleGeometry({ rectangle: import__316.Rectangle.fromDegrees(-81, 42, -80, 42) }); const rectangle2 = new import__316.RectangleGeometry({ rectangle: import__316.Rectangle.fromDegrees(-80, 39, -80, 39) }); const geometry0 = import__316.RectangleGeometry.createGeometry(rectangle0); const geometry1 = import__316.RectangleGeometry.createGeometry(rectangle1); const geometry2 = import__316.RectangleGeometry.createGeometry(rectangle2); expect(geometry0).toBeUndefined(); expect(geometry1).toBeUndefined(); expect(geometry2).toBeUndefined(); }); it("computing rectangle property", function() { const rectangle2 = new import__316.Rectangle.fromDegrees(-1, -1, 1, 1); const geometry = new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: rectangle2, granularity: 1 }); const r = geometry.rectangle; expect(import__317.Math.toDegrees(r.north)).toEqual(1); expect(import__317.Math.toDegrees(r.south)).toEqual(-1); expect(import__317.Math.toDegrees(r.east)).toEqual(1); expect(import__317.Math.toDegrees(r.west)).toEqual(-1); }); it("computing rectangle property with rotation", function() { const rectangle2 = new import__316.Rectangle.fromDegrees(-1, -1, 1, 1); const geometry = new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: rectangle2, granularity: 1, rotation: import__317.Math.toRadians(45) }); const r = geometry.rectangle; expect(import__317.Math.toDegrees(r.north)).toEqualEpsilon( 1.414213562373095, import__317.Math.EPSILON15 ); expect(import__317.Math.toDegrees(r.south)).toEqualEpsilon( -1.414213562373095, import__317.Math.EPSILON15 ); expect(import__317.Math.toDegrees(r.east)).toEqualEpsilon( 1.414213562373095, import__317.Math.EPSILON15 ); expect(import__317.Math.toDegrees(r.west)).toEqualEpsilon( -1.4142135623730951, import__317.Math.EPSILON15 ); }); it("computing textureCoordinateRotationPoints property", function() { const rectangle2 = new import__316.Rectangle.fromDegrees(-1, -1, 1, 1); let geometry = new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: rectangle2, granularity: 1, rotation: import__317.Math.toRadians(90) }); let textureCoordinateRotationPoints = geometry.textureCoordinateRotationPoints; expect(textureCoordinateRotationPoints.length).toEqual(6); expect(textureCoordinateRotationPoints[0]).toEqualEpsilon( 0, import__317.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[1]).toEqualEpsilon( 0, import__317.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[2]).toEqualEpsilon( 0, import__317.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[3]).toEqualEpsilon( 1, import__317.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[4]).toEqualEpsilon( 1, import__317.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[5]).toEqualEpsilon( 0, import__317.Math.EPSILON7 ); geometry = new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: rectangle2, granularity: 1, rotation: import__317.Math.toRadians(90) }); textureCoordinateRotationPoints = geometry.textureCoordinateRotationPoints; expect(textureCoordinateRotationPoints.length).toEqual(6); expect(textureCoordinateRotationPoints[0]).toEqualEpsilon( 0, import__317.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[1]).toEqualEpsilon( 0, import__317.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[2]).toEqualEpsilon( 0, import__317.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[3]).toEqualEpsilon( 1, import__317.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[4]).toEqualEpsilon( 1, import__317.Math.EPSILON7 ); expect(textureCoordinateRotationPoints[5]).toEqualEpsilon( 0, import__317.Math.EPSILON7 ); }); it("computeRectangle", function() { const options = { vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: new import__316.Rectangle.fromDegrees(-1, -1, 1, 1), granularity: 1, ellipsoid: import__316.Ellipsoid.UNIT_SPHERE, rotation: import__317.Math.PI }; const geometry = new import__316.RectangleGeometry(options); const expected = geometry.rectangle; const result = import__316.RectangleGeometry.computeRectangle(options); expect(result).toEqual(expected); }); it("computeRectangle with result parameter", function() { const options = { vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: new import__316.Rectangle.fromDegrees(-1, -1, 1, 1) }; const geometry = new import__316.RectangleGeometry(options); const result = new import__316.Rectangle(); const expected = geometry.rectangle; const returned = import__316.RectangleGeometry.computeRectangle(options, result); expect(returned).toEqual(expected); expect(returned).toBe(result); }); it("computing rectangle property with zero rotation", function() { expect(function() { return import__316.RectangleGeometry.createGeometry( new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: import__316.Rectangle.MAX_VALUE, granularity: 1, rotation: 0 }) ); }).not.toThrowDeveloperError(); }); it("can create rectangle geometry where the nw corner and the center are on opposite sides of the IDL", function() { const rectangle2 = new import__316.Rectangle( Math.PI - 5e-3, import__317.Math.PI_OVER_SIX + 0.02, 0.01 - Math.PI, import__317.Math.PI_OVER_SIX + 0.04 ); const geometry = new import__316.RectangleGeometry({ rectangle: rectangle2, rotation: 0.5 }); expect(function() { import__316.RectangleGeometry.createGeometry(geometry); }).not.toThrowDeveloperError(); }); const rectangle = new import__316.RectangleGeometry({ vertexFormat: import__316.VertexFormat.POSITION_ONLY, rectangle: new import__316.Rectangle(-2, -1, 0, 1), granularity: 1, ellipsoid: import__316.Ellipsoid.UNIT_SPHERE }); const packedInstance = [ -2, -1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1 ]; createPackableSpecs_default(import__316.RectangleGeometry, rectangle, packedInstance); }); // packages/engine/Specs/Core/RectangleOutlineGeometrySpec.js var import__318 = __toESM(require_Cesium(), 1); var import__319 = __toESM(require_Cesium(), 1); describe("Core/RectangleOutlineGeometry", function() { it("computes positions", function() { const rectangle2 = new import__318.Rectangle(-2, -1, 0, 1); const m = import__318.RectangleOutlineGeometry.createGeometry( new import__318.RectangleOutlineGeometry({ rectangle: rectangle2, granularity: 1 }) ); const positions = m.attributes.position.values; expect(positions.length).toEqual(8 * 3); expect(m.indices.length).toEqual(8 * 2); const expectedNWCorner = import__318.Ellipsoid.WGS84.cartographicToCartesian( import__318.Rectangle.northwest(rectangle2) ); expect( new import__318.Cartesian3(positions[0], positions[1], positions[2]) ).toEqualEpsilon(expectedNWCorner, import__319.Math.EPSILON9); }); it("computes positions across IDL", function() { const rectangle2 = import__318.Rectangle.fromDegrees(179, -1, -179, 1); const m = import__318.RectangleOutlineGeometry.createGeometry( new import__318.RectangleOutlineGeometry({ rectangle: rectangle2 }) ); const positions = m.attributes.position.values; expect(positions.length).toEqual(8 * 3); expect(m.indices.length).toEqual(8 * 2); const expectedNWCorner = import__318.Ellipsoid.WGS84.cartographicToCartesian( import__318.Rectangle.northwest(rectangle2) ); expect( new import__318.Cartesian3(positions[0], positions[1], positions[2]) ).toEqualEpsilon(expectedNWCorner, import__319.Math.EPSILON9); }); it("computes positions at north pole", function() { const rectangle2 = import__318.Rectangle.fromDegrees(-180, 89, -179, 90); const m = import__318.RectangleOutlineGeometry.createGeometry( new import__318.RectangleOutlineGeometry({ rectangle: rectangle2 }) ); const positions = m.attributes.position.values; expect(positions.length).toEqual(5 * 3); expect(m.indices.length).toEqual(5 * 2); }); it("computes positions at south pole", function() { const rectangle2 = import__318.Rectangle.fromDegrees(-180, -90, -179, -89); const m = import__318.RectangleOutlineGeometry.createGeometry( new import__318.RectangleOutlineGeometry({ rectangle: rectangle2 }) ); const positions = m.attributes.position.values; expect(positions.length).toEqual(5 * 3); expect(m.indices.length).toEqual(5 * 2); }); it("compute positions with rotation", function() { const rectangle2 = new import__318.Rectangle(-1, -1, 1, 1); const angle = import__319.Math.PI_OVER_TWO; const m = import__318.RectangleOutlineGeometry.createGeometry( new import__318.RectangleOutlineGeometry({ rectangle: rectangle2, rotation: angle, granularity: 1 }) ); const positions = m.attributes.position.values; expect(positions.length).toEqual(8 * 3); expect(m.indices.length).toEqual(8 * 2); const unrotatedNWCorner = import__318.Rectangle.northwest(rectangle2); const projection = new import__318.GeographicProjection(); const projectedNWCorner = projection.project(unrotatedNWCorner); const rotation = import__318.Matrix2.fromRotation(angle); const rotatedNWCornerCartographic = projection.unproject( import__318.Matrix2.multiplyByVector(rotation, projectedNWCorner, new import__318.Cartesian2()) ); const rotatedNWCorner = import__318.Ellipsoid.WGS84.cartographicToCartesian( rotatedNWCornerCartographic ); const actual = new import__318.Cartesian3(positions[0], positions[1], positions[2]); expect(actual).toEqualEpsilon(rotatedNWCorner, import__319.Math.EPSILON6); }); it("throws without rectangle", function() { expect(function() { return new import__318.RectangleOutlineGeometry({}); }).toThrowDeveloperError(); }); it("throws if rotated rectangle is invalid", function() { expect(function() { return import__318.RectangleOutlineGeometry.createGeometry( new import__318.RectangleOutlineGeometry({ rectangle: new import__318.Rectangle( -import__319.Math.PI_OVER_TWO, 1, import__319.Math.PI_OVER_TWO, import__319.Math.PI_OVER_TWO ), rotation: import__319.Math.PI_OVER_TWO }) ); }).toThrowDeveloperError(); }); it("throws if north is less than south", function() { expect(function() { return new import__318.RectangleOutlineGeometry({ rectangle: new import__318.Rectangle( -import__319.Math.PI_OVER_TWO, import__319.Math.PI_OVER_TWO, import__319.Math.PI_OVER_TWO, -import__319.Math.PI_OVER_TWO ) }); }).toThrowDeveloperError(); }); it("computes positions extruded", function() { const rectangle2 = new import__318.Rectangle(-2, -1, 0, 1); const m = import__318.RectangleOutlineGeometry.createGeometry( new import__318.RectangleOutlineGeometry({ rectangle: rectangle2, granularity: 1, extrudedHeight: 2 }) ); const positions = m.attributes.position.values; expect(positions.length).toEqual(16 * 3); expect(m.indices.length).toEqual(20 * 2); }); it("computes positions extruded at north pole", function() { const rectangle2 = import__318.Rectangle.fromDegrees(-180, 89, -179, 90); const m = import__318.RectangleOutlineGeometry.createGeometry( new import__318.RectangleOutlineGeometry({ rectangle: rectangle2, extrudedHeight: 2 }) ); const positions = m.attributes.position.values; expect(positions.length).toEqual(10 * 3); expect(m.indices.length).toEqual(13 * 2); }); it("computes positions extruded at south pole", function() { const rectangle2 = import__318.Rectangle.fromDegrees(-180, -90, -179, -89); const m = import__318.RectangleOutlineGeometry.createGeometry( new import__318.RectangleOutlineGeometry({ rectangle: rectangle2, extrudedHeight: 2 }) ); const positions = m.attributes.position.values; expect(positions.length).toEqual(10 * 3); expect(m.indices.length).toEqual(13 * 2); }); it("compute positions with rotation extruded", function() { const rectangle2 = new import__318.Rectangle(-1, -1, 1, 1); const angle = import__319.Math.PI_OVER_TWO; const m = import__318.RectangleOutlineGeometry.createGeometry( new import__318.RectangleOutlineGeometry({ rectangle: rectangle2, rotation: angle, granularity: 1, extrudedHeight: 2 }) ); const positions = m.attributes.position.values; expect(positions.length).toEqual(16 * 3); expect(m.indices.length).toEqual(20 * 2); const unrotatedNWCorner = import__318.Rectangle.northwest(rectangle2); const projection = new import__318.GeographicProjection(); const projectedNWCorner = projection.project(unrotatedNWCorner); const rotation = import__318.Matrix2.fromRotation(angle); const rotatedNWCornerCartographic = projection.unproject( import__318.Matrix2.multiplyByVector(rotation, projectedNWCorner, new import__318.Cartesian2()) ); rotatedNWCornerCartographic.height = 2; const rotatedNWCorner = import__318.Ellipsoid.WGS84.cartographicToCartesian( rotatedNWCornerCartographic ); const actual = new import__318.Cartesian3(positions[0], positions[1], positions[2]); expect(actual).toEqualEpsilon(rotatedNWCorner, import__319.Math.EPSILON6); }); it("computes non-extruded rectangle if height is small", function() { const rectangle2 = new import__318.Rectangle(-2, -1, 0, 1); const m = import__318.RectangleOutlineGeometry.createGeometry( new import__318.RectangleOutlineGeometry({ rectangle: rectangle2, granularity: 1, extrudedHeight: import__319.Math.EPSILON14 }) ); const positions = m.attributes.position.values; expect(positions.length).toEqual(8 * 3); expect(m.indices.length).toEqual(8 * 2); }); it("undefined is returned if any side are of length zero", function() { const rectangleOutline0 = new import__318.RectangleOutlineGeometry({ rectangle: import__318.Rectangle.fromDegrees(-80, 39, -80, 42) }); const rectangleOutline1 = new import__318.RectangleOutlineGeometry({ rectangle: import__318.Rectangle.fromDegrees(-81, 42, -80, 42) }); const rectangleOutline2 = new import__318.RectangleOutlineGeometry({ rectangle: import__318.Rectangle.fromDegrees(-80, 39, -80, 39) }); const geometry0 = import__318.RectangleOutlineGeometry.createGeometry( rectangleOutline0 ); const geometry1 = import__318.RectangleOutlineGeometry.createGeometry( rectangleOutline1 ); const geometry2 = import__318.RectangleOutlineGeometry.createGeometry( rectangleOutline2 ); expect(geometry0).toBeUndefined(); expect(geometry1).toBeUndefined(); expect(geometry2).toBeUndefined(); }); it("computes offset attribute", function() { const rectangle2 = new import__318.Rectangle(-2, -1, 0, 1); const m = import__318.RectangleOutlineGeometry.createGeometry( new import__318.RectangleOutlineGeometry({ rectangle: rectangle2, granularity: 1, offsetAttribute: import__318.GeometryOffsetAttribute.TOP }) ); const positions = m.attributes.position.values; const numVertices = 8; expect(positions.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); it("computes offset attribute extruded for top vertices", function() { const rectangle2 = new import__318.Rectangle(-2, -1, 0, 1); const m = import__318.RectangleOutlineGeometry.createGeometry( new import__318.RectangleOutlineGeometry({ rectangle: rectangle2, granularity: 1, extrudedHeight: 2, offsetAttribute: import__318.GeometryOffsetAttribute.TOP }) ); const positions = m.attributes.position.values; const numVertices = 16; expect(positions.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(0).fill(1, 0, 8); expect(offset).toEqual(expected); }); it("computes offset attribute extruded for all vertices", function() { const rectangle2 = new import__318.Rectangle(-2, -1, 0, 1); const m = import__318.RectangleOutlineGeometry.createGeometry( new import__318.RectangleOutlineGeometry({ rectangle: rectangle2, granularity: 1, extrudedHeight: 2, offsetAttribute: import__318.GeometryOffsetAttribute.ALL }) ); const positions = m.attributes.position.values; const numVertices = 16; expect(positions.length).toEqual(numVertices * 3); const offset = m.attributes.applyOffset.values; expect(offset.length).toEqual(numVertices); const expected = new Array(offset.length).fill(1); expect(offset).toEqual(expected); }); let rectangle = new import__318.RectangleOutlineGeometry({ rectangle: new import__318.Rectangle(0.1, 0.2, 0.3, 0.4), ellipsoid: new import__318.Ellipsoid(5, 6, 7), granularity: 8, height: 9, rotation: 10, extrudedHeight: 11 }); let packedInstance = [0.1, 0.2, 0.3, 0.4, 5, 6, 7, 8, 11, 10, 9, -1]; createPackableSpecs_default( import__318.RectangleOutlineGeometry, rectangle, packedInstance, "extruded" ); rectangle = new import__318.RectangleOutlineGeometry({ rectangle: new import__318.Rectangle(0.1, 0.2, 0.3, 0.4), ellipsoid: new import__318.Ellipsoid(5, 6, 7), granularity: 8, height: 9, rotation: 10 }); packedInstance = [0.1, 0.2, 0.3, 0.4, 5, 6, 7, 8, 9, 10, 9, -1]; createPackableSpecs_default( import__318.RectangleOutlineGeometry, rectangle, packedInstance, "at height" ); }); // packages/engine/Specs/Core/RectangleSpec.js var import__320 = __toESM(require_Cesium(), 1); describe("Core/Rectangle", function() { const west = -0.9; const south = 0.5; const east = 1.4; const north = 1; const center = new import__320.Cartographic((west + east) / 2, (south + north) / 2); it("default constructor sets expected values.", function() { const rectangle2 = new import__320.Rectangle(); expect(rectangle2.west).toEqual(0); expect(rectangle2.south).toEqual(0); expect(rectangle2.north).toEqual(0); expect(rectangle2.east).toEqual(0); }); it("constructor sets expected parameter values.", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); expect(rectangle2.west).toEqual(west); expect(rectangle2.south).toEqual(south); expect(rectangle2.east).toEqual(east); expect(rectangle2.north).toEqual(north); }); it("computeWidth", function() { let rectangle2 = new import__320.Rectangle(west, south, east, north); let expected = east - west; expect(import__320.Rectangle.computeWidth(rectangle2)).toEqual(expected); expect(rectangle2.width).toEqual(expected); rectangle2 = new import__320.Rectangle(2, -1, -2, 1); expected = rectangle2.east - rectangle2.west + import__320.Math.TWO_PI; expect(rectangle2.width).toEqual(expected); }); it("computeHeight", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); const expected = north - south; expect(import__320.Rectangle.computeHeight(rectangle2)).toEqual(expected); expect(rectangle2.height).toEqual(expected); }); it("fromDegrees produces expected values.", function() { const west2 = -10; const south2 = -20; const east2 = 10; const north2 = 20; const rectangle2 = import__320.Rectangle.fromDegrees(west2, south2, east2, north2); expect(rectangle2.west).toEqual(import__320.Math.toRadians(west2)); expect(rectangle2.south).toEqual(import__320.Math.toRadians(south2)); expect(rectangle2.east).toEqual(import__320.Math.toRadians(east2)); expect(rectangle2.north).toEqual(import__320.Math.toRadians(north2)); }); it("fromDegrees works with a result parameter.", function() { const west2 = -10; const south2 = -20; const east2 = 10; const north2 = 20; const result = new import__320.Rectangle(); const rectangle2 = import__320.Rectangle.fromDegrees(west2, south2, east2, north2, result); expect(result).toBe(rectangle2); expect(rectangle2.west).toEqual(import__320.Math.toRadians(west2)); expect(rectangle2.south).toEqual(import__320.Math.toRadians(south2)); expect(rectangle2.east).toEqual(import__320.Math.toRadians(east2)); expect(rectangle2.north).toEqual(import__320.Math.toRadians(north2)); }); it("fromRadians produces expected values.", function() { const west2 = -1; const south2 = -2; const east2 = 1; const north2 = 2; const rectangle2 = import__320.Rectangle.fromRadians(west2, south2, east2, north2); expect(rectangle2.west).toEqual(west2); expect(rectangle2.south).toEqual(south2); expect(rectangle2.east).toEqual(east2); expect(rectangle2.north).toEqual(north2); }); it("fromRadians works with a result parameter.", function() { const west2 = -1; const south2 = -2; const east2 = 1; const north2 = 2; const result = new import__320.Rectangle(); const rectangle2 = import__320.Rectangle.fromRadians(west2, south2, east2, north2, result); expect(result).toBe(rectangle2); expect(rectangle2.west).toEqual(west2); expect(rectangle2.south).toEqual(south2); expect(rectangle2.east).toEqual(east2); expect(rectangle2.north).toEqual(north2); }); it("fromCartographicArray produces expected values.", function() { const minLon = new import__320.Cartographic(-0.1, 0.3, 0); const minLat = new import__320.Cartographic(0, -0.2, 0); const maxLon = new import__320.Cartographic(0.3, -0.1, 0); const maxLat = new import__320.Cartographic(0.2, 0.4, 0); const rectangle2 = import__320.Rectangle.fromCartographicArray([ minLat, minLon, maxLat, maxLon ]); expect(rectangle2.west).toEqual(minLon.longitude); expect(rectangle2.south).toEqual(minLat.latitude); expect(rectangle2.east).toEqual(maxLon.longitude); expect(rectangle2.north).toEqual(maxLat.latitude); }); it("fromCartographicArray produces rectangle that crosses IDL.", function() { const minLon = import__320.Cartographic.fromDegrees(-178, 3); const minLat = import__320.Cartographic.fromDegrees(-179, -4); const maxLon = import__320.Cartographic.fromDegrees(178, 3); const maxLat = import__320.Cartographic.fromDegrees(179, 4); const rectangle2 = import__320.Rectangle.fromCartographicArray([ minLat, minLon, maxLat, maxLon ]); expect(rectangle2.east).toEqual(minLon.longitude); expect(rectangle2.south).toEqual(minLat.latitude); expect(rectangle2.west).toEqual(maxLon.longitude); expect(rectangle2.north).toEqual(maxLat.latitude); }); it("fromCartographicArray works with a result parameter.", function() { const minLon = new import__320.Cartographic(-0.1, 0.3, 0); const minLat = new import__320.Cartographic(0, -0.2, 0); const maxLon = new import__320.Cartographic(0.3, -0.1, 0); const maxLat = new import__320.Cartographic(0.2, 0.4, 0); const result = new import__320.Rectangle(); const rectangle2 = import__320.Rectangle.fromCartographicArray( [minLat, minLon, maxLat, maxLon], result ); expect(result).toBe(rectangle2); expect(rectangle2.west).toEqual(minLon.longitude); expect(rectangle2.south).toEqual(minLat.latitude); expect(rectangle2.east).toEqual(maxLon.longitude); expect(rectangle2.north).toEqual(maxLat.latitude); }); it("fromCartesianArray produces expected values.", function() { const minLon = new import__320.Cartographic(-0.1, 0.3, 0); const minLat = new import__320.Cartographic(0, -0.2, 0); const maxLon = new import__320.Cartographic(0.3, -0.1, 0); const maxLat = new import__320.Cartographic(0.2, 0.4, 0); const wgs84 = import__320.Ellipsoid.WGS84; const rectangle2 = import__320.Rectangle.fromCartesianArray( wgs84.cartographicArrayToCartesianArray([minLat, minLon, maxLat, maxLon]), wgs84 ); expect(rectangle2.west).toEqualEpsilon( minLon.longitude, import__320.Math.EPSILON15 ); expect(rectangle2.south).toEqualEpsilon( minLat.latitude, import__320.Math.EPSILON15 ); expect(rectangle2.east).toEqualEpsilon( maxLon.longitude, import__320.Math.EPSILON15 ); expect(rectangle2.north).toEqualEpsilon( maxLat.latitude, import__320.Math.EPSILON15 ); }); it("fromCartesianArray produces rectangle that crosses IDL.", function() { const minLon = import__320.Cartographic.fromDegrees(-178, 3); const minLat = import__320.Cartographic.fromDegrees(-179, -4); const maxLon = import__320.Cartographic.fromDegrees(178, 3); const maxLat = import__320.Cartographic.fromDegrees(179, 4); const wgs84 = import__320.Ellipsoid.WGS84; const rectangle2 = import__320.Rectangle.fromCartesianArray( wgs84.cartographicArrayToCartesianArray([minLat, minLon, maxLat, maxLon]), wgs84 ); expect(rectangle2.east).toEqual(minLon.longitude); expect(rectangle2.south).toEqual(minLat.latitude); expect(rectangle2.west).toEqual(maxLon.longitude); expect(rectangle2.north).toEqual(maxLat.latitude); }); it("fromCartesianArray works with a result parameter.", function() { const minLon = new import__320.Cartographic(-0.1, 0.3, 0); const minLat = new import__320.Cartographic(0, -0.2, 0); const maxLon = new import__320.Cartographic(0.3, -0.1, 0); const maxLat = new import__320.Cartographic(0.2, 0.4, 0); const wgs84 = import__320.Ellipsoid.WGS84; const result = new import__320.Rectangle(); const rectangle2 = import__320.Rectangle.fromCartesianArray( wgs84.cartographicArrayToCartesianArray([minLat, minLon, maxLat, maxLon]), wgs84, result ); expect(result).toBe(rectangle2); expect(rectangle2.west).toEqualEpsilon( minLon.longitude, import__320.Math.EPSILON15 ); expect(rectangle2.south).toEqualEpsilon( minLat.latitude, import__320.Math.EPSILON15 ); expect(rectangle2.east).toEqualEpsilon( maxLon.longitude, import__320.Math.EPSILON15 ); expect(rectangle2.north).toEqualEpsilon( maxLat.latitude, import__320.Math.EPSILON15 ); }); it("clone works without a result parameter.", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); const returnedResult = rectangle2.clone(); expect(returnedResult).toEqual(rectangle2); expect(returnedResult).not.toBe(rectangle2); }); it("clone works with a result parameter.", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); const result = new import__320.Rectangle(); const returnedResult = rectangle2.clone(result); expect(returnedResult).toEqual(rectangle2); expect(returnedResult).not.toBe(rectangle2); expect(returnedResult).toBe(result); }); it('clone works with "this" result parameter.', function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); const returnedResult = rectangle2.clone(rectangle2); expect(returnedResult).toEqual(new import__320.Rectangle(west, south, east, north)); expect(returnedResult).toBe(rectangle2); }); it("clone works without rectangle", function() { expect(import__320.Rectangle.clone()).not.toBeDefined(); }); it("Equals works in all cases", function() { const rectangle2 = new import__320.Rectangle(0.1, 0.2, 0.3, 0.4); expect(rectangle2.equals(new import__320.Rectangle(0.1, 0.2, 0.3, 0.4))).toEqual(true); expect(rectangle2.equals(new import__320.Rectangle(0.5, 0.2, 0.3, 0.4))).toEqual(false); expect(rectangle2.equals(new import__320.Rectangle(0.1, 0.5, 0.3, 0.4))).toEqual(false); expect(rectangle2.equals(new import__320.Rectangle(0.1, 0.2, 0.5, 0.4))).toEqual(false); expect(rectangle2.equals(new import__320.Rectangle(0.1, 0.2, 0.3, 0.5))).toEqual(false); expect(rectangle2.equals(void 0)).toEqual(false); }); it("Static equals works in all cases", function() { const rectangle2 = new import__320.Rectangle(0.1, 0.2, 0.3, 0.4); expect( import__320.Rectangle.equals(rectangle2, new import__320.Rectangle(0.1, 0.2, 0.3, 0.4)) ).toEqual(true); expect( import__320.Rectangle.equals(rectangle2, new import__320.Rectangle(0.5, 0.2, 0.3, 0.4)) ).toEqual(false); expect( import__320.Rectangle.equals(rectangle2, new import__320.Rectangle(0.1, 0.5, 0.3, 0.4)) ).toEqual(false); expect( import__320.Rectangle.equals(rectangle2, new import__320.Rectangle(0.1, 0.2, 0.5, 0.4)) ).toEqual(false); expect( import__320.Rectangle.equals(rectangle2, new import__320.Rectangle(0.1, 0.2, 0.3, 0.5)) ).toEqual(false); expect(import__320.Rectangle.equals(rectangle2, void 0)).toEqual(false); }); it("Static equals epsilon works in all cases", function() { const rectangle1 = new import__320.Rectangle(0.1, 0.2, 0.3, 0.4); expect( import__320.Rectangle.equalsEpsilon( rectangle1, new import__320.Rectangle(0.1, 0.2, 0.3, 0.4), 0 ) ).toEqual(true); expect( import__320.Rectangle.equalsEpsilon( rectangle1, new import__320.Rectangle(0.5, 0.2, 0.3, 0.4), 0 ) ).toEqual(false); expect( import__320.Rectangle.equalsEpsilon( rectangle1, new import__320.Rectangle(0.1, 0.5, 0.3, 0.4), 0 ) ).toEqual(false); expect( import__320.Rectangle.equalsEpsilon( rectangle1, new import__320.Rectangle(0.1, 0.2, 0.5, 0.4), 0 ) ).toEqual(false); expect( import__320.Rectangle.equalsEpsilon( rectangle1, new import__320.Rectangle(0.1, 0.2, 0.3, 0.5), 0 ) ).toEqual(false); expect( import__320.Rectangle.equalsEpsilon( rectangle1, new import__320.Rectangle(0.5, 0.2, 0.3, 0.4), 0.4 ) ).toEqual(true); expect( import__320.Rectangle.equalsEpsilon( rectangle1, new import__320.Rectangle(0.1, 0.5, 0.3, 0.4), 0.3 ) ).toEqual(true); expect( import__320.Rectangle.equalsEpsilon( rectangle1, new import__320.Rectangle(0.1, 0.2, 0.5, 0.4), 0.2 ) ).toEqual(true); expect( import__320.Rectangle.equalsEpsilon( rectangle1, new import__320.Rectangle(0.1, 0.2, 0.3, 0.5), 0.1 ) ).toEqual(true); expect(import__320.Rectangle.equalsEpsilon(rectangle1, void 0, 0)).toEqual(false); expect(import__320.Rectangle.equalsEpsilon(void 0, rectangle1, 0)).toEqual(false); expect(import__320.Rectangle.equalsEpsilon(rectangle1, rectangle1, 0)).toEqual(true); }); it("Equals epsilon works in all cases", function() { const rectangle2 = new import__320.Rectangle(0.1, 0.2, 0.3, 0.4); expect( rectangle2.equalsEpsilon(new import__320.Rectangle(0.1, 0.2, 0.3, 0.4), 0) ).toEqual(true); expect( rectangle2.equalsEpsilon(new import__320.Rectangle(0.5, 0.2, 0.3, 0.4), 0) ).toEqual(false); expect( rectangle2.equalsEpsilon(new import__320.Rectangle(0.1, 0.5, 0.3, 0.4), 0) ).toEqual(false); expect( rectangle2.equalsEpsilon(new import__320.Rectangle(0.1, 0.2, 0.5, 0.4), 0) ).toEqual(false); expect( rectangle2.equalsEpsilon(new import__320.Rectangle(0.1, 0.2, 0.3, 0.5), 0) ).toEqual(false); expect( rectangle2.equalsEpsilon(new import__320.Rectangle(0.5, 0.2, 0.3, 0.4), 0.4) ).toEqual(true); expect( rectangle2.equalsEpsilon(new import__320.Rectangle(0.1, 0.5, 0.3, 0.4), 0.3) ).toEqual(true); expect( rectangle2.equalsEpsilon(new import__320.Rectangle(0.1, 0.2, 0.5, 0.4), 0.2) ).toEqual(true); expect( rectangle2.equalsEpsilon(new import__320.Rectangle(0.1, 0.2, 0.3, 0.5), 0.1) ).toEqual(true); expect(rectangle2.equalsEpsilon(void 0, 0)).toEqual(false); }); it("fromCartographicArray throws with no array", function() { expect(function() { import__320.Rectangle.fromCartographicArray(void 0, new import__320.Rectangle()); }).toThrowDeveloperError(); }); it("fromCartesianArray throws with no array", function() { expect(function() { import__320.Rectangle.fromCartesianArray(void 0, void 0, new import__320.Rectangle()); }).toThrowDeveloperError(); }); it("validate throws with no rectangle", function() { expect(function() { import__320.Rectangle.validate(); }).toThrowDeveloperError(); }); it("validate throws with no west", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); rectangle2.west = void 0; expect(function() { import__320.Rectangle.validate(rectangle2); }).toThrowDeveloperError(); }); it("validate throws with no south", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); rectangle2.south = void 0; expect(function() { import__320.Rectangle.validate(rectangle2); }).toThrowDeveloperError(); }); it("validate throws with no east", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); rectangle2.east = void 0; expect(function() { import__320.Rectangle.validate(rectangle2); }).toThrowDeveloperError(); }); it("validate throws with no north", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); rectangle2.north = void 0; expect(function() { import__320.Rectangle.validate(rectangle2); }).toThrowDeveloperError(); }); it("validate throws with bad west", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); rectangle2.west = Math.PI * 2; expect(function() { import__320.Rectangle.validate(rectangle2); }).toThrowDeveloperError(); }); it("validate throws with bad south", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); rectangle2.south = Math.PI * 2; expect(function() { import__320.Rectangle.validate(rectangle2); }).toThrowDeveloperError(); }); it("validate throws with bad east", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); rectangle2.east = Math.PI * 2; expect(function() { import__320.Rectangle.validate(rectangle2); }).toThrowDeveloperError(); }); it("validate throws with bad north", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); rectangle2.north = Math.PI * 2; expect(function() { import__320.Rectangle.validate(rectangle2); }).toThrowDeveloperError(); }); it("southwest works without a result parameter", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); const returnedResult = import__320.Rectangle.southwest(rectangle2); expect(returnedResult.longitude).toEqual(west); expect(returnedResult.latitude).toEqual(south); }); it("southwest works with a result parameter", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); const result = new import__320.Cartographic(); const returnedResult = import__320.Rectangle.southwest(rectangle2, result); expect(returnedResult).toBe(result); expect(returnedResult.longitude).toEqual(west); expect(returnedResult.latitude).toEqual(south); }); it("southwest throws with no rectangle", function() { expect(function() { import__320.Rectangle.southwest(); }).toThrowDeveloperError(); }); it("northwest works without a result parameter", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); const returnedResult = import__320.Rectangle.northwest(rectangle2); expect(returnedResult.longitude).toEqual(west); expect(returnedResult.latitude).toEqual(north); }); it("northwest works with a result parameter", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); const result = new import__320.Cartographic(); const returnedResult = import__320.Rectangle.northwest(rectangle2, result); expect(returnedResult).toBe(result); expect(returnedResult.longitude).toEqual(west); expect(returnedResult.latitude).toEqual(north); }); it("getNothwest throws with no rectangle", function() { expect(function() { import__320.Rectangle.northwest(); }).toThrowDeveloperError(); }); it("northeast works without a result parameter", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); const returnedResult = import__320.Rectangle.northeast(rectangle2); expect(returnedResult.longitude).toEqual(east); expect(returnedResult.latitude).toEqual(north); }); it("northeast works with a result parameter", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); const result = new import__320.Cartographic(); const returnedResult = import__320.Rectangle.northeast(rectangle2, result); expect(returnedResult).toBe(result); expect(returnedResult.longitude).toEqual(east); expect(returnedResult.latitude).toEqual(north); }); it("getNotheast throws with no rectangle", function() { expect(function() { import__320.Rectangle.northeast(); }).toThrowDeveloperError(); }); it("southeast works without a result parameter", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); const returnedResult = import__320.Rectangle.southeast(rectangle2); expect(returnedResult.longitude).toEqual(east); expect(returnedResult.latitude).toEqual(south); }); it("southeast works with a result parameter", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); const result = new import__320.Cartographic(); const returnedResult = import__320.Rectangle.southeast(rectangle2, result); expect(returnedResult).toBe(result); expect(returnedResult.longitude).toEqual(east); expect(returnedResult.latitude).toEqual(south); }); it("southeast throws with no rectangle", function() { expect(function() { import__320.Rectangle.southeast(); }).toThrowDeveloperError(); }); it("center works without a result parameter", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); const returnedResult = import__320.Rectangle.center(rectangle2); expect(returnedResult).toEqualEpsilon(center, import__320.Math.EPSILON11); }); it("center works with a result parameter", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); const result = new import__320.Cartographic(); const returnedResult = import__320.Rectangle.center(rectangle2, result); expect(result).toBe(returnedResult); expect(returnedResult).toEqualEpsilon(center, import__320.Math.EPSILON11); }); it("center works across IDL", function() { let rectangle2 = import__320.Rectangle.fromDegrees(170, 0, -170, 0); let returnedResult = import__320.Rectangle.center(rectangle2); expect(returnedResult).toEqualEpsilon( import__320.Cartographic.fromDegrees(180, 0), import__320.Math.EPSILON11 ); rectangle2 = import__320.Rectangle.fromDegrees(160, 0, -170, 0); returnedResult = import__320.Rectangle.center(rectangle2); expect(returnedResult).toEqualEpsilon( import__320.Cartographic.fromDegrees(175, 0), import__320.Math.EPSILON11 ); rectangle2 = import__320.Rectangle.fromDegrees(170, 0, -160, 0); returnedResult = import__320.Rectangle.center(rectangle2); expect(returnedResult).toEqualEpsilon( import__320.Cartographic.fromDegrees(-175, 0), import__320.Math.EPSILON11 ); rectangle2 = import__320.Rectangle.fromDegrees(160, 0, 140, 0); returnedResult = import__320.Rectangle.center(rectangle2); expect(returnedResult).toEqualEpsilon( import__320.Cartographic.fromDegrees(-30, 0), import__320.Math.EPSILON11 ); }); it("center throws with no rectangle", function() { expect(function() { import__320.Rectangle.center(); }).toThrowDeveloperError(); }); it("intersection works without a result parameter", function() { const rectangle2 = new import__320.Rectangle(0.5, 0.1, 0.75, 0.9); const rectangle22 = new import__320.Rectangle(0, 0.25, 1, 0.8); const expected = new import__320.Rectangle(0.5, 0.25, 0.75, 0.8); const returnedResult = import__320.Rectangle.intersection(rectangle2, rectangle22); expect(returnedResult).toEqual(expected); }); it("intersection works with a result parameter", function() { const rectangle2 = new import__320.Rectangle(0.5, 0.1, 0.75, 0.9); const rectangle22 = new import__320.Rectangle(0, 0.25, 1, 0.8); const expected = new import__320.Rectangle(0.5, 0.25, 0.75, 0.8); const result = new import__320.Rectangle(); const returnedResult = import__320.Rectangle.intersection( rectangle2, rectangle22, result ); expect(returnedResult).toEqual(expected); expect(result).toBe(returnedResult); }); it("intersection works across the IDL (1)", function() { const rectangle1 = import__320.Rectangle.fromDegrees(170, -10, -170, 10); const rectangle2 = import__320.Rectangle.fromDegrees(-175, 5, -160, 15); const expected = import__320.Rectangle.fromDegrees(-175, 5, -170, 10); expect(import__320.Rectangle.intersection(rectangle1, rectangle2)).toEqual(expected); expect(import__320.Rectangle.intersection(rectangle2, rectangle1)).toEqual(expected); }); it("intersection works across the IDL (2)", function() { const rectangle1 = import__320.Rectangle.fromDegrees(170, -10, -170, 10); const rectangle2 = import__320.Rectangle.fromDegrees(160, 5, 175, 15); const expected = import__320.Rectangle.fromDegrees(170, 5, 175, 10); expect(import__320.Rectangle.intersection(rectangle1, rectangle2)).toEqual(expected); expect(import__320.Rectangle.intersection(rectangle2, rectangle1)).toEqual(expected); }); it("intersection works across the IDL (3)", function() { const rectangle1 = import__320.Rectangle.fromDegrees(170, -10, -170, 10); const rectangle2 = import__320.Rectangle.fromDegrees(175, 5, -175, 15); const expected = import__320.Rectangle.fromDegrees(175, 5, -175, 10); expect(import__320.Rectangle.intersection(rectangle1, rectangle2)).toEqual(expected); expect(import__320.Rectangle.intersection(rectangle2, rectangle1)).toEqual(expected); }); it("intersection returns undefined for a point", function() { const rectangle1 = new import__320.Rectangle(west, south, east, north); const rectangle2 = new import__320.Rectangle(east, north, east + 0.1, north + 0.1); expect(import__320.Rectangle.intersection(rectangle1, rectangle2)).not.toBeDefined(); expect(import__320.Rectangle.intersection(rectangle2, rectangle1)).not.toBeDefined(); }); it("intersection returns undefined for a east-west line (1)", function() { const rectangle1 = new import__320.Rectangle(west, south, east, north); const rectangle2 = new import__320.Rectangle(west, north, east, north + 0.1); expect(import__320.Rectangle.intersection(rectangle1, rectangle2)).not.toBeDefined(); expect(import__320.Rectangle.intersection(rectangle2, rectangle1)).not.toBeDefined(); }); it("intersection returns undefined for a east-west line (2)", function() { const rectangle1 = new import__320.Rectangle(west, south, east, north); const rectangle2 = new import__320.Rectangle(west, south + 0.1, east, south); expect(import__320.Rectangle.intersection(rectangle1, rectangle2)).not.toBeDefined(); expect(import__320.Rectangle.intersection(rectangle2, rectangle1)).not.toBeDefined(); }); it("intersection returns undefined for a north-south line (1)", function() { const rectangle1 = new import__320.Rectangle(west, south, east, north); const rectangle2 = new import__320.Rectangle(east, south, east + 0.1, north); expect(import__320.Rectangle.intersection(rectangle1, rectangle2)).not.toBeDefined(); expect(import__320.Rectangle.intersection(rectangle2, rectangle1)).not.toBeDefined(); }); it("intersection returns undefined for a north-south line (2)", function() { const rectangle1 = new import__320.Rectangle(west, south, east, north); const rectangle2 = new import__320.Rectangle(west - 0.1, south, west, north); expect(import__320.Rectangle.intersection(rectangle1, rectangle2)).not.toBeDefined(); expect(import__320.Rectangle.intersection(rectangle2, rectangle1)).not.toBeDefined(); }); it("intersection returns undefined for a north-south line (3)", function() { const west2 = import__320.Math.toRadians(170); const south2 = import__320.Math.toRadians(-10); const east2 = import__320.Math.toRadians(-170); const north2 = import__320.Math.toRadians(10); const rectangle1 = new import__320.Rectangle(west2, south2, east2, north2); const rectangle2 = new import__320.Rectangle(east2, south2, east2 + 0.1, north2); expect(import__320.Rectangle.intersection(rectangle1, rectangle2)).not.toBeDefined(); expect(import__320.Rectangle.intersection(rectangle2, rectangle1)).not.toBeDefined(); }); it("intersection returns undefined for a north-south line (4)", function() { const west2 = import__320.Math.toRadians(170); const south2 = import__320.Math.toRadians(-10); const east2 = import__320.Math.toRadians(-170); const north2 = import__320.Math.toRadians(10); const rectangle1 = new import__320.Rectangle(west2, south2, east2, north2); const rectangle2 = new import__320.Rectangle(west2 - 0.1, south2, west2, north2); expect(import__320.Rectangle.intersection(rectangle1, rectangle2)).not.toBeDefined(); expect(import__320.Rectangle.intersection(rectangle2, rectangle1)).not.toBeDefined(); }); it("intersection returns undefined if north-south direction is degenerate", function() { const rectangle1 = new import__320.Rectangle(west, south, east, north); const rectangle2 = new import__320.Rectangle(west, north + 0.1, east, north + 0.2); expect(import__320.Rectangle.intersection(rectangle1, rectangle2)).not.toBeDefined(); expect(import__320.Rectangle.intersection(rectangle2, rectangle1)).not.toBeDefined(); }); it("intersection returns undefined if east-west direction is degenerate", function() { const rectangle1 = new import__320.Rectangle(west, south, east, north); const rectangle2 = new import__320.Rectangle(east + 0.1, south, east + 0.2, north); expect(import__320.Rectangle.intersection(rectangle1, rectangle2)).not.toBeDefined(); expect(import__320.Rectangle.intersection(rectangle2, rectangle1)).not.toBeDefined(); }); it("union works without a result parameter", function() { const rectangle1 = new import__320.Rectangle(0.5, 0.1, 0.75, 0.9); const rectangle2 = new import__320.Rectangle(0.4, 0, 0.85, 0.8); const expected = new import__320.Rectangle(0.4, 0, 0.85, 0.9); const returnedResult = import__320.Rectangle.union(rectangle1, rectangle2); expect(returnedResult).toEqual(expected); }); it("union works with a result parameter", function() { const rectangle1 = new import__320.Rectangle(0.5, 0.1, 0.75, 0.9); const rectangle2 = new import__320.Rectangle(0.4, 0, 0.85, 0.8); const expected = new import__320.Rectangle(0.4, 0, 0.85, 0.9); const result = new import__320.Rectangle(-1, -1, 10, 10); const returnedResult = import__320.Rectangle.union(rectangle1, rectangle2, result); expect(result).toBe(returnedResult); expect(returnedResult).toEqual(expected); }); it("union works with first rectangle crossing the IDL", function() { const rectangle1 = new import__320.Rectangle(0.5, 0.1, -0.5, 0.9); const rectangle2 = new import__320.Rectangle(-0.85, 0, -0.4, 0.8); const expected = new import__320.Rectangle(0.5, 0, -0.4, 0.9); const returnedResult = import__320.Rectangle.union(rectangle1, rectangle2); expect(returnedResult).toEqualEpsilon(expected, import__320.Math.EPSILON15); }); it("union works with second rectangle crossing the IDL", function() { const rectangle1 = new import__320.Rectangle(0.5, 0.1, 0.75, 0.9); const rectangle2 = new import__320.Rectangle(0.6, 0, -0.2, 0.8); const expected = new import__320.Rectangle(0.5, 0, -0.2, 0.9); const returnedResult = import__320.Rectangle.union(rectangle1, rectangle2); expect(returnedResult).toEqualEpsilon(expected, import__320.Math.EPSILON15); }); it("union works with both rectangles crossing the IDL", function() { const rectangle1 = new import__320.Rectangle(0.5, 0.1, -0.4, 0.9); const rectangle2 = new import__320.Rectangle(0.4, 0, -0.5, 0.8); const expected = new import__320.Rectangle(0.4, 0, -0.4, 0.9); const returnedResult = import__320.Rectangle.union(rectangle1, rectangle2); expect(returnedResult).toEqualEpsilon(expected, import__320.Math.EPSILON15); }); it("union works with rectangles that span the entire globe", function() { const rectangle1 = new import__320.Rectangle( -import__320.Math.PI, -import__320.Math.PI_OVER_TWO, +import__320.Math.PI, 0 ); const rectangle2 = new import__320.Rectangle( -import__320.Math.PI, 0, +import__320.Math.PI, +import__320.Math.PI_OVER_TWO ); const expected = new import__320.Rectangle( -import__320.Math.PI, -import__320.Math.PI_OVER_TWO, +import__320.Math.PI, +import__320.Math.PI_OVER_TWO ); const returnedResult = import__320.Rectangle.union(rectangle1, rectangle2); expect(returnedResult).toEqualEpsilon(expected, import__320.Math.EPSILON15); }); it("expand works if rectangle needs to grow right", function() { const rectangle2 = new import__320.Rectangle(0.5, 0.1, 0.75, 0.9); const cartographic = new import__320.Cartographic(0.85, 0.5); const expected = new import__320.Rectangle(0.5, 0.1, 0.85, 0.9); const result = import__320.Rectangle.expand(rectangle2, cartographic); expect(result).toEqual(expected); }); it("expand works if rectangle needs to grow left", function() { const rectangle2 = new import__320.Rectangle(0.5, 0.1, 0.75, 0.9); const cartographic = new import__320.Cartographic(0.4, 0.5); const expected = new import__320.Rectangle(0.4, 0.1, 0.75, 0.9); const result = import__320.Rectangle.expand(rectangle2, cartographic); expect(result).toEqual(expected); }); it("expand works if rectangle needs to grow up", function() { const rectangle2 = new import__320.Rectangle(0.5, 0.1, 0.75, 0.9); const cartographic = new import__320.Cartographic(0.6, 1); const expected = new import__320.Rectangle(0.5, 0.1, 0.75, 1); const result = import__320.Rectangle.expand(rectangle2, cartographic); expect(result).toEqual(expected); }); it("expand works if rectangle needs to grow down", function() { const rectangle2 = new import__320.Rectangle(0.5, 0.1, 0.75, 0.9); const cartographic = new import__320.Cartographic(0.6, 0); const expected = new import__320.Rectangle(0.5, 0, 0.75, 0.9); const result = import__320.Rectangle.expand(rectangle2, cartographic); expect(result).toEqual(expected); }); it("expand works if rectangle does not need to grow", function() { const rectangle2 = new import__320.Rectangle(0.5, 0.1, 0.75, 0.9); const cartographic = new import__320.Cartographic(0.6, 0.5); const expected = new import__320.Rectangle(0.5, 0.1, 0.75, 0.9); const result = import__320.Rectangle.expand(rectangle2, cartographic); expect(result).toEqual(expected); }); it("expand works with a result parameter", function() { const rectangle2 = new import__320.Rectangle(0.5, 0.1, 0.75, 0.9); const cartographic = new import__320.Cartographic(0.85, 1); const expected = new import__320.Rectangle(0.5, 0.1, 0.85, 1); const result = new import__320.Rectangle(); const returnedResult = import__320.Rectangle.expand(rectangle2, cartographic, result); expect(returnedResult).toBe(returnedResult); expect(result).toEqual(expected); }); it("contains works", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); expect( import__320.Rectangle.contains(rectangle2, new import__320.Cartographic(west, south)) ).toEqual(true); expect( import__320.Rectangle.contains(rectangle2, new import__320.Cartographic(west, north)) ).toEqual(true); expect( import__320.Rectangle.contains(rectangle2, new import__320.Cartographic(east, south)) ).toEqual(true); expect( import__320.Rectangle.contains(rectangle2, new import__320.Cartographic(east, north)) ).toEqual(true); expect(import__320.Rectangle.contains(rectangle2, import__320.Rectangle.center(rectangle2))).toEqual( true ); expect( import__320.Rectangle.contains(rectangle2, new import__320.Cartographic(west - 0.1, south)) ).toEqual(false); expect( import__320.Rectangle.contains(rectangle2, new import__320.Cartographic(west, north + 0.1)) ).toEqual(false); expect( import__320.Rectangle.contains(rectangle2, new import__320.Cartographic(east, south - 0.1)) ).toEqual(false); expect( import__320.Rectangle.contains(rectangle2, new import__320.Cartographic(east + 0.1, north)) ).toEqual(false); }); it("contains works with rectangle across the IDL", function() { const west2 = import__320.Math.toRadians(170); const south2 = import__320.Math.toRadians(-10); const east2 = import__320.Math.toRadians(-170); const north2 = import__320.Math.toRadians(10); const rectangle2 = new import__320.Rectangle(west2, south2, east2, north2); expect( import__320.Rectangle.contains(rectangle2, new import__320.Cartographic(west2, south2)) ).toEqual(true); expect( import__320.Rectangle.contains(rectangle2, new import__320.Cartographic(west2, north2)) ).toEqual(true); expect( import__320.Rectangle.contains(rectangle2, new import__320.Cartographic(east2, south2)) ).toEqual(true); expect( import__320.Rectangle.contains(rectangle2, new import__320.Cartographic(east2, north2)) ).toEqual(true); expect(import__320.Rectangle.contains(rectangle2, import__320.Rectangle.center(rectangle2))).toEqual( true ); expect( import__320.Rectangle.contains(rectangle2, new import__320.Cartographic(west2 - 0.1, south2)) ).toEqual(false); expect( import__320.Rectangle.contains(rectangle2, new import__320.Cartographic(west2, north2 + 0.1)) ).toEqual(false); expect( import__320.Rectangle.contains(rectangle2, new import__320.Cartographic(east2, south2 - 0.1)) ).toEqual(false); expect( import__320.Rectangle.contains(rectangle2, new import__320.Cartographic(east2 + 0.1, north2)) ).toEqual(false); }); it("subsample works south of the equator", function() { const west2 = 0.1; const south2 = -0.3; const east2 = 0.2; const north2 = -0.4; const rectangle2 = new import__320.Rectangle(west2, south2, east2, north2); const returnedResult = import__320.Rectangle.subsample(rectangle2); expect(returnedResult).toEqual([ import__320.Ellipsoid.WGS84.cartographicToCartesian(import__320.Rectangle.northwest(rectangle2)), import__320.Ellipsoid.WGS84.cartographicToCartesian(import__320.Rectangle.northeast(rectangle2)), import__320.Ellipsoid.WGS84.cartographicToCartesian(import__320.Rectangle.southeast(rectangle2)), import__320.Ellipsoid.WGS84.cartographicToCartesian(import__320.Rectangle.southwest(rectangle2)) ]); }); it("subsample works with a result parameter", function() { const west2 = 0.1; const south2 = -0.3; const east2 = 0.2; const north2 = -0.4; const rectangle2 = new import__320.Rectangle(west2, south2, east2, north2); const cartesian0 = new import__320.Cartesian3(); const results = [cartesian0]; const returnedResult = import__320.Rectangle.subsample( rectangle2, import__320.Ellipsoid.WGS84, 0, results ); expect(results).toBe(returnedResult); expect(results[0]).toBe(cartesian0); expect(returnedResult).toEqual([ import__320.Ellipsoid.WGS84.cartographicToCartesian(import__320.Rectangle.northwest(rectangle2)), import__320.Ellipsoid.WGS84.cartographicToCartesian(import__320.Rectangle.northeast(rectangle2)), import__320.Ellipsoid.WGS84.cartographicToCartesian(import__320.Rectangle.southeast(rectangle2)), import__320.Ellipsoid.WGS84.cartographicToCartesian(import__320.Rectangle.southwest(rectangle2)) ]); }); it("subsample works north of the equator", function() { const west2 = 0.1; const south2 = 0.3; const east2 = 0.2; const north2 = 0.4; const rectangle2 = new import__320.Rectangle(west2, south2, east2, north2); const returnedResult = import__320.Rectangle.subsample(rectangle2); expect(returnedResult).toEqual([ import__320.Ellipsoid.WGS84.cartographicToCartesian(import__320.Rectangle.northwest(rectangle2)), import__320.Ellipsoid.WGS84.cartographicToCartesian(import__320.Rectangle.northeast(rectangle2)), import__320.Ellipsoid.WGS84.cartographicToCartesian(import__320.Rectangle.southeast(rectangle2)), import__320.Ellipsoid.WGS84.cartographicToCartesian(import__320.Rectangle.southwest(rectangle2)) ]); }); it("subsample works on the equator", function() { const west2 = 0.1; const south2 = -0.1; const east2 = 0.2; const north2 = 0; const rectangle2 = new import__320.Rectangle(west2, south2, east2, north2); const returnedResult = import__320.Rectangle.subsample(rectangle2); expect(returnedResult.length).toEqual(6); expect(returnedResult[0]).toEqual( import__320.Ellipsoid.WGS84.cartographicToCartesian(import__320.Rectangle.northwest(rectangle2)) ); expect(returnedResult[1]).toEqual( import__320.Ellipsoid.WGS84.cartographicToCartesian(import__320.Rectangle.northeast(rectangle2)) ); expect(returnedResult[2]).toEqual( import__320.Ellipsoid.WGS84.cartographicToCartesian(import__320.Rectangle.southeast(rectangle2)) ); expect(returnedResult[3]).toEqual( import__320.Ellipsoid.WGS84.cartographicToCartesian(import__320.Rectangle.southwest(rectangle2)) ); const cartographic4 = import__320.Ellipsoid.WGS84.cartesianToCartographic( returnedResult[4] ); expect(cartographic4.latitude).toEqual(0); expect(cartographic4.longitude).toEqualEpsilon(west2, import__320.Math.EPSILON16); const cartographic5 = import__320.Ellipsoid.WGS84.cartesianToCartographic( returnedResult[5] ); expect(cartographic5.latitude).toEqual(0); expect(cartographic5.longitude).toEqualEpsilon(east2, import__320.Math.EPSILON16); }); it("subsample works at a height above the ellipsoid", function() { const west2 = 0.1; const south2 = -0.3; const east2 = 0.2; const north2 = -0.4; const rectangle2 = new import__320.Rectangle(west2, south2, east2, north2); const height = 1e5; const returnedResult = import__320.Rectangle.subsample( rectangle2, import__320.Ellipsoid.WGS84, height ); const nw = import__320.Rectangle.northwest(rectangle2); nw.height = height; const ne = import__320.Rectangle.northeast(rectangle2); ne.height = height; const se = import__320.Rectangle.southeast(rectangle2); se.height = height; const sw = import__320.Rectangle.southwest(rectangle2); sw.height = height; expect(returnedResult).toEqual([ import__320.Ellipsoid.WGS84.cartographicToCartesian(nw), import__320.Ellipsoid.WGS84.cartographicToCartesian(ne), import__320.Ellipsoid.WGS84.cartographicToCartesian(se), import__320.Ellipsoid.WGS84.cartographicToCartesian(sw) ]); }); it("subsample throws with no rectangle", function() { expect(function() { import__320.Rectangle.subsample(); }).toThrowDeveloperError(); }); it("subsection works with a result parameter", function() { const west2 = 0; const east2 = 0.5; const south2 = 0; const north2 = 0.5; const rectangle2 = new import__320.Rectangle(west2, south2, east2, north2); const westLerp = 0.25; const eastLerp = 0.75; const southLerp = 0.25; const northLerp = 0.75; const expectedWest = 0.125; const expectedEast = 0.375; const expectedSouth = 0.125; const expectedNorth = 0.375; const expectedRectangle = new import__320.Rectangle( expectedWest, expectedSouth, expectedEast, expectedNorth ); const subsection = new import__320.Rectangle(); const result = import__320.Rectangle.subsection( rectangle2, westLerp, southLerp, eastLerp, northLerp, subsection ); expect(result).toEqual(expectedRectangle); expect(result).toBe(subsection); }); it("subsection works with no result parameter", function() { const west2 = 0; const east2 = 0.5; const south2 = 0; const north2 = 0.5; const rectangle2 = new import__320.Rectangle(west2, south2, east2, north2); const westLerp = 0.25; const eastLerp = 0.75; const southLerp = 0.25; const northLerp = 0.75; const expectedWest = 0.125; const expectedEast = 0.375; const expectedSouth = 0.125; const expectedNorth = 0.375; const expectedRectangle = new import__320.Rectangle( expectedWest, expectedSouth, expectedEast, expectedNorth ); const subsection = import__320.Rectangle.subsection( rectangle2, westLerp, southLerp, eastLerp, northLerp ); expect(subsection).toEqual(expectedRectangle); }); it("subsection works with empty range", function() { const west2 = 0; const east2 = 0.5; const south2 = 0; const north2 = 0.5; const rectangle2 = new import__320.Rectangle(west2, south2, east2, north2); const westLerp = 0; const eastLerp = 0; const southLerp = 0; const northLerp = 0; const expectedWest = west2; const expectedEast = west2; const expectedSouth = south2; const expectedNorth = south2; const expectedRectangle = new import__320.Rectangle( expectedWest, expectedSouth, expectedEast, expectedNorth ); const subsection = import__320.Rectangle.subsection( rectangle2, westLerp, southLerp, eastLerp, northLerp ); expect(subsection).toEqual(expectedRectangle); }); it("subsection works with full range", function() { const west2 = 0.1; const east2 = 0.9; const south2 = 0.1; const north2 = 0.9; const rectangle2 = new import__320.Rectangle(west2, south2, east2, north2); const westLerp = 0; const eastLerp = 1; const southLerp = 0; const northLerp = 1; const expectedWest = west2; const expectedEast = east2; const expectedSouth = south2; const expectedNorth = north2; const expectedRectangle = new import__320.Rectangle( expectedWest, expectedSouth, expectedEast, expectedNorth ); const subsection = import__320.Rectangle.subsection( rectangle2, westLerp, southLerp, eastLerp, northLerp ); expect(subsection).toEqual(expectedRectangle); }); it("subsection works with zero area rectangle", function() { const west2 = 0.1; const east2 = 0.1; const south2 = 0.1; const north2 = 0.1; const rectangle2 = new import__320.Rectangle(west2, south2, east2, north2); const westLerp = 0.22; const eastLerp = 0.88; const southLerp = 0.22; const northLerp = 0.88; const expectedWest = west2; const expectedEast = east2; const expectedSouth = south2; const expectedNorth = north2; const expectedRectangle = new import__320.Rectangle( expectedWest, expectedSouth, expectedEast, expectedNorth ); const subsection = import__320.Rectangle.subsection( rectangle2, westLerp, southLerp, eastLerp, northLerp ); expect(subsection).toEqual(expectedRectangle); }); it("subsection works with rectangle that crosses IDL and subsection that crosses IDL", function() { const west2 = import__320.Math.toRadians(45); const east2 = import__320.Math.toRadians(-45); const south2 = import__320.Math.toRadians(-90); const north2 = import__320.Math.toRadians(90); const rectangle2 = new import__320.Rectangle(west2, south2, east2, north2); const westLerp = 0.25; const eastLerp = 0.75; const southLerp = 0; const northLerp = 1; const expectedWest = import__320.Math.toRadians(112.5); const expectedEast = import__320.Math.toRadians(-112.5); const expectedSouth = south2; const expectedNorth = north2; const expectedRectangle = new import__320.Rectangle( expectedWest, expectedSouth, expectedEast, expectedNorth ); const subsection = import__320.Rectangle.subsection( rectangle2, westLerp, southLerp, eastLerp, northLerp ); expect(subsection).toEqualEpsilon(expectedRectangle, import__320.Math.EPSILON14); }); it("subsection works with rectangle that crosses IDL and subsection that doesn't cross IDL", function() { const west2 = import__320.Math.toRadians(45); const east2 = import__320.Math.toRadians(-45); const south2 = import__320.Math.toRadians(-90); const north2 = import__320.Math.toRadians(90); const rectangle2 = new import__320.Rectangle(west2, south2, east2, north2); const westLerp = 0.75; const eastLerp = 1; const southLerp = 0; const northLerp = 1; const expectedWest = import__320.Math.toRadians(-112.5); const expectedEast = east2; const expectedSouth = south2; const expectedNorth = north2; const expectedRectangle = new import__320.Rectangle( expectedWest, expectedSouth, expectedEast, expectedNorth ); const subsection = import__320.Rectangle.subsection( rectangle2, westLerp, southLerp, eastLerp, northLerp ); expect(subsection).toEqualEpsilon(expectedRectangle, import__320.Math.EPSILON14); }); it("subsection works with rectangle that crosses IDL and subsection with full range", function() { const west2 = import__320.Math.toRadians(45); const east2 = import__320.Math.toRadians(-45); const south2 = import__320.Math.toRadians(-90); const north2 = import__320.Math.toRadians(90); const rectangle2 = new import__320.Rectangle(west2, south2, east2, north2); const westLerp = 0; const eastLerp = 1; const southLerp = 0; const northLerp = 1; const expectedWest = west2; const expectedEast = east2; const expectedSouth = south2; const expectedNorth = north2; const expectedRectangle = new import__320.Rectangle( expectedWest, expectedSouth, expectedEast, expectedNorth ); const subsection = import__320.Rectangle.subsection( rectangle2, westLerp, southLerp, eastLerp, northLerp ); expect(subsection).toEqualEpsilon(expectedRectangle, import__320.Math.EPSILON14); }); it("subsection throws with no rectangle", function() { expect(function() { import__320.Rectangle.subsection(void 0); }).toThrowDeveloperError(); }); it("subsection throws with no westLerp", function() { expect(function() { import__320.Rectangle.subsection(new import__320.Rectangle(), void 0, 0, 0, 0); }).toThrowDeveloperError(); }); it("subsection throws with no southLerp", function() { expect(function() { import__320.Rectangle.subsection(new import__320.Rectangle(), 0, void 0, 0, 0); }).toThrowDeveloperError(); }); it("subsection throws with no eastLerp", function() { expect(function() { import__320.Rectangle.subsection(new import__320.Rectangle(), 0, 0, void 0, 0); }).toThrowDeveloperError(); }); it("subsection throws with no northLerp", function() { expect(function() { import__320.Rectangle.subsection(new import__320.Rectangle(), 0, 0, 0, void 0); }).toThrowDeveloperError(); }); it("subsection throws with out of range westLerp", function() { expect(function() { import__320.Rectangle.subsection(new import__320.Rectangle(), -0.1, 0, 0, 0); }).toThrowDeveloperError(); expect(function() { import__320.Rectangle.subsection(new import__320.Rectangle(), 1.1, 0, 0, 0); }).toThrowDeveloperError(); expect(function() { import__320.Rectangle.subsection(new import__320.Rectangle(), 0.5, 0, 0.4, 0); }).toThrowDeveloperError(); }); it("subsection throws with out of range southLerp", function() { expect(function() { import__320.Rectangle.subsection(new import__320.Rectangle(), 0, -0.1, 0, 0); }).toThrowDeveloperError(); expect(function() { import__320.Rectangle.subsection(new import__320.Rectangle(), 0, 1.1, 0, 0); }).toThrowDeveloperError(); expect(function() { import__320.Rectangle.subsection(new import__320.Rectangle(), 0, 0.5, 0, 0.4); }).toThrowDeveloperError(); }); it("subsection throws with out of range eastLerp", function() { expect(function() { import__320.Rectangle.subsection(new import__320.Rectangle(), 0, 0, -0.1, 0); }).toThrowDeveloperError(); expect(function() { import__320.Rectangle.subsection(new import__320.Rectangle(), 0, 0, 1.1, 0); }).toThrowDeveloperError(); expect(function() { import__320.Rectangle.subsection(new import__320.Rectangle(), 0.5, 0, 0.4, 0); }).toThrowDeveloperError(); }); it("subsection throws with out of range northLerp", function() { expect(function() { import__320.Rectangle.subsection(new import__320.Rectangle(), 0, 0, 0, -0.1); }).toThrowDeveloperError(); expect(function() { import__320.Rectangle.subsection(new import__320.Rectangle(), 0, 0, 0, 1.1); }).toThrowDeveloperError(); expect(function() { import__320.Rectangle.subsection(new import__320.Rectangle(), 0, 0.5, 0, 0.4); }).toThrowDeveloperError(); }); it("intersection throws with no rectangle", function() { expect(function() { import__320.Rectangle.intersection(void 0); }).toThrowDeveloperError(); }); it("intersection throws with no otherRectangle", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); expect(function() { import__320.Rectangle.intersection(rectangle2, void 0); }).toThrowDeveloperError(); }); it("union throws with no rectangle", function() { expect(function() { import__320.Rectangle.union(void 0); }).toThrowDeveloperError(); }); it("union throws with no otherRectangle", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); expect(function() { import__320.Rectangle.intersection(rectangle2, void 0); }).toThrowDeveloperError(); }); it("expand throws with no rectangle", function() { expect(function() { import__320.Rectangle.expand(void 0); }).toThrowDeveloperError(); }); it("expand throws with no cartographic", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); expect(function() { import__320.Rectangle.expand(rectangle2, void 0); }).toThrowDeveloperError(); }); it("contains throws with no cartographic", function() { const rectangle2 = new import__320.Rectangle(west, south, east, north); expect(function() { import__320.Rectangle.contains(rectangle2, void 0); }).toThrowDeveloperError(); }); it("fromBoundingSphere works with zero values", function() { const boundingSphere = new import__320.BoundingSphere(); const result = import__320.Rectangle.fromBoundingSphere(boundingSphere); const expectedRectangle = import__320.Rectangle.MAX_VALUE; expect(result).toEqualEpsilon(expectedRectangle, import__320.Math.EPSILON14); }); it("fromBoundingSphere works with non-zero values", function() { const boundingSphere = new import__320.BoundingSphere( new import__320.Cartesian3(1e7, 0, 0), 1e3 ); const result = import__320.Rectangle.fromBoundingSphere(boundingSphere); const expectedRectangle = new import__320.Rectangle(); expectedRectangle.west = -9999999966666667e-20; expectedRectangle.south = -10042880729608389e-20; expectedRectangle.east = 9999999966666667e-20; expectedRectangle.north = 10042880729608389e-20; expect(result).toEqualEpsilon(expectedRectangle, import__320.Math.EPSILON14); }); it("fromBoundingSphere works with bounding sphere centered at the poles", function() { const boundingSphere = new import__320.BoundingSphere( new import__320.Cartesian3(0, 0, import__320.Ellipsoid.WGS84.radii.z), 1e3 ); const result = import__320.Rectangle.fromBoundingSphere(boundingSphere); const expectedRectangle = new import__320.Rectangle(); expectedRectangle.west = -import__320.Math.PI_OVER_TWO; expectedRectangle.south = 1.5706400668742968; expectedRectangle.east = import__320.Math.PI; expectedRectangle.north = import__320.Math.PI_OVER_TWO; expect(result).toEqualEpsilon(expectedRectangle, import__320.Math.EPSILON14); }); it("fromBoundingSphere uses result parameter", function() { const boundingSphere = new import__320.BoundingSphere( new import__320.Cartesian3(1e7, 0, 0), 1e3 ); const result = new import__320.Rectangle(); const returned = import__320.Rectangle.fromBoundingSphere( boundingSphere, import__320.Ellipsoid.WGS84, result ); const expectedRectangle = new import__320.Rectangle(); expectedRectangle.west = -9999999966666667e-20; expectedRectangle.south = -10042880729608389e-20; expectedRectangle.east = 9999999966666667e-20; expectedRectangle.north = 10042880729608389e-20; expect(result).toEqualEpsilon(expectedRectangle, import__320.Math.EPSILON14); expect(returned).toBe(result); }); it("fromBoundingSphere throws with no bounding sphere", function() { expect(function() { import__320.Rectangle.fromBoundingSphere(void 0); }).toThrowDeveloperError(); }); const rectangle = new import__320.Rectangle(west, south, east, north); const packedInstance = [west, south, east, north]; createPackableSpecs_default(import__320.Rectangle, rectangle, packedInstance); }); // packages/engine/Specs/Core/RequestErrorEventSpec.js var import__321 = __toESM(require_Cesium(), 1); describe("Core/RequestErrorEvent", function() { it("parses response headers provided as a string", function() { const event = new import__321.RequestErrorEvent( 404, "foo", "This-is-a-test: first\r\nAnother: second value!" ); expect(event.responseHeaders).toEqual({ "This-is-a-test": "first", Another: "second value!" }); }); it("leaves the response headers alone if they're already specified as an object literal", function() { const event = new import__321.RequestErrorEvent(404, "foo", { "This-is-a-test": "first", Another: "second value!" }); expect(event.responseHeaders).toEqual({ "This-is-a-test": "first", Another: "second value!" }); }); }); // packages/engine/Specs/Core/RequestSchedulerSpec.js var import__322 = __toESM(require_Cesium(), 1); describe("Core/RequestScheduler", function() { let originalMaximumRequests; let originalMaximumRequestsPerServer; let originalPriorityHeapLength; let originalRequestsByServer; beforeAll(function() { originalMaximumRequests = import__322.RequestScheduler.maximumRequests; originalMaximumRequestsPerServer = import__322.RequestScheduler.maximumRequestsPerServer; originalPriorityHeapLength = import__322.RequestScheduler.priorityHeapLength; originalRequestsByServer = import__322.RequestScheduler.requestsByServer; }); beforeEach(function() { import__322.RequestScheduler.clearForSpecs(); import__322.RequestScheduler.requestsByServer = {}; }); afterEach(function() { import__322.RequestScheduler.maximumRequests = originalMaximumRequests; import__322.RequestScheduler.maximumRequestsPerServer = originalMaximumRequestsPerServer; import__322.RequestScheduler.priorityHeapLength = originalPriorityHeapLength; import__322.RequestScheduler.requestsByServer = originalRequestsByServer; }); it("request throws when request is undefined", function() { expect(function() { import__322.RequestScheduler.request(); }).toThrowDeveloperError(); }); it("request throws when request.url is undefined", function() { expect(function() { import__322.RequestScheduler.request( new import__322.Request({ requestFunction: function(url) { return void 0; } }) ); }).toThrowDeveloperError(); }); it("request throws when request.requestFunction is undefined", function() { expect(function() { import__322.RequestScheduler.request( new import__322.Request({ url: "file/path" }) ); }).toThrowDeveloperError(); }); it("getServer throws if url is undefined", function() { expect(function() { import__322.RequestScheduler.getServerKey(); }).toThrowDeveloperError(); }); it("getServer with https", function() { const server = import__322.RequestScheduler.getServerKey("https://test.invalid/1"); expect(server).toEqual("test.invalid:443"); }); it("getServer with http", function() { const server = import__322.RequestScheduler.getServerKey("http://test.invalid/1"); expect(server).toEqual("test.invalid:80"); }); it("honors maximumRequests", function() { import__322.RequestScheduler.maximumRequests = 2; const statistics = import__322.RequestScheduler.statistics; const deferreds = []; function requestFunction() { const deferred = (0, import__322.defer)(); deferreds.push(deferred); return deferred.promise; } function createRequest() { return new import__322.Request({ url: "http://test.invalid/1", requestFunction, throttle: true }); } const promise1 = import__322.RequestScheduler.request(createRequest()); const promise2 = import__322.RequestScheduler.request(createRequest()); import__322.RequestScheduler.update(); const promise3 = import__322.RequestScheduler.request(createRequest()); import__322.RequestScheduler.update(); expect(statistics.numberOfActiveRequests).toBe(2); expect(promise1).toBeDefined(); expect(promise2).toBeDefined(); expect(promise3).not.toBeDefined(); deferreds[0].resolve(); return promise1.then(function() { import__322.RequestScheduler.update(); expect(statistics.numberOfActiveRequests).toBe(1); const promise4 = import__322.RequestScheduler.request(createRequest()); import__322.RequestScheduler.update(); expect(statistics.numberOfActiveRequests).toBe(2); expect(promise4).toBeDefined(); const promise5 = import__322.RequestScheduler.request(createRequest()); import__322.RequestScheduler.update(); expect(statistics.numberOfActiveRequests).toBe(2); expect(promise5).not.toBeDefined(); import__322.RequestScheduler.maximumRequests = 3; const promise6 = import__322.RequestScheduler.request(createRequest()); import__322.RequestScheduler.update(); expect(statistics.numberOfActiveRequests).toBe(3); expect(promise6).toBeDefined(); import__322.RequestScheduler.update(); const length2 = deferreds.length; for (let i = 0; i < length2; ++i) { deferreds[i].resolve(); } return Promise.all([promise2, promise4, promise6]); }); }); it("honors maximumRequestsPerServer", function() { import__322.RequestScheduler.maximumRequestsPerServer = 2; const deferreds = []; function requestFunction() { const deferred = (0, import__322.defer)(); deferreds.push(deferred); return deferred.promise; } const url = "http://test.invalid/1"; const server = import__322.RequestScheduler.getServerKey(url); function createRequest() { return new import__322.Request({ url, requestFunction, throttleByServer: true }); } const promise1 = import__322.RequestScheduler.request(createRequest()); const promise2 = import__322.RequestScheduler.request(createRequest()); import__322.RequestScheduler.update(); const promise3 = import__322.RequestScheduler.request(createRequest()); import__322.RequestScheduler.update(); expect(import__322.RequestScheduler.numberOfActiveRequestsByServer(server)).toBe(2); expect(promise1).toBeDefined(); expect(promise2).toBeDefined(); expect(promise3).not.toBeDefined(); deferreds[0].resolve(); return promise1.then(function() { import__322.RequestScheduler.update(); expect(import__322.RequestScheduler.numberOfActiveRequestsByServer(server)).toBe(1); const promise4 = import__322.RequestScheduler.request(createRequest()); import__322.RequestScheduler.update(); expect(import__322.RequestScheduler.numberOfActiveRequestsByServer(server)).toBe(2); expect(promise4).toBeDefined(); const promise5 = import__322.RequestScheduler.request(createRequest()); import__322.RequestScheduler.update(); expect(import__322.RequestScheduler.numberOfActiveRequestsByServer(server)).toBe(2); expect(promise5).not.toBeDefined(); import__322.RequestScheduler.maximumRequestsPerServer = 3; const promise6 = import__322.RequestScheduler.request(createRequest()); import__322.RequestScheduler.update(); expect(import__322.RequestScheduler.numberOfActiveRequestsByServer(server)).toBe(3); expect(promise6).toBeDefined(); const length2 = deferreds.length; for (let i = 0; i < length2; ++i) { deferreds[i].resolve(); } import__322.RequestScheduler.update(); return Promise.all([promise2, promise3, promise4, promise5, promise6]); }); }); it("honors priorityHeapLength", function() { const deferred = (0, import__322.defer)(); const requests = []; function requestFunction() { return deferred.promise; } function createRequest(priority) { const request = new import__322.Request({ url: "http://test.invalid/1", requestFunction, throttle: true, priority }); requests.push(request); return request; } import__322.RequestScheduler.priorityHeapLength = 1; const firstRequest = createRequest(0); const promise = import__322.RequestScheduler.request(firstRequest).catch(function(error) { expect(error).toBeUndefined(); }); expect(promise).toBeDefined(); const promise2 = import__322.RequestScheduler.request(createRequest(1)); expect(promise2).toBeUndefined(); import__322.RequestScheduler.priorityHeapLength = 3; const promise3 = import__322.RequestScheduler.request(createRequest(2)); const promise4 = import__322.RequestScheduler.request(createRequest(3)); expect(promise4).toBeDefined(); const promise5 = import__322.RequestScheduler.request(createRequest(4)); expect(promise5).toBeUndefined(); import__322.RequestScheduler.priorityHeapLength = 2; expect(firstRequest.state).toBe(import__322.RequestState.CANCELLED); deferred.resolve(); import__322.RequestScheduler.update(); return Promise.all([promise, promise2, promise3, promise4, promise5]); }); function testImmediateRequest(url, dataOrBlobUri) { const statistics = import__322.RequestScheduler.statistics; const deferred = (0, import__322.defer)(); function requestFunction() { return deferred.promise; } const request = new import__322.Request({ url, requestFunction }); const promise = import__322.RequestScheduler.request(request); expect(promise).toBeDefined(); if (dataOrBlobUri) { expect(request.serverKey).toBeUndefined(); expect(statistics.numberOfActiveRequests).toBe(0); } else { expect(statistics.numberOfActiveRequests).toBe(1); expect( import__322.RequestScheduler.numberOfActiveRequestsByServer(request.serverKey) ).toBe(1); } deferred.resolve(); return promise.then(function() { expect(request.state).toBe(import__322.RequestState.RECEIVED); expect(statistics.numberOfActiveRequests).toBe(0); if (!dataOrBlobUri) { expect( import__322.RequestScheduler.numberOfActiveRequestsByServer(request.serverKey) ).toBe(0); } }); } it("data uri goes through immediately", function() { const dataUri = "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D"; return testImmediateRequest(dataUri, true); }); it("blob uri goes through immediately", function() { const uint8Array = new Uint8Array(4); const blob = new Blob([uint8Array], { type: "application/octet-stream" }); const blobUrl = window.URL.createObjectURL(blob); return testImmediateRequest(blobUrl, true); }); it("request goes through immediately when throttle is false", function() { const url = "https://test.invalid/1"; return testImmediateRequest(url, false); }); it("makes a throttled request", function() { const deferreds = []; function requestFunction() { const deferred = (0, import__322.defer)(); deferreds.push(deferred); return deferred.promise; } const request = new import__322.Request({ throttle: true, url: "https://test.invalid/1", requestFunction }); expect(request.state).toBe(import__322.RequestState.UNISSUED); const promise = import__322.RequestScheduler.request(request); expect(promise).toBeDefined(); expect(request.state).toBe(import__322.RequestState.ISSUED); import__322.RequestScheduler.update(); expect(request.state).toBe(import__322.RequestState.ACTIVE); deferreds[0].resolve(); return promise.then(function() { expect(request.state).toBe(import__322.RequestState.RECEIVED); }); }); it("cancels an issued request", function() { const statistics = import__322.RequestScheduler.statistics; function requestFunction() { return Promise.resolve(); } const request = new import__322.Request({ throttle: true, url: "https://test.invalid/1", requestFunction }); const promise = import__322.RequestScheduler.request(request); expect(request.state).toBe(import__322.RequestState.ISSUED); request.cancel(); import__322.RequestScheduler.update(); expect(request.state).toBe(import__322.RequestState.CANCELLED); expect(statistics.numberOfCancelledRequests).toBe(1); expect(statistics.numberOfCancelledActiveRequests).toBe(0); return promise.then(function() { fail("should not be called"); }).catch(function(error) { expect(request.state).toBe(import__322.RequestState.CANCELLED); }); }); it("cancels an active request", function() { const statistics = import__322.RequestScheduler.statistics; const cancelFunction = jasmine.createSpy("cancelFunction"); function requestFunction() { return (0, import__322.defer)().promise; } const request = new import__322.Request({ throttle: true, url: "https://test.invalid/1", requestFunction, cancelFunction }); const promise = import__322.RequestScheduler.request(request); import__322.RequestScheduler.update(); expect(request.state).toBe(import__322.RequestState.ACTIVE); request.cancel(); import__322.RequestScheduler.update(); expect(request.state).toBe(import__322.RequestState.CANCELLED); expect(statistics.numberOfCancelledRequests).toBe(1); expect(statistics.numberOfCancelledActiveRequests).toBe(1); expect( import__322.RequestScheduler.numberOfActiveRequestsByServer(request.serverKey) ).toBe(0); expect(cancelFunction).toHaveBeenCalled(); return promise.then(function() { fail("should not be called"); }).catch(function(error) { expect(request.state).toBe(import__322.RequestState.CANCELLED); }); }); it("handles request failure", function() { const statistics = import__322.RequestScheduler.statistics; const deferreds = []; function requestFunction() { const deferred = (0, import__322.defer)(); deferreds.push(deferred); return deferred.promise; } const request = new import__322.Request({ url: "https://test.invalid/1", requestFunction }); const promise = import__322.RequestScheduler.request(request); expect(request.state).toBe(import__322.RequestState.ACTIVE); expect(statistics.numberOfActiveRequests).toBe(1); deferreds[0].reject("Request failed"); return promise.then(function() { fail("should not be called"); }).catch(function(error) { expect(error).toBe("Request failed"); }).finally(function() { import__322.RequestScheduler.update(); expect(statistics.numberOfActiveRequests).toBe(0); }); }); it("prioritizes requests", function() { let currentPriority = 0; function getRequestFunction(priority) { return function() { expect(priority).toBeGreaterThan(currentPriority); currentPriority = priority; return Promise.resolve(); }; } function createRequest(priority) { return new import__322.Request({ throttle: true, url: "https://test.invalid/1", requestFunction: getRequestFunction(priority), priority }); } const length2 = import__322.RequestScheduler.priorityHeapLength; const promises = []; for (let i = 0; i < length2; ++i) { const priority = Math.random(); import__322.RequestScheduler.request(createRequest(priority)); } import__322.RequestScheduler.update(); expect(currentPriority).toBeGreaterThan(0); return Promise.all(promises); }); it("updates priority", function() { let invertPriority = false; function getPriorityFunction(priority) { return function() { if (invertPriority) { return 1 - priority; } return priority; }; } function requestFunction() { return Promise.resolve(); } function createRequest(priority) { return new import__322.Request({ throttle: true, url: "https://test.invalid/1", requestFunction, priorityFunction: getPriorityFunction(priority) }); } let i; let request; const length2 = import__322.RequestScheduler.priorityHeapLength; for (i = 0; i < length2; ++i) { const priority = i / (length2 - 1); request = createRequest(priority); request.testId = i; import__322.RequestScheduler.request(request); } import__322.RequestScheduler.maximumRequests = 0; import__322.RequestScheduler.update(); const requestHeap = import__322.RequestScheduler.requestHeap; const requests = []; let currentTestId = 0; while (requestHeap.length > 0) { request = requestHeap.pop(); requests.push(request); expect(request.testId).toBeGreaterThanOrEqual(currentTestId); currentTestId = request.testId; } for (i = 0; i < length2; ++i) { requestHeap.insert(requests[i]); } invertPriority = true; import__322.RequestScheduler.update(); while (requestHeap.length > 0) { request = requestHeap.pop(); expect(request.testId).toBeLessThanOrEqual(currentTestId); currentTestId = request.testId; } }); it("handles low priority requests", function() { function requestFunction() { return Promise.resolve(); } function createRequest(priority) { return new import__322.Request({ throttle: true, url: "https://test.invalid/1", requestFunction, priority }); } const highPriority = 0; const mediumPriority = 0.5; const lowPriority = 1; const length2 = import__322.RequestScheduler.priorityHeapLength; const promises = []; for (let i = 0; i < length2; ++i) { promises.push(import__322.RequestScheduler.request(createRequest(mediumPriority))); } let promise = import__322.RequestScheduler.request(createRequest(lowPriority)); expect(promise).toBeUndefined(); expect(import__322.RequestScheduler.statistics.numberOfCancelledRequests).toBe(0); promise = import__322.RequestScheduler.request(createRequest(highPriority)); expect(promise).toBeDefined(); expect(import__322.RequestScheduler.statistics.numberOfCancelledRequests).toBe(1); import__322.RequestScheduler.update(); return Promise.all(promises).catch(function(error) { }).then(function() { return promise; }); }); it("unthrottled requests starve throttled requests", function() { const deferreds = []; function requestFunction() { const deferred = (0, import__322.defer)(); deferreds.push(deferred); return deferred.promise; } function createRequest(throttle) { return new import__322.Request({ url: "http://test.invalid/1", requestFunction, throttle }); } const promises = []; const throttledRequest = createRequest(true); promises.push(import__322.RequestScheduler.request(throttledRequest)); for (let i = 0; i < import__322.RequestScheduler.maximumRequests; ++i) { promises.push(import__322.RequestScheduler.request(createRequest(false))); } import__322.RequestScheduler.update(); expect(throttledRequest.state).toBe(import__322.RequestState.ISSUED); deferreds[0].resolve(); return deferreds[0].promise.then(function() { import__322.RequestScheduler.update(); expect(throttledRequest.state).toBe(import__322.RequestState.ACTIVE); const length2 = deferreds.length; for (let i = 0; i < length2; ++i) { deferreds[i].resolve(); } return Promise.all(deferreds).catch(function(error) { expect(error).toBe(true); }); }); }); it("request throttled by server is cancelled", function() { const deferreds = []; const promises = []; function requestFunction() { const deferred = (0, import__322.defer)(); deferreds.push(deferred); return deferred.promise; } function createRequest(throttleByServer) { return new import__322.Request({ url: "http://test.invalid/1", requestFunction, throttle: throttleByServer, throttleByServer }); } for (let i = 0; i < import__322.RequestScheduler.maximumRequestsPerServer - 1; ++i) { promises.push(import__322.RequestScheduler.request(createRequest(false))); } const throttledRequest = createRequest(true); promises.push(import__322.RequestScheduler.request(throttledRequest)); promises.push(import__322.RequestScheduler.request(createRequest(false))); import__322.RequestScheduler.update(); expect(throttledRequest.state).toBe(import__322.RequestState.CANCELLED); const length2 = deferreds.length; for (let i = 0; i < length2; ++i) { deferreds[i].resolve(); } return Promise.all(promises).catch(function(e) { }); }); it("does not throttle requests when throttleRequests is false", function() { import__322.RequestScheduler.maximumRequests = 0; function requestFunction() { return Promise.resolve(); } import__322.RequestScheduler.throttleRequests = true; let request = new import__322.Request({ throttle: true, url: "https://test.invalid/1", requestFunction }); let promise = import__322.RequestScheduler.request(request); expect(promise).toBeUndefined(); import__322.RequestScheduler.throttleRequests = false; request = new import__322.Request({ throttle: true, url: "https://test.invalid/1", requestFunction }); promise = import__322.RequestScheduler.request(request); expect(promise).toBeDefined(); import__322.RequestScheduler.throttleRequests = true; return promise; }); it("does not throttle requests by server when throttleRequests is false", function() { import__322.RequestScheduler.maximumRequestsPerServer = 0; function requestFunction() { return Promise.resolve(); } import__322.RequestScheduler.throttleRequests = true; let request = new import__322.Request({ throttleByServer: true, url: "https://test.invalid/1", requestFunction }); let promise = import__322.RequestScheduler.request(request); expect(promise).toBeUndefined(); import__322.RequestScheduler.throttleRequests = false; request = new import__322.Request({ throttleByServer: true, url: "https://test.invalid/1", requestFunction }); promise = import__322.RequestScheduler.request(request); expect(promise).toBeDefined(); import__322.RequestScheduler.throttleRequests = true; return promise; }); it("debugShowStatistics", function() { spyOn(console, "log"); import__322.RequestScheduler.debugShowStatistics = true; const deferreds = []; const promises = []; function requestFunction() { const deferred = (0, import__322.defer)(); deferreds.push(deferred); return deferred.promise; } function createRequest() { return new import__322.Request({ url: "https://test.invalid/1", requestFunction }); } const requests = [createRequest(), createRequest(), createRequest()]; promises.push(import__322.RequestScheduler.request(requests[0])); promises.push(import__322.RequestScheduler.request(requests[1])); promises.push(import__322.RequestScheduler.request(requests[2])); import__322.RequestScheduler.update(); deferreds[0].reject(); requests[0].cancel(); requests[1].cancel(); requests[2].cancel(); return Promise.all( requests.map(function(request) { return request.deferred; }) ).finally(function() { import__322.RequestScheduler.update(); expect(console.log).toHaveBeenCalledWith( "Number of attempted requests: 3" ); expect(console.log).toHaveBeenCalledWith( "Number of cancelled requests: 3" ); expect(console.log).toHaveBeenCalledWith( "Number of cancelled active requests: 2" ); expect(console.log).toHaveBeenCalledWith("Number of failed requests: 1"); import__322.RequestScheduler.debugShowStatistics = false; const length2 = deferreds.length; for (let i = 0; i < length2; ++i) { deferreds[i].resolve(); } return Promise.all(promises).catch(function(e) { }); }); }); it("successful request causes requestCompletedEvent to be raised", function() { let deferred; function requestFunction() { deferred = (0, import__322.defer)(); return deferred.promise; } const request = new import__322.Request({ url: "https://test.invalid/1", requestFunction }); const promise = import__322.RequestScheduler.request(request); expect(promise).toBeDefined(); let eventRaised = false; const removeListenerCallback = import__322.RequestScheduler.requestCompletedEvent.addEventListener( function() { eventRaised = true; } ); deferred.resolve(); return promise.then(function() { expect(eventRaised).toBe(true); }).finally(function() { removeListenerCallback(); }); }); it("successful data request causes requestCompletedEvent to be raised", function() { let deferred; function requestFunction() { deferred = (0, import__322.defer)(); return deferred.promise; } const request = new import__322.Request({ url: "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D", requestFunction }); let eventRaised = false; const removeListenerCallback = import__322.RequestScheduler.requestCompletedEvent.addEventListener( function() { eventRaised = true; } ); const promise = import__322.RequestScheduler.request(request); expect(promise).toBeDefined(); deferred.resolve(); import__322.RequestScheduler.update(); return promise.then(function() { expect(eventRaised).toBe(true); }).finally(function() { removeListenerCallback(); }); }); it("successful blob request causes requestCompletedEvent to be raised", function() { let deferred; function requestFunction() { deferred = (0, import__322.defer)(); return deferred.promise; } const uint8Array = new Uint8Array(4); const blob = new Blob([uint8Array], { type: "application/octet-stream" }); const blobUrl = window.URL.createObjectURL(blob); const request = new import__322.Request({ url: blobUrl, requestFunction }); let eventRaised = false; const removeListenerCallback = import__322.RequestScheduler.requestCompletedEvent.addEventListener( function() { eventRaised = true; } ); const promise = import__322.RequestScheduler.request(request); expect(promise).toBeDefined(); deferred.resolve(); import__322.RequestScheduler.update(); return promise.then(function() { expect(eventRaised).toBe(true); }).finally(function() { removeListenerCallback(); }); }); it("unsuccessful requests raise requestCompletedEvent with error", function() { let deferred; function requestFunction() { deferred = (0, import__322.defer)(); return deferred.promise; } const request = new import__322.Request({ url: "https://test.invalid/1", requestFunction }); let eventRaised = false; const removeListenerCallback = import__322.RequestScheduler.requestCompletedEvent.addEventListener( function(error) { eventRaised = true; expect(error).toBeDefined(); } ); const promise = import__322.RequestScheduler.request(request); expect(promise).toBeDefined(); deferred.reject({ error: "error" }); import__322.RequestScheduler.update(); return promise.then(function() { fail(); }).catch(function(e) { expect(eventRaised).toBe(true); }).finally(function() { removeListenerCallback(); }); }); it("canceled requests do not cause requestCompletedEvent to be raised", function() { let cancelDeferred; function requestCancelFunction() { cancelDeferred = (0, import__322.defer)(); return cancelDeferred.promise; } const requestToCancel = new import__322.Request({ url: "https://test.invalid/1", requestFunction: requestCancelFunction }); const promise = import__322.RequestScheduler.request(requestToCancel); const removeListenerCallback = import__322.RequestScheduler.requestCompletedEvent.addEventListener( function() { fail("should not be called"); } ); requestToCancel.cancel(); import__322.RequestScheduler.update(); cancelDeferred.resolve(); removeListenerCallback(); return promise.then(function() { fail(); }).catch(function(error) { expect(error).toBeUndefined(); }); }); it("RequestScheduler.requestsByServer allows for custom maximum requests", function() { let promise; const promises = []; import__322.RequestScheduler.requestsByServer["test.invalid:80"] = 23; const deferred = (0, import__322.defer)(); for (let i = 0; i < 23; i++) { promise = import__322.RequestScheduler.request( new import__322.Request({ url: "http://test.invalid/1", throttle: true, throttleByServer: true, requestFunction: function() { return deferred.promise; } }) ); import__322.RequestScheduler.update(); expect(promise).toBeDefined(); promises.push(promise); } promise = import__322.RequestScheduler.request( new import__322.Request({ url: "http://test.invalid/1", throttle: true, throttleByServer: true, requestFunction: function() { return (0, import__322.defer)(); } }) ); expect(promise).toBeUndefined(); deferred.resolve(); return Promise.all(promises); }); it("serverHasOpenSlots works for single requests", function() { const deferreds = []; const promises = []; function requestFunction() { const deferred = (0, import__322.defer)(); deferreds.push(deferred); return deferred.promise; } function createRequest() { return new import__322.Request({ url: "https://test.invalid:80/1", requestFunction }); } import__322.RequestScheduler.maximumRequestsPerServer = 5; promises.push(import__322.RequestScheduler.request(createRequest())); promises.push(import__322.RequestScheduler.request(createRequest())); expect(import__322.RequestScheduler.serverHasOpenSlots("test.invalid:80")).toBe(true); promises.push(import__322.RequestScheduler.request(createRequest())); promises.push(import__322.RequestScheduler.request(createRequest())); promises.push(import__322.RequestScheduler.request(createRequest())); expect(import__322.RequestScheduler.serverHasOpenSlots("test.invalid:80")).toBe(false); const length2 = deferreds.length; for (let i = 0; i < length2; ++i) { deferreds[i].resolve(); } return Promise.all(promises).catch(function(e) { expect(e).toBe(true); }); }); it("serverHasOpenSlots works for multiple requests on a single server", function() { const deferreds = []; const promises = []; function requestFunction() { const deferred = (0, import__322.defer)(); deferreds.push(deferred); return deferred.promise; } function createRequest() { return new import__322.Request({ url: "https://test.invalid:80/1", requestFunction }); } import__322.RequestScheduler.maximumRequestsPerServer = 5; promises.push(import__322.RequestScheduler.request(createRequest())); promises.push(import__322.RequestScheduler.request(createRequest())); expect(import__322.RequestScheduler.serverHasOpenSlots("test.invalid:80", 3)).toBe( true ); expect(import__322.RequestScheduler.serverHasOpenSlots("test.invalid:80", 4)).toBe( false ); const length2 = deferreds.length; for (let i = 0; i < length2; ++i) { deferreds[i].resolve(); } return Promise.all(promises); }); }); // packages/engine/Specs/Core/RequestSpec.js var import__323 = __toESM(require_Cesium(), 1); describe("Core/Request", function() { it("sets correct properties in constructor", function() { const options = Object.freeze({ url: "https://www.example.com", requestFunction: Promise.resolve(), cancelFunction: () => void 0, priorityFunction: () => 1, priority: 1, throttle: true, throttleByServer: true, type: import__323.RequestType.IMAGERY, serverKey: "customKey" }); const request = new import__323.Request(options); expect(request.url).toBe(options.url); expect(request.requestFunction).toBe(options.requestFunction); expect(request.cancelFunction).toBe(options.cancelFunction); expect(request.priorityFunction).toBe(options.priorityFunction); expect(request.priority).toBe(options.priority); expect(request.throttle).toBe(options.throttle); expect(request.throttleByServer).toBe(options.throttleByServer); expect(request.type).toBe(options.type); expect(request.serverKey).toBe(options.serverKey); expect(request.state).toBe(import__323.RequestState.UNISSUED); }); it("cancels", function() { const request = new import__323.Request(); expect(request.cancelled).toBe(false); request.cancel(); expect(request.cancelled).toBe(true); }); it("cloning without options creates a request with the same properties", function() { const initialOptions = Object.freeze({ url: "https://www.example.com", requestFunction: Promise.resolve(), cancelFunction: () => void 0, priorityFunction: () => 1, priority: 1, throttle: true, throttleByServer: true, type: import__323.RequestType.IMAGERY, serverKey: "customKey" }); const request = new import__323.Request(initialOptions); const clone24 = request.clone(); expect(clone24.url).toBe(initialOptions.url); expect(clone24.requestFunction).toBe(initialOptions.requestFunction); expect(clone24.cancelFunction).toBe(initialOptions.cancelFunction); expect(clone24.priorityFunction).toBe(initialOptions.priorityFunction); expect(clone24.priority).toBe(initialOptions.priority); expect(clone24.throttle).toBe(initialOptions.throttle); expect(clone24.throttleByServer).toBe(initialOptions.throttleByServer); expect(clone24.type).toBe(initialOptions.type); expect(clone24.serverKey).toBe(initialOptions.serverKey); }); it("cloning with a result parameter updates the properties of the result", function() { const options1 = Object.freeze({ url: "https://www.example.com", requestFunction: Promise.resolve(), cancelFunction: () => void 0, priorityFunction: () => 1, priority: 1, throttle: true, throttleByServer: true, type: import__323.RequestType.IMAGERY, serverKey: "customKey" }); const options2 = Object.freeze({ url: "http://example.com", requestFunction: fetch, cancelFunction: () => "cancelled", priorityFunction: () => 2, priority: 2, throttle: false, throttleByServer: false, type: import__323.RequestType.TERRAIN, serverKey: "updatedKey" }); const request1 = new import__323.Request(options1); const request2 = new import__323.Request(options2); const clone24 = request2.clone(request1); expect(clone24.url).toBe(options2.url); expect(clone24.requestFunction).toBe(options2.requestFunction); expect(clone24.cancelFunction).toBe(options2.cancelFunction); expect(clone24.priorityFunction).toBe(options2.priorityFunction); expect(clone24.priority).toBe(options2.priority); expect(clone24.throttle).toBe(options2.throttle); expect(clone24.throttleByServer).toBe(options2.throttleByServer); expect(clone24.type).toBe(options2.type); expect(clone24.serverKey).toBe(options2.serverKey); }); }); // packages/engine/Specs/Core/ResourceSpec.js var import_urijs = __toESM(require_URI(), 1); var import__324 = __toESM(require_Cesium(), 1); // Specs/dataUriToBuffer.js function dataUriToBuffer(dataUri) { const binaryString = atob(dataUri.split(",")[1]); const length2 = binaryString.length; const bytes = new Uint8Array(length2); for (let i = 0; i < length2; ++i) { bytes[i] = binaryString.charCodeAt(i); } return bytes; } var dataUriToBuffer_default = dataUriToBuffer; // packages/engine/Specs/Core/ResourceSpec.js describe("Core/Resource", function() { const dataUri = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIW2Nk+M/wHwAEBgIA5agATwAAAABJRU5ErkJggg=="; let supportsImageBitmapOptions; beforeAll(function() { return import__324.Resource.supportsImageBitmapOptions().then(function(result) { supportsImageBitmapOptions = result; }); }); it("Constructor sets correct properties", function() { const proxy = new import__324.DefaultProxy("/proxy/"); const request = new import__324.Request(); function retryFunc() { } const resource = new import__324.Resource({ url: "http://test.com/tileset", queryParameters: { key1: "value1", key2: "value2" }, templateValues: { key3: "value3", key4: "value4" }, headers: { Accept: "application/test-type" }, proxy, retryCallback: retryFunc, retryAttempts: 4, request }); expect(resource.getUrlComponent(false, false)).toEqual( "http://test.com/tileset" ); expect(resource.getUrlComponent(true, false)).toEqual( "http://test.com/tileset?key1=value1&key2=value2" ); expect(resource.getUrlComponent(false, true)).toEqual( proxy.getURL("http://test.com/tileset") ); expect(resource.getUrlComponent(true, true)).toEqual( proxy.getURL("http://test.com/tileset?key1=value1&key2=value2") ); expect(resource.url).toEqual( proxy.getURL("http://test.com/tileset?key1=value1&key2=value2") ); expect(String(resource)).toEqual( proxy.getURL("http://test.com/tileset?key1=value1&key2=value2") ); expect(resource.queryParameters).toEqual({ key1: "value1", key2: "value2" }); expect(resource.templateValues).toEqual({ key3: "value3", key4: "value4" }); expect(resource.headers).toEqual({ Accept: "application/test-type" }); expect(resource.proxy).toBe(proxy); expect(resource.retryCallback).toBe(retryFunc); expect(resource.retryAttempts).toEqual(4); expect(resource._retryCount).toEqual(0); expect(resource.request).toBe(request); }); it("Constructor sets correct properties", function() { const url = "http://invalid.domain.com/tileset"; const resource = new import__324.Resource(url); expect(resource.url).toEqual(url); expect(String(resource)).toEqual(url); expect(resource.queryParameters).toEqual({}); expect(resource.templateValues).toEqual({}); expect(resource.headers).toEqual({}); expect(resource.proxy).toBeUndefined(); expect(resource.retryCallback).toBeUndefined(); expect(resource.retryAttempts).toEqual(0); expect(resource.request).toBeDefined(); }); it("_makeRequest returns undefined if the request is throttled", function() { const oldMaximumRequests = import__324.RequestScheduler.maximumRequests; import__324.RequestScheduler.maximumRequests = 0; const resource = new import__324.Resource({ url: "http://example.invalid/testuri", request: new import__324.Request({ throttle: true }) }); const promise = resource._makeRequest({ method: "GET" }); expect(promise).toBeUndefined(); import__324.RequestScheduler.maximumRequests = oldMaximumRequests; return promise; }); it("appendForwardSlash appends a /", function() { const resource = new import__324.Resource({ url: "http://test.com/tileset" }); expect(resource.url).toEqual("http://test.com/tileset"); resource.appendForwardSlash(); expect(resource.url).toEqual("http://test.com/tileset/"); }); it("Setting a url with a query string sets queryParameters correctly", function() { const resource = new import__324.Resource({ url: "http://test.com/tileset?foo=bar&baz=foo" }); expect(resource.getUrlComponent()).toEqual("http://test.com/tileset"); expect(resource.getUrlComponent(true)).toEqual( "http://test.com/tileset?foo=bar&baz=foo" ); expect(resource.queryParameters).toEqual({ foo: "bar", baz: "foo" }); }); it("Constructing with parseUrl false does not strip query parameters from url", function() { const resource = new import__324.Resource({ url: "http://test.com/tileset?foo=bar&baz=foo", parseUrl: false }); expect(resource.getUrlComponent()).toEqual( "http://test.com/tileset?foo=bar&baz=foo" ); expect(resource.getUrlComponent(true)).toEqual( "http://test.com/tileset?foo=bar&baz=foo" ); expect(resource.queryParameters).toEqual({}); }); it("createIfNeeded returns undefined, if parameter is undefined", function() { expect(import__324.Resource.createIfNeeded()).toBeUndefined(); }); it("createIfNeeded returns Resource, if parameter is a Resource", function() { const resource = new import__324.Resource({ url: "http://test.com/tileset" }); expect(import__324.Resource.createIfNeeded(resource)).toEqual(resource); }); it("createIfNeeded returns Resource, if parameter is a String", function() { const resource = import__324.Resource.createIfNeeded("http://test.com/tileset"); expect(resource.url).toEqual("http://test.com/tileset"); }); it("multiple values for query parameters are allowed", function() { const resource = new import__324.Resource( "http://test.com/tileset/endpoint?a=1&a=2&b=3&a=4" ); expect(resource.queryParameters.a).toEqual(["1", "2", "4"]); expect(resource.queryParameters.b).toEqual("3"); expect(resource.url).toEqual( "http://test.com/tileset/endpoint?a=1&a=2&a=4&b=3" ); }); it("multiple values for query parameters works with getDerivedResource without preserverQueryParameters", function() { const resource = new import__324.Resource( "http://test.com/tileset/endpoint?a=1&a=2&b=3&a=4" ); expect(resource.queryParameters.a).toEqual(["1", "2", "4"]); expect(resource.queryParameters.b).toEqual("3"); expect(resource.url).toEqual( "http://test.com/tileset/endpoint?a=1&a=2&a=4&b=3" ); const derived = resource.getDerivedResource({ url: "other_endpoint?a=5&b=6&a=7" }); expect(derived.queryParameters.a).toEqual(["5", "7"]); expect(derived.queryParameters.b).toEqual("6"); expect(derived.url).toEqual( "http://test.com/tileset/other_endpoint?a=5&a=7&b=6" ); }); it("multiple values for query parameters works with getDerivedResource with preserveQueryParameters", function() { const resource = new import__324.Resource( "http://test.com/tileset/endpoint?a=1&a=2&b=3&a=4" ); expect(resource.queryParameters.a).toEqual(["1", "2", "4"]); expect(resource.queryParameters.b).toEqual("3"); expect(resource.url).toEqual( "http://test.com/tileset/endpoint?a=1&a=2&a=4&b=3" ); const derived = resource.getDerivedResource({ url: "other_endpoint?a=5&b=6&a=7", preserveQueryParameters: true }); expect(derived.queryParameters.a).toEqual(["5", "7", "1", "2", "4"]); expect(derived.queryParameters.b).toEqual(["6", "3"]); expect(derived.url).toEqual( "http://test.com/tileset/other_endpoint?a=5&a=7&a=1&a=2&a=4&b=6&b=3" ); }); it("replaces templateValues in the url", function() { const resource = new import__324.Resource({ url: "http://test.com/tileset/{foo}/{bar}", templateValues: { foo: "test1", bar: "test2" } }); expect(resource.url).toEqual("http://test.com/tileset/test1/test2"); }); it("replaces numeric templateValues", function() { const resource = new import__324.Resource({ url: "http://test.com/tileset/{0}/{1}", templateValues: { 0: "test1", 1: "test2" } }); expect(resource.url).toEqual("http://test.com/tileset/test1/test2"); }); it("leaves templateValues unchanged that are not provided", function() { const resource = new import__324.Resource({ url: "http://test.com/tileset/{foo}/{bar}" }); expect(resource.url).toEqual("http://test.com/tileset/{foo}/{bar}"); }); it("url encodes replacement templateValues in the url", function() { const resource = new import__324.Resource({ url: "http://test.com/tileset/{foo}/{bar}", templateValues: { foo: "a/b", bar: "x$y#" } }); expect(resource.url).toEqual("http://test.com/tileset/a%2Fb/x%24y%23"); }); it("getDerivedResource sets correct properties", function() { const proxy = new import__324.DefaultProxy("/proxy/"); const request = new import__324.Request(); function retryFunc() { } const parent = new import__324.Resource({ url: "http://test.com/tileset?key=value", queryParameters: { foo: "bar" }, templateValues: { key5: "value5", key6: "value6" } }); parent.appendForwardSlash(); const resource = parent.getDerivedResource({ url: "tileset.json", queryParameters: { key1: "value1", key2: "value2" }, templateValues: { key3: "value3", key4: "value4" }, headers: { Accept: "application/test-type" }, proxy, retryCallback: retryFunc, retryAttempts: 4, request }); expect(resource.getUrlComponent(false, false)).toEqual( "http://test.com/tileset/tileset.json" ); expect(resource.getUrlComponent(true, false)).toEqual( "http://test.com/tileset/tileset.json?key1=value1&key2=value2&key=value&foo=bar" ); expect(resource.getUrlComponent(false, true)).toEqual( proxy.getURL("http://test.com/tileset/tileset.json") ); expect(resource.getUrlComponent(true, true)).toEqual( proxy.getURL( "http://test.com/tileset/tileset.json?key1=value1&key2=value2&key=value&foo=bar" ) ); expect(resource.url).toEqual( proxy.getURL( "http://test.com/tileset/tileset.json?key1=value1&key2=value2&key=value&foo=bar" ) ); expect(resource.queryParameters).toEqual({ foo: "bar", key: "value", key1: "value1", key2: "value2" }); expect(resource.templateValues).toEqual({ key5: "value5", key6: "value6", key3: "value3", key4: "value4" }); expect(resource.headers).toEqual({ Accept: "application/test-type" }); expect(resource.proxy).toBe(proxy); expect(resource.retryCallback).toBe(retryFunc); expect(resource.retryAttempts).toEqual(4); expect(resource._retryCount).toEqual(0); expect(resource.request).toBe(request); }); it("getDerivedResource works with directory parent resource", function() { const parent = new import__324.Resource({ url: "http://test.com/tileset/" }); expect(parent.url).toEqual("http://test.com/tileset/"); const resource = parent.getDerivedResource({ url: "tileset.json" }); expect(resource.url).toEqual("http://test.com/tileset/tileset.json"); }); it("getDerivedResource works with file parent resource", function() { const parent = new import__324.Resource({ url: "http://test.com/tileset/tileset.json" }); expect(parent.url).toEqual("http://test.com/tileset/tileset.json"); const resource = parent.getDerivedResource({ url: "0/0/0.b3dm" }); expect(resource.url).toEqual("http://test.com/tileset/0/0/0.b3dm"); }); it("getDerivedResource works with only template values", function() { const parent = new import__324.Resource({ url: "http://test.com/terrain/{z}/{x}/{y}.terrain" }); expect(parent.url).toEqual("http://test.com/terrain/{z}/{x}/{y}.terrain"); const resource = parent.getDerivedResource({ templateValues: { x: 1, y: 2, z: 0 } }); expect(resource.url).toEqual("http://test.com/terrain/0/1/2.terrain"); }); it("getDerivedResource works with only query parameters", function() { const parent = new import__324.Resource({ url: "http://test.com/terrain" }); expect(parent.url).toEqual("http://test.com/terrain"); const resource = parent.getDerivedResource({ queryParameters: { x: 1, y: 2, z: 0 } }); expect(resource.url).toEqual("http://test.com/terrain?x=1&y=2&z=0"); }); it("setQueryParameters with useAsDefault set to true", function() { const resource = new import__324.Resource({ url: "http://test.com/terrain", queryParameters: { x: 1, y: 2 } }); expect(resource.queryParameters).toEqual({ x: 1, y: 2 }); resource.setQueryParameters( { x: 3, y: 4, z: 0 }, true ); expect(resource.queryParameters).toEqual({ x: 1, y: 2, z: 0 }); }); it("setQueryParameters with useAsDefault set to false", function() { const resource = new import__324.Resource({ url: "http://test.com/terrain", queryParameters: { x: 1, y: 2 } }); expect(resource.queryParameters).toEqual({ x: 1, y: 2 }); resource.setQueryParameters( { x: 3, y: 4, z: 0 }, false ); expect(resource.queryParameters).toEqual({ x: 3, y: 4, z: 0 }); }); it("appendQueryParameters works with non-arrays", function() { const resource = new import__324.Resource({ url: "http://test.com/terrain", queryParameters: { x: 1, y: 2 } }); expect(resource.queryParameters).toEqual({ x: 1, y: 2 }); resource.appendQueryParameters({ x: 3, y: 4, z: 0 }); expect(resource.queryParameters).toEqual({ x: [3, 1], y: [4, 2], z: 0 }); }); it("appendQueryParameters works with arrays/non-arrays", function() { const resource = new import__324.Resource({ url: "http://test.com/terrain", queryParameters: { x: [1, 2], y: 2, z: [-1, -2] } }); expect(resource.queryParameters).toEqual({ x: [1, 2], y: 2, z: [-1, -2] }); resource.appendQueryParameters({ x: 3, y: [4, 5], z: [-3, -4] }); expect(resource.queryParameters).toEqual({ x: [3, 1, 2], y: [4, 5, 2], z: [-3, -4, -1, -2] }); }); it("setTemplateValues with useAsDefault set to true", function() { const resource = new import__324.Resource({ url: "http://test.com/terrain/{z}/{x}/{y}.terrain", templateValues: { x: 1, y: 2, map: "my map" } }); expect(resource.templateValues).toEqual({ x: 1, y: 2, map: "my map" }); resource.setTemplateValues( { x: 3, y: 4, z: 0, style: "my style" }, true ); expect(resource.templateValues).toEqual({ x: 1, y: 2, map: "my map", z: 0, style: "my style" }); }); it("setTemplateValues with useAsDefault set to false", function() { const resource = new import__324.Resource({ url: "http://test.com/terrain/{z}/{x}/{y}.terrain", templateValues: { x: 1, y: 2, map: "my map" } }); expect(resource.templateValues).toEqual({ x: 1, y: 2, map: "my map" }); resource.setTemplateValues( { x: 3, y: 4, z: 0, style: "my style" }, false ); expect(resource.templateValues).toEqual({ x: 3, y: 4, map: "my map", z: 0, style: "my style" }); }); it("retryOnFail doesn't exceed retryAttempts", function() { const cb = jasmine.createSpy("retry").and.returnValue(true); const resource = new import__324.Resource({ url: "http://test.com/terrain", retryCallback: cb, retryAttempts: 3 }); let promise = resource.retryOnError(); const promises = [promise]; for (let i = 1; i < 6; ++i) { promise = promise.then(function(result) { return resource.retryOnError(); }); promises.push(promise); } return Promise.all(promises).then(function(result) { expect(result).toEqual([true, true, true, false, false, false]); expect(cb.calls.count()).toEqual(3); expect(resource._retryCount).toEqual(3); }); }); it("retryOnFail returns value from callback", function() { let result = true; const cb = jasmine.createSpy("retry").and.callFake(function() { result = !result; return result; }); const resource = new import__324.Resource({ url: "http://test.com/terrain", retryCallback: cb, retryAttempts: 4 }); let promise = resource.retryOnError(); const promises = [promise]; for (let i = 1; i < 6; ++i) { promise = promise.then(function(result2) { return resource.retryOnError(); }); promises.push(promise); } return Promise.all(promises).then(function(result2) { expect(result2).toEqual([false, true, false, true, false, false]); expect(cb.calls.count()).toEqual(4); expect(resource._retryCount).toEqual(4); }); }); it("isDataUri returns correct values", function() { const dataResource = new import__324.Resource({ url: "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3" }); expect(dataResource.isDataUri).toBe(true); const resource = new import__324.Resource({ url: "http://invalid.uri/tileset" }); expect(resource.isDataUri).toBe(false); }); it("isBlobUri returns correct values", function() { const dataResource = new import__324.Resource({ url: "blob:d3958f5c-0777-0845-9dcf-2cb28783acaf" }); expect(dataResource.isBlobUri).toBe(true); const resource = new import__324.Resource({ url: "http://invalid.uri/tileset" }); expect(resource.isBlobUri).toBe(false); }); it("post calls with correct method", function() { const expectedUrl = "http://test.com/endpoint"; const expectedResponseType = "json"; const expectedData = { stuff: "myStuff" }; const expectedHeaders = { "X-My-Header": "My-Value" }; const expectedResult = { status: "success" }; const expectedMimeType = "application/test-data"; const resource = new import__324.Resource({ url: expectedUrl, headers: expectedHeaders }); spyOn(import__324.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toEqual(expectedUrl); expect(responseType).toEqual(expectedResponseType); expect(method).toEqual("POST"); expect(data).toEqual(expectedData); expect(headers["X-My-Header"]).toEqual("My-Value"); expect(headers["X-My-Other-Header"]).toEqual("My-Other-Value"); expect(overrideMimeType).toBe(expectedMimeType); deferred.resolve(expectedResult); }); return resource.post(expectedData, { responseType: expectedResponseType, headers: { "X-My-Other-Header": "My-Other-Value" }, overrideMimeType: expectedMimeType }).then(function(result) { expect(result).toEqual(expectedResult); }); }); it("static post calls with correct method", function() { const expectedUrl = "http://test.com/endpoint"; const expectedResponseType = "json"; const expectedData = { stuff: "myStuff" }; const expectedHeaders = { "X-My-Header": "My-Value" }; const expectedResult = { status: "success" }; const expectedMimeType = "application/test-data"; spyOn(import__324.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toEqual(expectedUrl); expect(responseType).toEqual(expectedResponseType); expect(method).toEqual("POST"); expect(data).toEqual(expectedData); expect(headers).toEqual(expectedHeaders); expect(overrideMimeType).toBe(expectedMimeType); deferred.resolve(expectedResult); }); return import__324.Resource.post({ url: expectedUrl, data: expectedData, responseType: expectedResponseType, headers: expectedHeaders, overrideMimeType: expectedMimeType }).then(function(result) { expect(result).toEqual(expectedResult); }); }); it("put calls with correct method", function() { const expectedUrl = "http://test.com/endpoint"; const expectedResponseType = "json"; const expectedData = { stuff: "myStuff" }; const expectedHeaders = { "X-My-Header": "My-Value" }; const expectedResult = { status: "success" }; const expectedMimeType = "application/test-data"; const resource = new import__324.Resource({ url: expectedUrl, headers: expectedHeaders }); spyOn(import__324.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toEqual(expectedUrl); expect(responseType).toEqual(expectedResponseType); expect(method).toEqual("PUT"); expect(data).toEqual(expectedData); expect(headers["X-My-Header"]).toEqual("My-Value"); expect(headers["X-My-Other-Header"]).toEqual("My-Other-Value"); expect(overrideMimeType).toBe(expectedMimeType); deferred.resolve(expectedResult); }); return resource.put(expectedData, { responseType: expectedResponseType, headers: { "X-My-Other-Header": "My-Other-Value" }, overrideMimeType: expectedMimeType }).then(function(result) { expect(result).toEqual(expectedResult); }); }); it("static put calls with correct method", function() { const expectedUrl = "http://test.com/endpoint"; const expectedResponseType = "json"; const expectedData = { stuff: "myStuff" }; const expectedHeaders = { "X-My-Header": "My-Value" }; const expectedResult = { status: "success" }; const expectedMimeType = "application/test-data"; spyOn(import__324.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toEqual(expectedUrl); expect(responseType).toEqual(expectedResponseType); expect(method).toEqual("PUT"); expect(data).toEqual(expectedData); expect(headers).toEqual(expectedHeaders); expect(overrideMimeType).toBe(expectedMimeType); deferred.resolve(expectedResult); }); return import__324.Resource.put({ url: expectedUrl, data: expectedData, responseType: expectedResponseType, headers: expectedHeaders, overrideMimeType: expectedMimeType }).then(function(result) { expect(result).toEqual(expectedResult); }); }); it("patch calls with correct method", function() { const expectedUrl = "http://test.com/endpoint"; const expectedResponseType = "json"; const expectedData = { stuff: "myStuff" }; const expectedHeaders = { "X-My-Header": "My-Value" }; const expectedResult = { status: "success" }; const expectedMimeType = "application/test-data"; const resource = new import__324.Resource({ url: expectedUrl, headers: expectedHeaders }); spyOn(import__324.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toEqual(expectedUrl); expect(responseType).toEqual(expectedResponseType); expect(method).toEqual("PATCH"); expect(data).toEqual(expectedData); expect(headers["X-My-Header"]).toEqual("My-Value"); expect(headers["X-My-Other-Header"]).toEqual("My-Other-Value"); expect(overrideMimeType).toBe(expectedMimeType); deferred.resolve(expectedResult); }); return resource.patch(expectedData, { responseType: expectedResponseType, headers: { "X-My-Other-Header": "My-Other-Value" }, overrideMimeType: expectedMimeType }).then(function(result) { expect(result).toEqual(expectedResult); }); }); it("static patch calls with correct method", function() { const expectedUrl = "http://test.com/endpoint"; const expectedResponseType = "json"; const expectedData = { stuff: "myStuff" }; const expectedHeaders = { "X-My-Header": "My-Value" }; const expectedResult = { status: "success" }; const expectedMimeType = "application/test-data"; spyOn(import__324.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toEqual(expectedUrl); expect(responseType).toEqual(expectedResponseType); expect(method).toEqual("PATCH"); expect(data).toEqual(expectedData); expect(headers).toEqual(expectedHeaders); expect(overrideMimeType).toBe(expectedMimeType); deferred.resolve(expectedResult); }); return import__324.Resource.patch({ url: expectedUrl, data: expectedData, responseType: expectedResponseType, headers: expectedHeaders, overrideMimeType: expectedMimeType }).then(function(result) { expect(result).toEqual(expectedResult); }); }); it("static fetchArrayBuffer calls correct method", function() { const url = "http://test.com/data"; const expectedResult = Promise.resolve(); spyOn(import__324.Resource.prototype, "fetchArrayBuffer").and.returnValue( expectedResult ); const result = import__324.Resource.fetchArrayBuffer(url); expect(result).toBe(expectedResult); return import__324.Resource.fetchArrayBuffer(url).then(function() { expect(import__324.Resource.prototype.fetchArrayBuffer).toHaveBeenCalled(); }); }); it("fetchArrayBuffer calls fetch with expected parameters", function() { const url = "http://test.com/data"; const expectedResult = Promise.resolve(); spyOn(import__324.Resource.prototype, "fetch").and.returnValue(expectedResult); const result = import__324.Resource.fetchArrayBuffer(url); expect(result).toBe(expectedResult); return result.then(function() { expect(import__324.Resource.prototype.fetch).toHaveBeenCalledWith({ responseType: "arraybuffer" }); }); }); it("static fetchBlob calls correct method", function() { const url = "http://test.com/data"; spyOn(import__324.Resource.prototype, "fetchBlob").and.returnValue(Promise.resolve()); return import__324.Resource.fetchBlob(url).then(function() { expect(import__324.Resource.prototype.fetchBlob).toHaveBeenCalled(); }); }); it("fetchBlob calls fetch with expected parameters", function() { const url = "http://test.com/data"; const expectedResult = Promise.resolve(); spyOn(import__324.Resource.prototype, "fetch").and.returnValue(expectedResult); const result = import__324.Resource.fetchBlob(url); expect(result).toBe(expectedResult); return result.then(function() { expect(import__324.Resource.prototype.fetch).toHaveBeenCalledWith({ responseType: "blob" }); }); }); it("fetchArrayBuffer calls fetch with expected parameters", function() { const url = "http://test.com/data"; const expectedResult = Promise.resolve(); spyOn(import__324.Resource.prototype, "fetch").and.returnValue(expectedResult); const result = import__324.Resource.fetchArrayBuffer(url); expect(result).toBe(expectedResult); return result.then(function() { expect(import__324.Resource.prototype.fetch).toHaveBeenCalledWith({ responseType: "arraybuffer" }); }); }); it("static fetchImage calls correct method", function() { const url = "http://test.com/data"; spyOn(import__324.Resource.prototype, "fetchImage").and.returnValue(Promise.resolve()); return import__324.Resource.fetchImage(url).then(function() { expect(import__324.Resource.prototype.fetchImage).toHaveBeenCalled(); }); }); it("static fetchText calls correct method", function() { const url = "http://test.com/data"; spyOn(import__324.Resource.prototype, "fetchText").and.returnValue(Promise.resolve()); return import__324.Resource.fetchText(url).then(function() { expect(import__324.Resource.prototype.fetchText).toHaveBeenCalled(); }); }); it("fetchText calls fetch with expected parameters", function() { const url = "http://test.com/data"; const expectedResult = Promise.resolve(); spyOn(import__324.Resource.prototype, "fetch").and.returnValue(expectedResult); const result = import__324.Resource.fetchText(url); expect(result).toBe(expectedResult); return result.then(function() { expect(import__324.Resource.prototype.fetch).toHaveBeenCalledWith({ responseType: "text" }); }); }); it("static fetchJson calls correct method", function() { const url = "http://test.com/data"; spyOn(import__324.Resource.prototype, "fetchJson").and.returnValue(Promise.resolve()); return import__324.Resource.fetchJson(url).then(function() { expect(import__324.Resource.prototype.fetchJson).toHaveBeenCalled(); }); }); it("fetchJson calls fetch with expected parameters and parses result", function() { const expectedResult = { x: 123 }; spyOn(import__324.Resource.prototype, "fetch").and.returnValue( Promise.resolve(JSON.stringify(expectedResult)) ); return import__324.Resource.fetchJson("url").then(function(result) { expect(result).toEqual(expectedResult); expect(import__324.Resource.prototype.fetch).toHaveBeenCalledWith({ responseType: "text", headers: { Accept: "application/json,*/*;q=0.01" } }); }); }); it("static fetchXML calls correct method", function() { const url = "http://test.com/data"; spyOn(import__324.Resource.prototype, "fetchXML").and.returnValue(Promise.resolve()); return import__324.Resource.fetchXML(url).then(function() { expect(import__324.Resource.prototype.fetchXML).toHaveBeenCalled(); }); }); it("fetchXML calls fetch with expected parameters", function() { const url = "http://test.com/data"; const expectedResult = Promise.resolve(); spyOn(import__324.Resource.prototype, "fetch").and.returnValue(expectedResult); const result = import__324.Resource.fetchXML(url); expect(result).toBe(expectedResult); return result.then(function() { expect(import__324.Resource.prototype.fetch).toHaveBeenCalledWith({ responseType: "document", overrideMimeType: "text/xml" }); }); }); it("static fetchJsonp calls correct method", function() { const url = "http://test.com/data"; spyOn(import__324.Resource.prototype, "fetchJsonp").and.returnValue(Promise.resolve()); return import__324.Resource.fetchJsonp(url).then(function() { expect(import__324.Resource.prototype.fetchJsonp).toHaveBeenCalled(); }); }); it("static fetch calls correct method", function() { const url = "http://test.com/data"; spyOn(import__324.Resource.prototype, "fetch").and.returnValue(Promise.resolve()); return import__324.Resource.fetch(url).then(function() { expect(import__324.Resource.prototype.fetch).toHaveBeenCalled(); }); }); it("fetch calls correct method", function() { const expectedUrl = "http://test.com/endpoint"; const expectedResult = { status: "success" }; spyOn(import__324.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toEqual(expectedUrl); expect(method).toEqual("GET"); deferred.resolve(expectedResult); }); const resource = new import__324.Resource({ url: expectedUrl }); return resource.fetch().then(function(result) { expect(result).toEqual(expectedResult); }); }); it("static delete calls correct method", function() { const url = "http://test.com/data"; spyOn(import__324.Resource.prototype, "delete").and.returnValue(Promise.resolve()); return import__324.Resource.delete(url).then(function() { expect(import__324.Resource.prototype.delete).toHaveBeenCalled(); }); }); it("delete calls correct method", function() { const expectedUrl = "http://test.com/endpoint"; const expectedResult = { status: "success" }; spyOn(import__324.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toEqual(expectedUrl); expect(method).toEqual("DELETE"); deferred.resolve(expectedResult); }); const resource = new import__324.Resource({ url: expectedUrl }); return resource.delete().then(function(result) { expect(result).toEqual(expectedResult); }); }); it("static head calls correct method", function() { const url = "http://test.com/data"; spyOn(import__324.Resource.prototype, "head").and.returnValue(Promise.resolve({})); return import__324.Resource.head(url).then(function() { expect(import__324.Resource.prototype.head).toHaveBeenCalled(); }); }); it("head calls correct method", function() { const expectedUrl = "http://test.com/endpoint"; const expectedResult = { "accept-ranges": "bytes", "access-control-allow-headers": "Origin, X-Requested-With, Content-Type, Accept", "access-control-allow-origin": "*", "cache-control": "public, max-age=0", connection: "keep-alive", "content-length": "883", "content-type": "image/png", date: "Tue, 13 Feb 2018 03:38:55 GMT", etag: 'W/"373-15e34d146a1"', vary: "Accept-Encoding", "x-powered-vy": "Express" }; let headerString = ""; for (const key in expectedResult) { if (expectedResult.hasOwnProperty(key)) { headerString += `${key}: ${expectedResult[key]}\r `; } } const fakeXHR = { status: 200, send: function() { this.onload(); }, open: function() { }, getAllResponseHeaders: function() { return headerString; } }; spyOn(window, "XMLHttpRequest").and.returnValue(fakeXHR); spyOn(import__324.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toEqual(expectedUrl); expect(method).toEqual("HEAD"); import__324.Resource._DefaultImplementations.loadWithXhr( url, responseType, method, data, headers, deferred, overrideMimeType ); }); const resource = new import__324.Resource({ url: expectedUrl }); return resource.head().then(function(result) { expect(result.date).toEqual(expectedResult.date); expect(result["last-modified"]).toEqual(expectedResult["last-modified"]); expect(result["x-powered-by"]).toEqual(expectedResult["x-powered-by"]); expect(result.etag).toEqual(expectedResult.etag); expect(result["content-type"]).toEqual(expectedResult["content-type"]); expect(result["access-control-allow-origin"]).toEqual( expectedResult["access-control-allow-origin"] ); expect(result["cache-control"]).toEqual(expectedResult["cache-control"]); expect(result["accept-ranges"]).toEqual(expectedResult["accept-ranges"]); expect(result["access-control-allow-headers"]).toEqual( expectedResult["access-control-allow-headers"] ); expect(result["content-length"]).toEqual( expectedResult["content-length"] ); }); }); it("static options calls correct method", function() { const url = "http://test.com/data"; spyOn(import__324.Resource.prototype, "options").and.returnValue(Promise.resolve({})); return import__324.Resource.options(url).then(function() { expect(import__324.Resource.prototype.options).toHaveBeenCalled(); }); }); it("options calls correct method", function() { const expectedUrl = "http://test.com/endpoint"; const expectedResult = { "access-control-allow-headers": "Origin, X-Requested-With, Content-Type, Accept", "access-control-allow-methods": "GET, PUT, POST, DELETE, OPTIONS", "access-control-allow-origin": "*", connection: "keep-alive", "content-length": "2", "content-type": "text/plain; charset=utf-8", date: "Tue, 13 Feb 2018 03:38:55 GMT", etag: 'W/"2-nOO9QiTIwXgNtWtBJezz8kv3SLc"', vary: "Accept-Encoding", "x-powered-vy": "Express" }; let headerString = ""; for (const key in expectedResult) { if (expectedResult.hasOwnProperty(key)) { headerString += `${key}: ${expectedResult[key]}\r `; } } const fakeXHR = { status: 200, send: function() { this.onload(); }, open: function() { }, getAllResponseHeaders: function() { return headerString; } }; spyOn(window, "XMLHttpRequest").and.returnValue(fakeXHR); spyOn(import__324.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toEqual(expectedUrl); expect(method).toEqual("OPTIONS"); import__324.Resource._DefaultImplementations.loadWithXhr( url, responseType, method, data, headers, deferred, overrideMimeType ); }); const resource = new import__324.Resource({ url: expectedUrl }); return resource.options().then(function(result) { expect(result.date).toEqual(expectedResult.date); expect(result["x-powered-by"]).toEqual(expectedResult["x-powered-by"]); expect(result.etag).toEqual(expectedResult.etag); expect(result["content-type"]).toEqual(expectedResult["content-type"]); expect(result["access-control-allow-origin"]).toEqual( expectedResult["access-control-allow-origin"] ); expect(result["access-control-allow-methods"]).toEqual( expectedResult["access-control-allow-methods"] ); expect(result["access-control-allow-headers"]).toEqual( expectedResult["access-control-allow-headers"] ); expect(result["content-length"]).toEqual( expectedResult["content-length"] ); }); }); it("can load an SVG", function() { return import__324.Resource.fetchImage("./Data/Images/Red16x16.svg").then(function(loadedImage) { expect(loadedImage.width).toEqual(16); expect(loadedImage.height).toEqual(16); }); }); it("can load a dimensionless SVG", function() { return import__324.Resource.fetchImage("./Data/Images/Blue.svg").then(function(loadedImage) { expect(loadedImage.width).toBeGreaterThan(0); expect(loadedImage.height).toBeGreaterThan(0); }); }); it("can load an image preferring blob", function() { return import__324.Resource.fetchImage("./Data/Images/Green.png", true).then(function(loadedImage) { expect(loadedImage.width).toEqual(1); expect(loadedImage.height).toEqual(1); }); }); it("can load an image from a data URI", function() { return import__324.Resource.fetchImage(dataUri).then(function(loadedImage) { expect(loadedImage.width).toEqual(1); expect(loadedImage.height).toEqual(1); }); }); describe("fetchImage with ImageBitmap", function() { let canvas; beforeAll(function() { canvas = createCanvas_default(1, 2); }); afterAll(function() { document.body.removeChild(canvas); }); function getColorAtPixel(image, x, y) { const context = canvas.getContext("2d"); context.drawImage(image, 0, 0, image.width, image.height); const imageData = context.getImageData(0, 0, 1, 1); return [ imageData.data[0], imageData.data[1], imageData.data[2], imageData.data[3] ]; } it("can call supportsImageBitmapOptions", function() { if (!supportsImageBitmapOptions) { return; } return import__324.Resource.supportsImageBitmapOptions().then(function(result) { expect(typeof result).toEqual("boolean"); }); }); it("can load and decode an image", function() { if (!supportsImageBitmapOptions) { return; } return import__324.Resource.fetchImage({ url: "./Data/Images/Green.png", preferImageBitmap: true }).then(function(loadedImage) { expect(loadedImage.width).toEqual(1); expect(loadedImage.height).toEqual(1); expect(loadedImage).toBeInstanceOf(ImageBitmap); }); }); it("correctly flips image when ImageBitmapOptions are supported", function() { if (!supportsImageBitmapOptions) { return; } return import__324.Resource.fetchImage({ url: "./Data/Images/BlueOverRed.png", flipY: true, preferImageBitmap: true }).then(function(loadedImage) { expect(getColorAtPixel(loadedImage, 0, 0)).toEqual([255, 0, 0, 255]); }); }); it("correctly loads image without flip when ImageBitmapOptions are supported", function() { if (!supportsImageBitmapOptions) { return; } return import__324.Resource.fetchImage({ url: "./Data/Images/BlueOverRed.png", flipY: false, preferImageBitmap: true }).then(function(loadedImage) { expect(getColorAtPixel(loadedImage, 0, 0)).toEqual([0, 0, 255, 255]); }); }); it("correctly ignores gamma color profile when ImageBitmapOptions are supported", function() { if (!supportsImageBitmapOptions) { return; } return import__324.Resource.fetchImage({ url: "./Data/Images/Gamma.png", flipY: false, skipColorSpaceConversion: true, preferImageBitmap: true }).then(function(loadedImage) { expect(getColorAtPixel(loadedImage, 0, 0)).toEqual([0, 136, 0, 255]); }); }); it("correctly allows gamma color profile when ImageBitmapOptions are supported", function() { if (!supportsImageBitmapOptions) { return; } return import__324.Resource.fetchImage({ url: "./Data/Images/Gamma.png", flipY: false, skipColorSpaceConversion: false, preferImageBitmap: true }).then(function(loadedImage) { expect(getColorAtPixel(loadedImage, 0, 0)).toEqual([0, 59, 0, 255]); }); }); it("correctly ignores custom color profile when ImageBitmapOptions are supported", function() { if (!supportsImageBitmapOptions) { return; } return import__324.Resource.fetchImage({ url: "./Data/Images/CustomColorProfile.png", flipY: false, skipColorSpaceConversion: true, preferImageBitmap: true }).then(function(loadedImage) { expect(getColorAtPixel(loadedImage, 0, 0)).toEqual([0, 136, 0, 255]); }); }); it("correctly allows custom color profile when ImageBitmapOptions are supported", function() { if (!supportsImageBitmapOptions) { return; } return import__324.Resource.fetchImage({ url: "./Data/Images/CustomColorProfile.png", flipY: false, skipColorSpaceConversion: false, preferImageBitmap: true }).then(function(loadedImage) { expect(getColorAtPixel(loadedImage, 0, 0)).toEqual([193, 0, 0, 255]); }); }); it("does not use ImageBitmap when ImageBitmapOptions are not supported", function() { if (!supportsImageBitmapOptions) { return; } spyOn(import__324.Resource, "supportsImageBitmapOptions").and.returnValue( Promise.resolve(false) ); spyOn(window, "createImageBitmap").and.callThrough(); return import__324.Resource.fetchImage({ url: "./Data/Images/Green.png", preferImageBitmap: true }).then(function() { expect(window.createImageBitmap).not.toHaveBeenCalledWith(); }); }); it("rejects the promise when the image errors", function() { if (!supportsImageBitmapOptions) { return; } return import__324.Resource.fetchImage({ url: "http://example.invalid/testuri.png", preferImageBitmap: true }).then(function() { fail("expected promise to reject"); }).catch(function(error) { expect(error).toBeInstanceOf(import__324.RequestErrorEvent); }); }); it("rejects the promise with extra error information when image errors and options.preferBlob is true", function() { if (!supportsImageBitmapOptions) { return; } spyOn(import__324.Resource.prototype, "fetch").and.returnValue( Promise.resolve(new Blob([new Uint8Array([])], { type: "text/plain" })) ); return import__324.Resource.fetchImage({ url: "http://example.invalid/testuri.png", preferImageBitmap: true, preferBlob: true }).then(function() { fail("expected promise to reject"); }).catch(function(error) { expect(error.blob).toBeInstanceOf(Blob); }); }); }); describe("fetchImage without ImageBitmap", function() { beforeAll(function() { spyOn(import__324.Resource, "supportsImageBitmapOptions").and.returnValue( Promise.resolve(false) ); }); it("can load an image", function() { return import__324.Resource.fetchImage("./Data/Images/Green.png").then(function(loadedImage) { expect(loadedImage.width).toEqual(1); expect(loadedImage.height).toEqual(1); }); }); it("sets the crossOrigin property for cross-origin images", function() { const fakeImage = {}; const deferred = (0, import__324.defer)(); const imageConstructorSpy = spyOn(window, "Image").and.callFake( function() { deferred.resolve(); return fakeImage; } ); deferred.promise.then(function() { fakeImage.onload(); }); return import__324.Resource.fetchImage("http://example.invalid/someImage.png").then( function() { expect(imageConstructorSpy).toHaveBeenCalled(); expect(fakeImage.crossOrigin).toEqual(""); } ); }); it("does not set the crossOrigin property for non-cross-origin images", function() { const fakeImage = {}; const deferred = (0, import__324.defer)(); const imageConstructorSpy = spyOn(window, "Image").and.callFake( function() { deferred.resolve(); return fakeImage; } ); deferred.promise.then(function() { fakeImage.onload(); }); return import__324.Resource.fetchImage("./someImage.png").then(function() { expect(imageConstructorSpy).toHaveBeenCalled(); expect(fakeImage.crossOrigin).toBeUndefined(); }); }); it("does not set the crossOrigin property for data URIs", function() { const fakeImage = {}; const deferred = (0, import__324.defer)(); const imageConstructorSpy = spyOn(window, "Image").and.callFake( function() { deferred.resolve(); return fakeImage; } ); deferred.promise.then(function() { fakeImage.onload(); }); return import__324.Resource.fetchImage(dataUri).then(function() { expect(imageConstructorSpy).toHaveBeenCalled(); expect(fakeImage.crossOrigin).toBeUndefined(); }); }); it("resolves the promise when the image loads", function() { const fakeImage = {}; const deferred = (0, import__324.defer)(); spyOn(window, "Image").and.callFake(function() { deferred.resolve(); return fakeImage; }); let success = false; let failure = false; let loadedImage; deferred.promise.then(function() { expect(success).toEqual(false); expect(failure).toEqual(false); fakeImage.onload(); }); const promise = Promise.resolve(import__324.Resource.fetchImage(dataUri)).then(function(image) { success = true; loadedImage = image; }).catch(function() { failure = true; }); return promise.finally(function() { expect(success).toEqual(true); expect(failure).toEqual(false); expect(loadedImage).toBe(fakeImage); }); }); it("rejects the promise when the image errors", function() { const deferred = (0, import__324.defer)(); const fakeImage = {}; spyOn(window, "Image").and.callFake(function() { deferred.resolve(); return fakeImage; }); let success = false; let failure = false; let loadedImage; deferred.promise.then(function() { expect(success).toEqual(false); expect(failure).toEqual(false); fakeImage.onerror(new Error()); }); return import__324.Resource.fetchImage(dataUri).then(function(image) { success = true; loadedImage = image; }).catch(function() { failure = true; }).finally(function() { expect(success).toEqual(false); expect(failure).toEqual(true); expect(loadedImage).toBeUndefined(); }); }); it("Calls loadWithXhr with blob response type if headers is set", function() { const expectedUrl = "http://example.invalid/testuri.png"; const expectedHeaders = { "X-my-header": "my-value" }; spyOn(import__324.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toEqual(expectedUrl); expect(headers).toEqual(expectedHeaders); expect(responseType).toEqual("blob"); const binary = dataUriToBuffer_default(dataUri); deferred.resolve(new Blob([binary], { type: "image/png" })); }); const testResource = new import__324.Resource({ url: expectedUrl, headers: expectedHeaders }); const promise = testResource.fetchImage(); expect(promise).toBeDefined(); return promise.then(function(image) { expect(image).toBeDefined(); }); }); it("Doesn't call loadWithXhr with blob response type if headers is set but is a data URI", function() { spyOn(import__324.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { deferred.reject("this shouldn't happen"); }); spyOn(import__324.Resource._Implementations, "createImage").and.callFake(function(url, crossOrigin, deferred) { expect(url).toEqual(dataUri); }).and.callThrough(); const testResource = new import__324.Resource({ url: dataUri, headers: { "X-my-header": "my-value" } }); const promise = testResource.fetchImage(); expect(promise).toBeDefined(); return promise.then(function(image) { expect(image).toBeDefined(); }); }); describe("retries when Resource has the callback set", function() { it("rejects after too many retries", function() { let deferred = (0, import__324.defer)(); let fakeImage = {}; spyOn(window, "Image").and.callFake(function() { deferred.resolve(); fakeImage = {}; return fakeImage; }); const cb = jasmine.createSpy("retry").and.returnValue(true); const resource = new import__324.Resource({ url: "http://example.invalid/image.png", retryCallback: cb, retryAttempts: 1 }); deferred.promise.then(function() { fakeImage.onerror("some error"); deferred = (0, import__324.defer)(); return deferred.promise; }).then(function() { fakeImage.onerror(); }); let success = false; let failure = false; return resource.fetchImage().then(function() { success = true; }).catch(function() { failure = true; }).finally(function() { expect(cb.calls.count()).toEqual(1); const receivedResource = cb.calls.argsFor(0)[0]; expect(receivedResource.url).toEqual(resource.url); expect(receivedResource._retryCount).toEqual(1); expect(cb.calls.argsFor(0)[1]).toEqual("some error"); expect(success).toBe(false); expect(failure).toBe(true); }); }); it("rejects after callback returns false", function() { const deferred = (0, import__324.defer)(); let fakeImage = {}; spyOn(window, "Image").and.callFake(function() { deferred.resolve(); fakeImage = {}; return fakeImage; }); const cb = jasmine.createSpy("retry").and.returnValue(false); const resource = new import__324.Resource({ url: "http://example.invalid/image.png", retryCallback: cb, retryAttempts: 2 }); deferred.promise.then(function() { fakeImage.onerror("some error"); }); let success = false; let failure = false; return resource.fetchImage().then(function(value) { success = true; }).catch(function(error) { failure = true; }).finally(function() { expect(success).toBe(false); expect(failure).toBe(true); expect(cb.calls.count()).toEqual(1); const receivedResource = cb.calls.argsFor(0)[0]; expect(receivedResource.url).toEqual(resource.url); expect(receivedResource._retryCount).toEqual(1); expect(cb.calls.argsFor(0)[1]).toEqual("some error"); }); }); it("resolves after retry", function() { let deferred = (0, import__324.defer)(); let fakeImage = {}; spyOn(window, "Image").and.callFake(function() { deferred.resolve(); fakeImage = {}; return fakeImage; }); const cb = jasmine.createSpy("retry").and.returnValue(true); const resource = new import__324.Resource({ url: "http://example.invalid/image.png", retryCallback: cb, retryAttempts: 1 }); deferred.promise.then(function() { fakeImage.onerror("some error"); deferred = (0, import__324.defer)(); return deferred.promise; }).then(function() { fakeImage.onload(); }); let success = false; let failure = false; return resource.fetchImage().then(function(value) { success = true; }).catch(function(error) { failure = true; }).finally(function() { expect(cb.calls.count()).toEqual(1); const receivedResource = cb.calls.argsFor(0)[0]; expect(receivedResource.url).toEqual(resource.url); expect(receivedResource._retryCount).toEqual(1); expect(cb.calls.argsFor(0)[1]).toEqual("some error"); fakeImage.onload(); expect(success).toBe(true); expect(failure).toBe(false); }); }); }); }); describe("loadWithXhr", function() { const loadWithXhr = function(options) { const resource = new import__324.Resource(options); return resource._makeRequest({ responseType: options.responseType, overrideMimeType: options.overrideMimeType, method: (0, import__324.defaultValue)(options.method, "GET"), data: options.data }); }; describe("data URI loading", function() { it("can load URI escaped text with default response type", function() { return loadWithXhr({ url: "data:,Hello%2C%20World!" }).then(function(result) { expect(result).toEqual("Hello, World!"); }); }); it("can load URI escaped text with responseType=text", function() { return loadWithXhr({ url: "data:,Hello%2C%20World!", responseType: "text" }).then(function(result) { expect(result).toEqual("Hello, World!"); }); }); it("can load Base64 encoded text with default response type", function() { return loadWithXhr({ url: "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==" }).then(function(result) { expect(result).toEqual("Hello, World!"); }); }); it("can load Base64 encoded text with responseType=text", function() { return loadWithXhr({ url: "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==", responseType: "text" }).then(function(result) { expect(result).toEqual("Hello, World!"); }); }); it("can load Base64 & URI encoded text with default responseType", function() { return loadWithXhr({ url: "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D" }).then(function(result) { expect(result).toEqual("Hello, World!"); }); }); it("can load Base64 & URI encoded text with responseType=text", function() { return loadWithXhr({ url: "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D", responseType: "text" }).then(function(result) { expect(result).toEqual("Hello, World!"); }); }); it("can load URI escaped HTML as text with default responseType", function() { return loadWithXhr({ url: "data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E" }).then(function(result) { expect(result).toEqual("

Hello, World!

"); }); }); it("can load URI escaped HTML as text with responseType=text", function() { return loadWithXhr({ url: "data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E", responseType: "text" }).then(function(result) { expect(result).toEqual("

Hello, World!

"); }); }); it("can load URI escaped text as JSON", function() { return loadWithXhr({ url: "data:application/json,%7B%22key%22%3A%22value%22%7D", responseType: "json" }).then(function(result) { expect(result.key).toEqual("value"); }); }); it("can load Base64 encoded text as JSON", function() { return loadWithXhr({ url: "data:application/json;base64,eyJrZXkiOiJ2YWx1ZSJ9", responseType: "json" }).then(function(result) { expect(result.key).toEqual("value"); }); }); it("can load URI escaped HTML as document", function() { return loadWithXhr({ url: "data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E", responseType: "document" }).then(function(result) { expect(result.querySelector("h1")).not.toBeNull(); }); }); const tile = "data:;base64,rZ+P95jW+j0AAABAplRYwQAAAAAAAAAAFwEcw/RY1UUqDN/so3WJQETWnpq/aabA19EOeYzEh8D+6WPqtldYQYlaPeMGcRRAO+KDbxWIcsMAAAAAAAAAANsAAAD+N/03/mf/UQDq/f/+T/8foDBgL/8TACwAWP8H/xf/H/8b/yMAGP8r/wv/H/8P/w8ACP8PAEj/F/8TADwAIAAg/w8AMAAg/wcAGP8v/xf/J4gPIBOnIv8P/wf/FwAo/xfkM+MXACwACAAAAAgAGAAA/w//B/8P/wf/D/8XmgmZGf8XAAgAEBYZFQkAGAAQABj/DwAQAAgAEAAA/w8ACP8P/w8AIP8v2QD9DScR/w8AGAAQABAACAAQABwABAAIAAAAAAAI/xf/HwAQ/y8ADP8j/wf/D/8HRAlDEQAAABAAIP8fADAAFP8P/xP/H/8H5wf4Ag8TAAAABAAEAAD/D/8HAAAAAAAANhLKBf8HABAAIAAA/y95GHoIAAD/D/8DAAz/BwAAAAD/DwAAAAAAAAAAABD/Gz4Vwhb/G/8XAKz9t/4XAAj/D/0P/g8AAP0PAAAAAP4P/Q8AAAAAAAD+//8TABT/PwBA/y8AGP8n/w8AKAAYABAAAAAAAAAAAP8PABD/DwAQAAD/DwAIAAgAAP8PABD9//4P/Q/+H/8P/Q/+EwAYAAz/H/8PABj9H/43ABAACP1PAADWBdUF/gMADv0R/g8AEP8LdwCHBwAI/wsACP8HAAAACAAMAAQACP8DAAwACP8P/wcAIP8PABAACAAE/xsAAP8HABj/H/8HABT/CwAQABAAAL4WFwSlAv8PABAAAAAIAAh0A4wEAAD/B/8P/w8AAAAQAAgAEAAQ/wcAAAAI9wQHCwAAABAAAAgI+Af/BwAA/wcAEAAA/xf/BwAYAAAAGAAAAAD/DwAQuw/4AMQO/w8AGAAAAAAAEP8HAAT/E/8HABAAIFESUgoACP8D/wsAFP8T/w//D/8H1hvVA/8PACAADAAEAAgABAAQ/xMACP8HYREzDGkK/w8AHP8j/w8AAAAY/w8AMP8P5hoaHf8PACD/BwAQAAQ5HjoS/yf/HwAU/xv/B/8P/w8AEP8PACAAEAAgAAj/G7ItTh7/CwAIAAQACP8f/w//D/8P/w//DwAQ/w//DwAAAEAAEAAQABAAEP8TAAT/B/8H/wcACP8HABj/JwAIAAD/D/8P/w//D/8PAAD/DwAA/w8AAP8PAAD/D/8H/wcAQAAA/w8AAAAA/w8ABAAAABT/JwAIAAD/BwAYABD/D/83ABBwbM1nul3BXggB7QCqADoARH8JagIPNQkNGk5YCQunTVhLcUvMAAsBWAAbAKkArQCgAckA0AAXABwAGwCCAL4AHgqlCgIWfxVhAGAA3wByAKTgYdIxDm8AIwAxAIYAQwAYqNmncha+DYckCgDaADcAiwCuAs4GFAUvBlcI0vb59iAAYQAHAHbgr986A34DMgGBCbIAOABKAH4AlwDMABUB4QC4AdkBDm0OV83CDQCdAPsAPgAuAdwA6AAzAD4W3QmLC+Rs3WzvANwAgQPOCxEAuwomAFUAXoP9gygAKiIvEVYKWQUlFJsAWgQUBrYPnGdRNw9MQgAVAGAAlAA4AHMAkgAXASYApJgDkeZO+VX8BVQRkxb8w2vEpQB0AEcAHgCOAIAAWwCgAFMACQApAE0AKAA5AHTgz99zAD4AtABVAK4ApwCfAD8ApgAeAGMAagBYAD8AwwBMACAAEwBkAAgBLQCKZhlmQgA+AJxXuxLVRE8ATQCAAfIkBxvDA6kIEQA5AAIAPgA1ACwAEAAcADIAFwCSALkAIgGlAZwAnADrAJkAKQAJAMYAcwAaAG0ADwAFALcBuACSAQAAAAAAAAAAAwAAAAMAAwAAAAMABAACAAAABgAAAAAABQAIAAEAAgAIAAAABwABAAkABwAAAAAAAAADAAoACAABAAoAAgAEAAoACAAAAAAACgAAAAQAAQALAAIAAQAAAAUAAQAAAAYABgABAAgAAAAJAAAAAQAKAAMACgACAAkACwAJAAAACgADAAEAAQAOAAwAAAAPAAIADwABAAAAAQAAABEAEAARAAEAFAAQAAAAAQARAAIAAgADAAAAAwABAAAABAABAAMAAAAGAAcABgABAAAABAAHAAAAAQAIAAIAAAAKAAsACgABAAQACwANAAEAAAAOAA0AAQACAA4AAAAAAA8AEQACAA8ADwABAAMAEgACABEAEgATAAAAAQADABMAFAAAAAIAAQAVABYAFgAXAAEAAgABAAAAAgAAAAIAAQADABkABAACAAAAAQAHAAUABwABAAAABwAIAAEACQAHAAAAAAAJAAAACgAAAAQAAgALAAUACwADAAEAAAAPAA4AAQAOAAUADwABABIAAgAAAAIAEwACAAEABgADAAIAEwAAABMAFAACAAEAAgAAAAAAAgAEAAYAAwAEAAEACAACAAYACAAHAAAACQAAAAQAAgABAAoAAAAKAAAACwAOAAAABQAMAAMAAgAMAAEADwAQAAAAAgAQAAEAAAACABIAEgAUAAEAAAADAAIAAAAEAAIABAABAAUABQABAAYAAAAIAAcABwACAAEACAAAAAAAAwACAAoAAQAMAAoAAAAMAA0AAQANAAIAAAANAAAAAAASAA8AAwABAA8ADwAEAAIAEQASAAEAAAASAAAAEwACABUAAwABABMAAAAEAAYAAQACAAQAAAAAAAgACAABAAMABwACAAgAAgAHAAAAAQAIAAoACgAAAAIADAABAAsADQABAAwADQAOAAAAAgAOAAAAAQAPAAAAAwABABAAEgAAABIABAASAAEAEwAAAAIAFQABABQAAQAAAAMAAwAAAAcABAACAAEAAQAFAAcABQAAAAAABwAAAAkAAQAIAAIAAwAIAAAAAQAJAAUAAgAAAAsACwABAAAADAABAA4ADwAOAAEAAAASABAAAgABABAAAQARABIAAAASAAIAEgABAAAAFQATAAEAAAAEAAAABgAHAAUAAQAFAAcABQACAAQABwAAAAIACAAKAAEACgAAAAIAAQALAAAAAQAMAA0ADgABAA0AAAACAA8AAQAPAAAADQABABAAEQASAA0AEgABAA0AAQASAAAAAgABAAAAAQAEAAMAAAAFAAAAAAAHAAMAAQAIAAcAAgAHAAQACAAAAAoAAQAJAAAACgADAAEACwAAAA0ADAADAAAAAQACAA0ADwAOAAIAAgAQAA8AAgAAABEAEwARAAAAAQASAAIAAQAAABUAFAAVAAEAAQAAABUAFQABACkAAgAAAAAAAgAEAAUAAwAEAAAAAQAFAAIABwAAAAcABwABAAQAAAAAAAoAAwAKAAEACgAMAAIAAAANAAwADQABAAMAAAACAA0ADQAQAAEAAAAAAAQABgAEAAEAAwACAAQAAQAFAAYABQAAAAAABwADAAIABwAAAAoAAQAIAAIAAAAOAAsACwACAAEADQAOAAEAAAAAAA8ADwABAA4AAgAPAAAAAQAQAAQAAAATABAAEAADAAEAPAA7ABMAAQA8ABMAPAABAAAAAQACAAAAAwAFAAEABQAGAAAAAAAHAAIAAwAHAAEACAAAAAAACAACAAoAAQAEAAoACAAMAAAAAQADAAkADAANAAkADgABAA0ADwAAAA8AAgAPAAAAAQAQAAIAAAASAAAAEwAUAAEABAATAAIAFAAVAAEAAQAVAAAAAwACAAEAAQAAAAQAAQAGAAQAAAAHAAAACAACAAcAAQAIAAMAAAAKAAgACAADAAEADAAKAAEADAAAAAwAAgAAAA4AAgAOAAEAAAARAA4ADgADAAEAAAAAABMAAwACABMAEwABABIAAAAVABMAAQATAAIAAgAAAAAABAABAAMABQACAAQABgAIAAUAAAADAAYABgAJAAEAAAACAAoACQABAAoAAAAKAAAAAwALAAAAAQAMAAMAAgAMAA4ADgAQAAIAAAADABEAEQAQAAEAAAAAABIAFAACABIAAwASAAEAFAAVAAIAAgAAAAIAAwAWAAAAAAADAAUAAgABAAUAAAAFAAQABQABAAcAAAAKAAgACAACAAEACgABAAsACwABAAAACgAMAAEACgAAAAAAAQAPAAwAAwACAAwAAAAQAAIAEAABABEAAQATABEAAQAAAAAAAAAEAAIAAAAXAAUABQACAAEABAAFAAYABgAHAAQAAAAIAAkACQAAAAIACwABAAoACwAMAAEAAQAMAAAAEAABAA0AEAAOAAAAAgARAAEAAAAQABEAAQARAAAAAgABAAAAAgATAAAAAwAAAAMABAAAAAAABgAEAAIAAQADAAYABABCAAAAQwAFAAAABAAGAAIAAQAGABkABAAAAAQAVQAFAAMABQBVAAEAAAAHAAUABQACAAEABwABAAAAAgADAFoAAgAAAAIAAQADAFsAWwAEAFkAWQAEAFcABABYAFcAWAAGAEkABgBIAEkAMwBIAAUAHQAzAAUAWwBaAAEAAQBaAAAAAABcAF4AXAABAAIAAAACAGAAXwBgAAIAAAAAAAMAAgADAGIAYgB0AAIAAAACAAMAdQABAAMAAgABAAAAAgAAAAIAAwB3AHgAAQADAAAAAQAEAHkAAAADAAIAAwABAAAAewCPAAMAAwCPAAIAAAADAAAAkQCSAAQABAACAAMAAQAEAJIAAQAAAAMAkwCmAAIApgABAAIApgClAAEAIQAAACEAIQABAAAAAQA4ACIAAAACAAMAOQACADgAOAACAAAAAAACAAQABAADAAEAAwAAAAIAAAAEAAMAAwACAAEABAABAAAAPQAFAD8AAQAAAAYAQAAGAAEAAAAEAAAABAAFAAAABgAHAAIAAQAGAAMABwAAAAMAAQAEAAMAvQC+AAQABAABAL0ABAC+AAIAvgAGAAIAAAAGAAcAAQAHALsAuwAHAL8ABgABAAAABwBaAEYAWgAHAAEAAQACAAAAvgADAL0AAQADAL4AAgBcAFsAAQCZAAIAAgCZAFwArACZAAEAvgCsAAEAXACZAJgAwAAAAMMAwQAFAAAAAgDCAAEA2AACANYAxAACANgAEQAAAAEAnwCoANUA2QAFANoAzgDLAMkApwCmAKMAqgCsAK0AqwACAAAAAQAEABEAAAAEAK4ADAAkAMYAxQDIAMIAwQC/ALsAugC5ALIAsAC8AL0AAgAAAJ8ArgA="; it("can load Base64 encoded data as arraybuffer", function() { return loadWithXhr({ url: tile, responseType: "arraybuffer" }).then(function(result) { expect(result.byteLength).toEqual(3914); }); }); const image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAEISURBVEhLvVXBDYQwDOuojHKj8LhBbpTbpBCEkZsmIVTXq1RVQGrHiWlLmTTqPiZBlyLgy/KSZQ5JSHDQ/mCYCsC8106kDU0AdwRnvYZArWRcAl0dcYJq1hWCb3hBrumbDAVMwAC82WoRvgMnVMDBnB0nYZFTbE6BBvdUGqVqCbjBIk3PyFFR/NU7EKzru+qZsau3ryPwwCRLKYOzutZuCL6fUmWeJGzNzL/RxAMrUmASSCkkAayk2IxPlwhAAYGpsiHQjbLccfdOY5gKkCXAMi7SscAwbQpAnKyctWyUZ6z8ja3OGMepwD8asz+9FnSvbhU8uVOHFIwQsI3/p0CfhuqCSQuxLqsN6mu8SS+N42MAAAAASUVORK5CYII="; it("can load Base64 encoded data as blob", function() { return loadWithXhr({ url: image, responseType: "blob" }).then(function(result) { expect(result.type).toEqual("image/png"); const blobUrl = URL.createObjectURL(result); return import__324.Resource.fetchImage(blobUrl).then(function(image2) { expect(image2.width).toEqual(24); expect(image2.height).toEqual(24); }); }); }); xit("can support 2xx HTTP status (other than 200)", function() { return loadWithXhr({ method: "POST", url: "http://jsonplaceholder.typicode.com/posts", data: { title: "foo", body: "bar", userId: 1 } }).then(function(result) { expect(JSON.parse(result).id).toEqual(101); }); }); }); describe("URL loading using XHR", function() { describe("returns a promise that rejects when the request", function() { it("results in an HTTP status code greater than or equal to 300", function() { return loadWithXhr({ url: "http://example.invalid" }).then(function() { fail("expected promise to reject"); }).catch(function(err) { expect(err).toBeInstanceOf(import__324.RequestErrorEvent); }); }); it("loads an invalid JSON string response with a json responseType", function() { return loadWithXhr({ url: "Data/htmlString.txt", responseType: "json" }).then(function() { fail("expected promise to reject"); }).catch(function(err) { expect(err).toBeDefined(); expect(err).toBeInstanceOf(Error); }); }); }); describe("returns a promise that resolves when the request loads", function() { it("a non-null response with default responseType", function() { return loadWithXhr({ url: "Data/textString.txt" }).then(function(result) { expect(result).toBe("Hello, World!"); }); }); it("a non-null response with a browser-supported responseType", function() { return loadWithXhr({ url: "Data/textString.txt", responseType: "text" }).then(function(result) { expect(result).toBe("Hello, World!"); }); }); it("a valid JSON string response as JSON with a json responseType", function() { return loadWithXhr({ url: "Data/jsonString.txt", responseType: "json" }).then(function(result) { expect(result).toEqual( jasmine.objectContaining({ hello: "world" }) ); }); }); }); }); describe("URL loading using mocked XHR", function() { let fakeXHR; let requestConstructorSpy; beforeEach(function() { fakeXHR = jasmine.createSpyObj("XMLHttpRequest", [ "send", "open", "setRequestHeader", "abort", "getAllResponseHeaders" ]); fakeXHR.simulateError = function() { fakeXHR.response = ""; if (typeof fakeXHR.onerror === "function") { fakeXHR.onerror(); } }; fakeXHR.simulateHttpResponse = function(statusCode, response) { fakeXHR.status = statusCode; fakeXHR.response = response; if (typeof fakeXHR.onload === "function") { fakeXHR.onload(); } }; fakeXHR.simulateResponseXMLLoad = function(responseXML) { fakeXHR.status = 200; fakeXHR.responseXML = responseXML; if (typeof fakeXHR.onload === "function") { fakeXHR.onload(); } }; fakeXHR.simulateResponseTextLoad = function(responseText) { fakeXHR.simulateHttpResponse(200, responseText); }; requestConstructorSpy = spyOn(window, "XMLHttpRequest").and.returnValue( fakeXHR ); }); describe("returns a promise that rejects when the request", function() { it("errors", function() { const promise = loadWithXhr({ url: "http://example.invalid" }); let resolvedValue; let rejectedError; expect(promise).toBeDefined(); const handledPromise = promise.then(function(value) { resolvedValue = value; }).catch(function(error) { rejectedError = error; }); expect(resolvedValue).toBeUndefined(); expect(rejectedError).toBeUndefined(); fakeXHR.simulateError(); return handledPromise.finally(function() { expect(resolvedValue).toBeUndefined(); expect(rejectedError).toBeInstanceOf(import__324.RequestErrorEvent); }); }); it("results in an HTTP status code less than 200", function() { const promise = loadWithXhr({ url: "http://example.invalid" }); expect(promise).toBeDefined(); let resolvedValue; let rejectedError; const handledPromise = promise.then(function(value) { resolvedValue = value; }).catch(function(error) { rejectedError = error; }); expect(resolvedValue).toBeUndefined(); expect(rejectedError).toBeUndefined(); fakeXHR.simulateHttpResponse(199); return handledPromise.finally(function() { expect(resolvedValue).toBeUndefined(); expect(rejectedError).toBeInstanceOf(import__324.RequestErrorEvent); }); }); it("is an image with status code 204 with preferImageBitmap", function() { if (!supportsImageBitmapOptions) { return; } spyOn(import__324.Resource.prototype, "fetchBlob").and.callFake(function() { return Promise.resolve({}); }); const promise = import__324.Resource.fetchImage({ url: "./Data/Images/Green.png", preferImageBitmap: true, // We only load with xhr if the resource has headers headers: { "a-header": true } }); expect(promise).toBeDefined(); let resolved = false; let resolvedValue; let rejectedError; const handledPromise = promise.then(function(value) { resolved = true; resolvedValue = value; }).catch(function(error) { rejectedError = error; }); expect(resolvedValue).toBeUndefined(); expect(rejectedError).toBeUndefined(); fakeXHR.simulateHttpResponse(204); return handledPromise.finally(function() { expect(resolved).toBe(false); expect(resolvedValue).toBeUndefined(); expect(rejectedError).toBeDefined(); }); }); it("resolves undefined for status code 204", function() { const promise = loadWithXhr({ url: "http://example.invalid" }); expect(promise).toBeDefined(); let resolved = false; let resolvedValue; let rejectedError; const handledPromise = promise.then(function(value) { resolved = true; resolvedValue = value; }).catch(function(error) { rejectedError = error; }); expect(resolvedValue).toBeUndefined(); expect(rejectedError).toBeUndefined(); fakeXHR.simulateHttpResponse(204); return handledPromise.finally(function() { expect(resolved).toBe(true); expect(resolvedValue).toBeUndefined(); expect(rejectedError).toBeUndefined(); }); }); }); describe("returns a promise that resolves when the request loads", function() { it("a null response with a '' responseType and non-null responseXML with child nodes", function() { const promise = loadWithXhr({ url: "http://example.invalid", responseType: "" }); expect(promise).toBeDefined(); let resolvedValue; let rejectedError; const handledPromise = promise.then(function(value) { resolvedValue = value; }).catch(function(error) { rejectedError = error; }); expect(resolvedValue).toBeUndefined(); expect(rejectedError).toBeUndefined(); const responseXML = { hasChildNodes: jasmine.createSpy("hasChildNodes").and.returnValue(true) }; fakeXHR.simulateResponseXMLLoad(responseXML); return handledPromise.finally(function() { expect(resolvedValue).toEqual(responseXML); expect(rejectedError).toBeUndefined(); }); }); it("a null response with a document responseType and non-null responseXML with child nodes", function() { const promise = loadWithXhr({ url: "http://example.invalid", responseType: "document" }); expect(promise).toBeDefined(); let resolvedValue; let rejectedError; const handledPromise = promise.then(function(value) { resolvedValue = value; }).catch(function(error) { rejectedError = error; }); expect(resolvedValue).toBeUndefined(); expect(rejectedError).toBeUndefined(); const responseXML = { hasChildNodes: jasmine.createSpy("hasChildNodes").and.returnValue(true) }; fakeXHR.simulateResponseXMLLoad(responseXML); return handledPromise.finally(function() { expect(resolvedValue).toEqual(responseXML); expect(rejectedError).toBeUndefined(); }); }); it("a null response with a '' responseType and non-null responseText", function() { const promise = loadWithXhr({ url: "http://example.invalid", responseType: "" }); expect(promise).toBeDefined(); let resolvedValue; let rejectedError; const handledPromise = promise.then(function(value) { resolvedValue = value; }).catch(function(error) { rejectedError = error; }); expect(resolvedValue).toBeUndefined(); expect(rejectedError).toBeUndefined(); const responseText = "hello world"; fakeXHR.simulateResponseTextLoad(responseText); return handledPromise.finally(function() { expect(resolvedValue).toEqual(responseText); expect(rejectedError).toBeUndefined(); }); }); it("a null response with a text responseType and non-null responseText", function() { const promise = loadWithXhr({ url: "http://example.invalid", responseType: "text" }); expect(promise).toBeDefined(); let resolvedValue; let rejectedError; const handledPromise = promise.then(function(value) { resolvedValue = value; }).catch(function(error) { rejectedError = error; }); expect(resolvedValue).toBeUndefined(); expect(rejectedError).toBeUndefined(); const responseText = "hello world"; fakeXHR.simulateResponseTextLoad(responseText); return handledPromise.finally(function() { expect(resolvedValue).toEqual(responseText); expect(rejectedError).toBeUndefined(); }); }); }); describe("retries when Resource has the callback set", function() { it("rejects after too many retries", function() { const cb = jasmine.createSpy("retry").and.returnValue(true); const resource = new import__324.Resource({ url: "http://example.invalid", retryCallback: cb, retryAttempts: 1 }); const promise = loadWithXhr(resource); expect(promise).toBeDefined(); fakeXHR.simulateError(); pollToPromise_default(function() { return requestConstructorSpy.calls.count() > 1; }).then(function() { fakeXHR.simulateError(); }); return promise.then(function() { fail(); }).catch(function(error) { expect(error).toBeInstanceOf(import__324.RequestErrorEvent); expect(cb.calls.count()).toEqual(1); const receivedResource = cb.calls.argsFor(0)[0]; expect(receivedResource.url).toEqual(resource.url); expect(receivedResource._retryCount).toEqual(1); expect(cb.calls.argsFor(0)[1] instanceof import__324.RequestErrorEvent).toBe( true ); }); }); it("rejects after callback returns false", function() { const cb = jasmine.createSpy("retry").and.returnValue(false); const resource = new import__324.Resource({ url: "http://example.invalid", retryCallback: cb, retryAttempts: 2 }); const promise = loadWithXhr(resource); expect(promise).toBeDefined(); fakeXHR.simulateError(); return promise.then(function() { fail(); }).catch(function(error) { expect(error).toBeInstanceOf(import__324.RequestErrorEvent); expect(cb.calls.count()).toEqual(1); const receivedResource = cb.calls.argsFor(0)[0]; expect(receivedResource.url).toEqual(resource.url); expect(receivedResource._retryCount).toEqual(1); expect(cb.calls.argsFor(0)[1] instanceof import__324.RequestErrorEvent).toBe( true ); }); }); it("resolves after retry", function() { const cb = jasmine.createSpy("retry").and.returnValue(true); const resource = new import__324.Resource({ url: "http://example.invalid", retryCallback: cb, retryAttempts: 1 }); const promise = loadWithXhr(resource); expect(promise).toBeDefined(); fakeXHR.simulateError(); pollToPromise_default(function() { return requestConstructorSpy.calls.count() > 1; }).then(function() { fakeXHR.simulateHttpResponse(200, "OK"); }); return promise.then(function(value) { expect(value).toBeDefined(); expect(cb.calls.count()).toEqual(1); const receivedResource = cb.calls.argsFor(0)[0]; expect(receivedResource.url).toEqual(resource.url); expect(receivedResource._retryCount).toEqual(1); expect(cb.calls.argsFor(0)[1] instanceof import__324.RequestErrorEvent).toBe( true ); }); }); }); }); }); describe("fetchJsonp", function() { it("returns a promise that resolves when the request loads", function() { const testUrl = "http://example.invalid/testuri"; spyOn(import__324.Resource._Implementations, "loadAndExecuteScript").and.callFake( function(url, name, deferred) { expect(url).toContain(testUrl); expect(name).toContain("loadJsonp"); expect(deferred).toBeDefined(); deferred.resolve(); } ); return import__324.Resource.fetchJsonp(testUrl); }); it("returns a promise that rejects when the request errors", function() { const testUrl = "http://example.invalid/testuri"; return import__324.Resource.fetchJsonp(testUrl).catch(function(error) { expect(error).toBeDefined(); }); }); it("Uses callback name specified in options", function() { const testUrl = "test"; const options = { callbackParameterName: "testCallback" }; spyOn(import__324.Resource._Implementations, "loadAndExecuteScript").and.callFake( function(url, functionName, deferred) { expect(url).toContain("callback=loadJsonp"); deferred.resolve(); } ); return import__324.Resource.fetchJsonp(testUrl, options); }); describe("retries when Resource has the callback set", function() { it("rejects after too many retries", function() { const cb = jasmine.createSpy("retry").and.returnValue(true); let lastDeferred; spyOn(import__324.Resource._Implementations, "loadAndExecuteScript").and.callFake( function(url, functionName, deferred) { lastDeferred = deferred; } ); const resource = new import__324.Resource({ url: "http://example.invalid", retryCallback: cb, retryAttempts: 1 }); const promise = resource.fetchJsonp(); expect(promise).toBeDefined(); lastDeferred.reject("some error"); lastDeferred = void 0; pollToPromise_default(function() { return (0, import__324.defined)(lastDeferred); }).then(function() { lastDeferred.reject("another error"); }); return promise.then(function() { fail(); }).catch(function(error) { expect(cb.calls.count()).toEqual(1); const receivedResource = cb.calls.argsFor(0)[0]; expect(receivedResource.url).toEqual(resource.url); expect(receivedResource._retryCount).toEqual(1); expect(cb.calls.argsFor(0)[1]).toEqual("some error"); expect(error).toEqual("another error"); }); }); it("rejects after callback returns false", function() { const cb = jasmine.createSpy("retry").and.returnValue(false); let lastDeferred; spyOn(import__324.Resource._Implementations, "loadAndExecuteScript").and.callFake( function(url, functionName, deferred) { lastDeferred = deferred; } ); const resource = new import__324.Resource({ url: "http://example.invalid", retryCallback: cb, retryAttempts: 2 }); const promise = resource.fetchJsonp(); expect(promise).toBeDefined(); lastDeferred.reject("some error"); return promise.then(function() { fail(); }).catch(function(error) { expect(cb.calls.count()).toEqual(1); const receivedResource = cb.calls.argsFor(0)[0]; expect(receivedResource.url).toEqual(resource.url); expect(receivedResource._retryCount).toEqual(1); expect(cb.calls.argsFor(0)[1]).toEqual("some error"); expect(error).toEqual("some error"); }); }); it("resolves after retry", function() { const cb = jasmine.createSpy("retry").and.returnValue(true); let lastDeferred; let lastUrl; spyOn(import__324.Resource._Implementations, "loadAndExecuteScript").and.callFake( function(url, functionName, deferred) { lastUrl = url; lastDeferred = deferred; } ); const resource = new import__324.Resource({ url: "http://example.invalid", retryCallback: cb, retryAttempts: 1 }); const promise = resource.fetchJsonp(); expect(promise).toBeDefined(); lastDeferred.reject("some error"); lastDeferred = void 0; pollToPromise_default(function() { return (0, import__324.defined)(lastDeferred); }).then(function() { const uri = new import_urijs.default(lastUrl); const query = (0, import__324.queryToObject)(uri.query()); window[query.callback]("something good"); lastDeferred.resolve(); }); return promise.then(function(result) { expect(result).toEqual("something good"); expect(cb.calls.count()).toEqual(1); const receivedResource = cb.calls.argsFor(0)[0]; expect(receivedResource.url).toEqual(resource.url); expect(receivedResource._retryCount).toEqual(1); expect(cb.calls.argsFor(0)[1]).toEqual("some error"); }); }); }); }); }); // packages/engine/Specs/Core/RuntimeErrorSpec.js var import__325 = __toESM(require_Cesium(), 1); describe("Core/RuntimeError", function() { const name = "RuntimeError"; const testMessage = "Testing"; let e; beforeEach(function() { e = new import__325.RuntimeError(testMessage); }); it("has a name property", function() { expect(e.name).toEqual(name); }); it("has a message property", function() { expect(e.message).toEqual(testMessage); }); it("has a stack property", function() { if (!window.specsUsingRelease) { expect(e.stack).toContain(name); } }); it("has a working toString", function() { const str = new import__325.RuntimeError(testMessage).toString(); if (!window.specsUsingRelease) { expect(e.stack).toContain(name); } expect(str).toContain(testMessage); }); }); // packages/engine/Specs/Core/S2CellSpec.js var import__326 = __toESM(require_Cesium(), 1); var import__327 = __toESM(require_Cesium(), 1); describe("Core/S2Cell", function() { if (!import__326.FeatureDetection.supportsBigInt()) { return; } it("constructor", function() { const cell = new import__326.S2Cell(BigInt("3458764513820540928")); expect(cell._cellId).toEqual(BigInt("3458764513820540928")); }); it("throws for invalid cell ID in constructor", function() { expect(function() { (0, import__326.S2Cell)(BigInt(-1)); }).toThrowDeveloperError(); }); it("throws for missing cell ID in constructor", function() { expect(function() { (0, import__326.S2Cell)(); }).toThrowDeveloperError(); }); it("creates cell from valid token", function() { const cell = import__326.S2Cell.fromToken("3"); expect(cell._cellId).toEqual(BigInt("3458764513820540928")); }); it("throws for creating cell from invalid token", function() { expect(function() { import__326.S2Cell.fromToken("XX"); }).toThrowDeveloperError(); }); it("creates cell from valid face, position, level", function() { let cell = import__326.S2Cell.fromFacePositionLevel(0, BigInt(0), 1); expect(import__326.S2Cell.getTokenFromId(cell._cellId)).toEqual("04"); cell = import__326.S2Cell.fromFacePositionLevel(BigInt(0), BigInt(1), 1); expect(import__326.S2Cell.getTokenFromId(cell._cellId)).toEqual("0c"); cell = import__326.S2Cell.fromFacePositionLevel(BigInt(0), BigInt(2), 1); expect(import__326.S2Cell.getTokenFromId(cell._cellId)).toEqual("14"); cell = import__326.S2Cell.fromFacePositionLevel(BigInt(0), BigInt(3), 1); expect(import__326.S2Cell.getTokenFromId(cell._cellId)).toEqual("1c"); cell = import__326.S2Cell.fromFacePositionLevel(2, BigInt("0"), 1); expect(import__326.S2Cell.getTokenFromId(cell._cellId)).toEqual("44"); cell = import__326.S2Cell.fromFacePositionLevel(4, BigInt("0"), 1); expect(import__326.S2Cell.getTokenFromId(cell._cellId)).toEqual("84"); cell = import__326.S2Cell.fromFacePositionLevel(1, BigInt("538969508876688737"), 30); expect(import__326.S2Cell.getTokenFromId(cell._cellId)).toEqual("2ef59bd352b93ac3"); }); it("throws for creating cell from invalid face, position, level", function() { expect(function() { import__326.S2Cell.fromFacePositionLevel(-1, BigInt(0), 1); }).toThrowDeveloperError(); expect(function() { import__326.S2Cell.fromFacePositionLevel(6, BigInt(0), 1); }).toThrowDeveloperError(); expect(function() { import__326.S2Cell.fromFacePositionLevel(0, BigInt(-1), 1); }).toThrowDeveloperError(); expect(function() { import__326.S2Cell.fromFacePositionLevel(0, BigInt(4), 1); }).toThrowDeveloperError(); expect(function() { import__326.S2Cell.fromFacePositionLevel(0, BigInt(0), -1); }).toThrowDeveloperError(); expect(function() { import__326.S2Cell.fromFacePositionLevel(0, BigInt(0), 31); }).toThrowDeveloperError(); }); it("accepts valid token", function() { let tokenValidity = import__326.S2Cell.isValidToken("1"); expect(tokenValidity).toBe(true); tokenValidity = import__326.S2Cell.isValidToken("2ef59bd34"); expect(tokenValidity).toBe(true); tokenValidity = import__326.S2Cell.isValidToken("2ef59bd352b93ac3"); expect(tokenValidity).toBe(true); }); it("rejects token of invalid value", function() { let tokenValidity = import__326.S2Cell.isValidToken("LOL"); expect(tokenValidity).toBe(false); tokenValidity = import__326.S2Cell.isValidToken("----"); expect(tokenValidity).toBe(false); tokenValidity = import__326.S2Cell.isValidToken("9".repeat(17)); expect(tokenValidity).toBe(false); tokenValidity = import__326.S2Cell.isValidToken("0"); expect(tokenValidity).toBe(false); tokenValidity = import__326.S2Cell.isValidToken("\u{1F921}"); expect(tokenValidity).toBe(false); }); it("throws for token of invalid type", function() { expect(function() { import__326.S2Cell.isValidToken(420); }).toThrowDeveloperError(); expect(function() { import__326.S2Cell.isValidToken({}); }).toThrowDeveloperError(); }); it("accepts valid cell ID", function() { let cellIdValidity = import__326.S2Cell.isValidId(BigInt("3383782026967071428")); expect(cellIdValidity).toBe(true); cellIdValidity = import__326.S2Cell.isValidId(BigInt("3458764513820540928")); expect(cellIdValidity).toBe(true); }); it("rejects cell ID of invalid value", function() { let cellIdValidity = import__326.S2Cell.isValidId(BigInt("0")); expect(cellIdValidity).toBe(false); cellIdValidity = import__326.S2Cell.isValidId(BigInt("-1")); expect(cellIdValidity).toBe(false); cellIdValidity = import__326.S2Cell.isValidId(BigInt("18446744073709551619995")); expect(cellIdValidity).toBe(false); cellIdValidity = import__326.S2Cell.isValidId(BigInt("222446744073709551619995")); expect(cellIdValidity).toBe(false); cellIdValidity = import__326.S2Cell.isValidId( BigInt( "0b0010101000000000000000000000000000000000000000000000000000000000" ) ); expect(cellIdValidity).toBe(false); }); it("throws for cell ID of invalid type", function() { expect(function() { import__326.S2Cell.isValidId(420); }).toThrowDeveloperError(); expect(function() { import__326.S2Cell.isValidId("2ef"); }).toThrowDeveloperError(); }); it("correctly converts cell ID to token", function() { expect(import__326.S2Cell.getIdFromToken("04")).toEqual(BigInt("288230376151711744")); expect(import__326.S2Cell.getIdFromToken("3")).toEqual(BigInt("3458764513820540928")); expect(import__326.S2Cell.getIdFromToken("2ef59bd352b93ac3")).toEqual( BigInt("3383782026967071427") ); }); it("correctly converts token to cell ID", function() { expect(import__326.S2Cell.getTokenFromId(BigInt("288230376151711744"))).toEqual("04"); expect(import__326.S2Cell.getTokenFromId(BigInt("3458764513820540928"))).toEqual("3"); expect(import__326.S2Cell.getTokenFromId(BigInt("3383782026967071427"))).toEqual( "2ef59bd352b93ac3" ); }); it("gets correct level of cell", function() { expect(import__326.S2Cell.getLevel(BigInt("3170534137668829184"))).toEqual(1); expect(import__326.S2Cell.getLevel(BigInt("3383782026921377792"))).toEqual(16); expect(import__326.S2Cell.getLevel(BigInt("3383782026967071427"))).toEqual(30); }); it("throws on missing/invalid cell ID in getting level of cell", function() { expect(function() { import__326.S2Cell.getLevel(BigInt("-1")); }).toThrowDeveloperError(); expect(function() { import__326.S2Cell.getLevel(); }).toThrowDeveloperError(); expect(function() { import__326.S2Cell.getLevel(BigInt("3170534137668829184444")); }).toThrowDeveloperError(); expect(function() { import__326.S2Cell.getLevel(BigInt(0)); }).toThrowDeveloperError(); }); it("gets correct parent of cell", function() { const cell = new import__326.S2Cell(BigInt("3383782026967515136")); const parent = cell.getParent(); expect(parent._cellId).toEqual(BigInt("3383782026971709440")); }); it("gets correct parent of cell at given level", function() { const cell = new import__326.S2Cell(BigInt("3383782026967056384")); let parent = cell.getParentAtLevel(21); expect(parent._cellId).toEqual(BigInt("3383782026967252992")); parent = cell.getParentAtLevel(7); expect(parent._cellId).toEqual(BigInt("3383821801271328768")); parent = cell.getParentAtLevel(0); expect(parent._cellId).toEqual(BigInt("3458764513820540928")); }); it("throws on getting parent of cell at invalid level", function() { let cell = new import__326.S2Cell(BigInt("3458764513820540928")); expect(function() { cell.getParentAtLevel(0); }).toThrowDeveloperError(); cell = new import__326.S2Cell(BigInt("3383782026967072768")); expect(function() { cell.getParentAtLevel(-1); }).toThrowDeveloperError(); expect(function() { cell.getParentAtLevel(30); }).toThrowDeveloperError(); }); it("throws on getting parent of level 0 cells", function() { const cell = import__326.S2Cell.fromToken("3"); expect(function() { cell.getParent(); }).toThrowDeveloperError(); }); it("gets correct children of cell", function() { const cell = new import__326.S2Cell(BigInt("3383782026971709440")); const expectedChildCellIds = [ BigInt(3383782026959126500), BigInt(3383782026967515e3), BigInt(3383782026975904e3), BigInt(3383782026984292400) ]; let i; for (i = 0; i < 4; i++) { expect(cell.getChild(i)._cellId).toEqual(expectedChildCellIds[i]); } }); it("throws on invalid child index in getting children of cell", function() { const cell = new import__326.S2Cell(BigInt("3383782026971709440")); expect(function() { cell.getChild(4); }).toThrowDeveloperError(); expect(function() { cell.getChild(-1); }).toThrowDeveloperError(); }); it("throws on getting children of level 30 cell", function() { const cell = new import__326.S2Cell(BigInt("3383782026967071427")); expect(cell._level).toEqual(30); expect(function() { cell.getChild(0); }).toThrowDeveloperError(); }); it("gets correct center of cell", function() { expect(import__326.S2Cell.fromToken("1").getCenter()).toEqualEpsilon( import__326.Cartesian3.fromDegrees(0, 0), import__327.Math.EPSILON15 ); expect(import__326.S2Cell.fromToken("3").getCenter()).toEqualEpsilon( import__326.Cartesian3.fromDegrees(90, 0), import__327.Math.EPSILON15 ); expect(import__326.S2Cell.fromToken("5").getCenter()).toEqualEpsilon( import__326.Cartesian3.fromDegrees(-180, 90), import__327.Math.EPSILON15 ); expect(import__326.S2Cell.fromToken("7").getCenter()).toEqualEpsilon( import__326.Cartesian3.fromDegrees(-180, 0), import__327.Math.EPSILON15 ); expect(import__326.S2Cell.fromToken("9").getCenter()).toEqualEpsilon( import__326.Cartesian3.fromDegrees(-90, 0), import__327.Math.EPSILON15 ); expect(import__326.S2Cell.fromToken("b").getCenter()).toEqualEpsilon( import__326.Cartesian3.fromDegrees(0, -90), import__327.Math.EPSILON15 ); expect(import__326.S2Cell.fromToken("2ef59bd352b93ac3").getCenter()).toEqualEpsilon( import__326.Cartesian3.fromDegrees(105.64131803774308, -10.490091033598308), import__327.Math.EPSILON15 ); expect(import__326.S2Cell.fromToken("1234567").getCenter()).toEqualEpsilon( import__326.Cartesian3.fromDegrees(9.868307318504081, 27.468392925827605), import__327.Math.EPSILON15 ); }); it("throws on invalid vertex index", function() { const cell = new import__326.S2Cell(BigInt("3383782026971709440")); expect(function() { cell.getVertex(-1); }).toThrowDeveloperError(); expect(function() { cell.getVertex(4); }).toThrowDeveloperError(); }); it("gets correct vertices of cell", function() { const cell = import__326.S2Cell.fromToken("2ef59bd352b93ac3"); expect(cell.getVertex(0)).toEqualEpsilon( import__326.Cartesian3.fromDegrees(105.64131799299665, -10.490091077431977), import__327.Math.EPSILON15 ); expect(cell.getVertex(1)).toEqualEpsilon( import__326.Cartesian3.fromDegrees(105.64131808248949, -10.490091072946313), import__327.Math.EPSILON15 ); expect(cell.getVertex(2)).toEqualEpsilon( import__326.Cartesian3.fromDegrees(105.64131808248948, -10.490090989764633), import__327.Math.EPSILON15 ); expect(cell.getVertex(3)).toEqualEpsilon( import__326.Cartesian3.fromDegrees(105.64131799299665, -10.4900909942503), import__327.Math.EPSILON15 ); }); }); // packages/engine/Specs/Core/ScreenSpaceEventHandlerSpec.js var import__328 = __toESM(require_Cesium(), 1); // Specs/DomEventSimulator.js var import_engine18 = __toESM(require_Cesium(), 1); function createMouseEvent(type, options) { options = (0, import_engine18.defaultValue)(options, import_engine18.defaultValue.EMPTY_OBJECT); const canBubble = (0, import_engine18.defaultValue)(options.canBubble, true); const cancelable = (0, import_engine18.defaultValue)(options.cancelable, true); const view = (0, import_engine18.defaultValue)(options.view, window); const detail = (0, import_engine18.defaultValue)(options.detail, 0); const screenX = (0, import_engine18.defaultValue)(options.screenX, 0); const screenY = (0, import_engine18.defaultValue)(options.screenY, 0); const clientX = (0, import_engine18.defaultValue)(options.clientX, 0); const clientY = (0, import_engine18.defaultValue)(options.clientY, 0); const ctrlKey = (0, import_engine18.defaultValue)(options.ctrlKey, false); const altKey = (0, import_engine18.defaultValue)(options.altKey, false); const shiftKey = (0, import_engine18.defaultValue)(options.shiftKey, false); const metaKey = (0, import_engine18.defaultValue)(options.metaKey, false); const button = (0, import_engine18.defaultValue)(options.button, 0); const relatedTarget = (0, import_engine18.defaultValue)(options.relatedTarget, null); const event = document.createEvent("MouseEvent"); event.initMouseEvent( type, canBubble, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget ); return event; } function createModifiersList(ctrlKey, altKey, shiftKey, metaKey) { const modifiers = []; if (ctrlKey) { modifiers.push("Control"); } if (altKey) { modifiers.push("Alt"); } if (shiftKey) { modifiers.push("Shift"); } if (metaKey) { modifiers.push("Meta"); } return modifiers.join(" "); } function createMouseWheelEvent(type, options) { options = (0, import_engine18.defaultValue)(options, import_engine18.defaultValue.EMPTY_OBJECT); const canBubble = (0, import_engine18.defaultValue)(options.canBubble, true); const cancelable = (0, import_engine18.defaultValue)(options.cancelable, true); const view = (0, import_engine18.defaultValue)(options.view, window); const detail = (0, import_engine18.defaultValue)(options.detail, 0); const screenX = (0, import_engine18.defaultValue)(options.screenX, 0); const screenY = (0, import_engine18.defaultValue)(options.screenY, 0); const clientX = (0, import_engine18.defaultValue)(options.clientX, 0); const clientY = (0, import_engine18.defaultValue)(options.clientY, 0); const button = (0, import_engine18.defaultValue)(options.button, 0); const relatedTarget = (0, import_engine18.defaultValue)(options.relatedTarget, null); const ctrlKey = (0, import_engine18.defaultValue)(options.ctrlKey, false); const altKey = (0, import_engine18.defaultValue)(options.altKey, false); const shiftKey = (0, import_engine18.defaultValue)(options.shiftKey, false); const metaKey = (0, import_engine18.defaultValue)(options.metaKey, false); const wheelDelta = (0, import_engine18.defaultValue)(options.wheelDelta, 0); const event = document.createEvent("MouseWheelEvent"); const modifiersList = createModifiersList(ctrlKey, altKey, shiftKey, metaKey); event.initMouseWheelEvent( type, canBubble, cancelable, view, detail, screenX, screenY, clientX, clientY, button, relatedTarget, modifiersList, wheelDelta ); return event; } function createWheelEvent(type, options) { options = (0, import_engine18.defaultValue)(options, import_engine18.defaultValue.EMPTY_OBJECT); const canBubble = (0, import_engine18.defaultValue)(options.canBubble, true); const cancelable = (0, import_engine18.defaultValue)(options.cancelable, true); const view = (0, import_engine18.defaultValue)(options.view, window); const detail = (0, import_engine18.defaultValue)(options.detail, 0); const screenX = (0, import_engine18.defaultValue)(options.screenX, 0); const screenY = (0, import_engine18.defaultValue)(options.screenY, 0); const clientX = (0, import_engine18.defaultValue)(options.clientX, 0); const clientY = (0, import_engine18.defaultValue)(options.clientY, 0); const button = (0, import_engine18.defaultValue)(options.button, 0); const relatedTarget = (0, import_engine18.defaultValue)(options.relatedTarget, null); const ctrlKey = (0, import_engine18.defaultValue)(options.ctrlKey, false); const altKey = (0, import_engine18.defaultValue)(options.altKey, false); const shiftKey = (0, import_engine18.defaultValue)(options.shiftKey, false); const metaKey = (0, import_engine18.defaultValue)(options.metaKey, false); const deltaX = (0, import_engine18.defaultValue)(options.deltaX, 0); const deltaY = (0, import_engine18.defaultValue)(options.deltaY, 0); const deltaZ = (0, import_engine18.defaultValue)(options.deltaZ, 0); const deltaMode = (0, import_engine18.defaultValue)(options.deltaMode, 0); try { return new WheelEvent(type, { view, detail, screenX, screenY, clientX, clientY, button, relatedTarget, ctrlKey, altKey, shiftKey, metaKey, deltaX, deltaY, deltaZ, deltaMode }); } catch (e) { const event = document.createEvent("WheelEvent"); const modifiersList = createModifiersList( ctrlKey, altKey, shiftKey, metaKey ); event.initWheelEvent( type, canBubble, cancelable, view, detail, screenX, screenY, clientX, clientY, button, relatedTarget, modifiersList, deltaX, deltaY, deltaZ, deltaMode ); return event; } } function createTouchEvent(type, options) { options = (0, import_engine18.defaultValue)(options, import_engine18.defaultValue.EMPTY_OBJECT); const canBubble = (0, import_engine18.defaultValue)(options.canBubble, true); const cancelable = (0, import_engine18.defaultValue)(options.cancelable, true); const view = (0, import_engine18.defaultValue)(options.view, window); const detail = (0, import_engine18.defaultValue)(options.detail, 0); const event = document.createEvent("UIEvent"); event.initUIEvent(type, canBubble, cancelable, view, detail); event.touches = (0, import_engine18.defaultValue)(options.touches, []); event.targetTouches = (0, import_engine18.defaultValue)(options.targetTouches, []); event.changedTouches = (0, import_engine18.defaultValue)(options.changedTouches, []); return event; } function createPointerEvent(type, options) { options = (0, import_engine18.defaultValue)(options, import_engine18.defaultValue.EMPTY_OBJECT); let event; if (import_engine18.FeatureDetection.isInternetExplorer()) { const canBubble = (0, import_engine18.defaultValue)(options.canBubble, true); const cancelable = (0, import_engine18.defaultValue)(options.cancelable, true); const view = (0, import_engine18.defaultValue)(options.view, window); const detail = (0, import_engine18.defaultValue)(options.detail, 0); const screenX = (0, import_engine18.defaultValue)(options.screenX, 0); const screenY = (0, import_engine18.defaultValue)(options.screenY, 0); const clientX = (0, import_engine18.defaultValue)(options.clientX, 0); const clientY = (0, import_engine18.defaultValue)(options.clientY, 0); const ctrlKey = (0, import_engine18.defaultValue)(options.ctrlKey, false); const altKey = (0, import_engine18.defaultValue)(options.altKey, false); const shiftKey = (0, import_engine18.defaultValue)(options.shiftKey, false); const metaKey = (0, import_engine18.defaultValue)(options.metaKey, false); const button = (0, import_engine18.defaultValue)(options.button, 0); const relatedTarget = (0, import_engine18.defaultValue)(options.relatedTarget, null); const offsetX = (0, import_engine18.defaultValue)(options.offsetX, 0); const offsetY = (0, import_engine18.defaultValue)(options.offsetY, 0); const width = (0, import_engine18.defaultValue)(options.width, 0); const height = (0, import_engine18.defaultValue)(options.height, 0); const pressure = (0, import_engine18.defaultValue)(options.pressure, 0); const rotation = (0, import_engine18.defaultValue)(options.rotation, 0); const tiltX = (0, import_engine18.defaultValue)(options.tiltX, 0); const tiltY = (0, import_engine18.defaultValue)(options.tiltY, 0); const pointerId = (0, import_engine18.defaultValue)(options.pointerId, 1); const pointerType = (0, import_engine18.defaultValue)(options.pointerType, 0); const hwTimestamp = (0, import_engine18.defaultValue)(options.hwTimestamp, 0); const isPrimary = (0, import_engine18.defaultValue)(options.isPrimary, 0); event = document.createEvent("PointerEvent"); event.initPointerEvent( type, canBubble, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget, offsetX, offsetY, width, height, pressure, rotation, tiltX, tiltY, pointerId, pointerType, hwTimestamp, isPrimary ); } else { event = new window.PointerEvent(type, { canBubble: (0, import_engine18.defaultValue)(options.canBubble, true), cancelable: (0, import_engine18.defaultValue)(options.cancelable, true), view: (0, import_engine18.defaultValue)(options.view, window), detail: (0, import_engine18.defaultValue)(options.detail, 0), screenX: (0, import_engine18.defaultValue)(options.screenX, 0), screenY: (0, import_engine18.defaultValue)(options.screenY, 0), clientX: (0, import_engine18.defaultValue)(options.clientX, 0), clientY: (0, import_engine18.defaultValue)(options.clientY, 0), ctrlKey: (0, import_engine18.defaultValue)(options.ctrlKey, false), altKey: (0, import_engine18.defaultValue)(options.altKey, false), shiftKey: (0, import_engine18.defaultValue)(options.shiftKey, false), metaKey: (0, import_engine18.defaultValue)(options.metaKey, false), button: (0, import_engine18.defaultValue)(options.button, 0), relatedTarget: (0, import_engine18.defaultValue)(options.relatedTarget, null), offsetX: (0, import_engine18.defaultValue)(options.offsetX, 0), offsetY: (0, import_engine18.defaultValue)(options.offsetY, 0), width: (0, import_engine18.defaultValue)(options.width, 0), height: (0, import_engine18.defaultValue)(options.height, 0), pressure: (0, import_engine18.defaultValue)(options.pressure, 0), rotation: (0, import_engine18.defaultValue)(options.rotation, 0), tiltX: (0, import_engine18.defaultValue)(options.tiltX, 0), tiltY: (0, import_engine18.defaultValue)(options.tiltY, 0), pointerId: (0, import_engine18.defaultValue)(options.pointerId, 1), pointerType: (0, import_engine18.defaultValue)(options.pointerType, 0), hwTimestamp: (0, import_engine18.defaultValue)(options.hwTimestamp, 0), isPrimary: (0, import_engine18.defaultValue)(options.isPrimary, 0) }); } return event; } function createDeviceOrientationEvent(type, options) { options = (0, import_engine18.defaultValue)(options, import_engine18.defaultValue.EMPTY_OBJECT); const canBubble = (0, import_engine18.defaultValue)(options.canBubble, true); const cancelable = (0, import_engine18.defaultValue)(options.cancelable, true); const alpha = (0, import_engine18.defaultValue)(options.alpha, 0); const beta = (0, import_engine18.defaultValue)(options.beta, 0); const gamma = (0, import_engine18.defaultValue)(options.gamma, 0); const absolute = (0, import_engine18.defaultValue)(options.absolute, false); let event; event = document.createEvent("DeviceOrientationEvent"); if (typeof event.initDeviceOrientationEvent === "function") { event.initDeviceOrientationEvent( type, canBubble, cancelable, alpha, beta, gamma, absolute ); } else { event = new DeviceOrientationEvent("deviceorientation", { alpha, beta, gamma, absolute }); } return event; } var DomEventSimulator = { fireMouseDown: function(element, options) { element.dispatchEvent(createMouseEvent("mousedown", options)); }, fireMouseUp: function(element, options) { element.dispatchEvent(createMouseEvent("mouseup", options)); }, fireMouseMove: function(element, options) { element.dispatchEvent(createMouseEvent("mousemove", options)); }, fireClick: function(element, options) { element.dispatchEvent(createMouseEvent("click", options)); }, fireDoubleClick: function(element, options) { element.dispatchEvent(createMouseEvent("dblclick", options)); }, fireMouseWheel: function(element, options) { element.dispatchEvent(createMouseWheelEvent("mousewheel", options)); }, fireWheel: function(element, options) { element.dispatchEvent(createWheelEvent("wheel", options)); }, fireTouchStart: function(element, options) { element.dispatchEvent(createTouchEvent("touchstart", options)); }, fireTouchMove: function(element, options) { element.dispatchEvent(createTouchEvent("touchmove", options)); }, fireTouchEnd: function(element, options) { element.dispatchEvent(createTouchEvent("touchend", options)); }, fireTouchCancel: function(element, options) { element.dispatchEvent(createTouchEvent("touchcancel", options)); }, firePointerDown: function(element, options) { element.dispatchEvent(createPointerEvent("pointerdown", options)); }, firePointerUp: function(element, options) { element.dispatchEvent(createPointerEvent("pointerup", options)); }, firePointerMove: function(element, options) { element.dispatchEvent(createPointerEvent("pointermove", options)); }, firePointerCancel: function(element, options) { element.dispatchEvent(createPointerEvent("pointercancel", options)); }, fireDeviceOrientation: function(element, options) { element.dispatchEvent( createDeviceOrientationEvent("deviceorientation", options) ); }, fireMockEvent: function(eventHandler, event) { eventHandler.call(window, event); } }; var DomEventSimulator_default = DomEventSimulator; // packages/engine/Specs/Core/ScreenSpaceEventHandlerSpec.js describe("Core/ScreenSpaceEventHandler", function() { let usePointerEvents; let element; let handler; function createCloningSpy(name) { const spy = jasmine.createSpy(name); const cloningSpy = function() { const args = [].slice.apply(arguments).map(function(arg) { return (0, import__328.clone)(arg, true); }); spy.apply(this, args); }; function createPropertyDescriptor(prop) { return { get: function() { return spy[prop]; }, set: function(value) { spy[prop] = value; } }; } for (const prop in spy) { if (spy.hasOwnProperty(prop)) { Object.defineProperty(cloningSpy, prop, createPropertyDescriptor(prop)); } } return cloningSpy; } const eventsToStop = "pointerdown pointerup pointermove pointercancel mousedown mouseup mousemove touchstart touchend touchmove touchcancel dblclick wheel mousewheel DOMMouseScroll".split( " " ); function stop(event) { event.stopPropagation(); event.preventDefault(); } beforeAll(function() { usePointerEvents = import__328.FeatureDetection.supportsPointerEvents(); }); beforeEach(function() { eventsToStop.forEach(function(e) { document.addEventListener(e, stop, false); }); element = document.createElement("div"); element.style.position = "absolute"; element.style.top = "0"; element.style.left = "0"; document.body.appendChild(element); element.disableRootEvents = true; if (usePointerEvents) { spyOn(element, "setPointerCapture"); } handler = new import__328.ScreenSpaceEventHandler(element); }); afterEach(function() { document.body.removeChild(element); handler = !handler.isDestroyed() && handler.destroy(); eventsToStop.forEach(function(e) { document.removeEventListener(e, stop, false); }); }); describe("setInputAction", function() { it("throws if action is undefined", function() { expect(function() { handler.setInputAction(); }).toThrowDeveloperError(); }); it("throws if type is undefined", function() { expect(function() { handler.setInputAction(function() { }); }).toThrowDeveloperError(); }); }); describe("getInputAction", function() { it("throws if type is undefined", function() { expect(function() { handler.getInputAction(); }).toThrowDeveloperError(); }); }); describe("removeInputAction", function() { it("throws if type is undefined", function() { expect(function() { handler.removeInputAction(); }).toThrowDeveloperError(); }); }); const MouseButton = { LEFT: 0, MIDDLE: 1, RIGHT: 2 }; function keyForValue(obj, val) { for (const key in obj) { if (obj[key] === val) { return key; } } } function createMouseSpec(specFunction, eventType, button, modifier) { let specName = `${keyForValue(import__328.ScreenSpaceEventType, eventType)} action`; if ((0, import__328.defined)(modifier)) { specName += ` with ${keyForValue( import__328.KeyboardEventModifier, modifier )} modifier`; } it(specName, function() { const eventOptions = { button, ctrlKey: modifier === import__328.KeyboardEventModifier.CTRL, altKey: modifier === import__328.KeyboardEventModifier.ALT, shiftKey: modifier === import__328.KeyboardEventModifier.SHIFT }; specFunction(eventType, modifier, eventOptions); }); } function createAllMouseSpecCombinations(specFunction, possibleButtons, possibleModifiers, possibleEventTypes) { for (let i = 0; i < possibleButtons.length; ++i) { const eventType = possibleEventTypes[i]; const button = possibleButtons[i]; for (let j = 0; j < possibleModifiers.length; ++j) { const modifier = possibleModifiers[j]; createMouseSpec(specFunction, eventType, button, modifier); } } } function simulateMouseDown(element2, options) { if (usePointerEvents) { DomEventSimulator_default.firePointerDown( element2, (0, import__328.combine)(options, { pointerType: "mouse" }) ); } else { DomEventSimulator_default.fireMouseDown(element2, options); } } function simulateMouseUp(element2, options) { if (usePointerEvents) { DomEventSimulator_default.firePointerUp( element2, (0, import__328.combine)(options, { pointerType: "mouse" }) ); } else { DomEventSimulator_default.fireMouseUp(element2, options); } } function simulateMouseMove(element2, options) { if (usePointerEvents) { DomEventSimulator_default.firePointerMove( element2, (0, import__328.combine)(options, { pointerType: "mouse" }) ); } else { DomEventSimulator_default.fireMouseMove(element2, options); } } describe("handles mouse down", function() { function testMouseDownEvent(eventType, modifier, eventOptions) { const action = createCloningSpy("action"); handler.setInputAction(action, eventType, modifier); expect(handler.getInputAction(eventType, modifier)).toEqual(action); function simulateInput() { simulateMouseDown( element, (0, import__328.combine)( { clientX: 1, clientY: 2 }, eventOptions ) ); } simulateInput(); expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith({ position: new import__328.Cartesian2(1, 2) }); action.calls.reset(); handler.removeInputAction(eventType, modifier); simulateInput(); expect(action).not.toHaveBeenCalled(); } const possibleButtons = [ MouseButton.LEFT, MouseButton.MIDDLE, MouseButton.RIGHT ]; const possibleModifiers = [ void 0, import__328.KeyboardEventModifier.SHIFT, import__328.KeyboardEventModifier.CTRL, import__328.KeyboardEventModifier.ALT ]; const possibleEventTypes = [ import__328.ScreenSpaceEventType.LEFT_DOWN, import__328.ScreenSpaceEventType.MIDDLE_DOWN, import__328.ScreenSpaceEventType.RIGHT_DOWN ]; createAllMouseSpecCombinations( testMouseDownEvent, possibleButtons, possibleModifiers, possibleEventTypes ); }); describe("handles mouse up", function() { function testMouseUpEvent(eventType, modifier, eventOptions) { const action = createCloningSpy("action"); handler.setInputAction(action, eventType, modifier); expect(handler.getInputAction(eventType, modifier)).toEqual(action); function simulateInput() { simulateMouseDown( element, (0, import__328.combine)( { clientX: 1, clientY: 2 }, eventOptions ) ); simulateMouseUp( element, (0, import__328.combine)( { clientX: 1, clientY: 2 }, eventOptions ) ); } simulateInput(); expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith({ position: new import__328.Cartesian2(1, 2) }); action.calls.reset(); function simulateInput2() { simulateMouseDown( element, (0, import__328.combine)( { clientX: 1, clientY: 2 }, eventOptions ) ); simulateMouseMove( element, (0, import__328.combine)( { clientX: 10, clientY: 11 }, eventOptions ) ); simulateMouseUp( element, (0, import__328.combine)( { clientX: 10, clientY: 11 }, eventOptions ) ); } simulateInput2(); expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith({ position: new import__328.Cartesian2(10, 11) }); action.calls.reset(); handler.removeInputAction(eventType, modifier); simulateInput(); simulateInput2(); expect(action).not.toHaveBeenCalled(); } const possibleButtons = [ MouseButton.LEFT, MouseButton.MIDDLE, MouseButton.RIGHT ]; const possibleModifiers = [ void 0, import__328.KeyboardEventModifier.SHIFT, import__328.KeyboardEventModifier.CTRL, import__328.KeyboardEventModifier.ALT ]; const possibleEventTypes = [ import__328.ScreenSpaceEventType.LEFT_UP, import__328.ScreenSpaceEventType.MIDDLE_UP, import__328.ScreenSpaceEventType.RIGHT_UP ]; createAllMouseSpecCombinations( testMouseUpEvent, possibleButtons, possibleModifiers, possibleEventTypes ); }); describe("handles mouse click", function() { function testMouseClickEvent(eventType, modifier, eventOptions) { const action = createCloningSpy("action"); handler.setInputAction(action, eventType, modifier); expect(handler.getInputAction(eventType, modifier)).toEqual(action); function simulateInput() { simulateMouseDown( element, (0, import__328.combine)( { clientX: 1, clientY: 2 }, eventOptions ) ); simulateMouseUp( element, (0, import__328.combine)( { clientX: 1, clientY: 2 }, eventOptions ) ); } simulateInput(); expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith({ position: new import__328.Cartesian2(1, 2) }); action.calls.reset(); simulateMouseDown( element, (0, import__328.combine)( { clientX: 1, clientY: 2 }, eventOptions ) ); simulateMouseUp( element, (0, import__328.combine)( { clientX: 10, clientY: 11 }, eventOptions ) ); expect(action).not.toHaveBeenCalled(); action.calls.reset(); handler.removeInputAction(eventType, modifier); simulateInput(); expect(action).not.toHaveBeenCalled(); } const possibleButtons = [ MouseButton.LEFT, MouseButton.MIDDLE, MouseButton.RIGHT ]; const possibleModifiers = [ void 0, import__328.KeyboardEventModifier.SHIFT, import__328.KeyboardEventModifier.CTRL, import__328.KeyboardEventModifier.ALT ]; const possibleEventTypes = [ import__328.ScreenSpaceEventType.LEFT_CLICK, import__328.ScreenSpaceEventType.MIDDLE_CLICK, import__328.ScreenSpaceEventType.RIGHT_CLICK ]; createAllMouseSpecCombinations( testMouseClickEvent, possibleButtons, possibleModifiers, possibleEventTypes ); }); describe("handles mouse double click", function() { function testMouseDoubleClickEvent(eventType, modifier, eventOptions) { const action = createCloningSpy("action"); handler.setInputAction(action, eventType, modifier); expect(handler.getInputAction(eventType, modifier)).toEqual(action); function simulateInput() { DomEventSimulator_default.fireDoubleClick( element, (0, import__328.combine)( { clientX: 1, clientY: 2 }, eventOptions ) ); } simulateInput(); expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith({ position: new import__328.Cartesian2(1, 2) }); action.calls.reset(); handler.removeInputAction(eventType, modifier); simulateInput(); expect(action).not.toHaveBeenCalled(); } const possibleButtons = [MouseButton.LEFT]; const possibleModifiers = [ void 0, import__328.KeyboardEventModifier.SHIFT, import__328.KeyboardEventModifier.CTRL, import__328.KeyboardEventModifier.ALT ]; const possibleEventTypes = [import__328.ScreenSpaceEventType.LEFT_DOUBLE_CLICK]; createAllMouseSpecCombinations( testMouseDoubleClickEvent, possibleButtons, possibleModifiers, possibleEventTypes ); }); describe("handles mouse move", function() { function testMouseMoveEvent(eventType, modifier, eventOptions) { const action = createCloningSpy("action"); handler.setInputAction(action, eventType, modifier); expect(handler.getInputAction(eventType, modifier)).toEqual(action); function simulateInput() { simulateMouseMove( element, (0, import__328.combine)( { clientX: 1, clientY: 2 }, eventOptions ) ); simulateMouseMove( element, (0, import__328.combine)( { clientX: 2, clientY: 3 }, eventOptions ) ); } simulateInput(); expect(action.calls.count()).toEqual(2); expect(action).toHaveBeenCalledWith({ startPosition: new import__328.Cartesian2(1, 2), endPosition: new import__328.Cartesian2(2, 3) }); action.calls.reset(); handler.removeInputAction(eventType, modifier); simulateInput(); expect(action).not.toHaveBeenCalled(); } const possibleButtons = [void 0]; const possibleModifiers = [ void 0, import__328.KeyboardEventModifier.SHIFT, import__328.KeyboardEventModifier.CTRL, import__328.KeyboardEventModifier.ALT ]; const possibleEventTypes = [import__328.ScreenSpaceEventType.MOUSE_MOVE]; createAllMouseSpecCombinations( testMouseMoveEvent, possibleButtons, possibleModifiers, possibleEventTypes ); }); describe("handles mouse wheel", function() { if ("onwheel" in document) { describe("using standard wheel event", function() { function testWheelEvent(eventType, modifier, eventOptions) { const action = createCloningSpy("action"); handler.setInputAction(action, eventType, modifier); expect(handler.getInputAction(eventType, modifier)).toEqual(action); function simulateInput() { DomEventSimulator_default.fireWheel( element, (0, import__328.combine)( { deltaY: 120 }, eventOptions ) ); } simulateInput(); expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith(-120); action.calls.reset(); handler.removeInputAction(eventType, modifier); simulateInput(); expect(action).not.toHaveBeenCalled(); } const possibleButtons = [void 0]; const possibleModifiers = [ void 0, import__328.KeyboardEventModifier.SHIFT, import__328.KeyboardEventModifier.CTRL, import__328.KeyboardEventModifier.ALT ]; const possibleEventTypes = [import__328.ScreenSpaceEventType.WHEEL]; createAllMouseSpecCombinations( testWheelEvent, possibleButtons, possibleModifiers, possibleEventTypes ); }); } else if (document.onmousewheel !== void 0) { describe("using legacy mousewheel event", function() { function testMouseWheelEvent(eventType, modifier, eventOptions) { const action = createCloningSpy("action"); handler.setInputAction(action, eventType, modifier); expect(handler.getInputAction(eventType, modifier)).toEqual(action); function simulateInput() { DomEventSimulator_default.fireMouseWheel( element, (0, import__328.combine)( { wheelDelta: -120 }, eventOptions ) ); } simulateInput(); expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith(-120); action.calls.reset(); handler.removeInputAction(eventType, modifier); simulateInput(); expect(action).not.toHaveBeenCalled(); } const possibleButtons = [void 0]; const possibleModifiers = [ void 0, import__328.KeyboardEventModifier.SHIFT, import__328.KeyboardEventModifier.CTRL, import__328.KeyboardEventModifier.ALT ]; const possibleEventTypes = [import__328.ScreenSpaceEventType.WHEEL]; createAllMouseSpecCombinations( testMouseWheelEvent, possibleButtons, possibleModifiers, possibleEventTypes ); }); } }); it("handles touch start", function() { const eventType = import__328.ScreenSpaceEventType.LEFT_DOWN; const action = createCloningSpy("action"); handler.setInputAction(action, eventType); expect(handler.getInputAction(eventType)).toEqual(action); function simulateInput() { const touchStartPosition = { clientX: 1, clientY: 2 }; if (usePointerEvents) { DomEventSimulator_default.firePointerDown( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchStartPosition ) ); } else { DomEventSimulator_default.fireTouchStart(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchStartPosition ) ] }); } } simulateInput(); expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith({ position: new import__328.Cartesian2(1, 2) }); action.calls.reset(); handler.removeInputAction(eventType); simulateInput(); expect(action).not.toHaveBeenCalled(); }); it("handles touch move", function() { const eventType = import__328.ScreenSpaceEventType.MOUSE_MOVE; const action = createCloningSpy("action"); handler.setInputAction(action, eventType); expect(handler.getInputAction(eventType)).toEqual(action); function simulateInput() { const touchStartPosition = { clientX: 1, clientY: 2 }; const touchMovePosition = { clientX: 10, clientY: 11 }; if (usePointerEvents) { DomEventSimulator_default.firePointerDown( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchStartPosition ) ); DomEventSimulator_default.firePointerMove( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchMovePosition ) ); } else { DomEventSimulator_default.fireTouchStart(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchStartPosition ) ] }); DomEventSimulator_default.fireTouchMove(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchMovePosition ) ] }); } } simulateInput(); expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith({ startPosition: new import__328.Cartesian2(1, 2), endPosition: new import__328.Cartesian2(10, 11) }); action.calls.reset(); handler.removeInputAction(eventType); simulateInput(); expect(action).not.toHaveBeenCalled(); }); it("handles touch end", function() { const eventType = import__328.ScreenSpaceEventType.LEFT_UP; const action = createCloningSpy("action"); handler.setInputAction(action, eventType); expect(handler.getInputAction(eventType)).toEqual(action); function simulateInput() { const touchStartPosition = { clientX: 1, clientY: 2 }; const touchEndPosition = { clientX: 1, clientY: 2 }; if (usePointerEvents) { DomEventSimulator_default.firePointerDown( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchStartPosition ) ); DomEventSimulator_default.firePointerUp( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchEndPosition ) ); } else { DomEventSimulator_default.fireTouchStart(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchStartPosition ) ] }); DomEventSimulator_default.fireTouchEnd(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchEndPosition ) ] }); } } simulateInput(); expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith({ position: new import__328.Cartesian2(1, 2) }); action.calls.reset(); function simulateInput2() { const touchStartPosition = { clientX: 1, clientY: 2 }; const touchMovePosition = { clientX: 10, clientY: 11 }; const touchEndPosition = { clientX: 10, clientY: 11 }; if (usePointerEvents) { DomEventSimulator_default.firePointerDown( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchStartPosition ) ); DomEventSimulator_default.firePointerMove( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchMovePosition ) ); DomEventSimulator_default.firePointerUp( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchEndPosition ) ); } else { DomEventSimulator_default.fireTouchStart(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchStartPosition ) ] }); DomEventSimulator_default.fireTouchMove(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchMovePosition ) ] }); DomEventSimulator_default.fireTouchEnd(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchEndPosition ) ] }); } } simulateInput2(); expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith({ position: new import__328.Cartesian2(10, 11) }); action.calls.reset(); handler.removeInputAction(eventType); simulateInput(); simulateInput2(); expect(action).not.toHaveBeenCalled(); }); it("treats touch end as touch cancel", function() { const eventType = import__328.ScreenSpaceEventType.LEFT_UP; const action = createCloningSpy("action"); handler.setInputAction(action, eventType); expect(handler.getInputAction(eventType)).toEqual(action); function simulateInput() { const touchStartPosition = { clientX: 1, clientY: 2 }; const touchEndPosition = { clientX: 1, clientY: 2 }; if (usePointerEvents) { DomEventSimulator_default.firePointerDown( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchStartPosition ) ); DomEventSimulator_default.firePointerCancel( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchEndPosition ) ); } else { DomEventSimulator_default.fireTouchStart(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchStartPosition ) ] }); DomEventSimulator_default.fireTouchCancel(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchEndPosition ) ] }); } } simulateInput(); expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith({ position: new import__328.Cartesian2(1, 2) }); action.calls.reset(); function simulateInput2() { const touchStartPosition = { clientX: 1, clientY: 2 }; const touchMovePosition = { clientX: 10, clientY: 11 }; const touchEndPosition = { clientX: 10, clientY: 11 }; if (usePointerEvents) { DomEventSimulator_default.firePointerDown( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchStartPosition ) ); DomEventSimulator_default.firePointerMove( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchMovePosition ) ); DomEventSimulator_default.firePointerCancel( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchEndPosition ) ); } else { DomEventSimulator_default.fireTouchStart(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchStartPosition ) ] }); DomEventSimulator_default.fireTouchMove(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchMovePosition ) ] }); DomEventSimulator_default.fireTouchCancel(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchEndPosition ) ] }); } } simulateInput2(); expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith({ position: new import__328.Cartesian2(10, 11) }); action.calls.reset(); handler.removeInputAction(eventType); simulateInput(); simulateInput2(); expect(action).not.toHaveBeenCalled(); }); it("handles touch pinch start", function() { const eventType = import__328.ScreenSpaceEventType.PINCH_START; const action = createCloningSpy("action"); handler.setInputAction(action, eventType); expect(handler.getInputAction(eventType)).toEqual(action); function simulateInput() { const touch1StartPosition = { clientX: 1, clientY: 2 }; const touch2StartPosition = { clientX: 3, clientY: 4 }; if (usePointerEvents) { DomEventSimulator_default.firePointerDown( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touch1StartPosition ) ); DomEventSimulator_default.firePointerDown( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 2 }, touch2StartPosition ) ); } else { DomEventSimulator_default.fireTouchStart(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touch1StartPosition ) ] }); DomEventSimulator_default.fireTouchStart(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touch1StartPosition ), (0, import__328.combine)( { identifier: 1 }, touch2StartPosition ) ] }); } } simulateInput(); expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith({ position1: new import__328.Cartesian2(1, 2), position2: new import__328.Cartesian2(3, 4) }); action.calls.reset(); handler.removeInputAction(eventType); simulateInput(); expect(action).not.toHaveBeenCalled(); }); it("handles touch pinch move", function() { const eventType = import__328.ScreenSpaceEventType.PINCH_MOVE; const action = createCloningSpy("action"); handler.setInputAction(action, eventType); expect(handler.getInputAction(eventType)).toEqual(action); function simulateInput() { const touch1StartPosition = { clientX: 1, clientY: 2 }; const touch2StartPosition = { clientX: 4, clientY: 3 }; const touch1MovePosition = { clientX: 10, clientY: 11 }; const touch2MovePosition = { clientX: 21, clientY: 20 }; if (usePointerEvents) { DomEventSimulator_default.firePointerDown( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touch1StartPosition ) ); DomEventSimulator_default.firePointerDown( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 2 }, touch2StartPosition ) ); DomEventSimulator_default.firePointerMove( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touch1MovePosition ) ); DomEventSimulator_default.firePointerMove( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 2 }, touch2MovePosition ) ); } else { DomEventSimulator_default.fireTouchStart(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touch1StartPosition ) ] }); DomEventSimulator_default.fireTouchStart(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touch1StartPosition ), (0, import__328.combine)( { identifier: 1 }, touch2StartPosition ) ] }); DomEventSimulator_default.fireTouchMove(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touch1MovePosition ), (0, import__328.combine)( { identifier: 1 }, touch2MovePosition ) ] }); } } simulateInput(); if (usePointerEvents) { expect(action.calls.count()).toEqual(2); expect(action).toHaveBeenCalledWith({ distance: { startPosition: new import__328.Cartesian2(0, Math.sqrt(3 * 3 + 1 * 1) * 0.25), endPosition: new import__328.Cartesian2(0, Math.sqrt(-6 * -6 + -8 * -8) * 0.25) }, angleAndHeight: { startPosition: new import__328.Cartesian2(Math.atan2(1, 3), (3 + 2) * 0.125), endPosition: new import__328.Cartesian2(Math.atan2(-8, -6), (3 + 11) * 0.125) } }); expect(action).toHaveBeenCalledWith({ distance: { startPosition: new import__328.Cartesian2(0, Math.sqrt(-6 * -6 + -8 * -8) * 0.25), endPosition: new import__328.Cartesian2(0, Math.sqrt(11 * 11 + 9 * 9) * 0.25) }, angleAndHeight: { startPosition: new import__328.Cartesian2(Math.atan2(-8, -6), (3 + 11) * 0.125), endPosition: new import__328.Cartesian2(Math.atan2(9, 11), (11 + 20) * 0.125) } }); } else { expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith({ distance: { startPosition: new import__328.Cartesian2(0, Math.sqrt(3 * 3 + 1 * 1) * 0.25), endPosition: new import__328.Cartesian2(0, Math.sqrt(11 * 11 + 9 * 9) * 0.25) }, angleAndHeight: { startPosition: new import__328.Cartesian2(Math.atan2(1, 3), (3 + 2) * 0.125), endPosition: new import__328.Cartesian2(Math.atan2(9, 11), (11 + 20) * 0.125) } }); } action.calls.reset(); handler.removeInputAction(eventType); simulateInput(); expect(action).not.toHaveBeenCalled(); }); it("handles touch pinch release", function() { const leftDownEventType = import__328.ScreenSpaceEventType.LEFT_DOWN; const leftDownAction = createCloningSpy("LEFT_DOWN"); handler.setInputAction(leftDownAction, leftDownEventType); const pinchStartEventType = import__328.ScreenSpaceEventType.PINCH_START; const pinchStartAction = createCloningSpy("PINCH_START"); handler.setInputAction(pinchStartAction, pinchStartEventType); const pinchEndEventType = import__328.ScreenSpaceEventType.PINCH_END; const pinchEndAction = createCloningSpy("PINCH_END"); handler.setInputAction(pinchEndAction, pinchEndEventType); const touch1Position = { clientX: 1, clientY: 2 }; const touch2Position = { clientX: 4, clientY: 3 }; if (usePointerEvents) { DomEventSimulator_default.firePointerDown( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touch1Position ) ); DomEventSimulator_default.firePointerDown( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 2 }, touch2Position ) ); leftDownAction.calls.reset(); DomEventSimulator_default.firePointerUp( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touch1Position ) ); expect(pinchEndAction).not.toHaveBeenCalled(); expect(leftDownAction).not.toHaveBeenCalled(); pinchEndAction.calls.reset(); pinchStartAction.calls.reset(); DomEventSimulator_default.firePointerDown( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touch2Position ) ); expect(pinchStartAction).not.toHaveBeenCalled(); DomEventSimulator_default.firePointerUp( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touch2Position ) ); DomEventSimulator_default.firePointerUp( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 2 }, touch2Position ) ); expect(pinchEndAction).toHaveBeenCalled(); } else { DomEventSimulator_default.fireTouchStart(element, { changedTouches: [ (0, import__328.combine)({ identifier: 0 }, touch1Position), (0, import__328.combine)({ identifier: 1 }, touch2Position) ] }); leftDownAction.calls.reset(); DomEventSimulator_default.fireTouchEnd(element, { changedTouches: [(0, import__328.combine)({ identifier: 0 }, touch1Position)] }); expect(pinchEndAction).not.toHaveBeenCalled(); expect(leftDownAction).not.toHaveBeenCalled(); pinchEndAction.calls.reset(); DomEventSimulator_default.fireTouchEnd(element, { changedTouches: [(0, import__328.combine)({ identifier: 1 }, touch2Position)] }); expect(pinchEndAction).toHaveBeenCalled(); } }); it("handles touch click", function() { const eventType = import__328.ScreenSpaceEventType.LEFT_CLICK; const action = createCloningSpy("action"); handler.setInputAction(action, eventType); expect(handler.getInputAction(eventType)).toEqual(action); function simulateInput() { const touchStartPosition = { clientX: 1, clientY: 2 }; const touchEndPosition = { clientX: 1, clientY: 2 }; if (usePointerEvents) { DomEventSimulator_default.firePointerDown( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchStartPosition ) ); DomEventSimulator_default.firePointerUp( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchEndPosition ) ); } else { DomEventSimulator_default.fireTouchStart(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchStartPosition ) ] }); DomEventSimulator_default.fireTouchEnd(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchEndPosition ) ] }); } } simulateInput(); expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith({ position: new import__328.Cartesian2(1, 2) }); action.calls.reset(); handler.removeInputAction(eventType); simulateInput(); expect(action).not.toHaveBeenCalled(); }); it("handles touch and hold gesture", function() { jasmine.clock().install(); const delay = import__328.ScreenSpaceEventHandler.touchHoldDelayMilliseconds; let eventType = import__328.ScreenSpaceEventType.RIGHT_CLICK; const action = createCloningSpy("action"); handler.setInputAction(action, eventType); expect(handler.getInputAction(eventType)).toEqual(action); function simulateInput(timeout) { const touchStartPosition = { clientX: 1, clientY: 2 }; const touchEndPosition = { clientX: 1, clientY: 2 }; if (usePointerEvents) { DomEventSimulator_default.firePointerDown( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchStartPosition ) ); jasmine.clock().tick(timeout); DomEventSimulator_default.firePointerUp( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchEndPosition ) ); } else { DomEventSimulator_default.fireTouchStart(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchStartPosition ) ] }); jasmine.clock().tick(timeout); DomEventSimulator_default.fireTouchEnd(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchEndPosition ) ] }); } } simulateInput(delay + 1); expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith({ position: new import__328.Cartesian2(1, 2) }); action.calls.reset(); simulateInput(delay - 1); expect(action).not.toHaveBeenCalled(); action.calls.reset(); handler.removeInputAction(eventType); simulateInput(delay + 1); expect(action).not.toHaveBeenCalled(); eventType = import__328.ScreenSpaceEventType.LEFT_CLICK; handler.setInputAction(action, eventType); simulateInput(delay + 1); expect(action).not.toHaveBeenCalled(); jasmine.clock().uninstall(); }); it("treats touch cancel as touch end for touch clicks", function() { const eventType = import__328.ScreenSpaceEventType.LEFT_CLICK; const action = createCloningSpy("action"); handler.setInputAction(action, eventType); expect(handler.getInputAction(eventType)).toEqual(action); function simulateInput() { const touchStartPosition = { clientX: 1, clientY: 2 }; const touchEndPosition = { clientX: 1, clientY: 2 }; if (usePointerEvents) { DomEventSimulator_default.firePointerDown( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchStartPosition ) ); DomEventSimulator_default.firePointerCancel( element, (0, import__328.combine)( { pointerType: "touch", pointerId: 1 }, touchEndPosition ) ); } else { DomEventSimulator_default.fireTouchStart(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchStartPosition ) ] }); DomEventSimulator_default.fireTouchCancel(element, { changedTouches: [ (0, import__328.combine)( { identifier: 0 }, touchEndPosition ) ] }); } } simulateInput(); expect(action.calls.count()).toEqual(1); expect(action).toHaveBeenCalledWith({ position: new import__328.Cartesian2(1, 2) }); action.calls.reset(); handler.removeInputAction(eventType); simulateInput(); expect(action).not.toHaveBeenCalled(); }); it("sets isDestroyed when destroyed", function() { expect(handler.isDestroyed()).toEqual(false); handler.destroy(); expect(handler.isDestroyed()).toEqual(true); }); it("unregisters event listeners when destroyed", function() { handler = handler.destroy(); spyOn(element, "addEventListener").and.callThrough(); spyOn(element, "removeEventListener").and.callThrough(); handler = new import__328.ScreenSpaceEventHandler(element); expect(element.addEventListener.calls.count()).not.toEqual(0); expect(element.removeEventListener.calls.count()).toEqual(0); handler.destroy(); expect(element.removeEventListener.calls.count()).toEqual( element.addEventListener.calls.count() ); }); }); // packages/engine/Specs/Core/ShowGeometryInstanceAttributeSpec.js var import__329 = __toESM(require_Cesium(), 1); describe("Core/ShowGeometryInstanceAttribute", function() { it("constructor", function() { const attribute = new import__329.ShowGeometryInstanceAttribute(false); expect(attribute.componentDatatype).toEqual( import__329.ComponentDatatype.UNSIGNED_BYTE ); expect(attribute.componentsPerAttribute).toEqual(1); expect(attribute.normalize).toEqual(false); expect(attribute.value).toEqual(new Uint8Array([false])); }); it("toValue", function() { const expectedResult = new Uint8Array([true]); expect(import__329.ShowGeometryInstanceAttribute.toValue(true)).toEqual(expectedResult); }); it("toValue works with a result parameter", function() { const expectedResult = new Uint8Array([true]); const result = new Uint8Array(1); const returnedResult = import__329.ShowGeometryInstanceAttribute.toValue(true, result); expect(returnedResult).toEqual(expectedResult); expect(returnedResult).toBe(result); }); it("toValue throws without a color", function() { expect(function() { import__329.ShowGeometryInstanceAttribute.toValue(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/Simon1994PlanetaryPositionsSpec.js var import__330 = __toESM(require_Cesium(), 1); describe("Core/Simon1994PlanetaryPositions", function() { it("computes correct sun position", function() { let date = new import__330.JulianDate(2451545, 0, import__330.TimeStandard.TAI); let sun = import__330.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame(date); let X = 26500268539790234e-6; let Y = -13275644725327325e-5; let Z = -57556483362533806e-6; expect(X).toEqualEpsilon(sun.x, import__330.Math.EPSILON2); expect(Y).toEqualEpsilon(sun.y, import__330.Math.EPSILON2); expect(Z).toEqualEpsilon(sun.z, import__330.Math.EPSILON2); date = new import__330.JulianDate(24564015e-1, 0, import__330.TimeStandard.TAI); sun = import__330.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame(date); X = 13151238894033589e-5; Y = 6666134266794993e-5; Z = 2889797560790526e-5; expect(X).toEqualEpsilon(sun.x, import__330.Math.EPSILON3); expect(Y).toEqualEpsilon(sun.y, import__330.Math.EPSILON3); expect(Z).toEqualEpsilon(sun.z, import__330.Math.EPSILON3); date = new import__330.JulianDate(2455998591667e-6, 0, import__330.TimeStandard.TAI); sun = import__330.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame(date); X = 14710998995619534e-5; Y = -1959999688121758e-5; Z = -8497578102769646e-6; expect(X).toEqualEpsilon(sun.x, import__330.Math.EPSILON3); expect(Y).toEqualEpsilon(sun.y, import__330.Math.EPSILON3); expect(Z).toEqualEpsilon(sun.z, import__330.Math.EPSILON3); }); it("computes correct moon position", function() { let date = new import__330.JulianDate(2451545, 0, import__330.TimeStandard.TAI); let moon = import__330.Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame(date); let X = -29163241061232185e-8; let Y = -2665221463682163e-7; let Z = -7599451808104315e-8; expect(X).toEqualEpsilon(moon.x, import__330.Math.EPSILON4); expect(Y).toEqualEpsilon(moon.y, import__330.Math.EPSILON4); expect(Z).toEqualEpsilon(moon.z, import__330.Math.EPSILON4); date = new import__330.JulianDate(24564015e-1, 0, import__330.TimeStandard.TAI); moon = import__330.Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame(date); X = -2237929744736526e-7; Y = 3157724353449064e-7; Z = 9791301123611277e-8; expect(X).toEqualEpsilon(moon.x, import__330.Math.EPSILON4); expect(Y).toEqualEpsilon(moon.y, import__330.Math.EPSILON4); expect(Z).toEqualEpsilon(moon.z, import__330.Math.EPSILON4); date = new import__330.JulianDate(2455998591667e-6, 0, import__330.TimeStandard.TAI); moon = import__330.Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame(date); X = -26842611700202647e-8; Y = -22046886173998192e-8; Z = -11067016458446842e-8; expect(X).toEqualEpsilon(moon.x, import__330.Math.EPSILON4); expect(Y).toEqualEpsilon(moon.y, import__330.Math.EPSILON4); expect(Z).toEqualEpsilon(moon.z, import__330.Math.EPSILON4); }); it("has the sun rising in the east and setting in the west", function() { let transformMatrix = new import__330.Matrix3(); const timesOfDay = []; let i; for (i = 1; i < 25; i++) { const date = /* @__PURE__ */ new Date("July 6, 2011"); date.setUTCHours(i, 0, 0, 0); timesOfDay.push(import__330.JulianDate.fromDate(date)); } const angles = []; for (i = 0; i < 24; i++) { transformMatrix = import__330.Transforms.computeIcrfToFixedMatrix( timesOfDay[i], transformMatrix ); if (!(0, import__330.defined)(transformMatrix)) { transformMatrix = import__330.Transforms.computeTemeToPseudoFixedMatrix( timesOfDay[i], transformMatrix ); } const position = import__330.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame( timesOfDay[i] ); import__330.Matrix3.multiplyByVector(transformMatrix, position, position); angles.push( import__330.Math.convertLongitudeRange(Math.atan2(position.y, position.x)) ); } for (i = 1; i < 24; i++) { expect(angles[i]).toBeLessThan(angles[i - 1]); } }); it("works without a time", function() { import__330.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame(void 0); }); }); // packages/engine/Specs/Core/SimplePolylineGeometrySpec.js var import__331 = __toESM(require_Cesium(), 1); var import__332 = __toESM(require_Cesium(), 1); describe("Core/SimplePolylineGeometry", function() { it("constructor throws with no positions", function() { expect(function() { return new import__331.SimplePolylineGeometry(); }).toThrowDeveloperError(); }); it("constructor throws with less than two positions", function() { expect(function() { return new import__331.SimplePolylineGeometry({ positions: [import__331.Cartesian3.ZERO] }); }).toThrowDeveloperError(); }); it("constructor throws with invalid number of colors", function() { expect(function() { return new import__331.SimplePolylineGeometry({ positions: [import__331.Cartesian3.ZERO, import__331.Cartesian3.UNIT_X, import__331.Cartesian3.UNIT_Y], colors: [] }); }).toThrowDeveloperError(); }); it("constructor computes all vertex attributes", function() { const positions2 = [ new import__331.Cartesian3(1, 0, 0), new import__331.Cartesian3(0, 1, 0), new import__331.Cartesian3(0, 0, 1) ]; const line2 = import__331.SimplePolylineGeometry.createGeometry( new import__331.SimplePolylineGeometry({ positions: positions2, granularity: Math.PI, ellipsoid: import__331.Ellipsoid.UNIT_SPHERE }) ); expect(line2.attributes.position.values).toEqualEpsilon( [1, 0, 0, 0, 1, 0, 0, 0, 1], import__332.Math.EPSILON10 ); expect(line2.indices).toEqual([0, 1, 1, 2]); expect(line2.primitiveType).toEqual(import__331.PrimitiveType.LINES); expect(line2.boundingSphere).toEqual(import__331.BoundingSphere.fromPoints(positions2)); }); it("constructor computes all vertex attributes for rhumb lines", function() { const positions2 = import__331.Cartesian3.fromDegreesArray([30, 30, 30, 60, 60, 60]); const line2 = import__331.SimplePolylineGeometry.createGeometry( new import__331.SimplePolylineGeometry({ positions: positions2, granularity: Math.PI, ellipsoid: import__331.Ellipsoid.UNIT_SPHERE, arcType: import__331.ArcType.RHUMB }) ); const cartesian3Array = []; import__331.Cartesian3.packArray(positions2, cartesian3Array); expect(line2.attributes.position.values).toEqualEpsilon( cartesian3Array, import__332.Math.EPSILON8 ); expect(line2.indices).toEqual([0, 1, 1, 2]); expect(line2.primitiveType).toEqual(import__331.PrimitiveType.LINES); expect(line2.boundingSphere).toEqual(import__331.BoundingSphere.fromPoints(positions2)); }); it("constructor computes per segment colors", function() { const positions2 = [ new import__331.Cartesian3(1, 0, 0), new import__331.Cartesian3(0, 1, 0), new import__331.Cartesian3(0, 0, 1) ]; const colors = [ new import__331.Color(1, 0, 0, 1), new import__331.Color(0, 1, 0, 1), new import__331.Color(0, 0, 1, 1) ]; const line2 = import__331.SimplePolylineGeometry.createGeometry( new import__331.SimplePolylineGeometry({ positions: positions2, colors, granularity: Math.PI, ellipsoid: import__331.Ellipsoid.UNIT_SPHERE }) ); expect(line2.attributes.color).toBeDefined(); const numVertices = positions2.length * 2 - 2; expect(line2.attributes.color.values.length).toEqual(numVertices * 4); }); it("constructor computes per vertex colors", function() { const positions2 = [ new import__331.Cartesian3(1, 0, 0), new import__331.Cartesian3(0, 1, 0), new import__331.Cartesian3(0, 0, 1) ]; const colors = [ new import__331.Color(1, 0, 0, 1), new import__331.Color(0, 1, 0, 1), new import__331.Color(0, 0, 1, 1) ]; const line2 = import__331.SimplePolylineGeometry.createGeometry( new import__331.SimplePolylineGeometry({ positions: positions2, colors, colorsPerVertex: true, granularity: Math.PI, ellipsoid: import__331.Ellipsoid.UNIT_SPHERE }) ); expect(line2.attributes.color).toBeDefined(); const numVertices = positions2.length; expect(line2.attributes.color.values.length).toEqual(numVertices * 4); }); it("constructor computes all vertex attributes, no subdivision", function() { const positions2 = [ new import__331.Cartesian3(), new import__331.Cartesian3(1, 0, 0), new import__331.Cartesian3(2, 0, 0) ]; const line2 = import__331.SimplePolylineGeometry.createGeometry( new import__331.SimplePolylineGeometry({ positions: positions2, arcType: import__331.ArcType.NONE }) ); expect(line2.attributes.position.values).toEqual([ 0, 0, 0, 1, 0, 0, 2, 0, 0 ]); expect(line2.indices).toEqual([0, 1, 1, 2]); expect(line2.primitiveType).toEqual(import__331.PrimitiveType.LINES); expect(line2.boundingSphere).toEqual(import__331.BoundingSphere.fromPoints(positions2)); }); it("constructor computes per segment colors, no subdivision", function() { const positions2 = [ new import__331.Cartesian3(), new import__331.Cartesian3(1, 0, 0), new import__331.Cartesian3(2, 0, 0) ]; const colors = [ new import__331.Color(1, 0, 0, 1), new import__331.Color(0, 1, 0, 1), new import__331.Color(0, 0, 1, 1) ]; const line2 = import__331.SimplePolylineGeometry.createGeometry( new import__331.SimplePolylineGeometry({ positions: positions2, colors, arcType: import__331.ArcType.NONE }) ); expect(line2.attributes.color).toBeDefined(); const numVertices = positions2.length * 2 - 2; expect(line2.attributes.color.values.length).toEqual(numVertices * 4); }); it("constructor computes per vertex colors, no subdivision", function() { const positions2 = [ new import__331.Cartesian3(), new import__331.Cartesian3(1, 0, 0), new import__331.Cartesian3(2, 0, 0) ]; const colors = [ new import__331.Color(1, 0, 0, 1), new import__331.Color(0, 1, 0, 1), new import__331.Color(0, 0, 1, 1) ]; const line2 = import__331.SimplePolylineGeometry.createGeometry( new import__331.SimplePolylineGeometry({ positions: positions2, colors, colorsPerVertex: true, arcType: import__331.ArcType.NONE }) ); expect(line2.attributes.color).toBeDefined(); const numVertices = positions2.length; expect(line2.attributes.color.values.length).toEqual(numVertices * 4); }); const positions = [ new import__331.Cartesian3(1, 2, 3), new import__331.Cartesian3(4, 5, 6), new import__331.Cartesian3(7, 8, 9) ]; let line = new import__331.SimplePolylineGeometry({ positions, colors: [import__331.Color.RED, import__331.Color.LIME, import__331.Color.BLUE], colorsPerVertex: true, arcType: import__331.ArcType.NONE, granularity: 11, ellipsoid: new import__331.Ellipsoid(12, 13, 14) }); let packedInstance = [ 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 12, 13, 14, 1, 0, 11 ]; createPackableSpecs_default( import__331.SimplePolylineGeometry, line, packedInstance, "per vertex colors" ); line = new import__331.SimplePolylineGeometry({ positions, colorsPerVertex: false, arcType: import__331.ArcType.NONE, granularity: 11, ellipsoid: new import__331.Ellipsoid(12, 13, 14) }); packedInstance = [3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 12, 13, 14, 0, 0, 11]; createPackableSpecs_default(import__331.SimplePolylineGeometry, line, packedInstance); line = new import__331.SimplePolylineGeometry({ positions, width: 10, colorsPerVertex: false, arcType: import__331.ArcType.GEODESIC, granularity: 11, ellipsoid: new import__331.Ellipsoid(12, 13, 14) }); packedInstance = [3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 12, 13, 14, 0, 1, 11]; createPackableSpecs_default( import__331.SimplePolylineGeometry, line, packedInstance, "geodesic line" ); line = new import__331.SimplePolylineGeometry({ positions, width: 10, colorsPerVertex: false, arcType: import__331.ArcType.RHUMB, granularity: 11, ellipsoid: new import__331.Ellipsoid(12, 13, 14) }); packedInstance = [3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 12, 13, 14, 0, 2, 11]; createPackableSpecs_default( import__331.SimplePolylineGeometry, line, packedInstance, "rhumb line" ); line = new import__331.SimplePolylineGeometry({ positions, width: 10, colorsPerVertex: false, arcType: import__331.ArcType.NONE, granularity: 11, ellipsoid: new import__331.Ellipsoid(12, 13, 14) }); packedInstance = [3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 12, 13, 14, 0, 0, 11]; createPackableSpecs_default( import__331.SimplePolylineGeometry, line, packedInstance, "straight line" ); }); // packages/engine/Specs/Core/SphereGeometrySpec.js var import__333 = __toESM(require_Cesium(), 1); var import__334 = __toESM(require_Cesium(), 1); describe("Core/SphereGeometry", function() { it("constructor throws with invalid stackPartitions", function() { expect(function() { return new import__333.SphereGeometry({ stackPartitions: -1 }); }).toThrowDeveloperError(); }); it("constructor throws with invalid slicePartitions", function() { expect(function() { return new import__333.SphereGeometry({ slicePartitions: -1 }); }).toThrowDeveloperError(); }); it("computes positions", function() { const m = import__333.SphereGeometry.createGeometry( new import__333.SphereGeometry({ vertexFormat: import__333.VertexFormat.POSITION_ONLY, radius: 1, stackPartitions: 3, slicePartitions: 3 }) ); const numVertices = 36; const numTriangles = 18; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); expect(m.boundingSphere.radius).toEqual(1); }); it("compute all vertex attributes", function() { const m = import__333.SphereGeometry.createGeometry( new import__333.SphereGeometry({ vertexFormat: import__333.VertexFormat.ALL, radius: 1, stackPartitions: 3, slicePartitions: 3 }) ); const numVertices = 36; const numTriangles = 18; expect(m.attributes.position.values.length).toEqual(numVertices * 3); expect(m.attributes.st.values.length).toEqual(numVertices * 2); expect(m.attributes.normal.values.length).toEqual(numVertices * 3); expect(m.attributes.tangent.values.length).toEqual(numVertices * 3); expect(m.attributes.bitangent.values.length).toEqual(numVertices * 3); expect(m.indices.length).toEqual(numTriangles * 3); }); it("computes attributes for a unit sphere", function() { const m = import__333.SphereGeometry.createGeometry( new import__333.SphereGeometry({ vertexFormat: import__333.VertexFormat.ALL, radius: 1, stackPartitions: 3, slicePartitions: 3 }) ); const positions = m.attributes.position.values; const normals = m.attributes.normal.values; const tangents = m.attributes.tangent.values; const bitangents = m.attributes.bitangent.values; for (let i = 0; i < positions.length; i += 3) { const position = import__333.Cartesian3.fromArray(positions, i); const normal = import__333.Cartesian3.fromArray(normals, i); const tangent = import__333.Cartesian3.fromArray(tangents, i); const bitangent = import__333.Cartesian3.fromArray(bitangents, i); expect(import__333.Cartesian3.magnitude(position)).toEqualEpsilon( 1, import__334.Math.EPSILON10 ); expect(normal).toEqualEpsilon( import__333.Cartesian3.normalize(position, position), import__334.Math.EPSILON7 ); expect(import__333.Cartesian3.dot(import__333.Cartesian3.UNIT_Z, tangent)).not.toBeLessThan(0); expect(bitangent).toEqualEpsilon( import__333.Cartesian3.cross(normal, tangent, normal), import__334.Math.EPSILON7 ); } }); it("undefined is returned if radius is equals to zero", function() { const sphere2 = new import__333.SphereGeometry({ radius: 0, vertexFormat: import__333.VertexFormat.POSITION_ONLY }); const geometry = import__333.SphereGeometry.createGeometry(sphere2); expect(geometry).toBeUndefined(); }); const sphere = new import__333.SphereGeometry({ vertexFormat: import__333.VertexFormat.POSITION_ONLY, radius: 1, stackPartitions: 3, slicePartitions: 3 }); const packedInstance = [ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, import__334.Math.TWO_PI, 0, import__334.Math.PI, 3, 3, -1 ]; createPackableSpecs_default(import__333.SphereGeometry, sphere, packedInstance); }); // packages/engine/Specs/Core/SphereOutlineGeometrySpec.js var import__335 = __toESM(require_Cesium(), 1); var import__336 = __toESM(require_Cesium(), 1); describe("Core/SphereOutlineGeometry", function() { it("constructor throws if stackPartitions less than 1", function() { expect(function() { return new import__335.SphereOutlineGeometry({ stackPartitions: 0 }); }).toThrowDeveloperError(); }); it("constructor throws if slicePartitions less than 0", function() { expect(function() { return new import__335.SphereOutlineGeometry({ slicePartitions: -1 }); }).toThrowDeveloperError(); }); it("constructor throws if subdivisions less than 0", function() { expect(function() { return new import__335.SphereOutlineGeometry({ subdivisions: -2 }); }).toThrowDeveloperError(); }); it("computes positions", function() { const m = import__335.SphereOutlineGeometry.createGeometry( new import__335.SphereOutlineGeometry({ stackPartitions: 2, slicePartitions: 2, subdivisions: 2 }) ); expect(m.attributes.position.values.length).toEqual(12 * 3); expect(m.indices.length).toEqual(6 * 2); expect(m.boundingSphere.radius).toEqual(1); }); it("undefined is returned if radius is equals to zero", function() { const sphereOutline = new import__335.SphereOutlineGeometry({ radius: 0 }); const geometry = import__335.SphereOutlineGeometry.createGeometry(sphereOutline); expect(geometry).toBeUndefined(); }); const sphere = new import__335.SphereOutlineGeometry({ radius: 1, stackPartitions: 3, slicePartitions: 3, subdivisions: 2 }); const packedInstance = [ 1, 1, 1, 1, 1, 1, 0, import__336.Math.TWO_PI, 0, import__336.Math.PI, 3, 3, 2, -1 ]; createPackableSpecs_default(import__335.SphereOutlineGeometry, sphere, packedInstance); }); // packages/engine/Specs/Core/SphericalSpec.js var import__337 = __toESM(require_Cesium(), 1); var import__338 = __toESM(require_Cesium(), 1); describe("Core/Spherical", function() { function NotSpherical(clock, cone, magnitude) { this.clock = clock; this.cone = cone; this.magnitude = magnitude; } NotSpherical.areEqual = function(left, right) { return left.clock === right.clock && left.cone === right.cone && left.magnitude === right.magnitude; }; it("Default constructing sets properties to their expected values.", function() { const v = new import__337.Spherical(); expect(v.clock).toEqual(0); expect(v.cone).toEqual(0); expect(v.magnitude).toEqual(1); }); it("Construtor parameters are assigned to the appropriate properties", function() { const v = new import__337.Spherical(1, 2, 3); expect(v.clock).toEqual(1); expect(v.cone).toEqual(2); expect(v.magnitude).toEqual(3); }); const fortyFiveDegrees = Math.PI / 4; const sixtyDegrees = Math.PI / 3; const cartesian = new import__337.Cartesian3(1, Math.sqrt(3), -2); const spherical = new import__337.Spherical( sixtyDegrees, fortyFiveDegrees + Math.PI / 2, Math.sqrt(8) ); it("Can convert Cartesian3 to a new spherical instance", function() { expect(spherical).toEqualEpsilon( import__337.Spherical.fromCartesian3(cartesian), import__338.Math.EPSILON15 ); }); it("Can convert Cartesian3 to an existing spherical instance", function() { const existing = new import__337.Spherical(); expect(spherical).toEqualEpsilon( import__337.Spherical.fromCartesian3(cartesian, existing), import__338.Math.EPSILON15 ); expect(spherical).toEqualEpsilon(existing, import__338.Math.EPSILON15); }); it("Cloning with no result parameter returns a new instance.", function() { const v = new import__337.Spherical(1, 2, 3); const clone24 = v.clone(); expect(clone24).not.toBe(v); expect(clone24).toBeInstanceOf(import__337.Spherical); expect(clone24).toEqual(v); }); it("Cloning with result modifies existing instance and returns it.", function() { const v = new import__337.Spherical(1, 2, 3); const w = new NotSpherical(); expect(NotSpherical.areEqual(v, w)).toEqual(false); const clone24 = v.clone(w); expect(clone24).not.toBe(v); expect(clone24).toBe(w); expect(NotSpherical.areEqual(v, w)).toEqual(true); }); it("Normalizing with no result parameter creates new instance and sets magnitude to 1.0", function() { const v = new import__337.Spherical(0, 2, 3); const w = import__337.Spherical.normalize(v); expect(w).not.toEqual(v); expect(w.clock).toEqual(0); expect(w.cone).toEqual(2); expect(w.magnitude).toEqual(1); }); it("Normalizing with result parameter modifies instance and sets magnitude to 1.0", function() { const v = new import__337.Spherical(0, 2, 3); const w = new NotSpherical(); const q = import__337.Spherical.normalize(v, w); expect(q).not.toEqual(v); expect(q).toBe(w); expect(q.clock).toEqual(0); expect(q.cone).toEqual(2); expect(q.magnitude).toEqual(1); }); it("Normalizing with this as result parameter modifies instance and sets magnitude to 1.0", function() { const v = new import__337.Spherical(0, 2, 3); const q = import__337.Spherical.normalize(v, v); expect(q).toBe(v); expect(q.clock).toEqual(0); expect(q.cone).toEqual(2); expect(q.magnitude).toEqual(1); }); it("equalsEpsilon returns true for expected values.", function() { expect(new import__337.Spherical(1, 2, 1)).toEqualEpsilon(new NotSpherical(1, 2, 1), 0); expect(new import__337.Spherical(1, 2, 1)).toEqualEpsilon(new NotSpherical(1, 2, 2), 1); }); it("equalsEpsilon returns false for expected values.", function() { expect(new import__337.Spherical(1, 2, 1)).not.toEqualEpsilon( new NotSpherical(1, 2, 3), 1 ); }); it("toString returns the expected format.", function() { const v = new import__337.Spherical(1, 2, 3); expect(v.toString()).toEqual("(1, 2, 3)"); }); }); // packages/engine/Specs/Core/SplineSpec.js var import__339 = __toESM(require_Cesium(), 1); describe("Core/Spline", function() { it("contructor throws", function() { expect(function() { return new import__339.Spline(); }).toThrowDeveloperError(); }); it("wraps time that is out-of-bounds", function() { const spline = import__339.HermiteSpline.createNaturalCubic({ points: [import__339.Cartesian3.ZERO, import__339.Cartesian3.UNIT_X, import__339.Cartesian3.UNIT_Y], times: [0, 1, 2] }); expect(spline.wrapTime(-0.5)).toEqual(1.5); expect(spline.wrapTime(2.5)).toEqual(0.5); }); it("clamps time that is out-of-bounds", function() { const spline = import__339.HermiteSpline.createNaturalCubic({ points: [import__339.Cartesian3.ZERO, import__339.Cartesian3.UNIT_X, import__339.Cartesian3.UNIT_Y], times: [0, 1, 2] }); expect(spline.clampTime(-0.5)).toEqual(0); expect(spline.clampTime(2.5)).toEqual(2); }); it("wrapTime throws without a time", function() { const spline = import__339.HermiteSpline.createNaturalCubic({ points: [import__339.Cartesian3.ZERO, import__339.Cartesian3.UNIT_X, import__339.Cartesian3.UNIT_Y], times: [0, 1, 2] }); expect(function() { spline.wrapTime(); }).toThrowDeveloperError(); }); it("clampTime throws without a time", function() { const spline = import__339.HermiteSpline.createNaturalCubic({ points: [import__339.Cartesian3.ZERO, import__339.Cartesian3.UNIT_X, import__339.Cartesian3.UNIT_Y], times: [0, 1, 2] }); expect(function() { spline.clampTime(); }).toThrowDeveloperError(); }); it("findTimeInterval throws without a time", function() { const spline = import__339.HermiteSpline.createNaturalCubic({ points: [import__339.Cartesian3.ZERO, import__339.Cartesian3.UNIT_X, import__339.Cartesian3.UNIT_Y], times: [0, 1, 2] }); expect(function() { spline.findTimeInterval(); }).toThrowDeveloperError(); }); it("findTimeInterval throws when time is out of range", function() { const spline = import__339.HermiteSpline.createNaturalCubic({ points: [import__339.Cartesian3.ZERO, import__339.Cartesian3.UNIT_X, import__339.Cartesian3.UNIT_Y], times: [0, 1, 2] }); expect(function() { spline.findTimeInterval(4); }).toThrowDeveloperError(); }); it("findTimeInterval", function() { const spline = import__339.HermiteSpline.createNaturalCubic({ points: [ import__339.Cartesian3.ZERO, import__339.Cartesian3.UNIT_X, import__339.Cartesian3.UNIT_Y, import__339.Cartesian3.UNIT_Z ], times: [0, 1, 2, 4] }); const times = spline.times; expect(spline.findTimeInterval(times[0])).toEqual(0); expect(spline.findTimeInterval(times[1])).toEqual(1); expect(spline.findTimeInterval(times[0], 1)).toEqual(0); expect(spline.findTimeInterval(times[times.length - 2], 0)).toEqual( times.length - 2 ); expect(spline.findTimeInterval(times[0], times.length - 1)).toEqual(0); }); it("getPointType throws for invalid point type", function() { expect(function() { import__339.Spline.getPointType({}); }).toThrowDeveloperError(); }); it("getPointType", function() { expect(import__339.Spline.getPointType(1)).toEqual(Number); expect(import__339.Spline.getPointType(new import__339.Cartesian3())).not.toThrowDeveloperError(); expect(import__339.Spline.getPointType(new import__339.Quaternion())).not.toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/SteppedSplineSpec.js var import__340 = __toESM(require_Cesium(), 1); describe("Core/SteppedSpline", function() { let times; let cartesianPoints; let numberPoints; let quaternionPoints; beforeEach(function() { times = [0, 1, 2, 3]; cartesianPoints = [ new import__340.Cartesian3(-1, -1, 0), new import__340.Cartesian3(-0.5, -0.125, 0), new import__340.Cartesian3(0.5, 0.125, 0), new import__340.Cartesian3(1, 1, 0) ]; numberPoints = [10, -5, 8, 3]; quaternionPoints = [ new import__340.Quaternion(0, 0, 0, 0), new import__340.Quaternion(0.707, 0, 0.707, 0), new import__340.Quaternion(0.5, 0.5, 0.5, 0.5), new import__340.Quaternion(0, 0, 0, 1) ]; }); it("constructor throws without times or points", function() { expect(function() { return new import__340.SteppedSpline(); }).toThrowDeveloperError(); }); it("constructor throws when control points length is less than 2", function() { expect(function() { return new import__340.SteppedSpline({ points: [import__340.Cartesian3.ZERO], times: [0] }); }).toThrowDeveloperError(); }); it("constructor throws when times.length is not equal to points.length", function() { expect(function() { return new import__340.SteppedSpline({ points: numberPoints, times: [0, 1] }); }).toThrowDeveloperError(); }); it("evaluate throws without time", function() { const spline = new import__340.SteppedSpline({ points: numberPoints, times }); expect(function() { spline.evaluate(); }).toThrowDeveloperError(); }); it("evaluate throws when time is out of range", function() { const spline = new import__340.SteppedSpline({ points: numberPoints, times }); expect(function() { spline.evaluate(times[0] - 1); }).toThrowDeveloperError(); }); it("evaluate returns number value", function() { const spline = new import__340.SteppedSpline({ points: numberPoints, times }); expect(spline.evaluate(times[0])).toEqual(numberPoints[0]); expect(spline.evaluate(times[1])).toEqual(numberPoints[1]); const time2 = (times[0] + times[1]) / 2; expect(spline.evaluate(time2)).toEqual(numberPoints[0]); }); it("evaluate returns cartesian3 value", function() { const spline = new import__340.SteppedSpline({ points: cartesianPoints, times }); let returnedValue = spline.evaluate(times[0]); expect(returnedValue).toEqual(cartesianPoints[0]); returnedValue = spline.evaluate(times[1]); expect(returnedValue).toEqual(cartesianPoints[1]); const time2 = (times[0] + times[1]) / 2; returnedValue = spline.evaluate(time2); expect(returnedValue).toEqual(cartesianPoints[0]); }); it("evaluate returns cartesian3 value with result parameter", function() { const spline = new import__340.SteppedSpline({ points: cartesianPoints, times }); const result = new import__340.Cartesian3(); const time2 = (times[1] + times[2]) / 2; const returnedValue = spline.evaluate(time2, result); expect(returnedValue).toBe(result); expect(returnedValue).toEqual(cartesianPoints[1]); }); it("evaluate returns quaternion value", function() { const spline = new import__340.SteppedSpline({ points: quaternionPoints, times }); let returnedValue = spline.evaluate(times[0]); expect(returnedValue).toEqual(quaternionPoints[0]); returnedValue = spline.evaluate(times[1]); expect(returnedValue).toEqual(quaternionPoints[1]); const time2 = (times[0] + times[1]) / 2; returnedValue = spline.evaluate(time2); expect(returnedValue).toEqual(quaternionPoints[0]); }); it("evaluate returns quaternion value with result parameter", function() { const spline = new import__340.SteppedSpline({ points: quaternionPoints, times }); const result = new import__340.Quaternion(); const time2 = (times[1] + times[2]) / 2; const returnedValue = spline.evaluate(time2, result); expect(returnedValue).toBe(result); expect(returnedValue).toEqual(quaternionPoints[1]); }); }); // packages/engine/Specs/Core/StereographicSpec.js var import__341 = __toESM(require_Cesium(), 1); describe("Core/Stereographic", function() { it("construct with default values", function() { const stereographic = new import__341.Stereographic(); expect(stereographic.x).toEqual(0); expect(stereographic.y).toEqual(0); expect(stereographic.tangentPlane).toEqual( import__341.Stereographic.NORTH_POLE_TANGENT_PLANE ); }); it("construct with values", function() { const stereographic = new import__341.Stereographic( new import__341.Cartesian2(1, 2), import__341.Stereographic.SOUTH_POLE_TANGENT_PLANE ); expect(stereographic.x).toEqual(1); expect(stereographic.y).toEqual(2); expect(stereographic.tangentPlane).toEqual( import__341.Stereographic.SOUTH_POLE_TANGENT_PLANE ); }); it("fromCartesian constructs a Stereographic in the northern hemisphere", function() { const stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(30, 60) ); expect(stereographic.x).toEqualEpsilon(0.1347555369, import__341.Math.EPSILON7); expect(stereographic.y).toEqualEpsilon(-0.2334034365, import__341.Math.EPSILON7); expect(stereographic.tangentPlane).toEqual( import__341.Stereographic.NORTH_POLE_TANGENT_PLANE ); }); it("fromCartesian constructs a Stereographic at 0,0", function() { const stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(0, 0) ); expect(stereographic.x).toEqualEpsilon(0, import__341.Math.EPSILON7); expect(stereographic.y).toEqualEpsilon(-1, import__341.Math.EPSILON7); expect(stereographic.tangentPlane).toEqual( import__341.Stereographic.NORTH_POLE_TANGENT_PLANE ); }); it("fromCartesian constructs a Stereographic in the southern hemisphere", function() { const stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(30, -60) ); expect(stereographic.x).toEqualEpsilon(0.1347555369, import__341.Math.EPSILON7); expect(stereographic.y).toEqualEpsilon(-0.2334034365, import__341.Math.EPSILON7); expect(stereographic.tangentPlane).toEqual( import__341.Stereographic.SOUTH_POLE_TANGENT_PLANE ); }); it("can get longitude from a Stereographic in the northern hemisphere", function() { let stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(30, 60) ); expect(stereographic.longitude).toEqualEpsilon( import__341.Math.toRadians(30), import__341.Math.EPSILON7 ); stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(60, 30) ); expect(stereographic.longitude).toEqualEpsilon( import__341.Math.toRadians(60), import__341.Math.EPSILON7 ); stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(-60, 30) ); expect(stereographic.longitude).toEqualEpsilon( import__341.Math.toRadians(-60), import__341.Math.EPSILON7 ); stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(-135, 60) ); expect(stereographic.longitude).toEqualEpsilon( import__341.Math.toRadians(-135), import__341.Math.EPSILON7 ); stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(135, 60) ); expect(stereographic.longitude).toEqualEpsilon( import__341.Math.toRadians(135), import__341.Math.EPSILON7 ); }); it("can get longitude from a Stereographic in the southern hemisphere", function() { let stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(30, -60) ); expect(stereographic.longitude).toEqualEpsilon( import__341.Math.toRadians(30), import__341.Math.EPSILON7 ); stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(60, -30) ); expect(stereographic.longitude).toEqualEpsilon( import__341.Math.toRadians(60), import__341.Math.EPSILON7 ); stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(-60, -30) ); expect(stereographic.longitude).toEqualEpsilon( import__341.Math.toRadians(-60), import__341.Math.EPSILON7 ); stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(-135, -60) ); expect(stereographic.longitude).toEqualEpsilon( import__341.Math.toRadians(-135), import__341.Math.EPSILON7 ); stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(135, -60) ); expect(stereographic.longitude).toEqualEpsilon( import__341.Math.toRadians(135), import__341.Math.EPSILON7 ); }); it("can get conformal latitidude from a Stereographic in the northern hemisphere", function() { let stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(30, 60) ); expect(stereographic.conformalLatitude).toEqualEpsilon( 1.04428418, import__341.Math.EPSILON7 ); stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(60, 30) ); expect(stereographic.conformalLatitude).toEqualEpsilon( 0.52069517, import__341.Math.EPSILON7 ); }); it("can get conformal latitidude from a Stereographic in the southern hemisphere", function() { let stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(30, -60) ); expect(stereographic.conformalLatitude).toEqualEpsilon( -1.04428418, import__341.Math.EPSILON7 ); stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(60, -30) ); expect(stereographic.conformalLatitude).toEqualEpsilon( -0.52069517, import__341.Math.EPSILON7 ); }); it("can get latitidude from a Stereographic in the northern hemisphere", function() { let stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(30, 60) ); expect(stereographic.getLatitude()).toEqualEpsilon( import__341.Math.toRadians(60), import__341.Math.EPSILON7 ); stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(60, 30) ); expect(stereographic.getLatitude()).toEqualEpsilon( import__341.Math.toRadians(30), import__341.Math.EPSILON7 ); }); it("can get latitidude from a Stereographic in the southern hemisphere", function() { let stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(30, -60) ); expect(stereographic.getLatitude()).toEqualEpsilon( import__341.Math.toRadians(-60), import__341.Math.EPSILON7 ); stereographic = new import__341.Stereographic.fromCartesian( import__341.Cartesian3.fromDegrees(60, -30) ); expect(stereographic.getLatitude()).toEqualEpsilon( import__341.Math.toRadians(-30), import__341.Math.EPSILON7 ); }); it("fromCartesianArray creates a Stereographic array", function() { const stereographics = import__341.Stereographic.fromCartesianArray([ import__341.Cartesian3.fromDegrees(30, 60), import__341.Cartesian3.fromDegrees(30, -60) ]); expect(stereographics.length).toBe(2); expect(stereographics[0].x).toEqualEpsilon( 0.1347555369, import__341.Math.EPSILON7 ); expect(stereographics[0].y).toEqualEpsilon( -0.2334034365, import__341.Math.EPSILON7 ); expect(stereographics[0].tangentPlane).toEqual( import__341.Stereographic.NORTH_POLE_TANGENT_PLANE ); expect(stereographics[1].x).toEqualEpsilon( 0.1347555369, import__341.Math.EPSILON7 ); expect(stereographics[1].y).toEqualEpsilon( -0.2334034365, import__341.Math.EPSILON7 ); expect(stereographics[1].tangentPlane).toEqual( import__341.Stereographic.SOUTH_POLE_TANGENT_PLANE ); }); it("clone works with a result parameter", function() { const stereographic = new import__341.Stereographic( new import__341.Cartesian2(1, 2), import__341.Stereographic.SOUTH_POLE_TANGENT_PLANE ); const result = new import__341.Stereographic(); const returnedResult = import__341.Stereographic.clone(stereographic, result); expect(stereographic).not.toBe(result); expect(result).toBe(returnedResult); expect(stereographic.position).toEqual(result.position); }); it("clone works without result parmater", function() { const stereographic = new import__341.Stereographic( new import__341.Cartesian2(1, 2), import__341.Stereographic.SOUTH_POLE_TANGENT_PLANE ); const result = import__341.Stereographic.clone(stereographic); expect(stereographic).not.toBe(result); expect(stereographic.position).toEqual(result.position); }); it("clone returns undefined with no parameter", function() { expect(import__341.Stereographic.clone()).toBeUndefined(); }); }); // packages/engine/Specs/Core/TaskProcessorSpec.js var import__342 = __toESM(require_Cesium(), 1); // Specs/absolutize.js function absolutize(url) { const a = document.createElement("a"); a.href = url; a.href = a.href; return a.href; } var absolutize_default = absolutize; // packages/engine/Specs/Core/TaskProcessorSpec.js describe("Core/TaskProcessor", function() { let taskProcessor; afterEach(function() { import__342.TaskProcessor._workerModulePrefix = import__342.TaskProcessor._defaultWorkerModulePrefix; if (taskProcessor && !taskProcessor.isDestroyed()) { taskProcessor = taskProcessor.destroy(); } }); it("throws runtime error if browser is not supported", async function() { spyOn(import__342.FeatureDetection, "supportsEsmWebWorkers").and.returnValue(false); taskProcessor = new import__342.TaskProcessor( absolutize_default("../Specs/Build/TestWorkers/returnParameters.js") ); expect(() => taskProcessor.scheduleTask()).toThrowError(import__342.RuntimeError); }); it("works with a simple worker", async function() { taskProcessor = new import__342.TaskProcessor( absolutize_default("../Build/Specs/TestWorkers/returnParameters.js") ); const parameters = { prop: "blah", obj: { val: true } }; await expectAsync(taskProcessor.scheduleTask(parameters)).toBeResolvedTo( parameters ); }); it("works with a simple worker defined as relative to TaskProcessor._workerModulePrefix", async function() { window.CESIUM_WORKERS = void 0; import__342.TaskProcessor._workerModulePrefix = absolutize_default( "../Build/Specs/TestWorkers/" ); taskProcessor = new import__342.TaskProcessor("returnParameters.js"); const parameters = { prop: "blah", obj: { val: true } }; await expectAsync(taskProcessor.scheduleTask(parameters)).toBeResolvedTo( parameters ); }); it("can be destroyed", function() { taskProcessor = new import__342.TaskProcessor( absolutize_default("../Specs/Build/TestWorkers/returnParameters.js") ); expect(taskProcessor.isDestroyed()).toEqual(false); taskProcessor.destroy(); expect(taskProcessor.isDestroyed()).toEqual(true); }); it("can transfer array buffer", async function() { taskProcessor = new import__342.TaskProcessor( absolutize_default("../Build/Specs/TestWorkers/returnByteLength.js") ); const byteLength = 100; const parameters = new ArrayBuffer(byteLength); expect(parameters.byteLength).toEqual(byteLength); const canTransferArrayBuffer = await import__342.TaskProcessor._canTransferArrayBuffer; const result = await taskProcessor.scheduleTask(parameters, [parameters]); if (canTransferArrayBuffer) { expect(parameters.byteLength).toEqual(0); } expect(result).toEqual(byteLength); }); it("can transfer array buffer back from worker", async function() { taskProcessor = new import__342.TaskProcessor( absolutize_default("../Build/Specs/TestWorkers/transferArrayBuffer.js") ); const byteLength = 100; const parameters = { byteLength }; const result = await taskProcessor.scheduleTask(parameters); expect(result.byteLength).toEqual(100); }); it("rejects promise if worker throws", async function() { taskProcessor = new import__342.TaskProcessor( absolutize_default("../Build/Specs/TestWorkers/throwError.js") ); const message = "foo"; const parameters = { message }; await expectAsync( taskProcessor.scheduleTask(parameters) ).toBeRejectedWithError(Error, message); }); it("rejects promise if worker returns a non-clonable result", async function() { taskProcessor = new import__342.TaskProcessor( absolutize_default("../Build/Specs/TestWorkers/returnNonCloneable.js") ); const message = "foo"; const parameters = { message }; await expectAsync(taskProcessor.scheduleTask(parameters)).toBeRejectedWith( jasmine.stringContaining("postMessage failed") ); }); it("successful task raises the taskCompletedEvent", async function() { taskProcessor = new import__342.TaskProcessor( absolutize_default("../Build/Specs/TestWorkers/returnParameters.js") ); const parameters = { prop: "blah", obj: { val: true } }; let eventRaised = false; const removeListenerCallback = import__342.TaskProcessor.taskCompletedEvent.addEventListener( function() { eventRaised = true; } ); await expectAsync(taskProcessor.scheduleTask(parameters)).toBeResolved(); expect(eventRaised).toBe(true); removeListenerCallback(); }); it("unsuccessful task raises the taskCompletedEvent with error", async function() { taskProcessor = new import__342.TaskProcessor( absolutize_default("../Build/Specs/TestWorkers/returnNonCloneable.js") ); const message = "foo"; const parameters = { message }; let eventRaised = false; const removeListenerCallback = import__342.TaskProcessor.taskCompletedEvent.addEventListener( function(error) { eventRaised = true; expect(error).toBeDefined(); } ); await expectAsync(taskProcessor.scheduleTask(parameters)).toBeRejected(); expect(eventRaised).toBe(true); removeListenerCallback(); }); it("can load and compile web assembly module", async function() { const binaryUrl = absolutize_default("../Specs/TestWorkers/TestWasm/testWasm.wasm"); taskProcessor = new import__342.TaskProcessor( absolutize_default("../Build/Specs/TestWorkers/returnWasmConfig.js", 5) ); const result = await taskProcessor.initWebAssemblyModule({ wasmBinaryFile: binaryUrl, fallbackModulePath: "TestWasm/testWasmFallback" }); expect(result).toBeDefined(); if (import__342.FeatureDetection.supportsWebAssembly()) { expect(result.wasmBinary).toBeDefined(); expect(result.wasmBinaryFile).toEqual(binaryUrl); } }); it("uses a backup module if web assembly is not supported", async function() { const binaryUrl = absolutize_default("../Specs/TestWorkers/TestWasm/testWasm.wasm"); taskProcessor = new import__342.TaskProcessor( absolutize_default("../Build/Specs/TestWorkers/returnWasmConfig.js", 5) ); spyOn(import__342.FeatureDetection, "supportsWebAssembly").and.returnValue(false); const result = await taskProcessor.initWebAssemblyModule({ wasmBinaryFile: binaryUrl, fallbackModulePath: "TestWasm/testWasmFallback" }); expect(result).toBeDefined(); expect(result.modulePath).toMatch(/TestWasm\/testWasmFallback/); expect(result.wasmBinary).not.toBeDefined(); }); it("throws runtime error if web assembly is not supported and no backup is provided", async function() { const binaryUrl = absolutize_default("../Specs/TestWorkers/TestWasm/testWasm.wasm"); taskProcessor = new import__342.TaskProcessor( absolutize_default("../Build/Specs/TestWorkers/returnWasmConfig.js", 5) ); spyOn(import__342.FeatureDetection, "supportsWebAssembly").and.returnValue(false); await expectAsync( taskProcessor.initWebAssemblyModule({ wasmBinaryFile: binaryUrl }) ).toBeRejectedWithError(import__342.RuntimeError); }); }); // packages/engine/Specs/Core/TerrainEncodingSpec.js var import__343 = __toESM(require_Cesium(), 1); var import__344 = __toESM(require_Cesium(), 1); describe("Core/TerrainEncoding", function() { let center; let maximum; let minimum; let aabox; let fromENU; let minimumHeight; let maximumHeight; beforeEach(function() { center = import__343.Cartesian3.fromDegrees(0, 0); maximum = new import__343.Cartesian3(600, 600, 600); minimum = import__343.Cartesian3.negate(maximum, new import__343.Cartesian3()); aabox = new import__343.AxisAlignedBoundingBox(minimum, maximum, center); maximumHeight = 600; minimumHeight = maximumHeight; fromENU = import__343.Transforms.eastNorthUpToFixedFrame(center); }); it("default constructs", function() { const encoding = new import__343.TerrainEncoding(); expect(encoding.quantization).toBe(import__343.TerrainQuantization.NONE); expect(encoding.minimumHeight).not.toBeDefined(); expect(encoding.maximumHeight).not.toBeDefined(); expect(encoding.center).not.toBeDefined(); expect(encoding.toScaledENU).not.toBeDefined(); expect(encoding.fromScaledENU).not.toBeDefined(); expect(encoding.matrix).not.toBeDefined(); expect(encoding.hasVertexNormals).not.toBeDefined(); }); it("constructs without quantization", function() { const maximum2 = new import__343.Cartesian3(1e6, 1e6, 1e6); const minimum2 = import__343.Cartesian3.negate(maximum2, new import__343.Cartesian3()); const aabox2 = new import__343.AxisAlignedBoundingBox(minimum2, maximum2, center); const maximumHeight2 = 1e6; const minimumHeight2 = maximumHeight2; const hasVertexNormals = false; const encoding = new import__343.TerrainEncoding( aabox2.center, aabox2, minimumHeight2, maximumHeight2, fromENU, hasVertexNormals ); expect(encoding.quantization).toEqual(import__343.TerrainQuantization.NONE); expect(encoding.minimumHeight).toEqual(minimumHeight2); expect(encoding.maximumHeight).toEqual(maximumHeight2); expect(encoding.center).toEqual(center); expect(encoding.toScaledENU).toBeDefined(); expect(encoding.toScaledENU).toBeInstanceOf(import__343.Matrix4); expect(encoding.fromScaledENU).toBeDefined(); expect(encoding.fromScaledENU).toBeInstanceOf(import__343.Matrix4); expect(encoding.matrix).toBeDefined(); expect(encoding.matrix).toBeInstanceOf(import__343.Matrix4); expect(encoding.hasVertexNormals).toEqual(hasVertexNormals); }); it("constructs with quantization", function() { const maximum2 = new import__343.Cartesian3(100, 100, 100); const minimum2 = import__343.Cartesian3.negate(maximum2, new import__343.Cartesian3()); const aabox2 = new import__343.AxisAlignedBoundingBox(minimum2, maximum2, center); const minimumHeight2 = -100; const maximumHeight2 = 100; const hasVertexNormals = false; const encoding = new import__343.TerrainEncoding( aabox2.center, aabox2, minimumHeight2, maximumHeight2, fromENU, hasVertexNormals ); expect(encoding.quantization).toEqual(import__343.TerrainQuantization.BITS12); expect(encoding.minimumHeight).toEqual(minimumHeight2); expect(encoding.maximumHeight).toEqual(maximumHeight2); expect(encoding.center).toEqual(center); expect(encoding.toScaledENU).toBeDefined(); expect(encoding.toScaledENU).toBeInstanceOf(import__343.Matrix4); expect(encoding.fromScaledENU).toBeDefined(); expect(encoding.fromScaledENU).toBeInstanceOf(import__343.Matrix4); expect(encoding.matrix).toBeDefined(); expect(encoding.matrix).toBeInstanceOf(import__343.Matrix4); expect(encoding.hasVertexNormals).toEqual(hasVertexNormals); }); it("encodes without quantization or normals", function() { const maximum2 = new import__343.Cartesian3(6e3, 6e3, 6e3); const minimum2 = import__343.Cartesian3.negate(maximum2, new import__343.Cartesian3()); const aabox2 = new import__343.AxisAlignedBoundingBox(minimum2, maximum2, center); const maximumHeight2 = 6e3; const minimumHeight2 = maximumHeight2; const hasVertexNormals = false; const encoding = new import__343.TerrainEncoding( aabox2.center, aabox2, minimumHeight2, maximumHeight2, fromENU, hasVertexNormals ); const position = new import__343.Cartesian3(1e3, 1e3, 1e3); import__343.Matrix4.multiplyByPoint(fromENU, position, position); const buffer = []; encoding.encode(buffer, 0, position, import__343.Cartesian2.ZERO, 100); expect(encoding.stride).toEqual(6); expect(buffer.length).toEqual(encoding.stride); expect(encoding.decodePosition(buffer, 0)).toEqual(position); }); it("encodes without quantization and with normals", function() { const maximum2 = new import__343.Cartesian3(6e3, 6e3, 6e3); const minimum2 = import__343.Cartesian3.negate(maximum2, new import__343.Cartesian3()); const aabox2 = new import__343.AxisAlignedBoundingBox(minimum2, maximum2, center); const maximumHeight2 = 6e3; const minimumHeight2 = maximumHeight2; const hasVertexNormals = true; const encoding = new import__343.TerrainEncoding( aabox2.center, aabox2, minimumHeight2, maximumHeight2, fromENU, hasVertexNormals ); const position = new import__343.Cartesian3(1e3, 1e3, 1e3); import__343.Matrix4.multiplyByPoint(fromENU, position, position); const normal = import__343.Cartesian3.normalize(position, new import__343.Cartesian3()); const buffer = []; encoding.encode(buffer, 0, position, import__343.Cartesian2.ZERO, 100, normal); expect(encoding.stride).toEqual(7); expect(buffer.length).toEqual(encoding.stride); expect(encoding.decodePosition(buffer, 0)).toEqual(position); }); it("encodes position with quantization and without normals", function() { const hasVertexNormals = false; const encoding = new import__343.TerrainEncoding( aabox.center, aabox, minimumHeight, maximumHeight, fromENU, hasVertexNormals ); const position = new import__343.Cartesian3(100, 100, 100); import__343.Matrix4.multiplyByPoint(fromENU, position, position); const buffer = []; encoding.encode(buffer, 0, position, import__343.Cartesian2.ZERO, 100); expect(encoding.stride).toEqual(3); expect(buffer.length).toEqual(encoding.stride); expect(encoding.decodePosition(buffer, 0)).toEqualEpsilon(position, 1); }); it("encodes position with quantization and normals", function() { const hasVertexNormals = true; const encoding = new import__343.TerrainEncoding( aabox.center, aabox, minimumHeight, maximumHeight, fromENU, hasVertexNormals ); const position = new import__343.Cartesian3(100, 100, 100); import__343.Matrix4.multiplyByPoint(fromENU, position, position); const normal = import__343.Cartesian3.normalize(position, new import__343.Cartesian3()); const buffer = []; encoding.encode(buffer, 0, position, import__343.Cartesian2.ZERO, 100, normal); expect(encoding.stride).toEqual(4); expect(buffer.length).toEqual(encoding.stride); expect(encoding.decodePosition(buffer, 0)).toEqualEpsilon(position, 1); }); it("encodes position without quantization and with exaggeration", function() { const hasVertexNormals = false; const hasWebMercatorT = false; const hasGeodeticSurfaceNormals = true; const height = 1e6; const position = new import__343.Cartesian3(height, 0, 0); const geodeticSurfaceNormal = new import__343.Cartesian3(1, 0, 0); const exaggeration = 2; const exaggerationRelativeHeight = 10; const exaggeratedHeight = import__343.VerticalExaggeration.getHeight( height, exaggeration, exaggerationRelativeHeight ); const exaggeratedPosition = new import__343.Cartesian3(exaggeratedHeight, 0, 0); const maximumHeight2 = height; const minimumHeight2 = -height; const maximum2 = new import__343.Cartesian3(height, height, height); const minimum2 = import__343.Cartesian3.negate(maximum2, new import__343.Cartesian3()); const aabox2 = new import__343.AxisAlignedBoundingBox(minimum2, maximum2, import__343.Cartesian3.ZERO); const encoding = new import__343.TerrainEncoding( aabox2.center, aabox2, minimumHeight2, maximumHeight2, import__343.Matrix4.IDENTITY, hasVertexNormals, hasWebMercatorT, hasGeodeticSurfaceNormals, exaggeration, exaggerationRelativeHeight ); const buffer = []; encoding.encode( buffer, 0, position, import__343.Cartesian2.ZERO, height, void 0, void 0, geodeticSurfaceNormal ); expect(encoding.stride).toEqual(9); expect(buffer.length).toEqual(encoding.stride); expect(encoding.getExaggeratedPosition(buffer, 0)).toEqualEpsilon( exaggeratedPosition, import__344.Math.EPSILON5 ); expect( encoding.decodeGeodeticSurfaceNormal(buffer, 0, new import__343.Cartesian3()) ).toEqualEpsilon(geodeticSurfaceNormal, import__344.Math.EPSILON5); }); it("encodes texture coordinates with quantization and without normals", function() { const hasVertexNormals = false; const encoding = new import__343.TerrainEncoding( aabox.center, aabox, minimumHeight, maximumHeight, fromENU, hasVertexNormals ); const texCoords = new import__343.Cartesian2(0.25, 0.75); const buffer = []; encoding.encode(buffer, 0, import__343.Cartesian3.ZERO, texCoords, 100); expect(encoding.stride).toEqual(3); expect(buffer.length).toEqual(encoding.stride); expect(encoding.decodeTextureCoordinates(buffer, 0)).toEqualEpsilon( texCoords, 1 / 4095 ); }); it("encodes textureCoordinates with quantization and normals", function() { const hasVertexNormals = true; const encoding = new import__343.TerrainEncoding( aabox.center, aabox, minimumHeight, maximumHeight, fromENU, hasVertexNormals ); const texCoords = new import__343.Cartesian2(0.75, 0.25); const buffer = []; encoding.encode( buffer, 0, import__343.Cartesian3.ZERO, texCoords, 100, import__343.Cartesian3.UNIT_X ); expect(encoding.stride).toEqual(4); expect(buffer.length).toEqual(encoding.stride); expect(encoding.decodeTextureCoordinates(buffer, 0)).toEqualEpsilon( texCoords, 1 / 4095 ); }); it("encodes height with quantization and without normals", function() { const hasVertexNormals = false; minimumHeight = 0; maximumHeight = 200; const encoding = new import__343.TerrainEncoding( aabox.center, aabox, minimumHeight, maximumHeight, fromENU, hasVertexNormals ); const buffer = []; const height = (maximumHeight + minimumHeight) * 0.5; encoding.encode(buffer, 0, center, import__343.Cartesian2.ZERO, height); expect(encoding.stride).toEqual(3); expect(buffer.length).toEqual(encoding.stride); expect(encoding.decodeHeight(buffer, 0)).toEqualEpsilon( height, 200 / 4095 ); }); it("encodes height with quantization and normals", function() { const hasVertexNormals = true; minimumHeight = 0; maximumHeight = 200; const encoding = new import__343.TerrainEncoding( aabox.center, aabox, minimumHeight, maximumHeight, fromENU, hasVertexNormals ); const buffer = []; const height = (maximumHeight + minimumHeight) * 0.5; encoding.encode( buffer, 0, center, import__343.Cartesian2.ZERO, height, import__343.Cartesian3.UNIT_X ); expect(encoding.stride).toEqual(4); expect(buffer.length).toEqual(encoding.stride); expect(encoding.decodeHeight(buffer, 0)).toEqualEpsilon( height, 200 / 4095 ); }); it("gets oct-encoded normal", function() { const hasVertexNormals = true; const encoding = new import__343.TerrainEncoding( aabox.center, aabox, minimumHeight, maximumHeight, fromENU, hasVertexNormals ); const normal = new import__343.Cartesian3(1, 1, 1); import__343.Cartesian3.normalize(normal, normal); const octNormal = import__343.AttributeCompression.octEncode(normal, new import__343.Cartesian2()); const buffer = []; encoding.encode( buffer, 0, center, import__343.Cartesian2.ZERO, minimumHeight, octNormal ); expect(encoding.stride).toEqual(4); expect(buffer.length).toEqual(encoding.stride); expect(encoding.getOctEncodedNormal(buffer, 0)).toEqual(octNormal); }); it("adds geodetic surface normals", function() { const hasVertexNormals = false; const encoding = new import__343.TerrainEncoding( aabox.center, aabox, minimumHeight, maximumHeight, fromENU, hasVertexNormals ); const oldBuffer = []; encoding.encode(oldBuffer, 0, center, import__343.Cartesian2.ZERO, minimumHeight); const oldStride = encoding.stride; const newBuffer = []; const ellipsoid = import__343.Ellipsoid.UNIT_SPHERE; encoding.addGeodeticSurfaceNormals(oldBuffer, newBuffer, ellipsoid); const newStride = encoding.stride; const strideDifference = newStride - oldStride; expect(strideDifference).toEqual(3); expect(oldBuffer.length).toEqual(oldStride); expect(newBuffer.length).toEqual(newStride); }); it("removes geodetic surface normals", function() { const hasVertexNormals = false; const hasWebMarcatorT = false; const hasGeodeticSurfaceNormals = true; const encoding = new import__343.TerrainEncoding( aabox.center, aabox, minimumHeight, maximumHeight, fromENU, hasVertexNormals, hasWebMarcatorT, hasGeodeticSurfaceNormals ); const geodeticSurfaceNormal = new import__343.Cartesian3(1, 0, 0); const oldBuffer = []; encoding.encode( oldBuffer, 0, center, import__343.Cartesian2.ZERO, minimumHeight, void 0, void 0, geodeticSurfaceNormal ); const oldStride = encoding.stride; const newBuffer = []; encoding.removeGeodeticSurfaceNormals(oldBuffer, newBuffer); const newStride = encoding.stride; const strideDifference = newStride - oldStride; expect(strideDifference).toEqual(-3); expect(oldBuffer.length).toEqual(oldStride); expect(newBuffer.length).toEqual(newStride); }); it("gets attributes", function() { const center2 = import__343.Cartesian3.fromDegrees(0, 0); const maximum2 = new import__343.Cartesian3(1e6, 1e6, 1e6); const minimum2 = import__343.Cartesian3.negate(maximum2, new import__343.Cartesian3()); const aabox2 = new import__343.AxisAlignedBoundingBox(minimum2, maximum2, center2); const maximumHeight2 = 1e6; const minimumHeight2 = maximumHeight2; const fromENU2 = import__343.Transforms.eastNorthUpToFixedFrame(center2); const hasVertexNormals = false; const encoding = new import__343.TerrainEncoding( aabox2.center, aabox2, minimumHeight2, maximumHeight2, fromENU2, hasVertexNormals ); const buffer = []; const attributes = encoding.getAttributes(buffer); expect(attributes).toBeDefined(); expect(attributes.length).toEqual(2); }); it("gets attribute locations", function() { const center2 = import__343.Cartesian3.fromDegrees(0, 0); const maximum2 = new import__343.Cartesian3(1e6, 1e6, 1e6); const minimum2 = import__343.Cartesian3.negate(maximum2, new import__343.Cartesian3()); const aabox2 = new import__343.AxisAlignedBoundingBox(minimum2, maximum2, center2); const maximumHeight2 = 1e6; const minimumHeight2 = maximumHeight2; const fromENU2 = import__343.Transforms.eastNorthUpToFixedFrame(center2); const hasVertexNormals = false; const encoding = new import__343.TerrainEncoding( aabox2.center, aabox2, minimumHeight2, maximumHeight2, fromENU2, hasVertexNormals ); const attributeLocations = encoding.getAttributeLocations(); expect(attributeLocations).toBeDefined(); }); it("clones", function() { const center2 = import__343.Cartesian3.fromDegrees(0, 0); const maximum2 = new import__343.Cartesian3(1e6, 1e6, 1e6); const minimum2 = import__343.Cartesian3.negate(maximum2, new import__343.Cartesian3()); const aabox2 = new import__343.AxisAlignedBoundingBox(minimum2, maximum2, center2); const maximumHeight2 = 1e6; const minimumHeight2 = maximumHeight2; const fromENU2 = import__343.Transforms.eastNorthUpToFixedFrame(center2); const hasVertexNormals = false; const encoding = new import__343.TerrainEncoding( aabox2.center, aabox2, minimumHeight2, maximumHeight2, fromENU2, hasVertexNormals ); const cloned = import__343.TerrainEncoding.clone(encoding); expect(cloned.quantization).toEqual(encoding.quantization); expect(cloned.minimumHeight).toEqual(encoding.minimumHeight); expect(cloned.maximumHeight).toEqual(encoding.maximumHeight); expect(cloned.center).toEqual(encoding.center); expect(cloned.toScaledENU).toEqual(encoding.toScaledENU); expect(cloned.fromScaledENU).toEqual(encoding.fromScaledENU); expect(cloned.matrix).toEqual(encoding.matrix); expect(cloned.hasVertexNormals).toEqual(encoding.hasVertexNormals); }); it("clones with result", function() { const center2 = import__343.Cartesian3.fromDegrees(0, 0); const maximum2 = new import__343.Cartesian3(1e6, 1e6, 1e6); const minimum2 = import__343.Cartesian3.negate(maximum2, new import__343.Cartesian3()); const aabox2 = new import__343.AxisAlignedBoundingBox(minimum2, maximum2, center2); const maximumHeight2 = 1e6; const minimumHeight2 = maximumHeight2; const fromENU2 = import__343.Transforms.eastNorthUpToFixedFrame(center2); const hasVertexNormals = false; const encoding = new import__343.TerrainEncoding( aabox2.center, aabox2, minimumHeight2, maximumHeight2, fromENU2, hasVertexNormals ); const result = new import__343.TerrainEncoding(); const cloned = import__343.TerrainEncoding.clone(encoding, result); expect(cloned).toBe(result); expect(cloned.quantization).toEqual(encoding.quantization); expect(cloned.minimumHeight).toEqual(encoding.minimumHeight); expect(cloned.maximumHeight).toEqual(encoding.maximumHeight); expect(cloned.center).toEqual(encoding.center); expect(cloned.toScaledENU).toEqual(encoding.toScaledENU); expect(cloned.fromScaledENU).toEqual(encoding.fromScaledENU); expect(cloned.matrix).toEqual(encoding.matrix); expect(cloned.hasVertexNormals).toEqual(encoding.hasVertexNormals); }); }); // packages/engine/Specs/Core/TileAvailabilitySpec.js var import__345 = __toESM(require_Cesium(), 1); describe("Core/TileAvailability", function() { const webMercator = new import__345.WebMercatorTilingScheme(); const geographic = new import__345.GeographicTilingScheme(); function createAvailability(tilingScheme, maxLevel) { const availability = new import__345.TileAvailability(tilingScheme, 15); availability.addAvailableTileRange( 0, 0, 0, tilingScheme.getNumberOfXTilesAtLevel(), tilingScheme.getNumberOfYTilesAtLevel() ); return availability; } describe("computeMaximumLevelAtPosition", function() { it("returns -1 if position outside the tiling scheme", function() { const availability = createAvailability(webMercator, 15); expect( availability.computeMaximumLevelAtPosition( import__345.Cartographic.fromDegrees(25, 88) ) ).toBe(-1); }); it("returns 0 if there are no rectangles", function() { const availability = createAvailability(geographic, 15); expect( availability.computeMaximumLevelAtPosition( import__345.Cartographic.fromDegrees(25, 88) ) ).toBe(0); }); it("returns the higher level when on a boundary at level 0", function() { let availability = createAvailability(geographic, 15); availability.addAvailableTileRange(0, 0, 0, 0, 0); availability.addAvailableTileRange(1, 1, 0, 1, 0); expect( availability.computeMaximumLevelAtPosition( import__345.Cartographic.fromRadians(0, 0) ) ).toBe(1); availability = createAvailability(geographic, 15); availability.addAvailableTileRange(1, 1, 0, 1, 0); availability.addAvailableTileRange(0, 0, 0, 0, 0); expect( availability.computeMaximumLevelAtPosition( import__345.Cartographic.fromRadians(0, 0) ) ).toBe(1); }); it("returns the higher level when on a boundary at level 1", function() { const availability = createAvailability(geographic, 15); availability.addAvailableTileRange(0, 0, 0, 1, 0); availability.addAvailableTileRange(1, 1, 1, 1, 1); expect( availability.computeMaximumLevelAtPosition( import__345.Cartographic.fromRadians(-Math.PI / 2, 0) ) ).toBe(1); }); }); describe("computeBestAvailableLevelOverRectangle", function() { it("returns 0 if there are no rectangles", function() { const availability = createAvailability(geographic, 15); expect( availability.computeBestAvailableLevelOverRectangle( import__345.Rectangle.fromDegrees(1, 2, 3, 4) ) ).toBe(0); }); it("reports the correct level when entirely inside a worldwide rectangle of that level", function() { const availability = createAvailability(geographic, 15); availability.addAvailableTileRange( 5, 0, 0, geographic.getNumberOfXTilesAtLevel(5) - 1, geographic.getNumberOfYTilesAtLevel(5) - 1 ); availability.addAvailableTileRange(6, 7, 8, 9, 10); expect( availability.computeBestAvailableLevelOverRectangle( import__345.Rectangle.fromDegrees(1, 2, 3, 4) ) ).toBe(5); }); it("reports the correct level when entirely inside a smaller rectangle of that level", function() { const availability = createAvailability(geographic, 15); availability.addAvailableTileRange( 5, 0, 0, geographic.getNumberOfXTilesAtLevel(5) - 1, geographic.getNumberOfYTilesAtLevel(5) - 1 ); availability.addAvailableTileRange(6, 7, 8, 9, 10); const rectangle = geographic.tileXYToRectangle(8, 9, 6); expect( availability.computeBestAvailableLevelOverRectangle(rectangle) ).toBe(6); }); it("reports the correct level when partially overlapping a smaller rectangle", function() { const availability = createAvailability(geographic, 15); availability.addAvailableTileRange( 5, 0, 0, geographic.getNumberOfXTilesAtLevel(5) - 1, geographic.getNumberOfYTilesAtLevel(5) - 1 ); availability.addAvailableTileRange(6, 7, 8, 7, 8); const rectangle = geographic.tileXYToRectangle(7, 8, 6); rectangle.west -= 0.01; rectangle.east += 0.01; rectangle.south -= 0.01; rectangle.north += 0.01; expect( availability.computeBestAvailableLevelOverRectangle(rectangle) ).toBe(5); }); it("works with a rectangle crossing 180 degrees longitude", function() { const availability = createAvailability(geographic, 15); availability.addAvailableTileRange( 5, 0, 0, geographic.getNumberOfXTilesAtLevel(5) - 1, geographic.getNumberOfYTilesAtLevel(5) - 1 ); availability.addAvailableTileRange( 6, 0, 0, 10, geographic.getNumberOfYTilesAtLevel(6) - 1 ); availability.addAvailableTileRange( 6, geographic.getNumberOfXTilesAtLevel(6) - 11, 0, geographic.getNumberOfXTilesAtLevel(6) - 1, geographic.getNumberOfYTilesAtLevel(6) - 1 ); let rectangle = import__345.Rectangle.fromDegrees(179, 45, -179, 50); expect( availability.computeBestAvailableLevelOverRectangle(rectangle) ).toBe(6); rectangle = import__345.Rectangle.fromDegrees(45, 45, -45, 50); expect( availability.computeBestAvailableLevelOverRectangle(rectangle) ).toBe(5); }); it("works when four rectangles combine to cover the area", function() { const availability = createAvailability(geographic, 15); availability.addAvailableTileRange( 5, 0, 0, geographic.getNumberOfXTilesAtLevel(5) - 1, geographic.getNumberOfYTilesAtLevel(5) - 1 ); availability.addAvailableTileRange(6, 0, 2, 1, 3); availability.addAvailableTileRange(6, 2, 0, 3, 1); availability.addAvailableTileRange(6, 0, 0, 1, 1); availability.addAvailableTileRange(6, 2, 2, 3, 3); const rectangle = geographic.tileXYToRectangle(0, 0, 4); expect( availability.computeBestAvailableLevelOverRectangle(rectangle) ).toBe(6); }); }); describe("addAvailableTileRange", function() { function checkNodeRectanglesSorted(node) { if (!(0, import__345.defined)(node)) { return; } const levelRectangles = node.rectangles; for (let i = 0; i < levelRectangles.length; ++i) { for (let j = i; j < levelRectangles.length; ++j) { expect(levelRectangles[i].level <= levelRectangles[j].level).toBe( true ); } } checkNodeRectanglesSorted(node._ne); checkNodeRectanglesSorted(node._se); checkNodeRectanglesSorted(node._nw); checkNodeRectanglesSorted(node._sw); } it("keeps availability ranges sorted by rectangle", function() { let availability = createAvailability(geographic, 15); availability.addAvailableTileRange(0, 0, 0, 1, 0); availability.addAvailableTileRange(1, 0, 0, 3, 1); expect( availability.computeMaximumLevelAtPosition( new import__345.Cartographic(-Math.PI / 2, 0) ) ).toBe(1); availability = createAvailability(geographic, 15); availability.addAvailableTileRange(1, 0, 0, 3, 1); availability.addAvailableTileRange(0, 0, 0, 1, 0); expect( availability.computeMaximumLevelAtPosition( new import__345.Cartographic(-Math.PI / 2, 0) ) ).toBe(1); }); it("ensure the boundary rectangles are sorted properly", function() { const availability = new import__345.TileAvailability(geographic, 6); availability.addAvailableTileRange(0, 0, 0, 1, 0); availability.addAvailableTileRange(1, 0, 0, 2, 0); availability.addAvailableTileRange(2, 0, 0, 4, 0); availability.addAvailableTileRange(3, 0, 0, 8, 0); availability.addAvailableTileRange(0, 0, 0, 1, 0); for (let i = 0; i < availability._rootNodes.length; ++i) { const node = availability._rootNodes[i]; checkNodeRectanglesSorted(node); } }); }); }); // packages/engine/Specs/Core/TimeIntervalCollectionSpec.js var import__346 = __toESM(require_Cesium(), 1); describe("Core/TimeIntervalCollection", function() { function defaultDataCallback(interval, index) { return index; } function iso8601ToJulianDateArray(iso8601Dates) { const julianDates = []; for (let i = 0; i < iso8601Dates.length; ++i) { julianDates[i] = import__346.JulianDate.fromIso8601(iso8601Dates[i]); } return julianDates; } function checkIntervals(intervals, julianDates, isStartIncluded, isStopIncluded, dataCallback2) { dataCallback2 = (0, import__346.defaultValue)(dataCallback2, defaultDataCallback); const length2 = intervals.length; expect(length2).toEqual(julianDates.length - 1); for (let i = 0; i < length2; ++i) { const interval = intervals.get(i); expect(import__346.JulianDate.compare(interval.start, julianDates[i])).toEqual(0); expect(import__346.JulianDate.compare(interval.stop, julianDates[i + 1])).toEqual(0); expect(interval.isStartIncluded).toBe(i === 0 ? isStartIncluded : true); expect(interval.isStopIncluded).toBe( i === length2 - 1 ? isStopIncluded : false ); expect(interval.data).toEqual(dataCallback2(interval, i)); } } function TestObject(value) { this.value = value; } TestObject.equals = function(left, right) { return left.value === right.value; }; TestObject.merge = function(left, right) { return new TestObject(left.value + right.value); }; it("constructing a default interval collection has expected property values.", function() { const intervals = new import__346.TimeIntervalCollection(); expect(intervals.length).toEqual(0); expect(intervals.start).toBeUndefined(); expect(intervals.stop).toBeUndefined(); expect(intervals.isStartIncluded).toEqual(false); expect(intervals.isStopIncluded).toEqual(false); expect(intervals.isEmpty).toEqual(true); expect(intervals.changedEvent).toBeDefined(); }); it("constructing an interval collection from array.", function() { const arg = [ new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: true, isStopIncluded: false }), new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: true }) ]; const intervals = new import__346.TimeIntervalCollection(arg); expect(intervals.length).toEqual(2); expect(intervals.start).toEqual(arg[0].start); expect(intervals.stop).toEqual(arg[1].stop); expect(intervals.isStartIncluded).toEqual(true); expect(intervals.isStopIncluded).toEqual(true); expect(intervals.isEmpty).toEqual(false); expect(intervals.changedEvent).toBeDefined(); }); it("isStartIncluded/isStopIncluded works.", function() { const intervals = new import__346.TimeIntervalCollection(); const interval1 = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: true, isStopIncluded: false }); const interval2 = new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: true }); expect(intervals.isStartIncluded).toBe(false); expect(intervals.isStopIncluded).toBe(false); intervals.addInterval(interval1); expect(intervals.isStartIncluded).toBe(true); expect(intervals.isStopIncluded).toBe(false); intervals.addInterval(interval2); expect(intervals.isStartIncluded).toBe(true); expect(intervals.isStopIncluded).toBe(true); }); it("contains works for a simple interval collection.", function() { const intervals = new import__346.TimeIntervalCollection(); const interval1 = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: true, isStopIncluded: false }); const interval2 = new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: true }); intervals.addInterval(interval1); intervals.addInterval(interval2); expect(intervals.contains(new import__346.JulianDate(0.5))).toEqual(false); expect(intervals.contains(new import__346.JulianDate(1.5))).toEqual(true); expect(intervals.contains(new import__346.JulianDate(2))).toEqual(false); expect(intervals.contains(new import__346.JulianDate(2.5))).toEqual(true); expect(intervals.contains(new import__346.JulianDate(3))).toEqual(true); expect(intervals.contains(new import__346.JulianDate(3.5))).toEqual(false); }); it("contains works for a endpoints of a closed interval collection.", function() { const intervals = new import__346.TimeIntervalCollection(); const interval = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: true, isStopIncluded: true }); intervals.addInterval(interval); expect(intervals.contains(interval.start)).toEqual(true); expect(intervals.contains(interval.stop)).toEqual(true); }); it("contains works for a endpoints of an open interval collection.", function() { const intervals = new import__346.TimeIntervalCollection(); const interval = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: false, isStopIncluded: false }); intervals.addInterval(interval); expect(intervals.contains(interval.start)).toEqual(false); expect(intervals.contains(interval.stop)).toEqual(false); }); it("indexOf finds the correct interval for a valid date", function() { const intervals = new import__346.TimeIntervalCollection(); const interval1 = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: true, isStopIncluded: false }); const interval2 = new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: true }); intervals.addInterval(interval1); intervals.addInterval(interval2); expect(intervals.indexOf(new import__346.JulianDate(2.5))).toEqual(1); }); it("indexOf returns complement of index of the interval that a missing date would come before", function() { const intervals = new import__346.TimeIntervalCollection(); const interval1 = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: true, isStopIncluded: false }); const interval2 = new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: true }); intervals.addInterval(interval1); intervals.addInterval(interval2); expect(intervals.indexOf(new import__346.JulianDate(2))).toEqual(~1); }); it("indexOf returns complement of collection length if the date is after all intervals.", function() { const intervals = new import__346.TimeIntervalCollection(); const interval1 = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: true, isStopIncluded: false }); const interval2 = new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: true }); intervals.addInterval(interval1); intervals.addInterval(interval2); expect(intervals.indexOf(new import__346.JulianDate(4))).toEqual(~2); }); it("get returns the interval at the correct index", function() { const intervals = new import__346.TimeIntervalCollection(); const interval1 = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: false, isStopIncluded: false }); const interval2 = new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: false }); const interval3 = new import__346.TimeInterval({ start: new import__346.JulianDate(4), stop: new import__346.JulianDate(5), isStartIncluded: false, isStopIncluded: false }); intervals.addInterval(interval1); intervals.addInterval(interval2); intervals.addInterval(interval3); expect(intervals.get(1)).toEqual(interval2); }); it("get is undefined for a out of range index", function() { const intervals = new import__346.TimeIntervalCollection(); expect(intervals.get(1)).toBeUndefined(); }); it("findInterval works when looking for an exact interval", function() { const intervals = new import__346.TimeIntervalCollection(); const interval1 = new import__346.TimeInterval({ start: new import__346.JulianDate(0), stop: new import__346.JulianDate(1), isStartIncluded: false, isStopIncluded: false, data: 1 }); const interval2 = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: true, isStopIncluded: false, data: 2 }); const interval3 = new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: false, data: 3 }); intervals.addInterval(interval1); intervals.addInterval(interval2); intervals.addInterval(interval3); expect( intervals.findInterval({ start: interval2.start, stop: interval2.stop, isStartIncluded: true, isStopIncluded: false }) ).toEqual(interval2); }); it("findInterval works when you do not care about end points", function() { const intervals = new import__346.TimeIntervalCollection(); const interval1 = new import__346.TimeInterval({ start: new import__346.JulianDate(0), stop: new import__346.JulianDate(1), isStartIncluded: false, isStopIncluded: false, data: 1 }); const interval2 = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: true, isStopIncluded: false, data: 2 }); const interval3 = new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: false, data: 3 }); intervals.addInterval(interval1); intervals.addInterval(interval2); intervals.addInterval(interval3); expect( intervals.findInterval({ start: interval2.start, stop: interval2.stop }) ).toEqual(interval2); }); it("getStart & getStop return expected values.", function() { const intervals = new import__346.TimeIntervalCollection(); const interval1 = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: true, isStopIncluded: false }); const interval2 = new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: true, isStopIncluded: false }); intervals.addInterval(interval1); intervals.addInterval(interval2); expect(intervals.start).toEqual(interval1.start); expect(intervals.stop).toEqual(interval2.stop); }); it("isEmpty and clear return expected values", function() { const intervals = new import__346.TimeIntervalCollection(); intervals.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: false, isStopIncluded: true }) ); expect(intervals.isEmpty).toEqual(false); intervals.removeAll(); expect(intervals.isEmpty).toEqual(true); }); it("length returns the correct interval length when adding intervals with different data", function() { const intervals = new import__346.TimeIntervalCollection(); expect(intervals.length).toEqual(0); intervals.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(4), isStartIncluded: true, isStopIncluded: true, data: 1 }) ); expect(intervals.length).toEqual(1); intervals.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: true, isStopIncluded: true, data: 2 }) ); expect(intervals.length).toEqual(3); intervals.removeAll(); expect(intervals.length).toEqual(0); }); it("length returns the correct length after two intervals with the same data are merged.", function() { const intervals = new import__346.TimeIntervalCollection(); intervals.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(4), isStartIncluded: true, isStopIncluded: true, data: 1 }) ); expect(intervals.length).toEqual(1); intervals.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: true, isStopIncluded: true, data: 1 }) ); expect(intervals.length).toEqual(1); intervals.removeAll(); expect(intervals.length).toEqual(0); }); it("addInterval and findIntervalContainingDate work when using non-overlapping intervals", function() { const interval1 = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: true, isStopIncluded: true, data: 1 }); const interval2 = new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: true, data: 2 }); const interval3 = new import__346.TimeInterval({ start: new import__346.JulianDate(4), stop: new import__346.JulianDate(5), isStartIncluded: true, isStopIncluded: true, data: 3 }); const intervals = new import__346.TimeIntervalCollection(); intervals.addInterval(interval1); expect(intervals.length).toEqual(1); expect(intervals.start).toEqual(interval1.start); expect(intervals.stop).toEqual(interval1.stop); expect(intervals.isEmpty).toEqual(false); expect(intervals.findIntervalContainingDate(interval1.start)).toEqual( interval1 ); expect(intervals.findIntervalContainingDate(interval1.stop)).toEqual( interval1 ); intervals.addInterval(interval2); expect(intervals.length).toEqual(2); expect(intervals.start).toEqual(interval1.start); expect(intervals.stop).toEqual(interval2.stop); expect(intervals.isEmpty).toEqual(false); expect(intervals.findIntervalContainingDate(interval1.start)).toEqual( interval1 ); expect(intervals.findIntervalContainingDate(interval1.stop)).toEqual( interval1 ); expect(intervals.findIntervalContainingDate(interval2.stop)).toEqual( interval2 ); intervals.addInterval(interval3); expect(intervals.length).toEqual(3); expect(intervals.start).toEqual(interval1.start); expect(intervals.stop).toEqual(interval3.stop); expect(intervals.isEmpty).toEqual(false); expect(intervals.findIntervalContainingDate(interval1.start)).toEqual( interval1 ); expect(intervals.findIntervalContainingDate(interval1.stop)).toEqual( interval1 ); expect(intervals.findIntervalContainingDate(interval2.stop)).toEqual( interval2 ); expect(intervals.findIntervalContainingDate(interval3.start)).toEqual( interval3 ); expect(intervals.findIntervalContainingDate(interval3.stop)).toEqual( interval3 ); }); it("addInterval and findIntervalContainingDate work when using overlapping intervals", function() { const interval1 = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2.5), isStartIncluded: true, isStopIncluded: true, data: 1 }); const interval2 = new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: true, data: 2 }); const interval3 = new import__346.TimeInterval({ start: interval1.start, stop: interval2.stop, isStartIncluded: true, isStopIncluded: true, data: 3 }); const intervals = new import__346.TimeIntervalCollection(); intervals.addInterval(interval1); expect(intervals.length).toEqual(1); expect(intervals.start).toEqual(interval1.start); expect(intervals.stop).toEqual(interval1.stop); expect(intervals.isEmpty).toEqual(false); expect(intervals.findIntervalContainingDate(interval1.start).data).toEqual( 1 ); expect(intervals.findIntervalContainingDate(interval1.stop).data).toEqual( 1 ); intervals.addInterval(interval2); expect(intervals.length).toEqual(2); expect(intervals.start).toEqual(interval1.start); expect(intervals.stop).toEqual(interval2.stop); expect(intervals.isEmpty).toEqual(false); expect(intervals.findIntervalContainingDate(interval1.start).data).toEqual( 1 ); expect(intervals.findIntervalContainingDate(interval1.stop).data).toEqual( 2 ); expect(intervals.findIntervalContainingDate(interval2.stop).data).toEqual( 2 ); intervals.addInterval(interval3); expect(intervals.length).toEqual(1); expect(intervals.start).toEqual(interval3.start); expect(intervals.stop).toEqual(interval3.stop); expect(intervals.isEmpty).toEqual(false); expect(intervals.findIntervalContainingDate(interval1.start).data).toEqual( 3 ); expect(intervals.findIntervalContainingDate(interval1.stop).data).toEqual( 3 ); expect(intervals.findIntervalContainingDate(interval2.start).data).toEqual( 3 ); expect(intervals.findIntervalContainingDate(interval2.stop).data).toEqual( 3 ); expect(intervals.findIntervalContainingDate(interval3.start).data).toEqual( 3 ); expect(intervals.findIntervalContainingDate(interval3.stop).data).toEqual( 3 ); }); it("findDataForIntervalContainingDate works", function() { const interval1 = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2.5), isStartIncluded: true, isStopIncluded: true, data: 1 }); const interval2 = new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: true, data: 2 }); const intervals = new import__346.TimeIntervalCollection(); intervals.addInterval(interval1); expect( intervals.findDataForIntervalContainingDate(interval1.start) ).toEqual(1); expect(intervals.findDataForIntervalContainingDate(interval1.stop)).toEqual( 1 ); intervals.addInterval(interval2); expect( intervals.findDataForIntervalContainingDate(interval1.start) ).toEqual(1); expect(intervals.findDataForIntervalContainingDate(interval1.stop)).toEqual( 2 ); expect(intervals.findDataForIntervalContainingDate(interval2.stop)).toEqual( 2 ); expect( intervals.findDataForIntervalContainingDate(new import__346.JulianDate(5)) ).toBeUndefined(); }); it("addInterval correctly intervals that have the same data when using equalsCallback", function() { const intervals = new import__346.TimeIntervalCollection(); const interval1 = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(4), isStartIncluded: true, isStopIncluded: true, data: new TestObject(2) }); const interval2 = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(3), isStartIncluded: true, isStopIncluded: false, data: new TestObject(2) }); const interval3 = new import__346.TimeInterval({ start: new import__346.JulianDate(3), stop: new import__346.JulianDate(4), isStartIncluded: false, isStopIncluded: true, data: new TestObject(2) }); const interval4 = new import__346.TimeInterval({ start: new import__346.JulianDate(3), stop: new import__346.JulianDate(4), isStartIncluded: true, isStopIncluded: true, data: new TestObject(3) }); intervals.addInterval(interval1, TestObject.equals); expect(intervals.length).toEqual(1); expect(intervals.start).toEqual(interval1.start); expect(intervals.stop).toEqual(interval1.stop); expect(intervals.get(0).data.value).toEqual(2); intervals.addInterval(interval2, TestObject.equals); expect(intervals.length).toEqual(1); expect(intervals.start).toEqual(interval1.start); expect(intervals.stop).toEqual(interval1.stop); expect(intervals.get(0).data.value).toEqual(2); intervals.addInterval(interval3, TestObject.equals); expect(intervals.length).toEqual(1); expect(intervals.start).toEqual(interval1.start); expect(intervals.stop).toEqual(interval1.stop); expect(intervals.get(0).data.value).toEqual(2); intervals.addInterval(interval4, TestObject.equals); expect(intervals.length).toEqual(2); expect(intervals.start).toEqual(interval1.start); expect(intervals.stop).toEqual(interval1.stop); expect(intervals.get(0).start).toEqual(interval1.start); expect(intervals.get(0).stop).toEqual(interval4.start); expect(intervals.get(0).isStartIncluded).toEqual(true); expect(intervals.get(0).isStopIncluded).toEqual(false); expect(intervals.get(0).data.value).toEqual(2); expect(intervals.get(1).start).toEqual(interval4.start); expect(intervals.get(1).stop).toEqual(interval4.stop); expect(intervals.get(1).isStartIncluded).toEqual(true); expect(intervals.get(1).isStopIncluded).toEqual(true); expect(intervals.get(1).data.value).toEqual(3); }); it("removeInterval works correctly", function() { function createTimeInterval(startDays, stopDays, isStartIncluded, isStopIncluded) { return new import__346.TimeInterval({ start: new import__346.JulianDate(startDays, 0, import__346.TimeStandard.TAI), stop: new import__346.JulianDate(stopDays, 0, import__346.TimeStandard.TAI), isStartIncluded, isStopIncluded }); } const intervals = new import__346.TimeIntervalCollection(); intervals.addInterval(createTimeInterval(10, 20)); intervals.addInterval(createTimeInterval(30, 40)); expect(intervals.removeInterval(import__346.TimeInterval.EMPTY)).toEqual(false); expect(intervals.length).toEqual(2); expect(intervals.removeInterval(createTimeInterval(1, 5))).toEqual( false ); expect(intervals.length).toEqual(2); expect(intervals.removeInterval(createTimeInterval(50, 60))).toEqual( false ); expect(intervals.length).toEqual(2); expect(intervals.removeInterval(createTimeInterval(22, 28))).toEqual( false ); expect(intervals.length).toEqual(2); expect(intervals.removeInterval(createTimeInterval(5, 15))).toEqual( true ); expect(intervals.length).toEqual(2); expect(import__346.JulianDate.totalDays(intervals.get(0).start)).toEqual(15); expect(import__346.JulianDate.totalDays(intervals.get(0).stop)).toEqual(20); expect(intervals.removeInterval(createTimeInterval(35, 45))).toEqual( true ); expect(intervals.length).toEqual(2); expect(import__346.JulianDate.totalDays(intervals.get(1).start)).toEqual(30); expect(import__346.JulianDate.totalDays(intervals.get(1).stop)).toEqual(35); intervals.removeAll(); intervals.addInterval(createTimeInterval(10, 20)); intervals.addInterval(createTimeInterval(30, 40)); expect(intervals.removeInterval(createTimeInterval(12, 18))).toEqual( true ); expect(intervals.length).toEqual(3); expect(import__346.JulianDate.totalDays(intervals.get(0).stop)).toEqual(12); expect(intervals.get(0).isStopIncluded).toEqual(false); expect(import__346.JulianDate.totalDays(intervals.get(1).start)).toEqual(18); expect(intervals.get(1).isStartIncluded).toEqual(false); intervals.removeAll(); intervals.addInterval(createTimeInterval(10, 20)); intervals.addInterval(createTimeInterval(30, 40)); intervals.addInterval(createTimeInterval(45, 50)); expect(intervals.removeInterval(createTimeInterval(25, 46))).toEqual( true ); expect(intervals.length).toEqual(2); expect(import__346.JulianDate.totalDays(intervals.get(1).start)).toEqual(46); expect(intervals.get(1).isStartIncluded).toEqual(false); intervals.removeAll(); intervals.addInterval(createTimeInterval(10, 20)); intervals.addInterval(createTimeInterval(30, 40)); intervals.addInterval(createTimeInterval(45, 50)); expect(intervals.removeInterval(createTimeInterval(25, 40))).toEqual( true ); expect(intervals.length).toEqual(2); expect(import__346.JulianDate.totalDays(intervals.get(0).stop)).toEqual(20); expect(import__346.JulianDate.totalDays(intervals.get(1).start)).toEqual(45); intervals.removeAll(); intervals.addInterval(createTimeInterval(10, 20)); intervals.addInterval(createTimeInterval(30, 40)); intervals.addInterval(createTimeInterval(45, 50)); expect( intervals.removeInterval(createTimeInterval(25, 40, true, false)) ).toEqual(true); expect(intervals.length).toEqual(3); expect(import__346.JulianDate.totalDays(intervals.get(0).stop)).toEqual(20); expect(import__346.JulianDate.totalDays(intervals.get(1).start)).toEqual(40); expect(import__346.JulianDate.totalDays(intervals.get(1).stop)).toEqual(40); expect(intervals.get(1).isStartIncluded).toEqual(true); expect(intervals.get(1).isStopIncluded).toEqual(true); expect(import__346.JulianDate.totalDays(intervals.get(2).start)).toEqual(45); intervals.removeAll(); intervals.addInterval(createTimeInterval(10, 20)); intervals.addInterval(createTimeInterval(30, 40)); intervals.addInterval(createTimeInterval(40, 50, false, true)); expect( intervals.removeInterval(createTimeInterval(25, 40, true, false)) ).toEqual(true); expect(intervals.length).toEqual(2); expect(import__346.JulianDate.totalDays(intervals.get(0).stop)).toEqual(20); expect(import__346.JulianDate.totalDays(intervals.get(1).start)).toEqual(40); expect(intervals.get(1).isStartIncluded).toEqual(true); intervals.removeAll(); intervals.addInterval(createTimeInterval(10, 20)); expect(intervals.removeInterval(createTimeInterval(0, 10))).toEqual( true ); expect(intervals.length).toEqual(1); expect(import__346.JulianDate.totalDays(intervals.get(0).start)).toEqual(10); expect(import__346.JulianDate.totalDays(intervals.get(0).stop)).toEqual(20); expect(intervals.get(0).isStartIncluded).toEqual(false); expect(intervals.get(0).isStopIncluded).toEqual(true); intervals.removeAll(); intervals.addInterval(createTimeInterval(10, 20)); expect( intervals.removeInterval(createTimeInterval(20, 30, false, true)) ).toEqual(false); expect(intervals.length).toEqual(1); expect(import__346.JulianDate.totalDays(intervals.get(0).start)).toEqual(10); expect(import__346.JulianDate.totalDays(intervals.get(0).stop)).toEqual(20); expect(intervals.get(0).isStartIncluded).toEqual(true); expect(intervals.get(0).isStopIncluded).toEqual(true); intervals.removeAll(); intervals.addInterval(createTimeInterval(0, 20)); expect( intervals.removeInterval(createTimeInterval(0, 20, false, false)) ).toEqual(true); expect(intervals.length).toEqual(2); expect(import__346.JulianDate.totalDays(intervals.get(0).start)).toEqual(0); expect(import__346.JulianDate.totalDays(intervals.get(0).stop)).toEqual(0); expect(intervals.get(0).isStartIncluded).toEqual(true); expect(intervals.get(0).isStopIncluded).toEqual(true); expect(import__346.JulianDate.totalDays(intervals.get(1).start)).toEqual(20); expect(import__346.JulianDate.totalDays(intervals.get(1).stop)).toEqual(20); expect(intervals.get(1).isStartIncluded).toEqual(true); expect(intervals.get(1).isStopIncluded).toEqual(true); }); it("removeInterval removes the first interval correctly", function() { const intervals = new import__346.TimeIntervalCollection(); const from1To3 = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(3), isStopIncluded: true, isStartIncluded: true, data: "1-to-3" }); const from3To6 = new import__346.TimeInterval({ start: new import__346.JulianDate(3), stop: new import__346.JulianDate(6), isStopIncluded: true, isStartIncluded: true, data: "3-to-6" }); intervals.addInterval(from1To3); intervals.addInterval(from3To6); expect(intervals.length).toEqual(2); expect(intervals.get(0).isStartIncluded).toBeTruthy(); expect(intervals.get(0).isStopIncluded).toBeFalsy(); expect(intervals.get(0).start.dayNumber).toEqual(1); expect(intervals.get(0).stop.dayNumber).toEqual(3); expect(intervals.get(0).data).toEqual("1-to-3"); expect(intervals.get(1).isStartIncluded).toBeTruthy(); expect(intervals.get(1).isStopIncluded).toBeTruthy(); expect(intervals.get(1).start.dayNumber).toEqual(3); expect(intervals.get(1).stop.dayNumber).toEqual(6); expect(intervals.get(1).data).toEqual("3-to-6"); const toRemove = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(3), isStopIncluded: true, isStartIncluded: true, data: void 0 }); expect(intervals.removeInterval(toRemove)).toEqual(true); expect(intervals.length).toEqual(1); expect(intervals.start.dayNumber).toEqual(3); expect(intervals.stop.dayNumber).toEqual(6); expect(intervals.get(0).start.dayNumber).toEqual(3); expect(intervals.get(0).stop.dayNumber).toEqual(6); expect(intervals.get(0).isStartIncluded).toEqual(false); expect(intervals.get(0).isStopIncluded).toEqual(true); expect(intervals.get(0).data).toEqual("3-to-6"); }); it("should add and remove intervals correctly (some kind of integration test)", function() { const CONST_DAY_NUM = 3e6; function intervalFromSeconds(seconds, data) { return new import__346.TimeInterval({ start: new import__346.JulianDate(CONST_DAY_NUM, seconds), stop: new import__346.JulianDate(CONST_DAY_NUM, seconds + 4), isStartIncluded: true, isStopIncluded: true, data }); } function addIntervals(collection2, specs) { specs.forEach(function(spec) { collection2.addInterval(intervalFromSeconds(spec.sec, spec.data)); }); } function removeInterval(collection2, fromSecond, toSecond) { collection2.removeInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(CONST_DAY_NUM, fromSecond), stop: new import__346.JulianDate(CONST_DAY_NUM, toSecond), isStartIncluded: true, isStopIncluded: true, data: void 0 }) ); } function expectCollection(collection2, count, expectation) { expectation.forEach(function(item) { const interval = collection2.findIntervalContainingDate( new import__346.JulianDate(CONST_DAY_NUM, item.sec) ); if (item.data === null) { if (interval !== void 0) { throw new Error( `expected undefined at ${item.sec} seconds but it was ${interval.data}` ); } expect(interval).toBeUndefined(); } else if (interval === void 0) { throw new Error( `expected ${item.data} at ${item.sec} seconds, but it was undefined` ); } else if (interval.data !== item.data) { throw new Error( `expected ${item.data} at ${item.sec} seconds, but it was ${interval.data}` ); } }); if (collection2.length !== count) { throw new Error( `Expected interval to have ${count} elements but it had ${collection2.length}` ); } } const collection = new import__346.TimeIntervalCollection(); addIntervals(collection, [ { sec: 0, data: 0 }, { sec: 2, data: 2 }, { sec: 4, data: 4 }, { sec: 6, data: 6 } ]); expectCollection(collection, 4, [ { sec: 0, data: 0 }, { sec: 1, data: 0 }, { sec: 2, data: 2 }, { sec: 3, data: 2 }, { sec: 4, data: 4 }, { sec: 5, data: 4 }, { sec: 6, data: 6 }, { sec: 7, data: 6 }, { sec: 8, data: 6 }, { sec: 9, data: 6 }, { sec: 10, data: 6 }, { sec: 11, data: null } ]); addIntervals(collection, [ { sec: 1, data: 1 }, { sec: 3, data: 3 } ]); expectCollection(collection, 4, [ { sec: 0, data: 0 }, { sec: 1, data: 1 }, { sec: 2, data: 1 }, { sec: 3, data: 3 }, { sec: 4, data: 3 }, { sec: 5, data: 3 }, { sec: 6, data: 3 }, { sec: 7, data: 3 }, { sec: 8, data: 6 }, { sec: 9, data: 6 }, { sec: 10, data: 6 }, { sec: 11, data: null } ]); addIntervals(collection, [{ sec: 3, data: 31 }]); expectCollection(collection, 4, [ { sec: 0, data: 0 }, { sec: 1, data: 1 }, { sec: 2, data: 1 }, { sec: 3, data: 31 }, { sec: 4, data: 31 }, { sec: 5, data: 31 }, { sec: 6, data: 31 }, { sec: 7, data: 31 }, { sec: 8, data: 6 }, { sec: 9, data: 6 }, { sec: 10, data: 6 }, { sec: 11, data: null } ]); removeInterval(collection, 3, 8); expectCollection(collection, 3, [ { sec: 0, data: 0 }, { sec: 1, data: 1 }, { sec: 2, data: 1 }, { sec: 3, data: null }, { sec: 4, data: null }, { sec: 5, data: null }, { sec: 6, data: null }, { sec: 7, data: null }, { sec: 8, data: null }, { sec: 9, data: 6 }, { sec: 10, data: 6 }, { sec: 11, data: null } ]); removeInterval(collection, 0, 1); expectCollection(collection, 2, [ { sec: 0, data: null }, { sec: 1, data: null }, { sec: 2, data: 1 }, { sec: 3, data: null }, { sec: 4, data: null }, { sec: 5, data: null }, { sec: 6, data: null }, { sec: 7, data: null }, { sec: 8, data: null }, { sec: 9, data: 6 }, { sec: 10, data: 6 }, { sec: 11, data: null } ]); removeInterval(collection, 0, 11); expectCollection(collection, 0, [ { sec: 0, data: null }, { sec: 11, data: null } ]); addIntervals(collection, [ { sec: 1, data: 1 }, { sec: 12, data: 12 } ]); expectCollection(collection, 2, [ { sec: 0, data: null }, { sec: 1, data: 1 }, { sec: 2, data: 1 }, { sec: 3, data: 1 }, { sec: 4, data: 1 }, { sec: 5, data: 1 }, { sec: 6, data: null }, { sec: 7, data: null }, { sec: 8, data: null }, { sec: 9, data: null }, { sec: 10, data: null }, { sec: 11, data: null }, { sec: 12, data: 12 }, { sec: 13, data: 12 }, { sec: 14, data: 12 }, { sec: 15, data: 12 }, { sec: 16, data: 12 }, { sec: 17, data: null } ]); removeInterval(collection, 0, 3); expectCollection(collection, 2, [ { sec: 0, data: null }, { sec: 1, data: null }, { sec: 2, data: null }, { sec: 3, data: null }, { sec: 4, data: 1 }, { sec: 5, data: 1 }, { sec: 6, data: null }, { sec: 7, data: null }, { sec: 8, data: null }, { sec: 12, data: 12 }, { sec: 16, data: 12 }, { sec: 17, data: null } ]); }); it("removeInterval leaves a hole", function() { const intervals = new import__346.TimeIntervalCollection(); const interval = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(4), isStartIncluded: true, isStopIncluded: true }); const removedInterval = new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: true, isStopIncluded: false }); intervals.addInterval(interval); expect(intervals.removeInterval(removedInterval)).toEqual(true); expect(intervals.length).toEqual(2); expect(intervals.get(0).start).toEqual(interval.start); expect(intervals.get(0).stop).toEqual(removedInterval.start); expect(intervals.get(0).isStartIncluded).toEqual(true); expect(intervals.get(0).isStopIncluded).toEqual(false); expect(intervals.get(1).start).toEqual(removedInterval.stop); expect(intervals.get(1).stop).toEqual(interval.stop); expect(intervals.get(1).isStartIncluded).toEqual(true); expect(intervals.get(1).isStopIncluded).toEqual(true); }); it("removeInterval with an interval of the exact same size works.", function() { const intervals = new import__346.TimeIntervalCollection(); const interval = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(4), isStartIncluded: true, isStopIncluded: false }); intervals.addInterval(interval); expect(intervals.length).toEqual(1); expect(intervals.get(0).start).toEqual(interval.start); expect(intervals.get(0).stop).toEqual(interval.stop); expect(intervals.get(0).isStartIncluded).toEqual(true); expect(intervals.get(0).isStopIncluded).toEqual(false); intervals.removeInterval(interval); expect(intervals.length).toEqual(0); }); it("removeInterval with an empty interval has no affect.", function() { const intervals = new import__346.TimeIntervalCollection(); const interval = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(4), isStartIncluded: true, isStopIncluded: true }); intervals.addInterval(interval); expect(intervals.length).toEqual(1); expect(intervals.get(0).start).toEqual(interval.start); expect(intervals.get(0).stop).toEqual(interval.stop); expect(intervals.get(0).isStartIncluded).toEqual(true); expect(intervals.get(0).isStopIncluded).toEqual(true); expect(intervals.removeInterval(import__346.TimeInterval.EMPTY)).toEqual(false); expect(intervals.length).toEqual(1); expect(intervals.get(0).start).toEqual(interval.start); expect(intervals.get(0).stop).toEqual(interval.stop); expect(intervals.get(0).isStartIncluded).toEqual(true); expect(intervals.get(0).isStopIncluded).toEqual(true); }); it("removeInterval takes isStartIncluded and isStopIncluded into account", function() { const intervals = new import__346.TimeIntervalCollection(); const interval = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(4), isStartIncluded: true, isStopIncluded: true }); const removedInterval = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(4), isStartIncluded: false, isStopIncluded: false }); intervals.addInterval(interval); expect(intervals.removeInterval(removedInterval)).toEqual(true); expect(intervals.length).toEqual(2); expect(intervals.get(0).start).toEqual(interval.start); expect(intervals.get(0).stop).toEqual(interval.start); expect(intervals.get(0).isStartIncluded).toEqual(true); expect(intervals.get(0).isStopIncluded).toEqual(true); expect(intervals.get(1).start).toEqual(interval.stop); expect(intervals.get(1).stop).toEqual(interval.stop); expect(intervals.get(1).isStartIncluded).toEqual(true); expect(intervals.get(1).isStopIncluded).toEqual(true); }); it("removeInterval removes overlapped intervals", function() { const intervals = new import__346.TimeIntervalCollection(); intervals.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: true, isStopIncluded: false }) ); intervals.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: false }) ); intervals.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(3), stop: new import__346.JulianDate(4), isStartIncluded: false, isStopIncluded: false }) ); intervals.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(4), stop: new import__346.JulianDate(5), isStartIncluded: false, isStopIncluded: true }) ); const removedInterval = new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(4), isStartIncluded: false, isStopIncluded: false }); expect(intervals.length).toEqual(4); expect(intervals.removeInterval(removedInterval)).toEqual(true); expect(intervals.length).toEqual(2); }); it("intersect works with an empty collection", function() { const left = new import__346.TimeIntervalCollection(); left.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(4), isStartIncluded: true, isStopIncluded: true }) ); expect(left.intersect(new import__346.TimeIntervalCollection()).length).toEqual(0); }); it("intersect works non-overlapping intervals", function() { const left = new import__346.TimeIntervalCollection(); left.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: true, isStopIncluded: false }) ); const right = new import__346.TimeIntervalCollection(); right.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: true, isStopIncluded: true }) ); expect(left.intersect(right).length).toEqual(0); }); it("intersect works with intersecting intervals and no merge callback", function() { const left = new import__346.TimeIntervalCollection(); left.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(4), isStartIncluded: true, isStopIncluded: true }) ); const right = new import__346.TimeIntervalCollection(); right.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: false }) ); const intersectedIntervals = left.intersect(right); expect(intersectedIntervals.length).toEqual(1); expect(intersectedIntervals.get(0).start).toEqual(right.get(0).start); expect(intersectedIntervals.get(0).stop).toEqual(right.get(0).stop); expect(intersectedIntervals.get(0).isStartIncluded).toEqual(false); expect(intersectedIntervals.get(0).isStopIncluded).toEqual(false); }); it("intersect works with intersecting intervals an a merge callback", function() { const left = new import__346.TimeIntervalCollection(); left.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(4), isStartIncluded: true, isStopIncluded: true, data: new TestObject(1) }) ); const right = new import__346.TimeIntervalCollection(); right.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: false, data: new TestObject(2) }) ); const intersectedIntervals = left.intersect( right, TestObject.equals, TestObject.merge ); expect(intersectedIntervals.length).toEqual(1); expect(intersectedIntervals.get(0).start).toEqual(right.start); expect(intersectedIntervals.get(0).stop).toEqual(right.stop); expect(intersectedIntervals.get(0).isStartIncluded).toEqual(false); expect(intersectedIntervals.get(0).isStopIncluded).toEqual(false); expect(intersectedIntervals.get(0).data.value).toEqual(3); }); it("equals works without data", function() { const interval1 = new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: true, isStopIncluded: true }); const interval2 = new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: true }); const interval3 = new import__346.TimeInterval({ start: new import__346.JulianDate(4), stop: new import__346.JulianDate(5), isStartIncluded: true, isStopIncluded: true }); const left = new import__346.TimeIntervalCollection(); left.addInterval(interval1); left.addInterval(interval2); left.addInterval(interval3); const right = new import__346.TimeIntervalCollection(); right.addInterval(interval1); right.addInterval(interval2); right.addInterval(interval3); expect(left.equals(right)).toEqual(true); }); it("equals works with data", function() { const left = new import__346.TimeIntervalCollection(); left.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: true, isStopIncluded: true, data: {} }) ); left.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: true, data: {} }) ); left.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(4), stop: new import__346.JulianDate(5), isStartIncluded: true, isStopIncluded: true, data: {} }) ); const right = new import__346.TimeIntervalCollection(); right.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(1), stop: new import__346.JulianDate(2), isStartIncluded: true, isStopIncluded: true, data: {} }) ); right.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(2), stop: new import__346.JulianDate(3), isStartIncluded: false, isStopIncluded: true, data: {} }) ); right.addInterval( new import__346.TimeInterval({ start: new import__346.JulianDate(4), stop: new import__346.JulianDate(5), isStartIncluded: true, isStopIncluded: true, data: {} }) ); expect(left.equals(right)).toEqual(false); expect( left.equals(right, function() { return true; }) ).toEqual(true); expect( left.equals(right, function() { return false; }) ).toEqual(false); }); it("get throws with undefined", function() { const intervals = new import__346.TimeIntervalCollection(); expect(function() { intervals.get(void 0); }).toThrowDeveloperError(); }); it("findIntervalContainingDate throws with undefined date", function() { const intervals = new import__346.TimeIntervalCollection(); expect(function() { intervals.findIntervalContainingDate(void 0); }).toThrowDeveloperError(); }); it("findDataForIntervalContainingDate throws with undefined date", function() { const intervals = new import__346.TimeIntervalCollection(); expect(function() { intervals.findDataForIntervalContainingDate(void 0); }).toThrowDeveloperError(); }); it("contains throws with undefined date", function() { const intervals = new import__346.TimeIntervalCollection(); expect(function() { intervals.contains(void 0); }).toThrowDeveloperError(); }); it("indexOf throws with undefined date", function() { const intervals = new import__346.TimeIntervalCollection(); expect(function() { intervals.indexOf(void 0); }).toThrowDeveloperError(); }); it("addInterval throws with undefined interval", function() { const intervals = new import__346.TimeIntervalCollection(); expect(function() { intervals.addInterval(void 0, TestObject.equals); }).toThrowDeveloperError(); }); it("removeInterval throws with undefined", function() { const intervals = new import__346.TimeIntervalCollection(); expect(function() { intervals.removeInterval(void 0); }).toThrowDeveloperError(); }); it("intersect throws with undefined interval", function() { const intervals = new import__346.TimeIntervalCollection(); expect(function() { intervals.intersect(void 0); }).toThrowDeveloperError(); }); it("changed event is raised as expected", function() { const interval = new import__346.TimeInterval({ start: new import__346.JulianDate(10, 0), stop: new import__346.JulianDate(12, 0) }); const intervals = new import__346.TimeIntervalCollection(); const listener = jasmine.createSpy("listener"); intervals.changedEvent.addEventListener(listener); intervals.addInterval(interval); expect(listener).toHaveBeenCalledWith(intervals); listener.calls.reset(); intervals.removeInterval(interval); expect(listener).toHaveBeenCalledWith(intervals); intervals.addInterval(interval); listener.calls.reset(); intervals.removeAll(); expect(listener).toHaveBeenCalledWith(intervals); }); it("fromIso8601 throws without options", function() { expect(function() { import__346.TimeIntervalCollection.fromIso8601(void 0); }).toThrowDeveloperError(); }); it("fromIso8601 throws without options.iso8601", function() { expect(function() { import__346.TimeIntervalCollection.fromIso8601({}); }).toThrowDeveloperError(); }); it("fromIso8601 return single interval if no duration", function() { const start = "2017-01-01T00:00:00Z"; const stop = "2017-01-02T00:00:00Z"; const julianDates = iso8601ToJulianDateArray([start, stop]); const intervals = import__346.TimeIntervalCollection.fromIso8601({ iso8601: `${start}/${stop}`, isStartIncluded: false, isStopIncluded: false }); checkIntervals(intervals, julianDates, false, false); }); it("fromIso8601 works with just year", function() { const iso8601Dates = [ "2017-01-01T00:00:00Z", "2018-01-01T00:00:00Z", "2019-01-01T00:00:00Z", "2020-01-01T00:00:00Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601({ iso8601: `${iso8601Dates[0]}/${iso8601Dates[iso8601Dates.length - 1]}/P1Y` }); checkIntervals(intervals, julianDates, true, true); }); it("fromIso8601 works with just month", function() { const iso8601Dates = [ "2016-12-02T10:00:01.5Z", "2017-01-02T10:00:01.5Z", "2017-02-02T10:00:01.5Z", "2017-03-02T10:00:01.5Z", "2017-04-02T10:00:01.5Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601({ iso8601: `${iso8601Dates[0]}/${iso8601Dates[iso8601Dates.length - 1]}/P1M` }); checkIntervals(intervals, julianDates, true, true); }); it("fromIso8601 works with just day", function() { const iso8601Dates = [ "2016-12-31T10:01:01.5Z", "2017-01-01T10:01:01.5Z", "2017-01-02T10:01:01.5Z", "2017-01-03T10:01:01.5Z", "2017-01-04T10:01:01.5Z", "2017-01-05T10:01:01.5Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601({ iso8601: `${iso8601Dates[0]}/${iso8601Dates[iso8601Dates.length - 1]}/P1D`, isStartIncluded: false }); checkIntervals(intervals, julianDates, false, true); }); it("fromIso8601 works with just all date components", function() { const iso8601Dates = [ "2017-01-01T10:01:01.5Z", "2018-03-04T10:01:01.5Z", "2019-05-07T10:01:01.5Z", "2020-07-10T10:01:01.5Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601({ iso8601: `${iso8601Dates[0]}/${iso8601Dates[iso8601Dates.length - 1]}/P1Y2M3D`, isStopIncluded: false }); checkIntervals(intervals, julianDates, true, false); }); it("fromIso8601 works with just just hour", function() { const iso8601Dates = [ "2017-01-01T22:01:01.5Z", "2017-01-01T23:01:01.5Z", "2017-01-02T00:01:01.5Z", "2017-01-02T01:01:01.5Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601({ iso8601: `${iso8601Dates[0]}/${iso8601Dates[iso8601Dates.length - 1]}/PT1H`, isStartIncluded: false }); checkIntervals(intervals, julianDates, false, true); }); it("fromIso8601 works with just just minute", function() { const iso8601Dates = [ "2016-12-31T23:58:01.5Z", "2016-12-31T23:59:01.5Z", "2017-01-01T00:00:01.5Z", "2017-01-01T00:01:01.5Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601({ iso8601: `${iso8601Dates[0]}/${iso8601Dates[iso8601Dates.length - 1]}/PT1M`, isStopIncluded: false }); checkIntervals(intervals, julianDates, true, false); }); it("fromIso8601 works with just just second", function() { const iso8601Dates = [ "2016-12-31T23:59:58.5Z", "2016-12-31T23:59:59.5Z", "2017-01-01T00:00:00.5Z", "2017-01-01T00:00:01.5Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601({ iso8601: `${iso8601Dates[0]}/${iso8601Dates[iso8601Dates.length - 1]}/PT1S`, isStartIncluded: false, isStopIncluded: false }); checkIntervals(intervals, julianDates, false, false); }); it("fromIso8601 works with just just millisecond", function() { const iso8601Dates = [ "2016-12-31T23:59:58.5Z", "2016-12-31T23:59:59Z", "2016-12-31T23:59:59.5Z", "2017-01-01T00:00:00Z", "2017-01-01T00:00:00.5Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601({ iso8601: `${iso8601Dates[0]}/${iso8601Dates[iso8601Dates.length - 1]}/PT0.5S` }); checkIntervals(intervals, julianDates, true, true); }); it("fromIso8601 works with just all time components", function() { const iso8601Dates = [ "2017-01-01T10:01:01.5Z", "2017-01-01T11:03:05Z", "2017-01-01T12:05:08.5Z", "2017-01-01T13:07:12Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601({ iso8601: `${iso8601Dates[0]}/${iso8601Dates[iso8601Dates.length - 1]}/PT1H2M3.5S` }); checkIntervals(intervals, julianDates, true, true); }); it("fromIso8601 works with just all date and time components", function() { const iso8601Dates = [ "2017-01-01T10:01:01.5Z", "2018-03-04T11:03:05Z", "2019-05-07T12:05:08.5Z", "2020-07-10T13:07:12Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601({ iso8601: `${iso8601Dates[0]}/${iso8601Dates[iso8601Dates.length - 1]}/P1Y2M3DT1H2M3.5S` }); checkIntervals(intervals, julianDates, true, true); }); it("fromIso8601 works with just all date and time components with date string for duration", function() { const iso8601Dates = [ "2017-01-01T10:01:01.5Z", "2018-03-04T11:03:05Z", "2019-05-07T12:05:08.5Z", "2020-07-10T13:07:12Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601({ iso8601: `${iso8601Dates[0]}/${iso8601Dates[iso8601Dates.length - 1]}/0001-02-03T01:02:03.5` }); checkIntervals(intervals, julianDates, true, true); }); function dataCallback(interval, index) { if (import__346.JulianDate.compare(import__346.Iso8601.MINIMUM_VALUE, interval.start) === 0) { return "default"; } return import__346.JulianDate.toIso8601(interval.start); } it("fromIso8601 calls the dataCallback on interval create", function() { const dataSpy = jasmine.createSpy("data").and.callFake(dataCallback); const iso8601Dates = [ "2017-01-01T10:01:01.5Z", "2018-03-04T11:03:05Z", "2019-05-07T12:05:08.5Z", "2020-07-10T13:07:12Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601({ iso8601: `${iso8601Dates[0]}/${iso8601Dates[iso8601Dates.length - 1]}/P1Y2M3DT1H2M3.5S`, dataCallback: dataSpy }); expect(dataSpy.calls.count()).toEqual(3); for (let i = 0; i < 3; ++i) { expect(dataSpy).toHaveBeenCalledWith(intervals.get(i), i); } checkIntervals(intervals, julianDates, true, true, dataCallback); }); it("fromIso8601 handles leadingInterval option", function() { const dataSpy = jasmine.createSpy("data").and.callFake(dataCallback); const iso8601Dates = [ "2016-12-31T23:58:01.5Z", "2016-12-31T23:59:01.5Z", "2017-01-01T00:00:01.5Z", "2017-01-01T00:01:01.5Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601({ iso8601: `${iso8601Dates[0]}/${iso8601Dates[iso8601Dates.length - 1]}/PT1M`, isStartIncluded: true, isStopIncluded: false, leadingInterval: true, dataCallback: dataSpy }); expect(dataSpy.calls.count()).toEqual(4); for (let i = 0; i < 4; ++i) { expect(dataSpy).toHaveBeenCalledWith(intervals.get(i), i); } const leading = intervals._intervals.shift(); expect(import__346.JulianDate.compare(leading.start, import__346.Iso8601.MINIMUM_VALUE)).toEqual(0); expect(import__346.JulianDate.compare(leading.stop, julianDates[0])).toEqual(0); expect(leading.isStartIncluded).toBe(true); expect(leading.isStopIncluded).toBe(false); expect(leading.data).toEqual(dataCallback(leading, 0)); checkIntervals(intervals, julianDates, true, false, dataCallback); }); it("fromIso8601 handles trailingInterval option", function() { const dataSpy = jasmine.createSpy("data").and.callFake(dataCallback); const iso8601Dates = [ "2016-12-31T23:58:01.5Z", "2016-12-31T23:59:01.5Z", "2017-01-01T00:00:01.5Z", "2017-01-01T00:01:01.5Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601({ iso8601: `${iso8601Dates[0]}/${iso8601Dates[iso8601Dates.length - 1]}/PT1M`, isStartIncluded: false, isStopIncluded: true, trailingInterval: true, dataCallback: dataSpy }); expect(dataSpy.calls.count()).toEqual(4); for (let i = 0; i < 4; ++i) { expect(dataSpy).toHaveBeenCalledWith(intervals.get(i), i); } const trailing = intervals._intervals.pop(); expect( import__346.JulianDate.compare(trailing.start, julianDates[iso8601Dates.length - 1]) ).toEqual(0); expect(import__346.JulianDate.compare(trailing.stop, import__346.Iso8601.MAXIMUM_VALUE)).toEqual(0); expect(trailing.isStartIncluded).toBe(false); expect(trailing.isStopIncluded).toBe(true); expect(trailing.data).toEqual(dataCallback(trailing, 4)); checkIntervals(intervals, julianDates, false, true, dataCallback); }); it("fromIso8601 handles leadingInterval and trailingInterval option", function() { const dataSpy = jasmine.createSpy("data").and.callFake(dataCallback); const iso8601Dates = [ "2016-12-31T23:58:01.5Z", "2016-12-31T23:59:01.5Z", "2017-01-01T00:00:01.5Z", "2017-01-01T00:01:01.5Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601({ iso8601: `${iso8601Dates[0]}/${iso8601Dates[iso8601Dates.length - 1]}/PT1M`, isStartIncluded: false, isStopIncluded: false, leadingInterval: true, trailingInterval: true, dataCallback: dataSpy }); expect(dataSpy.calls.count()).toEqual(5); for (let i = 0; i < 4; ++i) { expect(dataSpy).toHaveBeenCalledWith(intervals.get(i), i); } const leading = intervals._intervals.shift(); expect(import__346.JulianDate.compare(leading.start, import__346.Iso8601.MINIMUM_VALUE)).toEqual(0); expect(import__346.JulianDate.compare(leading.stop, julianDates[0])).toEqual(0); expect(leading.isStartIncluded).toBe(true); expect(leading.isStopIncluded).toBe(true); expect(leading.data).toEqual(dataCallback(leading, 0)); const trailing = intervals._intervals.pop(); expect( import__346.JulianDate.compare(trailing.start, julianDates[iso8601Dates.length - 1]) ).toEqual(0); expect(import__346.JulianDate.compare(trailing.stop, import__346.Iso8601.MAXIMUM_VALUE)).toEqual(0); expect(trailing.isStartIncluded).toBe(true); expect(trailing.isStopIncluded).toBe(true); expect(trailing.data).toEqual(dataCallback(trailing, 4)); checkIntervals(intervals, julianDates, false, false, dataCallback); }); it("fromIso8601DateArray handles leadingInterval option", function() { const dataSpy = jasmine.createSpy("data").and.callFake(dataCallback); const iso8601Dates = [ "2016-12-31T23:58:01.5Z", "2016-12-31T23:59:01.5Z", "2017-01-01T00:00:01.5Z", "2017-01-01T00:01:01.5Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601DateArray({ iso8601Dates, isStartIncluded: true, isStopIncluded: false, leadingInterval: true, dataCallback: dataSpy }); expect(dataSpy.calls.count()).toEqual(4); for (let i = 0; i < 4; ++i) { expect(dataSpy).toHaveBeenCalledWith(intervals.get(i), i); } const leading = intervals._intervals.shift(); expect(import__346.JulianDate.compare(leading.start, import__346.Iso8601.MINIMUM_VALUE)).toEqual(0); expect(import__346.JulianDate.compare(leading.stop, julianDates[0])).toEqual(0); expect(leading.isStartIncluded).toBe(true); expect(leading.isStopIncluded).toBe(false); expect(leading.data).toEqual(dataCallback(leading, 0)); checkIntervals(intervals, julianDates, true, false, dataCallback); }); it("fromIso8601DateArray handles trailingInterval option", function() { const dataSpy = jasmine.createSpy("data").and.callFake(dataCallback); const iso8601Dates = [ "2016-12-31T23:58:01.5Z", "2016-12-31T23:59:01.5Z", "2017-01-01T00:00:01.5Z", "2017-01-01T00:01:01.5Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601DateArray({ iso8601Dates, isStartIncluded: false, isStopIncluded: true, trailingInterval: true, dataCallback: dataSpy }); expect(dataSpy.calls.count()).toEqual(4); for (let i = 0; i < 4; ++i) { expect(dataSpy).toHaveBeenCalledWith(intervals.get(i), i); } const trailing = intervals._intervals.pop(); expect( import__346.JulianDate.compare(trailing.start, julianDates[iso8601Dates.length - 1]) ).toEqual(0); expect(import__346.JulianDate.compare(trailing.stop, import__346.Iso8601.MAXIMUM_VALUE)).toEqual(0); expect(trailing.isStartIncluded).toBe(false); expect(trailing.isStopIncluded).toBe(true); expect(trailing.data).toEqual(dataCallback(trailing, 4)); checkIntervals(intervals, julianDates, false, true, dataCallback); }); it("fromIso8601DateArray handles leadingInterval and trailingInterval option", function() { const dataSpy = jasmine.createSpy("data").and.callFake(dataCallback); const iso8601Dates = [ "2016-12-31T23:58:01.5Z", "2016-12-31T23:59:01.5Z", "2017-01-01T00:00:01.5Z", "2017-01-01T00:01:01.5Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const intervals = import__346.TimeIntervalCollection.fromIso8601DateArray({ iso8601Dates, isStartIncluded: false, isStopIncluded: false, leadingInterval: true, trailingInterval: true, dataCallback: dataSpy }); expect(dataSpy.calls.count()).toEqual(5); for (let i = 0; i < 4; ++i) { expect(dataSpy).toHaveBeenCalledWith(intervals.get(i), i); } const leading = intervals._intervals.shift(); expect(import__346.JulianDate.compare(leading.start, import__346.Iso8601.MINIMUM_VALUE)).toEqual(0); expect(import__346.JulianDate.compare(leading.stop, julianDates[0])).toEqual(0); expect(leading.isStartIncluded).toBe(true); expect(leading.isStopIncluded).toBe(true); expect(leading.data).toEqual(dataCallback(leading, 0)); const trailing = intervals._intervals.pop(); expect( import__346.JulianDate.compare(trailing.start, julianDates[iso8601Dates.length - 1]) ).toEqual(0); expect(import__346.JulianDate.compare(trailing.stop, import__346.Iso8601.MAXIMUM_VALUE)).toEqual(0); expect(trailing.isStartIncluded).toBe(true); expect(trailing.isStopIncluded).toBe(true); expect(trailing.data).toEqual(dataCallback(trailing, 4)); checkIntervals(intervals, julianDates, false, false, dataCallback); }); it("fromIso8601DurationArray handles relativeToPrevious set to false", function() { const dataSpy = jasmine.createSpy("data").and.callFake(dataCallback); const iso8601Dates = [ "2016-12-31T23:58:01.5Z", "2016-12-31T23:59:01.5Z", "2017-01-01T00:00:01.5Z", "2017-01-01T00:01:01.5Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const iso8601Durations = ["PT0M", "PT1M", "PT2M", "PT3M"]; const intervals = import__346.TimeIntervalCollection.fromIso8601DurationArray({ epoch: julianDates[0], iso8601Durations, relativeToPrevious: false, isStartIncluded: false, isStopIncluded: false, leadingInterval: true, trailingInterval: true, dataCallback: dataSpy }); expect(dataSpy.calls.count()).toEqual(5); for (let i = 0; i < 4; ++i) { expect(dataSpy).toHaveBeenCalledWith(intervals.get(i), i); } const leading = intervals._intervals.shift(); expect(import__346.JulianDate.compare(leading.start, import__346.Iso8601.MINIMUM_VALUE)).toEqual(0); expect(import__346.JulianDate.compare(leading.stop, julianDates[0])).toEqual(0); expect(leading.isStartIncluded).toBe(true); expect(leading.isStopIncluded).toBe(true); expect(leading.data).toEqual(dataCallback(leading, 0)); const trailing = intervals._intervals.pop(); expect( import__346.JulianDate.compare(trailing.start, julianDates[iso8601Dates.length - 1]) ).toEqual(0); expect(import__346.JulianDate.compare(trailing.stop, import__346.Iso8601.MAXIMUM_VALUE)).toEqual(0); expect(trailing.isStartIncluded).toBe(true); expect(trailing.isStopIncluded).toBe(true); expect(trailing.data).toEqual(dataCallback(trailing, 4)); checkIntervals(intervals, julianDates, false, false, dataCallback); }); it("fromIso8601DurationArray handles relativeToPrevious set to true", function() { const dataSpy = jasmine.createSpy("data").and.callFake(dataCallback); const iso8601Dates = [ "2016-12-31T23:58:01.5Z", "2016-12-31T23:59:01.5Z", "2017-01-01T00:00:01.5Z", "2017-01-01T00:01:01.5Z" ]; const julianDates = iso8601ToJulianDateArray(iso8601Dates); const iso8601Durations = ["PT0M", "PT1M", "PT1M", "PT1M"]; const intervals = import__346.TimeIntervalCollection.fromIso8601DurationArray({ epoch: julianDates[0], iso8601Durations, relativeToPrevious: true, isStartIncluded: false, isStopIncluded: false, leadingInterval: true, trailingInterval: true, dataCallback: dataSpy }); expect(dataSpy.calls.count()).toEqual(5); for (let i = 0; i < 4; ++i) { expect(dataSpy).toHaveBeenCalledWith(intervals.get(i), i); } const leading = intervals._intervals.shift(); expect(import__346.JulianDate.compare(leading.start, import__346.Iso8601.MINIMUM_VALUE)).toEqual(0); expect(import__346.JulianDate.compare(leading.stop, julianDates[0])).toEqual(0); expect(leading.isStartIncluded).toBe(true); expect(leading.isStopIncluded).toBe(true); expect(leading.data).toEqual(dataCallback(leading, 0)); const trailing = intervals._intervals.pop(); expect( import__346.JulianDate.compare(trailing.start, julianDates[iso8601Dates.length - 1]) ).toEqual(0); expect(import__346.JulianDate.compare(trailing.stop, import__346.Iso8601.MAXIMUM_VALUE)).toEqual(0); expect(trailing.isStartIncluded).toBe(true); expect(trailing.isStopIncluded).toBe(true); expect(trailing.data).toEqual(dataCallback(trailing, 4)); checkIntervals(intervals, julianDates, false, false, dataCallback); }); }); // packages/engine/Specs/Core/TimeIntervalSpec.js var import__347 = __toESM(require_Cesium(), 1); describe("Core/TimeInterval", function() { function returnTrue() { return true; } it("Constructor sets expected defaults.", function() { const interval = new import__347.TimeInterval(); expect(interval.start).toEqual(new import__347.JulianDate()); expect(interval.stop).toEqual(new import__347.JulianDate()); expect(interval.isStartIncluded).toBe(true); expect(interval.isStopIncluded).toBe(true); expect(interval.data).toBeUndefined(); }); it("Constructor assigns all options.", function() { const start = import__347.JulianDate.now(); const stop = import__347.JulianDate.addDays(start, 1, new import__347.JulianDate()); const isStartIncluded = false; const isStopIncluded = false; const data = {}; const interval = new import__347.TimeInterval({ start, stop, isStartIncluded, isStopIncluded, data }); expect(interval.start).toEqual(start); expect(interval.stop).toEqual(stop); expect(interval.isStartIncluded).toEqual(isStartIncluded); expect(interval.isStopIncluded).toEqual(isStopIncluded); expect(interval.data).toEqual(data); }); it("fromIso8601 assigns expected defaults.", function() { const start = import__347.JulianDate.fromIso8601("2013"); const stop = import__347.JulianDate.fromIso8601("2014"); const interval = import__347.TimeInterval.fromIso8601({ iso8601: "2013/2014" }); expect(interval.start).toEqual(start); expect(interval.stop).toEqual(stop); expect(interval.isStartIncluded).toBe(true); expect(interval.isStopIncluded).toBe(true); expect(interval.data).toBeUndefined(); }); it("fromIso8601 assigns all options.", function() { const start = import__347.JulianDate.fromIso8601("2013"); const stop = import__347.JulianDate.fromIso8601("2014"); const isStartIncluded = false; const isStopIncluded = false; const data = {}; const interval = import__347.TimeInterval.fromIso8601({ iso8601: "2013/2014", isStartIncluded, isStopIncluded, data }); expect(interval.start).toEqual(start); expect(interval.stop).toEqual(stop); expect(interval.isStartIncluded).toEqual(isStartIncluded); expect(interval.isStopIncluded).toEqual(isStopIncluded); expect(interval.data).toEqual(data); }); it("fromIso8601 works with result parameter.", function() { const start = import__347.JulianDate.fromIso8601("2013"); const stop = import__347.JulianDate.fromIso8601("2014"); const isStartIncluded = false; const isStopIncluded = false; const data = {}; const expectedResult = new import__347.TimeInterval(); const interval = import__347.TimeInterval.fromIso8601( { iso8601: "2013/2014", isStartIncluded, isStopIncluded, data }, expectedResult ); expect(expectedResult).toBe(interval); expect(interval.start).toEqual(start); expect(interval.stop).toEqual(stop); expect(interval.isStartIncluded).toEqual(isStartIncluded); expect(interval.isStopIncluded).toEqual(isStopIncluded); expect(interval.data).toEqual(data); }); it("fromIso8601 throws error when given Invalid ISO 8601 date.", function() { expect(function() { import__347.TimeInterval.fromIso8601({ iso8601: "2020-08-29T00:00:00+00:00" }); }).toThrowDeveloperError(); }); it("toIso8601 works", function() { const isoDate1 = "0950-01-02T03:04:05Z"; const isoDate2 = "0950-01-03T03:04:05Z"; const interval = new import__347.TimeInterval({ start: import__347.JulianDate.fromIso8601(isoDate1), stop: import__347.JulianDate.fromIso8601(isoDate2) }); expect(import__347.TimeInterval.toIso8601(interval)).toEqual( "0950-01-02T03:04:05Z/0950-01-03T03:04:05Z" ); }); it("can round-trip with ISO8601", function() { const interval = new import__347.TimeInterval({ start: import__347.JulianDate.now(), stop: import__347.JulianDate.now() }); expect( import__347.TimeInterval.fromIso8601({ iso8601: import__347.TimeInterval.toIso8601(interval) }) ).toEqual(interval); }); it("toIso8601 works with specified precision", function() { const isoDate1 = "0950-01-02T03:04:05.012345Z"; const isoDate2 = "0950-01-03T03:04:05.012345Z"; const interval = new import__347.TimeInterval({ start: import__347.JulianDate.fromIso8601(isoDate1), stop: import__347.JulianDate.fromIso8601(isoDate2) }); expect(import__347.TimeInterval.toIso8601(interval, 0)).toEqual( "0950-01-02T03:04:05Z/0950-01-03T03:04:05Z" ); expect(import__347.TimeInterval.toIso8601(interval, 7)).toEqual( "0950-01-02T03:04:05.0123450Z/0950-01-03T03:04:05.0123450Z" ); }); it("isEmpty is false for a non-empty interval", function() { const interval = new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2) }); expect(interval.isEmpty).toEqual(false); }); it("isEmpty is false for an instantaneous interval closed on both ends", function() { const interval = new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(1) }); expect(interval.isEmpty).toEqual(false); }); it("isEmpty is true for an instantaneous interval open on both ends", function() { const interval = new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(1), isStartIncluded: false, isStopIncluded: false }); expect(interval.isEmpty).toEqual(true); }); it("isEmpty is true for an instantaneous interval open on start", function() { const interval = new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(1), isStartIncluded: false, isStopIncluded: true }); expect(interval.isEmpty).toEqual(true); }); it("isEmpty is true for an instantaneous interval open on stop", function() { const interval = new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(1), isStartIncluded: true, isStopIncluded: false }); expect(interval.isEmpty).toEqual(true); }); it("isEmpty is true for an interval with stop before start", function() { const interval = new import__347.TimeInterval({ start: new import__347.JulianDate(5), stop: new import__347.JulianDate(4) }); expect(interval.isEmpty).toEqual(true); }); it("isEmpty is true for an instantaneous interval only closed on stop end", function() { const interval = new import__347.TimeInterval({ start: new import__347.JulianDate(5), stop: new import__347.JulianDate(5), isStartIncluded: false, isStopIncluded: true }); expect(interval.isEmpty).toEqual(true); }); it("isEmpty is true for an instantaneous interval only closed on start end", function() { const interval = new import__347.TimeInterval({ start: new import__347.JulianDate(5), stop: new import__347.JulianDate(5), isStartIncluded: true, isStopIncluded: false }); expect(interval.isEmpty).toEqual(true); }); it("contains works for a non-empty interval.", function() { const interval = new import__347.TimeInterval({ start: new import__347.JulianDate(2451545), stop: new import__347.JulianDate(2451546) }); expect(import__347.TimeInterval.contains(interval, new import__347.JulianDate(24515455e-1))).toEqual( true ); expect(import__347.TimeInterval.contains(interval, new import__347.JulianDate(24515465e-1))).toEqual( false ); }); it("contains works for an empty interval.", function() { expect(import__347.TimeInterval.contains(import__347.TimeInterval.EMPTY, new import__347.JulianDate())).toEqual( false ); }); it("contains returns true at start and stop times of a closed interval", function() { const interval = new import__347.TimeInterval({ start: new import__347.JulianDate(2451545), stop: new import__347.JulianDate(2451546), isStartIncluded: true, isStopIncluded: true }); expect(import__347.TimeInterval.contains(interval, new import__347.JulianDate(2451545))).toEqual( true ); expect(import__347.TimeInterval.contains(interval, new import__347.JulianDate(2451546))).toEqual( true ); }); it("contains returns false at start and stop times of an open interval", function() { const interval = new import__347.TimeInterval({ start: new import__347.JulianDate(2451545), stop: new import__347.JulianDate(2451546), isStartIncluded: false, isStopIncluded: false }); expect(import__347.TimeInterval.contains(interval, new import__347.JulianDate(2451545))).toEqual( false ); expect(import__347.TimeInterval.contains(interval, new import__347.JulianDate(2451546))).toEqual( false ); }); it("equals and equalsEpsilon work", function() { let left = new import__347.TimeInterval(); let right = new import__347.TimeInterval(); expect(left.equals(right)).toEqual(true); expect(left.equalsEpsilon(right, 0)).toEqual(true); right = new import__347.TimeInterval(); right.start = new import__347.JulianDate(-1); expect(left.equals(right)).toEqual(false); expect(left.equalsEpsilon(right, 0)).toEqual(false); right = new import__347.TimeInterval(); right.stop = new import__347.JulianDate(1); expect(left.equals(right)).toEqual(false); expect(left.equalsEpsilon(right, 0)).toEqual(false); right = new import__347.TimeInterval(); right.isStartIncluded = false; expect(left.equals(right)).toEqual(false); expect(left.equalsEpsilon(right, 0)).toEqual(false); right = new import__347.TimeInterval(); right.isStopIncluded = false; expect(left.equals(right)).toEqual(false); expect(left.equalsEpsilon(right, 0)).toEqual(false); left = new import__347.TimeInterval(); right = new import__347.TimeInterval(); right.data = {}; expect(left.equals(right)).toEqual(false); expect(left.equalsEpsilon(right, 0)).toEqual(false); expect(left.equals(right, returnTrue)).toEqual(true); expect(left.equalsEpsilon(right, 0, returnTrue)).toEqual(true); expect(import__347.TimeInterval.equals(void 0, void 0)).toEqual(true); expect(import__347.TimeInterval.equalsEpsilon(void 0, void 0, 0)).toEqual(true); expect(import__347.TimeInterval.equals(left, void 0)).toEqual(false); expect(import__347.TimeInterval.equalsEpsilon(left, void 0, 0)).toEqual(false); expect(import__347.TimeInterval.equals(void 0, right)).toEqual(false); expect(import__347.TimeInterval.equalsEpsilon(void 0, right, 0)).toEqual(false); }); it("equalsEpsilon works within threshold", function() { const left = new import__347.TimeInterval({ start: new import__347.JulianDate(0), stop: new import__347.JulianDate(1) }); const right = new import__347.TimeInterval({ start: new import__347.JulianDate(0), stop: new import__347.JulianDate(1, 1) }); expect(left.equalsEpsilon(right, 1)).toEqual(true); expect(left.equalsEpsilon(right, 0.99)).toEqual(false); }); it("clone returns an identical interval", function() { const interval = new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2.5), isStartIncluded: true, isStopIncluded: false, data: 12 }); expect(interval.clone()).toEqual(interval); }); it("clone works with a result parameter", function() { const result = new import__347.TimeInterval(); const interval = new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2.5), isStartIncluded: true, isStopIncluded: false, data: 12 }); const returnedResult = interval.clone(result); expect(returnedResult).toBe(result); expect(returnedResult).toEqual(interval); }); it("clone returns undefined when parameter is undefined", function() { expect(import__347.TimeInterval.clone(void 0)).toBeUndefined(); }); it("formats as ISO8601 with toString", function() { const interval = new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2.5) }); expect(interval.toString()).toEqual(import__347.TimeInterval.toIso8601(interval)); }); it("intersect properly intersects with an exhaustive set of cases", function() { const testParameters = [ new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2.5), isStartIncluded: true, isStopIncluded: true }), new import__347.TimeInterval({ start: new import__347.JulianDate(1.5), stop: new import__347.JulianDate(2), isStartIncluded: true, isStopIncluded: true }), new import__347.TimeInterval({ start: new import__347.JulianDate(1.5), stop: new import__347.JulianDate(2), isStartIncluded: true, isStopIncluded: true }), new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2.5), isStartIncluded: true, isStopIncluded: true }), new import__347.TimeInterval({ start: new import__347.JulianDate(3), stop: new import__347.JulianDate(4), isStartIncluded: true, isStopIncluded: true }), new import__347.TimeInterval({ start: new import__347.JulianDate(0), stop: new import__347.JulianDate(0), isStartIncluded: false, isStopIncluded: false }), new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2.5), isStartIncluded: true, isStopIncluded: true }), new import__347.TimeInterval({ start: new import__347.JulianDate(2), stop: new import__347.JulianDate(3), isStartIncluded: true, isStopIncluded: true }), new import__347.TimeInterval({ start: new import__347.JulianDate(2), stop: new import__347.JulianDate(2.5), isStartIncluded: true, isStopIncluded: true }), new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2), isStartIncluded: true, isStopIncluded: true }), new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2), isStartIncluded: false, isStopIncluded: false }), new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2), isStartIncluded: false, isStopIncluded: false }), new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2), isStartIncluded: true, isStopIncluded: false }), new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2), isStartIncluded: false, isStopIncluded: true }), new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2), isStartIncluded: false, isStopIncluded: false }), new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2), isStartIncluded: true, isStopIncluded: false }), new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2), isStartIncluded: true, isStopIncluded: false }), new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2), isStartIncluded: true, isStopIncluded: false }), new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(3), isStartIncluded: false, isStopIncluded: false }), new import__347.TimeInterval({ start: new import__347.JulianDate(2), stop: new import__347.JulianDate(4), isStartIncluded: false, isStopIncluded: false }), new import__347.TimeInterval({ start: new import__347.JulianDate(2), stop: new import__347.JulianDate(3), isStartIncluded: false, isStopIncluded: false }), new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(3), isStartIncluded: false, isStopIncluded: false }), new import__347.TimeInterval({ start: new import__347.JulianDate(2), stop: new import__347.JulianDate(4), isStartIncluded: true, isStopIncluded: true }), new import__347.TimeInterval({ start: new import__347.JulianDate(2), stop: new import__347.JulianDate(3), isStartIncluded: true, isStopIncluded: false }), new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(1), isStartIncluded: false, isStopIncluded: false }), new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2), isStartIncluded: true, isStopIncluded: true }), new import__347.TimeInterval({ start: new import__347.JulianDate(0), stop: new import__347.JulianDate(0), isStartIncluded: false, isStopIncluded: false }), new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(3), isStartIncluded: true, isStopIncluded: true }), new import__347.TimeInterval({ start: new import__347.JulianDate(2), stop: new import__347.JulianDate(3), isStartIncluded: true, isStopIncluded: true }), new import__347.TimeInterval({ start: new import__347.JulianDate(2), stop: new import__347.JulianDate(3), isStartIncluded: true, isStopIncluded: true }), new import__347.TimeInterval({ start: new import__347.JulianDate(3), stop: new import__347.JulianDate(2), isStartIncluded: true, isStopIncluded: true }), new import__347.TimeInterval({ start: new import__347.JulianDate(3), stop: new import__347.JulianDate(3), isStartIncluded: true, isStopIncluded: true }), new import__347.TimeInterval({ start: new import__347.JulianDate(0), stop: new import__347.JulianDate(0), isStartIncluded: false, isStopIncluded: false }) ]; for (let i = 0; i < testParameters.length - 2; i = i + 3) { const first = testParameters[i]; const second = testParameters[i + 1]; const expectedResult = testParameters[i + 2]; const intersect1 = import__347.TimeInterval.intersect( first, second, new import__347.TimeInterval() ); const intersect2 = import__347.TimeInterval.intersect( second, first, new import__347.TimeInterval() ); expect(intersect1).toEqual(intersect2); expect(intersect2).toEqual(intersect1); expect(expectedResult).toEqual(intersect1); } }); it("intersect with undefined results in an empty interval.", function() { const interval = new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(2) }); expect( import__347.TimeInterval.intersect(interval, void 0, new import__347.TimeInterval()) ).toEqual(import__347.TimeInterval.EMPTY); }); it("intersect with a merge callback properly merges data.", function() { const oneToThree = new import__347.TimeInterval({ start: new import__347.JulianDate(1), stop: new import__347.JulianDate(3), data: 2 }); const twoToFour = new import__347.TimeInterval({ start: new import__347.JulianDate(2), stop: new import__347.JulianDate(4), data: 3 }); const twoToThree = import__347.TimeInterval.intersect( oneToThree, twoToFour, new import__347.TimeInterval(), function(left, right) { return left + right; } ); expect(twoToThree.start).toEqual(twoToFour.start); expect(twoToThree.stop).toEqual(oneToThree.stop); expect(twoToThree.isStartIncluded).toEqual(true); expect(twoToThree.isStopIncluded).toEqual(true); expect(twoToThree.data).toEqual(5); }); it("fromIso8601 throws without options object.", function() { expect(function() { import__347.TimeInterval.fromIso8601(void 0); }).toThrowDeveloperError(); }); it("fromIso8601 throws without iso8601.", function() { expect(function() { import__347.TimeInterval.fromIso8601({}); }).toThrowDeveloperError(); }); it("intersect throws without left.", function() { const right = new import__347.TimeInterval(); const result = new import__347.TimeInterval(); expect(function() { import__347.TimeInterval.intersect(void 0, right, result); }).toThrowDeveloperError(); }); it("contains throws without interval.", function() { const date = new import__347.JulianDate(); expect(function() { import__347.TimeInterval.contains(void 0, date); }).toThrowDeveloperError(); }); it("contains throws without date.", function() { const timeInterval = new import__347.TimeInterval(); expect(function() { import__347.TimeInterval.contains(timeInterval, void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/TipsifySpec.js var import__348 = __toESM(require_Cesium(), 1); describe("Core/Tipsify", function() { it("can calculate the ACMR", function() { expect( import__348.Tipsify.calculateACMR({ indices: [0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 5, 6, 0, 1, 6], maximumIndex: 6, cacheSize: 3 }) ).toEqual(2); }); it("can calculate the ACMR without a specified maximum index", function() { expect( import__348.Tipsify.calculateACMR({ indices: [0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 5, 6, 0, 1, 6], cacheSize: 3 }) ).toEqual(2); }); it("throws when calculating ACMR (1 of 4)", function() { expect(function() { import__348.Tipsify.calculateACMR({ indices: void 0, maximumIndex: 1, cacheSize: 3 }); }).toThrowDeveloperError(); }); it("throws when calculating ACMR (2 of 4)", function() { expect(function() { import__348.Tipsify.calculateACMR({ indices: [1, 2, 3, 4], maximumIndex: 1, cacheSize: 3 }); }).toThrowDeveloperError(); }); it("throws when calculating ACMR (3 of 4)", function() { expect(function() { import__348.Tipsify.calculateACMR({ indices: [0, 1, 2], maximumIndex: -1, cacheSize: 2 }); }).toThrowDeveloperError(); }); it("throws when calculating ACMR (4 of 4)", function() { expect(function() { import__348.Tipsify.calculateACMR({ indices: [0, 1, 2], maximumIndex: 2, cacheSize: 2 }); }).toThrowDeveloperError(); }); it("throws when executing Tipsify (1 of 5)", function() { expect(function() { import__348.Tipsify.tipsify({ indices: void 0, maximumIndex: 1, cacheSize: 3 }); }).toThrowDeveloperError(); }); it("throws when executing Tipsify (2 of 5)", function() { expect(function() { import__348.Tipsify.tipsify({ indices: [1, 2, 3, 4], maximumIndex: 1, cacheSize: 3 }); }).toThrowDeveloperError(); }); it("throws when executing Tipsify (3 of 5)", function() { expect(function() { import__348.Tipsify.tipsify({ indices: [1, 2, 3], maximumIndex: -1, cacheSize: 3 }); }).toThrowDeveloperError(); }); it("throws when executing Tipsify (4 of 5)", function() { expect(function() { import__348.Tipsify.tipsify({ indices: [0, 1, 2], maximumIndex: 2, cacheSize: 2 }); }).toThrowDeveloperError(); }); it("throws when executing Tipsify (5 of 5)", function() { expect(function() { import__348.Tipsify.tipsify(); }).toThrowDeveloperError(); }); it("can lower ACMR using the Tipsify algorithm", function() { const indices = [ 0, 1, 7, 1, 7, 8, 1, 2, 8, 2, 8, 9, 2, 3, 9, 3, 9, 10, 3, 4, 10, 4, 10, 11, 4, 5, 11, 5, 11, 12, 6, 13, 14, 6, 7, 14, 7, 14, 15, 7, 8, 15, 8, 15, 16, 8, 9, 16, 9, 16, 17, 9, 10, 17, 10, 17, 18, 10, 11, 18, 11, 18, 19, 11, 12, 19, 12, 19, 20, 13, 21, 22, 13, 14, 22, 14, 22, 23, 14, 15, 23, 15, 23, 24, 15, 16, 24, 16, 24, 25, 16, 17, 25, 17, 25, 26, 17, 18, 26, 18, 26, 27, 18, 19, 27, 19, 27, 28, 19, 20, 28 ]; const acmrBefore = import__348.Tipsify.calculateACMR({ indices, maximumIndex: 28, cacheSize: 6 }); const result = import__348.Tipsify.tipsify({ indices, maximumIndex: 28, cacheSize: 6 }); const acmrAfter = import__348.Tipsify.calculateACMR({ indices: result, maximumIndex: 28, cacheSize: 6 }); expect(acmrAfter).toBeLessThan(acmrBefore); }); it("can Tipsify without knowing the maximum index", function() { const indices = [ 0, 1, 7, 1, 7, 8, 1, 2, 8, 2, 8, 9, 2, 3, 9, 3, 9, 10, 3, 4, 10, 4, 10, 11, 4, 5, 11, 5, 11, 12, 6, 13, 14, 6, 7, 14, 7, 14, 15, 7, 8, 15, 8, 15, 16, 8, 9, 16, 9, 16, 17, 9, 10, 17, 10, 17, 18, 10, 11, 18, 11, 18, 19, 11, 12, 19, 12, 19, 20, 13, 21, 22, 13, 14, 22, 14, 22, 23, 14, 15, 23, 15, 23, 24, 15, 16, 24, 16, 24, 25, 16, 17, 25, 17, 25, 26, 17, 18, 26, 18, 26, 27, 18, 19, 27, 19, 27, 28, 19, 20, 28 ]; expect(import__348.Tipsify.tipsify({ indices, cacheSize: 6 })).toEqual( import__348.Tipsify.tipsify({ indices, maximumIndex: 28, cacheSize: 6 }) ); }); }); // packages/engine/Specs/Core/TransformsSpec.js var import__349 = __toESM(require_Cesium(), 1); var import__350 = __toESM(require_Cesium(), 1); describe("Core/Transforms", function() { const negativeX = new import__349.Cartesian4(-1, 0, 0, 0); const negativeY = new import__349.Cartesian4(0, -1, 0, 0); const negativeZ = new import__349.Cartesian4(0, 0, -1, 0); it("eastNorthUpToFixedFrame works without a result parameter", function() { const origin = new import__349.Cartesian3(1, 0, 0); const expectedTranslation = new import__349.Cartesian4( origin.x, origin.y, origin.z, 1 ); const returnedResult = import__349.Transforms.eastNorthUpToFixedFrame( origin, import__349.Ellipsoid.UNIT_SPHERE ); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Y ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Z ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_X ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("eastNorthUpToFixedFrame works with a result parameter", function() { const origin = new import__349.Cartesian3(1, 0, 0); const expectedTranslation = new import__349.Cartesian4( origin.x, origin.y, origin.z, 1 ); const result = new import__349.Matrix4(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2); const returnedResult = import__349.Transforms.eastNorthUpToFixedFrame( origin, import__349.Ellipsoid.UNIT_SPHERE, result ); expect(result).toBe(returnedResult); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Y ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Z ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_X ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("eastNorthUpToFixedFrame works at the north pole", function() { const northPole = new import__349.Cartesian3(0, 0, 1); const expectedTranslation = new import__349.Cartesian4( northPole.x, northPole.y, northPole.z, 1 ); const result = new import__349.Matrix4(); const returnedResult = import__349.Transforms.eastNorthUpToFixedFrame( northPole, import__349.Ellipsoid.UNIT_SPHERE, result ); expect(returnedResult).toBe(result); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Y ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( negativeX ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Z ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("eastNorthUpToFixedFrame works at the south pole", function() { const southPole = new import__349.Cartesian3(0, 0, -1); const expectedTranslation = new import__349.Cartesian4( southPole.x, southPole.y, southPole.z, 1 ); const returnedResult = import__349.Transforms.eastNorthUpToFixedFrame( southPole, import__349.Ellipsoid.UNIT_SPHERE ); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Y ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_X ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( negativeZ ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("eastNorthUpToFixedFrame works at the origin", function() { const origin = import__349.Cartesian3.ZERO; const expectedTranslation = new import__349.Cartesian4(0, 0, 0, 1); const returnedResult = import__349.Transforms.eastNorthUpToFixedFrame( origin, import__349.Ellipsoid.WGS84 ); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Y ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( negativeX ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Z ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("northEastDownToFixedFrame works without a result parameter", function() { const origin = new import__349.Cartesian3(1, 0, 0); const expectedTranslation = new import__349.Cartesian4( origin.x, origin.y, origin.z, 1 ); const returnedResult = import__349.Transforms.northEastDownToFixedFrame( origin, import__349.Ellipsoid.UNIT_SPHERE ); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Z ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Y ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( negativeX ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("northEastDownToFixedFrame works with a result parameter", function() { const origin = new import__349.Cartesian3(1, 0, 0); const expectedTranslation = new import__349.Cartesian4( origin.x, origin.y, origin.z, 1 ); const result = new import__349.Matrix4(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2); const returnedResult = import__349.Transforms.northEastDownToFixedFrame( origin, import__349.Ellipsoid.UNIT_SPHERE, result ); expect(result).toBe(returnedResult); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Z ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Y ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( negativeX ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("northEastDownToFixedFrame works at the north pole", function() { const northPole = new import__349.Cartesian3(0, 0, 1); const expectedTranslation = new import__349.Cartesian4( northPole.x, northPole.y, northPole.z, 1 ); const result = new import__349.Matrix4(); const returnedResult = import__349.Transforms.northEastDownToFixedFrame( northPole, import__349.Ellipsoid.UNIT_SPHERE, result ); expect(returnedResult).toBe(result); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( negativeX ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Y ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( negativeZ ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("northEastDownToFixedFrame works at the south pole", function() { const southPole = new import__349.Cartesian3(0, 0, -1); const expectedTranslation = new import__349.Cartesian4( southPole.x, southPole.y, southPole.z, 1 ); const returnedResult = import__349.Transforms.northEastDownToFixedFrame( southPole, import__349.Ellipsoid.UNIT_SPHERE ); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_X ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Y ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Z ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("northEastDownToFixedFrame works at the origin", function() { const origin = import__349.Cartesian3.ZERO; const expectedTranslation = new import__349.Cartesian4(0, 0, 0, 1); const returnedResult = import__349.Transforms.northEastDownToFixedFrame( origin, import__349.Ellipsoid.UNIT_SPHERE ); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( negativeX ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Y ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( negativeZ ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("northUpEastToFixedFrame works without a result parameter", function() { const origin = new import__349.Cartesian3(1, 0, 0); const expectedTranslation = new import__349.Cartesian4( origin.x, origin.y, origin.z, 1 ); const returnedResult = import__349.Transforms.northUpEastToFixedFrame( origin, import__349.Ellipsoid.UNIT_SPHERE ); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Z ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_X ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Y ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("northUpEastToFixedFrame works with a result parameter", function() { const origin = new import__349.Cartesian3(1, 0, 0); const expectedTranslation = new import__349.Cartesian4( origin.x, origin.y, origin.z, 1 ); const result = new import__349.Matrix4(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2); const returnedResult = import__349.Transforms.northUpEastToFixedFrame( origin, import__349.Ellipsoid.UNIT_SPHERE, result ); expect(result).toBe(returnedResult); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Z ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_X ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Y ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("northUpEastToFixedFrame works at the north pole", function() { const northPole = new import__349.Cartesian3(0, 0, 1); const expectedTranslation = new import__349.Cartesian4( northPole.x, northPole.y, northPole.z, 1 ); const result = new import__349.Matrix4(); const returnedResult = import__349.Transforms.northUpEastToFixedFrame( northPole, import__349.Ellipsoid.UNIT_SPHERE, result ); expect(returnedResult).toBe(result); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( negativeX ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Z ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Y ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("northUpEastToFixedFrame works at the south pole", function() { const southPole = new import__349.Cartesian3(0, 0, -1); const expectedTranslation = new import__349.Cartesian4( southPole.x, southPole.y, southPole.z, 1 ); const returnedResult = import__349.Transforms.northUpEastToFixedFrame( southPole, import__349.Ellipsoid.UNIT_SPHERE ); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_X ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( negativeZ ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Y ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("northUpEastToFixedFrame works at the origin", function() { const origin = import__349.Cartesian3.ZERO; const expectedTranslation = new import__349.Cartesian4(0, 0, 0, 1); const returnedResult = import__349.Transforms.northUpEastToFixedFrame( origin, import__349.Ellipsoid.UNIT_SPHERE ); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( negativeX ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Z ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Y ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("northWestUpToFixedFrame works without a result parameter", function() { const origin = new import__349.Cartesian3(1, 0, 0); const expectedTranslation = new import__349.Cartesian4( origin.x, origin.y, origin.z, 1 ); const returnedResult = import__349.Transforms.northWestUpToFixedFrame( origin, import__349.Ellipsoid.UNIT_SPHERE ); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Z ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( negativeY ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_X ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("northWestUpToFixedFrame works with a result parameter", function() { const origin = new import__349.Cartesian3(1, 0, 0); const expectedTranslation = new import__349.Cartesian4( origin.x, origin.y, origin.z, 1 ); const result = new import__349.Matrix4(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2); const returnedResult = import__349.Transforms.northWestUpToFixedFrame( origin, import__349.Ellipsoid.UNIT_SPHERE, result ); expect(result).toBe(returnedResult); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Z ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( negativeY ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_X ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("northWestUpToFixedFrame works at the north pole", function() { const northPole = new import__349.Cartesian3(0, 0, 1); const expectedTranslation = new import__349.Cartesian4( northPole.x, northPole.y, northPole.z, 1 ); const result = new import__349.Matrix4(); const returnedResult = import__349.Transforms.northWestUpToFixedFrame( northPole, import__349.Ellipsoid.UNIT_SPHERE, result ); expect(returnedResult).toBe(result); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( negativeX ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( negativeY ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Z ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("northWestUpToFixedFrame works at the south pole", function() { const southPole = new import__349.Cartesian3(0, 0, -1); const expectedTranslation = new import__349.Cartesian4( southPole.x, southPole.y, southPole.z, 1 ); const returnedResult = import__349.Transforms.northWestUpToFixedFrame( southPole, import__349.Ellipsoid.UNIT_SPHERE ); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_X ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( negativeY ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( negativeZ ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("northWestUpToFixedFrame works at the origin", function() { const origin = import__349.Cartesian3.ZERO; const expectedTranslation = new import__349.Cartesian4(0, 0, 0, 1); const returnedResult = import__349.Transforms.northWestUpToFixedFrame( origin, import__349.Ellipsoid.UNIT_SPHERE ); expect(import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4())).toEqual( negativeX ); expect(import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4())).toEqual( negativeY ); expect(import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4())).toEqual( import__349.Cartesian4.UNIT_Z ); expect(import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4())).toEqual( expectedTranslation ); }); it("normal use of localFrameToFixedFrameGenerator", function() { const cartesianTab = [ new import__349.Cartesian3(0, 0, 1), new import__349.Cartesian3(0, 0, -1), new import__349.Cartesian3(10, 20, 30), new import__349.Cartesian3(-10, -20, -30), new import__349.Cartesian3(-25, 60, -1), new import__349.Cartesian3(9, 0, -7) ]; const converterTab = [ { converter: import__349.Transforms.localFrameToFixedFrameGenerator("north", "east"), order: ["north", "east", "down"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("north", "west"), order: ["north", "west", "up"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("north", "up"), order: ["north", "up", "east"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("north", "down"), order: ["north", "down", "west"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("south", "east"), order: ["south", "east", "up"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("south", "west"), order: ["south", "west", "down"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("south", "up"), order: ["south", "up", "west"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("south", "down"), order: ["south", "down", "east"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("east", "north"), order: ["east", "north", "up"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("east", "south"), order: ["east", "south", "down"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("east", "up"), order: ["east", "up", "south"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("east", "down"), order: ["east", "down", "north"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("west", "north"), order: ["west", "north", "down"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("west", "south"), order: ["west", "south", "up"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("west", "up"), order: ["west", "up", "north"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("west", "down"), order: ["west", "down", "south"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("up", "north"), order: ["up", "north", "west"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("up", "south"), order: ["up", "south", "east"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("up", "east"), order: ["up", "east", "north"] }, { converter: import__349.Transforms.localFrameToFixedFrameGenerator("up", "west"), order: ["up", "west", "south"] } ]; function testAllLocalFrame(classicalENUMatrix, position) { const ENUColumn = new import__349.Cartesian4(); const converterColumn = new import__349.Cartesian4(); for (let i = 0; i < converterTab.length; i++) { const converterMatrix = converterTab[i].converter( position, import__349.Ellipsoid.UNIT_SPHERE ); const order = converterTab[i].order; import__349.Matrix4.getColumn(classicalENUMatrix, 3, ENUColumn); import__349.Matrix4.getColumn(converterMatrix, 3, converterColumn); expect(ENUColumn).toEqual(converterColumn); for (let j = 0; j < 3; j++) { import__349.Matrix4.getColumn(converterMatrix, j, converterColumn); const axisName = order[j]; if (axisName === "east") { import__349.Matrix4.getColumn(classicalENUMatrix, 0, ENUColumn); } else if (axisName === "west") { import__349.Matrix4.getColumn(classicalENUMatrix, 0, ENUColumn); import__349.Cartesian4.negate(ENUColumn, ENUColumn); } else if (axisName === "north") { import__349.Matrix4.getColumn(classicalENUMatrix, 1, ENUColumn); } else if (axisName === "south") { import__349.Matrix4.getColumn(classicalENUMatrix, 1, ENUColumn); import__349.Cartesian4.negate(ENUColumn, ENUColumn); } else if (axisName === "up") { import__349.Matrix4.getColumn(classicalENUMatrix, 2, ENUColumn); } else if (axisName === "down") { import__349.Matrix4.getColumn(classicalENUMatrix, 2, ENUColumn); import__349.Cartesian4.negate(ENUColumn, ENUColumn); } expect(ENUColumn).toEqual(converterColumn); } } } for (let i = 0; i < cartesianTab.length; i++) { const cartesian = cartesianTab[i]; const classicalEastNorthUpReferential = import__349.Transforms.eastNorthUpToFixedFrame( cartesian, import__349.Ellipsoid.UNIT_SPHERE ); testAllLocalFrame(classicalEastNorthUpReferential, cartesian); } }); it("abnormal use of localFrameToFixedFrameGenerator", function() { function checkDeveloperError(firstAxis, secondAxis) { expect(function() { import__349.Transforms.localFrameToFixedFrameGenerator(firstAxis, secondAxis); }).toThrowDeveloperError(); } checkDeveloperError(void 0, void 0); checkDeveloperError("north", void 0); checkDeveloperError(void 0, "north"); checkDeveloperError("south", void 0); checkDeveloperError("northe", "southe"); checkDeveloperError("north", "north"); checkDeveloperError("north", "south"); checkDeveloperError("south", "north"); checkDeveloperError("south", "south"); checkDeveloperError("up", "up"); checkDeveloperError("up", "down"); checkDeveloperError("down", "up"); checkDeveloperError("down", "down"); checkDeveloperError("east", "east"); checkDeveloperError("east", "west"); checkDeveloperError("west", "east"); checkDeveloperError("west", "west"); }); it("headingPitchRollToFixedFrame works without a result parameter", function() { const origin = new import__349.Cartesian3(1, 0, 0); const heading = import__350.Math.toRadians(20); const pitch = import__350.Math.toRadians(30); const roll = import__350.Math.toRadians(40); const hpr = new import__349.HeadingPitchRoll(heading, pitch, roll); const expectedRotation = import__349.Matrix3.fromQuaternion( import__349.Quaternion.fromHeadingPitchRoll(hpr) ); const expectedX = import__349.Matrix3.getColumn(expectedRotation, 0, new import__349.Cartesian3()); const expectedY = import__349.Matrix3.getColumn(expectedRotation, 1, new import__349.Cartesian3()); const expectedZ = import__349.Matrix3.getColumn(expectedRotation, 2, new import__349.Cartesian3()); import__349.Cartesian3.fromElements(expectedX.z, expectedX.x, expectedX.y, expectedX); import__349.Cartesian3.fromElements(expectedY.z, expectedY.x, expectedY.y, expectedY); import__349.Cartesian3.fromElements(expectedZ.z, expectedZ.x, expectedZ.y, expectedZ); const returnedResult = import__349.Transforms.headingPitchRollToFixedFrame( origin, hpr, import__349.Ellipsoid.UNIT_SPHERE ); const actualX = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4()) ); const actualY = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4()) ); const actualZ = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4()) ); const actualTranslation = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4()) ); expect(actualX).toEqual(expectedX); expect(actualY).toEqual(expectedY); expect(actualZ).toEqual(expectedZ); expect(actualTranslation).toEqual(origin); }); it("headingPitchRollToFixedFrame works with a HeadingPitchRoll object and without a result parameter and a fixedFrameTransform", function() { const origin = new import__349.Cartesian3(1, 0, 0); const heading = import__350.Math.toRadians(20); const pitch = import__350.Math.toRadians(30); const roll = import__350.Math.toRadians(40); const hpr = new import__349.HeadingPitchRoll(heading, pitch, roll); const expectedRotation = import__349.Matrix3.fromQuaternion( import__349.Quaternion.fromHeadingPitchRoll(hpr) ); const expectedX = import__349.Matrix3.getColumn(expectedRotation, 0, new import__349.Cartesian3()); const expectedY = import__349.Matrix3.getColumn(expectedRotation, 1, new import__349.Cartesian3()); const expectedZ = import__349.Matrix3.getColumn(expectedRotation, 2, new import__349.Cartesian3()); import__349.Cartesian3.fromElements(expectedX.z, expectedX.x, expectedX.y, expectedX); import__349.Cartesian3.fromElements(expectedY.z, expectedY.x, expectedY.y, expectedY); import__349.Cartesian3.fromElements(expectedZ.z, expectedZ.x, expectedZ.y, expectedZ); const returnedResult = import__349.Transforms.headingPitchRollToFixedFrame( origin, hpr, import__349.Ellipsoid.UNIT_SPHERE ); const actualX = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4()) ); const actualY = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4()) ); const actualZ = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4()) ); const actualTranslation = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4()) ); expect(actualX).toEqual(expectedX); expect(actualY).toEqual(expectedY); expect(actualZ).toEqual(expectedZ); expect(actualTranslation).toEqual(origin); }); it("headingPitchRollToFixedFrame works with a HeadingPitchRoll object and without a result parameter", function() { const origin = new import__349.Cartesian3(1, 0, 0); const heading = import__350.Math.toRadians(20); const pitch = import__350.Math.toRadians(30); const roll = import__350.Math.toRadians(40); const hpr = new import__349.HeadingPitchRoll(heading, pitch, roll); const expectedRotation = import__349.Matrix3.fromQuaternion( import__349.Quaternion.fromHeadingPitchRoll(hpr) ); const expectedX = import__349.Matrix3.getColumn(expectedRotation, 0, new import__349.Cartesian3()); const expectedY = import__349.Matrix3.getColumn(expectedRotation, 1, new import__349.Cartesian3()); const expectedZ = import__349.Matrix3.getColumn(expectedRotation, 2, new import__349.Cartesian3()); import__349.Cartesian3.fromElements(expectedX.z, expectedX.x, expectedX.y, expectedX); import__349.Cartesian3.fromElements(expectedY.z, expectedY.x, expectedY.y, expectedY); import__349.Cartesian3.fromElements(expectedZ.z, expectedZ.x, expectedZ.y, expectedZ); const returnedResult = import__349.Transforms.headingPitchRollToFixedFrame( origin, hpr, import__349.Ellipsoid.UNIT_SPHERE, import__349.Transforms.eastNorthUpToFixedFrame ); const actualX = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4()) ); const actualY = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4()) ); const actualZ = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4()) ); const actualTranslation = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4()) ); expect(actualX).toEqual(expectedX); expect(actualY).toEqual(expectedY); expect(actualZ).toEqual(expectedZ); expect(actualTranslation).toEqual(origin); }); it("headingPitchRollToFixedFrame works with a result parameter", function() { const origin = new import__349.Cartesian3(1, 0, 0); const heading = import__350.Math.toRadians(20); const pitch = import__350.Math.toRadians(30); const roll = import__350.Math.toRadians(40); const hpr = new import__349.HeadingPitchRoll(heading, pitch, roll); const expectedRotation = import__349.Matrix3.fromQuaternion( import__349.Quaternion.fromHeadingPitchRoll(hpr) ); const expectedX = import__349.Matrix3.getColumn(expectedRotation, 0, new import__349.Cartesian3()); const expectedY = import__349.Matrix3.getColumn(expectedRotation, 1, new import__349.Cartesian3()); const expectedZ = import__349.Matrix3.getColumn(expectedRotation, 2, new import__349.Cartesian3()); import__349.Cartesian3.fromElements(expectedX.z, expectedX.x, expectedX.y, expectedX); import__349.Cartesian3.fromElements(expectedY.z, expectedY.x, expectedY.y, expectedY); import__349.Cartesian3.fromElements(expectedZ.z, expectedZ.x, expectedZ.y, expectedZ); const result = new import__349.Matrix4(); const returnedResult = import__349.Transforms.headingPitchRollToFixedFrame( origin, hpr, import__349.Ellipsoid.UNIT_SPHERE, import__349.Transforms.eastNorthUpToFixedFrame, result ); const actualX = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4()) ); const actualY = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4()) ); const actualZ = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4()) ); const actualTranslation = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4()) ); expect(returnedResult).toBe(result); expect(actualX).toEqual(expectedX); expect(actualY).toEqual(expectedY); expect(actualZ).toEqual(expectedZ); expect(actualTranslation).toEqual(origin); }); it("headingPitchRollToFixedFrame works with a custom fixedFrameTransform", function() { const origin = new import__349.Cartesian3(1, 0, 0); const heading = import__350.Math.toRadians(20); const pitch = import__350.Math.toRadians(30); const roll = import__350.Math.toRadians(40); const hpr = new import__349.HeadingPitchRoll(heading, pitch, roll); const expectedRotation = import__349.Matrix3.fromQuaternion( import__349.Quaternion.fromHeadingPitchRoll(hpr) ); const expectedEast = import__349.Matrix3.getColumn( expectedRotation, 0, new import__349.Cartesian3() ); const expectedNorth = import__349.Matrix3.getColumn( expectedRotation, 1, new import__349.Cartesian3() ); const expectedUp = import__349.Matrix3.getColumn(expectedRotation, 2, new import__349.Cartesian3()); import__349.Cartesian3.fromElements( expectedEast.z, expectedEast.x, expectedEast.y, expectedEast ); import__349.Cartesian3.fromElements( expectedNorth.z, expectedNorth.x, expectedNorth.y, expectedNorth ); import__349.Cartesian3.fromElements( expectedUp.z, expectedUp.x, expectedUp.y, expectedUp ); const result = new import__349.Matrix4(); let returnedResult = import__349.Transforms.headingPitchRollToFixedFrame( origin, hpr, import__349.Ellipsoid.UNIT_SPHERE, import__349.Transforms.eastNorthUpToFixedFrame, result ); let actualEast = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4()) ); let actualNorth = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4()) ); let actualUp = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4()) ); let actualTranslation = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4()) ); expect(returnedResult).toBe(result); expect(actualEast).toEqual(expectedEast); expect(actualNorth).toEqual(expectedNorth); expect(actualUp).toEqual(expectedUp); expect(actualTranslation).toEqual(origin); const UNEFixedFrameConverter = import__349.Transforms.localFrameToFixedFrameGenerator( "west", "south" ); returnedResult = import__349.Transforms.headingPitchRollToFixedFrame( origin, hpr, import__349.Ellipsoid.UNIT_SPHERE, UNEFixedFrameConverter, result ); actualEast = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 0, new import__349.Cartesian4()) ); actualEast.y = -actualEast.y; actualEast.z = -actualEast.z; actualNorth = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 1, new import__349.Cartesian4()) ); actualNorth.y = -actualNorth.y; actualNorth.z = -actualNorth.z; actualUp = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 2, new import__349.Cartesian4()) ); actualUp.y = -actualUp.y; actualUp.z = -actualUp.z; actualTranslation = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(returnedResult, 3, new import__349.Cartesian4()) ); expect(returnedResult).toBe(result); expect(actualEast).toEqual(expectedEast); expect(actualNorth).toEqual(expectedNorth); expect(actualUp).toEqual(expectedUp); expect(actualTranslation).toEqual(origin); }); it("headingPitchRollQuaternion works without a result parameter", function() { const origin = new import__349.Cartesian3(1, 0, 0); const heading = import__350.Math.toRadians(20); const pitch = import__350.Math.toRadians(30); const roll = import__350.Math.toRadians(40); const hpr = new import__349.HeadingPitchRoll(heading, pitch, roll); const transform = import__349.Transforms.headingPitchRollToFixedFrame( origin, hpr, import__349.Ellipsoid.UNIT_SPHERE ); const expected = import__349.Matrix4.getMatrix3(transform, new import__349.Matrix3()); const quaternion = import__349.Transforms.headingPitchRollQuaternion( origin, hpr, import__349.Ellipsoid.UNIT_SPHERE, import__349.Transforms.eastNorthUpToFixedFrame ); const actual = import__349.Matrix3.fromQuaternion(quaternion); expect(actual).toEqualEpsilon(expected, import__350.Math.EPSILON11); }); it("headingPitchRollQuaternion works with a result parameter", function() { const origin = new import__349.Cartesian3(1, 0, 0); const heading = import__350.Math.toRadians(20); const pitch = import__350.Math.toRadians(30); const roll = import__350.Math.toRadians(40); const hpr = new import__349.HeadingPitchRoll(heading, pitch, roll); const transform = import__349.Transforms.headingPitchRollToFixedFrame( origin, hpr, import__349.Ellipsoid.UNIT_SPHERE ); const expected = import__349.Matrix4.getMatrix3(transform, new import__349.Matrix3()); const result = new import__349.Quaternion(); const quaternion = import__349.Transforms.headingPitchRollQuaternion( origin, hpr, import__349.Ellipsoid.UNIT_SPHERE, import__349.Transforms.eastNorthUpToFixedFrame, result ); const actual = import__349.Matrix3.fromQuaternion(quaternion); expect(quaternion).toBe(result); expect(actual).toEqualEpsilon(expected, import__350.Math.EPSILON11); }); it("headingPitchRollQuaternion works without a custom fixedFrameTransform", function() { const origin = new import__349.Cartesian3(1, 0, 0); const heading = import__350.Math.toRadians(20); const pitch = import__350.Math.toRadians(30); const roll = import__350.Math.toRadians(40); const hpr = new import__349.HeadingPitchRoll(heading, pitch, roll); const transform = import__349.Transforms.headingPitchRollToFixedFrame( origin, hpr, import__349.Ellipsoid.UNIT_SPHERE ); const expected = import__349.Matrix4.getMatrix3(transform, new import__349.Matrix3()); const result = new import__349.Quaternion(); const quaternion = import__349.Transforms.headingPitchRollQuaternion( origin, hpr, import__349.Ellipsoid.UNIT_SPHERE, void 0, result ); const actual = import__349.Matrix3.fromQuaternion(quaternion); expect(quaternion).toBe(result); expect(actual).toEqualEpsilon(expected, import__350.Math.EPSILON11); }); it("headingPitchRollQuaternion works with a custom fixedFrameTransform", function() { const origin = new import__349.Cartesian3(1, 0, 0); const heading = import__350.Math.toRadians(20); const pitch = import__350.Math.toRadians(30); const roll = import__350.Math.toRadians(40); const hpr = new import__349.HeadingPitchRoll(heading, pitch, roll); const fixedFrameTransform = import__349.Transforms.localFrameToFixedFrameGenerator( "west", "south" ); const transform = import__349.Transforms.headingPitchRollToFixedFrame( origin, hpr, import__349.Ellipsoid.UNIT_SPHERE, fixedFrameTransform ); const expected = import__349.Matrix4.getMatrix3(transform, new import__349.Matrix3()); const result = new import__349.Quaternion(); const quaternion = import__349.Transforms.headingPitchRollQuaternion( origin, hpr, import__349.Ellipsoid.UNIT_SPHERE, fixedFrameTransform, result ); const actual = import__349.Matrix3.fromQuaternion(quaternion); expect(quaternion).toBe(result); expect(actual).toEqualEpsilon(expected, import__350.Math.EPSILON11); }); it("computeTemeToPseudoFixedMatrix works before noon", function() { let time2 = import__349.JulianDate.fromDate(/* @__PURE__ */ new Date("June 29, 2015 12:00:00 UTC")); const t = import__349.Transforms.computeTemeToPseudoFixedMatrix(time2); const det = t[0] * t[4] * t[8] + t[3] * t[7] * t[2] + t[6] * t[1] * t[5] - t[6] * t[4] * t[2] - t[3] * t[1] * t[8] - t[0] * t[7] * t[5]; expect(det).toEqualEpsilon(1, import__350.Math.EPSILON14); const t4 = import__349.Matrix4.fromRotationTranslation( t, import__349.Cartesian3.ZERO, new import__349.Matrix4() ); expect(import__349.Matrix4.inverse(t4, new import__349.Matrix4())).toEqualEpsilon( import__349.Matrix4.inverseTransformation(t4, new import__349.Matrix4()), import__350.Math.EPSILON14 ); time2 = import__349.JulianDate.addHours(time2, 23.93447, new import__349.JulianDate()); const u = import__349.Transforms.computeTemeToPseudoFixedMatrix(time2); const tAngle = import__349.Quaternion.computeAngle(import__349.Quaternion.fromRotationMatrix(t)); const uAngle = import__349.Quaternion.computeAngle(import__349.Quaternion.fromRotationMatrix(u)); expect(tAngle).toEqualEpsilon(uAngle, import__350.Math.EPSILON6); }); it("computeTemeToPseudoFixedMatrix works after noon", function() { let time2 = import__349.JulianDate.fromDate(/* @__PURE__ */ new Date("June 29, 2015 12:00:00 UTC")); const t = import__349.Transforms.computeTemeToPseudoFixedMatrix(time2); const det = t[0] * t[4] * t[8] + t[3] * t[7] * t[2] + t[6] * t[1] * t[5] - t[6] * t[4] * t[2] - t[3] * t[1] * t[8] - t[0] * t[7] * t[5]; expect(det).toEqualEpsilon(1, import__350.Math.EPSILON14); const t4 = import__349.Matrix4.fromRotationTranslation(t); expect(import__349.Matrix4.inverse(t4, new import__349.Matrix4())).toEqualEpsilon( import__349.Matrix4.inverseTransformation(t4, new import__349.Matrix4()), import__350.Math.EPSILON14 ); time2 = import__349.JulianDate.addHours(time2, 23.93447, new import__349.JulianDate()); const u = import__349.Transforms.computeTemeToPseudoFixedMatrix(time2); const tAngle = import__349.Quaternion.computeAngle(import__349.Quaternion.fromRotationMatrix(t)); const uAngle = import__349.Quaternion.computeAngle(import__349.Quaternion.fromRotationMatrix(u)); expect(tAngle).toEqualEpsilon(uAngle, import__350.Math.EPSILON6); }); it("computeTemeToPseudoFixedMatrix works with a result parameter", function() { let time2 = import__349.JulianDate.fromDate(/* @__PURE__ */ new Date("June 29, 2015 12:00:00 UTC")); const resultT = new import__349.Matrix3(); const t = import__349.Transforms.computeTemeToPseudoFixedMatrix(time2, resultT); expect(t).toBe(resultT); const det = t[0] * t[4] * t[8] + t[3] * t[7] * t[2] + t[6] * t[1] * t[5] - t[6] * t[4] * t[2] - t[3] * t[1] * t[8] - t[0] * t[7] * t[5]; expect(det).toEqualEpsilon(1, import__350.Math.EPSILON14); const t4 = import__349.Matrix4.fromRotationTranslation(t); expect(import__349.Matrix4.inverse(t4, new import__349.Matrix4())).toEqualEpsilon( import__349.Matrix4.inverseTransformation(t4, new import__349.Matrix4()), import__350.Math.EPSILON14 ); time2 = import__349.JulianDate.addHours(time2, 23.93447, new import__349.JulianDate()); const resultU = new import__349.Matrix3(); const u = import__349.Transforms.computeTemeToPseudoFixedMatrix(time2, resultU); expect(u).toBe(resultU); const tAngle = import__349.Quaternion.computeAngle(import__349.Quaternion.fromRotationMatrix(t)); const uAngle = import__349.Quaternion.computeAngle(import__349.Quaternion.fromRotationMatrix(u)); expect(tAngle).toEqualEpsilon(uAngle, import__350.Math.EPSILON6); }); describe("computeIcrfToFixedMatrix", function() { async function preloadTransformationData(start, stop, eopUrl) { if ((0, import__349.defined)(eopUrl)) { import__349.Transforms.earthOrientationParameters = await import__349.EarthOrientationParameters.fromUrl( eopUrl ); } import__349.Transforms.iau2006XysData = new import__349.Iau2006XysData(); const preloadInterval = new import__349.TimeInterval({ start, stop }); await import__349.Transforms.preloadIcrfFixed(preloadInterval); } it("throws if the date parameter is not specified", function() { expect(function() { import__349.Transforms.computeIcrfToFixedMatrix(void 0); }).toThrowDeveloperError(); expect(function() { import__349.Transforms.computeFixedToIcrfMatrix(void 0); }).toThrowDeveloperError(); }); it("works with data from STK Components", async function() { const componentsData = await import__349.Resource.fetchJson( "Data/EarthOrientationParameters/IcrfToFixedStkComponentsRotationData.json" ); const start = import__349.JulianDate.fromIso8601(componentsData[0].date); const stop = import__349.JulianDate.fromIso8601( componentsData[componentsData.length - 1].date ); await preloadTransformationData( start, stop, "Data/EarthOrientationParameters/EOP-2011-July.json" ); for (let i = 0; i < componentsData.length; ++i) { const time2 = import__349.JulianDate.fromIso8601(componentsData[i].date); const resultT = new import__349.Matrix3(); const t = import__349.Transforms.computeIcrfToFixedMatrix(time2, resultT); expect(t).toBe(resultT); const det = t[0] * t[4] * t[8] + t[3] * t[7] * t[2] + t[6] * t[1] * t[5] - t[6] * t[4] * t[2] - t[3] * t[1] * t[8] - t[0] * t[7] * t[5]; expect(det).toEqualEpsilon(1, import__350.Math.EPSILON14); const t4 = import__349.Matrix4.fromRotationTranslation(t); expect(import__349.Matrix4.inverse(t4, new import__349.Matrix4())).toEqualEpsilon( import__349.Matrix4.inverseTransformation(t4, new import__349.Matrix4()), import__350.Math.EPSILON14 ); const expectedMtx = import__349.Matrix3.fromQuaternion( import__349.Quaternion.conjugate( componentsData[i].icrfToFixedQuaternion, new import__349.Quaternion() ) ); const testInverse = import__349.Matrix3.multiply( import__349.Matrix3.transpose(t, new import__349.Matrix3()), expectedMtx, new import__349.Matrix3() ); const testDiff = new import__349.Matrix3(); for (let k = 0; k < 9; k++) { testDiff[k] = t[k] - expectedMtx[k]; } expect(testInverse).toEqualEpsilon( import__349.Matrix3.IDENTITY, import__350.Math.EPSILON14 ); expect(testDiff).toEqualEpsilon(new import__349.Matrix3(), import__350.Math.EPSILON14); } }); it("works with hard-coded data", async function() { let time2 = new import__349.JulianDate(2455745, 43200); await preloadTransformationData( time2, time2, "Data/EarthOrientationParameters/EOP-2011-July.json" ); const resultT = new import__349.Matrix3(); const t = import__349.Transforms.computeIcrfToFixedMatrix(time2, resultT); expect(t).toBe(resultT); const det = t[0] * t[4] * t[8] + t[3] * t[7] * t[2] + t[6] * t[1] * t[5] - t[6] * t[4] * t[2] - t[3] * t[1] * t[8] - t[0] * t[7] * t[5]; expect(det).toEqualEpsilon(1, import__350.Math.EPSILON14); const t4 = import__349.Matrix4.fromRotationTranslation(t); expect(import__349.Matrix4.inverse(t4, new import__349.Matrix4())).toEqualEpsilon( import__349.Matrix4.inverseTransformation(t4, new import__349.Matrix4()), import__350.Math.EPSILON14 ); time2 = import__349.JulianDate.addHours(time2, 23.93447, new import__349.JulianDate()); const resultU = new import__349.Matrix3(); const u = import__349.Transforms.computeIcrfToFixedMatrix(time2, resultU); expect(u).toBe(resultU); const tAngle = import__349.Quaternion.computeAngle(import__349.Quaternion.fromRotationMatrix(t)); const uAngle = import__349.Quaternion.computeAngle(import__349.Quaternion.fromRotationMatrix(u)); expect(tAngle).toEqualEpsilon(uAngle, import__350.Math.EPSILON6); const expectedMtx = new import__349.Matrix3( 0.18264414843630006, -0.9831790614431595, -21950336420248503e-20, 0.9831784091522497, 0.18264428011734501, -0.0011325710874539787, 0.0011536112127187594, -8953486608559891e-21, 0.9999993345502811 ); const testInverse = import__349.Matrix3.multiply( import__349.Matrix3.transpose(t, new import__349.Matrix3()), expectedMtx, new import__349.Matrix3() ); const testDiff = new import__349.Matrix3(); for (let i = 0; i < 9; i++) { testDiff[i] = t[i] - expectedMtx[i]; } expect(testInverse).toEqualEpsilon( import__349.Matrix3.IDENTITY, import__350.Math.EPSILON14 ); expect(testDiff).toEqualEpsilon(new import__349.Matrix3(), import__350.Math.EPSILON14); }); it("works over day boundary", async function() { const time2 = new import__349.JulianDate(2455745, 86395); await preloadTransformationData( time2, time2, "Data/EarthOrientationParameters/EOP-2011-July.json" ); const resultT = new import__349.Matrix3(); const t = import__349.Transforms.computeIcrfToFixedMatrix(time2, resultT); const expectedMtx = new import__349.Matrix3( -0.19073578935932833, 0.9816413836674872, 22919174269963536e-20, -0.9816407371283619, -0.1907359267933394, 0.0011266944449015753, 0.0011497249933208494, -10082996932331842e-21, 0.9999993390151679 ); const testInverse = import__349.Matrix3.multiply( import__349.Matrix3.transpose(t, new import__349.Matrix3()), expectedMtx, new import__349.Matrix3() ); const testDiff = new import__349.Matrix3(); for (let i = 0; i < 9; i++) { testDiff[i] = t[i] - expectedMtx[i]; } expect(testInverse).toEqualEpsilon( import__349.Matrix3.IDENTITY, import__350.Math.EPSILON14 ); expect(testDiff).toEqualEpsilon(new import__349.Matrix3(), import__350.Math.EPSILON14); }); it("works over day boundary backwards", async function() { const time2 = new import__349.JulianDate(2455745, 10); await preloadTransformationData( time2, time2, "Data/EarthOrientationParameters/EOP-2011-July.json" ); const resultT = new import__349.Matrix3(); const t = import__349.Transforms.computeIcrfToFixedMatrix(time2, resultT); const expectedMtx = new import__349.Matrix3( -0.17489910479510423, 0.984586338811966, 21110831245616662e-20, -0.9845856906528683, -0.17489923190143036, 0.0011297972845023996, 0.0011493056536445096, -1025368996280683e-20, 0.99999933949547 ); const testInverse = import__349.Matrix3.multiply( import__349.Matrix3.transpose(t, new import__349.Matrix3()), expectedMtx, new import__349.Matrix3() ); const testDiff = new import__349.Matrix3(); for (let i = 0; i < 9; i++) { testDiff[i] = t[i] - expectedMtx[i]; } expect(testInverse).toEqualEpsilon( import__349.Matrix3.IDENTITY, import__350.Math.EPSILON14 ); expect(testDiff).toEqualEpsilon(new import__349.Matrix3(), import__350.Math.EPSILON14); }); it("works with position rotation", async function() { const inertialPos = new import__349.Cartesian3( -732210115395708e-8, -415256991558387e-7, 0 ); const expectedFixedPos = new import__349.Cartesian3( 394898589917795e-7, -14783363192887e-6, -8075.05820056297 ); const time2 = new import__349.JulianDate(2455745, 43200); await preloadTransformationData( time2, time2, "Data/EarthOrientationParameters/EOP-2011-July.json" ); const resultT = new import__349.Matrix3(); const t = import__349.Transforms.computeIcrfToFixedMatrix(time2, resultT); const result = import__349.Matrix3.multiplyByVector(t, inertialPos, new import__349.Cartesian3()); const error = import__349.Cartesian3.subtract( result, expectedFixedPos, new import__349.Cartesian3() ); expect(error).toEqualEpsilon(import__349.Cartesian3.ZERO, import__350.Math.EPSILON7); }); it("undefined prior to 1974", async function() { const time2 = new import__349.JulianDate(2440587, 43200); await preloadTransformationData( time2, import__349.JulianDate.addDays(time2, 1, new import__349.JulianDate()) ); const resultT = new import__349.Matrix3(); const t = import__349.Transforms.computeIcrfToFixedMatrix(time2, resultT); expect(t).toEqual(void 0); }); it("works after 2028", async function() { const time2 = new import__349.JulianDate(2462502, 43200); await preloadTransformationData( time2, import__349.JulianDate.addDays(time2, 1, new import__349.JulianDate()) ); const resultT = new import__349.Matrix3(); const t = import__349.Transforms.computeIcrfToFixedMatrix(time2, resultT); expect(t).toBeDefined(); }); it("works without EOP data loaded", async function() { const inertialPos = new import__349.Cartesian3( -732210115395708e-8, -415256991558387e-7, 0 ); const expectedFixedPos = new import__349.Cartesian3( 394895457583001e-7, -147841999085371e-7, -8034.77037239318 ); const time2 = new import__349.JulianDate(2455745, 43200); import__349.Transforms.earthOrientationParameters = new import__349.EarthOrientationParameters(); await preloadTransformationData(time2, time2); const resultT = new import__349.Matrix3(); const t = import__349.Transforms.computeIcrfToFixedMatrix(time2, resultT); const result = import__349.Matrix3.multiplyByVector(t, inertialPos, new import__349.Cartesian3()); const error = import__349.Cartesian3.subtract( result, expectedFixedPos, new import__349.Cartesian3() ); expect(error).toEqualEpsilon(import__349.Cartesian3.ZERO, import__350.Math.EPSILON7); }); it("throws a RuntimeError when asked to compute with invalid EOP data", async function() { const time2 = new import__349.JulianDate(2455745, 43200); await expectAsync( async function() { await preloadTransformationData( time2, time2, "Data/EarthOrientationParameters/EOP-Invalid.json" ); return import__349.Transforms.computeIcrfToFixedMatrix(time2); }() ).toBeRejectedWithError( import__349.RuntimeError, "Error in loaded EOP data: The columnNames property is required." ); }); it("returns undefined before XYS data is loaded.", function() { import__349.Transforms.earthOrientationParameters = new import__349.EarthOrientationParameters(); import__349.Transforms.iau2006XysData = new import__349.Iau2006XysData(); const time2 = new import__349.JulianDate(2455745, 43200); expect(import__349.Transforms.computeIcrfToFixedMatrix(time2)).toBeUndefined(); }); }); const width = 1024; const height = 768; const perspective = import__349.Matrix4.computePerspectiveFieldOfView( import__350.Math.toRadians(60), width / height, 1, 10, new import__349.Matrix4() ); const vpTransform = import__349.Matrix4.computeViewportTransformation( { width, height }, 0, 1, new import__349.Matrix4() ); it("pointToGLWindowCoordinates works at the center", function() { const view = import__349.Matrix4.fromCamera({ position: import__349.Cartesian3.multiplyByScalar( import__349.Cartesian3.UNIT_X, 2, new import__349.Cartesian3() ), direction: import__349.Cartesian3.negate(import__349.Cartesian3.UNIT_X, new import__349.Cartesian3()), up: import__349.Cartesian3.UNIT_Z }); const mvpMatrix = import__349.Matrix4.multiply(perspective, view, new import__349.Matrix4()); const expected = new import__349.Cartesian2(width * 0.5, height * 0.5); const returnedResult = import__349.Transforms.pointToGLWindowCoordinates( mvpMatrix, vpTransform, import__349.Cartesian3.ZERO ); expect(returnedResult).toEqual(expected); }); it("pointToGLWindowCoordinates works with a result parameter", function() { const view = import__349.Matrix4.fromCamera({ position: import__349.Cartesian3.multiplyByScalar( import__349.Cartesian3.UNIT_X, 2, new import__349.Cartesian3() ), direction: import__349.Cartesian3.negate(import__349.Cartesian3.UNIT_X, new import__349.Cartesian3()), up: import__349.Cartesian3.UNIT_Z }); const mvpMatrix = import__349.Matrix4.multiply(perspective, view, new import__349.Matrix4()); const expected = new import__349.Cartesian2(width * 0.5, height * 0.5); const result = new import__349.Cartesian2(); const returnedResult = import__349.Transforms.pointToGLWindowCoordinates( mvpMatrix, vpTransform, import__349.Cartesian3.ZERO, result ); expect(result).toBe(returnedResult); expect(returnedResult).toEqual(expected); }); it("pointToGLWindowCoordinates works at the lower left", function() { const z = -perspective[import__349.Matrix4.COLUMN3ROW2] / perspective[import__349.Matrix4.COLUMN2ROW2]; const x = z / perspective[import__349.Matrix4.COLUMN0ROW0]; const y = z / perspective[import__349.Matrix4.COLUMN1ROW1]; const point = new import__349.Cartesian3(x, y, z); const expected = new import__349.Cartesian2(0, 0); const returnedResult = import__349.Transforms.pointToGLWindowCoordinates( perspective, vpTransform, point ); expect(returnedResult).toEqualEpsilon(expected, import__350.Math.EPSILON12); }); it("pointToGLWindowCoordinates works at the upper right", function() { const z = -perspective[import__349.Matrix4.COLUMN3ROW2] / perspective[import__349.Matrix4.COLUMN2ROW2]; const x = -z / perspective[import__349.Matrix4.COLUMN0ROW0]; const y = -z / perspective[import__349.Matrix4.COLUMN1ROW1]; const point = new import__349.Cartesian3(x, y, z); const expected = new import__349.Cartesian2(width, height); const returnedResult = import__349.Transforms.pointToGLWindowCoordinates( perspective, vpTransform, point ); expect(returnedResult).toEqualEpsilon(expected, import__350.Math.EPSILON12); }); it("pointToWindowCoordinates works at the center", function() { const view = import__349.Matrix4.fromCamera({ position: import__349.Cartesian3.multiplyByScalar( import__349.Cartesian3.UNIT_X, 2, new import__349.Cartesian3() ), direction: import__349.Cartesian3.negate(import__349.Cartesian3.UNIT_X, new import__349.Cartesian3()), up: import__349.Cartesian3.UNIT_Z }); const mvpMatrix = import__349.Matrix4.multiply(perspective, view, new import__349.Matrix4()); const expected = new import__349.Cartesian2(width * 0.5, height * 0.5); const returnedResult = import__349.Transforms.pointToWindowCoordinates( mvpMatrix, vpTransform, import__349.Cartesian3.ZERO ); expect(returnedResult).toEqual(expected); }); it("pointToWindowCoordinates works with a result parameter", function() { const view = import__349.Matrix4.fromCamera({ position: import__349.Cartesian3.multiplyByScalar( import__349.Cartesian3.UNIT_X, 2, new import__349.Cartesian3() ), direction: import__349.Cartesian3.negate(import__349.Cartesian3.UNIT_X, new import__349.Cartesian3()), up: import__349.Cartesian3.UNIT_Z }); const mvpMatrix = import__349.Matrix4.multiply(perspective, view, new import__349.Matrix4()); const expected = new import__349.Cartesian2(width * 0.5, height * 0.5); const result = new import__349.Cartesian2(); const returnedResult = import__349.Transforms.pointToWindowCoordinates( mvpMatrix, vpTransform, import__349.Cartesian3.ZERO, result ); expect(result).toBe(returnedResult); expect(returnedResult).toEqual(expected); }); it("pointToWindowCoordinates works at the lower left", function() { const z = -perspective[import__349.Matrix4.COLUMN3ROW2] / perspective[import__349.Matrix4.COLUMN2ROW2]; const x = z / perspective[import__349.Matrix4.COLUMN0ROW0]; const y = z / perspective[import__349.Matrix4.COLUMN1ROW1]; const point = new import__349.Cartesian3(x, y, z); const expected = new import__349.Cartesian2(0, height); const returnedResult = import__349.Transforms.pointToWindowCoordinates( perspective, vpTransform, point ); expect(returnedResult).toEqualEpsilon(expected, import__350.Math.EPSILON12); }); it("pointToWindowCoordinates works at the upper right", function() { const z = -perspective[import__349.Matrix4.COLUMN3ROW2] / perspective[import__349.Matrix4.COLUMN2ROW2]; const x = -z / perspective[import__349.Matrix4.COLUMN0ROW0]; const y = -z / perspective[import__349.Matrix4.COLUMN1ROW1]; const point = new import__349.Cartesian3(x, y, z); const expected = new import__349.Cartesian2(width, 0); const returnedResult = import__349.Transforms.pointToWindowCoordinates( perspective, vpTransform, point ); expect(returnedResult).toEqualEpsilon(expected, import__350.Math.EPSILON12); }); it("rotationMatrixFromPositionVelocity works without a result parameter", function() { let matrix = import__349.Transforms.rotationMatrixFromPositionVelocity( import__349.Cartesian3.UNIT_X, import__349.Cartesian3.UNIT_Y ); let expected = new import__349.Matrix3(0, 0, 1, 1, 0, 0, 0, 1, 0); expect(matrix).toEqualEpsilon(expected, import__350.Math.EPSILON14); matrix = import__349.Transforms.rotationMatrixFromPositionVelocity( import__349.Cartesian3.UNIT_X, import__349.Cartesian3.UNIT_Z ); expected = new import__349.Matrix3(0, 0, 1, 0, -1, 0, 1, 0, 0); expect(matrix).toEqualEpsilon(expected, import__350.Math.EPSILON14); matrix = import__349.Transforms.rotationMatrixFromPositionVelocity( import__349.Cartesian3.UNIT_Y, import__349.Cartesian3.UNIT_Z ); expected = new import__349.Matrix3(0, 1, 0, 0, 0, 1, 1, 0, 0); expect(matrix).toEqualEpsilon(expected, import__350.Math.EPSILON14); }); it("rotationMatrixFromPositionVelocity works with a result parameter", function() { const result = new import__349.Matrix3(); import__349.Transforms.rotationMatrixFromPositionVelocity( import__349.Cartesian3.UNIT_X, import__349.Cartesian3.UNIT_Y, import__349.Ellipsoid.WGS84, result ); let expected = new import__349.Matrix3(0, 0, 1, 1, 0, 0, 0, 1, 0); expect(result).toEqualEpsilon(expected, import__350.Math.EPSILON14); import__349.Transforms.rotationMatrixFromPositionVelocity( import__349.Cartesian3.UNIT_X, import__349.Cartesian3.UNIT_Z, import__349.Ellipsoid.WGS84, result ); expected = new import__349.Matrix3(0, 0, 1, 0, -1, 0, 1, 0, 0); expect(result).toEqualEpsilon(expected, import__350.Math.EPSILON14); import__349.Transforms.rotationMatrixFromPositionVelocity( import__349.Cartesian3.UNIT_Y, import__349.Cartesian3.UNIT_Z, import__349.Ellipsoid.WGS84, result ); expected = new import__349.Matrix3(0, 1, 0, 0, 0, 1, 1, 0, 0); expect(result).toEqualEpsilon(expected, import__350.Math.EPSILON14); }); it("basisTo2D projects translation", function() { const ellipsoid = import__349.Ellipsoid.WGS84; const projection = new import__349.GeographicProjection(ellipsoid); const origin = import__349.Cartesian3.fromDegrees(-72, 40, 100, ellipsoid); const heading = import__350.Math.toRadians(90); const pitch = import__350.Math.toRadians(45); const roll = 0; const hpr = new import__349.HeadingPitchRoll(heading, pitch, roll); const modelMatrix = import__349.Transforms.headingPitchRollToFixedFrame( origin, hpr, ellipsoid ); const modelMatrix2D = import__349.Transforms.basisTo2D( projection, modelMatrix, new import__349.Matrix4() ); const translation2D = import__349.Cartesian3.fromCartesian4( import__349.Matrix4.getColumn(modelMatrix2D, 3, new import__349.Cartesian4()) ); const carto = ellipsoid.cartesianToCartographic(origin); const expected = projection.project(carto); import__349.Cartesian3.fromElements(expected.z, expected.x, expected.y, expected); expect(translation2D).toEqual(expected); }); it("basisTo2D transforms rotation", function() { const ellipsoid = import__349.Ellipsoid.WGS84; const projection = new import__349.GeographicProjection(ellipsoid); const origin = import__349.Cartesian3.fromDegrees(-72, 40, 100, ellipsoid); const heading = import__350.Math.toRadians(90); const pitch = import__350.Math.toRadians(45); const roll = 0; const hpr = new import__349.HeadingPitchRoll(heading, pitch, roll); const modelMatrix = import__349.Transforms.headingPitchRollToFixedFrame( origin, hpr, ellipsoid ); const modelMatrix2D = import__349.Transforms.basisTo2D( projection, modelMatrix, new import__349.Matrix4() ); const rotation2D = import__349.Matrix4.getMatrix3(modelMatrix2D, new import__349.Matrix3()); const enu = import__349.Transforms.eastNorthUpToFixedFrame(origin, ellipsoid); const enuInverse = import__349.Matrix4.inverseTransformation(enu, enu); const hprPlusTranslate = import__349.Matrix4.multiply( enuInverse, modelMatrix, new import__349.Matrix4() ); const hpr2 = import__349.Matrix4.getMatrix3(hprPlusTranslate, new import__349.Matrix3()); const row0 = import__349.Matrix3.getRow(hpr2, 0, new import__349.Cartesian3()); const row1 = import__349.Matrix3.getRow(hpr2, 1, new import__349.Cartesian3()); const row2 = import__349.Matrix3.getRow(hpr2, 2, new import__349.Cartesian3()); const expected = new import__349.Matrix3(); import__349.Matrix3.setRow(expected, 0, row2, expected); import__349.Matrix3.setRow(expected, 1, row0, expected); import__349.Matrix3.setRow(expected, 2, row1, expected); expect(rotation2D).toEqualEpsilon(expected, import__350.Math.EPSILON3); }); it("wgs84To2DModelMatrix creates a model matrix to transform vertices centered origin to 2D", function() { const ellipsoid = import__349.Ellipsoid.WGS84; const projection = new import__349.GeographicProjection(ellipsoid); const origin = import__349.Cartesian3.fromDegrees(-72, 40, 100, ellipsoid); const actual = import__349.Transforms.wgs84To2DModelMatrix( projection, origin, new import__349.Matrix4() ); const expected = import__349.Matrix4.fromTranslation(origin); import__349.Transforms.basisTo2D(projection, expected, expected); const actualRotation = import__349.Matrix4.getMatrix3(actual, new import__349.Matrix3()); const expectedRotation = import__349.Matrix4.getMatrix3(expected, new import__349.Matrix3()); expect(actualRotation).toEqualEpsilon( expectedRotation, import__350.Math.EPSILON14 ); const fromENU = import__349.Transforms.eastNorthUpToFixedFrame( origin, ellipsoid, new import__349.Matrix4() ); const toENU = import__349.Matrix4.inverseTransformation(fromENU, new import__349.Matrix4()); const toENUTranslation = import__349.Matrix4.getTranslation(toENU, new import__349.Cartesian4()); const projectedTranslation = import__349.Matrix4.getTranslation( expected, new import__349.Cartesian4() ); const expectedTranslation = new import__349.Cartesian4(); expectedTranslation.x = projectedTranslation.x + toENUTranslation.z; expectedTranslation.y = projectedTranslation.y + toENUTranslation.x; expectedTranslation.z = projectedTranslation.z + toENUTranslation.y; const actualTranslation = import__349.Matrix4.getTranslation(actual, new import__349.Cartesian4()); expect(actualTranslation).toEqualEpsilon( expectedTranslation, import__350.Math.EPSILON14 ); }); it("fixedFrameToHeadingPitchRoll returns heading/pitch/roll from a transform", function() { const expected = new import__349.HeadingPitchRoll(0.5, 0.6, 0.7); let transform = import__349.Transforms.eastNorthUpToFixedFrame( import__349.Cartesian3.fromDegrees(0, 0) ); const transform2 = import__349.Matrix4.fromTranslationQuaternionRotationScale( new import__349.Cartesian3(), import__349.Quaternion.fromHeadingPitchRoll(expected), new import__349.Cartesian3(1, 1, 1) ); transform = import__349.Matrix4.multiply(transform, transform2, transform2); const actual = import__349.Transforms.fixedFrameToHeadingPitchRoll(transform); expect(actual).toEqualEpsilon(expected, import__350.Math.EPSILON10); }); it("fixedFrameToHeadingPitchRoll throws with no transform", function() { expect(function() { return import__349.Transforms.fixedFrameToHeadingPitchRoll(); }).toThrowDeveloperError(); }); it("eastNorthUpToFixedFrame throws without an origin", function() { expect(function() { import__349.Transforms.eastNorthUpToFixedFrame(void 0, import__349.Ellipsoid.WGS84); }).toThrowDeveloperError(); }); it("northEastDownToFixedFrame throws without an origin", function() { expect(function() { import__349.Transforms.northEastDownToFixedFrame(void 0, import__349.Ellipsoid.WGS84); }).toThrowDeveloperError(); }); it("northWestUpToFixedFrame throws without an origin", function() { expect(function() { import__349.Transforms.northWestUpToFixedFrame(void 0, import__349.Ellipsoid.WGS84); }).toThrowDeveloperError(); }); it("headingPitchRollToFixedFrame throws without an origin", function() { expect(function() { import__349.Transforms.headingPitchRollToFixedFrame( void 0, new import__349.HeadingPitchRoll() ); }).toThrowDeveloperError(); }); it("headingPitchRollToFixedFrame throws without a headingPitchRoll", function() { expect(function() { import__349.Transforms.headingPitchRollToFixedFrame(import__349.Cartesian3.ZERO, void 0); }).toThrowDeveloperError(); }); it("computeTemeToPseudoFixedMatrix throws without a date", function() { expect(function() { import__349.Transforms.computeTemeToPseudoFixedMatrix(void 0); }).toThrowDeveloperError(); }); it("pointToWindowCoordinates throws without modelViewProjectionMatrix", function() { expect(function() { import__349.Transforms.pointToWindowCoordinates( void 0, import__349.Matrix4.IDENTITY, import__349.Cartesian3.ZERO ); }).toThrowDeveloperError(); }); it("pointToWindowCoordinates throws without viewportTransformation", function() { expect(function() { import__349.Transforms.pointToWindowCoordinates( import__349.Matrix4.IDENTITY, void 0, import__349.Cartesian3.ZERO ); }).toThrowDeveloperError(); }); it("pointToWindowCoordinates throws without a point", function() { expect(function() { import__349.Transforms.pointToWindowCoordinates( import__349.Matrix4.IDENTITY, import__349.Matrix4.IDENTITY, void 0 ); }).toThrowDeveloperError(); }); it("basisTo2D throws without projection", function() { expect(function() { import__349.Transforms.basisTo2D(void 0, import__349.Matrix4.IDENTITY, new import__349.Matrix4()); }).toThrowDeveloperError(); }); it("basisTo2D throws without matrix", function() { expect(function() { import__349.Transforms.basisTo2D( new import__349.GeographicProjection(), void 0, new import__349.Matrix4() ); }).toThrowDeveloperError(); }); it("basisTo2D throws without result", function() { expect(function() { import__349.Transforms.basisTo2D( new import__349.GeographicProjection(), import__349.Matrix4.IDENTITY, void 0 ); }).toThrowDeveloperError(); }); it("wgs84To2DModelMatrix throws without projection", function() { expect(function() { import__349.Transforms.wgs84To2DModelMatrix( void 0, import__349.Cartesian3.UNIT_X, new import__349.Matrix4() ); }).toThrowDeveloperError(); }); it("wgs84To2DModelMatrix throws without center", function() { expect(function() { import__349.Transforms.wgs84To2DModelMatrix( new import__349.GeographicProjection(), void 0, new import__349.Matrix4() ); }).toThrowDeveloperError(); }); it("wgs84To2DModelMatrix throws without result", function() { expect(function() { import__349.Transforms.wgs84To2DModelMatrix( new import__349.GeographicProjection(), import__349.Cartesian3.UNIT_X, void 0 ); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/TranslationRotationScaleSpec.js var import__351 = __toESM(require_Cesium(), 1); describe("Core/TranslationRotationScale", function() { it("sets correct values when constructed with no arguments", function() { const transformation = new import__351.TranslationRotationScale(); expect(transformation.translation).toEqual(import__351.Cartesian3.ZERO); expect(transformation.rotation).toEqual(import__351.Quaternion.IDENTITY); expect(transformation.scale).toEqual(new import__351.Cartesian3(1, 1, 1)); }); it("sets correct values when constructed with arguments", function() { const translation = import__351.Cartesian3.UNIT_Y; const rotation = new import__351.Quaternion(0.5, 0.5, 0.5, 0.5); const scale = import__351.Cartesian3.UNIT_X; const transformation = new import__351.TranslationRotationScale( translation, rotation, scale ); expect(transformation.translation).toEqual(translation); expect(transformation.rotation).toEqual(rotation); expect(transformation.scale).toEqual(scale); }); it("has a working equals function", function() { const left = new import__351.TranslationRotationScale(); left.translation = import__351.Cartesian3.UNIT_Y; left.rotation = new import__351.Quaternion(0.5, 0.5, 0.5, 0.5); left.scale = import__351.Cartesian3.UNIT_X; const right = new import__351.TranslationRotationScale(); right.translation = import__351.Cartesian3.UNIT_Y; right.rotation = new import__351.Quaternion(0.5, 0.5, 0.5, 0.5); right.scale = import__351.Cartesian3.UNIT_X; expect(left.equals(right)).toEqual(true); right.scale = import__351.Cartesian3.ZERO; expect(left.equals(right)).toEqual(false); right.scale = import__351.Cartesian3.UNIT_X; right.translation = import__351.Cartesian3.ZERO; expect(left.equals(right)).toEqual(false); right.translation = import__351.Cartesian3.UNIT_Y; right.rotation = import__351.Quaternion.ZERO; expect(left.equals(right)).toEqual(false); }); }); // packages/engine/Specs/Core/TridiagonalSystemSolverSpec.js var import__352 = __toESM(require_Cesium(), 1); var import__353 = __toESM(require_Cesium(), 1); describe("Core/TridiagonalSystemSolver", function() { it("solve throws exception without lower diagonal", function() { expect(function() { import__352.TridiagonalSystemSolver.solve(); }).toThrowDeveloperError(); }); it("solve throws exception without diagonal", function() { expect(function() { import__352.TridiagonalSystemSolver.solve([]); }).toThrowDeveloperError(); }); it("solve throws exception without upper diagonal", function() { expect(function() { import__352.TridiagonalSystemSolver.solve([], []); }).toThrowDeveloperError(); }); it("solve throws exception without rhs vector", function() { expect(function() { import__352.TridiagonalSystemSolver.solve([], [], []); }).toThrowDeveloperError(); }); it("solve throws exception when rhs vector length is not equal to diagonal length", function() { expect(function() { import__352.TridiagonalSystemSolver.solve([], [], [], [1]); }).toThrowDeveloperError(); }); it("solve throws exception when lower diagonal length is not equal to upper diagonal length", function() { expect(function() { import__352.TridiagonalSystemSolver.solve([1], [1], [], [1]); }).toThrowDeveloperError(); }); it("solve throws exception when lower/upper diagonal length is not one less than diagonal length", function() { expect(function() { import__352.TridiagonalSystemSolver.solve([1], [1], [1], [1]); }).toThrowDeveloperError(); }); it("solve three unknowns", function() { const l = [1, 1]; const d = [-2.175, -2.15, -2.125]; const u = [1, 1]; const r = [ new import__352.Cartesian3(-1.625), new import__352.Cartesian3(0.5), new import__352.Cartesian3(1.625) ]; const expected = [ new import__352.Cartesian3(0.552), new import__352.Cartesian3(-0.4244), new import__352.Cartesian3(-0.9644) ]; const actual = import__352.TridiagonalSystemSolver.solve(l, d, u, r); expect(actual.length).toEqual(expected.length); expect(actual[0]).toEqualEpsilon(expected[0], import__353.Math.EPSILON4); expect(actual[1]).toEqualEpsilon(expected[1], import__353.Math.EPSILON4); expect(actual[2]).toEqualEpsilon(expected[2], import__353.Math.EPSILON4); }); it("solve nine unknowns", function() { const l = [1, 1, 1, 1, 1, 1, 1, 1]; const d = [ -2.0304, -2.0288, -2.0272, -2.0256, -2.024, -2.0224, -2.0208, -2.0192, -2.0176 ]; const u = [1, 1, 1, 1, 1, 1, 1, 1]; const r = [ new import__352.Cartesian3(-1.952), new import__352.Cartesian3(0.056), new import__352.Cartesian3(0.064), new import__352.Cartesian3(0.072), new import__352.Cartesian3(0.08), new import__352.Cartesian3(0.088), new import__352.Cartesian3(0.096), new import__352.Cartesian3(0.104), new import__352.Cartesian3(1.112) ]; const expected = [ new import__352.Cartesian3(1.3513), new import__352.Cartesian3(0.7918), new import__352.Cartesian3(0.311), new import__352.Cartesian3(-0.0974), new import__352.Cartesian3(-0.4362), new import__352.Cartesian3(-0.7055), new import__352.Cartesian3(-0.9025), new import__352.Cartesian3(-1.0224), new import__352.Cartesian3(-1.0579) ]; const actual = import__352.TridiagonalSystemSolver.solve(l, d, u, r); expect(actual.length).toEqual(expected.length); expect(actual[0]).toEqualEpsilon(expected[0], import__353.Math.EPSILON4); expect(actual[1]).toEqualEpsilon(expected[1], import__353.Math.EPSILON4); expect(actual[2]).toEqualEpsilon(expected[2], import__353.Math.EPSILON4); expect(actual[3]).toEqualEpsilon(expected[3], import__353.Math.EPSILON4); expect(actual[4]).toEqualEpsilon(expected[4], import__353.Math.EPSILON4); expect(actual[5]).toEqualEpsilon(expected[5], import__353.Math.EPSILON4); expect(actual[6]).toEqualEpsilon(expected[6], import__353.Math.EPSILON4); expect(actual[7]).toEqualEpsilon(expected[7], import__353.Math.EPSILON4); expect(actual[8]).toEqualEpsilon(expected[8], import__353.Math.EPSILON4); }); }); // packages/engine/Specs/Core/TrustedServersSpec.js var import__354 = __toESM(require_Cesium(), 1); describe("Core/TrustedServers", function() { afterEach(function() { import__354.TrustedServers.clear(); }); it("add without argument throws", function() { expect(function() { import__354.TrustedServers.add(); }).toThrowDeveloperError(); }); it("remove without argument throws", function() { expect(function() { import__354.TrustedServers.remove(); }).toThrowDeveloperError(); }); it("isTrusted without argument throws", function() { expect(function() { import__354.TrustedServers.contains(); }).toThrowDeveloperError(); }); it("http without a port", function() { import__354.TrustedServers.add("cesiumjs.org", 80); expect(import__354.TrustedServers.contains("http://cesiumjs.org/index.html")).toBe( true ); expect(import__354.TrustedServers.contains("https://cesiumjs.org/index.html")).toBe( false ); }); it("https without a port", function() { import__354.TrustedServers.add("cesiumjs.org", 443); expect(import__354.TrustedServers.contains("https://cesiumjs.org/index.html")).toBe( true ); expect(import__354.TrustedServers.contains("http://cesiumjs.org/index.html")).toBe( false ); }); it("add", function() { expect(import__354.TrustedServers.contains("http://cesiumjs.org:81/index.html")).toBe( false ); import__354.TrustedServers.add("cesiumjs.org", 81); expect(import__354.TrustedServers.contains("http://cesiumjs.org/index.html")).toBe( false ); expect(import__354.TrustedServers.contains("http://cesiumjs.org:81/index.html")).toBe( true ); }); it("remove", function() { import__354.TrustedServers.add("cesiumjs.org", 81); expect(import__354.TrustedServers.contains("http://cesiumjs.org:81/index.html")).toBe( true ); import__354.TrustedServers.remove("cesiumjs.org", 8080); expect(import__354.TrustedServers.contains("http://cesiumjs.org:81/index.html")).toBe( true ); import__354.TrustedServers.remove("cesiumjs.org", 81); expect(import__354.TrustedServers.contains("http://cesiumjs.org:81/index.html")).toBe( false ); }); it("handles username/password credentials", function() { import__354.TrustedServers.add("cesiumjs.org", 81); expect( import__354.TrustedServers.contains("http://user:pass@cesiumjs.org:81/index.html") ).toBe(true); }); it("always returns false for relative paths", function() { expect(import__354.TrustedServers.contains("./data/index.html")).toBe(false); }); it("handles protocol relative URLs", function() { import__354.TrustedServers.add("cesiumjs.org", 80); expect(import__354.TrustedServers.contains("//cesiumjs.org/index.html")).toBe(true); }); it("clear", function() { import__354.TrustedServers.add("cesiumjs.org", 80); expect(import__354.TrustedServers.contains("http://cesiumjs.org/index.html")).toBe( true ); import__354.TrustedServers.clear(); expect(import__354.TrustedServers.contains("http://cesiumjs.org/index.html")).toBe( false ); import__354.TrustedServers.add("cesiumjs.org", 80); expect(import__354.TrustedServers.contains("http://cesiumjs.org/index.html")).toBe( true ); }); }); // packages/engine/Specs/Core/VRTheWorldTerrainProviderSpec.js var import__355 = __toESM(require_Cesium(), 1); describe("Core/VRTheWorldTerrainProvider", function() { const imageUrl = "Data/Images/Red16x16.png"; function patchXHRLoad() { import__355.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { if (url === imageUrl) { import__355.Resource._DefaultImplementations.loadWithXhr( url, responseType, method, data, headers, deferred, overrideMimeType ); return; } setTimeout(function() { const parser = new DOMParser(); const xmlString = 'Hawaii World elevlayer to make cesium work rightEPSG:4326'; const xml = parser.parseFromString(xmlString, "text/xml"); deferred.resolve(xml); }, 1); }; } let originalRequestersPerServer; beforeEach(function() { import__355.RequestScheduler.clearForSpecs(); originalRequestersPerServer = import__355.RequestScheduler.maximumRequestsPerServer; }); afterEach(function() { import__355.Resource._Implementations.createImage = import__355.Resource._DefaultImplementations.createImage; import__355.Resource._Implementations.loadWithXhr = import__355.Resource._DefaultImplementations.loadWithXhr; import__355.RequestScheduler.maximumRequestsPerServer = originalRequestersPerServer; }); function createRequest() { return new import__355.Request({ throttleByServer: true }); } it("conforms to TerrainProvider interface", function() { expect(import__355.VRTheWorldTerrainProvider).toConformToInterface(import__355.TerrainProvider); }); it("fromUrl rejects without url", async function() { await expectAsync( import__355.VRTheWorldTerrainProvider.fromUrl() ).toBeRejectedWithDeveloperError( "url is required, actual value was undefined" ); }); it("fromUrl resolves to new VRTheWorldTerrainProvider", async function() { patchXHRLoad(); const provider = await import__355.VRTheWorldTerrainProvider.fromUrl("made/up/url"); expect(provider).toBeInstanceOf(import__355.VRTheWorldTerrainProvider); }); it("fromUrl with Resource resolves to new VRTheWorldTerrainProvider", async function() { patchXHRLoad(); const resource = new import__355.Resource({ url: "made/up/url" }); const provider = await import__355.VRTheWorldTerrainProvider.fromUrl(resource); expect(provider).toBeInstanceOf(import__355.VRTheWorldTerrainProvider); }); it("has error event", async function() { patchXHRLoad(); const provider = await import__355.VRTheWorldTerrainProvider.fromUrl("made/up/url"); expect(provider.errorEvent).toBeDefined(); expect(provider.errorEvent).toBe(provider.errorEvent); }); it("returns reasonable geometric error for various levels", async function() { patchXHRLoad(); const provider = await import__355.VRTheWorldTerrainProvider.fromUrl("made/up/url"); expect(provider.getLevelMaximumGeometricError(0)).toBeGreaterThan(0); expect(provider.getLevelMaximumGeometricError(0)).toEqualEpsilon( provider.getLevelMaximumGeometricError(1) * 2, import__355.Math.EPSILON10 ); expect(provider.getLevelMaximumGeometricError(1)).toEqualEpsilon( provider.getLevelMaximumGeometricError(2) * 2, import__355.Math.EPSILON10 ); }); it("credit is undefined if credit option is not provided", async function() { patchXHRLoad(); const provider = await import__355.VRTheWorldTerrainProvider.fromUrl("made/up/url"); expect(provider.credit).toBeUndefined(); }); it("credit is defined if credit option is provided", async function() { patchXHRLoad(); const provider = await import__355.VRTheWorldTerrainProvider.fromUrl("made/up/url", { credit: "thanks to our awesome made up contributors!" }); expect(provider.credit).toBeDefined(); }); it("does not have a water mask", async function() { patchXHRLoad(); const provider = await import__355.VRTheWorldTerrainProvider.fromUrl("made/up/url"); expect(provider.hasWaterMask).toBe(false); }); it("fromUrl throws if the SRS is not supported", async function() { patchXHRLoad(); import__355.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { setTimeout(function() { const parser = new DOMParser(); const xmlString = 'Hawaii World elevlayer to make cesium work rightEPSG:foo'; const xml = parser.parseFromString(xmlString, "text/xml"); deferred.resolve(xml); }, 1); }; await expectAsync( import__355.VRTheWorldTerrainProvider.fromUrl("made/up/url") ).toBeRejectedWithError( import__355.RuntimeError, "An error occurred while accessing made/up/url: SRS EPSG:foo is not supported" ); }); describe("requestTileGeometry", function() { it("provides HeightmapTerrainData", async function() { patchXHRLoad(); const baseUrl = "made/up/url"; import__355.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { expect(request.url.indexOf(".tif?cesium=true")).toBeGreaterThanOrEqual( 0 ); import__355.Resource._DefaultImplementations.createImage( new import__355.Request({ url: imageUrl }), crossOrigin, deferred ); }; const terrainProvider = await import__355.VRTheWorldTerrainProvider.fromUrl(baseUrl); expect(terrainProvider.tilingScheme).toBeInstanceOf( import__355.GeographicTilingScheme ); const loadedData = await terrainProvider.requestTileGeometry(0, 0, 0); expect(loadedData).toBeInstanceOf(import__355.HeightmapTerrainData); }); it("returns undefined if too many requests are already in progress", async function() { patchXHRLoad(); const baseUrl = "made/up/url"; const terrainProvider = await import__355.VRTheWorldTerrainProvider.fromUrl(baseUrl); import__355.RequestScheduler.maximumRequestsPerServer = 0; expect( terrainProvider.requestTileGeometry(0, 0, 0, createRequest()) ).toBeUndefined(); }); }); }); // packages/engine/Specs/Core/VertexFormatSpec.js var import__356 = __toESM(require_Cesium(), 1); describe("Core/VertexFormat", function() { it("clone", function() { const vertexFormat = new import__356.VertexFormat({ position: true, normal: true }); const cloned = import__356.VertexFormat.clone(vertexFormat); expect(cloned).toBeInstanceOf(import__356.VertexFormat); expect(cloned).toEqual(vertexFormat); }); it("clone uses result parameter if provided", function() { const vertexFormat = new import__356.VertexFormat({ position: true, normal: true }); const result = new import__356.VertexFormat(); const cloned = import__356.VertexFormat.clone(vertexFormat, result); expect(cloned).toBe(result); expect(cloned).toEqual(vertexFormat); }); createPackableSpecs_default(import__356.VertexFormat, import__356.VertexFormat.POSITION_AND_NORMAL, [ 1, 1, 0, 0, 0, 0 ]); }); // packages/engine/Specs/Core/VerticalExaggerationSpec.js var import__357 = __toESM(require_Cesium(), 1); describe("Core/VerticalExaggeration", function() { it("getHeight leaves heights unchanged with a scale of 1.0", function() { const height = 100; const scale = 1; const relativeHeight = 0; const result = import__357.VerticalExaggeration.getHeight( height, scale, relativeHeight ); expect(result).toEqual(height); }); it("getHeight scales up heights above relativeHeight", function() { const height = 150; const scale = 2; const relativeHeight = 100; const result = import__357.VerticalExaggeration.getHeight( height, scale, relativeHeight ); expect(result).toEqual(200); }); it("getHeight does not change heights equal to relativeHeight", function() { const height = 100; const scale = 1; const relativeHeight = 100; const result = import__357.VerticalExaggeration.getHeight( height, scale, relativeHeight ); expect(result).toEqual(100); }); it("getHeight scales down heights below relativeHeight", function() { const height = 100; const scale = 2; const relativeHeight = 200; const result = import__357.VerticalExaggeration.getHeight( height, scale, relativeHeight ); expect(result).toEqual(0); }); it("getPosition leaves positions unchanged with a scale of 1.0", function() { const position = import__357.Cartesian3.fromRadians(0, 0, 100); const ellipsoid = import__357.Ellipsoid.WGS84; const verticalExaggeration = 1; const verticalExaggerationRelativeHeight = 0; const result = import__357.VerticalExaggeration.getPosition( position, ellipsoid, verticalExaggeration, verticalExaggerationRelativeHeight ); expect(result).toEqualEpsilon(position, import__357.Math.EPSILON8); }); it("getPosition scales up positions above relativeHeight", function() { const position = import__357.Cartesian3.fromRadians(0, 0, 150); const ellipsoid = import__357.Ellipsoid.WGS84; const verticalExaggeration = 2; const verticalExaggerationRelativeHeight = 100; const result = import__357.VerticalExaggeration.getPosition( position, ellipsoid, verticalExaggeration, verticalExaggerationRelativeHeight ); expect(result).toEqualEpsilon( import__357.Cartesian3.fromRadians(0, 0, 200), import__357.Math.EPSILON8 ); }); it("getPosition does not change positions equal to relativeHeight", function() { const position = import__357.Cartesian3.fromRadians(0, 0, 100); const ellipsoid = import__357.Ellipsoid.WGS84; const verticalExaggeration = 1; const verticalExaggerationRelativeHeight = 100; const result = import__357.VerticalExaggeration.getPosition( position, ellipsoid, verticalExaggeration, verticalExaggerationRelativeHeight ); expect(result).toEqualEpsilon(position, import__357.Math.EPSILON8); }); it("getPosition scales down positions below relativeHeight", function() { const position = import__357.Cartesian3.fromRadians(0, 0, 100); const ellipsoid = import__357.Ellipsoid.WGS84; const verticalExaggeration = 2; const verticalExaggerationRelativeHeight = 200; const result = import__357.VerticalExaggeration.getPosition( position, ellipsoid, verticalExaggeration, verticalExaggerationRelativeHeight ); expect(result).toEqualEpsilon( import__357.Cartesian3.fromRadians(0, 0, 0), import__357.Math.EPSILON8 ); }); }); // packages/engine/Specs/Core/VideoSynchronizerSpec.js var import__358 = __toESM(require_Cesium(), 1); var import__359 = __toESM(require_Cesium(), 1); describe("Core/VideoSynchronizer", function() { if (import__358.FeatureDetection.isInternetExplorer()) { return; } function loadVideo() { const element = document.createElement("video"); let source = document.createElement("source"); source.setAttribute("src", "Data/Videos/big-buck-bunny-trailer-small.webm"); source.setAttribute("type", "video/webm"); element.appendChild(source); source = document.createElement("source"); source.setAttribute("src", "Data/Videos/big-buck-bunny-trailer-small.mp4"); source.setAttribute("type", "video/mp4"); element.appendChild(source); source = document.createElement("source"); source.setAttribute("src", "Data/Videos/big-buck-bunny-trailer-small.mov"); source.setAttribute("type", "video/quicktime"); element.appendChild(source); return element; } it("Can default construct", function() { const videoSynchronizer = new import__358.VideoSynchronizer(); expect(videoSynchronizer.clock).not.toBeDefined(); expect(videoSynchronizer.element).not.toBeDefined(); expect(videoSynchronizer.epoch).toBe(import__358.Iso8601.MINIMUM_VALUE); expect(videoSynchronizer.tolerance).toBe(1); expect(videoSynchronizer.isDestroyed()).toBe(false); expect(videoSynchronizer.destroy()).not.toBeDefined(); expect(videoSynchronizer.isDestroyed()).toBe(true); }); it("Can construct with options", function() { const clock = new import__358.Clock(); const element = document.createElement("video"); const epoch = new import__358.JulianDate(); const tolerance = 0.15; const videoSynchronizer = new import__358.VideoSynchronizer({ clock, element, epoch, tolerance }); expect(videoSynchronizer.clock).toBe(clock); expect(videoSynchronizer.element).toBe(element); expect(videoSynchronizer.epoch).toBe(epoch); expect(videoSynchronizer.tolerance).toBe(tolerance); expect(videoSynchronizer.isDestroyed()).toBe(false); expect(videoSynchronizer.destroy()).not.toBeDefined(); expect(videoSynchronizer.isDestroyed()).toBe(true); }); it("Syncs time when looping", function() { const epoch = import__358.JulianDate.fromIso8601("2015-11-01T00:00:00Z"); const clock = new import__358.Clock(); clock.shouldAnimate = false; clock.currentTime = epoch.clone(); const element = loadVideo(); element.loop = true; const videoSynchronizer = new import__358.VideoSynchronizer({ clock, element, epoch }); return pollToPromise_default(function() { clock.tick(); return element.currentTime === 0; }).then(function() { clock.currentTime = import__358.JulianDate.addSeconds(epoch, 10, clock.currentTime); return pollToPromise_default(function() { clock.tick(); return element.currentTime === 10; }); }).then(function() { clock.currentTime = import__358.JulianDate.addSeconds(epoch, 60, clock.currentTime); return pollToPromise_default(function() { clock.tick(); return import__359.Math.equalsEpsilon( element.currentTime, 60 - element.duration, import__359.Math.EPSILON3 ); }); }).then(function() { clock.currentTime = import__358.JulianDate.addSeconds(epoch, -1, clock.currentTime); return pollToPromise_default(function() { clock.tick(); return import__359.Math.equalsEpsilon( element.currentTime, element.duration - 1, import__359.Math.EPSILON1 ); }); }).then(function() { videoSynchronizer.destroy(); }); }); it("Syncs time when not looping", function() { const epoch = import__358.JulianDate.fromIso8601("2015-11-01T00:00:00Z"); const clock = new import__358.Clock(); clock.shouldAnimate = false; clock.currentTime = epoch.clone(); const element = loadVideo(); const videoSynchronizer = new import__358.VideoSynchronizer({ clock, element, epoch }); return pollToPromise_default(function() { clock.tick(); return element.currentTime === 0; }).then(function() { clock.currentTime = import__358.JulianDate.addSeconds(epoch, 10, clock.currentTime); return pollToPromise_default(function() { clock.tick(); return element.currentTime === 10; }); }).then(function() { clock.currentTime = import__358.JulianDate.addSeconds(epoch, 60, clock.currentTime); return pollToPromise_default(function() { clock.tick(); return import__359.Math.equalsEpsilon( element.currentTime, element.duration, import__359.Math.EPSILON3 ); }); }).then(function() { clock.currentTime = import__358.JulianDate.addSeconds(epoch, -1, clock.currentTime); return pollToPromise_default(function() { clock.tick(); return element.currentTime === 0; }); }).then(function() { videoSynchronizer.destroy(); }); }); it("Plays/pauses video based on clock", function() { const epoch = import__358.JulianDate.fromIso8601("2015-11-01T00:00:00Z"); const clock = new import__358.Clock(); const element = jasmine.createSpyObj("MockVideoElement", [ "addEventListener", "removeEventListener", "play", "pause" ]); element.paused = false; element.play.and.callFake(function() { this.paused = false; }); element.pause.and.callFake(function() { this.paused = true; }); const videoSynchronizer = new import__358.VideoSynchronizer({ clock, element, epoch }); clock.shouldAnimate = false; clock.tick(); expect(element.pause.calls.count()).toEqual(1); clock.shouldAnimate = true; clock.tick(); expect(element.play.calls.count()).toEqual(1); clock.shouldAnimate = false; clock.tick(); expect(element.pause.calls.count()).toEqual(2); videoSynchronizer.destroy(); }); }); // packages/engine/Specs/Core/WallGeometrySpec.js var import__360 = __toESM(require_Cesium(), 1); var import__361 = __toESM(require_Cesium(), 1); describe("Core/WallGeometry", function() { const ellipsoid = import__360.Ellipsoid.WGS84; it("throws with no positions", function() { expect(function() { return new import__360.WallGeometry(); }).toThrowDeveloperError(); }); it("throws when positions and minimumHeights length do not match", function() { expect(function() { return new import__360.WallGeometry({ positions: new Array(2), minimumHeights: new Array(3) }); }).toThrowDeveloperError(); }); it("throws when positions and maximumHeights length do not match", function() { expect(function() { return new import__360.WallGeometry({ positions: new Array(2), maximumHeights: new Array(3) }); }).toThrowDeveloperError(); }); it("returns undefined with less than 2 unique positions", function() { const geometry = import__360.WallGeometry.createGeometry( new import__360.WallGeometry({ positions: import__360.Cartesian3.fromDegreesArrayHeights([ 49, 18, 1e3, 49, 18, 5e3, 49, 18, 1e3 ]) }) ); expect(geometry).toBeUndefined(); }); it("returns undefined with no heights", function() { let geometry = import__360.WallGeometry.createGeometry( new import__360.WallGeometry({ positions: import__360.Cartesian3.fromDegreesArray([ 49, 18, 49, 18, 49, 18 ]) }) ); expect(geometry).toBeUndefined(); geometry = import__360.WallGeometry.createGeometry( new import__360.WallGeometry({ positions: import__360.Cartesian3.fromDegreesArray([ 49, 18, 49, 18, 49, 18 ]), maximumHeights: [0, 0, 0] }) ); expect(geometry).toBeUndefined(); }); it("does not throw when positions are unique but close", function() { import__360.WallGeometry.createGeometry( new import__360.WallGeometry({ vertexFormat: import__360.VertexFormat.POSITION_ONLY, positions: import__360.Cartesian3.fromDegreesArray([ -47.93121266896352, -15.771192496304398, -47.93119792786269, -15.771148001875085 ]) }) ); }); it("creates positions relative to ellipsoid", function() { const w = import__360.WallGeometry.createGeometry( new import__360.WallGeometry({ vertexFormat: import__360.VertexFormat.POSITION_ONLY, positions: import__360.Cartesian3.fromDegreesArrayHeights([ 49, 18, 1e3, 50, 18, 1e3 ]) }) ); const positions2 = w.attributes.position.values; const numPositions = 4; const numTriangles = 2; expect(positions2.length).toEqual(numPositions * 3); expect(w.indices.length).toEqual(numTriangles * 3); let cartographic = ellipsoid.cartesianToCartographic( import__360.Cartesian3.fromArray(positions2, 0) ); expect(cartographic.height).toEqualEpsilon(0, import__361.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__360.Cartesian3.fromArray(positions2, 3) ); expect(cartographic.height).toEqualEpsilon(1e3, import__361.Math.EPSILON8); }); it("creates positions when first and last positions are equal", function() { const w = import__360.WallGeometry.createGeometry( new import__360.WallGeometry({ vertexFormat: import__360.VertexFormat.POSITION_ONLY, positions: import__360.Cartesian3.fromDegreesArrayHeights([ -107, 43, 1e3, -106, 43, 1e3, -106, 42, 1e3, -107, 42, 1e3, -107, 43, 1e3 ]) }) ); const positions2 = w.attributes.position.values; const numPositions = 16; const numTriangles = 8; expect(positions2.length).toEqual(numPositions * 3); expect(w.indices.length).toEqual(numTriangles * 3); let cartographic = ellipsoid.cartesianToCartographic( import__360.Cartesian3.fromArray(positions2, 0) ); expect(cartographic.height).toEqualEpsilon(0, import__361.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__360.Cartesian3.fromArray(positions2, 3) ); expect(cartographic.height).toEqualEpsilon(1e3, import__361.Math.EPSILON8); }); it("creates positions with minimum and maximum heights", function() { const w = import__360.WallGeometry.createGeometry( new import__360.WallGeometry({ vertexFormat: import__360.VertexFormat.POSITION_ONLY, positions: import__360.Cartesian3.fromDegreesArrayHeights([ 49, 18, 1e3, 50, 18, 1e3 ]), minimumHeights: [1e3, 2e3], maximumHeights: [3e3, 4e3] }) ); const positions2 = w.attributes.position.values; const numPositions = 4; const numTriangles = 2; expect(positions2.length).toEqual(numPositions * 3); expect(w.indices.length).toEqual(numTriangles * 3); let cartographic = ellipsoid.cartesianToCartographic( import__360.Cartesian3.fromArray(positions2, 0) ); expect(cartographic.height).toEqualEpsilon(1e3, import__361.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__360.Cartesian3.fromArray(positions2, 3) ); expect(cartographic.height).toEqualEpsilon(3e3, import__361.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__360.Cartesian3.fromArray(positions2, 6) ); expect(cartographic.height).toEqualEpsilon(2e3, import__361.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__360.Cartesian3.fromArray(positions2, 9) ); expect(cartographic.height).toEqualEpsilon(4e3, import__361.Math.EPSILON8); }); it("cleans positions with duplicates", function() { const w = import__360.WallGeometry.createGeometry( new import__360.WallGeometry({ vertexFormat: import__360.VertexFormat.POSITION_ONLY, positions: import__360.Cartesian3.fromDegreesArrayHeights([ 49, 18, 1e3, 49, 18, 2e3, 50, 18, 1e3, 50, 18, 1e3, 50, 18, 1e3, 51, 18, 1e3, 51, 18, 1e3 ]) }) ); const numPositions = 8; const numTriangles = 4; const positions2 = w.attributes.position.values; expect(positions2.length).toEqual(numPositions * 3); expect(w.indices.length).toEqual(numTriangles * 3); let cartographic = ellipsoid.cartesianToCartographic( import__360.Cartesian3.fromArray(positions2, 0) ); expect(cartographic.height).toEqualEpsilon(0, import__361.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__360.Cartesian3.fromArray(positions2, 3) ); expect(cartographic.height).toEqualEpsilon(2e3, import__361.Math.EPSILON8); }); it("removes duplicates with very small difference", function() { const w = import__360.WallGeometry.createGeometry( new import__360.WallGeometry({ vertexFormat: import__360.VertexFormat.POSITION_ONLY, positions: [ new import__360.Cartesian3( 4347090215457887e-9, 1.0614034237998386e6, 4538066036525028e-9 ), new import__360.Cartesian3( 4348147589624987e-9, 1.0438978776143644e6, 4541092234751661e-9 ), new import__360.Cartesian3( 4348147589882754e-9, 1.0438978776762491e6, 4541092234492364e-9 ), new import__360.Cartesian3( 4335659882947743e-9, 1047571602084736e-9, 4552098654605664e-9 ) ] }) ); const numPositions = 8; const numTriangles = 4; const positions2 = w.attributes.position.values; expect(positions2.length).toEqual(numPositions * 3); expect(w.indices.length).toEqual(numTriangles * 3); }); it("does not clean positions that add up past EPSILON10", function() { const eightyPercentOfEpsilon14 = 0.8 * import__361.Math.EPSILON10; const inputPositions = import__360.Cartesian3.fromRadiansArrayHeights([ 1, 1, 1e3, 1, 1 + eightyPercentOfEpsilon14, 1e3, 1, 1 + 2 * eightyPercentOfEpsilon14, 1e3, 1, 1 + 3 * eightyPercentOfEpsilon14, 1e3 ]); const w = import__360.WallGeometry.createGeometry( new import__360.WallGeometry({ vertexFormat: import__360.VertexFormat.POSITION_ONLY, positions: inputPositions }) ); expect(w).toBeDefined(); const expectedPositions = import__360.Cartesian3.fromRadiansArrayHeights([ 1, 1, 1e3, 1, 1 + 2 * eightyPercentOfEpsilon14, 1e3 ]); const expectedW = import__360.WallGeometry.createGeometry( new import__360.WallGeometry({ vertexFormat: import__360.VertexFormat.POSITION_ONLY, positions: expectedPositions }) ); const positions2 = w.attributes.position.values; expect(positions2.length).toEqual( expectedW.attributes.position.values.length ); }); it("cleans selects maximum height from duplicates", function() { const w = import__360.WallGeometry.createGeometry( new import__360.WallGeometry({ vertexFormat: import__360.VertexFormat.POSITION_ONLY, positions: import__360.Cartesian3.fromDegreesArrayHeights([ 49, 18, 1e3, 50, 18, 1e3, 50, 18, 6e3, 50, 18, 1e4, 51, 18, 1e3 ]) }) ); const numPositions = 8; const numTriangles = 4; const positions2 = w.attributes.position.values; expect(positions2.length).toEqual(numPositions * 3); expect(w.indices.length).toEqual(numTriangles * 3); let cartographic = ellipsoid.cartesianToCartographic( import__360.Cartesian3.fromArray(positions2, 0) ); expect(cartographic.height).toEqualEpsilon(0, import__361.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__360.Cartesian3.fromArray(positions2, 9) ); expect(cartographic.height).toEqualEpsilon(1e4, import__361.Math.EPSILON8); }); it("creates all attributes", function() { const w = import__360.WallGeometry.createGeometry( new import__360.WallGeometry({ vertexFormat: import__360.VertexFormat.ALL, positions: import__360.Cartesian3.fromDegreesArrayHeights([ 49, 18, 1e3, 50, 18, 1e3, 51, 18, 1e3 ]) }) ); const numPositions = 8; const numTriangles = 4; expect(w.attributes.position.values.length).toEqual(numPositions * 3); expect(w.attributes.normal.values.length).toEqual(numPositions * 3); expect(w.attributes.tangent.values.length).toEqual(numPositions * 3); expect(w.attributes.bitangent.values.length).toEqual(numPositions * 3); expect(w.attributes.st.values.length).toEqual(numPositions * 2); expect(w.indices.length).toEqual(numTriangles * 3); }); it("creates correct texture coordinates", function() { const w = import__360.WallGeometry.createGeometry( new import__360.WallGeometry({ vertexFormat: import__360.VertexFormat.ALL, positions: import__360.Cartesian3.fromDegreesArrayHeights([ 49, 18, 1e3, 50, 18, 1e3, 51, 18, 1e3 ]) }) ); expect(w.attributes.st.values.length).toEqual(4 * 2 * 2); expect(w.attributes.st.values).toEqual([ 0, 0, 0, 1, 0.5, 0, 0.5, 1, 0.5, 0, 0.5, 1, 1, 0, 1, 1 ]); }); it("creates correct texture coordinates when there are duplicate wall positions", function() { const w = import__360.WallGeometry.createGeometry( new import__360.WallGeometry({ vertexFormat: import__360.VertexFormat.ALL, positions: import__360.Cartesian3.fromDegreesArrayHeights([ 49, 18, 1e3, 50, 18, 1e3, 50, 18, 1e3, 51, 18, 1e3 ]) }) ); expect(w.attributes.st.values.length).toEqual(4 * 2 * 2); expect(w.attributes.st.values).toEqual([ 0, 0, 0, 1, 0.5, 0, 0.5, 1, 0.5, 0, 0.5, 1, 1, 0, 1, 1 ]); }); it("fromConstantHeights throws without positions", function() { expect(function() { return import__360.WallGeometry.fromConstantHeights(); }).toThrowDeveloperError(); }); it("creates positions with constant minimum and maximum heights", function() { const min = 1e3; const max = 2e3; const w = import__360.WallGeometry.createGeometry( import__360.WallGeometry.fromConstantHeights({ vertexFormat: import__360.VertexFormat.POSITION_ONLY, positions: import__360.Cartesian3.fromDegreesArrayHeights([ 49, 18, 1e3, 50, 18, 1e3 ]), minimumHeight: min, maximumHeight: max }) ); const numPositions = 4; const numTriangles = 2; const positions2 = w.attributes.position.values; expect(positions2.length).toEqual(numPositions * 3); expect(w.indices.length).toEqual(numTriangles * 3); let cartographic = ellipsoid.cartesianToCartographic( import__360.Cartesian3.fromArray(positions2, 0) ); expect(cartographic.height).toEqualEpsilon(min, import__361.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__360.Cartesian3.fromArray(positions2, 3) ); expect(cartographic.height).toEqualEpsilon(max, import__361.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__360.Cartesian3.fromArray(positions2, 6) ); expect(cartographic.height).toEqualEpsilon(min, import__361.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__360.Cartesian3.fromArray(positions2, 9) ); expect(cartographic.height).toEqualEpsilon(max, import__361.Math.EPSILON8); }); const positions = [ new import__360.Cartesian3(1, 0, 0), new import__360.Cartesian3(0, 1, 0), new import__360.Cartesian3(0, 0, 1) ]; const wall = new import__360.WallGeometry({ positions, vertexFormat: import__360.VertexFormat.POSITION_ONLY, granularity: 0.01, ellipsoid: import__360.Ellipsoid.UNIT_SPHERE }); const packedInstance = [ 3, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0.01 ]; createPackableSpecs_default(import__360.WallGeometry, wall, packedInstance); }); // packages/engine/Specs/Core/WallOutlineGeometrySpec.js var import__362 = __toESM(require_Cesium(), 1); var import__363 = __toESM(require_Cesium(), 1); describe("Core/WallOutlineGeometry", function() { const ellipsoid = import__362.Ellipsoid.WGS84; it("throws with no positions", function() { expect(function() { return new import__362.WallOutlineGeometry(); }).toThrowDeveloperError(); }); it("throws when positions and minimumHeights length do not match", function() { expect(function() { return new import__362.WallOutlineGeometry({ positions: new Array(2), minimumHeights: new Array(3) }); }).toThrowDeveloperError(); }); it("throws when positions and maximumHeights length do not match", function() { expect(function() { return new import__362.WallOutlineGeometry({ positions: new Array(2), maximumHeights: new Array(3) }); }).toThrowDeveloperError(); }); it("returns undefined with less than 2 unique positions", function() { const geometry = import__362.WallOutlineGeometry.createGeometry( new import__362.WallOutlineGeometry({ positions: import__362.Cartesian3.fromDegreesArrayHeights([ 49, 18, 1e3, 49, 18, 5e3, 49, 18, 1e3 ]) }) ); expect(geometry).toBeUndefined(); }); it("returns undefined with no heights", function() { let geometry = import__362.WallOutlineGeometry.createGeometry( new import__362.WallOutlineGeometry({ positions: import__362.Cartesian3.fromDegreesArray([ 49, 18, 49, 18, 49, 18 ]) }) ); expect(geometry).toBeUndefined(); geometry = import__362.WallOutlineGeometry.createGeometry( new import__362.WallOutlineGeometry({ positions: import__362.Cartesian3.fromDegreesArray([ 49, 18, 49, 18, 49, 18 ]), maximumHeights: [0, 0, 0] }) ); expect(geometry).toBeUndefined(); }); it("creates positions relative to ellipsoid", function() { const w = import__362.WallOutlineGeometry.createGeometry( new import__362.WallOutlineGeometry({ positions: import__362.Cartesian3.fromDegreesArrayHeights([ 49, 18, 1e3, 50, 18, 1e3 ]), granularity: Math.PI }) ); const positions2 = w.attributes.position.values; expect(positions2.length).toEqual(4 * 3); expect(w.indices.length).toEqual(4 * 2); let cartographic = ellipsoid.cartesianToCartographic( import__362.Cartesian3.fromArray(positions2, 0) ); expect(cartographic.height).toEqualEpsilon(0, import__363.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__362.Cartesian3.fromArray(positions2, 3) ); expect(cartographic.height).toEqualEpsilon(1e3, import__363.Math.EPSILON8); }); it("creates positions with minimum and maximum heights", function() { const w = import__362.WallOutlineGeometry.createGeometry( new import__362.WallOutlineGeometry({ positions: import__362.Cartesian3.fromDegreesArrayHeights([ 49, 18, 1e3, 50, 18, 1e3 ]), minimumHeights: [1e3, 2e3], maximumHeights: [3e3, 4e3], granularity: Math.PI }) ); const positions2 = w.attributes.position.values; expect(positions2.length).toEqual(4 * 3); expect(w.indices.length).toEqual(4 * 2); let cartographic = ellipsoid.cartesianToCartographic( import__362.Cartesian3.fromArray(positions2, 0) ); expect(cartographic.height).toEqualEpsilon(1e3, import__363.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__362.Cartesian3.fromArray(positions2, 3) ); expect(cartographic.height).toEqualEpsilon(3e3, import__363.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__362.Cartesian3.fromArray(positions2, 6) ); expect(cartographic.height).toEqualEpsilon(2e3, import__363.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__362.Cartesian3.fromArray(positions2, 9) ); expect(cartographic.height).toEqualEpsilon(4e3, import__363.Math.EPSILON8); }); it("cleans positions with duplicates", function() { const w = import__362.WallOutlineGeometry.createGeometry( new import__362.WallOutlineGeometry({ positions: import__362.Cartesian3.fromDegreesArrayHeights([ 49, 18, 1e3, 49, 18, 2e3, 50, 18, 1e3, 50, 18, 1e3, 50, 18, 1e3, 51, 18, 1e3, 51, 18, 1e3 ]) }) ); const positions2 = w.attributes.position.values; expect(positions2.length).toEqual(6 * 3); expect(w.indices.length).toEqual(7 * 2); let cartographic = ellipsoid.cartesianToCartographic( import__362.Cartesian3.fromArray(positions2, 0) ); expect(cartographic.height).toEqualEpsilon(0, import__363.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__362.Cartesian3.fromArray(positions2, 3) ); expect(cartographic.height).toEqualEpsilon(2e3, import__363.Math.EPSILON8); }); it("fromConstantHeights throws without positions", function() { expect(function() { return import__362.WallOutlineGeometry.fromConstantHeights(); }).toThrowDeveloperError(); }); it("creates positions with constant minimum and maximum heights", function() { const min = 1e3; const max = 2e3; const w = import__362.WallOutlineGeometry.createGeometry( import__362.WallOutlineGeometry.fromConstantHeights({ positions: import__362.Cartesian3.fromDegreesArrayHeights([ 49, 18, 1e3, 50, 18, 1e3 ]), minimumHeight: min, maximumHeight: max }) ); const positions2 = w.attributes.position.values; expect(positions2.length).toEqual(4 * 3); expect(w.indices.length).toEqual(4 * 2); let cartographic = ellipsoid.cartesianToCartographic( import__362.Cartesian3.fromArray(positions2, 0) ); expect(cartographic.height).toEqualEpsilon(min, import__363.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__362.Cartesian3.fromArray(positions2, 3) ); expect(cartographic.height).toEqualEpsilon(max, import__363.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__362.Cartesian3.fromArray(positions2, 6) ); expect(cartographic.height).toEqualEpsilon(min, import__363.Math.EPSILON8); cartographic = ellipsoid.cartesianToCartographic( import__362.Cartesian3.fromArray(positions2, 9) ); expect(cartographic.height).toEqualEpsilon(max, import__363.Math.EPSILON8); }); const positions = [ new import__362.Cartesian3(1, 0, 0), new import__362.Cartesian3(0, 1, 0), new import__362.Cartesian3(0, 0, 1) ]; const wall = new import__362.WallOutlineGeometry({ positions, granularity: 0.01, ellipsoid: import__362.Ellipsoid.UNIT_SPHERE }); const packedInstance = [ 3, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0.01 ]; createPackableSpecs_default(import__362.WallOutlineGeometry, wall, packedInstance); }); // packages/engine/Specs/Core/WebMercatorProjectionSpec.js var import__364 = __toESM(require_Cesium(), 1); var import__365 = __toESM(require_Cesium(), 1); describe("Core/WebMercatorProjection", function() { it("construct0", function() { const projection = new import__364.WebMercatorProjection(); expect(projection.ellipsoid).toEqual(import__364.Ellipsoid.WGS84); }); it("construct1", function() { const ellipsoid = import__364.Ellipsoid.UNIT_SPHERE; const projection = new import__364.WebMercatorProjection(ellipsoid); expect(projection.ellipsoid).toEqual(ellipsoid); }); it("project0", function() { const height = 10; const cartographic = new import__364.Cartographic(0, 0, height); const projection = new import__364.WebMercatorProjection(); expect(projection.project(cartographic)).toEqual( new import__364.Cartesian3(0, 0, height) ); }); it("project1", function() { const ellipsoid = import__364.Ellipsoid.WGS84; const cartographic = new import__364.Cartographic( Math.PI, import__365.Math.PI_OVER_FOUR, 0 ); const expected = new import__364.Cartesian3( ellipsoid.maximumRadius * cartographic.longitude, ellipsoid.maximumRadius * Math.log(Math.tan(Math.PI / 4 + cartographic.latitude / 2)), 0 ); const projection = new import__364.WebMercatorProjection(ellipsoid); expect(projection.project(cartographic)).toEqualEpsilon( expected, import__365.Math.EPSILON8 ); }); it("project2", function() { const ellipsoid = import__364.Ellipsoid.UNIT_SPHERE; const cartographic = new import__364.Cartographic( -Math.PI, import__365.Math.PI_OVER_FOUR, 0 ); const expected = new import__364.Cartesian3( ellipsoid.maximumRadius * cartographic.longitude, ellipsoid.maximumRadius * Math.log(Math.tan(Math.PI / 4 + cartographic.latitude / 2)), 0 ); const projection = new import__364.WebMercatorProjection(ellipsoid); expect(projection.project(cartographic)).toEqualEpsilon( expected, import__365.Math.EPSILON15 ); }); it("project3", function() { const ellipsoid = import__364.Ellipsoid.WGS84; const cartographic = new import__364.Cartographic( Math.PI, import__365.Math.PI_OVER_FOUR, 0 ); const expected = new import__364.Cartesian3( ellipsoid.maximumRadius * cartographic.longitude, ellipsoid.maximumRadius * Math.log(Math.tan(Math.PI / 4 + cartographic.latitude / 2)), 0 ); const projection = new import__364.WebMercatorProjection(ellipsoid); const result = new import__364.Cartesian3(0, 0, 0); const returnValue = projection.project(cartographic, result); expect(result).toEqual(returnValue); expect(result).toEqualEpsilon(expected, import__365.Math.EPSILON8); }); it("unproject0", function() { const cartographic = new import__364.Cartographic( import__365.Math.PI_OVER_TWO, import__365.Math.PI_OVER_FOUR, 12 ); const projection = new import__364.WebMercatorProjection(); const projected = projection.project(cartographic); expect(projection.unproject(projected)).toEqualEpsilon( cartographic, import__365.Math.EPSILON14 ); }); it("unproject1", function() { const cartographic = new import__364.Cartographic( import__365.Math.PI_OVER_TWO, import__365.Math.PI_OVER_FOUR, 12 ); const projection = new import__364.WebMercatorProjection(); const projected = projection.project(cartographic); const result = new import__364.Cartographic(0, 0, 0); const returnValue = projection.unproject(projected, result); expect(result).toEqual(returnValue); expect(result).toEqualEpsilon(cartographic, import__365.Math.EPSILON14); }); it("unproject is correct at corners", function() { const projection = new import__364.WebMercatorProjection(); const southwest = projection.unproject( new import__364.Cartesian2(-20037508342787e-6, -20037508342787e-6) ); expect(southwest.longitude).toEqualEpsilon(-Math.PI, import__365.Math.EPSILON12); expect(southwest.latitude).toEqualEpsilon( import__365.Math.toRadians(-85.05112878), import__365.Math.EPSILON11 ); const southeast = projection.unproject( new import__364.Cartesian2(20037508342787e-6, -20037508342787e-6) ); expect(southeast.longitude).toEqualEpsilon(Math.PI, import__365.Math.EPSILON12); expect(southeast.latitude).toEqualEpsilon( import__365.Math.toRadians(-85.05112878), import__365.Math.EPSILON11 ); const northeast = projection.unproject( new import__364.Cartesian2(20037508342787e-6, 20037508342787e-6) ); expect(northeast.longitude).toEqualEpsilon(Math.PI, import__365.Math.EPSILON12); expect(northeast.latitude).toEqualEpsilon( import__365.Math.toRadians(85.05112878), import__365.Math.EPSILON11 ); const northwest = projection.unproject( new import__364.Cartesian2(-20037508342787e-6, 20037508342787e-6) ); expect(northwest.longitude).toEqualEpsilon(-Math.PI, import__365.Math.EPSILON12); expect(northwest.latitude).toEqualEpsilon( import__365.Math.toRadians(85.05112878), import__365.Math.EPSILON11 ); }); it("project is correct at corners.", function() { const maxLatitude = import__364.WebMercatorProjection.MaximumLatitude; const projection = new import__364.WebMercatorProjection(); const southwest = projection.project( new import__364.Cartographic(-Math.PI, -maxLatitude) ); expect(southwest.x).toEqualEpsilon(-20037508342787e-6, import__365.Math.EPSILON3); expect(southwest.y).toEqualEpsilon(-20037508342787e-6, import__365.Math.EPSILON3); const southeast = projection.project( new import__364.Cartographic(Math.PI, -maxLatitude) ); expect(southeast.x).toEqualEpsilon(20037508342787e-6, import__365.Math.EPSILON3); expect(southeast.y).toEqualEpsilon(-20037508342787e-6, import__365.Math.EPSILON3); const northeast = projection.project( new import__364.Cartographic(Math.PI, maxLatitude) ); expect(northeast.x).toEqualEpsilon(20037508342787e-6, import__365.Math.EPSILON3); expect(northeast.y).toEqualEpsilon(20037508342787e-6, import__365.Math.EPSILON3); const northwest = projection.project( new import__364.Cartographic(-Math.PI, maxLatitude) ); expect(northwest.x).toEqualEpsilon(-20037508342787e-6, import__365.Math.EPSILON3); expect(northwest.y).toEqualEpsilon(20037508342787e-6, import__365.Math.EPSILON3); }); it("projected y is clamped to valid latitude range.", function() { const projection = new import__364.WebMercatorProjection(); const southPole = projection.project( new import__364.Cartographic(0, -import__365.Math.PI_OVER_TWO) ); const southLimit = projection.project( new import__364.Cartographic(0, -import__364.WebMercatorProjection.MaximumLatitude) ); expect(southPole.y).toEqual(southLimit.y); const northPole = projection.project( new import__364.Cartographic(0, import__365.Math.PI_OVER_TWO) ); const northLimit = projection.project( new import__364.Cartographic(0, import__364.WebMercatorProjection.MaximumLatitude) ); expect(northPole.y).toEqual(northLimit.y); }); it("project throws without cartesian", function() { const projection = new import__364.WebMercatorProjection(); expect(function() { return projection.unproject(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/WebMercatorTilingSchemeSpec.js var import__366 = __toESM(require_Cesium(), 1); var import__367 = __toESM(require_Cesium(), 1); describe("Core/WebMercatorTilingScheme", function() { let tilingScheme; beforeEach(function() { tilingScheme = new import__366.WebMercatorTilingScheme(); }); it("conforms to TilingScheme interface.", function() { expect(import__366.WebMercatorTilingScheme).toConformToInterface(import__366.TilingScheme); }); it("default constructing uses WGS84 ellipsoid", function() { const tilingScheme2 = new import__366.WebMercatorTilingScheme(); expect(tilingScheme2.ellipsoid).toEqual(import__366.Ellipsoid.WGS84); }); it("uses specified ellipsoid", function() { const tilingScheme2 = new import__366.WebMercatorTilingScheme({ ellipsoid: import__366.Ellipsoid.UNIT_SPHERE }); expect(tilingScheme2.ellipsoid).toEqual(import__366.Ellipsoid.UNIT_SPHERE); }); describe("Conversions from tile indices to cartographic rectangles", function() { it("tileXYToRectangle returns full rectangle for single root tile.", function() { const rectangle = tilingScheme.tileXYToRectangle(0, 0, 0); const tilingSchemeRectangle = tilingScheme.rectangle; expect(rectangle.west).toEqualEpsilon( tilingSchemeRectangle.west, import__367.Math.EPSILON10 ); expect(rectangle.south).toEqualEpsilon( tilingSchemeRectangle.south, import__367.Math.EPSILON10 ); expect(rectangle.east).toEqualEpsilon( tilingSchemeRectangle.east, import__367.Math.EPSILON10 ); expect(rectangle.north).toEqualEpsilon( tilingSchemeRectangle.north, import__367.Math.EPSILON10 ); }); it("tileXYToRectangle uses result parameter if provided", function() { const tilingSchemeRectangle = tilingScheme.rectangle; const result = new import__366.Rectangle(0, 0, 0); const rectangle = tilingScheme.tileXYToRectangle(0, 0, 0, result); expect(result).toEqual(rectangle); expect(rectangle.west).toEqualEpsilon( tilingSchemeRectangle.west, import__367.Math.EPSILON10 ); expect(rectangle.south).toEqualEpsilon( tilingSchemeRectangle.south, import__367.Math.EPSILON10 ); expect(rectangle.east).toEqualEpsilon( tilingSchemeRectangle.east, import__367.Math.EPSILON10 ); expect(rectangle.north).toEqualEpsilon( tilingSchemeRectangle.north, import__367.Math.EPSILON10 ); }); it("tiles are numbered from the northwest corner.", function() { const northwest = tilingScheme.tileXYToRectangle(0, 0, 1); const northeast = tilingScheme.tileXYToRectangle(1, 0, 1); const southeast = tilingScheme.tileXYToRectangle(1, 1, 1); const southwest = tilingScheme.tileXYToRectangle(0, 1, 1); expect(northeast.north).toEqual(northwest.north); expect(northeast.south).toEqual(northwest.south); expect(southeast.north).toEqual(southwest.north); expect(southeast.south).toEqual(southwest.south); expect(northwest.west).toEqual(southwest.west); expect(northwest.east).toEqual(southwest.east); expect(northeast.west).toEqual(southeast.west); expect(northeast.east).toEqual(southeast.east); expect(northeast.north).toBeGreaterThan(southeast.north); expect(northeast.south).toBeGreaterThan(southeast.south); expect(northwest.north).toBeGreaterThan(southwest.north); expect(northwest.south).toBeGreaterThan(southwest.south); expect(northeast.east).toBeGreaterThan(northwest.east); expect(northeast.west).toBeGreaterThan(northwest.west); expect(southeast.east).toBeGreaterThan(southwest.east); expect(southeast.west).toBeGreaterThan(southwest.west); }); it("adjacent tiles have overlapping coordinates", function() { const northwest = tilingScheme.tileXYToRectangle(0, 0, 1); const northeast = tilingScheme.tileXYToRectangle(1, 0, 1); const southeast = tilingScheme.tileXYToRectangle(1, 1, 1); const southwest = tilingScheme.tileXYToRectangle(0, 1, 1); expect(northeast.south).toEqualEpsilon( southeast.north, import__367.Math.EPSILON15 ); expect(northwest.south).toEqualEpsilon( southwest.north, import__367.Math.EPSILON15 ); expect(northeast.west).toEqualEpsilon( northwest.east, import__367.Math.EPSILON15 ); expect(southeast.west).toEqualEpsilon( southwest.east, import__367.Math.EPSILON15 ); }); }); describe("Conversions from cartographic positions to tile indices", function() { it("calculates correct tile indices for 4 corners at level 0", function() { let coordinates; const tilingSchemeRectangle = tilingScheme.rectangle; coordinates = tilingScheme.positionToTileXY( import__366.Rectangle.southwest(tilingSchemeRectangle), 0 ); expect(coordinates.x).toEqual(0); expect(coordinates.y).toEqual(0); coordinates = tilingScheme.positionToTileXY( import__366.Rectangle.northwest(tilingSchemeRectangle), 0 ); expect(coordinates.x).toEqual(0); expect(coordinates.y).toEqual(0); coordinates = tilingScheme.positionToTileXY( import__366.Rectangle.northeast(tilingSchemeRectangle), 0 ); expect(coordinates.x).toEqual(0); expect(coordinates.y).toEqual(0); coordinates = tilingScheme.positionToTileXY( import__366.Rectangle.southeast(tilingSchemeRectangle), 0 ); expect(coordinates.x).toEqual(0); expect(coordinates.y).toEqual(0); }); it("calculates correct tile indices for 4 corners at level 1", function() { let coordinates; const tilingSchemeRectangle = tilingScheme.rectangle; coordinates = tilingScheme.positionToTileXY( import__366.Rectangle.southwest(tilingSchemeRectangle), 1 ); expect(coordinates.x).toEqual(0); expect(coordinates.y).toEqual(1); coordinates = tilingScheme.positionToTileXY( import__366.Rectangle.northwest(tilingSchemeRectangle), 1 ); expect(coordinates.x).toEqual(0); expect(coordinates.y).toEqual(0); coordinates = tilingScheme.positionToTileXY( import__366.Rectangle.northeast(tilingSchemeRectangle), 1 ); expect(coordinates.x).toEqual(1); expect(coordinates.y).toEqual(0); coordinates = tilingScheme.positionToTileXY( import__366.Rectangle.southeast(tilingSchemeRectangle), 1 ); expect(coordinates.x).toEqual(1); expect(coordinates.y).toEqual(1); }); it("calculates correct tile indices for the center at level 1", function() { const coordinates = tilingScheme.positionToTileXY( new import__366.Cartographic(0, 0), 1 ); expect(coordinates.x).toEqual(1); expect(coordinates.y).toEqual(1); }); it("calculates correct tile indices for the center at level 2", function() { const coordinates = tilingScheme.positionToTileXY( new import__366.Cartographic(0, 0), 2 ); expect(coordinates.x).toEqual(2); expect(coordinates.y).toEqual(2); }); it("calculates correct tile indices around the center at level 2", function() { let coordinates; coordinates = tilingScheme.positionToTileXY( new import__366.Cartographic(-0.05, -0.05), 2 ); expect(coordinates.x).toEqual(1); expect(coordinates.y).toEqual(2); coordinates = tilingScheme.positionToTileXY( new import__366.Cartographic(-0.05, 0.05), 2 ); expect(coordinates.x).toEqual(1); expect(coordinates.y).toEqual(1); coordinates = tilingScheme.positionToTileXY( new import__366.Cartographic(0.05, 0.05), 2 ); expect(coordinates.x).toEqual(2); expect(coordinates.y).toEqual(1); coordinates = tilingScheme.positionToTileXY( new import__366.Cartographic(0.05, -0.05), 2 ); expect(coordinates.x).toEqual(2); expect(coordinates.y).toEqual(2); }); }); it("uses a WebMercatorProjection", function() { const tilingScheme2 = new import__366.WebMercatorTilingScheme(); expect(tilingScheme2.projection).toBeInstanceOf(import__366.WebMercatorProjection); }); describe("rectangleToNativeRectangle", function() { it("converts radians to web mercator meters", function() { const tilingScheme2 = new import__366.WebMercatorTilingScheme(); const rectangleInRadians = new import__366.Rectangle(0.1, 0.2, 0.3, 0.4); const nativeRectangle = tilingScheme2.rectangleToNativeRectangle( rectangleInRadians ); const projection = new import__366.WebMercatorProjection(); const expectedSouthwest = projection.project( import__366.Rectangle.southwest(rectangleInRadians) ); const expectedNortheast = projection.project( import__366.Rectangle.northeast(rectangleInRadians) ); expect(nativeRectangle.west).toEqualEpsilon( expectedSouthwest.x, import__367.Math.EPSILON13 ); expect(nativeRectangle.south).toEqualEpsilon( expectedSouthwest.y, import__367.Math.EPSILON13 ); expect(nativeRectangle.east).toEqualEpsilon( expectedNortheast.x, import__367.Math.EPSILON13 ); expect(nativeRectangle.north).toEqualEpsilon( expectedNortheast.y, import__367.Math.EPSILON13 ); }); it("uses result parameter if provided", function() { const tilingScheme2 = new import__366.WebMercatorTilingScheme(); const rectangleInRadians = new import__366.Rectangle(0.1, 0.2, 0.3, 0.4); const projection = new import__366.WebMercatorProjection(); const expectedSouthwest = projection.project( import__366.Rectangle.southwest(rectangleInRadians) ); const expectedNortheast = projection.project( import__366.Rectangle.northeast(rectangleInRadians) ); const resultRectangle = new import__366.Rectangle(0, 0, 0, 0); const outputRectangle = tilingScheme2.rectangleToNativeRectangle( rectangleInRadians, resultRectangle ); expect(outputRectangle).toEqual(resultRectangle); expect(resultRectangle.west).toEqualEpsilon( expectedSouthwest.x, import__367.Math.EPSILON13 ); expect(resultRectangle.south).toEqualEpsilon( expectedSouthwest.y, import__367.Math.EPSILON13 ); expect(resultRectangle.east).toEqualEpsilon( expectedNortheast.x, import__367.Math.EPSILON13 ); expect(resultRectangle.north).toEqualEpsilon( expectedNortheast.y, import__367.Math.EPSILON13 ); }); }); describe("positionToTileXY", function() { it("returns undefined when outside rectangle", function() { const projection = new import__366.WebMercatorProjection(); const rectangleInRadians = new import__366.Rectangle(0.1, 0.2, 0.3, 0.4); const tilingScheme2 = new import__366.WebMercatorTilingScheme({ rectangleSouthwestInMeters: projection.project( import__366.Rectangle.southwest(rectangleInRadians) ), rectangleNortheastInMeters: projection.project( import__366.Rectangle.northeast(rectangleInRadians) ) }); const tooFarWest = new import__366.Cartographic(0.05, 0.3); expect(tilingScheme2.positionToTileXY(tooFarWest, 0)).toBeUndefined(); const tooFarSouth = new import__366.Cartographic(0.2, 0.1); expect(tilingScheme2.positionToTileXY(tooFarSouth, 0)).toBeUndefined(); const tooFarEast = new import__366.Cartographic(0.4, 0.3); expect(tilingScheme2.positionToTileXY(tooFarEast, 0)).toBeUndefined(); const tooFarNorth = new import__366.Cartographic(0.2, 0.5); expect(tilingScheme2.positionToTileXY(tooFarNorth, 0)).toBeUndefined(); }); it("returns correct tile for position in center of tile", function() { const tilingScheme2 = new import__366.WebMercatorTilingScheme(); const centerOfSouthwesternChild = new import__366.Cartographic( -Math.PI / 2, -Math.PI / 4 ); expect( tilingScheme2.positionToTileXY(centerOfSouthwesternChild, 1) ).toEqual(new import__366.Cartesian2(0, 1)); const centerOfNortheasternChild = new import__366.Cartographic( Math.PI / 2, Math.PI / 4 ); expect( tilingScheme2.positionToTileXY(centerOfNortheasternChild, 1) ).toEqual(new import__366.Cartesian2(1, 0)); }); it("returns Southeast tile when on the boundary between tiles", function() { const tilingScheme2 = new import__366.WebMercatorTilingScheme(); const centerOfMap = new import__366.Cartographic(0, 0); expect(tilingScheme2.positionToTileXY(centerOfMap, 1)).toEqual( new import__366.Cartesian2(1, 1) ); }); it("does not return tile outside valid range", function() { const tilingScheme2 = new import__366.WebMercatorTilingScheme(); const southeastCorner = import__366.Rectangle.southeast(tilingScheme2.rectangle); expect(tilingScheme2.positionToTileXY(southeastCorner, 1)).toEqual( new import__366.Cartesian2(1, 1) ); }); it("uses result parameter if supplied", function() { const tilingScheme2 = new import__366.WebMercatorTilingScheme(); const centerOfNortheasternChild = new import__366.Cartographic( Math.PI / 2, Math.PI / 4 ); const resultParameter = new import__366.Cartesian2(0, 0); const returnedResult = tilingScheme2.positionToTileXY( centerOfNortheasternChild, 1, resultParameter ); expect(resultParameter).toEqual(returnedResult); expect(resultParameter).toEqual(new import__366.Cartesian2(1, 0)); }); }); }); // packages/engine/Specs/Core/WireframeIndexGeneratorSpec.js var import__368 = __toESM(require_Cesium(), 1); describe("Core/WireframeIndexGenerator", function() { const createWireframeIndices = import__368.WireframeIndexGenerator.createWireframeIndices; const getWireframeIndicesCount = import__368.WireframeIndexGenerator.getWireframeIndicesCount; it("createWireframeIndices returns undefined for non-triangles", function() { let result = createWireframeIndices(import__368.PrimitiveType.POINTS, 6); expect(result).toBeUndefined(); result = createWireframeIndices(import__368.PrimitiveType.LINES, 6); expect(result).toBeUndefined(); result = createWireframeIndices(import__368.PrimitiveType.LINE_STRIP, 6); expect(result).toBeUndefined(); result = createWireframeIndices(import__368.PrimitiveType.LINE_LOOP, 6); expect(result).toBeUndefined(); }); it("createWireframeIndices works for triangles", function() { const expected = [ 0, 1, 1, 2, 2, 0, // First triangle 3, 4, 4, 5, 5, 3 ]; const result = createWireframeIndices(import__368.PrimitiveType.TRIANGLES, 6); expect(result).toEqual(expected); }); it("createWireframeIndices works for triangles from indices", function() { const indices = [1, 0, 2, 4, 5, 3]; const expected = [ 1, 0, 0, 2, 2, 1, // First triangle 4, 5, 5, 3, 3, 4 ]; const result = createWireframeIndices(import__368.PrimitiveType.TRIANGLES, 6, indices); expect(result).toEqual(expected); }); it("createWireframeIndices works for triangle strip", function() { const expected = [ 0, 1, // First edge of the strip 1, 2, 2, 0, // The next two edges of the first triangle 2, 3, 3, 1, // The next two edges of the third triangle 3, 4, 4, 2, // And so on... 4, 5, 5, 3 ]; const result = createWireframeIndices(import__368.PrimitiveType.TRIANGLE_STRIP, 6); expect(result).toEqual(expected); }); it("createWireframeIndices works for triangle strip from indices", function() { const indices = [1, 0, 2, 4, 5, 3]; const expected = [ 1, 0, // First edge of the strip 0, 2, 2, 1, // The next two edges of the first triangle 2, 4, 4, 0, // The next two edges of the third triangle 4, 5, 5, 2, // And so on... 5, 3, 3, 4 ]; const result = createWireframeIndices( import__368.PrimitiveType.TRIANGLE_STRIP, 6, indices ); expect(result).toEqual(expected); }); it("createWireframeIndices works for triangle fan", function() { const expected = [ 0, 1, // First edge of the fan 1, 2, 2, 0, // The next two edges of the first triangle 2, 3, 3, 0, // The next two edges of the third triangle 3, 4, 4, 0, // And so on... 4, 5, 5, 0 ]; const result = createWireframeIndices(import__368.PrimitiveType.TRIANGLE_FAN, 6); expect(result).toEqual(expected); }); it("createWireframeIndices works for triangle fan from indices", function() { const indices = [1, 0, 2, 4, 5, 3]; const expected = [ 1, 0, // First edge of the fan 0, 2, 2, 1, // The next two edges of the first triangle 2, 4, 4, 1, // The next two edges of the third triangle 4, 5, 5, 1, // And so on... 5, 3, 3, 1 ]; const result = createWireframeIndices( import__368.PrimitiveType.TRIANGLE_FAN, 6, indices ); expect(result).toEqual(expected); }); it("getWireframeIndicesCount returns original count for non-triangles", function() { const originalCount = 6; let result = getWireframeIndicesCount(import__368.PrimitiveType.POINTS, originalCount); expect(result).toEqual(originalCount); result = getWireframeIndicesCount(import__368.PrimitiveType.LINES, originalCount); expect(result).toEqual(originalCount); result = getWireframeIndicesCount(import__368.PrimitiveType.LINE_STRIP, originalCount); expect(result).toEqual(originalCount); result = getWireframeIndicesCount(import__368.PrimitiveType.LINE_LOOP, originalCount); expect(result).toEqual(originalCount); }); it("getWireframeIndicesCount works", function() { const originalCount = 6; let result = getWireframeIndicesCount( import__368.PrimitiveType.TRIANGLES, originalCount ); expect(result).toEqual(12); result = getWireframeIndicesCount( import__368.PrimitiveType.TRIANGLE_STRIP, originalCount ); expect(result).toEqual(18); result = getWireframeIndicesCount( import__368.PrimitiveType.TRIANGLE_FAN, originalCount ); expect(result).toEqual(18); }); }); // packages/engine/Specs/Core/appendForwardSlashSpec.js var import__369 = __toESM(require_Cesium(), 1); describe("Core/appendForwardSlash", function() { it("Appends to a url", function() { expect((0, import__369.appendForwardSlash)("http://cesiumjs.org")).toEqual( "http://cesiumjs.org/" ); }); it("Does not append to a url", function() { expect((0, import__369.appendForwardSlash)("http://cesiumjs.org/")).toEqual( "http://cesiumjs.org/" ); }); it("Appends to an empty string", function() { expect((0, import__369.appendForwardSlash)("")).toEqual("/"); }); }); // packages/engine/Specs/Core/arrayRemoveDuplicatesSpec.js var import__370 = __toESM(require_Cesium(), 1); var import__371 = __toESM(require_Cesium(), 1); describe("Core/arrayRemoveDuplicates", function() { it("removeDuplicates returns positions if none removed - length === 1", function() { const positions = [import__370.Cartesian3.ZERO]; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon ); expect(noDuplicates).toBe(positions); }); it("removeDuplicates returns positions if none removed - length > 1", function() { const positions = [ import__370.Cartesian3.ZERO, import__370.Cartesian3.UNIT_X, import__370.Cartesian3.UNIT_Y, import__370.Cartesian3.UNIT_Z ]; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon ); expect(noDuplicates).toBe(positions); }); it("removeDuplicates wrapping returns positions if none removed", function() { const positions = [ import__370.Cartesian3.ZERO, import__370.Cartesian3.UNIT_X, import__370.Cartesian3.UNIT_Y, import__370.Cartesian3.UNIT_Z ]; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon, true ); expect(noDuplicates).toBe(positions); }); it("removeDuplicates to remove duplicates", function() { const positions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(3, 3, 3), new import__370.Cartesian3(3, 3, 3) ]; const expectedPositions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(3, 3, 3) ]; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon ); expect(noDuplicates).toEqual(expectedPositions); }); it("removeDuplicates doesn't remove duplicates that are nonadjacent", function() { const positions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(3, 3, 3), new import__370.Cartesian3(3, 3, 3) ]; const expectedPositions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(3, 3, 3) ]; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon ); expect(noDuplicates).toEqual(expectedPositions); }); it("removeDuplicates to remove duplicates with anonymous types", function() { const positions = [ { x: 1, y: 1, z: 1 }, { x: 1, y: 1, z: 1 }, { x: 1, y: 1, z: 1 }, { x: 1, y: 1, z: 1 }, { x: 2, y: 2, z: 2 }, { x: 3, y: 3, z: 3 }, { x: 3, y: 3, z: 3 } ]; const expectedPositions = [ { x: 1, y: 1, z: 1 }, { x: 2, y: 2, z: 2 }, { x: 3, y: 3, z: 3 } ]; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon ); expect(noDuplicates).toEqual(expectedPositions); }); it("removeDuplicates to remove duplicates with Spherical type", function() { const positions = [ new import__370.Spherical(1, 1, 1), new import__370.Spherical(1, 1, 1), new import__370.Spherical(1, 1, 1), new import__370.Spherical(1, 1, 1), new import__370.Spherical(2, 2, 1), new import__370.Spherical(3, 3, 1), new import__370.Spherical(3, 3, 2) ]; const expectedPositions = [ new import__370.Spherical(1, 1, 1), new import__370.Spherical(2, 2, 1), new import__370.Spherical(3, 3, 1), new import__370.Spherical(3, 3, 2) ]; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Spherical.equalsEpsilon ); expect(noDuplicates).toEqual(expectedPositions); }); it("removeDuplicates works with empty array", function() { const positions = []; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon ); expect(noDuplicates).toEqual(positions); }); it("removeDuplicates to remove positions within absolute epsilon 10", function() { const positions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 2, 3), new import__370.Cartesian3(1, 2, 3 + import__371.Math.EPSILON10) ]; const expectedPositions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 2, 3) ]; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon ); expect(noDuplicates).toEqual(expectedPositions); }); it("removeDuplicates to remove positions within relative epsilon 10", function() { const positions = [ new import__370.Cartesian3(0, 0, 1e6), new import__370.Cartesian3(0, 0, 3e6), new import__370.Cartesian3(0, 0, 30000000002e-4) ]; const expectedPositions = [ new import__370.Cartesian3(0, 0, 1e6), new import__370.Cartesian3(0, 0, 3e6) ]; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon ); expect(noDuplicates).toEqual(expectedPositions); }); it("removeDuplicates keeps positions that add up past relative epsilon 10", function() { const eightyPercentOfEpsilon = 0.8 * import__371.Math.EPSILON10; const positions = [ new import__370.Cartesian3(0, 0, 1), new import__370.Cartesian3(0, 0, 1 + eightyPercentOfEpsilon), new import__370.Cartesian3(0, 0, 1 + 2 * eightyPercentOfEpsilon), new import__370.Cartesian3(0, 0, 1 + 3 * eightyPercentOfEpsilon) ]; const expectedPositions = [ new import__370.Cartesian3(0, 0, 1), new import__370.Cartesian3(0, 0, 1 + 2 * eightyPercentOfEpsilon) ]; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon ); expect(noDuplicates).toEqual(expectedPositions); }); it("removeDuplicates returns undefined", function() { const noDuplicates = (0, import__370.arrayRemoveDuplicates)( void 0, import__370.Cartesian3.equalsEpsilon ); expect(noDuplicates).toBe(void 0); }); it("removeDuplicates doesn't remove duplicate first and last points without wrapping", function() { const positions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(3, 3, 3), new import__370.Cartesian3(1, 1, 1) ]; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon ); expect(noDuplicates).toBe(positions); }); it("removeDuplicates wrapping removes duplicate first and last points", function() { const positions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(3, 3, 3), new import__370.Cartesian3(1, 1, 1) ]; const expectedPositions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(3, 3, 3) ]; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon, true ); expect(noDuplicates).toEqual(expectedPositions); }); it("removeDuplicates wrapping removes duplicate including first and last points", function() { const positions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(3, 3, 3), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1) ]; const expectedPositions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(3, 3, 3) ]; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon, true ); expect(noDuplicates).toEqual(expectedPositions); }); it("removeDuplicates wrapping removes string of duplicates at end", function() { const positions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(3, 3, 3), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1) ]; const expectedPositions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(3, 3, 3) ]; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon, true ); expect(noDuplicates).toEqual(expectedPositions); }); it("removeDuplicates wrapping doesn't remove nonadjacent duplicates", function() { const positions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(3, 3, 3), new import__370.Cartesian3(1, 1, 1) ]; const expectedPositions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(3, 3, 3) ]; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon, true ); expect(noDuplicates).toEqual(expectedPositions); }); it("removeDuplicates doesn't modify removedIndices when there are no duplicates - length === 1", function() { const positions = [import__370.Cartesian3.ZERO]; const removedIndices = []; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon, false, removedIndices ); expect(noDuplicates).toBe(positions); expect(removedIndices).toEqual([]); }); it("removeDuplicates doesn't modify removedIndices when there are no duplicates - length > 1", function() { const positions = [ import__370.Cartesian3.ZERO, import__370.Cartesian3.UNIT_X, import__370.Cartesian3.UNIT_Y, import__370.Cartesian3.UNIT_Z ]; const removedIndices = []; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon, false, removedIndices ); expect(noDuplicates).toBe(positions); expect(removedIndices).toEqual([]); }); it("removeDuplicates modifies removedIndices when there are duplicates", function() { const positions = [ import__370.Cartesian3.ZERO, import__370.Cartesian3.UNIT_X, import__370.Cartesian3.UNIT_X, import__370.Cartesian3.UNIT_Y, import__370.Cartesian3.UNIT_Z, import__370.Cartesian3.UNIT_Z ]; const expectedPositions = [ import__370.Cartesian3.ZERO, import__370.Cartesian3.UNIT_X, import__370.Cartesian3.UNIT_Y, import__370.Cartesian3.UNIT_Z ]; const removedIndices = []; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon, false, removedIndices ); expect(noDuplicates).toEqual(expectedPositions); expect(removedIndices).toEqual([2, 5]); }); it("removeDuplicates doesn't modify removedIndices when there are duplicates without wrapping", function() { const positions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(3, 3, 3), new import__370.Cartesian3(1, 1, 1) ]; const removedIndices = []; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon, false, removedIndices ); expect(noDuplicates).toBe(positions); expect(removedIndices).toEqual([]); }); it("removeDuplicates modifies removedIndices when there are duplicates wrapped around", function() { const positions = [ import__370.Cartesian3.ZERO, import__370.Cartesian3.UNIT_X, import__370.Cartesian3.UNIT_Y, import__370.Cartesian3.UNIT_Z, import__370.Cartesian3.ZERO ]; const expectedPositions = [ import__370.Cartesian3.ZERO, import__370.Cartesian3.UNIT_X, import__370.Cartesian3.UNIT_Y, import__370.Cartesian3.UNIT_Z ]; const removedIndices = []; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon, true, removedIndices ); expect(noDuplicates).toEqual(expectedPositions); expect(removedIndices).toEqual([4]); }); it("removeDuplicates modifies removedIndices when there are duplicates including wrapped around", function() { const positions = [ import__370.Cartesian3.ZERO, import__370.Cartesian3.ZERO, import__370.Cartesian3.UNIT_X, import__370.Cartesian3.UNIT_Y, import__370.Cartesian3.UNIT_Y, import__370.Cartesian3.UNIT_Z, import__370.Cartesian3.UNIT_Z, import__370.Cartesian3.ZERO ]; const expectedPositions = [ import__370.Cartesian3.ZERO, import__370.Cartesian3.UNIT_X, import__370.Cartesian3.UNIT_Y, import__370.Cartesian3.UNIT_Z ]; const removedIndices = []; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon, true, removedIndices ); expect(noDuplicates).toEqual(expectedPositions); expect(removedIndices).toEqual([1, 4, 6, 7]); }); it("removeDuplicates wrapping modifies indicesRemoved with string of duplicates", function() { const positions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(3, 3, 3), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1) ]; const expectedPositions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(3, 3, 3) ]; const removedIndices = []; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon, true, removedIndices ); expect(noDuplicates).toEqual(expectedPositions); expect(removedIndices).toEqual([1, 4, 5, 6, 7, 8]); }); it("removeDuplicates wrapping modifies indicesRemoved with multiple strings of duplicates", function() { const positions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(3, 3, 3), new import__370.Cartesian3(3, 3, 3), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(3, 3, 3), new import__370.Cartesian3(3, 3, 3), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(1, 1, 1) ]; const expectedPositions = [ new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(2, 2, 2), new import__370.Cartesian3(3, 3, 3), new import__370.Cartesian3(1, 1, 1), new import__370.Cartesian3(3, 3, 3) ]; const removedIndices = []; const noDuplicates = (0, import__370.arrayRemoveDuplicates)( positions, import__370.Cartesian3.equalsEpsilon, true, removedIndices ); expect(noDuplicates).toEqual(expectedPositions); expect(removedIndices).toEqual([1, 4, 6, 7, 9, 10, 11]); }); }); // packages/engine/Specs/Core/barycentricCoordinatesSpec.js var import__372 = __toESM(require_Cesium(), 1); var import__373 = __toESM(require_Cesium(), 1); describe("Core/barycentricCoordinates", function() { const p0 = new import__372.Cartesian3(-1, 0, 0); const p1 = new import__372.Cartesian3(1, 0, 0); const p2 = new import__372.Cartesian3(0, 1, 1); it("evaluates to p0", function() { const point = import__372.Cartesian3.clone(p0); expect((0, import__372.barycentricCoordinates)(point, p0, p1, p2)).toEqual( import__372.Cartesian3.UNIT_X ); }); it("evaluates to p1", function() { const point = import__372.Cartesian3.clone(p1); expect((0, import__372.barycentricCoordinates)(point, p0, p1, p2)).toEqual( import__372.Cartesian3.UNIT_Y ); }); it("evaluates to p2", function() { const point = import__372.Cartesian3.clone(p2); expect((0, import__372.barycentricCoordinates)(point, p0, p1, p2)).toEqual( import__372.Cartesian3.UNIT_Z ); }); it("evaluates on the p0-p1 edge", function() { const point = import__372.Cartesian3.multiplyByScalar( import__372.Cartesian3.add(p1, p0, new import__372.Cartesian3()), 0.5, new import__372.Cartesian3() ); expect((0, import__372.barycentricCoordinates)(point, p0, p1, p2)).toEqual( new import__372.Cartesian3(0.5, 0.5, 0) ); }); it("evaluates on the p0-p2 edge", function() { const point = import__372.Cartesian3.multiplyByScalar( import__372.Cartesian3.add(p2, p0, new import__372.Cartesian3()), 0.5, new import__372.Cartesian3() ); expect((0, import__372.barycentricCoordinates)(point, p0, p1, p2)).toEqual( new import__372.Cartesian3(0.5, 0, 0.5) ); }); it("evaluates on the p1-p2 edge", function() { const point = import__372.Cartesian3.multiplyByScalar( import__372.Cartesian3.add(p2, p1, new import__372.Cartesian3()), 0.5, new import__372.Cartesian3() ); expect((0, import__372.barycentricCoordinates)(point, p0, p1, p2)).toEqual( new import__372.Cartesian3(0, 0.5, 0.5) ); }); it("evaluates on the interior", function() { const scalar = 1 / 3; const point = import__372.Cartesian3.multiplyByScalar( import__372.Cartesian3.add( import__372.Cartesian3.add(p0, p1, new import__372.Cartesian3()), p2, new import__372.Cartesian3() ), scalar, new import__372.Cartesian3() ); expect((0, import__372.barycentricCoordinates)(point, p0, p1, p2)).toEqualEpsilon( new import__372.Cartesian3(scalar, scalar, scalar), import__373.Math.EPSILON14 ); }); it("returns undefined for colinear points", function() { const p02 = new import__372.Cartesian3(-1, -1, 0); const p12 = new import__372.Cartesian3(0, 0, 0); const p22 = new import__372.Cartesian3(1, 1, 0); const point = new import__372.Cartesian3(0.5, 0.5, 0); const coord = (0, import__372.barycentricCoordinates)(point, p02, p12, p22); expect(coord).toBeUndefined(); }); it("evaluates with equal length sides", function() { const p02 = new import__372.Cartesian3( 9635312487071484, 13827945400273020, -16479219993905144 ); const p12 = new import__372.Cartesian3( 12832234180639317e-9, -10455085701705107e-9, 750010.7274386138 ); const p22 = new import__372.Cartesian3( -968901110628853e-8, -13420063892507521e-9, 750010.7274386119 ); expect((0, import__372.barycentricCoordinates)(p02, p02, p12, p22)).toEqual(import__372.Cartesian3.UNIT_X); expect((0, import__372.barycentricCoordinates)(p12, p02, p12, p22)).toEqual(import__372.Cartesian3.UNIT_Y); expect((0, import__372.barycentricCoordinates)(p22, p02, p12, p22)).toEqual(import__372.Cartesian3.UNIT_Z); }); it("throws without point", function() { expect(function() { (0, import__372.barycentricCoordinates)(); }).toThrowDeveloperError(); }); it("throws without p0", function() { expect(function() { (0, import__372.barycentricCoordinates)(new import__372.Cartesian3()); }).toThrowDeveloperError(); }); it("throws without p1", function() { expect(function() { (0, import__372.barycentricCoordinates)(new import__372.Cartesian3(), new import__372.Cartesian3()); }).toThrowDeveloperError(); }); it("throws without p2", function() { expect(function() { (0, import__372.barycentricCoordinates)( new import__372.Cartesian3(), new import__372.Cartesian3(), new import__372.Cartesian3() ); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/binarySearchSpec.js var import__374 = __toESM(require_Cesium(), 1); describe("Core/binarySearch", function() { it("can perform a binary search for 0", function() { const array = [0, 1, 2, 3, 4, 5, 6, 7]; const toFind = 0; const index = (0, import__374.binarySearch)(array, toFind, function(a, b) { return a - b; }); expect(index).toEqual(0); }); it("can perform a binary search for item in the list", function() { const array = [0, 1, 2, 3, 4, 5, 6, 7]; const toFind = 7; const index = (0, import__374.binarySearch)(array, toFind, function(a, b) { return a - b; }); expect(index).toEqual(7); }); it("can perform a binary search for item in between two items in the list", function() { const array = [0, 1, 2, 3, 4, 5, 6, 7]; const toFind = 3.5; const index = (0, import__374.binarySearch)(array, toFind, function(a, b) { return a - b; }); expect(~index).toEqual(4); }); it("can perform a binary search for item before all items in the list", function() { const array = [0, 1, 2, 3, 4, 5, 6, 7]; const toFind = -2; const index = (0, import__374.binarySearch)(array, toFind, function(a, b) { return a - b; }); expect(~index).toEqual(0); }); it("can perform a binary search for item after all items in the list", function() { const array = [0, 1, 2, 3, 4, 5, 6, 7]; const toFind = 12; const index = (0, import__374.binarySearch)(array, toFind, function(a, b) { return a - b; }); expect(~index).toEqual(8); }); function dummy() { return true; } it("throws an exception if array is missing", function() { expect(function() { (0, import__374.binarySearch)(void 0, 1, dummy); }).toThrowDeveloperError(); }); it("throws an exception if itemToFind is missing", function() { expect(function() { (0, import__374.binarySearch)([0, 1, 2], void 0, dummy); }).toThrowDeveloperError(); }); it("throws an exception if comparator is missing", function() { expect(function() { (0, import__374.binarySearch)([0, 1, 2], 1, void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/buildModuleUrlSpec.js var import_urijs2 = __toESM(require_URI(), 1); var import__375 = __toESM(require_Cesium(), 1); describe("Core/buildModuleUrl", function() { it("produces an absolute URL for a module", function() { const url = (0, import__375.buildModuleUrl)("Workers/transferTypedArrayTest.js"); expect(url).toMatch(/Workers\/transferTypedArrayTest.js$/); const uri = new import_urijs2.default(url); expect(uri.scheme().length).toBeGreaterThan(0); expect(uri.fragment().length).toEqual(0); return import__375.Resource.fetchText(url); }); it("matches the expected forms of URLs to Cesium.js", function() { const r = import__375.buildModuleUrl._cesiumScriptRegex; expect(r.exec("Cesium.js")[1]).toEqual(""); expect(r.exec("Cesium.js?v=1.7")[1]).toEqual(""); expect(r.exec("assets/foo/Cesium.js")[1]).toEqual("assets/foo/"); expect(r.exec("assets/foo/Cesium.js?v=1.7")[1]).toEqual("assets/foo/"); expect( r.exec("http://example.invalid/Cesium/assets/foo/Cesium.js")[1] ).toEqual("http://example.invalid/Cesium/assets/foo/"); expect( r.exec("http://example.invalid/Cesium/assets/foo/Cesium.js?v=1.7")[1] ).toEqual("http://example.invalid/Cesium/assets/foo/"); expect(r.exec("cesium.js")).toBeNull(); expect(r.exec("Cesium.js%20")).toBeNull(); expect(r.exec("Cesium.min.js")).toBeNull(); expect(r.exec("CesiumSomething.js")).toBeNull(); expect(r.exec("CesiumSomething.js?v=1.7")).toBeNull(); expect(r.exec("assets/foo/bar.cesium.js")).toBeNull(); expect(r.exec("assets/foo/bar.cesium.js?v=1.7")).toBeNull(); expect(r.exec("assets/foo/CesiumSomething.js")).toBeNull(); expect(r.exec("assets/foo/CesiumSomething.js?v=1.7")).toBeNull(); }); it("CESIUM_BASE_URL works with trailing slash", function() { const oldCESIUM_BASE_URL = window.CESIUM_BASE_URL; window.CESIUM_BASE_URL = "http://test.com/source/"; import__375.buildModuleUrl._clearBaseResource(); const url = import__375.buildModuleUrl._buildModuleUrlFromBaseUrl("Core/Cartesian3.js"); expect(url).toEqual("http://test.com/source/Core/Cartesian3.js"); window.CESIUM_BASE_URL = oldCESIUM_BASE_URL; import__375.buildModuleUrl._clearBaseResource(); }); it("CESIUM_BASE_URL works without trailing slash", function() { const oldCESIUM_BASE_URL = window.CESIUM_BASE_URL; window.CESIUM_BASE_URL = "http://test.com/source"; import__375.buildModuleUrl._clearBaseResource(); const url = import__375.buildModuleUrl._buildModuleUrlFromBaseUrl("Core/Cartesian3.js"); expect(url).toEqual("http://test.com/source/Core/Cartesian3.js"); window.CESIUM_BASE_URL = oldCESIUM_BASE_URL; import__375.buildModuleUrl._clearBaseResource(); }); }); // packages/engine/Specs/Core/cloneSpec.js var import__376 = __toESM(require_Cesium(), 1); describe("Core/clone", function() { it("can make shallow clones", function() { const obj = { a: 1, b: "s", c: { d: 0 } }; const clonedObj = (0, import__376.clone)(obj); expect(clonedObj).not.toBe(obj); expect(clonedObj.a).toEqual(obj.a); expect(clonedObj.b).toEqual(obj.b); expect(clonedObj.c).toBe(obj.c); expect(clonedObj.c.d).toEqual(obj.c.d); }); it("can make deep clones", function() { const obj = { a: 1, b: "s", c: { d: 0, e: { f: { g: 1 } } } }; const clonedObj = (0, import__376.clone)(obj, true); expect(clonedObj).not.toBe(obj); expect(clonedObj.a).toEqual(obj.a); expect(clonedObj.b).toEqual(obj.b); expect(clonedObj.c).not.toBe(obj.c); expect(clonedObj.c.d).toEqual(obj.c.d); expect(clonedObj.c.e).not.toBe(obj.c.e); expect(clonedObj.c.e.f).not.toBe(obj.c.e.f); expect(clonedObj.c.e.f.g).toEqual(obj.c.e.f.g); }); }); // packages/engine/Specs/Core/combineSpec.js var import__377 = __toESM(require_Cesium(), 1); describe("Core/combine", function() { it("can combine shallow references", function() { const obj1 = { x: 1, y: 2, other: { value1: 0 } }; const obj2 = { x: -1, z: 3, other: { value2: 1 } }; const composite = (0, import__377.combine)(obj1, obj2); expect(composite).toEqual({ x: 1, y: 2, z: 3, other: { value1: 0 } }); }); it("can combine deep references", function() { const object1 = { one: 1, deep: { value1: 10 } }; const object2 = { two: 2, deep: { value1: 5, value2: 11, sub: { val: "a" } } }; const composite = (0, import__377.combine)(object1, object2, true); expect(composite).toEqual({ one: 1, two: 2, deep: { value1: 10, value2: 11, sub: { val: "a" } } }); }); it("can accept undefined as either object", function() { const object = { one: 1, deep: { value1: 10 } }; expect((0, import__377.combine)(void 0, object)).toEqual(object); expect((0, import__377.combine)(void 0, object, true)).toEqual(object); expect((0, import__377.combine)(object, void 0)).toEqual(object); expect((0, import__377.combine)(object, void 0, true)).toEqual(object); expect((0, import__377.combine)(void 0, void 0)).toEqual({}); expect((0, import__377.combine)(void 0, void 0, true)).toEqual({}); }); }); // packages/engine/Specs/Core/createGuidSpec.js var import__378 = __toESM(require_Cesium(), 1); describe("Core/createGuid", function() { it("creates GUIDs", function() { const isGuidRegex = /^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$/; const guid1 = (0, import__378.createGuid)(); const guid2 = (0, import__378.createGuid)(); const guid3 = (0, import__378.createGuid)(); expect(guid1).not.toEqual(guid2); expect(guid1).not.toEqual(guid3); expect(guid2).not.toEqual(guid3); expect(isGuidRegex.test(guid1)).toEqual(true); expect(guid1.length).toEqual(36); expect(isGuidRegex.test(guid2)).toEqual(true); expect(guid2.length).toEqual(36); expect(isGuidRegex.test(guid3)).toEqual(true); expect(guid3.length).toEqual(36); }); }); // packages/engine/Specs/Core/createWorldBathymetryAsyncSpec.js var import__379 = __toESM(require_Cesium(), 1); describe("Core/createWorldBathymetryAsync", function() { it("resolves to CesiumTerrainProvider instance with default parameters", async function() { const provider = await (0, import__379.createWorldBathymetryAsync)(); expect(provider).toBeInstanceOf(import__379.CesiumTerrainProvider); expect(provider.requestVertexNormals).toBe(false); }); }); // packages/engine/Specs/Core/createWorldTerrainAsyncSpec.js var import__380 = __toESM(require_Cesium(), 1); describe("Core/createWorldTerrainAsync", function() { it("resolves to CesiumTerrainProvider instance with default parameters", async function() { const provider = await (0, import__380.createWorldTerrainAsync)(); expect(provider).toBeInstanceOf(import__380.CesiumTerrainProvider); expect(provider.requestVertexNormals).toBe(false); expect(provider.requestWaterMask).toBe(false); }); }); // packages/engine/Specs/Core/defaultValueSpec.js var import__381 = __toESM(require_Cesium(), 1); describe("Core/defaultValue", function() { it("Works with first parameter undefined", function() { expect((0, import__381.defaultValue)(void 0, 5)).toEqual(5); }); it("Works with first parameter null", function() { expect((0, import__381.defaultValue)(null, 5)).toEqual(5); }); it("Works with first parameter not undefined and not null", function() { expect((0, import__381.defaultValue)(1, 5)).toEqual(1); }); }); // packages/engine/Specs/Core/definedSpec.js var import__382 = __toESM(require_Cesium(), 1); describe("Core/defined", function() { it("works for defined value", function() { expect((0, import__382.defined)(0)).toEqual(true); }); it("works for null value", function() { expect((0, import__382.defined)(null)).toEqual(false); }); it("works for undefined value", function() { expect((0, import__382.defined)(void 0)).toEqual(false); }); }); // packages/engine/Specs/Core/deprecationWarningSpec.js var import__383 = __toESM(require_Cesium(), 1); describe("Core/deprecationWarning", function() { it("logs a warning", function() { spyOn(console, "warn"); (0, import__383.deprecationWarning)("deprecation-identifier", "message"); (0, import__383.deprecationWarning)("deprecation-identifier", "message"); (0, import__383.deprecationWarning)("another deprecation-identifier", "another message"); expect(console.warn.calls.count()).toEqual(2); expect(console.warn.calls.argsFor(0)[0]).toBe("message"); expect(console.warn.calls.argsFor(1)[0]).toBe("another message"); }); it("throws without identifier", function() { expect(function() { (0, import__383.deprecationWarning)(); }).toThrowDeveloperError(); }); it("throws without message", function() { expect(function() { (0, import__383.deprecationWarning)("identifier"); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/getAbsoluteUriSpec.js var import__384 = __toESM(require_Cesium(), 1); describe("Core/getAbsoluteUri", function() { it("works as expected", function() { let result = (0, import__384.getAbsoluteUri)( "http://www.mysite.com/awesome?makeitawesome=true" ); expect(result).toEqual("http://www.mysite.com/awesome?makeitawesome=true"); result = (0, import__384.getAbsoluteUri)("awesome.png", "http://test.com"); expect(result).toEqual("http://test.com/awesome.png"); result = (0, import__384.getAbsoluteUri)("awesome.png"); expect(result).toEqual(`${(0, import__384.getBaseUri)(document.location.href)}awesome.png`); }); it("document.baseURI is respected", function() { const fakeDocument = { baseURI: "http://test.com/index.html", location: document.location }; const result = import__384.getAbsoluteUri._implementation( "awesome.png", void 0, fakeDocument ); expect(result).toEqual("http://test.com/awesome.png"); }); it("throws with undefined parameter", function() { expect(function() { (0, import__384.getAbsoluteUri)(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/getBaseUriSpec.js var import__385 = __toESM(require_Cesium(), 1); describe("Core/getBaseUri", function() { it("works as expected", function() { let result = (0, import__385.getBaseUri)("http://www.mysite.com/awesome?makeitawesome=true"); expect(result).toEqual("http://www.mysite.com/"); result = (0, import__385.getBaseUri)( "http://www.mysite.com/somefolder/awesome.png#makeitawesome" ); expect(result).toEqual("http://www.mysite.com/somefolder/"); }); it("works with includeQuery flag", function() { let result = (0, import__385.getBaseUri)( "http://www.mysite.com/awesome?makeitawesome=true", true ); expect(result).toEqual("http://www.mysite.com/?makeitawesome=true"); result = (0, import__385.getBaseUri)( "http://www.mysite.com/somefolder/awesome.png#makeitawesome", true ); expect(result).toEqual("http://www.mysite.com/somefolder/#makeitawesome"); }); it("throws with undefined parameter", function() { expect(function() { (0, import__385.getBaseUri)(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/getExtensionFromUriSpec.js var import__386 = __toESM(require_Cesium(), 1); describe("Core/getExtensionFromUri", function() { it("works as expected", function() { let result = (0, import__386.getExtensionFromUri)( "http://www.mysite.com/awesome?makeitawesome=true" ); expect(result).toEqual(""); result = (0, import__386.getExtensionFromUri)( "http://www.mysite.com/somefolder/awesome.png#makeitawesome" ); expect(result).toEqual("png"); result = (0, import__386.getExtensionFromUri)("awesome.png"); expect(result).toEqual("png"); }); it("throws with undefined parameter", function() { expect(function() { (0, import__386.getExtensionFromUri)(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/getFilenameFromUriSpec.js var import__387 = __toESM(require_Cesium(), 1); describe("Core/getFilenameFromUri", function() { it("works as expected", function() { let result = (0, import__387.getFilenameFromUri)( "http://www.mysite.com/awesome?makeitawesome=true" ); expect(result).toEqual("awesome"); result = (0, import__387.getFilenameFromUri)( "http://www.mysite.com/somefolder/awesome.png#makeitawesome" ); expect(result).toEqual("awesome.png"); }); it("throws with undefined parameter", function() { expect(function() { (0, import__387.getFilenameFromUri)(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/getImageFromTypedArraySpec.js var import__388 = __toESM(require_Cesium(), 1); describe("Core/getImageFromTypedArray", function() { const pixelArray3x2 = Array(6).fill([0, 255, 0, 255]); const typedArray = new Uint8Array(pixelArray3x2.flat()); it("returns a Canvas of the expected size", function() { const canvas = (0, import__388.getImageFromTypedArray)(typedArray, 3, 2); expect(canvas.width).toBe(3); expect(canvas.height).toBe(2); }); it("fills the Canvas with the expected colors", function() { const canvas = (0, import__388.getImageFromTypedArray)(typedArray, 3, 2); const imageData = canvas.getContext("2d").getImageData(0, 0, 3, 2); const inputData = new Uint8ClampedArray(typedArray.buffer); expect(imageData.data).toEqual(inputData); }); }); // packages/engine/Specs/Core/getJsonFromTypedArraySpec.js var import__389 = __toESM(require_Cesium(), 1); describe("Core/getJsonFromTypedArray", function() { it("converts a typed array to string", function() { if (typeof TextEncoder === "undefined") { return; } const json = { a: [0, 1, 2], b: "b", c: { d: true } }; const string = JSON.stringify(json); const encoder = new TextEncoder(); const typedArray = encoder.encode(string); const result = (0, import__389.getJsonFromTypedArray)(typedArray); expect(result).toEqual(json); }); it("converts a sub-region of a typed array to json", function() { if (typeof TextEncoder === "undefined") { return; } const json = { a: [0, 1, 2], b: "b", c: { d: true } }; const string = JSON.stringify(json); const encoder = new TextEncoder(); const typedArray = encoder.encode(string); const result = (0, import__389.getJsonFromTypedArray)(typedArray, 25, 10); expect(result).toEqual(json.c); }); }); // packages/engine/Specs/Core/getStringFromTypedArraySpec.js var import__390 = __toESM(require_Cesium(), 1); describe("Core/getStringFromTypedArray", function() { function verifyString() { let arr = new Uint8Array([67, 101, 115, 105, 117, 109]); let string = (0, import__390.getStringFromTypedArray)(arr); expect(string).toEqual("Cesium"); arr = new Uint8Array(); string = (0, import__390.getStringFromTypedArray)(arr); expect(string).toEqual(""); } it("converts a typed array to string", function() { verifyString(); }); it("converts a typed array to string when forced to use fromCharCode", function() { spyOn(import__390.getStringFromTypedArray, "decode").and.callFake( import__390.getStringFromTypedArray.decodeWithFromCharCode ); verifyString(); }); it("converts a sub-region of a typed array to a string", function() { const arr = new Uint8Array([67, 101, 115, 105, 117, 109]); const string = (0, import__390.getStringFromTypedArray)(arr, 1, 3); expect(string).toEqual("esi"); }); it("throws if sub-region exceeds array bounds", function() { const arr = new Uint8Array([67, 101, 115, 105, 117, 109]); expect(function() { (0, import__390.getStringFromTypedArray)(arr, 3, 4); }).toThrowDeveloperError(); }); it("throws if byteOffset is negative", function() { const arr = new Uint8Array([67, 101, 115, 105, 117, 109]); expect(function() { (0, import__390.getStringFromTypedArray)(arr, -1, 0); }).toThrowDeveloperError(); }); it("throws if byteLength is negative", function() { const arr = new Uint8Array([67, 101, 115, 105, 117, 109]); expect(function() { (0, import__390.getStringFromTypedArray)(arr, 0, -1); }).toThrowDeveloperError(); }); it("throws without array", function() { expect(function() { (0, import__390.getStringFromTypedArray)(); }).toThrowDeveloperError(); }); it("Unicode 2-byte characters work", function() { const arr = new Uint8Array([90, 195, 188, 114, 105, 99, 104]); expect((0, import__390.getStringFromTypedArray)(arr)).toEqual("Z\xFCrich"); }); it("Unicode 2-byte characters work with decodeWithFromCharCode forced", function() { spyOn(import__390.getStringFromTypedArray, "decode").and.callFake( import__390.getStringFromTypedArray.decodeWithFromCharCode ); const arr = new Uint8Array([90, 195, 188, 114, 105, 99, 104]); expect((0, import__390.getStringFromTypedArray)(arr)).toEqual("Z\xFCrich"); }); it("Unicode 3-byte characters work", function() { const arr = new Uint8Array([224, 162, 160]); expect((0, import__390.getStringFromTypedArray)(arr)).toEqual("\u08A0"); }); it("Unicode 3-byte characters work with decodeWithFromCharCode forced", function() { spyOn(import__390.getStringFromTypedArray, "decode").and.callFake( import__390.getStringFromTypedArray.decodeWithFromCharCode ); const arr = new Uint8Array([224, 162, 160]); expect((0, import__390.getStringFromTypedArray)(arr)).toEqual("\u08A0"); }); it("Unicode 4-byte characters work", function() { const arr = new Uint8Array([240, 144, 138, 129]); expect((0, import__390.getStringFromTypedArray)(arr)).toEqual("\u{10281}"); }); it("Unicode 4-byte characters work with decodeWithFromCharCode forced", function() { spyOn(import__390.getStringFromTypedArray, "decode").and.callFake( import__390.getStringFromTypedArray.decodeWithFromCharCode ); const arr = new Uint8Array([240, 144, 138, 129]); expect((0, import__390.getStringFromTypedArray)(arr)).toEqual("\u{10281}"); }); }); // packages/engine/Specs/Core/isBlobUriSpec.js var import__391 = __toESM(require_Cesium(), 1); describe("Core/isBlobUri", function() { it("Throws if url is undefined", function() { expect(function() { (0, import__391.isBlobUri)(void 0); }).toThrowDeveloperError(); }); it("Determines that a uri is not a blob uri", function() { expect((0, import__391.isBlobUri)("http://cesiumjs.org/")).toEqual(false); }); it("Determines that a uri is a blob uri", function() { const uint8Array = new Uint8Array(4); const blob = new Blob([uint8Array], { type: "application/octet-stream" }); const blobUrl = window.URL.createObjectURL(blob); expect((0, import__391.isBlobUri)(blobUrl)).toEqual(true); }); }); // packages/engine/Specs/Core/isCrossOriginUrlSpec.js var import_urijs3 = __toESM(require_URI(), 1); var import__392 = __toESM(require_Cesium(), 1); describe("Core/isCrossOriginUrl", function() { it("returns false for relative urls", function() { expect((0, import__392.isCrossOriginUrl)("/some/url.jpg")).toEqual(false); expect((0, import__392.isCrossOriginUrl)("some/url.jpg")).toEqual(false); }); it("returns false for absolute urls that are not cross-origin", function() { let absoluteUrl = (0, import__392.getAbsoluteUri)("/some/url.jpg"); expect((0, import__392.isCrossOriginUrl)(absoluteUrl)).toEqual(false); absoluteUrl = (0, import__392.getAbsoluteUri)("some/url.jpg"); expect((0, import__392.isCrossOriginUrl)(absoluteUrl)).toEqual(false); }); it("returns true for absolute urls that are cross-origin", function() { expect((0, import__392.isCrossOriginUrl)("http://example.invalid/some/url.jpg")).toEqual( true ); let pageUri = new import_urijs3.default(location.href); pageUri.scheme(location.protocol === "https:" ? "http" : "https"); let absoluteUrl = pageUri.toString(); expect((0, import__392.isCrossOriginUrl)(absoluteUrl)).toEqual(true); pageUri = new import_urijs3.default(location.href); pageUri.authority(`${location.hostname}:${+location.port + 1}`); absoluteUrl = pageUri.toString(); expect((0, import__392.isCrossOriginUrl)(absoluteUrl)).toEqual(true); }); }); // packages/engine/Specs/Core/isDataUriSpec.js var import__393 = __toESM(require_Cesium(), 1); describe("Core/isDataUri", function() { it("Throws if url is undefined", function() { expect(function() { (0, import__393.isDataUri)(void 0); }).toThrowDeveloperError(); }); it("Determines that a uri is not a data uri", function() { expect((0, import__393.isDataUri)("http://cesiumjs.org/")).toEqual(false); }); it("Determines that a uri is a data uri", function() { const uri = `data:text/plain;base64,${btoa("a data uri")}`; expect((0, import__393.isDataUri)(uri)).toEqual(true); }); }); // packages/engine/Specs/Core/isLeapYearSpec.js var import__394 = __toESM(require_Cesium(), 1); describe("Core/isLeapYear", function() { it("Check for valid leap years", function() { expect((0, import__394.isLeapYear)(2e3)).toEqual(true); expect((0, import__394.isLeapYear)(2004)).toEqual(true); expect((0, import__394.isLeapYear)(2003)).toEqual(false); expect((0, import__394.isLeapYear)(2300)).toEqual(false); expect((0, import__394.isLeapYear)(2400)).toEqual(true); expect((0, import__394.isLeapYear)(-1)).toEqual(false); expect((0, import__394.isLeapYear)(-2e3)).toEqual(true); }); it("Fail with null value", function() { expect(function() { (0, import__394.isLeapYear)(null); }).toThrowDeveloperError(); }); it("Fail with undefined value", function() { expect(function() { (0, import__394.isLeapYear)(void 0); }).toThrowDeveloperError(); }); it("Fail with non-numerical value", function() { expect(function() { (0, import__394.isLeapYear)("asd"); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/loadImageFromTypedArraySpec.js var import__395 = __toESM(require_Cesium(), 1); describe("Core/loadImageFromTypedArray", function() { let supportsImageBitmapOptions; beforeAll(function() { return import__395.Resource.supportsImageBitmapOptions().then(function(result) { supportsImageBitmapOptions = result; }); }); it("can load an image", function() { return import__395.Resource.fetchArrayBuffer("./Data/Images/Blue10x10.png").then( function(arrayBuffer) { const options = { uint8Array: new Uint8Array(arrayBuffer), format: "image/png" }; return (0, import__395.loadImageFromTypedArray)(options).then(function(image) { expect(image.width).toEqual(10); expect(image.height).toEqual(10); }); } ); }); it("flips image only when flipY is true", function() { if (!supportsImageBitmapOptions) { return; } const options = { uint8Array: new Uint8Array([67, 101, 115, 105, 117, 109]), // This is an invalid PNG. format: "image/png", flipY: true }; spyOn(window, "createImageBitmap").and.returnValue(Promise.resolve({})); const blob = new Blob([options.uint8Array], { type: options.format }); return import__395.Resource.supportsImageBitmapOptions().then(function(result) { if (!result) { return; } return (0, import__395.loadImageFromTypedArray)(options).then(function() { expect(window.createImageBitmap).toHaveBeenCalledWith(blob, { imageOrientation: "flipY", premultiplyAlpha: "none", colorSpaceConversion: "default" }); window.createImageBitmap.calls.reset(); options.flipY = false; return (0, import__395.loadImageFromTypedArray)(options); }).then(function() { expect(window.createImageBitmap).toHaveBeenCalledWith(blob, { imageOrientation: "none", premultiplyAlpha: "none", colorSpaceConversion: "default" }); }); }); }); it("stores colorSpaceConversion correctly", function() { if (!supportsImageBitmapOptions) { return; } const options = { uint8Array: new Uint8Array([67, 101, 115, 105, 117, 109]), // This is an invalid PNG. format: "image/png", flipY: false, skipColorSpaceConversion: true }; spyOn(window, "createImageBitmap").and.returnValue(Promise.resolve({})); const blob = new Blob([options.uint8Array], { type: options.format }); return import__395.Resource.supportsImageBitmapOptions().then(function(result) { if (!result) { return; } return (0, import__395.loadImageFromTypedArray)(options).then(function() { expect(window.createImageBitmap).toHaveBeenCalledWith(blob, { imageOrientation: "none", premultiplyAlpha: "none", colorSpaceConversion: "none" }); window.createImageBitmap.calls.reset(); options.skipColorSpaceConversion = false; return (0, import__395.loadImageFromTypedArray)(options); }).then(function() { expect(window.createImageBitmap).toHaveBeenCalledWith(blob, { imageOrientation: "none", premultiplyAlpha: "none", colorSpaceConversion: "default" }); }); }); }); it("can load an image when ImageBitmap is not supported", function() { if (!supportsImageBitmapOptions) { return; } spyOn(import__395.Resource, "supportsImageBitmapOptions").and.returnValue( Promise.resolve(false) ); spyOn(window, "createImageBitmap").and.callThrough(); return import__395.Resource.fetchArrayBuffer("./Data/Images/Blue10x10.png").then( function(arrayBuffer) { const options = { uint8Array: new Uint8Array(arrayBuffer), format: "image/png" }; return (0, import__395.loadImageFromTypedArray)(options).then(function(image) { expect(image.width).toEqual(10); expect(image.height).toEqual(10); expect(window.createImageBitmap).not.toHaveBeenCalled(); }); } ); }); it("can not load an invalid image", function() { const options = { uint8Array: new Uint8Array([67, 101, 115, 105, 117, 109]), // This is an invalid PNG. format: "image/png" }; return (0, import__395.loadImageFromTypedArray)(options).then(function(image) { fail("should not be called"); }).catch(function() { }); }); it("Throws without array", function() { expect(function() { (0, import__395.loadImageFromTypedArray)({}); }).toThrowDeveloperError(); }); it("Throws without format", function() { expect(function() { (0, import__395.loadImageFromTypedArray)({ uint8Array: new Uint8Array() }); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/loadKTX2Spec.js var import__396 = __toESM(require_Cesium(), 1); describe("Core/loadKTX2", function() { it("throws with no url", function() { expect(function() { (0, import__396.loadKTX2)(); }).toThrowDeveloperError(); }); it("throws with unknown supported formats", function() { expect(function() { import__396.KTX2Transcoder.transcode(new Uint8Array()); }).toThrowDeveloperError(); }); it("throws if loadKTX2 is called with invalid url", function() { const testUrl = "http://example.invalid/testuri"; const promise = (0, import__396.loadKTX2)(testUrl); return promise.then(function(value) { fail(); }).catch(function(error) { expect(error).toBeDefined(); }); }); function expectKTX2TranscodeResult(url, supportedFormats, width, height, isCompressed) { const resource = import__396.Resource.createIfNeeded(url); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { const promise = import__396.KTX2Transcoder.transcode(buffer, supportedFormats); return promise.then(function(result) { expect(result).toBeDefined(); expect(result.width).toEqual(width); expect(result.height).toEqual(height); expect(import__396.PixelFormat.isCompressedFormat(result.internalFormat)).toEqual( isCompressed ); expect(result.bufferView).toBeDefined(); }); }); } it("transcodes ETC1S ktx2 to etc", function() { return expectKTX2TranscodeResult( "./Data/Images/Green4x4_ETC1S.ktx2", { etc: true }, 4, 4, true ); }); it("transcodes UASTC ktx2 to etc", function() { return expectKTX2TranscodeResult( "./Data/Images/Logo32x32_UASTC_Zstd.ktx2", { etc: true }, 32, 32, true ); }); it("transcodes ETC1S ktx2 to etc1", function() { return expectKTX2TranscodeResult( "./Data/Images/Green4x4_ETC1S.ktx2", { etc1: true }, 4, 4, true ); }); it("transcodes UASTC ktx2 to etc1", function() { return expectKTX2TranscodeResult( "./Data/Images/Logo32x32_UASTC_Zstd.ktx2", { etc1: true }, 32, 32, true ); }); it("transcodes ETC1S ktx2 to astc", function() { return expectKTX2TranscodeResult( "./Data/Images/Green4x4_ETC1S.ktx2", { astc: true }, 4, 4, true ); }); it("transcodes UASTC ktx2 to astc", function() { return expectKTX2TranscodeResult( "./Data/Images/Logo32x32_UASTC_Zstd.ktx2", { astc: true }, 32, 32, true ); }); it("transcodes ETC1S ktx2 to pvrtc", function() { return expectKTX2TranscodeResult( "./Data/Images/Green4x4_ETC1S.ktx2", { pvrtc: true }, 4, 4, true ); }); it("transcodes UASTC ktx2 to pvrtc", function() { return expectKTX2TranscodeResult( "./Data/Images/Logo32x32_UASTC_Zstd.ktx2", { pvrtc: true }, 32, 32, true ); }); it("transcodes ETC1S ktx2 to s3tc", function() { return expectKTX2TranscodeResult( "./Data/Images/Green4x4_ETC1S.ktx2", { s3tc: true }, 4, 4, true ); }); it("transcodes UASTC ktx2 to s3tc", function() { return expectKTX2TranscodeResult( "./Data/Images/Logo32x32_UASTC_Zstd.ktx2", { s3tc: true }, 32, 32, true ); }); it("transcodes ETC1S ktx2 to bc7", function() { return expectKTX2TranscodeResult( "./Data/Images/Green4x4_ETC1S.ktx2", { bc7: true }, 4, 4, true ); }); it("transcodes UASTC ktx2 to bc7", function() { return expectKTX2TranscodeResult( "./Data/Images/Logo32x32_UASTC_Zstd.ktx2", { bc7: true }, 32, 32, true ); }); it("returns a promise that resolves to an uncompressed texture", function() { return expectKTX2TranscodeResult( "./Data/Images/Green4x4.ktx2", { s3tc: true }, 4, 4, false ); }); it("returns a promise that resolves to an uncompressed texture containing all mip levels of the original texture", function() { const resource = import__396.Resource.createIfNeeded( "./Data/Images/Green4x4Mipmap.ktx2" ); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { const promise = import__396.KTX2Transcoder.transcode(buffer, {}); return promise.then(function(resolvedValue) { expect(resolvedValue).toBeDefined(); expect(resolvedValue.length).toEqual(3); const dims = [4, 2, 1]; for (let i = 0; i < resolvedValue.length; ++i) { expect(resolvedValue[i].width).toEqual(dims[i]); expect(resolvedValue[i].height).toEqual(dims[i]); expect( import__396.PixelFormat.isCompressedFormat(resolvedValue[i].internalFormat) ).toEqual(false); expect(resolvedValue[i].bufferView).toBeDefined(); } }); }); }); it("returns a promise that resolves to a compressed texture containing all mip levels of the original texture", function() { const resource = import__396.Resource.createIfNeeded( "./Data/Images/Green4x4Mipmap_ETC1S.ktx2" ); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { const promise = import__396.KTX2Transcoder.transcode(buffer, { etc1: true }); return promise.then(function(resolvedValue) { expect(resolvedValue).toBeDefined(); expect(resolvedValue.length).toEqual(3); const dims = [4, 2, 1]; for (let i = 0; i < resolvedValue.length; ++i) { expect(resolvedValue[i].width).toEqual(dims[i]); expect(resolvedValue[i].height).toEqual(dims[i]); expect( import__396.PixelFormat.isCompressedFormat(resolvedValue[i].internalFormat) ).toEqual(true); expect(resolvedValue[i].bufferView).toBeDefined(); } }); }); }); it("cannot parse invalid KTX2 buffer", function() { const invalidKTX = new Uint8Array([0, 1, 2, 3, 4, 5]); let resolvedValue; let rejectedError; const promise = (0, import__396.loadKTX2)(invalidKTX.buffer); return promise.then(function(value) { fail(); }).catch(function(error) { rejectedError = error; expect(resolvedValue).toBeUndefined(); expect(rejectedError).toBeInstanceOf(import__396.RuntimeError); expect(rejectedError.message).toEqual("Invalid KTX2 file."); }); }); it("3D textures are unsupported", function() { const resource = import__396.Resource.createIfNeeded("./Data/Images/Green4x4.ktx2"); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { const invalidKTX = new Uint32Array(buffer); invalidKTX[7] = 2; let resolvedValue; let rejectedError; const promise = (0, import__396.loadKTX2)(invalidKTX.buffer); return promise.then(function(value) { fail(); }).catch(function(error) { rejectedError = error; expect(resolvedValue).toBeUndefined(); expect(rejectedError).toBeInstanceOf(import__396.RuntimeError); expect(rejectedError.message).toEqual( "KTX2 3D textures are unsupported." ); }); }); }); it("texture arrays are unsupported", function() { const resource = import__396.Resource.createIfNeeded("./Data/Images/Green4x4.ktx2"); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { const invalidKTX = new Uint32Array(buffer); invalidKTX[8] = 15; let resolvedValue; let rejectedError; const promise = (0, import__396.loadKTX2)(invalidKTX.buffer); return promise.then(function(value) { fail(); }).catch(function(error) { rejectedError = error; expect(resolvedValue).toBeUndefined(); expect(rejectedError).toBeInstanceOf(import__396.RuntimeError); expect(rejectedError.message).toEqual( "KTX2 texture arrays are not supported." ); }); }); }); }); // packages/engine/Specs/Core/mergeSortSpec.js var import__397 = __toESM(require_Cesium(), 1); describe("Core/mergeSort", function() { it("sorts", function() { const array = [0, 9, 1, 8, 2, 7, 3, 6, 4, 5]; (0, import__397.mergeSort)(array, function(a, b) { return a - b; }); const expected = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; expect(array).toEqual(expected); }); it("stable sorts", function() { const array = [{ value: 5 }, { value: 10 }, { value: 5 }, { value: 0 }]; const expected = [array[3], array[0], array[2], array[1]]; (0, import__397.mergeSort)(array, function(a, b) { return a.value - b.value; }); expect(array).toEqual(expected); }); it("sorts with user defined object", function() { const array = [ new import__397.BoundingSphere(new import__397.Cartesian3(-2, 0, 0), 1), new import__397.BoundingSphere(new import__397.Cartesian3(-1, 0, 0), 1), new import__397.BoundingSphere(new import__397.Cartesian3(-3, 0, 0), 1) ]; const position = import__397.Cartesian3.ZERO; const comparator = function(a, b, position2) { return import__397.BoundingSphere.distanceSquaredTo(b, position2) - import__397.BoundingSphere.distanceSquaredTo(a, position2); }; const expected = [array[2], array[0], array[1]]; (0, import__397.mergeSort)(array, comparator, position); expect(array).toEqual(expected); }); function dummy() { return true; } it("throws an exception if array is missing", function() { expect(function() { (0, import__397.mergeSort)(void 0, dummy); }).toThrowDeveloperError(); }); it("throws an exception if comparator is missing", function() { expect(function() { (0, import__397.mergeSort)([0, 1, 2], void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/objectToQuerySpec.js var import__398 = __toESM(require_Cesium(), 1); describe("Core/objectToQuery", function() { it("can encode data", function() { const obj = { key1: "some value", key2: "a/b" }; const str = (0, import__398.objectToQuery)(obj); expect(str).toEqual("key1=some%20value&key2=a%2Fb"); }); it("can encode arrays of data", function() { const obj = { key: ["a", "b"] }; const str = (0, import__398.objectToQuery)(obj); expect(str).toEqual("key=a&key=b"); }); it("runs example code from the documentation", function() { const str = (0, import__398.objectToQuery)({ key1: "some value", key2: "a/b", key3: ["x", "y"] }); expect(str).toEqual("key1=some%20value&key2=a%2Fb&key3=x&key3=y"); }); it("can round-trip", function() { const obj = { foo: ["bar", "bar2"], bit: "byte" }; const obj2 = (0, import__398.queryToObject)((0, import__398.objectToQuery)(obj)); expect(obj2).toEqual(obj); }); it("can encode blank", function() { expect((0, import__398.objectToQuery)({})).toEqual(""); }); it("requires obj", function() { expect(function() { (0, import__398.objectToQuery)(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/oneTimeWarningSpec.js var import__399 = __toESM(require_Cesium(), 1); describe("Core/oneTimeWarning", function() { it("logs a warning", function() { spyOn(console, "warn"); (0, import__399.oneTimeWarning)("oneTime-identifier", "message"); (0, import__399.oneTimeWarning)("oneTime-identifier"); (0, import__399.oneTimeWarning)("another oneTime-identifier"); expect(console.warn.calls.count()).toEqual(2); expect(console.warn.calls.argsFor(0)[0]).toBe("message"); expect(console.warn.calls.argsFor(1)[0]).toBe("another oneTime-identifier"); }); it("throws without identifier", function() { expect(function() { (0, import__399.oneTimeWarning)(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/parseResponseHeadersSpec.js var import__400 = __toESM(require_Cesium(), 1); describe("Core/parseResponseHeaders", function() { it("returns an empty object literal when given falsy input", function() { expect((0, import__400.parseResponseHeaders)()).toEqual({}); expect((0, import__400.parseResponseHeaders)(null)).toEqual({}); expect((0, import__400.parseResponseHeaders)("")).toEqual({}); }); it("correctly parses response headers", function() { const headerString = "Date: Sun, 24 Oct 2004 04:58:38 GMT\r\nServer: Apache/1.3.31 (Unix)\r\nKeep-Alive: timeout=15, max=99\r\nConnection: Keep-Alive\r\nTransfer-Encoding: chunked\r\nContent-Type: text/plain; charset=utf-8"; expect((0, import__400.parseResponseHeaders)(headerString)).toEqual({ Date: "Sun, 24 Oct 2004 04:58:38 GMT", Server: "Apache/1.3.31 (Unix)", "Keep-Alive": "timeout=15, max=99", Connection: "Keep-Alive", "Transfer-Encoding": "chunked", "Content-Type": "text/plain; charset=utf-8" }); }); }); // packages/engine/Specs/Core/pointInsideTriangleSpec.js var import__401 = __toESM(require_Cesium(), 1); describe("Core/pointInsideTriangle", function() { it("pointInsideTriangle has point inside", function() { expect( (0, import__401.pointInsideTriangle)( new import__401.Cartesian2(0.25, 0.25), import__401.Cartesian2.ZERO, new import__401.Cartesian2(1, 0), new import__401.Cartesian2(0, 1) ) ).toEqual(true); }); it("pointInsideTriangle has point outside", function() { expect( (0, import__401.pointInsideTriangle)( new import__401.Cartesian2(1, 1), import__401.Cartesian2.ZERO, new import__401.Cartesian2(1, 0), new import__401.Cartesian2(0, 1) ) ).toEqual(false); }); it("pointInsideTriangle has point outside (2)", function() { expect( (0, import__401.pointInsideTriangle)( new import__401.Cartesian2(0.5, -0.5), import__401.Cartesian2.ZERO, new import__401.Cartesian2(1, 0), new import__401.Cartesian2(0, 1) ) ).toEqual(false); }); it("pointInsideTriangle has point outside (3)", function() { expect( (0, import__401.pointInsideTriangle)( new import__401.Cartesian2(-0.5, 0.5), import__401.Cartesian2.ZERO, new import__401.Cartesian2(1, 0), new import__401.Cartesian2(0, 1) ) ).toEqual(false); }); it("pointInsideTriangle has point on corner", function() { expect( (0, import__401.pointInsideTriangle)( import__401.Cartesian2.ZERO, import__401.Cartesian2.ZERO, new import__401.Cartesian2(1, 0), new import__401.Cartesian2(0, 1) ) ).toEqual(false); }); it("pointInsideTriangle has point inside on edge", function() { expect( (0, import__401.pointInsideTriangle)( new import__401.Cartesian2(0.5, 0), import__401.Cartesian2.ZERO, new import__401.Cartesian2(1, 0), new import__401.Cartesian2(0, 1) ) ).toEqual(false); }); it("throws without point", function() { expect(function() { (0, import__401.pointInsideTriangle)(); }).toThrowDeveloperError(); }); it("throws without p0", function() { expect(function() { (0, import__401.pointInsideTriangle)(new import__401.Cartesian2()); }).toThrowDeveloperError(); }); it("throws without p1", function() { expect(function() { (0, import__401.pointInsideTriangle)(new import__401.Cartesian2(), new import__401.Cartesian2()); }).toThrowDeveloperError(); }); it("throws without p2", function() { expect(function() { (0, import__401.pointInsideTriangle)(new import__401.Cartesian2(), new import__401.Cartesian2(), new import__401.Cartesian2()); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/queryToObjectSpec.js var import__402 = __toESM(require_Cesium(), 1); describe("Core/queryToObject", function() { it("can decode data", function() { let str = "key1=some%20value&key2=a%2Fb"; let obj = (0, import__402.queryToObject)(str); expect(obj).toEqual({ key1: "some value", key2: "a/b" }); str = "spec=Core%2FobjectToQuery%20can%20encode%20data.&debug=Core%2FobjectToQuery%20can%20encode%20data."; obj = (0, import__402.queryToObject)(str); expect(obj).toEqual({ spec: "Core/objectToQuery can encode data.", debug: "Core/objectToQuery can encode data." }); str = "q=query+string"; obj = (0, import__402.queryToObject)(str); expect(obj).toEqual({ q: "query string" }); }); it("can decode arrays of data", function() { const str = "key=a&key=b"; const obj = (0, import__402.queryToObject)(str); expect(obj).toEqual({ key: ["a", "b"] }); }); it("can use ; instead of &", function() { const str = "key=a;key=b;key2=c"; const obj = (0, import__402.queryToObject)(str); expect(obj).toEqual({ key: ["a", "b"], key2: "c" }); }); it("can decode blank", function() { expect((0, import__402.queryToObject)("")).toEqual({}); }); it("requires queryString", function() { expect(function() { (0, import__402.queryToObject)(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/resizeImageToNextPowerOfTwoSpec.js var import__403 = __toESM(require_Cesium(), 1); describe("Core/resizeImageToNextPowerOfTwo", function() { const canvas = document.createElement("canvas"); it("resizes an image so its width is a power of two", function() { canvas.width = 3; canvas.height = 2; const resizedImage = (0, import__403.resizeImageToNextPowerOfTwo)(canvas); expect(resizedImage.width).toBe(4); expect(resizedImage.height).toBe(2); }); it("resizes an image so its height is a power of two", function() { canvas.width = 4; canvas.height = 3; const resizedImage = (0, import__403.resizeImageToNextPowerOfTwo)(canvas); expect(resizedImage.width).toBe(4); expect(resizedImage.height).toBe(4); }); it("keeps original image size if both dimensions are already powers of two", function() { canvas.width = 8; canvas.height = 8; const resizedImage = (0, import__403.resizeImageToNextPowerOfTwo)(canvas); expect(resizedImage.width).toBe(8); expect(resizedImage.height).toBe(8); }); }); // packages/engine/Specs/Core/sampleTerrainMostDetailedSpec.js var import__404 = __toESM(require_Cesium(), 1); describe("Core/sampleTerrainMostDetailed", function() { let worldTerrain; beforeAll(async function() { worldTerrain = await (0, import__404.createWorldTerrainAsync)(); }); it("queries heights", async function() { const positions = [ import__404.Cartographic.fromDegrees(86.925145, 27.988257), import__404.Cartographic.fromDegrees(87, 28) ]; const passedPositions = await (0, import__404.sampleTerrainMostDetailed)( worldTerrain, positions ); expect(passedPositions).toBe(positions); expect(positions[0].height).toBeGreaterThan(5e3); expect(positions[0].height).toBeLessThan(1e4); expect(positions[1].height).toBeGreaterThan(5e3); expect(positions[1].height).toBeLessThan(1e4); }); it("should throw querying heights from terrain without availability", async function() { const terrainProvider = await import__404.CesiumTerrainProvider.fromUrl( "Data/CesiumTerrainTileJson/StandardHeightmap.tile.json" ); const positions = [ import__404.Cartographic.fromDegrees(86.925145, 27.988257), import__404.Cartographic.fromDegrees(87, 28) ]; await expectAsync( (0, import__404.sampleTerrainMostDetailed)(terrainProvider, positions) ).toBeRejectedWithDeveloperError( "sampleTerrainMostDetailed requires a terrain provider that has tile availability." ); }); it("uses a suitable common tile height for a range of locations", async function() { const positions = [ import__404.Cartographic.fromDegrees(86.925145, 27.988257), import__404.Cartographic.fromDegrees(87, 28) ]; await (0, import__404.sampleTerrainMostDetailed)(worldTerrain, positions); expect(positions[0].height).toBeGreaterThan(5e3); expect(positions[0].height).toBeLessThan(1e4); expect(positions[1].height).toBeGreaterThan(5e3); expect(positions[1].height).toBeLessThan(1e4); }); it("throws without terrainProvider", async function() { const positions = [ import__404.Cartographic.fromDegrees(86.925145, 27.988257), import__404.Cartographic.fromDegrees(87, 28) ]; await expectAsync( (0, import__404.sampleTerrainMostDetailed)(void 0, positions) ).toBeRejectedWithDeveloperError("terrainProvider is required."); }); it("throws without positions", async function() { await expectAsync( (0, import__404.sampleTerrainMostDetailed)(worldTerrain, void 0) ).toBeRejectedWithDeveloperError("positions is required."); }); it("works for a dodgy point right near the edge of a tile", async function() { const positions = [ new import__404.Cartographic(0.33179290856829535, 0.7363107781851078) ]; await (0, import__404.sampleTerrainMostDetailed)(worldTerrain, positions); expect(positions[0].height).toBeDefined(); }); it("rejects on tile error when rejectOnTileFail is set", async function() { const terrainProvider = await (0, import__404.createWorldTerrainAsync)(); terrainProvider.requestTileGeometry = function(x, y, level) { return Promise.reject(); }; const positions = [import__404.Cartographic.fromDegrees(0, 0, 0)]; return expectAsync( (0, import__404.sampleTerrainMostDetailed)(terrainProvider, positions, true) ).toBeRejected(); }); }); // packages/engine/Specs/Core/sampleTerrainSpec.js var import__405 = __toESM(require_Cesium(), 1); describe("Core/sampleTerrain", function() { let worldTerrain; beforeAll(async function() { worldTerrain = await (0, import__405.createWorldTerrainAsync)(); }); afterEach(function() { import__405.Resource._Implementations.loadWithXhr = import__405.Resource._DefaultImplementations.loadWithXhr; }); it("queries heights", function() { const positions = [ import__405.Cartographic.fromDegrees(86.925145, 27.988257), import__405.Cartographic.fromDegrees(87, 28) ]; return (0, import__405.sampleTerrain)(worldTerrain, 11, positions).then(function(passedPositions) { expect(passedPositions).toBe(positions); expect(positions[0].height).toBeGreaterThan(5e3); expect(positions[0].height).toBeLessThan(1e4); expect(positions[1].height).toBeGreaterThan(5e3); expect(positions[1].height).toBeLessThan(1e4); }); }); it("queries heights from terrain without availability", async function() { import__405.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { if ((0, import__405.defined)(url.match(/\/\d+\/\d+\/\d+\.terrain/))) { import__405.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/11_3027_1342.terrain", responseType, method, data, headers, deferred ); return; } import__405.Resource._DefaultImplementations.loadWithXhr( url, responseType, method, data, headers, deferred, overrideMimeType ); }; const terrainProvider = await import__405.CesiumTerrainProvider.fromUrl( "Data/CesiumTerrainTileJson/StandardHeightmap.tile.json" ); const positions = [ import__405.Cartographic.fromDegrees(86.925145, 27.988257), import__405.Cartographic.fromDegrees(87, 28) ]; const passedPositions = await (0, import__405.sampleTerrain)(terrainProvider, 11, positions); expect(passedPositions).toBe(positions); expect(positions[0].height).toBeGreaterThan(5e3); expect(positions[0].height).toBeLessThan(1e4); expect(positions[1].height).toBeGreaterThan(5e3); expect(positions[1].height).toBeLessThan(1e4); }); it("sets height to undefined if terrain data is not available at the position and specified level", function() { const positions = [import__405.Cartographic.fromDegrees(0, 0, 0)]; return (0, import__405.sampleTerrain)(worldTerrain, 18, positions).then(function() { expect(positions[0].height).toBeUndefined(); }); }); it("rejects if terrain data is not available and rejectOnTileFail is true", function() { const positions = [import__405.Cartographic.fromDegrees(0, 0, 0)]; return expectAsync( (0, import__405.sampleTerrain)(worldTerrain, 18, positions, true) ).toBeRejected(); }); it("fills in what it can when given a mix of positions with and without valid tiles", function() { const positions = [ import__405.Cartographic.fromDegrees(86.925145, 27.988257), import__405.Cartographic.fromDegrees(0, 89, 0), import__405.Cartographic.fromDegrees(87, 28) ]; return (0, import__405.sampleTerrain)(worldTerrain, 12, positions).then(function() { expect(positions[0].height).toBeGreaterThan(5e3); expect(positions[0].height).toBeLessThan(1e4); expect(positions[1].height).toBeUndefined(); expect(positions[2].height).toBeGreaterThan(5e3); expect(positions[2].height).toBeLessThan(1e4); }); }); it("requires terrainProvider, level, and positions", async function() { const positions = [ import__405.Cartographic.fromDegrees(86.925145, 27.988257), import__405.Cartographic.fromDegrees(0, 0, 0), import__405.Cartographic.fromDegrees(87, 28) ]; await expectAsync( (0, import__405.sampleTerrain)(void 0, 11, positions) ).toBeRejectedWithDeveloperError(); await expectAsync( (0, import__405.sampleTerrain)(worldTerrain, void 0, positions) ).toBeRejectedWithDeveloperError(); await expectAsync( (0, import__405.sampleTerrain)(worldTerrain, 11, void 0) ).toBeRejectedWithDeveloperError(); }); it("works for a dodgy point right near the edge of a tile", function() { const positions = [ new import__405.Cartographic(0.33179290856829535, 0.7363107781851078) ]; return (0, import__405.sampleTerrain)(worldTerrain, 12, positions).then(function() { expect(positions[0].height).toBeDefined(); }); }); describe("with terrain providers", function() { beforeEach(function() { import__405.RequestScheduler.clearForSpecs(); }); afterEach(function() { import__405.Resource._Implementations.loadWithXhr = import__405.Resource._DefaultImplementations.loadWithXhr; }); function spyOnTerrainDataCreateMesh(terrainProvider) { const originalRequestTileGeometry = terrainProvider.requestTileGeometry; spyOn(terrainProvider, "requestTileGeometry").and.callFake(function(x, y, level, request) { return originalRequestTileGeometry.call(terrainProvider, x, y, level, request).then(function(tile) { spyOn(tile, "createMesh").and.callThrough(); return tile; }); }); } function expectTileAndMeshCounts(terrainProvider, numberOfTilesRequested, wasFirstTileMeshCreated) { expect(terrainProvider.requestTileGeometry.calls.count()).toEqual( numberOfTilesRequested ); return terrainProvider.requestTileGeometry.calls.first().returnValue.then(function(terrainData) { expect(terrainData.createMesh.calls.count()).toEqual( wasFirstTileMeshCreated ? 1 : 0 ); }); } function endsWith(value, suffix) { return value.indexOf(suffix, value.length - suffix.length) >= 0; } function patchXHRLoad(proxySpec) { import__405.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { const availablePaths = Object.keys(proxySpec); let proxiedUrl; for (let i = 0; i < availablePaths.length; i++) { const srcPath = availablePaths[i]; if (endsWith(url, srcPath)) { proxiedUrl = proxySpec[availablePaths[i]]; break; } } if (!(0, import__405.defined)(proxiedUrl)) { throw new Error( `Unexpected XHR load to url: ${url}; spec includes: ${availablePaths.join( ", " )}` ); } return import__405.Resource._DefaultImplementations.loadWithXhr( proxiedUrl, responseType, method, data, headers, deferred, overrideMimeType ); }; } it("should work for Cesium World Terrain", async function() { patchXHRLoad({ "/layer.json": "Data/CesiumTerrainTileJson/9_759_335/layer.json", "/9/759/335.terrain?v=1.2.0": "Data/CesiumTerrainTileJson/9_759_335/9_759_335.terrain" }); const terrainProvider = await import__405.CesiumTerrainProvider.fromUrl( "made/up/url" ); spyOnTerrainDataCreateMesh(terrainProvider); const positionA = import__405.Cartographic.fromDegrees( 86.93666235421982, 27.97989963555095 ); const positionB = import__405.Cartographic.fromDegrees( 86.9366623542198, 27.9798996355509 ); const positionC = import__405.Cartographic.fromDegrees( 86.936662354213, 27.979899635557 ); const level = 9; return (0, import__405.sampleTerrain)(terrainProvider, level, [ positionA, positionB, positionC ]).then(function() { expect(positionA.height).toBeCloseTo(7780, 0); expect(positionB.height).toBeCloseTo(7780, 0); expect(positionC.height).toBeCloseTo(7780, 0); return expectTileAndMeshCounts(terrainProvider, 1, false); }); }); it("should work for ArcGIS terrain", async function() { patchXHRLoad({ "/?f=pjson": "Data/ArcGIS/9_214_379/root.json", "/tilemap/10/384/640/128/128": "Data/ArcGIS/9_214_379/tilemap_10_384_640_128_128.json", "/tile/9/214/379": "Data/ArcGIS/9_214_379/tile_9_214_379.tile" }); const terrainProvider = await import__405.ArcGISTiledElevationTerrainProvider.fromUrl( "made/up/url" ); spyOnTerrainDataCreateMesh(terrainProvider); const positionA = import__405.Cartographic.fromDegrees( 86.93666235421982, 27.97989963555095 ); const positionB = import__405.Cartographic.fromDegrees( 86.9366623542198, 27.9798996355509 ); const positionC = import__405.Cartographic.fromDegrees( 86.936662354213, 27.979899635557 ); const level = 9; await (0, import__405.sampleTerrain)(terrainProvider, level, [ positionA, positionB, positionC ]); expect(positionA.height).toBeCloseTo(7681, 0); expect(positionB.height).toBeCloseTo(7681, 0); expect(positionC.height).toBeCloseTo(7681, 0); await expectTileAndMeshCounts(terrainProvider, 1, true); }); it("should handle the RequestScheduler throttling the requestTileGeometry requests with a retry", async function() { patchXHRLoad({ "/?f=pjson": "Data/ArcGIS/9_214_379/root.json", "/tilemap/10/384/640/128/128": "Data/ArcGIS/9_214_379/tilemap_10_384_640_128_128.json", // we need multiple tiles to be requested, the actual value is not so important for this test "/tile/9/214/379": "Data/ArcGIS/9_214_379/tile_9_214_379.tile", "/tile/9/214/378": "Data/ArcGIS/9_214_379/tile_9_214_379.tile", "/tile/9/214/376": "Data/ArcGIS/9_214_379/tile_9_214_379.tile" }); const terrainProvider = await import__405.ArcGISTiledElevationTerrainProvider.fromUrl( "made/up/url" ); let i = 0; const originalRequestTileGeometry = terrainProvider.requestTileGeometry; spyOn(terrainProvider, "requestTileGeometry").and.callFake(function(x, y, level2, request) { i++; if (i === 2 || i === 3) { return void 0; } return originalRequestTileGeometry.call( terrainProvider, x, y, level2, request ); }); const positionA = import__405.Cartographic.fromDegrees(85, 28); const positionB = import__405.Cartographic.fromDegrees(86, 28); const positionC = import__405.Cartographic.fromDegrees(87, 28); const level = 9; await (0, import__405.sampleTerrain)(terrainProvider, level, [ positionA, positionB, positionC ]); const calls = terrainProvider.requestTileGeometry.calls; expect(calls.count()).toEqual(5); expect(calls.argsFor(0)).toEqual([376, 214, 9]); expect(calls.argsFor(1)).toEqual([378, 214, 9]); expect(calls.argsFor(2)).toEqual([378, 214, 9]); expect(calls.argsFor(3)).toEqual([378, 214, 9]); expect(calls.argsFor(4)).toEqual([379, 214, 9]); }); }); }); // packages/engine/Specs/Core/srgbToLinearSpec.js var import__406 = __toESM(require_Cesium(), 1); describe("Core/srgbToLinear", function() { it("converts 0 to 0", function() { expect((0, import__406.srgbToLinear)(0)).toEqual(0); }); it("converts value less than 0.04045", function() { expect((0, import__406.srgbToLinear)(0.0386).toFixed(3)).toEqual("0.003"); }); it("converts value greater than 0.04045", function() { expect((0, import__406.srgbToLinear)(0.5).toFixed(3)).toEqual("0.214"); }); it("converts 1 to 1", function() { expect((0, import__406.srgbToLinear)(1)).toEqual(1); }); }); // packages/engine/Specs/Core/subdivideArraySpec.js var import__407 = __toESM(require_Cesium(), 1); describe("Core/subdivideArray", function() { it("Splits evenly divided arrays", function() { const values = [1, 2, 3, 4]; const splitValues = (0, import__407.subdivideArray)(values, 4); expect(splitValues.length).toEqual(4); expect(splitValues[0]).toEqual([1]); expect(splitValues[1]).toEqual([2]); expect(splitValues[2]).toEqual([3]); expect(splitValues[3]).toEqual([4]); }); it("Splits unevenly divided arrays", function() { const values = [1, 2, 3, 4, 5, 6]; const splitValues = (0, import__407.subdivideArray)(values, 4); expect(splitValues.length).toEqual(4); expect(splitValues[0]).toEqual([1, 2]); expect(splitValues[1]).toEqual([3, 4]); expect(splitValues[2]).toEqual([5]); expect(splitValues[3]).toEqual([6]); }); it("Works with empty arrays", function() { const splitValues = (0, import__407.subdivideArray)([], 4); expect(splitValues.length).toEqual(0); }); it("Throws with undefined array", function() { expect(function() { (0, import__407.subdivideArray)(void 0, 8); }).toThrowDeveloperError(); }); it("Throws with invalid number of arrays", function() { expect(function() { (0, import__407.subdivideArray)([], -1); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Core/writeTextToCanvasSpec.js var import__408 = __toESM(require_Cesium(), 1); describe("Core/writeTextToCanvas", function() { it("returns undefined when text is blank", function() { const canvas = (0, import__408.writeTextToCanvas)(""); expect(canvas).toBeUndefined(); }); it("throws when text is undefined", function() { expect(function() { (0, import__408.writeTextToCanvas)(); }).toThrowDeveloperError(); }); it("sizes the canvas to fit the text", function() { const canvas1 = (0, import__408.writeTextToCanvas)("m"); const canvas2 = (0, import__408.writeTextToCanvas)("mm"); expect(canvas1.width).not.toEqual(canvas2.width); expect(canvas1.height).toEqual(canvas2.height); }); it("allows the text to be either stroked or filled", function() { const row = 20; function getColorChangeCount(canvas) { let colorChangeCount = 0; const context = canvas.getContext("2d"); let pixel = context.getImageData(0, row, 1, 1).data; let lastRed = pixel[0]; let lastGreen = pixel[1]; let lastBlue = pixel[2]; for (let column = 0; column < canvas.width; ++column) { pixel = context.getImageData(column, row, 1, 1).data; let red = pixel[0]; let green = pixel[1]; let blue = pixel[2]; if (red > 0 && red !== 255) { red = 255; } if (green > 0 && green !== 255) { green = 255; } if (blue > 0 && blue !== 255) { blue = 255; } if (red !== lastRed || green !== lastGreen || blue !== lastBlue) { ++colorChangeCount; } lastRed = red; lastGreen = green; lastBlue = blue; } return colorChangeCount; } const canvas1 = (0, import__408.writeTextToCanvas)("I", { font: '90px "Open Sans"', fill: true, fillColor: import__408.Color.RED, stroke: false }); let count = getColorChangeCount(canvas1); expect(count === 1 || count === 2).toEqual(true); const canvas2 = (0, import__408.writeTextToCanvas)("I", { font: '90px "Open Sans"', fill: false, stroke: true, strokeColor: import__408.Color.BLUE }); count = getColorChangeCount(canvas2); expect(count === 3 || count === 4).toEqual(true); }); it("background color defaults to transparent", function() { const canvas = (0, import__408.writeTextToCanvas)("a", { font: '90px "Open Sans"' }); const context = canvas.getContext("2d"); const pixel = context.getImageData(0, 0, 1, 1).data; expect(pixel).toEqual([0, 0, 0, 0]); }); it("background can be set", function() { const canvas = (0, import__408.writeTextToCanvas)("a", { font: '90px "Open Sans"', backgroundColor: import__408.Color.RED }); const context = canvas.getContext("2d"); const pixel = context.getImageData(0, 0, 1, 1).data; expect(pixel).toEqual([255, 0, 0, 255]); }); it("border can be set", function() { const canvas1 = (0, import__408.writeTextToCanvas)("a", { font: '90px "Open Sans"', backgroundColor: import__408.Color.RED }); const canvas2 = (0, import__408.writeTextToCanvas)("a", { font: '90px "Open Sans"', backgroundColor: import__408.Color.RED, padding: 2 }); expect(canvas2.width).toEqual(canvas1.width + 4); expect(canvas2.height).toEqual(canvas1.height + 4); }); }); // packages/engine/Specs/Widget/CesiumWidgetSpec.js var import__409 = __toESM(require_Cesium(), 1); describe( "Widget/CesiumWidget", function() { let container; let widget; beforeEach(function() { container = document.createElement("div"); container.id = "container"; container.style.width = "1px"; container.style.height = "1px"; container.style.overflow = "hidden"; container.style.position = "relative"; document.body.appendChild(container); }); afterEach(function() { if (widget && !widget.isDestroyed()) { widget = widget.destroy(); } document.body.removeChild(container); }); function createCesiumWidget(container2, options) { options = (0, import__409.defaultValue)(options, {}); options.contextOptions = (0, import__409.defaultValue)(options.contextOptions, {}); options.contextOptions.webgl = (0, import__409.defaultValue)( options.contextOptions.webgl, {} ); if (!!window.webglStub) { options.contextOptions.getWebGLStub = getWebGLStub_default; } return new import__409.CesiumWidget(container2, options); } it("can create, render, and destroy", function() { widget = createCesiumWidget(container); expect(widget.isDestroyed()).toEqual(false); expect(widget.container).toBeInstanceOf(HTMLElement); expect(widget.canvas).toBeInstanceOf(HTMLElement); expect(widget.creditDisplay).toBeInstanceOf(import__409.CreditDisplay); expect(widget.creditContainer).toBeInstanceOf(HTMLElement); expect(widget.creditViewport).toBeInstanceOf(HTMLElement); expect(widget.scene).toBeInstanceOf(import__409.Scene); expect(widget.imageryLayers).toBeInstanceOf(import__409.ImageryLayerCollection); expect(widget.terrainProvider).toBeInstanceOf(import__409.EllipsoidTerrainProvider); expect(widget.camera).toBeInstanceOf(import__409.Camera); expect(widget.clock).toBeInstanceOf(import__409.Clock); expect(widget.screenSpaceEventHandler).toBeInstanceOf( import__409.ScreenSpaceEventHandler ); expect(widget.useBrowserRecommendedResolution).toBe(true); widget.render(); widget.destroy(); expect(widget.isDestroyed()).toEqual(true); }); it("can pass id string for container", function() { widget = createCesiumWidget("container"); }); it("sets expected options clock", function() { const options = { clock: new import__409.Clock() }; widget = createCesiumWidget(container, options); expect(widget.clock).toBe(options.clock); }); it("can set scene mode 2D", function() { widget = createCesiumWidget(container, { sceneMode: import__409.SceneMode.SCENE2D }); widget.scene.completeMorph(); expect(widget.scene.mode).toBe(import__409.SceneMode.SCENE2D); }); it("can set map projection", function() { const mapProjection = new import__409.WebMercatorProjection(); widget = createCesiumWidget(container, { mapProjection }); expect(widget.scene.mapProjection).toEqual(mapProjection); }); it("can set scene mode Columbus", function() { widget = createCesiumWidget(container, { sceneMode: import__409.SceneMode.COLUMBUS_VIEW }); widget.scene.completeMorph(); expect(widget.scene.mode).toBe(import__409.SceneMode.COLUMBUS_VIEW); }); it("can disable render loop", function() { widget = createCesiumWidget(container, { useDefaultRenderLoop: false }); expect(widget.useDefaultRenderLoop).toBe(false); }); it("can set target frame rate", function() { widget = createCesiumWidget(container, { targetFrameRate: 23 }); expect(widget.targetFrameRate).toBe(23); }); it("sets expected options baseLayer", function() { const provider = new import__409.TileCoordinatesImageryProvider(); const options = { baseLayer: new import__409.ImageryLayer(provider) }; widget = createCesiumWidget(container, options); const imageryLayers = widget.scene.imageryLayers; expect(imageryLayers.length).toEqual(1); expect(imageryLayers.get(0).imageryProvider).toBe(provider); }); it("does not create imagery if baseLayer option is false", function() { const options = { baseLayer: false }; widget = createCesiumWidget(container, options); const imageryLayers = widget.scene.imageryLayers; expect(imageryLayers.length).toEqual(0); }); it("sets expected options terrainProvider", function() { const options = { terrainProvider: new import__409.EllipsoidTerrainProvider() }; widget = createCesiumWidget(container, options); expect(widget.terrainProvider).toBe(options.terrainProvider); const anotherProvider = new import__409.EllipsoidTerrainProvider(); widget.terrainProvider = anotherProvider; expect(widget.terrainProvider).toBe(anotherProvider); }); it("does not create a globe if option is false", function() { widget = createCesiumWidget(container, { globe: false }); expect(widget.scene.globe).not.toBeDefined(); }); it("sky atmopshere is hidden by default if a globe if option is false", function() { widget = createCesiumWidget(container, { globe: false }); expect(widget.scene.skyAtmosphere.show).toBeFalse(); }); it("does not create a skyBox if option is false", function() { widget = createCesiumWidget(container, { skyBox: false }); expect(widget.scene.skyBox).not.toBeDefined(); }); it("does not create a skyAtmosphere if option is false", function() { widget = createCesiumWidget(container, { skyAtmosphere: false }); expect(widget.scene.skyAtmosphere).not.toBeDefined(); }); it("sets expected options skyBox", function() { const options = { skyBox: new import__409.SkyBox({ sources: { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Green.png", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Green.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Green.png" } }) }; widget = createCesiumWidget(container, options); expect(widget.scene.skyBox).toBe(options.skyBox); }); it("can set contextOptions", function() { const webglOptions = { alpha: true, depth: true, //TODO Change to false when https://bugzilla.mozilla.org/show_bug.cgi?id=745912 is fixed. stencil: true, antialias: false, premultipliedAlpha: true, // Workaround IE 11.0.8, which does not honor false. preserveDrawingBuffer: true, powerPreference: "low-power" }; const contextOptions = { allowTextureFilterAnisotropic: false, webgl: webglOptions }; widget = createCesiumWidget(container, { contextOptions }); const context = widget.scene.context; const contextAttributes = context._gl.getContextAttributes(); expect(context.options.allowTextureFilterAnisotropic).toEqual(false); expect(contextAttributes.alpha).toEqual(webglOptions.alpha); expect(contextAttributes.depth).toEqual(webglOptions.depth); expect(contextAttributes.stencil).toEqual(webglOptions.stencil); expect(contextAttributes.antialias).toEqual(webglOptions.antialias); expect(contextAttributes.premultipliedAlpha).toEqual( webglOptions.premultipliedAlpha ); expect(contextAttributes.powerPreference).toEqual( webglOptions.powerPreference ); expect(contextAttributes.preserveDrawingBuffer).toEqual( webglOptions.preserveDrawingBuffer ); }); it("can disable Order Independent Translucency", function() { widget = createCesiumWidget(container, { orderIndependentTranslucency: false }); expect(widget.scene.orderIndependentTranslucency).toBe(false); }); it("can enable requestRenderMode", function() { widget = createCesiumWidget(container, { requestRenderMode: true }); expect(widget.scene.requestRenderMode).toBe(true); }); it("can set maximumRenderTimeChange", function() { widget = createCesiumWidget(container, { maximumRenderTimeChange: Number.POSITIVE_INFINITY }); expect(widget.scene.maximumRenderTimeChange).toBe( Number.POSITIVE_INFINITY ); }); it("throws if no container provided", function() { expect(function() { return createCesiumWidget(void 0); }).toThrowDeveloperError(); }); it("throws if targetFrameRate less than 0", function() { widget = createCesiumWidget(container); expect(function() { widget.targetFrameRate = -1; }).toThrowDeveloperError(); }); it("can set resolutionScale", function() { widget = createCesiumWidget(container); widget.resolutionScale = 0.5; expect(widget.resolutionScale).toBe(0.5); }); it("can enable useBrowserRecommendedResolution", function() { widget = createCesiumWidget(container, { useBrowserRecommendedResolution: true }); expect(widget.useBrowserRecommendedResolution).toBe(true); }); it("useBrowserRecommendedResolution ignores devicePixelRatio", function() { const oldDevicePixelRatio = window.devicePixelRatio; window.devicePixelRatio = 2; widget = createCesiumWidget(container, { useDefaultRenderLoop: false }); widget.resolutionScale = 0.5; widget.useBrowserRecommendedResolution = true; widget.resize(); expect(widget.scene.pixelRatio).toEqual(0.5); widget.useBrowserRecommendedResolution = false; widget.resize(); expect(widget.scene.pixelRatio).toEqual(1); window.devicePixelRatio = oldDevicePixelRatio; }); it("throws if resolutionScale is less than 0", function() { widget = createCesiumWidget(container); expect(function() { widget.resolutionScale = -1; }).toThrowDeveloperError(); }); it("resizing triggers a render in requestRender mode", function() { widget = createCesiumWidget(container, { requestRenderMode: true, maximumRenderTimeChange: Number.POSITIVE_INFINITY }); const scene2 = widget._scene; spyOn(scene2, "requestRender"); widget.resize(); expect(scene2.requestRender).not.toHaveBeenCalled(); widget._forceResize = true; widget.resize(); expect(scene2.requestRender).toHaveBeenCalled(); }); it("throws if no container id does not exist", function() { expect(function() { return createCesiumWidget("doesnotexist"); }).toThrowDeveloperError(); }); it("stops the render loop when render throws", function() { widget = createCesiumWidget(container); expect(widget.useDefaultRenderLoop).toEqual(true); const error = "foo"; widget.scene.primitives.update = function() { throw error; }; return pollToPromise_default(function() { return !widget.useDefaultRenderLoop; }, "render loop to be disabled."); }); it("shows the error panel when render throws", function() { widget = createCesiumWidget(container); const error = "foo"; widget.scene.primitives.update = function() { throw error; }; return pollToPromise_default(function() { return !widget.useDefaultRenderLoop; }).then(function() { expect( widget._element.querySelector(".cesium-widget-errorPanel") ).not.toBeNull(); const messages = widget._element.querySelectorAll( ".cesium-widget-errorPanel-message" ); let found = false; for (let i = 0; i < messages.length; ++i) { if (messages[i].textContent.indexOf(error) !== -1) { found = true; } } expect(found).toBe(true); DomEventSimulator_default.fireClick( widget._element.querySelector(".cesium-button") ); expect( widget._element.querySelector(".cesium-widget-errorPanel") ).toBeNull(); }); }); it("does not show the error panel if disabled", function() { widget = createCesiumWidget(container, { showRenderLoopErrors: false }); const error = "foo"; widget.scene.primitives.update = function() { throw error; }; return pollToPromise_default(function() { return !widget.useDefaultRenderLoop; }).then(function() { expect( widget._element.querySelector(".cesium-widget-errorPanel") ).toBeNull(); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/AppearanceSpec.js var import__410 = __toESM(require_Cesium(), 1); describe("Scene/Appearance", function() { it("constructor", function() { const material = import__410.Material.fromType("Color"); const vs = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin vec4 color;\nout vec4 v_color;\nvoid main() {\n gl_Position = czm_modelViewProjectionRelativeToEye * czm_computePosition();\n v_color = color;\n}\n"; const fs = "in vec4 v_color;\nvoid main() {\n out_FragColor = v_color;\n}\n"; const renderState = { depthTest: { enabled: true } }; const appearance = new import__410.Appearance({ material, vertexShaderSource: vs, fragmentShaderSource: fs, renderState, translucent: false, closed: true }); expect(appearance.material).toBe(material); expect(appearance.vertexShaderSource).toBe(vs); expect(appearance.fragmentShaderSource).toBe(fs); expect(appearance.renderState).toBe(renderState); expect(appearance.translucent).toEqual(false); expect(appearance.closed).toEqual(true); }); it("getFragmentShaderSource", function() { const fs = "out vec4 v_color;\nvoid main() {\n out_FragColor = v_color;\n}\n"; const appearance = new import__410.Appearance({ fragmentShaderSource: fs }); expect(appearance.getFragmentShaderSource().indexOf(fs)).toBeGreaterThan( -1 ); }); it("getFragmentShaderSource with material", function() { const material = import__410.Material.fromType("Color"); const fs = "in vec4 v_color;\nvoid main() {\n out_FragColor = v_color;\n}\n"; const appearance = new import__410.Appearance({ material, fragmentShaderSource: fs }); const fragmentSource = appearance.getFragmentShaderSource(); expect(fragmentSource.indexOf(material.shaderSource)).toBeGreaterThan(-1); expect(fragmentSource.indexOf(fs)).toBeGreaterThan(-1); }); it("getDefaultRenderState", function() { const renderState = import__410.Appearance.getDefaultRenderState(true, true); expect(renderState.depthTest).toBeDefined(); expect(renderState.depthTest.enabled).toEqual(true); expect(renderState.depthMask).toEqual(false); expect(renderState.blending).toEqual(import__410.BlendingState.ALPHA_BLEND); expect(renderState.cull).toBeDefined(); expect(renderState.cull.enabled).toEqual(true); expect(renderState.cull.face).toEqual(import__410.WebGLConstants.BACK); }); it("isTranslucent", function() { const appearance = new import__410.Appearance({ translucent: false }); expect(appearance.isTranslucent()).toEqual(false); appearance.translucent = true; expect(appearance.isTranslucent()).toEqual(true); appearance.material = import__410.Material.fromType("Color"); appearance.material.translucent = false; expect(appearance.isTranslucent()).toEqual(false); appearance.material.translucent = true; expect(appearance.isTranslucent()).toEqual(true); }); it("getRenderState", function() { const appearance = new import__410.Appearance({ translucent: false, closed: true, renderState: import__410.Appearance.getDefaultRenderState(false, true) }); let rs = appearance.getRenderState(); expect(rs.depthMask).toEqual(true); expect(rs.blending).not.toBeDefined(); appearance.translucent = true; rs = appearance.getRenderState(); expect(rs.depthMask).toEqual(false); expect(rs.blending).toBe(import__410.BlendingState.ALPHA_BLEND); }); }); // packages/engine/Specs/Scene/ArcGisMapServerImageryProviderSpec.js var import_urijs4 = __toESM(require_URI(), 1); var import__411 = __toESM(require_Cesium(), 1); describe("Scene/ArcGisMapServerImageryProvider", function() { let supportsImageBitmapOptions; beforeAll(function() { return import__411.Resource.supportsImageBitmapOptions().then(function(result) { supportsImageBitmapOptions = result; }); }); beforeEach(function() { import__411.RequestScheduler.clearForSpecs(); }); afterEach(function() { import__411.Resource._Implementations.loadAndExecuteScript = import__411.Resource._DefaultImplementations.loadAndExecuteScript; import__411.Resource._Implementations.createImage = import__411.Resource._DefaultImplementations.createImage; import__411.Resource._Implementations.loadWithXhr = import__411.Resource._DefaultImplementations.loadWithXhr; }); function stubJSONCall(baseUrl, result, withProxy, token) { spyOn(import__411.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { deferred.resolve(JSON.stringify(result)); }); } it("conforms to ImageryProvider interface", function() { expect(import__411.ArcGisMapServerImageryProvider).toConformToInterface( import__411.ImageryProvider ); }); const webMercatorResult = { currentVersion: 10.01, copyrightText: "Test copyright text", tileInfo: { rows: 128, cols: 256, origin: { x: -20037508342787e-6, y: 20037508342787e-6 }, spatialReference: { wkid: 102100 }, lods: [ { level: 0, resolution: 156543.033928, scale: 591657527591555e-6 }, { level: 1, resolution: 78271.5169639999, scale: 295828763795777e-6 }, { level: 2, resolution: 39135.7584820001, scale: 147914381897889e-6 } ] } }; it("fromUrl throws if url is not provided", async function() { await expectAsync( import__411.ArcGisMapServerImageryProvider.fromUrl() ).toBeRejectedWithDeveloperError( "url is required, actual value was undefined" ); }); it("fromUrl resolves with created provider", async function() { const baseUrl = "//tiledArcGisMapServer.invalid/"; stubJSONCall(baseUrl, webMercatorResult); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl(baseUrl); expect(provider).toBeInstanceOf(import__411.ArcGisMapServerImageryProvider); expect(provider.url).toEqual(baseUrl); }); it("fromUrl resolves with created provider with Resource parameter", async function() { const baseUrl = "//tiledArcGisMapServer.invalid/"; stubJSONCall(baseUrl, webMercatorResult); const resource = new import__411.Resource({ url: baseUrl }); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl(resource); expect(provider).toBeInstanceOf(import__411.ArcGisMapServerImageryProvider); expect(provider.url).toEqual(baseUrl); }); it("fromUrl throws if request fails", async function() { const baseUrl = "//tiledArcGisMapServer.invalid/"; await expectAsync( import__411.ArcGisMapServerImageryProvider.fromUrl(baseUrl) ).toBeRejectedWithError( import__411.RuntimeError, "An error occurred while accessing //tiledArcGisMapServer.invalid/" ); }); it("fromUrl throws on unsupported WKID", async function() { const baseUrl = "//tiledArcGisMapServer.invalid/"; const unsupportedWKIDResult = { currentVersion: 10.01, copyrightText: "Test copyright text", tileInfo: { rows: 128, cols: 256, origin: { x: -180, y: 90 }, spatialReference: { wkid: 1234 }, lods: [ { level: 0, resolution: 0.3515625, scale: 147748799285417e-6 }, { level: 1, resolution: 0.17578125, scale: 738743996427087e-7 }, { level: 2, resolution: 0.087890625, scale: 369371998213544e-7 } ] } }; stubJSONCall(baseUrl, unsupportedWKIDResult); await expectAsync( import__411.ArcGisMapServerImageryProvider.fromUrl(baseUrl) ).toBeRejectedWithError( import__411.RuntimeError, "An error occurred while accessing //tiledArcGisMapServer.invalid/: Tile spatial reference WKID 1234 is not supported." ); }); it("fromUrl throws if request fails", async function() { const baseUrl = "//tiledArcGisMapServer.invalid/"; const unsupportedFullExtentWKIDResult = { currentVersion: 10.01, copyrightText: "Test copyright text", tileInfo: { rows: 128, cols: 256, origin: { x: -20037508342787e-6, y: 20037508342787e-6 }, spatialReference: { wkid: 102100 }, lods: [ { level: 0, resolution: 156543.033928, scale: 591657527591555e-6 }, { level: 1, resolution: 78271.5169639999, scale: 295828763795777e-6 }, { level: 2, resolution: 39135.7584820001, scale: 147914381897889e-6 } ] }, fullExtent: { xmin: 11148026611962173e-9, ymin: -6443518758206591e-9, xmax: 18830976498143446e-9, ymax: -265936.19697360107, spatialReference: { wkid: 1234 } } }; stubJSONCall(baseUrl, unsupportedFullExtentWKIDResult); await expectAsync( import__411.ArcGisMapServerImageryProvider.fromUrl(baseUrl) ).toBeRejectedWithError( import__411.RuntimeError, "An error occurred while accessing //tiledArcGisMapServer.invalid/: fullExtent.spatialReference WKID 1234 is not supported." ); }); it("fromUrl creates provider for tiled servers in web mercator projection", async function() { const baseUrl = "//tiledArcGisMapServer.invalid/"; stubJSONCall(baseUrl, webMercatorResult); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl(baseUrl); expect(provider.tileWidth).toEqual(128); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toEqual(2); expect(provider.tilingScheme).toBeInstanceOf(import__411.WebMercatorTilingScheme); expect(provider.credit).toBeDefined(); expect(provider.tileDiscardPolicy).toBeInstanceOf( import__411.DiscardMissingTileImagePolicy ); expect(provider.rectangle).toEqual(new import__411.WebMercatorTilingScheme().rectangle); expect(provider.usingPrecachedTiles).toEqual(true); expect(provider.hasAlphaChannel).toBeDefined(); }); it("fromBasemapType throws without style", async function() { await expectAsync( import__411.ArcGisMapServerImageryProvider.fromBasemapType() ).toBeRejectedWithDeveloperError( "style is required, actual value was undefined" ); }); it("fromBasemapType throws with unknown style", async function() { await expectAsync( import__411.ArcGisMapServerImageryProvider.fromBasemapType("unknown") ).toBeRejectedWithDeveloperError("Unsupported basemap type: unknown"); }); it("fromBasemapType creates an ImageryProvider with expected values", async function() { const expectedUrl = import__411.ArcGisMapService.defaultWorldImageryServer; stubJSONCall(expectedUrl, webMercatorResult); const provider = await import__411.ArcGisMapServerImageryProvider.fromBasemapType( import__411.ArcGisBaseMapType.SATELLITE, { token: "myToken" } ); expect(provider.url).toContain(expectedUrl); expect(provider.token).toEqual("myToken"); expect(provider.credit.html).toEqual("Test copyright text"); expect(provider.usingPrecachedTiles).toBeTrue(); }); it("fromBasemapType displays default Credit if default token is used", async function() { const expectedUrl = import__411.ArcGisMapService.defaultWorldImageryServer; stubJSONCall(expectedUrl, webMercatorResult); const provider = await import__411.ArcGisMapServerImageryProvider.fromBasemapType( import__411.ArcGisBaseMapType.SATELLITE ); expect(provider.url).toContain(expectedUrl); expect(provider.token).toBeDefined(); expect(provider.credit.html).toContain( "This application is using a default ArcGIS access token." ); expect(provider.getTileCredits(0, 0, 0)[0].html).toEqual( "Test copyright text" ); }); it("supports tiled servers in web mercator projection", async function() { const baseUrl = "//tiledArcGisMapServer.invalid/"; stubJSONCall(baseUrl, webMercatorResult); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl(baseUrl); expect(provider.url).toEqual(baseUrl); expect(provider.tileWidth).toEqual(128); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toEqual(2); expect(provider.tilingScheme).toBeInstanceOf(import__411.WebMercatorTilingScheme); expect(provider.credit).toBeDefined(); expect(provider.tileDiscardPolicy).toBeInstanceOf( import__411.DiscardMissingTileImagePolicy ); expect(provider.rectangle).toEqual(new import__411.WebMercatorTilingScheme().rectangle); expect(provider.usingPrecachedTiles).toEqual(true); expect(provider.hasAlphaChannel).toBeDefined(); import__411.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { const url = request.url; if (/^blob:/.test(url)) { import__411.Resource._DefaultImplementations.createImage( request, crossOrigin, deferred ); } else { expect(url).toEqual((0, import__411.getAbsoluteUri)(`${baseUrl}tile/0/0/0`)); import__411.Resource._DefaultImplementations.createImage( new import__411.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); } }; import__411.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toEqual((0, import__411.getAbsoluteUri)(`${baseUrl}tile/0/0/0`)); import__411.Resource._DefaultImplementations.loadWithXhr( "Data/Images/Red16x16.png", responseType, method, data, headers, deferred ); }; return provider.requestImage(0, 0, 0).then(function(image) { expect(image).toBeImageOrImageBitmap(); }); }); const geographicResult = { currentVersion: 10.01, copyrightText: "Test copyright text", tileInfo: { rows: 128, cols: 256, origin: { x: -180, y: 90 }, spatialReference: { wkid: 4326 }, lods: [ { level: 0, resolution: 0.3515625, scale: 147748799285417e-6 }, { level: 1, resolution: 0.17578125, scale: 738743996427087e-7 }, { level: 2, resolution: 0.087890625, scale: 369371998213544e-7 } ] } }; it("supports tiled servers in geographic projection", async function() { const baseUrl = "//tiledArcGisMapServer.invalid/"; stubJSONCall(baseUrl, geographicResult); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl(baseUrl); expect(provider.url).toEqual(baseUrl); expect(provider.tileWidth).toEqual(128); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toEqual(2); expect(provider.tilingScheme).toBeInstanceOf(import__411.GeographicTilingScheme); expect(provider.credit).toBeDefined(); expect(provider.tileDiscardPolicy).toBeInstanceOf( import__411.DiscardMissingTileImagePolicy ); expect(provider.rectangle).toEqual(new import__411.GeographicTilingScheme().rectangle); expect(provider.usingPrecachedTiles).toEqual(true); import__411.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { const url = request.url; if (/^blob:/.test(url) || supportsImageBitmapOptions) { import__411.Resource._DefaultImplementations.createImage( request, crossOrigin, deferred, true, false, true ); } else { expect(url).toEqual((0, import__411.getAbsoluteUri)(`${baseUrl}tile/0/0/0`)); import__411.Resource._DefaultImplementations.createImage( new import__411.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); } }; import__411.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toEqual((0, import__411.getAbsoluteUri)(`${baseUrl}tile/0/0/0`)); import__411.Resource._DefaultImplementations.loadWithXhr( "Data/Images/Red16x16.png", responseType, method, data, headers, deferred ); }; return provider.requestImage(0, 0, 0).then(function(image) { expect(image).toBeImageOrImageBitmap(); }); }); it("fromUrl creates provider for tiled servers in geographic projection", async function() { const baseUrl = "//tiledArcGisMapServer.invalid"; stubJSONCall(baseUrl, geographicResult); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl(baseUrl); expect(provider.tileWidth).toEqual(128); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toEqual(2); expect(provider.tilingScheme).toBeInstanceOf(import__411.GeographicTilingScheme); expect(provider.credit).toBeDefined(); expect(provider.tileDiscardPolicy).toBeInstanceOf( import__411.DiscardMissingTileImagePolicy ); expect(provider.rectangle).toEqual(new import__411.GeographicTilingScheme().rectangle); expect(provider.usingPrecachedTiles).toEqual(true); }); it("supports non-tiled servers", async function() { const baseUrl = "//tiledArcGisMapServer.invalid/"; stubJSONCall(baseUrl, { currentVersion: 10.01, copyrightText: "Test copyright text" }); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl(baseUrl); expect(provider.url).toEqual(baseUrl); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__411.GeographicTilingScheme); expect(provider.credit).toBeDefined(); expect(provider.tileDiscardPolicy).toBeUndefined(); expect(provider.rectangle).toEqual(new import__411.GeographicTilingScheme().rectangle); expect(provider.usingPrecachedTiles).toEqual(false); expect(provider.enablePickFeatures).toBe(true); import__411.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { const uri = new import_urijs4.default(request.url); const params = (0, import__411.queryToObject)(uri.query()); const uriWithoutQuery = new import_urijs4.default(uri); uriWithoutQuery.query(""); expect(uriWithoutQuery.toString()).toEqual( (0, import__411.getAbsoluteUri)(`${baseUrl}export`) ); expect(params.f).toEqual("image"); expect(params.bboxSR).toEqual("4326"); expect(params.imageSR).toEqual("4326"); expect(params.format).toEqual("png32"); expect(params.transparent).toEqual("true"); expect(params.size).toEqual("256,256"); import__411.Resource._DefaultImplementations.createImage( new import__411.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }; return provider.requestImage(0, 0, 0).then(function(image) { expect(image).toBeImageOrImageBitmap(); }); }); it("fromUrl creates provider for non-tiled servers", async function() { const baseUrl = "//tiledArcGisMapServer.invalid/"; stubJSONCall(baseUrl, { currentVersion: 10.01, copyrightText: "Test copyright text" }); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl(baseUrl); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__411.GeographicTilingScheme); expect(provider.credit).toBeDefined(); expect(provider.tileDiscardPolicy).toBeUndefined(); expect(provider.rectangle).toEqual(new import__411.GeographicTilingScheme().rectangle); expect(provider.usingPrecachedTiles).toEqual(false); expect(provider.enablePickFeatures).toBe(true); }); it("supports non-tiled servers with various constructor parameters", async function() { const baseUrl = "//tiledArcGisMapServer.invalid/"; const token = "5e(u|2!7Y"; stubJSONCall( baseUrl, { currentVersion: 10.01, copyrightText: "Test copyright text" }, void 0, token ); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl(baseUrl, { token, tileWidth: 128, tileHeight: 512, tilingScheme: new import__411.WebMercatorTilingScheme(), rectangle: import__411.Rectangle.fromDegrees(1, 2, 3, 4), layers: "foo,bar", enablePickFeatures: false }); expect(provider.url).toEqual(baseUrl); expect(provider.tileWidth).toEqual(128); expect(provider.tileHeight).toEqual(512); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__411.WebMercatorTilingScheme); expect(provider.credit).toBeDefined(); expect(provider.tileDiscardPolicy).toBeUndefined(); expect(provider.rectangle).toEqual( import__411.Rectangle.fromDegrees(1, 2, 3, 4) ); expect(provider.usingPrecachedTiles).toBe(false); expect(provider.enablePickFeatures).toBe(false); expect(provider.layers).toEqual("foo,bar"); import__411.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { const uri = new import_urijs4.default(request.url); const params = (0, import__411.queryToObject)(uri.query()); const uriWithoutQuery = new import_urijs4.default(uri); uriWithoutQuery.query(""); expect(uriWithoutQuery.toString()).toEqual( (0, import__411.getAbsoluteUri)(`${baseUrl}export`) ); expect(params.f).toEqual("image"); expect(params.bboxSR).toEqual("3857"); expect(params.imageSR).toEqual("3857"); expect(params.format).toEqual("png32"); expect(params.transparent).toEqual("true"); expect(params.size).toEqual("128,512"); expect(params.layers).toEqual("show:foo,bar"); expect(params.token).toEqual(token); import__411.Resource._DefaultImplementations.createImage( new import__411.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }; return provider.requestImage(0, 0, 0).then(function(image) { expect(image).toBeImageOrImageBitmap(); }); }); it("includes security token in requests if one is specified", async function() { const baseUrl = "//tiledArcGisMapServer.invalid/", token = "5e(u|2!7Y"; stubJSONCall(baseUrl, webMercatorResult, false, token); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl(baseUrl, { token }); const expectedTileUrl = (0, import__411.getAbsoluteUri)( `${baseUrl}tile/0/0/0?${(0, import__411.objectToQuery)({ token })}` ); expect(provider.url).toEqual(baseUrl); expect(provider.token).toEqual(token); expect(provider.tileWidth).toEqual(128); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toEqual(2); expect(provider.tilingScheme).toBeInstanceOf(import__411.WebMercatorTilingScheme); expect(provider.credit).toBeDefined(); expect(provider.tileDiscardPolicy).toBeInstanceOf( import__411.DiscardMissingTileImagePolicy ); expect(provider.rectangle).toEqual(new import__411.WebMercatorTilingScheme().rectangle); expect(provider.usingPrecachedTiles).toEqual(true); expect(provider.hasAlphaChannel).toBeDefined(); import__411.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { const url = request.url; if (/^blob:/.test(url) || supportsImageBitmapOptions) { import__411.Resource._DefaultImplementations.createImage( request, crossOrigin, deferred, true, false, true ); } else { expect(url).toEqual(expectedTileUrl); import__411.Resource._DefaultImplementations.createImage( new import__411.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); } }; import__411.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toEqual(expectedTileUrl); import__411.Resource._DefaultImplementations.loadWithXhr( "Data/Images/Red16x16.png", responseType, method, data, headers, deferred ); }; const image = await provider.requestImage(0, 0, 0); expect(image).toBeImageOrImageBitmap(); }); it("honors fullExtent of tiled server with web mercator projection", async function() { const baseUrl = "//tiledArcGisMapServer.invalid/"; const webMercatorFullExtentResult = { currentVersion: 10.01, copyrightText: "Test copyright text", tileInfo: { rows: 128, cols: 256, origin: { x: -20037508342787e-6, y: 20037508342787e-6 }, spatialReference: { wkid: 102100 }, lods: [ { level: 0, resolution: 156543.033928, scale: 591657527591555e-6 }, { level: 1, resolution: 78271.5169639999, scale: 295828763795777e-6 }, { level: 2, resolution: 39135.7584820001, scale: 147914381897889e-6 } ] }, fullExtent: { xmin: 11148026611962173e-9, ymin: -6443518758206591e-9, xmax: 18830976498143446e-9, ymax: -265936.19697360107, spatialReference: { wkid: 102100 } } }; stubJSONCall(baseUrl, webMercatorFullExtentResult); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl(baseUrl); expect(provider.url).toEqual(baseUrl); const projection = new import__411.WebMercatorProjection(); const sw = projection.unproject( new import__411.Cartesian2(11148026611962173e-9, -6443518758206591e-9) ); const ne = projection.unproject( new import__411.Cartesian2(18830976498143446e-9, -265936.19697360107) ); const rectangle = new import__411.Rectangle( sw.longitude, sw.latitude, ne.longitude, ne.latitude ); expect(provider.rectangle).toEqual(rectangle); }); it("constrains extent to the tiling scheme's rectangle", async function() { const baseUrl = "//tiledArcGisMapServer.invalid/"; const webMercatorOutsideBoundsResult = { currentVersion: 10.01, copyrightText: "Test copyright text", tileInfo: { rows: 128, cols: 256, origin: { x: -20037508342787e-6, y: 20037508342787e-6 }, spatialReference: { wkid: 102100 }, lods: [ { level: 0, resolution: 156543.033928, scale: 591657527591555e-6 }, { level: 1, resolution: 78271.5169639999, scale: 295828763795777e-6 }, { level: 2, resolution: 39135.7584820001, scale: 147914381897889e-6 } ] }, fullExtent: { xmin: -20037507067161843e-9, ymin: -14745615008589065e-9, xmax: 20037507067161843e-9, ymax: 30240971958386205e-9, spatialReference: { wkid: 102100 } } }; stubJSONCall(baseUrl, webMercatorOutsideBoundsResult); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl(baseUrl); expect(provider.url).toEqual(baseUrl); expect(provider.rectangle.west).toBeGreaterThanOrEqual(-Math.PI); expect(provider.rectangle.east).toBeLessThanOrEqual(Math.PI); expect(provider.rectangle.south).toBeGreaterThanOrEqual( -import__411.WebMercatorProjection.MaximumLatitude ); expect(provider.rectangle.north).toBeLessThanOrEqual( import__411.WebMercatorProjection.MaximumLatitude ); }); it("honors fullExtent of tiled server with geographic projection", async function() { const baseUrl = "//tiledArcGisMapServer.invalid/"; const geographicFullExtentResult = { currentVersion: 10.01, copyrightText: "Test copyright text", tileInfo: { rows: 128, cols: 256, origin: { x: -20037508342787e-6, y: 20037508342787e-6 }, spatialReference: { wkid: 102100 }, lods: [ { level: 0, resolution: 156543.033928, scale: 591657527591555e-6 }, { level: 1, resolution: 78271.5169639999, scale: 295828763795777e-6 }, { level: 2, resolution: 39135.7584820001, scale: 147914381897889e-6 } ] }, fullExtent: { xmin: -123.4, ymin: -23.2, xmax: 100.7, ymax: 45.2, spatialReference: { wkid: 4326 } } }; stubJSONCall(baseUrl, geographicFullExtentResult); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl(baseUrl); expect(provider.url).toEqual(baseUrl); expect(provider.rectangle).toEqual( import__411.Rectangle.fromDegrees(-123.4, -23.2, 100.7, 45.2) ); }); it("throws if the spatialReference of the fullExtent is unknown", async function() { const baseUrl = "//tiledArcGisMapServer.invalid/"; const unknownSpatialReferenceResult = { currentVersion: 10.01, copyrightText: "Test copyright text", tileInfo: { rows: 128, cols: 256, origin: { x: -180, y: 90 }, spatialReference: { wkid: 1234 }, lods: [ { level: 0, resolution: 0.3515625, scale: 147748799285417e-6 }, { level: 1, resolution: 0.17578125, scale: 738743996427087e-7 }, { level: 2, resolution: 0.087890625, scale: 369371998213544e-7 } ] }, fullExtent: { xmin: -123.4, ymin: -23.2, xmax: 100.7, ymax: 45.2, spatialReference: { wkid: 1234 } } }; stubJSONCall(baseUrl, unknownSpatialReferenceResult); await expectAsync( import__411.ArcGisMapServerImageryProvider.fromUrl(baseUrl) ).toBeRejectedWithError( import__411.RuntimeError, "An error occurred while accessing //tiledArcGisMapServer.invalid/: Tile spatial reference WKID 1234 is not supported." ); }); describe("pickFeatures", function() { it("works with WebMercator geometry", async function() { stubJSONCall("made/up/map/server", webMercatorResult); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl( "made/up/map/server", { usePreCachedTilesIfAvailable: false } ); import__411.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toContain("identify"); import__411.Resource._DefaultImplementations.loadWithXhr( "Data/ArcGIS/identify-WebMercator.json", responseType, method, data, headers, deferred, overrideMimeType ); }; const pickResult = await provider.pickFeatures(0, 0, 0, 0.5, 0.5); expect(pickResult.length).toBe(1); const firstResult = pickResult[0]; expect(firstResult).toBeInstanceOf(import__411.ImageryLayerFeatureInfo); expect(firstResult.description).toContain("Hummock Grasses"); expect(firstResult.position).toEqual( new import__411.WebMercatorProjection().unproject( new import__411.Cartesian3(1481682457042425e-8, -2710890117898505e-9) ) ); }); it("works with Geographic geometry", async function() { stubJSONCall("made/up/map/server", geographicResult); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl( "made/up/map/server", { usePreCachedTilesIfAvailable: false } ); import__411.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toContain("identify"); import__411.Resource._DefaultImplementations.loadWithXhr( "Data/ArcGIS/identify-Geographic.json", responseType, method, data, headers, deferred, overrideMimeType ); }; return provider.pickFeatures(0, 0, 0, 0.5, 0.5).then(function(pickResult) { expect(pickResult.length).toBe(1); const firstResult = pickResult[0]; expect(firstResult).toBeInstanceOf(import__411.ImageryLayerFeatureInfo); expect(firstResult.description).toContain("Hummock Grasses"); expect(firstResult.position).toEqual( import__411.Cartographic.fromDegrees(123.45, -34.2) ); }); }); it("returns undefined if enablePickFeatures is false", async function() { stubJSONCall("made/up/map/server", webMercatorResult); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl( "made/up/map/server", { usePreCachedTilesIfAvailable: false, enablePickFeatures: false } ); expect(provider.pickFeatures(0, 0, 0, 0.5, 0.5)).toBeUndefined(); }); it("returns undefined if enablePickFeatures is dynamically set to false", async function() { stubJSONCall("made/up/map/server", geographicResult); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl( "made/up/map/server", { usePreCachedTilesIfAvailable: false, enablePickFeatures: true } ); provider.enablePickFeatures = false; expect(provider.pickFeatures(0, 0, 0, 0.5, 0.5)).toBeUndefined(); }); it("does not return undefined if enablePickFeatures is dynamically set to true", async function() { stubJSONCall("made/up/map/server", webMercatorResult); const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl( "made/up/map/server", { usePreCachedTilesIfAvailable: false, enablePickFeatures: false } ); provider.enablePickFeatures = true; import__411.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toContain("identify"); import__411.Resource._DefaultImplementations.loadWithXhr( "Data/ArcGIS/identify-WebMercator.json", responseType, method, data, headers, deferred, overrideMimeType ); }; const value = await provider.pickFeatures(0, 0, 0, 0.5, 0.5); expect(value).toBeDefined(); }); it("picks from individual layers", async function() { stubJSONCall("made/up/map/server", webMercatorResult); import__411.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { const uri = new import_urijs4.default(url); const query = (0, import__411.queryToObject)(uri.query()); expect(query.layers).toContain("visible:someLayer,anotherLayerYay"); import__411.Resource._DefaultImplementations.loadWithXhr( "Data/ArcGIS/identify-WebMercator.json", responseType, method, data, headers, deferred, overrideMimeType ); }; const provider = await import__411.ArcGisMapServerImageryProvider.fromUrl( "made/up/map/server", { usePreCachedTilesIfAvailable: false, layers: "someLayer,anotherLayerYay" } ); const pickResult = await provider.pickFeatures(0, 0, 0, 0.5, 0.5); expect(pickResult.length).toBe(1); }); }); }); // packages/engine/Specs/Scene/AttributeTypeSpec.js var import__412 = __toESM(require_Cesium(), 1); describe("Scene/AttributeType", function() { it("getMathType works", function() { expect(import__412.AttributeType.getMathType(import__412.AttributeType.SCALAR)).toBe(Number); expect(import__412.AttributeType.getMathType(import__412.AttributeType.VEC2)).toBe(import__412.Cartesian2); expect(import__412.AttributeType.getMathType(import__412.AttributeType.VEC3)).toBe(import__412.Cartesian3); expect(import__412.AttributeType.getMathType(import__412.AttributeType.VEC4)).toBe(import__412.Cartesian4); expect(import__412.AttributeType.getMathType(import__412.AttributeType.MAT2)).toBe(import__412.Matrix2); expect(import__412.AttributeType.getMathType(import__412.AttributeType.MAT3)).toBe(import__412.Matrix3); expect(import__412.AttributeType.getMathType(import__412.AttributeType.MAT4)).toBe(import__412.Matrix4); }); it("getMathType throws with invalid type", function() { expect(function() { import__412.AttributeType.getMathType("Invalid"); }).toThrowDeveloperError(); }); it("getGlslType throws for invalid attribute type", function() { expect(function() { import__412.AttributeType.getGlslType(void 0); }).toThrowDeveloperError(); expect(function() { import__412.AttributeType.getGlslType(""); }).toThrowDeveloperError(); expect(function() { import__412.AttributeType.getGlslType("int"); }).toThrowDeveloperError(); }); it("getGlslType works", function() { expect(import__412.AttributeType.getGlslType(import__412.AttributeType.SCALAR)).toEqual("float"); expect(import__412.AttributeType.getGlslType(import__412.AttributeType.VEC2)).toEqual("vec2"); expect(import__412.AttributeType.getGlslType(import__412.AttributeType.VEC3)).toEqual("vec3"); expect(import__412.AttributeType.getGlslType(import__412.AttributeType.VEC4)).toEqual("vec4"); expect(import__412.AttributeType.getGlslType(import__412.AttributeType.MAT2)).toEqual("mat2"); expect(import__412.AttributeType.getGlslType(import__412.AttributeType.MAT3)).toEqual("mat3"); expect(import__412.AttributeType.getGlslType(import__412.AttributeType.MAT4)).toEqual("mat4"); }); it("getNumberOfComponents works", function() { expect(import__412.AttributeType.getNumberOfComponents(import__412.AttributeType.SCALAR)).toBe(1); expect(import__412.AttributeType.getNumberOfComponents(import__412.AttributeType.VEC2)).toBe(2); expect(import__412.AttributeType.getNumberOfComponents(import__412.AttributeType.VEC3)).toBe(3); expect(import__412.AttributeType.getNumberOfComponents(import__412.AttributeType.VEC4)).toBe(4); expect(import__412.AttributeType.getNumberOfComponents(import__412.AttributeType.MAT2)).toBe(4); expect(import__412.AttributeType.getNumberOfComponents(import__412.AttributeType.MAT3)).toBe(9); expect(import__412.AttributeType.getNumberOfComponents(import__412.AttributeType.MAT4)).toBe(16); }); it("getAttributeLocationCount works", function() { expect(import__412.AttributeType.getAttributeLocationCount(import__412.AttributeType.SCALAR)).toBe( 1 ); expect(import__412.AttributeType.getAttributeLocationCount(import__412.AttributeType.VEC2)).toBe(1); expect(import__412.AttributeType.getAttributeLocationCount(import__412.AttributeType.VEC3)).toBe(1); expect(import__412.AttributeType.getAttributeLocationCount(import__412.AttributeType.VEC4)).toBe(1); expect(import__412.AttributeType.getAttributeLocationCount(import__412.AttributeType.MAT2)).toBe(2); expect(import__412.AttributeType.getAttributeLocationCount(import__412.AttributeType.MAT3)).toBe(3); expect(import__412.AttributeType.getAttributeLocationCount(import__412.AttributeType.MAT4)).toBe(4); }); it("getNumberOfComponents throws with invalid type", function() { expect(function() { import__412.AttributeType.getNumberOfComponents("Invalid"); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/AxisSpec.js var import__413 = __toESM(require_Cesium(), 1); var import__414 = __toESM(require_Cesium(), 1); describe("Scene/Axis", function() { function convertUpAxis(upAxis, transformation, expected) { const transformed = import__413.Matrix4.multiplyByVector( transformation, upAxis, new import__413.Cartesian4() ); import__413.Cartesian4.normalize(transformed, transformed); expect(transformed).toEqualEpsilon(expected, import__414.Math.EPSILON1); } it("Convert y-up to z-up", function() { convertUpAxis(import__413.Cartesian4.UNIT_Y, import__413.Axis.Y_UP_TO_Z_UP, import__413.Cartesian4.UNIT_Z); }); it("Convert y-up to x-up", function() { convertUpAxis(import__413.Cartesian4.UNIT_Y, import__413.Axis.Y_UP_TO_X_UP, import__413.Cartesian4.UNIT_X); }); it("Convert z-up to x-up", function() { convertUpAxis(import__413.Cartesian4.UNIT_Z, import__413.Axis.Z_UP_TO_X_UP, import__413.Cartesian4.UNIT_X); }); it("Convert z-up to y-up", function() { convertUpAxis(import__413.Cartesian4.UNIT_Z, import__413.Axis.Z_UP_TO_Y_UP, import__413.Cartesian4.UNIT_Y); }); it("Convert x-up to y-up", function() { convertUpAxis(import__413.Cartesian4.UNIT_X, import__413.Axis.X_UP_TO_Y_UP, import__413.Cartesian4.UNIT_Y); }); it("Convert x-up to z-up", function() { convertUpAxis(import__413.Cartesian4.UNIT_X, import__413.Axis.X_UP_TO_Z_UP, import__413.Cartesian4.UNIT_Z); }); }); // packages/engine/Specs/Scene/B3dmParserSpec.js var import__415 = __toESM(require_Cesium(), 1); // Specs/Cesium3DTilesTester.js var import_engine19 = __toESM(require_Cesium(), 1); var mockTile = { contentBoundingVolume: new import_engine19.TileBoundingSphere(), _contentBoundingVolume: new import_engine19.TileBoundingSphere(), _header: { content: { boundingVolume: { sphere: [0, 0, 0, 1] } } } }; function Cesium3DTilesTester() { } function padStringToByteAlignment(string, byteAlignment) { const length2 = string.length; const paddedLength = Math.ceil(length2 / byteAlignment) * byteAlignment; const padding = paddedLength - length2; let whitespace = ""; for (let i = 0; i < padding; ++i) { whitespace += " "; } return string + whitespace; } var time = new import_engine19.JulianDate(2457522); Cesium3DTilesTester.expectRender = function(scene2, tileset, callback) { const renderOptions = { scene: scene2, time }; tileset.show = false; expect(renderOptions).toRender([0, 0, 0, 255]); tileset.show = true; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); if ((0, import_engine19.defined)(callback)) { callback(rgba); } }); }; Cesium3DTilesTester.expectRenderBlank = function(scene2, tileset) { const renderOptions = { scene: scene2, time }; tileset.show = false; expect(renderOptions).toRender([0, 0, 0, 255]); tileset.show = true; expect(renderOptions).toRender([0, 0, 0, 255]); }; Cesium3DTilesTester.expectRenderTileset = function(scene2, tileset) { Cesium3DTilesTester.expectRender(scene2, tileset); expect(scene2).toPickAndCall(function(result) { expect(result).toBeDefined(); result.color = import_engine19.Color.clone(import_engine19.Color.YELLOW, result.color); Cesium3DTilesTester.expectRender(scene2, tileset, function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toBeGreaterThan(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); result.show = false; Cesium3DTilesTester.expectRenderBlank(scene2, tileset); result.show = true; Cesium3DTilesTester.expectRender(scene2, tileset); }); }; Cesium3DTilesTester.waitForTilesLoaded = function(scene2, tileset) { return pollToPromise_default(function() { scene2.renderForSpecs(); return tileset.tilesLoaded; }).then(function() { scene2.renderForSpecs(); return tileset; }); }; Cesium3DTilesTester.loadTileset = async function(scene2, url, options) { options = (0, import_engine19.defaultValue)(options, {}); options.cullRequestsWhileMoving = (0, import_engine19.defaultValue)( options.cullRequestsWhileMoving, false ); const tileset = await import_engine19.Cesium3DTileset.fromUrl(url, options); scene2.primitives.add(tileset); await Cesium3DTilesTester.waitForTilesLoaded(scene2, tileset); return tileset; }; Cesium3DTilesTester.createContentForMockTile = async function(arrayBuffer, type) { const tileset = {}; const url = import_engine19.Resource.createIfNeeded(""); return import_engine19.Cesium3DTileContentFactory[type]( tileset, mockTile, url, arrayBuffer, 0 ); }; Cesium3DTilesTester.tileDestroys = function(scene2, url, options) { return Cesium3DTilesTester.loadTileset(scene2, url, options).then(function(tileset) { const content = tileset.root.content; expect(content.isDestroyed()).toEqual(false); scene2.primitives.remove(tileset); expect(content.isDestroyed()).toEqual(true); }); }; Cesium3DTilesTester.generateBatchedTileBuffer = function(options) { options = (0, import_engine19.defaultValue)(options, import_engine19.defaultValue.EMPTY_OBJECT); const magic = (0, import_engine19.defaultValue)(options.magic, [98, 51, 100, 109]); const version = (0, import_engine19.defaultValue)(options.version, 1); const featuresLength = (0, import_engine19.defaultValue)(options.featuresLength, 1); const featureTableJson = { BATCH_LENGTH: featuresLength }; const featureTableJsonString = JSON.stringify(featureTableJson); const featureTableJsonByteLength = featureTableJsonString.length; const headerByteLength = 28; const byteLength = headerByteLength + featureTableJsonByteLength; const buffer = new ArrayBuffer(byteLength); const view = new DataView(buffer); view.setUint8(0, magic[0]); view.setUint8(1, magic[1]); view.setUint8(2, magic[2]); view.setUint8(3, magic[3]); view.setUint32(4, version, true); view.setUint32(8, byteLength, true); view.setUint32(12, featureTableJsonByteLength, true); view.setUint32(16, 0, true); view.setUint32(20, 0, true); view.setUint32(24, 0, true); let i; let byteOffset = headerByteLength; for (i = 0; i < featureTableJsonByteLength; i++) { view.setUint8(byteOffset, featureTableJsonString.charCodeAt(i)); byteOffset++; } return buffer; }; Cesium3DTilesTester.generateInstancedTileBuffer = function(options) { options = (0, import_engine19.defaultValue)(options, import_engine19.defaultValue.EMPTY_OBJECT); const magic = (0, import_engine19.defaultValue)(options.magic, [105, 51, 100, 109]); const version = (0, import_engine19.defaultValue)(options.version, 1); const gltfFormat = (0, import_engine19.defaultValue)(options.gltfFormat, 1); const gltfUri = (0, import_engine19.defaultValue)(options.gltfUri, "model.gltf"); const gltfUriByteLength = gltfUri.length; const featureTableJson = options.featureTableJson; let featureTableJsonString = ""; if ((0, import_engine19.defined)(featureTableJson)) { if (Object.keys(featureTableJson).length > 0) { featureTableJsonString = JSON.stringify(featureTableJson); } } else { const featuresLength = (0, import_engine19.defaultValue)(options.featuresLength, 1); featureTableJsonString = JSON.stringify({ INSTANCES_LENGTH: featuresLength, POSITION: new Array(featuresLength * 3).fill(0) }); } featureTableJsonString = padStringToByteAlignment(featureTableJsonString, 8); const featureTableJsonByteLength = featureTableJsonString.length; const featureTableBinary = (0, import_engine19.defaultValue)( options.featureTableBinary, new Uint8Array(0) ); const featureTableBinaryByteLength = featureTableBinary.length; const batchTableJson = options.batchTableJson; let batchTableJsonString = ""; if ((0, import_engine19.defined)(batchTableJson) && Object.keys(batchTableJson).length > 0) { batchTableJsonString = JSON.stringify(batchTableJson); } batchTableJsonString = padStringToByteAlignment(batchTableJsonString, 8); const batchTableJsonByteLength = batchTableJsonString.length; const batchTableBinary = (0, import_engine19.defaultValue)( options.batchTableBinary, new Uint8Array(0) ); const batchTableBinaryByteLength = batchTableBinary.length; const headerByteLength = 32; const byteLength = headerByteLength + featureTableJsonByteLength + featureTableBinaryByteLength + batchTableJsonByteLength + batchTableBinaryByteLength + gltfUriByteLength; const buffer = new ArrayBuffer(byteLength); const view = new DataView(buffer); view.setUint8(0, magic[0]); view.setUint8(1, magic[1]); view.setUint8(2, magic[2]); view.setUint8(3, magic[3]); view.setUint32(4, version, true); view.setUint32(8, byteLength, true); view.setUint32(12, featureTableJsonByteLength, true); view.setUint32(16, featureTableBinaryByteLength, true); view.setUint32(20, batchTableJsonByteLength, true); view.setUint32(24, batchTableBinaryByteLength, true); view.setUint32(28, gltfFormat, true); let i; let byteOffset = headerByteLength; for (i = 0; i < featureTableJsonByteLength; i++) { view.setUint8(byteOffset, featureTableJsonString.charCodeAt(i)); byteOffset++; } for (i = 0; i < featureTableBinaryByteLength; i++) { view.setUint8(byteOffset, featureTableBinary[i]); byteOffset++; } for (i = 0; i < batchTableJsonByteLength; i++) { view.setUint8(byteOffset, batchTableJsonString.charCodeAt(i)); byteOffset++; } for (i = 0; i < batchTableBinaryByteLength; i++) { view.setUint8(byteOffset, batchTableBinary[i]); byteOffset++; } for (i = 0; i < gltfUriByteLength; i++) { view.setUint8(byteOffset, gltfUri.charCodeAt(i)); byteOffset++; } return buffer; }; Cesium3DTilesTester.generatePointCloudTileBuffer = function(options) { options = (0, import_engine19.defaultValue)(options, import_engine19.defaultValue.EMPTY_OBJECT); const magic = (0, import_engine19.defaultValue)(options.magic, [112, 110, 116, 115]); const version = (0, import_engine19.defaultValue)(options.version, 1); let featureTableJson = options.featureTableJson; if (!(0, import_engine19.defined)(featureTableJson)) { featureTableJson = { POINTS_LENGTH: 1, POSITIONS: { byteOffset: 0 } }; } let featureTableJsonString = JSON.stringify(featureTableJson); featureTableJsonString = padStringToByteAlignment(featureTableJsonString, 4); const featureTableJsonByteLength = (0, import_engine19.defaultValue)( options.featureTableJsonByteLength, featureTableJsonString.length ); const featureTableBinary = new ArrayBuffer(12); const featureTableBinaryByteLength = featureTableBinary.byteLength; const headerByteLength = 28; const byteLength = headerByteLength + featureTableJsonByteLength + featureTableBinaryByteLength; const buffer = new ArrayBuffer(byteLength); const view = new DataView(buffer); view.setUint8(0, magic[0]); view.setUint8(1, magic[1]); view.setUint8(2, magic[2]); view.setUint8(3, magic[3]); view.setUint32(4, version, true); view.setUint32(8, byteLength, true); view.setUint32(12, featureTableJsonByteLength, true); view.setUint32(16, featureTableBinaryByteLength, true); view.setUint32(20, 0, true); view.setUint32(24, 0, true); let i; let byteOffset = headerByteLength; for (i = 0; i < featureTableJsonByteLength; i++) { view.setUint8(byteOffset, featureTableJsonString.charCodeAt(i)); byteOffset++; } for (i = 0; i < featureTableBinaryByteLength; i++) { view.setUint8(byteOffset, featureTableBinary[i]); byteOffset++; } return buffer; }; Cesium3DTilesTester.generateCompositeTileBuffer = function(options) { options = (0, import_engine19.defaultValue)(options, import_engine19.defaultValue.EMPTY_OBJECT); const magic = (0, import_engine19.defaultValue)(options.magic, [99, 109, 112, 116]); const version = (0, import_engine19.defaultValue)(options.version, 1); const tiles = (0, import_engine19.defaultValue)(options.tiles, []); const tilesLength = tiles.length; let i; let tilesByteLength = 0; for (i = 0; i < tilesLength; ++i) { tilesByteLength += tiles[i].byteLength; } const headerByteLength = 16; const byteLength = headerByteLength + tilesByteLength; const buffer = new ArrayBuffer(byteLength); const uint8Array = new Uint8Array(buffer); const view = new DataView(buffer); view.setUint8(0, magic[0]); view.setUint8(1, magic[1]); view.setUint8(2, magic[2]); view.setUint8(3, magic[3]); view.setUint32(4, version, true); view.setUint32(8, byteLength, true); view.setUint32(12, tilesLength, true); let byteOffset = headerByteLength; for (i = 0; i < tilesLength; ++i) { const tile = new Uint8Array(tiles[i]); uint8Array.set(tile, byteOffset); byteOffset += tile.byteLength; } return buffer; }; Cesium3DTilesTester.generateVectorTileBuffer = function(options) { options = (0, import_engine19.defaultValue)(options, import_engine19.defaultValue.EMPTY_OBJECT); const magic = (0, import_engine19.defaultValue)(options.magic, [118, 99, 116, 114]); const version = (0, import_engine19.defaultValue)(options.version, 1); let featureTableJsonString; let featureTableJsonByteLength = 0; const defineFeatureTable = (0, import_engine19.defaultValue)(options.defineFeatureTable, true); if (defineFeatureTable) { const defineRegion = (0, import_engine19.defaultValue)(options.defineRegion, true); const featureTableJson = { REGION: defineRegion ? [-1, -1, 1, 1, -1, 1] : void 0, POLYGONS_LENGTH: (0, import_engine19.defaultValue)(options.polygonsLength, 0), POLYLINES_LENGTH: (0, import_engine19.defaultValue)(options.polylinesLength, 0), POINTS_LENGTH: (0, import_engine19.defaultValue)(options.pointsLength, 0), POLYGON_BATCH_IDS: options.polygonBatchIds, POLYLINE_BATCH_IDS: options.polylineBatchIds, POINT_BATCH_IDS: options.pointBatchIds }; featureTableJsonString = JSON.stringify(featureTableJson); featureTableJsonByteLength = featureTableJsonString.length; } const headerByteLength = 44; const byteLength = headerByteLength + featureTableJsonByteLength; const buffer = new ArrayBuffer(byteLength); const view = new DataView(buffer); view.setUint8(0, magic[0]); view.setUint8(1, magic[1]); view.setUint8(2, magic[2]); view.setUint8(3, magic[3]); view.setUint32(4, version, true); view.setUint32(8, byteLength, true); view.setUint32(12, featureTableJsonByteLength, true); view.setUint32(16, 0, true); view.setUint32(20, 0, true); view.setUint32(24, 0, true); view.setUint32(28, 0, true); view.setUint32(32, 0, true); view.setUint32(36, 0, true); view.setUint32(40, 0, true); let i; let byteOffset = headerByteLength; for (i = 0; i < featureTableJsonByteLength; i++) { view.setUint8(byteOffset, featureTableJsonString.charCodeAt(i)); byteOffset++; } return buffer; }; Cesium3DTilesTester.generateGeometryTileBuffer = function(options) { options = (0, import_engine19.defaultValue)(options, import_engine19.defaultValue.EMPTY_OBJECT); const magic = (0, import_engine19.defaultValue)(options.magic, [103, 101, 111, 109]); const version = (0, import_engine19.defaultValue)(options.version, 1); let featureTableJsonString; let featureTableJsonByteLength = 0; const defineFeatureTable = (0, import_engine19.defaultValue)(options.defineFeatureTable, true); if (defineFeatureTable) { const featureTableJson = { BOXES_LENGTH: (0, import_engine19.defaultValue)(options.boxesLength, 0), CYLINDERS_LENGTH: (0, import_engine19.defaultValue)(options.cylindersLength, 0), ELLIPSOIDS_LENGTH: (0, import_engine19.defaultValue)(options.ellipsoidsLength, 0), SPHERES_LENGTH: (0, import_engine19.defaultValue)(options.spheresLength, 0), BOX_BATCH_IDS: options.boxBatchIds, CYLINDER_BATCH_IDS: options.cylinderBatchIds, ELLIPSOID_BATCH_IDS: options.ellipsoidBatchIds, SPHERE_BATCH_IDS: options.sphereBatchIds }; featureTableJsonString = JSON.stringify(featureTableJson); featureTableJsonByteLength = featureTableJsonString.length; } const headerByteLength = 28; const byteLength = headerByteLength + featureTableJsonByteLength; const buffer = new ArrayBuffer(byteLength); const view = new DataView(buffer); view.setUint8(0, magic[0]); view.setUint8(1, magic[1]); view.setUint8(2, magic[2]); view.setUint8(3, magic[3]); view.setUint32(4, version, true); view.setUint32(8, byteLength, true); view.setUint32(12, featureTableJsonByteLength, true); view.setUint32(16, 0, true); view.setUint32(20, 0, true); view.setUint32(24, 0, true); let i; let byteOffset = headerByteLength; for (i = 0; i < featureTableJsonByteLength; i++) { view.setUint8(byteOffset, featureTableJsonString.charCodeAt(i)); byteOffset++; } return buffer; }; var Cesium3DTilesTester_default = Cesium3DTilesTester; // packages/engine/Specs/Scene/B3dmParserSpec.js describe( "Scene/B3dmParser", function() { let scene2; const centerLongitude = -1.31968; const centerLatitude = 0.698874; const deprecated1Url = "./Data/Cesium3DTiles/Batched/BatchedDeprecated1/tileset.json"; const deprecated2Url = "./Data/Cesium3DTiles/Batched/BatchedDeprecated2/tileset.json"; function setCamera(longitude, latitude) { const center = import__415.Cartesian3.fromRadians(longitude, latitude); scene2.camera.lookAt(center, new import__415.HeadingPitchRange(0, -1.57, 15)); } beforeAll(function() { scene2 = createScene_default(); spyOn(import__415.B3dmParser, "_deprecationWarning"); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { setCamera(centerLongitude, centerLatitude); }); afterEach(function() { scene2.primitives.removeAll(); }); it("throws with invalid version", function() { const arrayBuffer = Cesium3DTilesTester_default.generateBatchedTileBuffer({ version: 2 }); expect(function() { import__415.B3dmParser.parse(arrayBuffer); }).toThrowError(import__415.RuntimeError); }); it("throws with empty gltf", function() { const arrayBuffer = Cesium3DTilesTester_default.generateBatchedTileBuffer(); expect(function() { import__415.B3dmParser.parse(arrayBuffer); }).toThrowError(import__415.RuntimeError); }); it("throws on undefined arrayBuffer", function() { expect(function() { import__415.B3dmParser.parse(void 0); }).toThrowDeveloperError(); }); it("recognizes the legacy 20-byte header", function() { return Cesium3DTilesTester_default.loadTileset(scene2, deprecated1Url).then( function(tileset) { expect(import__415.B3dmParser._deprecationWarning).toHaveBeenCalled(); Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); const batchTable = tileset.root.content.batchTable; expect(batchTable.featuresLength).toBe(10); } ); }); it("recognizes the legacy 24-byte header", function() { return Cesium3DTilesTester_default.loadTileset(scene2, deprecated2Url).then( function(tileset) { expect(import__415.B3dmParser._deprecationWarning).toHaveBeenCalled(); Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); const batchTable = tileset.root.content.batchTable; expect(batchTable.featuresLength).toBe(10); } ); }); it("logs deprecation warning for use of BATCHID without prefixed underscore", function() { return Cesium3DTilesTester_default.loadTileset(scene2, deprecated1Url).then( function(tileset) { expect(import__415.B3dmParser._deprecationWarning).toHaveBeenCalled(); Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); } ); }); }, "WebGL" ); // packages/engine/Specs/Scene/BatchTableHierarchySpec.js var import__416 = __toESM(require_Cesium(), 1); describe("Scene/BatchTableHierarchy", function() { const hierarchyExtension = { classes: [ { name: "Wall", length: 6, instances: { color: ["white", "red", "yellow", "gray", "brown", "black"] } }, { name: "Building", length: 3, instances: { name: ["unit29", "unit20", "unit93"], address: ["100 Main St", "102 Main St", "104 Main St"] } }, { name: "Owner", length: 3, instances: { type: ["city", "resident", "commercial"], id: [1120, 1250, 6445] } } ], instancesLength: 12, classIds: [0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2], parentCounts: [1, 3, 2, 1, 1, 1, 1, 1, 1, 0, 0, 0], parentIds: [6, 6, 10, 11, 7, 11, 7, 8, 8, 10, 10, 9] }; const binaryHierarchy = { classes: [ { name: "Box", length: 3, instances: { items: { type: "SCALAR", componentType: "UNSIGNED_BYTE", byteOffset: 0 }, coordinates: { type: "VEC2", componentType: "UNSIGNED_BYTE", byteOffset: 4 } } }, { name: "Pallet", length: 1, instances: { boxCount: [1] } } ], instancesLength: 4, classIds: [0, 1, 0, 0], parentIds: [1, 1, 2, 3] }; const binaryHierarchyBody = new Uint8Array([1, 2, 3, 0, 1, 0, 1, 2, 3, 2]); const binaryHierarchyWithBinaryIds = { classes: [ { name: "Box", length: 3, instances: { items: { type: "SCALAR", componentType: "UNSIGNED_BYTE", byteOffset: 8 }, coordinates: { type: "VEC2", componentType: "UNSIGNED_BYTE", byteOffset: 12 } } }, { name: "Pallet", length: 1, instances: { boxCount: [1] } } ], instancesLength: 4, classIds: { byteOffset: 18, componentType: "UNSIGNED_BYTE" }, parentIds: { byteOffset: 22, componentType: "UNSIGNED_BYTE" }, // included explicitly to test byteLength parentCounts: { byteOffset: 26, componentType: "UNSIGNED_BYTE" } }; const binaryHierarchyBodyWithIds = new Uint8Array([ // padding to simulate other data in the binary body 0, 0, 0, 0, 0, 0, 0, 0, // binary property: items 1, 2, 3, 0, // binary property: coordinates 1, 0, 1, 2, 3, 2, // class IDs 0, 1, 0, 0, // parent Ids 1, 1, 2, 3, // parent counts 1, 1, 1, 1 ]); it("throws without extension", function() { expect(function() { return new import__416.BatchTableHierarchy({ extension: void 0 }); }).toThrowDeveloperError(); }); it("throws for invalid binary property", function() { const missingType = { classes: [ { name: "Resources", length: 2, instances: { foodUnits: { byteOffset: 0, componentType: "UNSIGNED_SHORT" }, waterUnits: [15, 13] } } ], instancesLength: 2, classIds: [0, 0], parentIds: [1, 1] }; const foodUnits = new Uint16Array([10, 20]); const binaryBody = new Uint8Array(foodUnits.buffer); expect(function() { return new import__416.BatchTableHierarchy({ extension: missingType, binaryBody }); }).toThrowError(import__416.RuntimeError); const missingComponentType = { classes: [ { name: "Resources", length: 2, instances: { foodUnits: { byteOffset: 0, type: "SCALAR" }, waterUnits: [15, 13] } } ], instancesLength: 2, classIds: [0, 0], parentIds: [1, 1] }; expect(function() { return new import__416.BatchTableHierarchy({ extension: missingComponentType, binaryBody }); }).toThrowError(import__416.RuntimeError); }); it("throws if binaryBody is needed and not provided", function() { const hierarchyExtension2 = { classes: [ { name: "Resources", length: 2, instances: { foodUnits: { byteOffset: 0, type: "SCALAR", componentType: "UNSIGNED_SHORT" }, waterUnits: [15, 13] } } ], instancesLength: 2, classIds: [0, 0], parentIds: [1, 1] }; expect(function() { return new import__416.BatchTableHierarchy({ extension: hierarchyExtension2 }); }).toThrowError(import__416.RuntimeError); }); it("hasProperty returns true if the feature has this property", function() { const deep = true; const hierarchy = new import__416.BatchTableHierarchy({ extension: (0, import__416.clone)(hierarchyExtension, deep) }); expect(hierarchy.hasProperty(0, "color")).toBe(true); }); it("hasProperty returns false if the feature does not have this property", function() { const deep = true; const hierarchy = new import__416.BatchTableHierarchy({ extension: (0, import__416.clone)(hierarchyExtension, deep) }); expect(hierarchy.hasProperty(0, "height")).toBe(false); }); it("hasProperty returns false if the feature does not inherit this property", function() { const deep = true; const hierarchy = new import__416.BatchTableHierarchy({ extension: (0, import__416.clone)(hierarchyExtension, deep) }); expect(hierarchy.hasProperty(6, "color")).toBe(false); }); it("propertyExists returns true if any feature has this property", function() { const deep = true; const hierarchy = new import__416.BatchTableHierarchy({ extension: (0, import__416.clone)(hierarchyExtension, deep) }); expect(hierarchy.propertyExists("color")).toBe(true); }); it("propertyExists returns false if no features have this property", function() { const deep = true; const hierarchy = new import__416.BatchTableHierarchy({ extension: (0, import__416.clone)(hierarchyExtension, deep) }); expect(hierarchy.propertyExists("other")).toBe(false); }); it("getProperty returns property value", function() { const deep = true; const hierarchy = new import__416.BatchTableHierarchy({ extension: (0, import__416.clone)(hierarchyExtension, deep) }); expect(hierarchy.getProperty(0, "color")).toBe("white"); expect(hierarchy.getProperty(0, "name")).toBe("unit29"); expect(hierarchy.getProperty(0, "address")).toBe("100 Main St"); expect(hierarchy.getProperty(0, "type")).toBe("resident"); expect(hierarchy.getProperty(0, "id")).toBe(1250); }); it("getProperty returns undefined for unknown property", function() { const deep = true; const hierarchy = new import__416.BatchTableHierarchy({ extension: (0, import__416.clone)(hierarchyExtension, deep) }); expect(hierarchy.getProperty(0, "occupancy")).not.toBeDefined(); }); it("getProperty works with binary properties", function() { const deep = true; const hierarchy = new import__416.BatchTableHierarchy({ extension: (0, import__416.clone)(binaryHierarchy, deep), binaryBody: binaryHierarchyBody }); expect(hierarchy.getProperty(0, "items")).toBe(1); expect(hierarchy.getProperty(0, "coordinates")).toEqual( new import__416.Cartesian2(1, 0) ); expect(hierarchy.getProperty(0, "boxCount")).toBe(1); expect(hierarchy.getProperty(1, "items")).not.toBeDefined(); expect(hierarchy.getProperty(1, "coordinates")).not.toBeDefined(); expect(hierarchy.getProperty(1, "boxCount")).toBe(1); expect(hierarchy.getProperty(2, "items")).toBe(2); expect(hierarchy.getProperty(2, "coordinates")).toEqual( new import__416.Cartesian2(1, 2) ); expect(hierarchy.getProperty(2, "boxCount")).not.toBeDefined(); expect(hierarchy.getProperty(3, "items")).toBe(3); expect(hierarchy.getProperty(3, "coordinates")).toEqual( new import__416.Cartesian2(3, 2) ); expect(hierarchy.getProperty(3, "boxCount")).not.toBeDefined(); }); it("getProperty works with binary properties and ids", function() { const deep = true; const hierarchy = new import__416.BatchTableHierarchy({ extension: (0, import__416.clone)(binaryHierarchyWithBinaryIds, deep), binaryBody: binaryHierarchyBodyWithIds }); expect(hierarchy.getProperty(0, "items")).toBe(1); expect(hierarchy.getProperty(0, "coordinates")).toEqual( new import__416.Cartesian2(1, 0) ); expect(hierarchy.getProperty(0, "boxCount")).toBe(1); expect(hierarchy.getProperty(1, "items")).not.toBeDefined(); expect(hierarchy.getProperty(1, "coordinates")).not.toBeDefined(); expect(hierarchy.getProperty(1, "boxCount")).toBe(1); expect(hierarchy.getProperty(2, "items")).toBe(2); expect(hierarchy.getProperty(2, "coordinates")).toEqual( new import__416.Cartesian2(1, 2) ); expect(hierarchy.getProperty(2, "boxCount")).not.toBeDefined(); expect(hierarchy.getProperty(3, "items")).toBe(3); expect(hierarchy.getProperty(3, "coordinates")).toEqual( new import__416.Cartesian2(3, 2) ); expect(hierarchy.getProperty(3, "boxCount")).not.toBeDefined(); }); it("setProperty throws when trying to set an inherited property", function() { const deep = true; const hierarchy = new import__416.BatchTableHierarchy({ extension: (0, import__416.clone)(hierarchyExtension, deep) }); expect(function() { hierarchy.setProperty(0, "type", "city"); }).toThrowDeveloperError(); }); it("setProperty returns false when property does not exist", function() { const deep = true; const hierarchy = new import__416.BatchTableHierarchy({ extension: (0, import__416.clone)(hierarchyExtension, deep) }); expect(hierarchy.setProperty(0, "occupancy", 100)).toBe(false); }); it("setProperty sets property value", function() { const deep = true; const hierarchy = new import__416.BatchTableHierarchy({ extension: (0, import__416.clone)(hierarchyExtension, deep) }); expect(hierarchy.getProperty(0, "color")).toBe("white"); expect(hierarchy.setProperty(0, "color", "brown")).toBe(true); expect(hierarchy.getProperty(0, "color")).toBe("brown"); }); it("setProperty works with binary values", function() { const deep = true; const hierarchy = new import__416.BatchTableHierarchy({ extension: (0, import__416.clone)(binaryHierarchy, deep), binaryBody: binaryHierarchyBody }); expect(hierarchy.getProperty(0, "items")).toBe(1); expect(hierarchy.setProperty(0, "items", 5)).toBe(true); expect(hierarchy.getProperty(0, "items")).toBe(5); expect(hierarchy.getProperty(2, "coordinates")).toEqual( new import__416.Cartesian2(1, 2) ); const position = new import__416.Cartesian2(5, 5); expect(hierarchy.setProperty(2, "coordinates", position)).toBe(true); expect(hierarchy.getProperty(2, "coordinates")).toEqual(position); }); it("setProperty works with binary values and ids", function() { const deep = true; const hierarchy = new import__416.BatchTableHierarchy({ extension: (0, import__416.clone)(binaryHierarchyWithBinaryIds, deep), binaryBody: binaryHierarchyBodyWithIds }); expect(hierarchy.getProperty(0, "items")).toBe(1); expect(hierarchy.setProperty(0, "items", 5)).toBe(true); expect(hierarchy.getProperty(0, "items")).toBe(5); expect(hierarchy.getProperty(2, "coordinates")).toEqual( new import__416.Cartesian2(1, 2) ); const position = new import__416.Cartesian2(5, 5); expect(hierarchy.setProperty(2, "coordinates", position)).toBe(true); expect(hierarchy.getProperty(2, "coordinates")).toEqual(position); }); it("validates hierarchy with multiple parents", function() { const extension = { instancesLength: 4, classIds: [0, 1, 1, 2], parentCounts: [2, 1, 1, 0], parentIds: [1, 2, 3, 3], classes: [ { name: "window", length: 1, instances: { window_name: ["window0"] } }, { name: "door", length: 2, instances: { door_name: ["door0", "door1"] } }, { name: "building", length: 1, instances: { building_name: ["building0"] } } ] }; const hierarchy = new import__416.BatchTableHierarchy({ extension }); expect(hierarchy.getPropertyIds(0).sort()).toEqual([ "building_name", "door_name", "window_name" ]); }); it("validates hierarchy with multiple parents (2)", function() { const extension = { instancesLength: 4, classIds: [0, 1, 1, 2, 3], parentCounts: [3, 1, 2, 1, 0], parentIds: [1, 2, 4, 3, 3, 4, 4], classes: [ { name: "window", length: 1, instances: { window_name: ["window0"] } }, { name: "door", length: 2, instances: { door_name: ["door0", "door1"] } }, { name: "building", length: 1, instances: { building_name: ["building0"] } }, { name: "zone", length: 1, instances: { zone_name: ["zone0"] } } ] }; const hierarchy = new import__416.BatchTableHierarchy({ extension }); expect(hierarchy.getPropertyIds(0).sort()).toEqual([ "building_name", "door_name", "window_name", "zone_name" ]); expect(hierarchy.hasProperty(1, "zone_name")).toEqual(true); expect(hierarchy.hasProperty(2, "zone_name")).toEqual(true); }); it("throws if hierarchy has a circular dependency", function() { const extension = { instancesLength: 3, classIds: [0, 1, 2], parentIds: [1, 2, 0], classes: [ { name: "window", length: 1, instances: { window_name: ["window0"] } }, { name: "door", length: 1, instances: { door_name: ["door0"] } }, { name: "building", length: 1, instances: { building_name: ["building0"] } } ] }; expect(function() { return new import__416.BatchTableHierarchy({ extension }); }).toThrowDeveloperError(); }); it("throws if hierarchy has a circular dependency (2)", function() { const extension = { instancesLength: 4, classIds: [0, 1, 2, 0], parentIds: [1, 2, 3, 1], classes: [ { name: "window", length: 2, instances: { window_name: ["window0", "window1"] } }, { name: "door", length: 1, instances: { door_name: ["door0"] } }, { name: "building", length: 1, instances: { building_name: ["building0"] } } ] }; expect(function() { return new import__416.BatchTableHierarchy({ extension }); }).toThrowDeveloperError(); }); it("throws if an instance's parentId exceeds instancesLength", function() { const extension = { instancesLength: 2, classIds: [0, 1], parentIds: [1, 2], classes: [ { name: "window", length: 1, instances: { window_name: ["window0"] } }, { name: "door", length: 1, instances: { door_name: ["door0"] } } ] }; expect(function() { return new import__416.BatchTableHierarchy({ extension }); }).toThrowDeveloperError(); }); it("Computes byteLength from typed arrays", function() { const deep = true; const hierarchy = new import__416.BatchTableHierarchy({ extension: (0, import__416.clone)(binaryHierarchyWithBinaryIds, deep), binaryBody: binaryHierarchyBodyWithIds }); const classIdsSize = 4; const parentCountsSize = 4; const parentIndexesSize = 4 * 2; const parentIdsSize = 4; const binaryPropertiesSize = 3 + 6; const classIndexesSize = 4 * 2; const expectedByteLength = classIdsSize + parentCountsSize + parentIndexesSize + parentIdsSize + binaryPropertiesSize + classIndexesSize; expect(hierarchy.byteLength).toBe(expectedByteLength); }); }); // packages/engine/Specs/Scene/BatchTableSpec.js var import__417 = __toESM(require_Cesium(), 1); var import__418 = __toESM(require_Cesium(), 1); describe( "Scene/BatchTable", function() { const unsignedByteAttributes = [ { functionName: "batchTable_getShow", componentDatatype: import__417.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 1 }, { functionName: "batchTable_getPickColor", componentDatatype: import__417.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 4, normalize: true } ]; const floatAttributes = [ { functionName: "batchTable_getShow", componentDatatype: import__417.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 1 }, { functionName: "batchTable_getCenter", componentDatatype: import__417.ComponentDatatype.FLOAT, componentsPerAttribute: 4 } ]; let batchTable; let scene2; let context; beforeAll(function() { scene2 = createScene_default(); context = scene2.context; }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { batchTable = batchTable && !batchTable.isDestroyed() && batchTable.destroy(); }); it("constructor", function() { batchTable = new import__417.BatchTable(context, unsignedByteAttributes, 2); expect(batchTable.attributes).toBe(unsignedByteAttributes); expect(batchTable.numberOfInstances).toEqual(2); }); it("constructior throws without context", function() { expect(function() { batchTable = new import__417.BatchTable(void 0, unsignedByteAttributes, 5); }).toThrowDeveloperError(); }); it("constructior throws without attributes", function() { expect(function() { batchTable = new import__417.BatchTable(context, void 0, 5); }).toThrowDeveloperError(); }); it("constructor throws without number of instances", function() { expect(function() { batchTable = new import__417.BatchTable(context, unsignedByteAttributes, void 0); }).toThrowDeveloperError(); }); it("sets and gets entries in the table", function() { batchTable = new import__417.BatchTable(context, unsignedByteAttributes, 5); let i; let color = new import__417.Cartesian4(0, 1, 2, 3); for (i = 0; i < batchTable.numberOfInstances; ++i) { batchTable.setBatchedAttribute(i, 0, 1); batchTable.setBatchedAttribute(i, 1, color); } for (i = 0; i < batchTable.numberOfInstances; ++i) { expect(batchTable.getBatchedAttribute(3, 0)).toEqual(1); expect(batchTable.getBatchedAttribute(3, 1)).toEqual(color); } color = new import__417.Cartesian4(4, 5, 6, 7); batchTable.setBatchedAttribute(3, 0, 0); batchTable.setBatchedAttribute(3, 1, color); expect(batchTable.getBatchedAttribute(3, 0)).toEqual(0); expect(batchTable.getBatchedAttribute(3, 1)).toEqual(color); }); it("sets and gets entries in the table with float attributes", function() { const context2 = { floatingPointTexture: true }; batchTable = new import__417.BatchTable(context2, floatAttributes, 5); let i; let color = new import__417.Cartesian4(0, 1, 2, 3); for (i = 0; i < batchTable.numberOfInstances; ++i) { batchTable.setBatchedAttribute(i, 0, 1); batchTable.setBatchedAttribute(i, 1, color); } for (i = 0; i < batchTable.numberOfInstances; ++i) { expect(batchTable.getBatchedAttribute(3, 0)).toEqual(1); expect(batchTable.getBatchedAttribute(3, 1)).toEqual(color); } color = new import__417.Cartesian4(4, 5, 6, 7); batchTable.setBatchedAttribute(3, 0, 0); batchTable.setBatchedAttribute(3, 1, color); expect(batchTable.getBatchedAttribute(3, 0)).toEqual(0); expect(batchTable.getBatchedAttribute(3, 1)).toEqual(color); }); it("sets and gets entries in the table with float attributes and forced packing", function() { const context2 = { floatingPointTexture: false }; batchTable = new import__417.BatchTable(context2, floatAttributes, 5); let i; let color = new import__417.Cartesian4( 123456e7, -234567e25, 345678e-11, -456789e-15 ); for (i = 0; i < batchTable.numberOfInstances; ++i) { batchTable.setBatchedAttribute(i, 0, 1); batchTable.setBatchedAttribute(i, 1, color); } let value; for (i = 0; i < batchTable.numberOfInstances; ++i) { value = batchTable.getBatchedAttribute(3, 0); expect(value).toEqual(1); value = batchTable.getBatchedAttribute(3, 1); expect(value).toEqualEpsilon(color, import__418.Math.EPSILON6); } color = new import__417.Cartesian4( 0, Number.MAX_VALUE, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY ); batchTable.setBatchedAttribute(3, 0, 0); batchTable.setBatchedAttribute(3, 1, color); value = batchTable.getBatchedAttribute(3, 0); expect(value).toEqual(0); value = batchTable.getBatchedAttribute(3, 1); expect(value.x).toEqual(0); expect(value.y).toEqual(Number.POSITIVE_INFINITY); expect(value.z).toEqual(Number.POSITIVE_INFINITY); expect(value.w).toEqual(Number.NEGATIVE_INFINITY); }); it("gets with result parameter", function() { batchTable = new import__417.BatchTable(context, unsignedByteAttributes, 5); const color = new import__417.Cartesian4(0, 1, 2, 3); batchTable.setBatchedAttribute(0, 1, color); const result = new import__417.Cartesian4(); const returndValue = batchTable.getBatchedAttribute(0, 1, result); expect(returndValue).toBe(result); expect(result).toEqual(color); }); it("get entry throws when instance index is out of range", function() { batchTable = new import__417.BatchTable(context, unsignedByteAttributes, 5); expect(function() { batchTable.getBatchedAttribute(-1, 0); }).toThrowDeveloperError(); expect(function() { batchTable.getBatchedAttribute(100, 0); }).toThrowDeveloperError(); }); it("get entry throws when attribute index is out of range", function() { batchTable = new import__417.BatchTable(context, unsignedByteAttributes, 5); expect(function() { batchTable.getBatchedAttribute(0, -1); }).toThrowDeveloperError(); expect(function() { batchTable.getBatchedAttribute(0, 100); }).toThrowDeveloperError(); }); it("set entry throws when instance index is out of range", function() { batchTable = new import__417.BatchTable(context, unsignedByteAttributes, 5); expect(function() { batchTable.setBatchedAttribute(-1, 0, 0); }).toThrowDeveloperError(); expect(function() { batchTable.setBatchedAttribute(100, 0, 1); }).toThrowDeveloperError(); }); it("set entry throws when attribute index is out of range", function() { batchTable = new import__417.BatchTable(context, unsignedByteAttributes, 5); expect(function() { batchTable.setBatchedAttribute(0, -1, 1); }).toThrowDeveloperError(); expect(function() { batchTable.setBatchedAttribute(0, 100, 1); }).toThrowDeveloperError(); }); it("set entry throws when value is undefined", function() { batchTable = new import__417.BatchTable(context, unsignedByteAttributes, 5); expect(function() { batchTable.setBatchedAttribute(0, 0, void 0); }).toThrowDeveloperError(); }); it("creates a uniform callback with unsigned byte texture", function() { batchTable = new import__417.BatchTable(context, unsignedByteAttributes, 5); batchTable.update(scene2.frameState); const uniforms = batchTable.getUniformMapCallback()({}); expect(uniforms.batchTexture).toBeDefined(); expect(uniforms.batchTexture()).toBeInstanceOf(import__417.Texture); expect(uniforms.batchTexture().pixelDatatype).toEqual( import__417.PixelDatatype.UNSIGNED_BYTE ); expect(uniforms.batchTextureDimensions).toBeDefined(); expect(uniforms.batchTextureDimensions().x).toBeGreaterThan(0); expect(uniforms.batchTextureDimensions().y).toBeGreaterThan(0); expect(uniforms.batchTextureStep).toBeDefined(); expect(uniforms.batchTextureStep().x).toBeGreaterThan(0); expect(uniforms.batchTextureStep().y).toBeGreaterThan(0); expect(uniforms.batchTextureStep().z).toBeGreaterThan(0); expect(uniforms.batchTextureStep().w).toBeGreaterThan(0); }); it("creates a uniform callback with float texture", function() { if (!context.floatingPointTexture) { return; } batchTable = new import__417.BatchTable(context, floatAttributes, 5); batchTable.update(scene2.frameState); const uniforms = batchTable.getUniformMapCallback()({}); expect(uniforms.batchTexture).toBeDefined(); expect(uniforms.batchTexture()).toBeInstanceOf(import__417.Texture); expect(uniforms.batchTexture().pixelDatatype).toEqual( import__417.PixelDatatype.FLOAT ); expect(uniforms.batchTextureDimensions).toBeDefined(); expect(uniforms.batchTextureDimensions().x).toBeGreaterThan(0); expect(uniforms.batchTextureDimensions().y).toBeGreaterThan(0); expect(uniforms.batchTextureStep).toBeDefined(); expect(uniforms.batchTextureStep().x).toBeGreaterThan(0); expect(uniforms.batchTextureStep().y).toBeGreaterThan(0); expect(uniforms.batchTextureStep().z).toBeGreaterThan(0); expect(uniforms.batchTextureStep().w).toBeGreaterThan(0); if (scene2.context.floatingPointTexture) { expect(uniforms.batchTexture().pixelDatatype).toEqual( import__417.PixelDatatype.FLOAT ); } else { expect(uniforms.batchTexture().pixelDatatype).toEqual( import__417.PixelDatatype.UNSIGNED_BYTE ); } }); it("create shader functions", function() { batchTable = new import__417.BatchTable(context, unsignedByteAttributes, 5); const shader = "void main() { gl_Position = vec4(0.0); }"; const modifiedShader = batchTable.getVertexShaderCallback()(shader); expect( modifiedShader.indexOf(batchTable.attributes[0].functionName) ).not.toEqual(-1); expect( modifiedShader.indexOf(batchTable.attributes[1].functionName) ).not.toEqual(-1); }); it("isDestroyed", function() { batchTable = new import__417.BatchTable(context, unsignedByteAttributes, 5); expect(batchTable.isDestroyed()).toEqual(false); batchTable.destroy(); expect(batchTable.isDestroyed()).toEqual(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/BatchTextureSpec.js var import__419 = __toESM(require_Cesium(), 1); describe( "Scene/BatchTexture", function() { let scene2; const mockOwner = {}; const mockTileset = { _statistics: { batchTableByteLength: 0 } }; beforeAll(function() { scene2 = createScene_default(); }); const result = new import__419.Color(); it("throws without featuresLength", function() { expect(function() { return new import__419.BatchTexture({ featuresLength: void 0, owner: mockOwner }); }).toThrowDeveloperError(); }); it("throws without owner", function() { expect(function() { return new import__419.BatchTexture({ featuresLength: 1, owner: void 0 }); }).toThrowDeveloperError(); }); it("setShow throws with invalid batchId", function() { const batchTexture = new import__419.BatchTexture({ owner: mockOwner, featuresLength: 1 }); expect(function() { batchTexture.setShow(); }).toThrowDeveloperError(); expect(function() { batchTexture.setShow(-1); }).toThrowDeveloperError(); expect(function() { batchTexture.setShow(1); }).toThrowDeveloperError(); }); it("setShow throws with undefined value", function() { const batchTexture = new import__419.BatchTexture({ owner: mockOwner, featuresLength: 1 }); expect(function() { batchTexture.setShow(0); }).toThrowDeveloperError(); }); it("setShow sets show", function() { const batchTexture = new import__419.BatchTexture({ owner: mockOwner, featuresLength: 1 }); expect(batchTexture._batchValues).toBeUndefined(); expect(batchTexture._batchTexture).toBeUndefined(); batchTexture.setShow(0, true); batchTexture.update(mockTileset, scene2.frameState); expect(batchTexture._batchValues).toBeUndefined(); expect(batchTexture._batchTexture).toBeUndefined(); expect(batchTexture.getShow(0)).toEqual(true); batchTexture.setShow(0, false); expect(batchTexture._batchValuesDirty).toEqual(true); batchTexture.update(mockTileset, scene2.frameState); expect(batchTexture._batchValues).toBeDefined(); expect(batchTexture._batchTexture).toBeDefined(); expect(batchTexture._batchValuesDirty).toEqual(false); expect(batchTexture.getShow(0)).toEqual(false); batchTexture.setShow(0, false); expect(batchTexture._batchValuesDirty).toEqual(false); expect(batchTexture.getShow(0)).toEqual(false); }); it("getShow throws with invalid batchId", function() { const batchTexture = new import__419.BatchTexture({ owner: mockOwner, featuresLength: 1 }); expect(function() { batchTexture.getShow(); }).toThrowDeveloperError(); expect(function() { batchTexture.getShow(-1); }).toThrowDeveloperError(); expect(function() { batchTexture.getShow(1); }).toThrowDeveloperError(); }); it("getShow", function() { const batchTexture = new import__419.BatchTexture({ owner: mockOwner, featuresLength: 1 }); expect(batchTexture.getShow(0)).toEqual(true); batchTexture.setShow(0, false); expect(batchTexture.getShow(0)).toEqual(false); }); it("setColor throws with invalid batchId", function() { const batchTexture = new import__419.BatchTexture({ owner: mockOwner, featuresLength: 1 }); expect(function() { batchTexture.setColor(); }).toThrowDeveloperError(); expect(function() { batchTexture.setColor(-1); }).toThrowDeveloperError(); expect(function() { batchTexture.setColor(1); }).toThrowDeveloperError(); }); it("setColor throws with undefined value", function() { const batchTexture = new import__419.BatchTexture({ owner: mockOwner, featuresLength: 1 }); expect(function() { batchTexture.setColor(0); }).toThrowDeveloperError(); }); it("setColor", function() { const batchTexture = new import__419.BatchTexture({ owner: mockOwner, featuresLength: 1 }); expect(batchTexture._batchValues).toBeUndefined(); expect(batchTexture._batchTexture).toBeUndefined(); batchTexture.setColor(0, import__419.Color.WHITE); batchTexture.update(mockTileset, scene2.frameState); expect(batchTexture._batchValues).toBeUndefined(); expect(batchTexture._batchTexture).toBeUndefined(); expect(batchTexture.getColor(0, result)).toEqual(import__419.Color.WHITE); batchTexture.setColor(0, import__419.Color.YELLOW); expect(batchTexture._batchValuesDirty).toEqual(true); batchTexture.update(mockTileset, scene2.frameState); expect(batchTexture._batchValues).toBeDefined(); expect(batchTexture._batchTexture).toBeDefined(); expect(batchTexture._batchValuesDirty).toEqual(false); expect(batchTexture.getColor(0, result)).toEqual(import__419.Color.YELLOW); batchTexture.setColor(0, import__419.Color.YELLOW); expect(batchTexture._batchValuesDirty).toEqual(false); expect(batchTexture.getColor(0, result)).toEqual(import__419.Color.YELLOW); }); it("setAllColor throws with undefined value", function() { const batchTexture = new import__419.BatchTexture({ owner: mockOwner, featuresLength: 1 }); expect(function() { batchTexture.setAllColor(); }).toThrowDeveloperError(); }); it("setAllColor", function() { const batchTexture = new import__419.BatchTexture({ owner: mockOwner, featuresLength: 2 }); batchTexture.setAllColor(import__419.Color.YELLOW); expect(batchTexture.getColor(0, result)).toEqual(import__419.Color.YELLOW); expect(batchTexture.getColor(1, result)).toEqual(import__419.Color.YELLOW); }); it("setAllShow throws with undefined value", function() { const batchTexture = new import__419.BatchTexture({ owner: mockOwner, featuresLength: 1 }); expect(function() { batchTexture.setAllShow(); }).toThrowDeveloperError(); }); it("setAllShow", function() { const batchTexture = new import__419.BatchTexture({ owner: mockOwner, featuresLength: 2 }); batchTexture.setAllShow(false); expect(batchTexture.getShow(0)).toBe(false); expect(batchTexture.getShow(1)).toBe(false); }); it("getColor throws with invalid batchId", function() { const batchTexture = new import__419.BatchTexture({ owner: mockOwner, featuresLength: 1 }); expect(function() { batchTexture.getColor(); }).toThrowDeveloperError(); expect(function() { batchTexture.getColor(-1); }).toThrowDeveloperError(); expect(function() { batchTexture.getColor(1); }).toThrowDeveloperError(); }); it("getColor throws with undefined result", function() { const batchTexture = new import__419.BatchTexture({ owner: mockOwner, featuresLength: 1 }); expect(function() { batchTexture.getColor(0); }).toThrowDeveloperError(); }); it("getColor", function() { const batchTexture = new import__419.BatchTexture({ owner: mockOwner, featuresLength: 1 }); expect(batchTexture.getColor(0, result)).toEqual(import__419.Color.WHITE); batchTexture.setColor(0, import__419.Color.YELLOW); expect(batchTexture.getColor(0, result)).toEqual(import__419.Color.YELLOW); }); }, "WebGL" ); // packages/engine/Specs/Scene/BillboardCollectionSpec.js var import__420 = __toESM(require_Cesium(), 1); var import__421 = __toESM(require_Cesium(), 1); describe( "Scene/BillboardCollection", function() { let scene2; let context; let camera; let billboards; let greenImage; let blueImage; let whiteImage; let largeBlueImage; beforeAll(function() { scene2 = createScene_default(); context = scene2.context; camera = scene2.camera; return Promise.all([ import__420.Resource.fetchImage("./Data/Images/Green2x2.png").then(function(result) { greenImage = result; }), import__420.Resource.fetchImage("./Data/Images/Blue2x2.png").then(function(result) { blueImage = result; }), import__420.Resource.fetchImage("./Data/Images/White2x2.png").then(function(result) { whiteImage = result; }), import__420.Resource.fetchImage("./Data/Images/Blue10x10.png").then(function(result) { largeBlueImage = result; }) ]); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { scene2.morphTo3D(0); camera.position = new import__420.Cartesian3(10, 0, 0); camera.direction = import__420.Cartesian3.negate(import__420.Cartesian3.UNIT_X, new import__420.Cartesian3()); camera.up = import__420.Cartesian3.clone(import__420.Cartesian3.UNIT_Z); camera.frustum = new import__420.PerspectiveFrustum(); camera.frustum.aspectRatio = scene2.drawingBufferWidth / scene2.drawingBufferHeight; camera.frustum.fov = import__421.Math.toRadians(60); billboards = new import__420.BillboardCollection(); scene2.primitives.add(billboards); }); afterEach(function() { scene2.primitives.removeAll(); }); it("constructs a default billboard", function() { const b = billboards.add(); expect(b.show).toEqual(true); expect(b.position).toEqual(import__420.Cartesian3.ZERO); expect(b.pixelOffset).toEqual(import__420.Cartesian2.ZERO); expect(b.eyeOffset).toEqual(import__420.Cartesian3.ZERO); expect(b.horizontalOrigin).toEqual(import__420.HorizontalOrigin.CENTER); expect(b.verticalOrigin).toEqual(import__420.VerticalOrigin.CENTER); expect(b.scale).toEqual(1); expect(b.image).toBeUndefined(); expect(b.color.red).toEqual(1); expect(b.color.green).toEqual(1); expect(b.color.blue).toEqual(1); expect(b.color.alpha).toEqual(1); expect(b.rotation).toEqual(0); expect(b.alignedAxis).toEqual(import__420.Cartesian3.ZERO); expect(b.scaleByDistance).toBeUndefined(); expect(b.translucencyByDistance).toBeUndefined(); expect(b.pixelOffsetScaleByDistance).toBeUndefined(); expect(b.width).toBeUndefined(); expect(b.height).toBeUndefined(); expect(b.id).toBeUndefined(); expect(b.heightReference).toEqual(import__420.HeightReference.NONE); expect(b.sizeInMeters).toEqual(false); expect(b.distanceDisplayCondition).toBeUndefined(); expect(b.disableDepthTestDistance).toBeUndefined(); }); it("can add and remove before first update.", function() { const b = billboards.add(); billboards.remove(b); scene2.renderForSpecs(); }); it("explicitly constructs a billboard", function() { const b = billboards.add({ show: false, position: new import__420.Cartesian3(1, 2, 3), pixelOffset: new import__420.Cartesian2(1, 2), eyeOffset: new import__420.Cartesian3(1, 2, 3), horizontalOrigin: import__420.HorizontalOrigin.LEFT, verticalOrigin: import__420.VerticalOrigin.BOTTOM, scale: 2, image: greenImage, color: { red: 1, green: 2, blue: 3, alpha: 4 }, rotation: 1, alignedAxis: import__420.Cartesian3.UNIT_Z, scaleByDistance: new import__420.NearFarScalar(1, 3, 1e6, 0), translucencyByDistance: new import__420.NearFarScalar(1, 1, 1e6, 0), pixelOffsetScaleByDistance: new import__420.NearFarScalar(1, 1, 1e6, 0), width: 300, height: 200, sizeInMeters: true, distanceDisplayCondition: new import__420.DistanceDisplayCondition(10, 100), disableDepthTestDistance: 10, id: "id" }); expect(b.show).toEqual(false); expect(b.position).toEqual(new import__420.Cartesian3(1, 2, 3)); expect(b.pixelOffset).toEqual(new import__420.Cartesian2(1, 2)); expect(b.eyeOffset).toEqual(new import__420.Cartesian3(1, 2, 3)); expect(b.horizontalOrigin).toEqual(import__420.HorizontalOrigin.LEFT); expect(b.verticalOrigin).toEqual(import__420.VerticalOrigin.BOTTOM); expect(b.scale).toEqual(2); expect(b.image).toEqual(b._imageId); expect(b.color.red).toEqual(1); expect(b.color.green).toEqual(2); expect(b.color.blue).toEqual(3); expect(b.color.alpha).toEqual(4); expect(b.rotation).toEqual(1); expect(b.alignedAxis).toEqual(import__420.Cartesian3.UNIT_Z); expect(b.scaleByDistance).toEqual( new import__420.NearFarScalar(1, 3, 1e6, 0) ); expect(b.translucencyByDistance).toEqual( new import__420.NearFarScalar(1, 1, 1e6, 0) ); expect(b.pixelOffsetScaleByDistance).toEqual( new import__420.NearFarScalar(1, 1, 1e6, 0) ); expect(b.width).toEqual(300); expect(b.height).toEqual(200); expect(b.sizeInMeters).toEqual(true); expect(b.distanceDisplayCondition).toEqual( new import__420.DistanceDisplayCondition(10, 100) ); expect(b.disableDepthTestDistance).toEqual(10); expect(b.id).toEqual("id"); }); it("sets billboard properties", function() { const b = billboards.add(); b.show = false; b.position = new import__420.Cartesian3(1, 2, 3); b.pixelOffset = new import__420.Cartesian2(1, 2); b.eyeOffset = new import__420.Cartesian3(1, 2, 3); b.horizontalOrigin = import__420.HorizontalOrigin.LEFT; b.verticalOrigin = import__420.VerticalOrigin.BOTTOM; b.scale = 2; b.image = greenImage; b.color = new import__420.Color(1, 2, 3, 4); b.rotation = 1; b.alignedAxis = import__420.Cartesian3.UNIT_Z; b.width = 300; b.height = 200; b.scaleByDistance = new import__420.NearFarScalar(1e6, 3, 1e8, 0); b.translucencyByDistance = new import__420.NearFarScalar(1e6, 1, 1e8, 0); b.pixelOffsetScaleByDistance = new import__420.NearFarScalar(1e6, 3, 1e8, 0); b.sizeInMeters = true; b.distanceDisplayCondition = new import__420.DistanceDisplayCondition(10, 100); b.disableDepthTestDistance = 10; expect(b.show).toEqual(false); expect(b.position).toEqual(new import__420.Cartesian3(1, 2, 3)); expect(b.pixelOffset).toEqual(new import__420.Cartesian2(1, 2)); expect(b.eyeOffset).toEqual(new import__420.Cartesian3(1, 2, 3)); expect(b.horizontalOrigin).toEqual(import__420.HorizontalOrigin.LEFT); expect(b.verticalOrigin).toEqual(import__420.VerticalOrigin.BOTTOM); expect(b.scale).toEqual(2); expect(b.image).toEqual(b._imageId); expect(b.color.red).toEqual(1); expect(b.color.green).toEqual(2); expect(b.color.blue).toEqual(3); expect(b.color.alpha).toEqual(4); expect(b.rotation).toEqual(1); expect(b.alignedAxis).toEqual(import__420.Cartesian3.UNIT_Z); expect(b.scaleByDistance).toEqual( new import__420.NearFarScalar(1e6, 3, 1e8, 0) ); expect(b.translucencyByDistance).toEqual( new import__420.NearFarScalar(1e6, 1, 1e8, 0) ); expect(b.pixelOffsetScaleByDistance).toEqual( new import__420.NearFarScalar(1e6, 3, 1e8, 0) ); expect(b.width).toEqual(300); expect(b.height).toEqual(200); expect(b.sizeInMeters).toEqual(true); expect(b.distanceDisplayCondition).toEqual( new import__420.DistanceDisplayCondition(10, 100) ); expect(b.disableDepthTestDistance).toEqual(10); }); it("required properties throw for undefined", function() { const b = billboards.add(); b.show = false; b.position = new import__420.Cartesian3(1, 2, 3); b.pixelOffset = new import__420.Cartesian2(1, 2); b.eyeOffset = new import__420.Cartesian3(1, 2, 3); b.horizontalOrigin = import__420.HorizontalOrigin.LEFT; b.verticalOrigin = import__420.VerticalOrigin.BOTTOM; b.scale = 2; b.color = new import__420.Color(1, 2, 3, 4); b.rotation = 1; b.alignedAxis = import__420.Cartesian3.UNIT_Z; b.sizeInMeters = true; expect(function() { b.show = void 0; }).toThrowDeveloperError(); expect(function() { b.position = void 0; }).toThrowDeveloperError(); expect(function() { b.pixelOffset = void 0; }).toThrowDeveloperError(); expect(function() { b.eyeOffset = void 0; }).toThrowDeveloperError(); expect(function() { b.horizontalOrigin = void 0; }).toThrowDeveloperError(); expect(function() { b.verticalOrigin = void 0; }).toThrowDeveloperError(); expect(function() { b.scale = void 0; }).toThrowDeveloperError(); expect(function() { b.color = void 0; }).toThrowDeveloperError(); expect(function() { b.rotation = void 0; }).toThrowDeveloperError(); expect(function() { b.alignedAxis = void 0; }).toThrowDeveloperError(); expect(function() { b.sizeInMeters = void 0; }).toThrowDeveloperError(); }); it("optional properties handle undefined gracefully", function() { const b = billboards.add(); b.image = greenImage; b.width = 300; b.height = 200; b.scaleByDistance = new import__420.NearFarScalar(1e6, 3, 1e8, 0); b.translucencyByDistance = new import__420.NearFarScalar(1e6, 1, 1e8, 0); b.pixelOffsetScaleByDistance = new import__420.NearFarScalar(1e6, 3, 1e8, 0); b.distanceDisplayCondition = new import__420.DistanceDisplayCondition(10, 100); b.disableDepthTestDistance = 10; b.image = void 0; b.width = void 0; b.height = void 0; b.scaleByDistance = void 0; b.translucencyByDistance = void 0; b.pixelOffsetScaleByDistance = void 0; b.distanceDisplayCondition = void 0; b.disableDepthTestDistance = void 0; expect(b.image).not.toBeDefined(); expect(b.width).not.toBeDefined(); expect(b.height).not.toBeDefined(); expect(b.scaleByDistance).not.toBeDefined(); expect(b.translucencyByDistance).not.toBeDefined(); expect(b.pixelOffsetScaleByDistance).not.toBeDefined(); expect(b.distanceDisplayCondition).not.toBeDefined(); expect(b.disableDepthTestDistance).not.toBeDefined(); }); it("properties throw for incorrect types", function() { const b = billboards.add(); b.show = false; b.position = new import__420.Cartesian3(1, 2, 3); b.pixelOffset = new import__420.Cartesian2(1, 2); b.eyeOffset = new import__420.Cartesian3(1, 2, 3); b.horizontalOrigin = import__420.HorizontalOrigin.LEFT; b.verticalOrigin = import__420.VerticalOrigin.BOTTOM; b.scale = 2; b.color = new import__420.Color(1, 2, 3, 4); b.rotation = 1; b.alignedAxis = import__420.Cartesian3.UNIT_Z; b.width = 300; b.height = 200; b.scaleByDistance = new import__420.NearFarScalar(1e6, 3, 1e8, 0); b.translucencyByDistance = new import__420.NearFarScalar(1e6, 1, 1e8, 0); b.pixelOffsetScaleByDistance = new import__420.NearFarScalar(1e6, 3, 1e8, 0); b.sizeInMeters = true; b.distanceDisplayCondition = new import__420.DistanceDisplayCondition(10, 100); b.disableDepthTestDistance = 10; expect(function() { b.show = 10; }).toThrowDeveloperError(); expect(function() { b.position = 10; }).toThrowDeveloperError(); expect(function() { b.pixelOffset = 10; }).toThrowDeveloperError(); expect(function() { b.eyeOffset = 10; }).toThrowDeveloperError(); expect(function() { b.horizontalOrigin = "left"; }).toThrowDeveloperError(); expect(function() { b.verticalOrigin = "bottom"; }).toThrowDeveloperError(); expect(function() { b.scale = "scale"; }).toThrowDeveloperError(); expect(function() { b.color = 10; }).toThrowDeveloperError(); expect(function() { b.rotation = "rotation"; }).toThrowDeveloperError(); expect(function() { b.alignedAxis = 10; }).toThrowDeveloperError(); expect(function() { b.width = "100px"; }).toThrowDeveloperError(); expect(function() { b.height = "300px"; }).toThrowDeveloperError(); expect(function() { b.scaleByDistance = 10; }).toThrowDeveloperError(); expect(function() { b.translucencyByDistance = 10; }).toThrowDeveloperError(); expect(function() { b.pixelOffsetScaleByDistance = 10; }).toThrowDeveloperError(); expect(function() { b.sizeInMeters = 10; }).toThrowDeveloperError(); expect(function() { b.distanceDisplayCondition = 10; }).toThrowDeveloperError(); expect(function() { b.disableDepthTestDistance = "far"; }).toThrowDeveloperError(); }); it("image property setter creates image with GUID for non-uris", function() { const b = billboards.add(); b.image = 42; expect(b.image).not.toBe(42); const guidLength = 36; expect(b._imageId.length).toBe(guidLength); }); it("is not destroyed", function() { expect(billboards.isDestroyed()).toEqual(false); }); it("renders billboard in multiple passes", function() { const billboard = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); camera.position = new import__420.Cartesian3(2, 0, 0); scene2.renderForSpecs(); return pollToPromise_default(function() { return billboard.ready; }).then(function() { const frameState2 = scene2.frameState; frameState2.commandList.length = 0; billboards.blendOption = import__420.BlendOption.OPAQUE_AND_TRANSLUCENT; billboards.update(frameState2); expect(frameState2.commandList.length).toEqual(2); frameState2.commandList.length = 0; billboards.blendOption = import__420.BlendOption.OPAQUE; billboards.update(frameState2); expect(frameState2.commandList.length).toEqual(1); frameState2.commandList.length = 0; billboards.blendOption = import__420.BlendOption.TRANSLUCENT; billboards.update(frameState2); expect(frameState2.commandList.length).toEqual(1); }); }); it("renders billboard with sizeInMeters", function() { const billboard = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage, width: 2, height: 2, sizeInMeters: true }); scene2.renderForSpecs(); return pollToPromise_default(function() { return billboard.ready; }).then(function() { camera.position = new import__420.Cartesian3(2, 0, 0); expect(scene2).toRender([0, 255, 0, 255]); camera.position = new import__420.Cartesian3(1e6, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("disables billboard scaleByDistance", function() { const b = billboards.add({ scaleByDistance: new import__420.NearFarScalar(1, 3, 1e6, 0) }); b.scaleByDistance = void 0; expect(b.scaleByDistance).toBeUndefined(); }); it("disables billboard translucencyByDistance", function() { const b = billboards.add({ translucencyByDistance: new import__420.NearFarScalar(1, 1, 1e6, 0) }); b.translucencyByDistance = void 0; expect(b.translucencyByDistance).toBeUndefined(); }); it("disables billboard pixelOffsetScaleByDistance", function() { const b = billboards.add({ pixelOffsetScaleByDistance: new import__420.NearFarScalar(1, 1, 1e6, 0) }); b.pixelOffsetScaleByDistance = void 0; expect(b.pixelOffsetScaleByDistance).toBeUndefined(); }); it("renders billboard with scaleByDistance", function() { const billboard = billboards.add({ position: import__420.Cartesian3.ZERO, scaleByDistance: new import__420.NearFarScalar(2, 1, 4, 0), image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return billboard.ready; }).then(function() { camera.position = new import__420.Cartesian3(2, 0, 0); expect(scene2).toRender([0, 255, 0, 255]); camera.position = new import__420.Cartesian3(4, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("renders billboard with translucencyByDistance", function() { const billboard = billboards.add({ position: import__420.Cartesian3.ZERO, translucencyByDistance: new import__420.NearFarScalar(2, 1, 4, 0), image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return billboard.ready; }).then(function() { camera.position = new import__420.Cartesian3(2, 0, 0); expect(scene2).toRender([0, 255, 0, 255]); camera.position = new import__420.Cartesian3(4, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("renders billboard with pixelOffsetScaleByDistance", function() { const billboard = billboards.add({ position: import__420.Cartesian3.ZERO, pixelOffset: new import__420.Cartesian2(1, 0), pixelOffsetScaleByDistance: new import__420.NearFarScalar(2, 0, 4, 1e3), image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return billboard.ready; }).then(function() { camera.position = new import__420.Cartesian3(2, 0, 0); expect(scene2).toRender([0, 255, 0, 255]); camera.position = new import__420.Cartesian3(4, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("does not render billboard if show is false", function() { const billboard = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage, width: 2, height: 2, sizeInMeters: true }); scene2.renderForSpecs(); return pollToPromise_default(function() { return billboard.ready; }).then(function() { camera.position = new import__420.Cartesian3(2, 0, 0); expect(scene2).toRender([0, 255, 0, 255]); billboards.show = false; expect(scene2).toRender([0, 0, 0, 255]); }); }); it("throws scaleByDistance with nearDistance === farDistance", function() { const b = billboards.add(); const scale = new import__420.NearFarScalar(2e5, 1, 2e5, 0); expect(function() { b.scaleByDistance = scale; }).toThrowDeveloperError(); }); it("throws new billboard with invalid scaleByDistance (nearDistance === farDistance)", function() { const scale = new import__420.NearFarScalar(2e5, 1, 2e5, 0); expect(function() { billboards.add({ scaleByDistance: scale }); }).toThrowDeveloperError(); }); it("throws scaleByDistance with nearDistance > farDistance", function() { const b = billboards.add(); const scale = new import__420.NearFarScalar(1e9, 1, 1e5, 1); expect(function() { b.scaleByDistance = scale; }).toThrowDeveloperError(); }); it("throws pixelOffsetScaleByDistance with nearDistance === farDistance", function() { const b = billboards.add(); const scale = new import__420.NearFarScalar(2e5, 1, 2e5, 0); expect(function() { b.pixelOffsetScaleByDistance = scale; }).toThrowDeveloperError(); }); it("throws new billboard with invalid pixelOffsetScaleByDistance (nearDistance === farDistance)", function() { const scale = new import__420.NearFarScalar(2e5, 1, 2e5, 0); expect(function() { billboards.add({ pixelOffsetScaleByDistance: scale }); }).toThrowDeveloperError(); }); it("throws pixelOffsetScaleByDistance with nearDistance > farDistance", function() { const b = billboards.add(); const scale = new import__420.NearFarScalar(1e9, 1, 1e5, 1); expect(function() { b.pixelOffsetScaleByDistance = scale; }).toThrowDeveloperError(); }); it("throws translucencyByDistance with nearDistance === farDistance", function() { const b = billboards.add(); const translucency = new import__420.NearFarScalar(2e5, 1, 2e5, 0); expect(function() { b.translucencyByDistance = translucency; }).toThrowDeveloperError(); }); it("throws new billboard with invalid translucencyByDistance (nearDistance === farDistance)", function() { const translucency = new import__420.NearFarScalar(2e5, 1, 2e5, 0); expect(function() { billboards.add({ translucencyByDistance: translucency }); }).toThrowDeveloperError(); }); it("throws translucencyByDistance with nearDistance > farDistance", function() { const b = billboards.add(); const translucency = new import__420.NearFarScalar(1e9, 1, 1e5, 1); expect(function() { b.translucencyByDistance = translucency; }).toThrowDeveloperError(); }); it("renders billboard with distanceDisplayCondition", function() { const billboard = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage, distanceDisplayCondition: new import__420.DistanceDisplayCondition(10, 100) }); scene2.renderForSpecs(); return pollToPromise_default(function() { return billboard.ready; }).then(function() { camera.position = new import__420.Cartesian3(200, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); camera.position = new import__420.Cartesian3(50, 0, 0); expect(scene2).toRender([0, 255, 0, 255]); camera.position = new import__420.Cartesian3(5, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("throws new billboard with invalid distanceDisplayCondition (near >= far)", function() { const dc = new import__420.DistanceDisplayCondition(100, 10); expect(function() { billboards.add({ distanceDisplayCondition: dc }); }).toThrowDeveloperError(); }); it("throws distanceDisplayCondition with near >= far", function() { const b = billboards.add(); const dc = new import__420.DistanceDisplayCondition(100, 10); expect(function() { b.distanceDisplayCondition = dc; }).toThrowDeveloperError(); }); it("renders with disableDepthTestDistance", function() { const b = billboards.add({ position: new import__420.Cartesian3(-1, 0, 0), image: greenImage }); const blue = billboards.add({ position: import__420.Cartesian3.ZERO, image: blueImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready && blue.ready; }).then(function() { expect(scene2).toRender([0, 0, 255, 255]); b.disableDepthTestDistance = Number.POSITIVE_INFINITY; expect(scene2).toRender([0, 255, 0, 255]); }); }); it("throws with new billboard with disableDepthTestDistance less than 0.0", function() { expect(function() { billboards.add({ disableDepthTestDistance: -1 }); }).toThrowDeveloperError(); }); it("throws with disableDepthTestDistance set less than 0.0", function() { const b = billboards.add(); expect(function() { b.disableDepthTestDistance = -1; }).toThrowDeveloperError(); }); it("sets a removed billboard property", function() { const b = billboards.add(); billboards.remove(b); b.show = false; expect(b.show).toEqual(false); }); it("has zero billboards when constructed", function() { expect(billboards.length).toEqual(0); }); it("adds a billboard", function() { const b = billboards.add({ position: new import__420.Cartesian3(1, 2, 3) }); expect(billboards.length).toEqual(1); expect(billboards.get(0)).toEqual(b); }); it("removes the first billboard", function() { const one = billboards.add({ position: new import__420.Cartesian3(1, 2, 3) }); const two = billboards.add({ position: new import__420.Cartesian3(4, 5, 6) }); expect(billboards.length).toEqual(2); expect(billboards.remove(one)).toEqual(true); expect(billboards.length).toEqual(1); expect(billboards.get(0)).toEqual(two); }); it("removes the last billboard", function() { const one = billboards.add({ position: new import__420.Cartesian3(1, 2, 3) }); const two = billboards.add({ position: new import__420.Cartesian3(4, 5, 6) }); expect(billboards.length).toEqual(2); expect(billboards.remove(two)).toEqual(true); expect(billboards.length).toEqual(1); expect(billboards.get(0)).toEqual(one); }); it("removes the same billboard twice", function() { const b = billboards.add({ position: new import__420.Cartesian3(1, 2, 3) }); expect(billboards.length).toEqual(1); expect(billboards.remove(b)).toEqual(true); expect(billboards.length).toEqual(0); expect(billboards.remove(b)).toEqual(false); expect(billboards.length).toEqual(0); }); it("returns false when removing undefined", function() { billboards.add({ position: new import__420.Cartesian3(1, 2, 3) }); expect(billboards.length).toEqual(1); expect(billboards.remove(void 0)).toEqual(false); expect(billboards.length).toEqual(1); }); it("adds and removes billboards", function() { const one = billboards.add({ position: new import__420.Cartesian3(1, 2, 3) }); const two = billboards.add({ position: new import__420.Cartesian3(4, 5, 6) }); expect(billboards.length).toEqual(2); expect(billboards.get(0)).toEqual(one); expect(billboards.get(1)).toEqual(two); expect(billboards.remove(two)).toEqual(true); const three = billboards.add({ position: new import__420.Cartesian3(7, 8, 9) }); expect(billboards.length).toEqual(2); expect(billboards.get(0)).toEqual(one); expect(billboards.get(1)).toEqual(three); }); it("removes all billboards", function() { billboards.add({ position: new import__420.Cartesian3(1, 2, 3) }); billboards.add({ position: new import__420.Cartesian3(4, 5, 6) }); expect(billboards.length).toEqual(2); billboards.removeAll(); expect(billboards.length).toEqual(0); }); it("can check if it contains a billboard", function() { const billboard = billboards.add(); expect(billboards.contains(billboard)).toEqual(true); }); it("returns false when checking if it contains a billboard it does not contain", function() { const billboard = billboards.add(); billboards.remove(billboard); expect(billboards.contains(billboard)).toEqual(false); }); it("does not contain undefined", function() { expect(billboards.contains(void 0)).toEqual(false); }); it("does not contain random other objects", function() { expect(billboards.contains({})).toEqual(false); expect(billboards.contains(new import__420.Cartesian2())).toEqual(false); }); it("sets and gets a texture atlas", function() { expect(billboards.textureAtlas).toBeUndefined(); const atlas = new import__420.TextureAtlas({ context: scene2.context }); billboards.textureAtlas = atlas; expect(billboards.textureAtlas).toEqual(atlas); }); it("destroys a texture atlas", function() { let b = new import__420.BillboardCollection(); expect(b.destroyTextureAtlas).toEqual(true); const atlas = new import__420.TextureAtlas({ context: scene2.context }); b.textureAtlas = atlas; b = b.destroy(); expect(atlas.isDestroyed()).toEqual(true); }); it("does not destroy a texture atlas", function() { let b = new import__420.BillboardCollection(); b.destroyTextureAtlas = false; const atlas = new import__420.TextureAtlas({ context: scene2.context }); b.rextureAtlas = atlas; b = b.destroy(); expect(atlas.isDestroyed()).toEqual(false); }); it("does not render when constructed", function() { expect(scene2).toRender([0, 0, 0, 255]); }); it("modifies and removes a billboard, then renders", function() { const b1 = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); const b2 = billboards.add({ position: new import__420.Cartesian3(-1, 0, 0), image: largeBlueImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b1.ready && b2.ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); b1.scale = 2; billboards.remove(b1); expect(scene2).toRender([0, 0, 255, 255]); }); }); it("renders a green billboard", function() { const billboard = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return billboard.ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); }); }); it("adds and renders a billboard", function() { const billboard = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return billboard.ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); const b2 = billboards.add({ position: new import__420.Cartesian3(1, 0, 0), // Closer to camera image: largeBlueImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b2.ready; }); }).then(function() { expect(scene2).toRender([0, 0, 255, 255]); }); }); it("removes and renders a billboard", function() { const greenBillboard = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); const blueBillboard = billboards.add({ position: new import__420.Cartesian3(1, 0, 0), // Closer to camera image: largeBlueImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return greenBillboard.ready && blueBillboard.ready; }).then(function() { expect(scene2).toRender([0, 0, 255, 255]); billboards.remove(blueBillboard); expect(scene2).toRender([0, 255, 0, 255]); }); }); it("removes all billboards and renders", function() { const billboard = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return billboard.ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); billboards.removeAll(); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("removes all billboards, adds a billboard, and renders", function() { let billboard = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return billboard.ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); billboards.removeAll(); billboard = billboards.add({ position: import__420.Cartesian3.ZERO, image: largeBlueImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return billboard.ready; }); }).then(function() { expect(scene2).toRender([0, 0, 255, 255]); }); }); it("renders with a different texture atlas", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); billboards.textureAtlas = new import__420.TextureAtlas({ context: scene2.context }); b.image = blueImage; scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }); }).then(function() { expect(scene2).toRender([0, 0, 255, 255]); }); }); it("renders using billboard show property", function() { const greenBillboard = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); const blueBillboard = billboards.add({ show: false, position: import__420.Cartesian3.ZERO, image: largeBlueImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return greenBillboard.ready && blueBillboard.ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); greenBillboard.show = false; blueBillboard.show = true; expect(scene2).toRender([0, 0, 255, 255]); }); }); it("renders using billboard position property", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); b.position = new import__420.Cartesian3(20, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); b.position = new import__420.Cartesian3(1, 0, 0); expect(scene2).toRender([0, 255, 0, 255]); }); }); it("renders using billboard scale property", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); b.scale = 0; expect(scene2).toRender([0, 0, 0, 255]); b.scale = 2; expect(scene2).toRender([0, 255, 0, 255]); }); }); it("renders using billboard image property", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); b.image = largeBlueImage; scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }); }).then(function() { expect(scene2).toRender([0, 0, 255, 255]); }); }); it("renders using billboard setImage function", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); b.setImage((0, import__420.createGuid)(), largeBlueImage); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }); }).then(function() { expect(scene2).toRender([0, 0, 255, 255]); }); }); it("renders using billboard setImageSubRegion function", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); const guid = (0, import__420.createGuid)(); billboards.textureAtlas.addImage(guid, largeBlueImage); b.setImageSubRegion(guid, new import__420.BoundingRectangle(5, 5, 1, 1)); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }); }).then(function() { expect(scene2).toRender([0, 0, 255, 255]); }); }); it("renders using billboard color property", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: whiteImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { expect(scene2).toRender([255, 255, 255, 255]); b.color = new import__420.Color(1, 0, 1, 1); expect(scene2).toRender([255, 0, 255, 255]); b.color = new import__420.Color(0, 1, 0, 1); expect(scene2).toRender([0, 255, 0, 255]); }); }); it("renders using billboard rotation property", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { b.rotation = import__421.Math.PI_OVER_TWO; expect(scene2).toRender([0, 255, 0, 255]); }); }); it("renders using billboard aligned axis property", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { b.alignedAxis = import__420.Cartesian3.UNIT_X; expect(scene2).toRender([0, 255, 0, 255]); }); }); it("renders using billboard custom width property", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { b.width = 300; expect(scene2).toRender([0, 255, 0, 255]); }); }); it("renders using billboard custom height property", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { b.height = 300; expect(scene2).toRender([0, 255, 0, 255]); }); }); it("renders bounding volume with debugShowBoundingVolume", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage, scale: 0.5 // bring bounding volume in view }); billboards.debugShowBoundingVolume = true; scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { expect(scene2).notToRender([0, 0, 0, 255]); }); }); it("renders billboards when instancing is disabled", function() { const instancedArrays = context._instancedArrays; context._instancedArrays = void 0; expect(scene2).toRender([0, 0, 0, 255]); const b1 = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); scene2.renderForSpecs(); let b2; return pollToPromise_default(function() { return b1.ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); b2 = billboards.add({ position: new import__420.Cartesian3(1, 0, 0), // Closer to camera image: largeBlueImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b2.ready; }); }).then(function() { expect(scene2).toRender([0, 0, 255, 255]); billboards.remove(b2); expect(scene2).toRender([0, 255, 0, 255]); billboards.remove(b1); expect(scene2).toRender([0, 0, 0, 255]); context._instancedArrays = instancedArrays; }); }); it("updates 10% of billboards", function() { for (let i = 0; i < 10; ++i) { billboards.add({ position: import__420.Cartesian3.ZERO, image: whiteImage, show: i === 3 }); } scene2.renderForSpecs(); return pollToPromise_default(function() { return billboards.get(3).ready; }).then(function() { expect(scene2).toRender([255, 255, 255, 255]); billboards.get(3).color = new import__420.Color(0, 1, 0, 1); expect(scene2).toRender([0, 255, 0, 255]); billboards.get(3).color = new import__420.Color(1, 0, 0, 1); expect(scene2).toRender([255, 0, 0, 255]); }); }); it("renders more than 16K billboards", function() { for (let i = 0; i < 16 * 1024; ++i) { billboards.add({ position: import__420.Cartesian3.ZERO, image: whiteImage, color: { alpha: 0 } }); } const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: whiteImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { expect(scene2).toRender([255, 255, 255, 255]); }); }); it("is picked", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: whiteImage, id: "id" }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toEqual(b); expect(result.id).toEqual("id"); }); }); }); it("can change pick id", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: whiteImage, id: "id" }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toEqual(b); expect(result.id).toEqual("id"); }); b.id = "id2"; expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toEqual(b); expect(result.id).toEqual("id2"); }); }); }); it("is not picked", function() { const b = billboards.add({ show: false, position: import__420.Cartesian3.ZERO, image: whiteImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { expect(scene2).notToPick(); }); }); it("picks a billboard using scaleByDistance", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: whiteImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { const scaleByDistance = new import__420.NearFarScalar(1, 4, 3e9, 2); b.scaleByDistance = scaleByDistance; expect(scene2).toPickPrimitive(b); scaleByDistance.nearValue = 0; scaleByDistance.farValue = 0; b.scaleByDistance = scaleByDistance; expect(scene2).notToPick(); }); }); it("picks a billboard using translucencyByDistance", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: whiteImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { const translucency = new import__420.NearFarScalar(1, 0.9, 3e9, 0.8); b.translucencyByDistance = translucency; expect(scene2).toPickPrimitive(b); translucency.nearValue = 0; translucency.farValue = 0; b.translucencyByDistance = translucency; expect(scene2).notToPick(); }); }); it("picks a billboard using pixelOffsetScaleByDistance", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, pixelOffset: new import__420.Cartesian2(0, 100), image: whiteImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { const pixelOffsetScale = new import__420.NearFarScalar(1, 0, 3e9, 0); b.pixelOffsetScaleByDistance = pixelOffsetScale; expect(scene2).toPickPrimitive(b); pixelOffsetScale.nearValue = 10; pixelOffsetScale.farValue = 10; b.pixelOffsetScaleByDistance = pixelOffsetScale; expect(scene2).notToPick(); }); }); it("can pick a billboard using the rotation property", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { b.rotation = import__421.Math.PI_OVER_TWO; expect(scene2).toPickPrimitive(b); }); }); it("can pick a billboard using the aligned axis property", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, image: greenImage }); scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { b.alignedAxis = import__420.Cartesian3.UNIT_X; expect(scene2).toPickPrimitive(b); }); }); it("computes screen space position", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO }); scene2.renderForSpecs(); expect(b.computeScreenSpacePosition(scene2)).toEqualEpsilon( new import__420.Cartesian2(0.5, 0.5), import__421.Math.EPSILON1 ); }); it("stores screen space position in a result", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO }); const result = new import__420.Cartesian2(); scene2.renderForSpecs(); const actual = b.computeScreenSpacePosition(scene2, result); expect(actual).toEqual(result); expect(result).toEqualEpsilon( new import__420.Cartesian2(0.5, 0.5), import__421.Math.EPSILON1 ); }); it("computes screen space position with pixelOffset", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, pixelOffset: new import__420.Cartesian2(0.5, 0.5) }); scene2.renderForSpecs(); expect(b.computeScreenSpacePosition(scene2)).toEqualEpsilon( new import__420.Cartesian2(1, 1), import__421.Math.EPSILON1 ); }); it("computes screen space position with eyeOffset", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO, eyeOffset: new import__420.Cartesian3(1, 1, 0) }); scene2.renderForSpecs(); expect(b.computeScreenSpacePosition(scene2)).toEqualEpsilon( new import__420.Cartesian2(0.5, 0.5), import__421.Math.EPSILON1 ); }); it("computes screen space position in Columbus view", function() { const b = billboards.add({ position: import__420.Cartesian3.fromDegrees(0, 0, 10) }); scene2.morphToColumbusView(0); scene2.camera.setView({ destination: import__420.Rectangle.MAX_VALUE }); scene2.renderForSpecs(); expect(b.computeScreenSpacePosition(scene2)).toEqualEpsilon( new import__420.Cartesian2(0.5, 0.5), import__421.Math.EPSILON1 ); }); it("computes screen space position in 2D", function() { const b = billboards.add({ position: import__420.Cartesian3.fromDegrees(0, 0, 10) }); scene2.morphTo2D(0); scene2.camera.setView({ destination: import__420.Rectangle.MAX_VALUE }); scene2.renderForSpecs(); expect(b.computeScreenSpacePosition(scene2)).toEqualEpsilon( new import__420.Cartesian2(0.5, 0.5), import__421.Math.EPSILON1 ); }); it("throws when computing screen space position when not in a collection", function() { const b = billboards.add({ position: import__420.Cartesian3.ZERO }); billboards.remove(b); expect(function() { b.computeScreenSpacePosition(scene2); }).toThrowDeveloperError(); }); it("throws when computing screen space position without scene", function() { const b = billboards.add(); expect(function() { b.computeScreenSpacePosition(); }).toThrowDeveloperError(); }); it("computes screen space bounding box", function() { let width = 10; let height = 15; const scale = 1.5; const b = billboards.add({ width, height, scale }); const halfWidth = width * scale * 0.5; const halfHeight = height * scale * 0.5; width = width * scale; height = height * scale; const bbox = import__420.Billboard.getScreenSpaceBoundingBox(b, import__420.Cartesian2.ZERO); expect(bbox.x).toEqual(-halfWidth); expect(bbox.y).toEqual(-halfHeight); expect(bbox.width).toEqual(width); expect(bbox.height).toEqual(height); }); it("computes screen space bounding box with result", function() { let width = 10; let height = 15; const scale = 1.5; const b = billboards.add({ width, height, scale }); const halfWidth = width * scale * 0.5; const halfHeight = height * scale * 0.5; width = width * scale; height = height * scale; const result = new import__420.BoundingRectangle(); const bbox = import__420.Billboard.getScreenSpaceBoundingBox( b, import__420.Cartesian2.ZERO, result ); expect(bbox.x).toEqual(-halfWidth); expect(bbox.y).toEqual(-halfHeight); expect(bbox.width).toEqual(width); expect(bbox.height).toEqual(height); expect(bbox).toBe(result); }); it("computes screen space bounding box with vertical origin", function() { let width = 10; let height = 15; const scale = 1.5; const b = billboards.add({ width, height, scale, verticalOrigin: import__420.VerticalOrigin.BOTTOM }); const halfWidth = width * scale * 0.5; width = width * scale; height = height * scale; let bbox = import__420.Billboard.getScreenSpaceBoundingBox(b, import__420.Cartesian2.ZERO); expect(bbox.x).toEqual(-halfWidth); expect(bbox.y).toEqual(-height); expect(bbox.width).toEqual(width); expect(bbox.height).toEqual(height); b.verticalOrigin = import__420.VerticalOrigin.TOP; bbox = import__420.Billboard.getScreenSpaceBoundingBox(b, import__420.Cartesian2.ZERO); expect(bbox.x).toEqual(-halfWidth); expect(bbox.y).toEqual(0); expect(bbox.width).toEqual(width); expect(bbox.height).toEqual(height); }); it("computes screen space bounding box with horizontal origin", function() { let width = 10; let height = 15; const scale = 1.5; const b = billboards.add({ width, height, scale, horizontalOrigin: import__420.HorizontalOrigin.LEFT }); const halfHeight = height * scale * 0.5; height = height * scale; width = width * scale; let bbox = import__420.Billboard.getScreenSpaceBoundingBox(b, import__420.Cartesian2.ZERO); expect(bbox.x).toEqual(0); expect(bbox.y).toEqual(-halfHeight); expect(bbox.width).toEqual(width); expect(bbox.height).toEqual(height); b.horizontalOrigin = import__420.HorizontalOrigin.RIGHT; bbox = import__420.Billboard.getScreenSpaceBoundingBox(b, import__420.Cartesian2.ZERO); expect(bbox.x).toEqual(-width); expect(bbox.y).toEqual(-halfHeight); expect(bbox.width).toEqual(width); expect(bbox.height).toEqual(height); }); it("equals another billboard", function() { const b = billboards.add({ position: new import__420.Cartesian3(1, 2, 3), color: { red: 1, green: 0, blue: 0, alpha: 1 } }); const b2 = billboards.add({ position: new import__420.Cartesian3(1, 2, 3), color: { red: 1, green: 0, blue: 0, alpha: 1 } }); expect(b.equals(b2)).toEqual(true); }); it("does not equal another billboard", function() { const b = billboards.add({ position: new import__420.Cartesian3(1, 2, 3) }); const b2 = billboards.add({ position: new import__420.Cartesian3(4, 5, 6) }); expect(b.equals(b2)).toEqual(false); }); it("does not equal undefined", function() { const billboard = billboards.add(); expect(billboard.equals(void 0)).toEqual(false); }); it("throws when accessing without an index", function() { expect(function() { billboards.get(); }).toThrowDeveloperError(); }); it("setImage throws without an id", function() { const b = billboards.add(); expect(function() { b.setImage(void 0, {}); }).toThrowDeveloperError(); }); it("setImage throws without an inmage", function() { const b = billboards.add(); expect(function() { b.setImage("", void 0); }).toThrowDeveloperError(); }); it("setImageSubRegion throws without an id", function() { const b = billboards.add(); expect(function() { b.setImage(void 0, {}); }).toThrowDeveloperError(); }); it("setImageSubRegion throws without a sub-region", function() { const b = billboards.add(); expect(function() { b.setImage("", void 0); }).toThrowDeveloperError(); }); it("computes bounding sphere in 3D", function() { const one = billboards.add({ image: greenImage, position: import__420.Cartesian3.fromDegrees(-50, -50) }); const two = billboards.add({ image: greenImage, position: import__420.Cartesian3.fromDegrees(-50, 50) }); scene2.renderForSpecs(); return pollToPromise_default(function() { return one.ready && two.ready; }).then(function() { billboards.update(scene2.frameState); const actual = scene2.frameState.commandList[0].boundingVolume; const positions = [one.position, two.position]; const expected = import__420.BoundingSphere.fromPoints(positions); expect(actual.center).toEqual(expected.center); expect(actual.radius).toEqual(expected.radius); }); }); it("computes bounding sphere in Columbus view", function() { const projection = scene2.mapProjection; const ellipsoid = projection.ellipsoid; const one = billboards.add({ image: greenImage, position: import__420.Cartesian3.fromDegrees(-50, -50) }); const two = billboards.add({ image: greenImage, position: import__420.Cartesian3.fromDegrees(-50, 50) }); scene2.morphToColumbusView(0); scene2.renderForSpecs(); return pollToPromise_default(function() { return one.ready && two.ready; }).then(function() { billboards.update(scene2.frameState); const actual = scene2.frameState.commandList[0].boundingVolume; const projectedPositions = [ projection.project(ellipsoid.cartesianToCartographic(one.position)), projection.project(ellipsoid.cartesianToCartographic(two.position)) ]; const expected = import__420.BoundingSphere.fromPoints(projectedPositions); expected.center = new import__420.Cartesian3( 0, expected.center.x, expected.center.y ); expect(actual.center).toEqualEpsilon( expected.center, import__421.Math.EPSILON8 ); expect(actual.radius).toBeGreaterThanOrEqual(expected.radius); }); }); it("computes bounding sphere in 2D", function() { const projection = scene2.mapProjection; const ellipsoid = projection.ellipsoid; const one = billboards.add({ image: greenImage, position: import__420.Cartesian3.fromDegrees(-50, -50) }); const two = billboards.add({ image: greenImage, position: import__420.Cartesian3.fromDegrees(-50, 50) }); const maxRadii = ellipsoid.maximumRadius; const orthoFrustum = new import__420.OrthographicOffCenterFrustum(); orthoFrustum.right = maxRadii * Math.PI; orthoFrustum.left = -orthoFrustum.right; orthoFrustum.top = orthoFrustum.right; orthoFrustum.bottom = -orthoFrustum.top; orthoFrustum.near = 0.01 * maxRadii; orthoFrustum.far = 60 * maxRadii; camera.setView({ destination: import__420.Rectangle.fromDegrees(-60, -60, -40, 60) }); scene2.morphTo2D(0); scene2.renderForSpecs(); camera.frustum = orthoFrustum; return pollToPromise_default(function() { return one.ready && two.ready; }).then(function() { billboards.update(scene2.frameState); const actual = scene2.frameState.commandList[0].boundingVolume; const projectedPositions = [ projection.project(ellipsoid.cartesianToCartographic(one.position)), projection.project(ellipsoid.cartesianToCartographic(two.position)) ]; const expected = import__420.BoundingSphere.fromPoints(projectedPositions); expected.center = new import__420.Cartesian3( 0, expected.center.x, expected.center.y ); expect(actual.center).toEqualEpsilon( expected.center, import__421.Math.EPSILON8 ); expect(actual.radius).toBeGreaterThan(expected.radius); }); }); it("computes bounding sphere with pixel offset", function() { const one = billboards.add({ image: greenImage, position: import__420.Cartesian3.fromDegrees(-50, -50), pixelOffset: new import__420.Cartesian2(0, 200) }); const two = billboards.add({ image: greenImage, position: import__420.Cartesian3.fromDegrees(-50, 50), pixelOffset: new import__420.Cartesian2(0, 200) }); scene2.renderForSpecs(); return pollToPromise_default(function() { return one.ready && two.ready; }).then(function() { billboards.update(scene2.frameState); const actual = scene2.frameState.commandList[0].boundingVolume; const positions = [one.position, two.position]; const bs = import__420.BoundingSphere.fromPoints(positions); const dimensions = new import__420.Cartesian2(1, 1); const diff = import__420.Cartesian3.subtract( actual.center, camera.position, new import__420.Cartesian3() ); const vectorProjection = import__420.Cartesian3.multiplyByScalar( camera.direction, import__420.Cartesian3.dot(diff, camera.direction), new import__420.Cartesian3() ); const distance = Math.max( 0, import__420.Cartesian3.magnitude(vectorProjection) - bs.radius ); const pixelSize = camera.frustum.getPixelDimensions( dimensions.x, dimensions.y, distance, scene2.pixelRatio, new import__420.Cartesian2() ); bs.radius += pixelSize.y * 0.25 * Math.max(greenImage.width, greenImage.height) + pixelSize.y * one.pixelOffset.y; expect(actual.center).toEqual(bs.center); expect(actual.radius).toEqual(bs.radius); }); }); it("computes bounding sphere with non-centered origin", function() { let b = billboards.add({ image: greenImage, position: import__420.Cartesian3.fromDegrees(-50, -50) }); let centeredRadius, verticalRadius; scene2.renderForSpecs(); return pollToPromise_default(function() { return b.ready; }).then(function() { billboards.update(scene2.frameState); centeredRadius = scene2.frameState.commandList[0].boundingVolume.radius; billboards.removeAll(); b = billboards.add({ image: greenImage, position: import__420.Cartesian3.fromDegrees(-50, -50), verticalOrigin: import__420.VerticalOrigin.TOP }); return pollToPromise_default(function() { return b.ready; }); }).then(function() { billboards.update(scene2.frameState); verticalRadius = scene2.frameState.commandList[0].boundingVolume.radius; billboards.removeAll(); b = billboards.add({ image: greenImage, position: import__420.Cartesian3.fromDegrees(-50, -50), horizontalOrigin: import__420.HorizontalOrigin.LEFT }); return pollToPromise_default(function() { return b.ready; }); }).then(function() { billboards.update(scene2.frameState); const horizontalRadius = scene2.frameState.commandList[0].boundingVolume.radius; expect(verticalRadius).toEqual(2 * centeredRadius); expect(horizontalRadius).toEqual(2 * centeredRadius); }); }); it("can create a billboard using a URL", function() { scene2.renderForSpecs(); const one = billboards.add({ image: "./Data/Images/Green2x2.png" }); expect(one.ready).toEqual(false); expect(one.image).toEqual("./Data/Images/Green2x2.png"); return pollToPromise_default(function() { return one.ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); }); }); it("sets billboard width and height based on loaded image width and height", function() { scene2.renderForSpecs(); const one = billboards.add({ image: "./Data/Images/Green1x4.png" }); expect(one.width).toBeUndefined(); expect(one.height).toBeUndefined(); return pollToPromise_default(function() { return one.ready; }).then(function() { expect(one.width).toEqual(1); expect(one.height).toEqual(4); one.image = "./Data/Images/Blue10x10.png"; return pollToPromise_default(function() { return one.ready; }).then(function() { expect(one.width).toEqual(10); expect(one.height).toEqual(10); }); }); }); it("does not cancel image load when a billboard is set to the same URL repeatedly", function() { scene2.renderForSpecs(); const one = billboards.add({ image: "./Data/Images/Green.png" }); expect(one.ready).toEqual(false); expect(one.image).toEqual("./Data/Images/Green.png"); one.image = "./Data/Images/Green.png"; one.image = "./Data/Images/Green.png"; one.image = "./Data/Images/Green.png"; return pollToPromise_default(function() { return one.ready; }); }); it("ignores calls to set image equal to the current value after load", function() { scene2.renderForSpecs(); const one = billboards.add({ image: "./Data/Images/Green2x2.png" }); expect(one.ready).toEqual(false); expect(one.image).toEqual("./Data/Images/Green2x2.png"); return pollToPromise_default(function() { return one.ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); one.image = "./Data/Images/Green2x2.png"; expect(one.ready).toEqual(true); expect(scene2).toRender([0, 255, 0, 255]); }); }); it("can create a billboard using a function", function() { const one = billboards.add({ image: function() { return greenImage; } }); expect(one.image).toBeDefined(); scene2.renderForSpecs(); return pollToPromise_default(function() { return one.ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); }); }); it("can create a billboard using a function and id", function() { const one = billboards.add({ imageId: "Foo", image: function() { return greenImage; } }); scene2.renderForSpecs(); return pollToPromise_default(function() { return one.ready; }).then(function() { expect(one.image).toEqual("Foo"); expect(scene2).toRender([0, 255, 0, 255]); }); }); it("can create a billboard using another billboard image", function() { const createImage = jasmine.createSpy("createImage").and.returnValue(greenImage); const one = billboards.add({ image: createImage }); let two; scene2.renderForSpecs(); return pollToPromise_default(function() { return one.ready; }).then(function() { expect(createImage.calls.count()).toEqual(1); two = billboards.add({ image: one.image }); scene2.renderForSpecs(); return pollToPromise_default(function() { return one.ready; }); }).then(function() { expect(two.image).toEqual(one.image); expect(createImage.calls.count()).toEqual(1); expect(scene2).toRender([0, 255, 0, 255]); }); }); it("can create a billboard using a subregion of an image", function() { scene2.renderForSpecs(); const one = billboards.add({ image: "./Data/Images/Red16x16.png", imageSubRegion: new import__420.BoundingRectangle(0, 0, 2, 3) }); expect(one.ready).toEqual(false); return pollToPromise_default(function() { return one.ready; }).then(function() { expect(scene2).toRender([255, 0, 0, 255]); }); }); it("sets billboard width and height based on subregion width and height", function() { scene2.renderForSpecs(); const one = billboards.add({ image: "./Data/Images/Red16x16.png", imageSubRegion: new import__420.BoundingRectangle(0, 0, 1, 2) }); expect(one.width).toBeUndefined(); expect(one.height).toBeUndefined(); return pollToPromise_default(function() { return one.ready; }).then(function() { expect(one.width).toEqual(1); expect(one.height).toEqual(2); }); }); it("can change image while an image is loading", function() { scene2.renderForSpecs(); const one = billboards.add({ image: "./Data/Images/Green.png" }); expect(one.ready).toEqual(false); expect(one.image).toEqual("./Data/Images/Green.png"); one.image = "./Data/Images/Blue10x10.png"; expect(one.ready).toEqual(false); expect(one.image).toEqual("./Data/Images/Blue10x10.png"); return pollToPromise_default(function() { return one.ready; }).then(function() { return new Promise((resolve) => { let iterations = 10; function renderAndCheck() { expect(scene2).toRender([0, 0, 255, 255]); if (iterations > 0) { --iterations; setTimeout(renderAndCheck, 1); } else { resolve(); } } renderAndCheck(); }); }); }); it("can set image to undefined while an image is loading", function() { scene2.renderForSpecs(); const one = billboards.add({ image: "./Data/Images/Green.png" }); expect(one.ready).toEqual(false); expect(one.image).toEqual("./Data/Images/Green.png"); one.image = void 0; expect(one.ready).toEqual(false); expect(one.image).toBeUndefined(); return new Promise((resolve) => { let iterations = 10; function renderAndCheck() { expect(scene2).toRender([0, 0, 0, 255]); if (iterations > 0) { --iterations; setTimeout(renderAndCheck, 1); } else { resolve(); } } renderAndCheck(); }); }); it("does not crash when removing a billboard that is loading", function() { scene2.renderForSpecs(); const one = billboards.add({ image: "./Data/Images/Green.png" }); billboards.remove(one); return new Promise((resolve) => { let iterations = 10; function renderAndCheck() { expect(scene2).toRender([0, 0, 0, 255]); if (iterations > 0) { --iterations; setTimeout(renderAndCheck, 1); } else { resolve(); } } renderAndCheck(); }); }); it("can add a billboard without a globe", function() { scene2.globe = void 0; const billboardsWithoutGlobe = new import__420.BillboardCollection({ scene: scene2 }); const position = import__420.Cartesian3.fromDegrees(-73, 40); const b = billboardsWithoutGlobe.add({ position }); scene2.renderForSpecs(); expect(b.position).toEqual(position); expect(b._actualClampedPosition).toBeUndefined(); }); describe("height referenced billboards", function() { let billboardsWithHeight; beforeEach(function() { scene2.globe = new import__420.Globe(); billboardsWithHeight = new import__420.BillboardCollection({ scene: scene2 }); scene2.primitives.add(billboardsWithHeight); }); it("explicitly constructs a billboard with height reference", function() { const b = billboardsWithHeight.add({ heightReference: import__420.HeightReference.CLAMP_TO_GROUND }); expect(b.heightReference).toEqual(import__420.HeightReference.CLAMP_TO_GROUND); }); it("set billboard height reference property", function() { const b = billboardsWithHeight.add(); b.heightReference = import__420.HeightReference.CLAMP_TO_GROUND; expect(b.heightReference).toEqual(import__420.HeightReference.CLAMP_TO_GROUND); }); it("creating with a height reference creates a height update callback", function() { spyOn(scene2, "updateHeight"); const position = import__420.Cartesian3.fromDegrees(-72, 40); billboardsWithHeight.add({ heightReference: import__420.HeightReference.CLAMP_TO_GROUND, position }); expect(scene2.updateHeight).toHaveBeenCalledWith( import__420.Cartographic.fromCartesian(position), jasmine.any(Function), import__420.HeightReference.CLAMP_TO_GROUND ); }); it("set height reference property creates a height update callback", function() { spyOn(scene2, "updateHeight"); const position = import__420.Cartesian3.fromDegrees(-72, 40); const b = billboardsWithHeight.add({ position }); b.heightReference = import__420.HeightReference.CLAMP_TO_GROUND; expect(scene2.updateHeight).toHaveBeenCalledWith( import__420.Cartographic.fromCartesian(position), jasmine.any(Function), import__420.HeightReference.CLAMP_TO_GROUND ); }); it("updates the callback when the height reference changes", function() { spyOn(scene2, "updateHeight"); const position = import__420.Cartesian3.fromDegrees(-72, 40); const b = billboardsWithHeight.add({ heightReference: import__420.HeightReference.CLAMP_TO_GROUND, position }); expect(scene2.updateHeight).toHaveBeenCalledWith( import__420.Cartographic.fromCartesian(position), jasmine.any(Function), import__420.HeightReference.CLAMP_TO_GROUND ); b.heightReference = import__420.HeightReference.RELATIVE_TO_GROUND; expect(scene2.updateHeight).toHaveBeenCalledWith( import__420.Cartographic.fromCartesian(position), jasmine.any(Function), import__420.HeightReference.RELATIVE_TO_GROUND ); }); it("removes the callback when the height reference changes", function() { const removeCallback = jasmine.createSpy(); spyOn(scene2, "updateHeight").and.returnValue(removeCallback); const position = import__420.Cartesian3.fromDegrees(-72, 40); const b = billboardsWithHeight.add({ heightReference: import__420.HeightReference.CLAMP_TO_GROUND, position }); b.heightReference = import__420.HeightReference.NONE; expect(removeCallback).toHaveBeenCalled(); }); it("changing the position updates the callback", function() { const removeCallback = jasmine.createSpy(); spyOn(scene2, "updateHeight").and.returnValue(removeCallback); let position = import__420.Cartesian3.fromDegrees(-72, 40); const b = billboardsWithHeight.add({ heightReference: import__420.HeightReference.CLAMP_TO_GROUND, position }); expect(scene2.updateHeight).toHaveBeenCalledWith( import__420.Cartographic.fromCartesian(position), jasmine.any(Function), import__420.HeightReference.CLAMP_TO_GROUND ); position = b.position = import__420.Cartesian3.fromDegrees(-73, 40); expect(removeCallback).toHaveBeenCalled(); expect(scene2.updateHeight).toHaveBeenCalledWith( import__420.Cartographic.fromCartesian(position), jasmine.any(Function), import__420.HeightReference.CLAMP_TO_GROUND ); }); it("callback updates the position", function() { let invokeCallback; spyOn(scene2, "updateHeight").and.callFake( (cartographic2, updateCallback) => { invokeCallback = (height) => { cartographic2.height = height; updateCallback(cartographic2); }; } ); const position = import__420.Cartesian3.fromDegrees(-72, 40); const b = billboardsWithHeight.add({ heightReference: import__420.HeightReference.CLAMP_TO_GROUND, position }); expect(scene2.updateHeight).toHaveBeenCalled(); let cartographic = scene2.globe.ellipsoid.cartesianToCartographic( b._clampedPosition ); expect(cartographic.height).toEqual(0); invokeCallback(100); cartographic = scene2.globe.ellipsoid.cartesianToCartographic( b._clampedPosition ); expect(cartographic.height).toEqualEpsilon(100, import__421.Math.EPSILON9); b.position = import__420.Cartesian3.ZERO; expect(b._clampedPosition).toBeUndefined(); }); it("removes callback after disableDepthTest", function() { const removeCallback = jasmine.createSpy(); spyOn(scene2, "updateHeight").and.returnValue(removeCallback); const b = billboardsWithHeight.add({ heightReference: import__420.HeightReference.CLAMP_TO_GROUND, position: import__420.Cartesian3.fromDegrees(-122, 46), disableDepthTestDistance: Number.POSITIVE_INFINITY }); scene2.renderForSpecs(); expect(b._clampedPosition).toBeDefined(); b.disableDepthTestDistance = void 0; b.heightReference = import__420.HeightReference.NONE; scene2.renderForSpecs(); expect(b._clampedPosition).toBeUndefined(); expect(removeCallback).toHaveBeenCalled(); }); it("updates the callback when the terrain provider is changed", async function() { const removeCallback = jasmine.createSpy(); spyOn(scene2, "updateHeight").and.returnValue(removeCallback); const position = import__420.Cartesian3.fromDegrees(-72, 40); billboardsWithHeight.add({ heightReference: import__420.HeightReference.CLAMP_TO_GROUND, position }); expect(scene2.updateHeight).toHaveBeenCalledWith( import__420.Cartographic.fromCartesian(position), jasmine.any(Function), import__420.HeightReference.CLAMP_TO_GROUND ); const terrainProvider = await import__420.CesiumTerrainProvider.fromUrl( "made/up/url", { requestVertexNormals: true } ); scene2.terrainProvider = terrainProvider; expect(scene2.updateHeight).toHaveBeenCalledWith( import__420.Cartographic.fromCartesian(position), jasmine.any(Function), import__420.HeightReference.CLAMP_TO_GROUND ); expect(removeCallback).toHaveBeenCalled(); }); it("height reference without a scene rejects", function() { expect(function() { return billboards.add({ heightReference: import__420.HeightReference.CLAMP_TO_GROUND, position: import__420.Cartesian3.fromDegrees(-72, 40) }); }).toThrowDeveloperError(); }); it("changing height reference without a scene throws DeveloperError", function() { const b = billboards.add({ position: import__420.Cartesian3.fromDegrees(-72, 40) }); expect(function() { b.heightReference = import__420.HeightReference.CLAMP_TO_GROUND; }).toThrowDeveloperError(); }); it("height reference without a globe works", function() { scene2.globe = void 0; expect(function() { billboardsWithHeight.add({ heightReference: import__420.HeightReference.CLAMP_TO_GROUND, position: import__420.Cartesian3.fromDegrees(-72, 40) }); scene2.renderForSpecs(); }).not.toThrowError(); }); it("changing height reference without a globe throws DeveloperError", function() { const b = billboardsWithHeight.add({ position: import__420.Cartesian3.fromDegrees(-72, 40) }); scene2.globe = void 0; expect(function() { b.heightReference = import__420.HeightReference.CLAMP_TO_GROUND; scene2.renderForSpecs(); }).not.toThrowDeveloperError(); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/BingMapsImageryProviderSpec.js var import_urijs5 = __toESM(require_URI(), 1); var import__423 = __toESM(require_Cesium(), 1); // packages/engine/Specs/createFakeBingMapsMetadataResponse.js var import__422 = __toESM(require_Cesium(), 1); function createFakeBingMapsMetadataResponse_default(mapStyle) { let stylePrefix = "a"; switch (mapStyle) { case import__422.BingMapsStyle.AERIAL_WITH_LABELS: stylePrefix = "h"; break; case import__422.BingMapsStyle.ROAD: stylePrefix = "r"; break; } return { authenticationResultCode: "ValidCredentials", brandLogoUri: "http://dev.virtualearth.net/Branding/logo_powered_by.png", copyright: "Copyright \xA9 2014 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.", resourceSets: [ { estimatedTotal: 1, resources: [ { __type: "ImageryMetadata:http://schemas.microsoft.com/search/local/ws/rest/v1", imageHeight: 256, imageUrl: `http://ecn.{subdomain}.tiles.virtualearth.net.fake.invalid/tiles/${stylePrefix}{quadkey}.jpeg?g=3031&mkt={culture}`, imageUrlSubdomains: ["t0", "t1", "t2", "t3"], imageWidth: 256, imageryProviders: [ { attribution: "\xA9 2014 DigitalGlobe", coverageAreas: [ { bbox: [-67, -179.99, 27, 0], zoomMax: 21, zoomMin: 14 }, { bbox: [27, -179.99, 87, -126.5], zoomMax: 21, zoomMin: 14 }, { bbox: [48.4, -126.5, 87, -5.75], zoomMax: 21, zoomMin: 14 } ] }, { attribution: "Image courtesy of NASA", coverageAreas: [ { bbox: [-90, -180, 90, 180], zoomMax: 8, zoomMin: 1 } ] } ], vintageEnd: null, vintageStart: null, zoomMax: 21, zoomMin: 1 } ] } ], statusCode: 200, statusDescription: "OK", traceId: "ea754a48ccdb4dd297c8f35350e0f0d9|BN20130533|02.00.106.1600|" }; } // packages/engine/Specs/Scene/BingMapsImageryProviderSpec.js describe("Scene/BingMapsImageryProvider", function() { let supportsImageBitmapOptions; beforeAll(function() { return import__423.Resource.supportsImageBitmapOptions().then(function(result) { supportsImageBitmapOptions = result; }); }); beforeEach(function() { import__423.RequestScheduler.clearForSpecs(); import__423.BingMapsImageryProvider._metadataCache = {}; }); afterEach(function() { import__423.Resource._Implementations.loadAndExecuteScript = import__423.Resource._DefaultImplementations.loadAndExecuteScript; import__423.Resource._Implementations.loadAndExecuteScript = import__423.Resource._DefaultImplementations.loadAndExecuteScript; import__423.Resource._Implementations.loadWithXhr = import__423.Resource._DefaultImplementations.loadWithXhr; import__423.Resource._Implementations.createImage = import__423.Resource._DefaultImplementations.createImage; }); it("tileXYToQuadKey works for examples in Bing Maps documentation", function() { expect(import__423.BingMapsImageryProvider.tileXYToQuadKey(1, 0, 0)).toEqual("1"); expect(import__423.BingMapsImageryProvider.tileXYToQuadKey(1, 2, 1)).toEqual("21"); expect(import__423.BingMapsImageryProvider.tileXYToQuadKey(3, 5, 2)).toEqual("213"); expect(import__423.BingMapsImageryProvider.tileXYToQuadKey(4, 7, 2)).toEqual("322"); }); it("quadKeyToTileXY works for examples in Bing Maps documentation", function() { expect(import__423.BingMapsImageryProvider.quadKeyToTileXY("1")).toEqual({ x: 1, y: 0, level: 0 }); expect(import__423.BingMapsImageryProvider.quadKeyToTileXY("21")).toEqual({ x: 1, y: 2, level: 1 }); expect(import__423.BingMapsImageryProvider.quadKeyToTileXY("213")).toEqual({ x: 3, y: 5, level: 2 }); expect(import__423.BingMapsImageryProvider.quadKeyToTileXY("322")).toEqual({ x: 4, y: 7, level: 2 }); }); it("conforms to ImageryProvider interface", function() { expect(import__423.BingMapsImageryProvider).toConformToInterface(import__423.ImageryProvider); }); function installFakeMetadataRequest(url, mapStyle, mapLayer, culture) { const baseUri = new import_urijs5.default((0, import__423.appendForwardSlash)(url)); const expectedUri = new import_urijs5.default( `REST/v1/Imagery/Metadata/${mapStyle}` ).absoluteTo(baseUri); import__423.Resource._Implementations.loadAndExecuteScript = function(url2, functionName) { const uri = new import_urijs5.default(url2); const query = (0, import__423.queryToObject)(uri.query()); expect(query.jsonp).toBeDefined(); expect(query.incl).toEqual("ImageryProviders"); expect(query.key).toBeDefined(); if ((0, import__423.defined)(mapLayer)) { expect(query.mapLayer).toEqual(mapLayer); } if ((0, import__423.defined)(culture)) { expect(query.culture).toEqual(culture); } uri.query(""); expect(uri.toString()).toStartWith(expectedUri.toString()); setTimeout(function() { window[functionName](createFakeBingMapsMetadataResponse_default(mapStyle)); }, 1); }; } function installFakeImageRequest(expectedUrl, expectedParams, proxy) { import__423.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { const url = request.url; if (/^blob:/.test(url) || supportsImageBitmapOptions) { import__423.Resource._DefaultImplementations.createImage( request, crossOrigin, deferred, true, false, true ); } else { if ((0, import__423.defined)(expectedUrl)) { let uri = new import_urijs5.default(url); if (proxy) { uri = new import_urijs5.default(decodeURIComponent(uri.query())); } const query = (0, import__423.queryToObject)(uri.query()); uri.query(""); expect(uri.toString()).toEqual(expectedUrl); for (const param in expectedParams) { if (expectedParams.hasOwnProperty(param)) { expect(query[param]).toEqual(expectedParams[param]); } } } import__423.Resource._DefaultImplementations.createImage( new Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); } }; import__423.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { if ((0, import__423.defined)(expectedUrl)) { let uri = new import_urijs5.default(url); if (proxy) { uri = new import_urijs5.default(decodeURIComponent(uri.query())); } const query = (0, import__423.queryToObject)(uri.query()); uri.query(""); expect(uri.toString()).toEqual(expectedUrl); for (const param in expectedParams) { if (expectedParams.hasOwnProperty(param)) { expect(query[param]).toEqual(expectedParams[param]); } } } import__423.Resource._DefaultImplementations.loadWithXhr( "Data/Images/Red16x16.png", responseType, method, data, headers, deferred ); }; } it("fromUrl throws if url is not provided", async function() { await expectAsync( import__423.BingMapsImageryProvider.fromUrl() ).toBeRejectedWithDeveloperError( "url is required, actual value was undefined" ); }); it("fromUrl throws if key is not provided", async function() { await expectAsync( import__423.BingMapsImageryProvider.fromUrl("http://fake.fake.invalid/") ).toBeRejectedWithDeveloperError( "options.key is required, actual value was undefined" ); }); it("fromUrl resolves with created provider", async function() { const url = "http://fake.fake.invalid/"; const mapStyle = import__423.BingMapsStyle.ROAD; installFakeMetadataRequest(url, mapStyle); installFakeImageRequest(); const provider = await import__423.BingMapsImageryProvider.fromUrl(url, { key: "", mapStyle }); expect(provider).toBeInstanceOf(import__423.BingMapsImageryProvider); expect(provider.url).toEqual(url); }); it("fromUrl uses cached metadata result", async function() { const url = "http://fake.fake.invalid/"; const mapStyle = import__423.BingMapsStyle.ROAD; installFakeMetadataRequest(url, mapStyle); installFakeImageRequest(); const provider = await import__423.BingMapsImageryProvider.fromUrl(url, { key: "", mapStyle }); const provider2 = await import__423.BingMapsImageryProvider.fromUrl(url, { key: "", mapStyle }); expect(provider._attributionList).toBe(provider2._attributionList); installFakeMetadataRequest(url, import__423.BingMapsStyle.AERIAL); installFakeImageRequest(); const provider3 = await import__423.BingMapsImageryProvider.fromUrl(url, { key: "", mapStyle: import__423.BingMapsStyle.AERIAL }); expect(provider3._attributionList).not.toBe(provider._attributionList); }); it("fromUrl resolves with a path", async function() { const url = "http://fake.fake.invalid/some/subdirectory"; const mapStyle = import__423.BingMapsStyle.ROAD; installFakeMetadataRequest(url, mapStyle); installFakeImageRequest(); const provider = await import__423.BingMapsImageryProvider.fromUrl(url, { key: "", mapStyle }); expect(provider).toBeInstanceOf(import__423.BingMapsImageryProvider); expect(provider.url).toEqual(`${url}/`); }); it("fromUrl resolves with a path ending with a slash", async function() { const url = "http://fake.fake.invalid/some/subdirectory/"; const mapStyle = import__423.BingMapsStyle.ROAD; installFakeMetadataRequest(url, mapStyle); installFakeImageRequest(); const provider = await import__423.BingMapsImageryProvider.fromUrl(url, { key: "", mapStyle }); expect(provider).toBeInstanceOf(import__423.BingMapsImageryProvider); expect(provider.url).toEqual(url); }); it("fromUrl resolves with Resource", async function() { const url = "http://fake.fake.invalid/"; const mapStyle = import__423.BingMapsStyle.ROAD; installFakeMetadataRequest(url, mapStyle); installFakeImageRequest(); const resource = new import__423.Resource({ url }); const provider = await import__423.BingMapsImageryProvider.fromUrl(resource, { key: "", mapStyle }); expect(provider).toBeInstanceOf(import__423.BingMapsImageryProvider); expect(provider.url).toEqual(url); }); it("fromUrl takes mapLayer as option and sets hasAlphaChannel accordingly", async function() { const url = "http://fake.fake.invalid/"; const mapStyle = import__423.BingMapsStyle.AERIAL_WITH_LABELS_ON_DEMAND; const mapLayer = "Foreground"; installFakeMetadataRequest(url, mapStyle, mapLayer); installFakeImageRequest(); const resource = new import__423.Resource({ url }); const provider = await import__423.BingMapsImageryProvider.fromUrl(resource, { key: "", mapStyle, mapLayer }); expect(provider.mapLayer).toEqual("Foreground"); expect(provider.hasAlphaChannel).toBe(true); }); it("fromUrl throws if request fails", async function() { const url = "http://fake.fake.invalid"; await expectAsync( import__423.BingMapsImageryProvider.fromUrl(url, { key: "" }) ).toBeRejectedWithError( import__423.RuntimeError, new RegExp("An error occurred while accessing") ); }); it("fromUrl throws if metadata does not specify one resource in resourceSets", async function() { const url = "http://fake.fake.invalid"; const baseUri = new import_urijs5.default((0, import__423.appendForwardSlash)(url)); const expectedUri = new import_urijs5.default( `REST/v1/Imagery/Metadata/${import__423.BingMapsStyle.AERIAL}` ).absoluteTo(baseUri); import__423.Resource._Implementations.loadAndExecuteScript = function(url2, functionName) { const uri = new import_urijs5.default(url2); const query = (0, import__423.queryToObject)(uri.query()); expect(query.jsonp).toBeDefined(); expect(query.incl).toEqual("ImageryProviders"); expect(query.key).toBeDefined(); uri.query(""); expect(uri.toString()).toStartWith(expectedUri.toString()); setTimeout(function() { const response = createFakeBingMapsMetadataResponse_default( import__423.BingMapsStyle.AERIAL ); response.resourceSets = []; window[functionName](response); }, 1); }; installFakeImageRequest(); await expectAsync( import__423.BingMapsImageryProvider.fromUrl(url, { key: "" }) ).toBeRejectedWithError( import__423.RuntimeError, new RegExp("metadata does not specify one resource in resourceSets") ); }); it("returns valid value for hasAlphaChannel", async function() { const url = "http://fake.fake.invalid"; const mapStyle = import__423.BingMapsStyle.AERIAL; installFakeMetadataRequest(url, mapStyle); installFakeImageRequest(); const provider = await import__423.BingMapsImageryProvider.fromUrl(url, { key: "", mapStyle }); expect(typeof provider.hasAlphaChannel).toBe("boolean"); }); it("can provide a root tile", async function() { const url = "http://fake.fake.invalid"; const mapStyle = import__423.BingMapsStyle.ROAD; installFakeMetadataRequest(url, mapStyle); installFakeImageRequest(); const provider = await import__423.BingMapsImageryProvider.fromUrl(url, { key: "fake Key", mapStyle }); expect(provider.url).toStartWith(url); expect(provider.key).toBeDefined(); expect(provider.mapStyle).toEqual(mapStyle); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toEqual(20); expect(provider.tilingScheme).toBeInstanceOf(import__423.WebMercatorTilingScheme); expect(provider.tileDiscardPolicy).toBeInstanceOf( import__423.DiscardEmptyTileImagePolicy ); expect(provider.rectangle).toEqual(new import__423.WebMercatorTilingScheme().rectangle); expect(provider.credit).toBeInstanceOf(Object); installFakeImageRequest( "http://ecn.t0.tiles.virtualearth.net.fake.invalid/tiles/r0.jpeg", { g: "3031", mkt: "" } ); const image = await provider.requestImage(0, 0, 0); expect(image).toBeImageOrImageBitmap(); }); it("sets correct culture in tile requests", async function() { const url = "http://fake.fake.invalid"; const mapStyle = import__423.BingMapsStyle.AERIAL_WITH_LABELS; const culture = "ja-jp"; installFakeMetadataRequest(url, mapStyle, void 0, culture); installFakeImageRequest(); const provider = await import__423.BingMapsImageryProvider.fromUrl(url, { key: "", mapStyle, culture }); expect(provider.culture).toEqual(culture); installFakeImageRequest( "http://ecn.t0.tiles.virtualearth.net.fake.invalid/tiles/h0.jpeg", { g: "3031", mkt: "ja-jp" } ); const image = await provider.requestImage(0, 0, 0); expect(image).toBeImageOrImageBitmap(); }); it("raises error event when image cannot be loaded", async function() { const url = "http://foo.bar.invalid"; const mapStyle = import__423.BingMapsStyle.ROAD; installFakeMetadataRequest(url, mapStyle); installFakeImageRequest(); const provider = await import__423.BingMapsImageryProvider.fromUrl(url, { key: "", mapStyle }); const layer = new import__423.ImageryLayer(provider); let tries = 0; provider.errorEvent.addEventListener(function(error) { expect(error.timesRetried).toEqual(tries); ++tries; if (tries < 3) { error.retry = true; } setTimeout(function() { import__423.RequestScheduler.update(); }, 1); }); import__423.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { const url2 = request.url; if (/^blob:/.test(url2)) { import__423.Resource._DefaultImplementations.createImage( request, crossOrigin, deferred ); } else if (tries === 2) { import__423.Resource._DefaultImplementations.createImage( new Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); } else { setTimeout(function() { deferred.reject(); }, 1); } }; import__423.Resource._Implementations.loadWithXhr = function(url2, responseType, method, data, headers, deferred, overrideMimeType) { if (tries === 2) { import__423.Resource._DefaultImplementations.loadWithXhr( "Data/Images/Red16x16.png", responseType, method, data, headers, deferred ); } else { setTimeout(function() { deferred.reject(); }, 1); } }; const imagery = new import__423.Imagery(layer, 0, 0, 0); imagery.addReference(); layer._requestImagery(imagery); import__423.RequestScheduler.update(); return pollToPromise_default(function() { return imagery.state === import__423.ImageryState.RECEIVED; }).then(function() { expect(imagery.image).toBeImageOrImageBitmap(); expect(tries).toEqual(2); imagery.releaseReference(); }); }); it("correctly handles empty tiles", async function() { const url = "http://foo.bar.invalid"; const mapStyle = import__423.BingMapsStyle.ROAD_ON_DEMAND; installFakeMetadataRequest(url, mapStyle); const provider = await import__423.BingMapsImageryProvider.fromUrl(url, { key: "", mapStyle }); const layer = new import__423.ImageryLayer(provider); spyOn(import__423.ImageryProvider, "loadImage").and.callFake(function() { const e = new Error(); e.blob = { size: 0 }; return Promise.reject(e); }); const imagery = new import__423.Imagery(layer, 0, 0, 0); imagery.addReference(); layer._requestImagery(imagery); import__423.RequestScheduler.update(); return pollToPromise_default(function() { return imagery.state === import__423.ImageryState.RECEIVED; }).then(function() { expect(imagery.image).toBe(import__423.DiscardEmptyTileImagePolicy.EMPTY_IMAGE); imagery.releaseReference(); }); }); }); // packages/engine/Specs/Scene/BoundingVolumeSemanticsSpec.js var import__424 = __toESM(require_Cesium(), 1); describe("Scene/BoundingVolumeSemantics", function() { const boundingBox = [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]; const boundingRegion = [0, 0, import__424.Math.PI_OVER_SIX, import__424.Math.PI_OVER_TWO, 0, 50]; const boundingSphere = [0, 0, 0, 1]; const minimumHeight = -10; const maximumHeight = 10; const tileClass = import__424.MetadataClass.fromJson({ id: "tile", class: { properties: { tileBoundingBox: { type: "SCALAR", componentType: "FLOAT64", array: true, count: 12, semantic: "TILE_BOUNDING_BOX" }, tileBoundingRegion: { type: "SCALAR", componentType: "FLOAT64", array: true, count: 6, semantic: "TILE_BOUNDING_REGION" }, tileBoundingSphere: { type: "SCALAR", componentType: "FLOAT64", array: true, count: 4, semantic: "TILE_BOUNDING_SPHERE" }, tileMinimumHeight: { type: "SCALAR", componentType: "FLOAT32", semantic: "TILE_MINIMUM_HEIGHT" }, tileMaximumHeight: { type: "SCALAR", componentType: "FLOAT32", semantic: "TILE_MAXIMUM_HEIGHT" }, contentBoundingBox: { type: "SCALAR", componentType: "FLOAT64", array: true, count: 12, semantic: "CONTENT_BOUNDING_BOX" }, contentBoundingRegion: { type: "SCALAR", componentType: "FLOAT64", array: true, count: 6, semantic: "CONTENT_BOUNDING_REGION" }, contentBoundingSphere: { type: "SCALAR", componentType: "FLOAT64", array: true, count: 4, semantic: "CONTENT_BOUNDING_SPHERE" }, contentMinimumHeight: { type: "SCALAR", componentType: "FLOAT32", semantic: "CONTENT_MINIMUM_HEIGHT" }, contentMaximumHeight: { type: "SCALAR", componentType: "FLOAT32", semantic: "CONTENT_MAXIMUM_HEIGHT" } } } }); const emptyMetadata = new import__424.TileMetadata({ tile: { properties: {} }, class: { properties: {} } }); describe("parseAllBoundingVolumeSemantics", function() { it("throws without tileMetadata", function() { expect(function() { return import__424.BoundingVolumeSemantics.parseAllBoundingVolumeSemantics( void 0 ); }).toThrowDeveloperError(); }); it("works if no semantics are present", function() { expect( import__424.BoundingVolumeSemantics.parseAllBoundingVolumeSemantics(emptyMetadata) ).toEqual({ tile: { boundingVolume: void 0, minimumHeight: void 0, maximumHeight: void 0 }, content: { boundingVolume: void 0, minimumHeight: void 0, maximumHeight: void 0 } }); }); it("parses minimum and maximum height", function() { const tileMetadata = new import__424.TileMetadata({ class: tileClass, tile: { properties: { tileMinimumHeight: minimumHeight, tileMaximumHeight: maximumHeight, contentMinimumHeight: minimumHeight, contentMaximumHeight: maximumHeight } } }); expect( import__424.BoundingVolumeSemantics.parseAllBoundingVolumeSemantics(tileMetadata) ).toEqual({ tile: { boundingVolume: void 0, minimumHeight, maximumHeight }, content: { boundingVolume: void 0, minimumHeight, maximumHeight } }); }); it("parses bounding volumes", function() { const tileMetadata = new import__424.TileMetadata({ class: tileClass, tile: { properties: { tileBoundingBox: boundingBox, contentBoundingSphere: boundingSphere } } }); expect( import__424.BoundingVolumeSemantics.parseAllBoundingVolumeSemantics(tileMetadata) ).toEqual({ tile: { boundingVolume: { box: boundingBox }, minimumHeight: void 0, maximumHeight: void 0 }, content: { boundingVolume: { sphere: boundingSphere }, minimumHeight: void 0, maximumHeight: void 0 } }); }); it("bounding volumes are parsed with the precedence box, region, then sphere", function() { const tileMetadata = new import__424.TileMetadata({ class: tileClass, tile: { properties: { tileBoundingBox: boundingBox, tileBoundingRegion: boundingRegion, contentBoundingRegion: boundingRegion, contentBoundingSphere: boundingSphere } } }); expect( import__424.BoundingVolumeSemantics.parseAllBoundingVolumeSemantics(tileMetadata) ).toEqual({ tile: { boundingVolume: { box: boundingBox }, minimumHeight: void 0, maximumHeight: void 0 }, content: { boundingVolume: { region: boundingRegion }, minimumHeight: void 0, maximumHeight: void 0 } }); }); }); describe("parseBoundingVolumeSemantic", function() { it("throws without prefix", function() { expect(function() { return import__424.BoundingVolumeSemantics.parseBoundingVolumeSemantic( void 0, emptyMetadata ); }).toThrowDeveloperError(); }); it("throws if prefix is not TILE or CONTENT", function() { expect(function() { return import__424.BoundingVolumeSemantics.parseBoundingVolumeSemantic( "TILESET", emptyMetadata ); }).toThrowDeveloperError(); }); it("throws without tileMetadata", function() { expect(function() { return import__424.BoundingVolumeSemantics.parseBoundingVolumeSemantic( "TILE", void 0 ); }).toThrowDeveloperError(); }); it("returns undefined if there are no bounding volume semantics", function() { const boundingVolume = import__424.BoundingVolumeSemantics.parseBoundingVolumeSemantic( "TILE", emptyMetadata ); expect(boundingVolume).not.toBeDefined(); }); it("parses box", function() { const tileMetadata = new import__424.TileMetadata({ class: tileClass, tile: { properties: { tileBoundingBox: boundingBox } } }); const boundingVolume = import__424.BoundingVolumeSemantics.parseBoundingVolumeSemantic( "TILE", tileMetadata ); expect(boundingVolume).toEqual({ box: boundingBox }); }); it("parses region", function() { const tileMetadata = new import__424.TileMetadata({ class: tileClass, tile: { properties: { contentBoundingRegion: boundingRegion } } }); const boundingVolume = import__424.BoundingVolumeSemantics.parseBoundingVolumeSemantic( "CONTENT", tileMetadata ); expect(boundingVolume).toEqual({ region: boundingRegion }); }); it("parses sphere", function() { const tileMetadata = new import__424.TileMetadata({ class: tileClass, tile: { properties: { tileBoundingSphere: boundingSphere } } }); const boundingVolume = import__424.BoundingVolumeSemantics.parseBoundingVolumeSemantic( "TILE", tileMetadata ); expect(boundingVolume).toEqual({ sphere: boundingSphere }); }); it("parses with the precedence box, region, then sphere", function() { const tileMetadata = new import__424.TileMetadata({ class: tileClass, tile: { properties: { tileBoundingBox: boundingBox, tileBoundingRegion: boundingRegion, contentBoundingRegion: boundingRegion, contentBoundingSphere: boundingSphere } } }); const box = import__424.BoundingVolumeSemantics.parseBoundingVolumeSemantic( "TILE", tileMetadata ); expect(box).toEqual({ box: boundingBox }); const region = import__424.BoundingVolumeSemantics.parseBoundingVolumeSemantic( "CONTENT", tileMetadata ); expect(region).toEqual({ region: boundingRegion }); }); }); describe("_parseMinimumHeight", function() { it("throws without prefix", function() { expect(function() { return import__424.BoundingVolumeSemantics._parseMinimumHeight( void 0, emptyMetadata ); }).toThrowDeveloperError(); }); it("throws if prefix is not TILE or CONTENT", function() { expect(function() { return import__424.BoundingVolumeSemantics._parseMinimumHeight( "TILESET", emptyMetadata ); }).toThrowDeveloperError(); }); it("throws without tileMetadata", function() { expect(function() { return import__424.BoundingVolumeSemantics._parseMinimumHeight("TILE", void 0); }).toThrowDeveloperError(); }); it("returns undefined if minimum height not present", function() { const height = import__424.BoundingVolumeSemantics._parseMinimumHeight( "TILE", emptyMetadata ); expect(height).not.toBeDefined(); }); it("parses minimum height", function() { const tileMetadata = new import__424.TileMetadata({ class: tileClass, tile: { properties: { tileMinimumHeight: minimumHeight } } }); const height = import__424.BoundingVolumeSemantics._parseMinimumHeight( "TILE", tileMetadata ); expect(height).toBe(minimumHeight); }); }); describe("_parseMaximumHeight", function() { it("throws without prefix", function() { expect(function() { return import__424.BoundingVolumeSemantics._parseMaximumHeight( void 0, emptyMetadata ); }).toThrowDeveloperError(); }); it("throws if prefix is not TILE or CONTENT", function() { expect(function() { return import__424.BoundingVolumeSemantics._parseMaximumHeight( "TILESET", emptyMetadata ); }).toThrowDeveloperError(); }); it("throws without tileMetadata", function() { expect(function() { return import__424.BoundingVolumeSemantics._parseMaximumHeight("TILE", void 0); }).toThrowDeveloperError(); }); it("returns undefined if maximum height not present", function() { const height = import__424.BoundingVolumeSemantics._parseMaximumHeight( "TILE", emptyMetadata ); expect(height).not.toBeDefined(); }); it("parses maximum height", function() { const tileMetadata = new import__424.TileMetadata({ class: tileClass, tile: { properties: { contentMaximumHeight: maximumHeight } } }); const height = import__424.BoundingVolumeSemantics._parseMaximumHeight( "CONTENT", tileMetadata ); expect(height).toBe(maximumHeight); }); }); }); // packages/engine/Specs/Scene/BoxEmitterSpec.js var import__425 = __toESM(require_Cesium(), 1); describe("Scene/BoxEmitter", function() { let emitter; it("default constructor", function() { emitter = new import__425.BoxEmitter(); expect(emitter.dimensions).toEqual(new import__425.Cartesian3(1, 1, 1)); }); it("constructor", function() { const dimensions = new import__425.Cartesian3(2, 3, 4); emitter = new import__425.BoxEmitter(dimensions); expect(emitter.dimensions).toEqual(dimensions); }); it("constructor throws with invalid dimensions", function() { expect(function() { emitter = new import__425.BoxEmitter(new import__425.Cartesian3(-1, 1, 1)); }).toThrowDeveloperError(); expect(function() { emitter = new import__425.BoxEmitter(new import__425.Cartesian3(1, -1, 1)); }).toThrowDeveloperError(); expect(function() { emitter = new import__425.BoxEmitter(new import__425.Cartesian3(1, 1, -1)); }).toThrowDeveloperError(); }); it("dimensions setter", function() { emitter = new import__425.BoxEmitter(); const dimensions = new import__425.Cartesian3(2, 3, 4); emitter.dimensions = dimensions; expect(emitter.dimensions).toEqual(dimensions); }); it("dimensions setter throws with invalid value", function() { emitter = new import__425.BoxEmitter(); expect(function() { emitter.dimensions = void 0; }).toThrowDeveloperError(); expect(function() { emitter.dimensions = new import__425.Cartesian3(-1, 1, 1); }).toThrowDeveloperError(); expect(function() { emitter.dimensions = new import__425.Cartesian3(1, -1, 1); }).toThrowDeveloperError(); expect(function() { emitter.dimensions = new import__425.Cartesian3(1, -1, 1); }).toThrowDeveloperError(); }); it("emits", function() { emitter = new import__425.BoxEmitter(new import__425.Cartesian3(2, 3, 4)); const particle = new import__425.Particle(); for (let i = 0; i < 1e3; ++i) { emitter.emit(particle); expect(particle.position.x).toBeLessThanOrEqual(emitter.dimensions.x); expect(particle.position.y).toBeLessThanOrEqual(emitter.dimensions.y); expect(particle.position.z).toBeLessThanOrEqual(emitter.dimensions.z); expect(particle.velocity).toEqual( import__425.Cartesian3.normalize(particle.position, new import__425.Cartesian3()) ); } }); }); // packages/engine/Specs/Scene/BufferLoaderSpec.js var import__426 = __toESM(require_Cesium(), 1); describe("Scene/BufferLoader", function() { const typedArray = new Uint8Array([1, 3, 7, 15, 31, 63, 127, 255]); const arrayBuffer = typedArray.buffer; const resource = new import__426.Resource({ url: "https://example.com/external.bin" }); afterEach(function() { import__426.ResourceCache.clearForSpecs(); }); it("throws if neither options.typedArray nor options.resource are defined", function() { expect(function() { return new import__426.BufferLoader({ typedArray: void 0, resource: void 0 }); }).toThrowDeveloperError(); }); it("throws if both options.typedArray and options.resource are defined", function() { expect(function() { return new import__426.BufferLoader({ typedArray, resource }); }).toThrowDeveloperError(); }); it("load throws if buffer cannot be fetched", async function() { const error = new Error("404 Not Found"); spyOn(import__426.Resource.prototype, "fetchArrayBuffer").and.callFake(function() { return Promise.reject(error); }); const bufferLoader = new import__426.BufferLoader({ resource }); await expectAsync(bufferLoader.load()).toBeRejectedWithError( import__426.RuntimeError, "Failed to load external buffer: https://example.com/external.bin\n404 Not Found" ); }); it("loads buffer from typed array", async function() { const bufferLoader = new import__426.BufferLoader({ typedArray }); await bufferLoader.load(); expect(bufferLoader.typedArray).toBe(typedArray); }); it("loads external buffer", async function() { const fetchBuffer = spyOn( import__426.Resource.prototype, "fetchArrayBuffer" ).and.returnValue(Promise.resolve(arrayBuffer)); const bufferLoader = new import__426.BufferLoader({ resource }); await bufferLoader.load(); expect(fetchBuffer).toHaveBeenCalled(); expect(bufferLoader.typedArray.buffer).toBe(arrayBuffer); }); it("destroys buffer", async function() { spyOn(import__426.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); const bufferLoader = new import__426.BufferLoader({ resource }); expect(bufferLoader.typedArray).not.toBeDefined(); await bufferLoader.load(); expect(bufferLoader.typedArray.buffer).toBe(arrayBuffer); expect(bufferLoader.isDestroyed()).toBe(false); bufferLoader.destroy(); expect(bufferLoader.typedArray).not.toBeDefined(); expect(bufferLoader.isDestroyed()).toBe(true); }); it("handles asynchronous load after destroy", async function() { spyOn(import__426.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); const bufferLoader = new import__426.BufferLoader({ resource }); expect(bufferLoader.typedArray).not.toBeDefined(); const loadPromise = bufferLoader.load(); bufferLoader.destroy(); await expectAsync(loadPromise).toBeResolved(); expect(bufferLoader.typedArray).not.toBeDefined(); expect(bufferLoader.isDestroyed()).toBe(true); }); it("handles asynchronous error after destroy", async function() { spyOn(import__426.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.reject(new Error()) ); const bufferLoader = new import__426.BufferLoader({ resource }); expect(bufferLoader.typedArray).not.toBeDefined(); const loadPromise = bufferLoader.load(); bufferLoader.destroy(); await expectAsync(loadPromise).toBeResolved(); expect(bufferLoader.typedArray).not.toBeDefined(); expect(bufferLoader.isDestroyed()).toBe(true); }); }); // packages/engine/Specs/Scene/CameraEventAggregatorSpec.js var import__427 = __toESM(require_Cesium(), 1); describe("Scene/CameraEventAggregator", function() { let usePointerEvents; let canvas; let handler; let handler2; beforeAll(function() { usePointerEvents = import__427.FeatureDetection.supportsPointerEvents(); canvas = createCanvas_default(1024, 768); }); afterAll(function() { document.body.removeChild(canvas); }); beforeEach(function() { handler = new import__427.CameraEventAggregator(canvas); }); afterEach(function() { handler = handler && !handler.isDestroyed() && handler.destroy(); handler2 = handler2 && !handler2.isDestroyed() && handler2.destroy(); }); const MouseButtons = { LEFT: 0, MIDDLE: 1, RIGHT: 2 }; function simulateMouseDown(options) { if (usePointerEvents) { DomEventSimulator_default.firePointerDown( canvas, (0, import__427.combine)(options, { pointerType: "mouse" }) ); } else { DomEventSimulator_default.fireMouseDown(canvas, options); } } function simulateMouseUp(options) { if (usePointerEvents) { DomEventSimulator_default.firePointerUp( canvas, (0, import__427.combine)(options, { pointerType: "mouse" }) ); } else { DomEventSimulator_default.fireMouseUp(canvas, options); } } function simulateMouseMove(options) { if (usePointerEvents) { DomEventSimulator_default.firePointerMove( canvas, (0, import__427.combine)(options, { pointerType: "mouse" }) ); } else { DomEventSimulator_default.fireMouseMove(canvas, options); } } function moveMouse(button, startPosition, endPosition, shiftKey) { const canvasRect = canvas.getBoundingClientRect(); const options = { button, clientX: startPosition.x + canvasRect.left, clientY: startPosition.y + canvasRect.top, shiftKey }; simulateMouseDown(options); options.clientX = endPosition.x + canvasRect.left; options.clientY = endPosition.y + canvasRect.top; simulateMouseMove(options); simulateMouseUp(options); } it("throws without a canvas", function() { expect(function() { handler2 = new import__427.CameraEventAggregator(); }).toThrowDeveloperError(); }); it("getMovement throws without a type", function() { expect(function() { handler.getMovement(); }).toThrowDeveloperError(); }); it("isMoving throws without a type", function() { expect(function() { handler.isMoving(); }).toThrowDeveloperError(); }); it("isButtonDown throws without a type", function() { expect(function() { handler.isButtonDown(); }).toThrowDeveloperError(); }); it("getButtonPressTime throws without a type", function() { expect(function() { handler.getButtonPressTime(); }).toThrowDeveloperError(); }); it("getButtonReleaseTime throws without a type", function() { expect(function() { handler.getButtonReleaseTime(); }).toThrowDeveloperError(); }); it("getMovement", function() { const startPosition = import__427.Cartesian2.ZERO; const endPosition = import__427.Cartesian2.UNIT_X; moveMouse(MouseButtons.LEFT, startPosition, endPosition); let movement = handler.getMovement(import__427.CameraEventType.LEFT_DRAG); expect(movement).toBeDefined(); expect(movement.startPosition).toEqual(startPosition); expect(movement.endPosition).toEqual(endPosition); moveMouse(MouseButtons.RIGHT, startPosition, endPosition, true); movement = handler.getMovement( import__427.CameraEventType.RIGHT_DRAG, import__427.KeyboardEventModifier.SHIFT ); expect(movement).toBeDefined(); expect(movement.startPosition).toEqual(startPosition); expect(movement.endPosition).toEqual(endPosition); }); it("getLastMovement", function() { expect(handler.getLastMovement(import__427.CameraEventType.LEFT_DRAG)).toBeUndefined(); const startPosition = import__427.Cartesian2.ZERO; const endPosition = import__427.Cartesian2.UNIT_X; const endPosition2 = import__427.Cartesian2.UNIT_Y; const canvasRect = canvas.getBoundingClientRect(); const options = { button: MouseButtons.LEFT, clientX: startPosition.x + canvasRect.left, clientY: startPosition.y + canvasRect.top }; simulateMouseDown(options); options.clientX = endPosition.x + canvasRect.left; options.clientY = endPosition.y + canvasRect.top; simulateMouseMove(options); handler.reset(); options.clientX = endPosition2.x + canvasRect.left; options.clientY = endPosition2.y + canvasRect.top; simulateMouseMove(options); const movement = handler.getLastMovement(import__427.CameraEventType.LEFT_DRAG); expect(movement).toBeDefined(); expect(movement.startPosition).toEqual(startPosition); expect(movement.endPosition).toEqual(endPosition); }); it("isMoving", function() { expect(handler.isMoving(import__427.CameraEventType.LEFT_DRAG)).toEqual(false); const startPosition = import__427.Cartesian2.ZERO; const endPosition = import__427.Cartesian2.UNIT_X; moveMouse(MouseButtons.LEFT, startPosition, endPosition); expect(handler.isMoving(import__427.CameraEventType.LEFT_DRAG)).toEqual(true); handler.reset(); expect(handler.isMoving(import__427.CameraEventType.LEFT_DRAG)).toEqual(false); }); it("isButtonDown", function() { expect(handler.isButtonDown(import__427.CameraEventType.LEFT_DRAG)).toEqual(false); const options = { button: MouseButtons.LEFT, clientX: 0, clientY: 0 }; simulateMouseDown(options); expect(handler.isButtonDown(import__427.CameraEventType.LEFT_DRAG)).toEqual(true); simulateMouseUp(options); expect(handler.isButtonDown(import__427.CameraEventType.LEFT_DRAG)).toEqual(false); }); it("anyButtonDown", function() { expect(handler.anyButtonDown).toEqual(false); const options = { button: MouseButtons.LEFT, clientX: 0, clientY: 0 }; simulateMouseDown(options); expect(handler.anyButtonDown).toEqual(true); options.button = MouseButtons.RIGHT; simulateMouseDown(options); expect(handler.anyButtonDown).toEqual(true); simulateMouseUp(options); options.button = MouseButtons.LEFT; simulateMouseUp(options); expect(handler.anyButtonDown).toEqual(false); }); it("cancels anyButtonDown on any button up", function() { expect(handler.anyButtonDown).toEqual(false); const options = { button: MouseButtons.LEFT, clientX: 0, clientY: 0 }; simulateMouseDown(options); options.button = MouseButtons.RIGHT; simulateMouseDown(options); simulateMouseUp(options); expect(handler.anyButtonDown).toEqual(false); }); it("getButtonPressTime", function() { expect( handler.getButtonPressTime(import__427.CameraEventType.LEFT_DRAG) ).toBeUndefined(); const options = { button: MouseButtons.LEFT, clientX: 0, clientY: 0 }; const before = /* @__PURE__ */ new Date(); simulateMouseDown(options); const after = /* @__PURE__ */ new Date(); const downTime = handler.getButtonPressTime(import__427.CameraEventType.LEFT_DRAG); expect(downTime).toBeDefined(); expect(downTime.getTime()).toBeGreaterThanOrEqual(before.getTime()); expect(downTime.getTime()).toBeLessThanOrEqual(after.getTime()); }); it("getButtonReleaseTime", function() { expect( handler.getButtonReleaseTime(import__427.CameraEventType.LEFT_DRAG) ).toBeUndefined(); const options = { button: MouseButtons.LEFT, clientX: 0, clientY: 0 }; simulateMouseDown(options); const before = /* @__PURE__ */ new Date(); simulateMouseUp(options); const after = /* @__PURE__ */ new Date(); const upTime = handler.getButtonReleaseTime(import__427.CameraEventType.LEFT_DRAG); expect(upTime).toBeDefined(); expect(upTime.getTime()).toBeGreaterThanOrEqual(before.getTime()); expect(upTime.getTime()).toBeLessThanOrEqual(after.getTime()); }); it("aggregates events", function() { const startPosition = import__427.Cartesian2.ZERO; const endPosition = import__427.Cartesian2.UNIT_X; const endPosition2 = import__427.Cartesian2.UNIT_Y; const canvasRect = canvas.getBoundingClientRect(); const options = { button: MouseButtons.LEFT, clientX: startPosition.x + canvasRect.left, clientY: startPosition.y + canvasRect.top }; simulateMouseDown(options); options.clientX = endPosition.x + canvasRect.left; options.clientY = endPosition.y + canvasRect.top; simulateMouseMove(options); options.clientX = endPosition2.x + canvasRect.left; options.clientY = endPosition2.y + canvasRect.top; simulateMouseMove(options); const movement = handler.getMovement(import__427.CameraEventType.LEFT_DRAG); expect(movement).toBeDefined(); expect(movement.startPosition).toEqual(startPosition); expect(movement.endPosition).toEqual(endPosition2); }); it("isDestroyed", function() { expect(handler.isDestroyed()).toEqual(false); handler.destroy(); expect(handler.isDestroyed()).toEqual(true); }); }); // packages/engine/Specs/Scene/CameraFlightPathSpec.js var import__428 = __toESM(require_Cesium(), 1); var import__429 = __toESM(require_Cesium(), 1); describe( "Scene/CameraFlightPath", function() { let scene2; beforeEach(function() { scene2 = createScene_default(); }); afterEach(function() { scene2.destroyForSpecs(); }); function createOrthographicFrustum() { const current = scene2.camera.frustum; const f = new import__428.OrthographicOffCenterFrustum(); f.near = current.near; f.far = current.far; const tanTheta = Math.tan(0.5 * current.fovy); f.top = f.near * tanTheta; f.bottom = -f.top; f.right = current.aspectRatio * f.top; f.left = -f.right; return f; } it("create animation throws without a scene", function() { expect(function() { import__428.CameraFlightPath.createTween(void 0, { destination: new import__428.Cartesian3(1e9, 1e9, 1e9) }); }).toThrowDeveloperError(); }); it("create animation throws without a destination", function() { expect(function() { import__428.CameraFlightPath.createTween(scene2, {}); }).toThrowDeveloperError(); }); it("creates an animation", function() { const destination = new import__428.Cartesian3(1e9, 1e9, 1e9); const duration = 5; const complete = function() { }; const cancel = function() { }; const flight = import__428.CameraFlightPath.createTween(scene2, { destination, duration, complete, cancel }); expect(flight.duration).toEqual(duration); expect(typeof flight.complete).toEqual("function"); expect(typeof flight.cancel).toEqual("function"); expect(typeof flight.update).toEqual("function"); expect(flight.startObject).toBeDefined(); expect(flight.stopObject).toBeDefined(); expect(flight.easingFunction).toBeDefined(); }); it("creates an animation in 3d", function() { const camera = scene2.camera; const startPosition = import__428.Cartesian3.clone(camera.position); const startHeading = camera.heading; const startPitch = camera.pitch; const startRoll = camera.roll; const endPosition = import__428.Cartesian3.negate(startPosition, new import__428.Cartesian3()); const endHeading = import__429.Math.toRadians(20); const endPitch = import__429.Math.toRadians(-45); const endRoll = import__429.Math.TWO_PI; const duration = 5; const flight = import__428.CameraFlightPath.createTween(scene2, { destination: endPosition, heading: endHeading, pitch: endPitch, roll: endRoll, duration }); flight.update({ time: 0 }); expect(camera.position).toEqualEpsilon( startPosition, import__429.Math.EPSILON12 ); expect(camera.heading).toEqualEpsilon(startHeading, import__429.Math.EPSILON12); expect(camera.pitch).toEqualEpsilon(startPitch, import__429.Math.EPSILON12); expect(camera.roll).toEqualEpsilon(startRoll, import__429.Math.EPSILON12); flight.update({ time: duration }); expect(camera.position).toEqualEpsilon(endPosition, import__429.Math.EPSILON12); expect(camera.heading).toEqualEpsilon(endHeading, import__429.Math.EPSILON12); expect(camera.pitch).toEqualEpsilon(endPitch, import__429.Math.EPSILON12); expect(camera.roll).toEqualEpsilon(endRoll, import__429.Math.EPSILON12); }); it("creates an animation in 3d using custom ellipsoid", function() { const ellipsoid = new import__428.Ellipsoid(1737400, 1737400, 1737400); const mapProjection = new import__428.GeographicProjection(ellipsoid); scene2 = createScene_default({ mapProjection }); scene2.globe = new import__428.Globe(ellipsoid); const camera = scene2.camera; const startPosition = import__428.Cartesian3.clone(camera.position); const endPosition = import__428.Cartesian3.fromDegrees(0, 0, 100, ellipsoid); const duration = 1; const flight = import__428.CameraFlightPath.createTween(scene2, { destination: endPosition, duration }); flight.update({ time: 0 }); expect(camera.position).toEqualEpsilon( startPosition, import__429.Math.EPSILON12 ); flight.update({ time: duration }); expect(camera.position).toEqualEpsilon(endPosition, import__429.Math.EPSILON7); }); it("creates an animation in Columbus view", function() { scene2._mode = import__428.SceneMode.COLUMBUS_VIEW; const camera = scene2.camera; camera.position = new import__428.Cartesian3(0, 0, 1e3); camera.direction = import__428.Cartesian3.negate(import__428.Cartesian3.UNIT_Z, new import__428.Cartesian3()); camera.up = import__428.Cartesian3.clone(import__428.Cartesian3.UNIT_Y); camera.right = import__428.Cartesian3.cross( camera.direction, camera.up, new import__428.Cartesian3() ); const startPosition = import__428.Cartesian3.clone(camera.position); const projection = scene2.mapProjection; const destination = import__428.Cartesian3.add( startPosition, new import__428.Cartesian3(-6e5 * Math.PI, 6e5 * import__429.Math.PI_OVER_FOUR, 100), new import__428.Cartesian3() ); const endPosition = projection.ellipsoid.cartographicToCartesian( projection.unproject(destination) ); const duration = 5; const flight = import__428.CameraFlightPath.createTween(scene2, { destination: endPosition, duration }); flight.update({ time: 0 }); expect(camera.position).toEqualEpsilon( startPosition, import__429.Math.EPSILON12 ); flight.update({ time: duration }); expect(camera.position).toEqualEpsilon(destination, import__429.Math.EPSILON4); }); it("creates an animation in 2D", function() { scene2._mode = import__428.SceneMode.SCENE2D; const camera = scene2.camera; camera.position = new import__428.Cartesian3(0, 0, 1e3); camera.direction = import__428.Cartesian3.negate(import__428.Cartesian3.UNIT_Z, new import__428.Cartesian3()); camera.up = import__428.Cartesian3.clone(import__428.Cartesian3.UNIT_Y); camera.right = import__428.Cartesian3.cross( camera.direction, camera.up, new import__428.Cartesian3() ); camera.frustum = createOrthographicFrustum(); const startHeight = camera.frustum.right - camera.frustum.left; const startPosition = import__428.Cartesian3.clone(camera.position); const projection = scene2.mapProjection; const destination = import__428.Cartesian3.add( startPosition, new import__428.Cartesian3(-6e6 * Math.PI, 6e6 * import__429.Math.PI_OVER_FOUR, 100), new import__428.Cartesian3() ); const endPosition = projection.ellipsoid.cartographicToCartesian( projection.unproject(destination) ); const duration = 5; const flight = import__428.CameraFlightPath.createTween(scene2, { destination: endPosition, duration }); flight.update({ time: 0 }); expect(camera.position).toEqualEpsilon( startPosition, import__429.Math.EPSILON12 ); expect(camera.frustum.right - camera.frustum.left).toEqualEpsilon( startHeight, import__429.Math.EPSILON7 ); flight.update({ time: duration }); expect(camera.position.x).toEqualEpsilon( destination.x, import__429.Math.EPSILON7 ); expect(camera.position.y).toEqualEpsilon( destination.y, import__429.Math.EPSILON7 ); expect(camera.position.z).toEqualEpsilon( startPosition.z, import__429.Math.EPSILON7 ); expect(camera.frustum.right - camera.frustum.left).toEqualEpsilon( destination.z, import__429.Math.EPSILON7 ); }); it("creates a path where the start and end points only differ in height", function() { const camera = scene2.camera; const start = import__428.Cartesian3.clone(camera.position); const mag = import__428.Cartesian3.magnitude(start); const end = import__428.Cartesian3.multiplyByScalar( import__428.Cartesian3.normalize(start, new import__428.Cartesian3()), mag - 1e6, new import__428.Cartesian3() ); const duration = 3; const flight = import__428.CameraFlightPath.createTween(scene2, { destination: end, duration }); flight.update({ time: 0 }); expect(camera.position).toEqualEpsilon(start, import__429.Math.EPSILON12); flight.update({ time: duration }); expect(camera.position).toEqualEpsilon(end, import__429.Math.EPSILON12); }); it("does not create a path to the same point", function() { const camera = scene2.camera; camera.position = new import__428.Cartesian3(7e6, 0, 0); const startPosition = import__428.Cartesian3.clone(camera.position); const startHeading = camera.heading; const startPitch = camera.pitch; const startRoll = camera.roll; const duration = 3; const flight = import__428.CameraFlightPath.createTween(scene2, { destination: startPosition, heading: startHeading, pitch: startPitch, roll: startRoll, duration }); expect(flight.duration).toEqual(0); expect(camera.position).toEqual(startPosition); expect(camera.heading).toEqual(startHeading); expect(camera.pitch).toEqual(startPitch); expect(camera.roll).toEqual(startRoll); }); it("creates an animation with 0 duration", function() { const destination = new import__428.Cartesian3(1e9, 1e9, 1e9); const duration = 0; const complete = function() { return true; }; const flight = import__428.CameraFlightPath.createTween(scene2, { destination, duration, complete }); expect(flight.duration).toEqual(duration); expect(flight.complete).not.toEqual(complete); expect(flight.update).toBeUndefined(); expect(scene2.camera.position).not.toEqual(destination); flight.complete(); expect(scene2.camera.position).toEqualEpsilon( destination, import__429.Math.EPSILON14 ); }); it("duration is 0 when destination is the same as camera position in 2D", function() { scene2._mode = import__428.SceneMode.SCENE2D; const camera = scene2.camera; camera.position = new import__428.Cartesian3(0, 0, 1e3); camera.direction = import__428.Cartesian3.negate(import__428.Cartesian3.UNIT_Z, new import__428.Cartesian3()); camera.up = import__428.Cartesian3.clone(import__428.Cartesian3.UNIT_Y); camera.right = import__428.Cartesian3.cross( camera.direction, camera.up, new import__428.Cartesian3() ); camera.frustum = createOrthographicFrustum(); camera.update(scene2.mode); const frustum = camera.frustum; const destination = import__428.Cartesian3.clone(camera.position); destination.z = Math.max( frustum.right - frustum.left, frustum.top - frustum.bottom ); const projection = scene2.mapProjection; const endPosition = projection.ellipsoid.cartographicToCartesian( projection.unproject(destination) ); const flight = import__428.CameraFlightPath.createTween(scene2, { destination: endPosition }); expect(flight.duration).toEqual(0); }); it("duration is 0 when destination is the same as camera position in 3D", function() { scene2._mode = import__428.SceneMode.SCENE3D; const camera = scene2.camera; camera.position = new import__428.Cartesian3(0, 0, 1e3); camera.setView({ orientation: { heading: 0, pitch: -import__429.Math.PI_OVER_TWO, roll: 0 } }); camera.frustum = createOrthographicFrustum(); const flight = import__428.CameraFlightPath.createTween(scene2, { destination: camera.position }); expect(flight.duration).toEqual(0); }); it("duration is 0 when destination is the same as camera position in CV", function() { scene2._mode = import__428.SceneMode.COLUMBUS_VIEW; const camera = scene2.camera; camera.position = new import__428.Cartesian3(0, 0, 1e3); camera.setView({ orientation: { heading: 0, pitch: -import__429.Math.PI_OVER_TWO, roll: 0 } }); const projection = scene2.mapProjection; const endPosition = projection.ellipsoid.cartographicToCartesian( projection.unproject(camera.position) ); const flight = import__428.CameraFlightPath.createTween(scene2, { destination: endPosition }); expect(flight.duration).toEqual(0); }); it("creates an animation in 2D 0 duration", function() { scene2._mode = import__428.SceneMode.SCENE2D; const camera = scene2.camera; camera.position = new import__428.Cartesian3(0, 0, 1e3); camera.direction = import__428.Cartesian3.negate(import__428.Cartesian3.UNIT_Z, new import__428.Cartesian3()); camera.up = import__428.Cartesian3.clone(import__428.Cartesian3.UNIT_Y); camera.right = import__428.Cartesian3.cross( camera.direction, camera.up, new import__428.Cartesian3() ); camera.frustum = createOrthographicFrustum(); camera.update(scene2.mode); const startPosition = import__428.Cartesian3.clone(camera.position); const projection = scene2.mapProjection; const destination = import__428.Cartesian3.add( startPosition, new import__428.Cartesian3(-6e5 * Math.PI, 6e5 * import__429.Math.PI_OVER_FOUR, 100), new import__428.Cartesian3() ); const endPosition = projection.ellipsoid.cartographicToCartesian( projection.unproject(destination) ); const flight = import__428.CameraFlightPath.createTween(scene2, { destination: endPosition, duration: 0 }); expect(typeof flight.complete).toEqual("function"); flight.complete(); expect(camera.position.x).toEqualEpsilon( destination.x, import__429.Math.EPSILON7 ); expect(camera.position.y).toEqualEpsilon( destination.y, import__429.Math.EPSILON7 ); expect(camera.frustum.right - camera.frustum.left).toEqualEpsilon( destination.z, import__429.Math.EPSILON7 ); }); it("creates an animation in Columbus view 0 duration", function() { scene2._mode = import__428.SceneMode.COLUMBUS_VIEW; const camera = scene2.camera; camera.position = new import__428.Cartesian3(0, 0, 1e3); camera.direction = import__428.Cartesian3.negate(import__428.Cartesian3.UNIT_Z, new import__428.Cartesian3()); camera.up = import__428.Cartesian3.clone(import__428.Cartesian3.UNIT_Y); camera.right = import__428.Cartesian3.cross( camera.direction, camera.up, new import__428.Cartesian3() ); const startPosition = import__428.Cartesian3.clone(camera.position); const projection = scene2.mapProjection; const destination = import__428.Cartesian3.add( startPosition, new import__428.Cartesian3(-6e6 * Math.PI, 6e6 * import__429.Math.PI_OVER_FOUR, 100), new import__428.Cartesian3() ); const endPosition = projection.ellipsoid.cartographicToCartesian( projection.unproject(destination) ); const flight = import__428.CameraFlightPath.createTween(scene2, { destination: endPosition, duration: 0 }); expect(typeof flight.complete).toEqual("function"); flight.complete(); expect(camera.position).toEqualEpsilon(destination, import__429.Math.EPSILON8); }); it("creates an animation in 3d 0 duration", function() { const camera = scene2.camera; const startPosition = import__428.Cartesian3.clone(camera.position); const endPosition = import__428.Cartesian3.negate(startPosition, new import__428.Cartesian3()); const flight = import__428.CameraFlightPath.createTween(scene2, { destination: endPosition, duration: 0 }); expect(typeof flight.complete).toEqual("function"); flight.complete(); expect(camera.position).toEqualEpsilon(endPosition, import__429.Math.EPSILON12); }); it("creates animation to hit flyOverLongitude", function() { const camera = scene2.camera; const projection = scene2.mapProjection; const position = new import__428.Cartographic(); camera.position = import__428.Cartesian3.fromDegrees(10, 45, 1e3); const endPosition = import__428.Cartesian3.fromDegrees(20, 45, 1e3); const overLonFlight = import__428.CameraFlightPath.createTween(scene2, { destination: endPosition, duration: 1, flyOverLongitude: import__429.Math.toRadians(0) }); const directFlight = import__428.CameraFlightPath.createTween(scene2, { destination: endPosition, duration: 1 }); expect(typeof overLonFlight.update).toEqual("function"); expect(typeof directFlight.update).toEqual("function"); overLonFlight.update({ time: 0.3 }); projection.ellipsoid.cartesianToCartographic(camera.position, position); let lon = import__429.Math.toDegrees(position.longitude); expect(lon).toBeLessThan(10); directFlight.update({ time: 0.3 }); projection.ellipsoid.cartesianToCartographic(camera.position, position); lon = import__429.Math.toDegrees(position.longitude); expect(lon).toBeGreaterThan(10); expect(lon).toBeLessThan(20); }); it("uses flyOverLongitudeWeight", function() { const camera = scene2.camera; const projection = scene2.mapProjection; const position = new import__428.Cartographic(); camera.position = import__428.Cartesian3.fromDegrees(10, 45, 1e3); const endPosition = import__428.Cartesian3.fromDegrees(50, 45, 1e3); const overLonFlightSmallWeight = import__428.CameraFlightPath.createTween(scene2, { destination: endPosition, duration: 1, flyOverLongitude: import__429.Math.toRadians(0), flyOverLongitudeWeight: 2 }); const overLonFlightBigWeight = import__428.CameraFlightPath.createTween(scene2, { destination: endPosition, duration: 1, flyOverLongitude: import__429.Math.toRadians(0), flyOverLongitudeWeight: 20 }); overLonFlightBigWeight.update({ time: 0.3 }); projection.ellipsoid.cartesianToCartographic(camera.position, position); let lon = import__429.Math.toDegrees(position.longitude); expect(lon).toBeLessThan(10); overLonFlightSmallWeight.update({ time: 0.3 }); projection.ellipsoid.cartesianToCartographic(camera.position, position); lon = import__429.Math.toDegrees(position.longitude); expect(lon).toBeGreaterThan(10); expect(lon).toBeLessThan(50); }); it("adjust pitch if camera flyes higher than pitchAdjustHeight", function() { const camera = scene2.camera; const duration = 5; camera.setView({ destination: import__428.Cartesian3.fromDegrees(-20, 0, 1e3), orientation: { heading: import__429.Math.toRadians(0), pitch: import__429.Math.toRadians(-15), roll: 0 } }); const startPitch = camera.pitch; const endPitch = import__429.Math.toRadians(-45); const flight = import__428.CameraFlightPath.createTween(scene2, { destination: import__428.Cartesian3.fromDegrees(60, 0, 2e3), pitch: endPitch, duration, pitchAdjustHeight: 2e3 }); flight.update({ time: 0 }); expect(camera.pitch).toEqualEpsilon(startPitch, import__429.Math.EPSILON6); flight.update({ time: duration }); expect(camera.pitch).toEqualEpsilon(endPitch, import__429.Math.EPSILON6); flight.update({ time: duration / 2 }); expect(camera.pitch).toEqualEpsilon( -import__429.Math.PI_OVER_TWO, import__429.Math.EPSILON4 ); }); it("animation with flyOverLongitude is smooth over two pi", function() { const camera = scene2.camera; const duration = 100; const projection = scene2.mapProjection; const position = new import__428.Cartographic(); const startLonDegrees = 10; const endLonDegrees = 20; camera.position = import__428.Cartesian3.fromDegrees(startLonDegrees, 45, 1e3); const endPosition = import__428.Cartesian3.fromDegrees(endLonDegrees, 45, 1e3); const outsideTwoPiFlight = import__428.CameraFlightPath.createTween(scene2, { destination: endPosition, duration, flyOverLongitude: import__429.Math.toRadians(0) }); let prevLon = startLonDegrees; let crossedDateChangesLine = 0; for (let t = 1; t < duration; t++) { outsideTwoPiFlight.update({ time: t }); projection.ellipsoid.cartesianToCartographic(camera.position, position); const lon = import__429.Math.toDegrees(position.longitude); let d = lon - prevLon; if (d > 0) { expect(prevLon).toBeLessThan(-90); crossedDateChangesLine++; d -= 360; } prevLon = lon; expect(d).toBeLessThan(0); } expect(crossedDateChangesLine).toEqual(1); }); it("animation with flyOverLongitude is smooth", function() { const camera = scene2.camera; const duration = 100; const projection = scene2.mapProjection; const position = new import__428.Cartographic(); const startLonDegrees = -100; const endLonDegrees = 100; camera.position = import__428.Cartesian3.fromDegrees(startLonDegrees, 45, 1e3); const endPosition = import__428.Cartesian3.fromDegrees(endLonDegrees, 45, 1e3); const flight = import__428.CameraFlightPath.createTween(scene2, { destination: endPosition, duration, flyOverLongitude: import__429.Math.toRadians(0) }); let prevLon = startLonDegrees; for (let t = 1; t < duration; t++) { flight.update({ time: t }); projection.ellipsoid.cartesianToCartographic(camera.position, position); const lon = import__429.Math.toDegrees(position.longitude); const d = lon - prevLon; prevLon = lon; expect(d).toBeGreaterThan(0); } }); it("does not go above the maximum height", function() { const camera = scene2.camera; const startPosition = import__428.Cartesian3.fromDegrees(0, 0, 1e3); const endPosition = import__428.Cartesian3.fromDegrees(10, 0, 1e3); const duration = 5; camera.setView({ destination: startPosition }); let flight = import__428.CameraFlightPath.createTween(scene2, { destination: endPosition, duration }); let maximumHeight = Number.NEGATIVE_INFINITY; let i; for (i = 0; i <= duration; ++i) { flight.update({ time: i }); maximumHeight = Math.max( maximumHeight, camera.positionCartographic.height ); } maximumHeight *= 0.5; camera.setView({ destination: startPosition }); flight = import__428.CameraFlightPath.createTween(scene2, { destination: endPosition, duration, maximumHeight }); for (i = 0; i <= duration; ++i) { flight.update({ time: i }); expect(camera.positionCartographic.height).toBeLessThan(maximumHeight); } }); }, "WebGL" ); // packages/engine/Specs/Scene/CameraSpec.js var import__430 = __toESM(require_Cesium(), 1); var import__431 = __toESM(require_Cesium(), 1); describe("Scene/Camera", function() { let scene2; let camera; let position; let up; let dir; let right; const moveAmount = 3; const turnAmount = import__431.Math.PI_OVER_TWO; const rotateAmount = import__431.Math.PI_OVER_TWO; const zoomAmount = 1; function FakeScene(projection) { this.canvas = { clientWidth: 512, clientHeight: 384 }; this.drawingBufferWidth = 1024; this.drawingBufferHeight = 768; this.mapProjection = (0, import__430.defaultValue)(projection, new import__430.GeographicProjection()); this.tweens = new import__430.TweenCollection(); this.screenSpaceCameraController = { minimumZoomDistance: 0, maximumZoomDistance: 5906376272e3 // distance from the Sun to Pluto in meters. }; this.camera = void 0; this.preloadFlightCamera = void 0; this.context = { drawingBufferWidth: 1024, drawingBufferHeight: 768 }; this.mapMode2D = import__430.MapMode2D.INFINITE_2D; } beforeEach(function() { position = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Z); up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Y); dir = import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3()); right = import__430.Cartesian3.cross(dir, up, new import__430.Cartesian3()); scene2 = new FakeScene(); camera = new import__430.Camera(scene2); camera.position = import__430.Cartesian3.clone(position); camera.up = import__430.Cartesian3.clone(up); camera.direction = import__430.Cartesian3.clone(dir); camera.right = import__430.Cartesian3.clone(right); camera.minimumZoomDistance = 0; scene2.camera = camera; scene2.preloadFlightCamera = import__430.Camera.clone(camera); camera._scene = scene2; scene2.mapMode2D = import__430.MapMode2D.INFINITE_2D; }); it("constructor throws an exception when there is no canvas", function() { expect(function() { return new import__430.Camera(); }).toThrowDeveloperError(); }); it("get view matrix", function() { const viewMatrix = camera.viewMatrix; const position2 = camera.position; const up2 = camera.up; const dir2 = camera.direction; const right2 = camera.right; const rotation = new import__430.Matrix4( right2.x, right2.y, right2.z, 0, up2.x, up2.y, up2.z, 0, -dir2.x, -dir2.y, -dir2.z, 0, 0, 0, 0, 1 ); const translation = new import__430.Matrix4( 1, 0, 0, -position2.x, 0, 1, 0, -position2.y, 0, 0, 1, -position2.z, 0, 0, 0, 1 ); const expected = import__430.Matrix4.multiply(rotation, translation, new import__430.Matrix4()); expect(viewMatrix).toEqual(expected); }); it("get inverse view matrix", function() { const expected = import__430.Matrix4.inverse(camera.viewMatrix, new import__430.Matrix4()); expect(expected).toEqualEpsilon( camera.inverseViewMatrix, import__431.Math.EPSILON15 ); }); it("get inverse transform", function() { camera._setTransform( new import__430.Matrix4( 5, 0, 0, 1, 0, 5, 0, 2, 0, 0, 5, 3, 0, 0, 0, 1 ) ); const expected = import__430.Matrix4.inverseTransformation( camera.transform, new import__430.Matrix4() ); expect(expected).toEqual(camera.inverseTransform); }); it("Computes orthonormal direction, up, and right vectors", function() { camera.direction = new import__430.Cartesian3( -0.32297853365047874, 0.9461560708446421, 0.021761351171635013 ); camera.up = new import__430.Cartesian3( 0.9327219113001013, 0.31839266745173644, -29874778345595487e-26 ); camera.right = new import__430.Cartesian3( 0.0069286549295528715, -0.020297288960790985, 0.9853344956450351 ); expect(import__430.Cartesian3.magnitude(camera.right)).not.toEqualEpsilon( 1, import__431.Math.EPSILON8 ); expect(import__430.Cartesian3.magnitude(camera.up)).not.toEqualEpsilon( 1, import__431.Math.EPSILON8 ); const viewMatrix = camera.viewMatrix; expect(import__430.Cartesian3.magnitude(camera.right)).toEqualEpsilon( 1, import__431.Math.EPSILON8 ); expect(import__430.Cartesian3.magnitude(camera.up)).toEqualEpsilon( 1, import__431.Math.EPSILON8 ); const inverseAffine = import__430.Matrix4.inverseTransformation( viewMatrix, new import__430.Matrix4() ); const inverse = import__430.Matrix4.inverse(viewMatrix, new import__430.Matrix4()); expect(inverseAffine).toEqualEpsilon(inverse, import__431.Math.EPSILON8); }); it("get heading is undefined when morphing", function() { camera._mode = import__430.SceneMode.MORPHING; expect(camera.heading).not.toBeDefined(); }); it("get heading in 2D", function() { camera._mode = import__430.SceneMode.SCENE2D; const positionWC = import__430.Cartesian3.clone(camera.positionWC); const position2 = import__430.Cartesian3.clone(camera.position); const direction = import__430.Cartesian3.clone(camera.direction); const up2 = import__430.Cartesian3.clone(camera.up); const right2 = import__430.Cartesian3.clone(camera.right); const heading = import__431.Math.TWO_PI - Math.atan2(camera.right.y, camera.right.x); expect(camera.heading).toEqual(heading); expect(camera.positionWC).toEqualEpsilon(positionWC, import__431.Math.EPSILON8); expect(camera.position).toEqualEpsilon(position2, import__431.Math.EPSILON8); expect(camera.direction).toEqualEpsilon(direction, import__431.Math.EPSILON8); expect(camera.up).toEqualEpsilon(up2, import__431.Math.EPSILON8); expect(camera.right).toEqualEpsilon(right2, import__431.Math.EPSILON8); }); it("get heading in CV", function() { camera._mode = import__430.SceneMode.COLUMBUS_VIEW; const positionWC = import__430.Cartesian3.clone(camera.positionWC); const position2 = import__430.Cartesian3.clone(camera.position); const direction = import__430.Cartesian3.clone(camera.direction); const up2 = import__430.Cartesian3.clone(camera.up); const right2 = import__430.Cartesian3.clone(camera.right); const heading = import__431.Math.TWO_PI - Math.atan2(camera.right.y, camera.right.x); expect(camera.heading).toEqualEpsilon(heading, import__431.Math.EPSILON8); expect(camera.positionWC).toEqualEpsilon(positionWC, import__431.Math.EPSILON8); expect(camera.position).toEqualEpsilon(position2, import__431.Math.EPSILON8); expect(camera.direction).toEqualEpsilon(direction, import__431.Math.EPSILON8); expect(camera.up).toEqualEpsilon(up2, import__431.Math.EPSILON8); expect(camera.right).toEqualEpsilon(right2, import__431.Math.EPSILON8); }); it("get heading in 3D", function() { camera._mode = import__430.SceneMode.SCENE3D; const ellipsoid = import__430.Ellipsoid.WGS84; const toFixedFrame = import__430.Transforms.eastNorthUpToFixedFrame( camera.position, ellipsoid ); const transform = import__430.Matrix4.getMatrix3(toFixedFrame, new import__430.Matrix3()); import__430.Matrix3.transpose(transform, transform); let right2 = import__430.Matrix3.multiplyByVector( transform, camera.right, new import__430.Cartesian3() ); const heading = import__431.Math.TWO_PI - import__431.Math.zeroToTwoPi(Math.atan2(right2.y, right2.x)); const positionWC = import__430.Cartesian3.clone(camera.positionWC); const position2 = import__430.Cartesian3.clone(camera.position); const direction = import__430.Cartesian3.clone(camera.direction); const up2 = import__430.Cartesian3.clone(camera.up); right2 = import__430.Cartesian3.clone(camera.right); expect(camera.heading).toEqual(heading); expect(camera.positionWC).toEqualEpsilon(positionWC, import__431.Math.EPSILON8); expect(camera.position).toEqualEpsilon(position2, import__431.Math.EPSILON8); expect(camera.direction).toEqualEpsilon(direction, import__431.Math.EPSILON8); expect(camera.up).toEqualEpsilon(up2, import__431.Math.EPSILON8); expect(camera.right).toEqualEpsilon(right2, import__431.Math.EPSILON8); }); it("sets heading in 2D when the map can be rotated", function() { scene2.mapMode2D = import__430.MapMode2D.ROTATE; camera._mode = import__430.SceneMode.SCENE2D; const heading = camera.heading; const positionCartographic = camera.positionCartographic; const newHeading = import__431.Math.toRadians(45); camera.setView({ orientation: { heading: newHeading } }); expect(camera.positionCartographic).toEqual(positionCartographic); expect(camera.heading).not.toEqual(heading); expect(camera.heading).toEqualEpsilon(newHeading, import__431.Math.EPSILON14); }); it("does not set heading in 2D for infinite scrolling mode", function() { camera._mode = import__430.SceneMode.SCENE2D; const heading = camera.heading; const positionCartographic = camera.positionCartographic; const newHeading = import__431.Math.toRadians(45); camera.setView({ orientation: { heading: newHeading } }); expect(camera.positionCartographic).toEqual(positionCartographic); expect(camera.heading).toEqual(heading); }); it("set heading in CV", function() { camera._mode = import__430.SceneMode.COLUMBUS_VIEW; camera.position = import__430.Cartesian3.fromDegrees(-72, 40, 1e5); camera.direction = import__430.Cartesian3.negate( import__430.Cartesian3.normalize(camera.position, new import__430.Cartesian3()), new import__430.Cartesian3() ); camera.up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Z); camera.right = import__430.Cartesian3.cross( camera.direction, camera.up, new import__430.Cartesian3() ); const heading = camera.heading; const positionCartographic = camera.positionCartographic; const newHeading = import__431.Math.toRadians(45); camera.setView({ orientation: { heading: newHeading } }); expect(camera.positionCartographic).toEqual(positionCartographic); expect(camera.heading).not.toEqual(heading); expect(camera.heading).toEqualEpsilon(newHeading, import__431.Math.EPSILON4); }); it("set heading in 3D", function() { camera._mode = import__430.SceneMode.SCENE3D; camera.position = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_X); camera.direction = import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_X, new import__430.Cartesian3()); camera.up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Z); camera.right = import__430.Cartesian3.cross( camera.direction, camera.up, new import__430.Cartesian3() ); const heading = camera.heading; const newHeading = import__431.Math.toRadians(45); camera.setView({ orientation: { heading: newHeading } }); expect(camera.heading).not.toEqual(heading); expect(camera.heading).toEqualEpsilon(newHeading, import__431.Math.EPSILON14); }); it("set heading in 3D (2)", function() { camera._mode = import__430.SceneMode.SCENE3D; camera.position = import__430.Cartesian3.fromDegrees(136, -24, 45e5); import__430.Cartesian3.negate(camera.position, camera.direction); import__430.Cartesian3.normalize(camera.direction, camera.direction); import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Z, camera.up); import__430.Cartesian3.cross(camera.direction, camera.up, camera.right); import__430.Cartesian3.cross(camera.right, camera.direction, camera.up); const positionCartographic = camera.positionCartographic; camera.setView({ orientation: { heading: import__431.Math.PI } }); expect(camera.positionCartographic).toEqual(positionCartographic); expect(camera.heading).toEqualEpsilon(import__431.Math.PI, import__431.Math.EPSILON8); expect(camera.up.z).toBeLessThan(0); camera.setView({ orientation: { heading: import__431.Math.TWO_PI } }); expect(camera.positionCartographic).toEqual(positionCartographic); expect(camera.heading).toEqualEpsilon( import__431.Math.TWO_PI, import__431.Math.EPSILON8 ); expect(camera.up.z).toBeGreaterThan(0); }); it("pitch is undefined when mode is not 3D or Columbus view", function() { camera._mode = import__430.SceneMode.MORPHING; expect(camera.pitch).not.toBeDefined(); }); it("get pitch in CV", function() { camera._mode = import__430.SceneMode.COLUMBUS_VIEW; camera.position = import__430.Cartesian3.fromDegrees(0, 0, 1e5); camera.direction = import__430.Cartesian3.negate( import__430.Cartesian3.normalize(camera.position, new import__430.Cartesian3()), new import__430.Cartesian3() ); camera.up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Z); camera.right = import__430.Cartesian3.cross( camera.direction, camera.up, new import__430.Cartesian3() ); const positionWC = import__430.Cartesian3.clone(camera.positionWC); const position2 = import__430.Cartesian3.clone(camera.position); const direction = import__430.Cartesian3.clone(camera.direction); const up2 = import__430.Cartesian3.clone(camera.up); const right2 = import__430.Cartesian3.clone(camera.right); const pitch = import__431.Math.PI_OVER_TWO - Math.acos(-camera.direction.z); expect(camera.pitch).toEqualEpsilon(pitch, import__431.Math.EPSILON6); expect(camera.positionWC).toEqualEpsilon(positionWC, import__431.Math.EPSILON8); expect(camera.position).toEqualEpsilon(position2, import__431.Math.EPSILON8); expect(camera.direction).toEqualEpsilon(direction, import__431.Math.EPSILON8); expect(camera.up).toEqualEpsilon(up2, import__431.Math.EPSILON8); expect(camera.right).toEqualEpsilon(right2, import__431.Math.EPSILON8); }); it("get pitch in 3D", function() { camera._mode = import__430.SceneMode.SCENE3D; let direction = import__430.Cartesian3.normalize(camera.position, new import__430.Cartesian3()); import__430.Cartesian3.negate(direction, direction); const pitch = import__431.Math.PI_OVER_TWO - Math.acos(-import__430.Cartesian3.dot(camera.direction, direction)); const positionWC = import__430.Cartesian3.clone(camera.positionWC); const position2 = import__430.Cartesian3.clone(camera.position); direction = import__430.Cartesian3.clone(camera.direction); const up2 = import__430.Cartesian3.clone(camera.up); const right2 = import__430.Cartesian3.clone(camera.right); expect(camera.pitch).toEqual(pitch); expect(camera.positionWC).toEqualEpsilon(positionWC, import__431.Math.EPSILON8); expect(camera.position).toEqualEpsilon(position2, import__431.Math.EPSILON8); expect(camera.direction).toEqualEpsilon(direction, import__431.Math.EPSILON8); expect(camera.up).toEqualEpsilon(up2, import__431.Math.EPSILON8); expect(camera.right).toEqualEpsilon(right2, import__431.Math.EPSILON8); }); it("set pitch in CV", function() { camera._mode = import__430.SceneMode.COLUMBUS_VIEW; camera.position = import__430.Cartesian3.fromDegrees(-72, 40, 1e5); camera.direction = import__430.Cartesian3.negate( import__430.Cartesian3.normalize(camera.position, new import__430.Cartesian3()), new import__430.Cartesian3() ); camera.up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Z); camera.right = import__430.Cartesian3.cross( camera.direction, camera.up, new import__430.Cartesian3() ); const pitch = camera.pitch; const positionCartographic = camera.positionCartographic; const newPitch = import__431.Math.toRadians(45); camera.setView({ orientation: { pitch: newPitch } }); expect(camera.positionCartographic).toEqual(positionCartographic); expect(camera.pitch).not.toEqual(pitch); expect(camera.pitch).toEqualEpsilon(newPitch, import__431.Math.EPSILON4); }); it("set pitch in 3D", function() { camera._mode = import__430.SceneMode.SCENE3D; camera.position = import__430.Cartesian3.fromDegrees(-72, 40, 1e5); camera.direction = import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_X, new import__430.Cartesian3()); camera.up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Z); camera.right = import__430.Cartesian3.cross( camera.direction, camera.up, new import__430.Cartesian3() ); const pitch = camera.pitch; const positionCartographic = camera.positionCartographic; const newPitch = import__431.Math.toRadians(45); camera.setView({ orientation: { pitch: newPitch } }); expect(camera.positionCartographic).toEqual(positionCartographic); expect(camera.pitch).not.toEqual(pitch); expect(camera.pitch).toEqualEpsilon(newPitch, import__431.Math.EPSILON14); }); it("get roll in CV", function() { camera._mode = import__430.SceneMode.COLUMBUS_VIEW; camera.position = import__430.Cartesian3.fromDegrees(0, 0, 1e5); camera.direction = import__430.Cartesian3.negate( import__430.Cartesian3.normalize(camera.position, new import__430.Cartesian3()), new import__430.Cartesian3() ); camera.up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Z); camera.right = import__430.Cartesian3.cross( camera.direction, camera.up, new import__430.Cartesian3() ); camera.look(camera.direction, import__431.Math.toRadians(45)); const positionWC = import__430.Cartesian3.clone(camera.positionWC); const position2 = import__430.Cartesian3.clone(camera.position); const direction = import__430.Cartesian3.clone(camera.direction); const up2 = import__430.Cartesian3.clone(camera.up); const right2 = import__430.Cartesian3.clone(camera.right); const roll = import__431.Math.zeroToTwoPi(-import__431.Math.toRadians(45)); expect(camera.roll).toEqualEpsilon(roll, import__431.Math.EPSILON6); expect(camera.positionWC).toEqualEpsilon(positionWC, import__431.Math.EPSILON8); expect(camera.position).toEqualEpsilon(position2, import__431.Math.EPSILON8); expect(camera.direction).toEqualEpsilon(direction, import__431.Math.EPSILON8); expect(camera.up).toEqualEpsilon(up2, import__431.Math.EPSILON8); expect(camera.right).toEqualEpsilon(right2, import__431.Math.EPSILON8); }); it("get roll in 3D", function() { camera._mode = import__430.SceneMode.SCENE3D; const ellipsoid = import__430.Ellipsoid.WGS84; camera.position = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_X); import__430.Cartesian3.multiplyByScalar( camera.position, ellipsoid.maximumRadius + 100, camera.position ); camera.direction = new import__430.Cartesian3(-1, 0, 1); import__430.Cartesian3.normalize(camera.direction, camera.direction); camera.right = import__430.Cartesian3.cross( camera.direction, import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3() ); import__430.Cartesian3.normalize(camera.right, camera.right); camera.up = import__430.Cartesian3.cross( camera.right, camera.direction, new import__430.Cartesian3() ); const toFixedFrame = import__430.Transforms.eastNorthUpToFixedFrame( camera.position, ellipsoid ); const transform = import__430.Matrix4.getMatrix3(toFixedFrame, new import__430.Matrix3()); import__430.Matrix3.transpose(transform, transform); let right2 = import__430.Matrix3.multiplyByVector( transform, camera.right, new import__430.Cartesian3() ); const roll = import__431.Math.TWO_PI - Math.atan2(right2.z, right2.x); const positionWC = import__430.Cartesian3.clone(camera.positionWC); const position2 = import__430.Cartesian3.clone(camera.position); const direction = import__430.Cartesian3.clone(camera.direction); const up2 = import__430.Cartesian3.clone(camera.up); right2 = import__430.Cartesian3.clone(camera.right); expect(camera.roll).toEqual(roll); expect(camera.positionWC).toEqualEpsilon(positionWC, import__431.Math.EPSILON8); expect(camera.position).toEqualEpsilon(position2, import__431.Math.EPSILON8); expect(camera.direction).toEqualEpsilon(direction, import__431.Math.EPSILON8); expect(camera.up).toEqualEpsilon(up2, import__431.Math.EPSILON8); expect(camera.right).toEqualEpsilon(right2, import__431.Math.EPSILON8); }); it("get roll returns correct value past 90 degrees", function() { const roll = import__431.Math.toRadians(110); camera.setView({ destination: import__430.Cartesian3.fromDegrees(-72, 40, 20), orientation: { heading: 0, pitch: 0, roll } }); expect(camera.roll).toEqualEpsilon(roll, import__431.Math.EPSILON14); }); it("set roll in CV", function() { camera._mode = import__430.SceneMode.COLUMBUS_VIEW; camera.position = import__430.Cartesian3.fromDegrees(-72, 40, 1e5); camera.direction = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Y); camera.up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Z); camera.right = import__430.Cartesian3.cross( camera.direction, camera.up, new import__430.Cartesian3() ); const roll = camera.roll; const positionCartographic = camera.positionCartographic; const newRoll = import__431.Math.PI_OVER_FOUR; camera.setView({ orientation: { pitch: camera.pitch, roll: newRoll, heading: camera.heading } }); expect(camera.positionCartographic).toEqual(positionCartographic); expect(camera.roll).not.toEqual(roll); expect(camera.roll).toEqualEpsilon(newRoll, import__431.Math.EPSILON6); }); it("set roll in 3D", function() { camera._mode = import__430.SceneMode.SCENE3D; camera.position = import__430.Cartesian3.fromDegrees(-72, 40, 1e5); camera.direction = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Z); camera.up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_X); camera.right = import__430.Cartesian3.cross( camera.direction, camera.up, new import__430.Cartesian3() ); const roll = camera.roll; const positionCartographic = import__430.Cartographic.clone( camera.positionCartographic ); const newRoll = import__431.Math.PI_OVER_FOUR; camera.setView({ orientation: { pitch: camera.pitch, roll: newRoll, heading: camera.heading } }); expect(camera.positionCartographic).toEqual(positionCartographic); expect(camera.roll).not.toEqual(roll); expect(camera.roll).toEqualEpsilon(newRoll, import__431.Math.EPSILON6); }); it("update throws without mode", function() { expect(function() { camera.update(); }).toThrowDeveloperError(); }); it("update throws with frustum not supported in given mode", function() { camera.frustum = new import__430.PerspectiveFrustum(); expect(function() { camera.update(import__430.SceneMode.SCENE2D); }).toThrowDeveloperError(); camera.frustum = new import__430.OrthographicOffCenterFrustum(); expect(function() { camera.update(import__430.SceneMode.SCENE3D); }).toThrowDeveloperError(); expect(function() { camera.update(import__430.SceneMode.COLUMBUS_VIEW); }).toThrowDeveloperError(); }); it("setView with cartesian in 2D", function() { const ellipsoid = import__430.Ellipsoid.WGS84; const projection = new import__430.GeographicProjection(ellipsoid); const maxRadii = ellipsoid.maximumRadius; camera._mode = import__430.SceneMode.SCENE2D; camera._projection = projection; const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.right = maxRadii * Math.PI; frustum.left = -frustum.right; frustum.top = frustum.right * (scene2.drawingBufferHeight / scene2.drawingBufferWidth); frustum.bottom = -frustum.top; frustum.near = 0.01 * maxRadii; frustum.far = 60 * maxRadii; camera.frustum = frustum; const ratio = frustum.top / frustum.right; const cartesian = import__430.Cartesian3.fromDegrees(-75, 42, 100); camera.setView({ destination: cartesian }); const cart = ellipsoid.cartesianToCartographic(cartesian); expect(camera.positionCartographic).toEqualEpsilon( cart, import__431.Math.EPSILON6 ); expect(camera.direction).toEqualEpsilon( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3()), import__431.Math.EPSILON6 ); expect(camera.up).toEqualEpsilon(import__430.Cartesian3.UNIT_Y, import__431.Math.EPSILON6); expect(camera.right).toEqualEpsilon(import__430.Cartesian3.UNIT_X, import__431.Math.EPSILON6); expect(frustum.right - frustum.left).toEqualEpsilon( cart.height, import__431.Math.EPSILON6 ); expect(frustum.top / frustum.right).toEqual(ratio); }); it("setView with cartesian in Columbus View", function() { const ellipsoid = import__430.Ellipsoid.WGS84; const projection = new import__430.GeographicProjection(ellipsoid); camera._mode = import__430.SceneMode.COLUMBUS_VIEW; camera._projection = projection; const cartesian = import__430.Cartesian3.fromDegrees(-75, 42, 100); camera.setView({ destination: cartesian }); const cart = ellipsoid.cartesianToCartographic(cartesian); expect(camera.positionCartographic).toEqualEpsilon( cart, import__431.Math.EPSILON11 ); expect(camera.direction).toEqualEpsilon( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3()), import__431.Math.EPSILON6 ); expect(camera.up).toEqualEpsilon(import__430.Cartesian3.UNIT_Y, import__431.Math.EPSILON6); expect(camera.right).toEqualEpsilon(import__430.Cartesian3.UNIT_X, import__431.Math.EPSILON6); }); it("setView with cartesian in 3D", function() { const ellipsoid = import__430.Ellipsoid.WGS84; const projection = new import__430.GeographicProjection(ellipsoid); camera._mode = import__430.SceneMode.SCENE3D; camera._projection = projection; const cartesian = import__430.Cartesian3.fromDegrees(-75, 0, 100); camera.setView({ destination: cartesian }); expect(camera.positionCartographic).toEqualEpsilon( ellipsoid.cartesianToCartographic(cartesian), import__431.Math.EPSILON6 ); expect(camera.direction).toEqualEpsilon( import__430.Cartesian3.normalize( import__430.Cartesian3.negate(camera.position, new import__430.Cartesian3()), new import__430.Cartesian3() ), import__431.Math.EPSILON6 ); expect(camera.up).toEqualEpsilon(import__430.Cartesian3.UNIT_Z, import__431.Math.EPSILON6); expect(camera.right).toEqualEpsilon( import__430.Cartesian3.cross(camera.direction, camera.up, new import__430.Cartesian3()), import__431.Math.EPSILON6 ); }); it("setView with cartesian in Columbus View and orthographic frustum", function() { const ellipsoid = import__430.Ellipsoid.WGS84; const projection = new import__430.GeographicProjection(ellipsoid); camera._mode = import__430.SceneMode.COLUMBUS_VIEW; camera._projection = projection; camera.frustum = new import__430.OrthographicFrustum(); camera.frustum.aspectRatio = scene2.drawingBufferWidth / scene2.drawingBufferHeight; camera.frustum.width = camera.positionCartographic.height; const cartesian = import__430.Cartesian3.fromDegrees(-75, 42, 100); camera.setView({ destination: cartesian }); const cart = ellipsoid.cartesianToCartographic(cartesian); expect(camera.positionCartographic).toEqualEpsilon( cart, import__431.Math.EPSILON11 ); expect(camera.direction).toEqualEpsilon( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3()), import__431.Math.EPSILON6 ); expect(camera.up).toEqualEpsilon(import__430.Cartesian3.UNIT_Y, import__431.Math.EPSILON6); expect(camera.right).toEqualEpsilon(import__430.Cartesian3.UNIT_X, import__431.Math.EPSILON6); expect(camera.frustum.width).toEqual(cart.height); }); it("setView with cartesian in 3D and orthographic frustum", function() { const ellipsoid = import__430.Ellipsoid.WGS84; const projection = new import__430.GeographicProjection(ellipsoid); camera._mode = import__430.SceneMode.SCENE3D; camera._projection = projection; camera.frustum = new import__430.OrthographicFrustum(); camera.frustum.aspectRatio = scene2.drawingBufferWidth / scene2.drawingBufferHeight; camera.frustum.width = camera.positionCartographic.height; const cartesian = import__430.Cartesian3.fromDegrees(-75, 0, 100); camera.setView({ destination: cartesian }); const cart = ellipsoid.cartesianToCartographic(cartesian); expect(camera.positionCartographic).toEqualEpsilon( cart, import__431.Math.EPSILON6 ); expect(camera.direction).toEqualEpsilon( import__430.Cartesian3.normalize( import__430.Cartesian3.negate(camera.position, new import__430.Cartesian3()), new import__430.Cartesian3() ), import__431.Math.EPSILON6 ); expect(camera.up).toEqualEpsilon(import__430.Cartesian3.UNIT_Z, import__431.Math.EPSILON6); expect(camera.right).toEqualEpsilon( import__430.Cartesian3.cross(camera.direction, camera.up, new import__430.Cartesian3()), import__431.Math.EPSILON6 ); expect(camera.frustum.width).toEqual(cart.height); }); it("setView right rotation order", function() { const position2 = import__430.Cartesian3.fromDegrees(-117.16, 32.71, 0); const heading = import__431.Math.toRadians(180); const pitch = import__431.Math.toRadians(0); const roll = import__431.Math.toRadians(45); camera.setView({ destination: position2, orientation: { heading, pitch, roll } }); expect(camera.position).toEqualEpsilon(position2, import__431.Math.EPSILON6); expect(camera.heading).toEqualEpsilon(heading, import__431.Math.EPSILON6); expect(camera.pitch).toEqualEpsilon(pitch, import__431.Math.EPSILON6); expect(camera.roll).toEqualEpsilon(roll, import__431.Math.EPSILON6); }); it("setView (1)", function() { const position2 = import__430.Cartesian3.fromDegrees(-117.16, 32.71, 0); let heading = import__431.Math.toRadians(45); const pitch = import__431.Math.toRadians(-50); const roll = import__431.Math.toRadians(45); camera.setView({ destination: position2, orientation: { heading, pitch, roll } }); expect(camera.position).toEqualEpsilon(position2, import__431.Math.EPSILON6); expect(camera.heading).toEqualEpsilon(heading, import__431.Math.EPSILON6); expect(camera.pitch).toEqualEpsilon(pitch, import__431.Math.EPSILON6); expect(camera.roll).toEqualEpsilon(roll, import__431.Math.EPSILON6); heading = import__431.Math.toRadians(200); camera.setView({ orientation: { pitch: camera.pitch, roll: camera.roll, heading } }); expect(camera.position).toEqualEpsilon(position2, import__431.Math.EPSILON6); expect(camera.heading).toEqualEpsilon(heading, import__431.Math.EPSILON6); expect(camera.pitch).toEqualEpsilon(pitch, import__431.Math.EPSILON6); expect(camera.roll).toEqualEpsilon(roll, import__431.Math.EPSILON6); }); it("setView (2)", function() { const position2 = import__430.Cartesian3.fromDegrees(-117.16, 32.71, 0); const heading = import__431.Math.toRadians(45); let pitch = import__431.Math.toRadians(50); const roll = import__431.Math.toRadians(45); camera.setView({ destination: position2, orientation: { heading, pitch, roll } }); expect(camera.position).toEqualEpsilon(position2, import__431.Math.EPSILON6); expect(camera.heading).toEqualEpsilon(heading, import__431.Math.EPSILON6); expect(camera.pitch).toEqualEpsilon(pitch, import__431.Math.EPSILON6); expect(camera.roll).toEqualEpsilon(roll, import__431.Math.EPSILON6); pitch = import__431.Math.toRadians(-50); camera.setView({ orientation: { pitch, roll: camera.roll, heading: camera.heading } }); expect(camera.position).toEqualEpsilon(position2, import__431.Math.EPSILON6); expect(camera.heading).toEqualEpsilon(heading, import__431.Math.EPSILON6); expect(camera.pitch).toEqualEpsilon(pitch, import__431.Math.EPSILON6); expect(camera.roll).toEqualEpsilon(roll, import__431.Math.EPSILON6); }); it("setView (3)", function() { const position2 = import__430.Cartesian3.fromDegrees(-117.16, 32.71, 0); const heading = import__431.Math.toRadians(45); const pitch = import__431.Math.toRadians(50); let roll = import__431.Math.toRadians(45); camera.setView({ destination: position2, orientation: { heading, pitch, roll } }); expect(camera.position).toEqualEpsilon(position2, import__431.Math.EPSILON6); expect(camera.heading).toEqualEpsilon(heading, import__431.Math.EPSILON6); expect(camera.pitch).toEqualEpsilon(pitch, import__431.Math.EPSILON6); expect(camera.roll).toEqualEpsilon(roll, import__431.Math.EPSILON6); roll = import__431.Math.toRadians(200); camera.setView({ orientation: { roll, heading: camera.heading, pitch: camera.pitch } }); expect(camera.position).toEqualEpsilon(position2, import__431.Math.EPSILON6); expect(camera.heading).toEqualEpsilon(heading, import__431.Math.EPSILON6); expect(camera.pitch).toEqualEpsilon(pitch, import__431.Math.EPSILON6); expect(camera.roll).toEqualEpsilon(roll, import__431.Math.EPSILON6); }); it("setView with direction, up", function() { scene2.mode = import__430.SceneMode.SCENE3D; const direction = import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3()); const up2 = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Y); const options = { destination: import__430.Cartesian3.fromDegrees(-117.16, 32.71, 0), orientation: { direction, up: up2 }, duration: 1e-3 }; camera.setView(options); expect(camera.direction).toEqualEpsilon(direction, import__431.Math.EPSILON6); expect(camera.up).toEqualEpsilon(up2, import__431.Math.EPSILON6); }); it("worldToCameraCoordinates throws without cartesian", function() { expect(function() { camera.worldToCameraCoordinates(); }).toThrowDeveloperError(); }); it("worldToCameraCoordinates transforms to the cameras reference frame", function() { camera._setTransform( new import__430.Matrix4( 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 ) ); expect(camera.worldToCameraCoordinates(import__430.Cartesian4.UNIT_X)).toEqual( import__430.Cartesian4.UNIT_Z ); }); it("worldToCameraCoordinatesPoint throws without cartesian", function() { expect(function() { camera.worldToCameraCoordinatesPoint(); }).toThrowDeveloperError(); }); it("worldToCameraCoordinatesPoint transforms to the cameras reference frame", function() { camera._setTransform( new import__430.Matrix4( 0, 0, 1, 10, 1, 0, 0, 20, 0, 1, 0, 30, 0, 0, 0, 1 ) ); const expected = import__430.Cartesian3.add( import__430.Matrix4.getColumn(camera.inverseTransform, 3, new import__430.Cartesian4()), import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3() ); expect(camera.worldToCameraCoordinatesPoint(import__430.Cartesian3.UNIT_X)).toEqual( expected ); }); it("worldToCameraCoordinatesVector throws without cartesian", function() { expect(function() { camera.worldToCameraCoordinatesVector(); }).toThrowDeveloperError(); }); it("worldToCameraCoordinatesVector transforms to the cameras reference frame", function() { camera._setTransform( new import__430.Matrix4( 0, 0, 1, 10, 1, 0, 0, 20, 0, 1, 0, 30, 0, 0, 0, 1 ) ); expect(camera.worldToCameraCoordinatesVector(import__430.Cartesian3.UNIT_X)).toEqual( import__430.Cartesian3.UNIT_Z ); }); it("cameraToWorldCoordinates throws without cartesian", function() { expect(function() { camera.cameraToWorldCoordinates(); }).toThrowDeveloperError(); }); it("cameraToWorldCoordinates transforms from the cameras reference frame", function() { camera._setTransform( new import__430.Matrix4( 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 ) ); expect(camera.cameraToWorldCoordinates(import__430.Cartesian4.UNIT_Z)).toEqual( import__430.Cartesian4.UNIT_X ); }); it("cameraToWorldCoordinatesPoint throws without cartesian", function() { expect(function() { camera.cameraToWorldCoordinatesPoint(); }).toThrowDeveloperError(); }); it("cameraToWorldCoordinatesPoint transforms from the cameras reference frame", function() { camera._setTransform( new import__430.Matrix4( 0, 0, 1, 10, 1, 0, 0, 20, 0, 1, 0, 30, 0, 0, 0, 1 ) ); const expected = import__430.Cartesian3.add( import__430.Cartesian3.UNIT_X, import__430.Matrix4.getColumn(camera.transform, 3, new import__430.Cartesian4()), new import__430.Cartesian3() ); expect(camera.cameraToWorldCoordinatesPoint(import__430.Cartesian3.UNIT_Z)).toEqual( expected ); }); it("cameraToWorldCoordinatesVector throws without cartesian", function() { expect(function() { camera.cameraToWorldCoordinatesVector(); }).toThrowDeveloperError(); }); it("cameraToWorldCoordinatesVector transforms from the cameras reference frame", function() { camera._setTransform( new import__430.Matrix4( 0, 0, 1, 10, 1, 0, 0, 20, 0, 1, 0, 30, 0, 0, 0, 1 ) ); expect(camera.cameraToWorldCoordinatesVector(import__430.Cartesian3.UNIT_Z)).toEqual( import__430.Cartesian3.UNIT_X ); }); it("move throws without an axis", function() { expect(function() { expect(camera.move()); }).toThrowDeveloperError(); }); it("moves", function() { const direction = import__430.Cartesian3.normalize( new import__430.Cartesian3(1, 1, 0), new import__430.Cartesian3() ); camera.move(direction, moveAmount); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(direction.x * moveAmount, direction.y * moveAmount, 1), import__431.Math.EPSILON10 ); expect(camera.up).toEqual(up); expect(camera.direction).toEqual(dir); expect(camera.right).toEqual(right); }); it("moves up", function() { camera.moveUp(moveAmount); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(0, moveAmount, 1), import__431.Math.EPSILON10 ); expect(camera.up).toEqual(up); expect(camera.direction).toEqual(dir); expect(camera.right).toEqual(right); }); it("moves down", function() { camera.moveDown(moveAmount); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(0, -moveAmount, 1), import__431.Math.EPSILON10 ); expect(camera.up).toEqual(up); expect(camera.direction).toEqual(dir); expect(camera.right).toEqual(right); }); it("moves right", function() { camera.moveRight(moveAmount); expect(camera.position).toEqual( new import__430.Cartesian3(moveAmount, 0, 1), import__431.Math.EPSILON10 ); expect(camera.up).toEqual(up); expect(camera.direction).toEqual(dir); expect(camera.right).toEqual(right); }); it("moves left", function() { camera.moveLeft(moveAmount); expect(camera.position).toEqual( new import__430.Cartesian3(-moveAmount, 0, 1), import__431.Math.EPSILON10 ); expect(camera.up).toEqual(up); expect(camera.direction).toEqual(dir); expect(camera.right).toEqual(right); }); it("moves forward", function() { camera.moveForward(moveAmount); expect(camera.position).toEqual( new import__430.Cartesian3(0, 0, 1 - moveAmount), import__431.Math.EPSILON10 ); expect(camera.up).toEqual(up); expect(camera.direction).toEqual(dir); expect(camera.right).toEqual(right); }); it("moves backward", function() { camera.moveBackward(moveAmount); expect(camera.position).toEqual( new import__430.Cartesian3(0, 0, 1 + moveAmount), import__431.Math.EPSILON10 ); expect(camera.up).toEqual(up); expect(camera.direction).toEqual(dir); expect(camera.right).toEqual(right); }); it("moves forward in 2D mode zooms in camera instead of moving it", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; camera.frustum = frustum; camera.update(import__430.SceneMode.SCENE2D); const oldCamera = import__430.Camera.clone(camera); camera.moveForward(moveAmount); expect(camera.position).toEqual(oldCamera.position, import__431.Math.EPSILON10); expect(camera.frustum).not.toEqual(oldCamera.frustum); expect(camera.up).toEqual(up); expect(camera.direction).toEqual(dir); expect(camera.right).toEqual(right); }); it("moves backward in 2D mode zooms out camera instead of moving it", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; camera.frustum = frustum; camera.update(import__430.SceneMode.SCENE2D); const oldCamera = import__430.Camera.clone(camera); camera.moveBackward(moveAmount); expect(camera.position).toEqual(oldCamera.position, import__431.Math.EPSILON10); expect(camera.frustum).not.toEqual(oldCamera.frustum); expect(camera.up).toEqual(up); expect(camera.direction).toEqual(dir); expect(camera.right).toEqual(right); }); it("move clamps position in 2D", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; camera.frustum = frustum; camera.update(import__430.SceneMode.SCENE2D); const max = scene2.mapProjection.project( new import__430.Cartographic(Math.PI, import__431.Math.toRadians(85.05112878)) ); const factor = 1e3; const dx = max.x * factor; const dy = max.y * factor; camera.moveUp(dy); camera.moveRight(dx); expect(camera.position.x).toBeLessThan(dx); expect(camera.position.y).toBeLessThan(dy); camera.moveDown(dy); camera.moveLeft(dx); expect(camera.position.x).toBeGreaterThan(-dx); expect(camera.position.y).toBeGreaterThan(-dy); }); it("look throws without an axis", function() { expect(function() { expect(camera.look()); }).toThrowDeveloperError(); }); it("looks", function() { camera.look(import__430.Cartesian3.UNIT_X, import__431.Math.PI); expect(camera.position).toEqual(position); expect(camera.right).toEqual(right); expect(camera.up).toEqualEpsilon( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Y, new import__430.Cartesian3()), import__431.Math.EPSILON10 ); expect(camera.direction).toEqualEpsilon( import__430.Cartesian3.UNIT_Z, import__431.Math.EPSILON10 ); }); it("looks left", function() { camera.lookLeft(turnAmount); expect(camera.position).toEqual(position); expect(camera.up).toEqualEpsilon(up, import__431.Math.EPSILON15); expect(camera.direction).toEqualEpsilon( import__430.Cartesian3.negate(right, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); expect(camera.right).toEqualEpsilon(dir, import__431.Math.EPSILON15); }); it("looks right", function() { camera.lookRight(turnAmount); expect(camera.position).toEqual(position); expect(camera.up).toEqualEpsilon(up, import__431.Math.EPSILON15); expect(camera.direction).toEqualEpsilon(right, import__431.Math.EPSILON15); expect(camera.right).toEqualEpsilon( import__430.Cartesian3.negate(dir, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); }); it("looks up", function() { camera.lookUp(turnAmount); expect(camera.position).toEqual(position); expect(camera.right).toEqualEpsilon(right, import__431.Math.EPSILON15); expect(camera.direction).toEqualEpsilon(up, import__431.Math.EPSILON15); expect(camera.up).toEqualEpsilon( import__430.Cartesian3.negate(dir, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); }); it("looks down", function() { camera.lookDown(turnAmount); expect(camera.position).toEqual(position); expect(camera.right).toEqualEpsilon(right, import__431.Math.EPSILON15); expect(camera.direction).toEqualEpsilon( import__430.Cartesian3.negate(up, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); expect(camera.up).toEqualEpsilon(dir, import__431.Math.EPSILON15); }); it("looks left in 2D mode does not modify the camera at all", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; camera.frustum = frustum; camera.update(import__430.SceneMode.SCENE2D); const oldCamera = import__430.Camera.clone(camera); camera.lookLeft(turnAmount); expect(camera.position).toEqual(oldCamera.position); expect(camera.up).toEqualEpsilon(oldCamera.up, import__431.Math.EPSILON15); expect(camera.direction).toEqualEpsilon( oldCamera.direction, import__431.Math.EPSILON15 ); expect(camera.right).toEqualEpsilon(oldCamera.right, import__431.Math.EPSILON15); }); it("looks right in 2D mode does not modify the camera at all", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; camera.frustum = frustum; camera.update(import__430.SceneMode.SCENE2D); const oldCamera = import__430.Camera.clone(camera); camera.lookRight(turnAmount); expect(camera.position).toEqual(oldCamera.position); expect(camera.up).toEqualEpsilon(oldCamera.up, import__431.Math.EPSILON15); expect(camera.direction).toEqualEpsilon( oldCamera.direction, import__431.Math.EPSILON15 ); expect(camera.right).toEqualEpsilon(oldCamera.right, import__431.Math.EPSILON15); }); it("looks up in 2D mode does not modify the camera at all", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; camera.frustum = frustum; camera.update(import__430.SceneMode.SCENE2D); const oldCamera = import__430.Camera.clone(camera); camera.lookUp(turnAmount); expect(camera.position).toEqual(oldCamera.position); expect(camera.up).toEqualEpsilon(oldCamera.up, import__431.Math.EPSILON15); expect(camera.direction).toEqualEpsilon( oldCamera.direction, import__431.Math.EPSILON15 ); expect(camera.right).toEqualEpsilon(oldCamera.right, import__431.Math.EPSILON15); }); it("looks down in 2D mode does not modify the camera at all", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; camera.frustum = frustum; camera.update(import__430.SceneMode.SCENE2D); const oldCamera = import__430.Camera.clone(camera); camera.lookDown(turnAmount); expect(camera.position).toEqual(oldCamera.position); expect(camera.up).toEqualEpsilon(oldCamera.up, import__431.Math.EPSILON15); expect(camera.direction).toEqualEpsilon( oldCamera.direction, import__431.Math.EPSILON15 ); expect(camera.right).toEqualEpsilon(oldCamera.right, import__431.Math.EPSILON15); }); it("twists left", function() { camera.twistLeft(import__431.Math.PI_OVER_TWO); expect(camera.position).toEqual(position); expect(camera.direction).toEqualEpsilon(dir, import__431.Math.EPSILON15); expect(camera.up).toEqualEpsilon( import__430.Cartesian3.negate(right, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); expect(camera.right).toEqualEpsilon(up, import__431.Math.EPSILON15); }); it("twists right", function() { camera.twistRight(import__431.Math.PI_OVER_TWO); expect(camera.position).toEqual(position); expect(camera.direction).toEqualEpsilon(dir, import__431.Math.EPSILON15); expect(camera.up).toEqualEpsilon(right, import__431.Math.EPSILON14); expect(camera.right).toEqualEpsilon( import__430.Cartesian3.negate(up, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); }); it("rotate throws without an axis", function() { expect(function() { expect(camera.rotate()); }).toThrowDeveloperError(); }); it("rotates up", function() { camera.rotateUp(rotateAmount); expect(camera.up).toEqualEpsilon( import__430.Cartesian3.negate(dir, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); expect(camera.direction).toEqualEpsilon(up, import__431.Math.EPSILON15); expect(camera.right).toEqualEpsilon(right, import__431.Math.EPSILON15); expect(camera.position).toEqualEpsilon( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Y, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); }); it("rotates up with constrained axis 0", function() { camera.constrainedAxis = import__430.Cartesian3.UNIT_Y; camera.rotateUp(rotateAmount); expect(camera.up).toEqualEpsilon( import__430.Cartesian3.negate(dir, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); expect(camera.direction).toEqualEpsilon(up, import__431.Math.EPSILON15); expect(camera.right).toEqualEpsilon(right, import__431.Math.EPSILON15); expect(camera.position).toEqualEpsilon( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Y, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); }); it("rotates up with constrained axis 1", function() { camera.up = import__430.Cartesian3.negate(dir, new import__430.Cartesian3()); camera.direction = right; camera.right = import__430.Cartesian3.cross( camera.direction, camera.up, new import__430.Cartesian3() ); camera.constrainedAxis = import__430.Cartesian3.UNIT_Y; camera.rotateUp(rotateAmount); expect(camera.up).toEqualEpsilon( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Y, new import__430.Cartesian3()), import__431.Math.EPSILON14 ); expect(camera.direction).toEqualEpsilon(right, import__431.Math.EPSILON15); expect(camera.right).toEqualEpsilon(dir, import__431.Math.EPSILON15); expect(camera.position).toEqualEpsilon( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Y, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); }); it("rotates down", function() { camera.rotateDown(rotateAmount); expect(camera.up).toEqualEpsilon(dir, import__431.Math.EPSILON15); expect(camera.direction).toEqualEpsilon( import__430.Cartesian3.negate(up, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); expect(camera.right).toEqualEpsilon(right, import__431.Math.EPSILON15); expect(camera.position).toEqualEpsilon( import__430.Cartesian3.UNIT_Y, import__431.Math.EPSILON15 ); }); it("rotates down with constrained axis 0 ", function() { camera.constrainedAxis = import__430.Cartesian3.UNIT_Y; camera.rotateDown(rotateAmount); expect(camera.up).toEqualEpsilon(dir, import__431.Math.EPSILON15); expect(camera.direction).toEqualEpsilon( import__430.Cartesian3.negate(up, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); expect(camera.right).toEqualEpsilon(right, import__431.Math.EPSILON15); expect(camera.position).toEqualEpsilon( import__430.Cartesian3.UNIT_Y, import__431.Math.EPSILON15 ); }); it("rotates down with constrained axis 1", function() { camera.up = import__430.Cartesian3.negate(dir, new import__430.Cartesian3()); camera.direction = right; camera.right = import__430.Cartesian3.cross( camera.direction, camera.up, new import__430.Cartesian3() ); camera.constrainedAxis = import__430.Cartesian3.UNIT_Y; camera.rotateDown(rotateAmount); expect(camera.up).toEqualEpsilon(import__430.Cartesian3.UNIT_Y, import__431.Math.EPSILON15); expect(camera.direction).toEqualEpsilon(right, import__431.Math.EPSILON15); expect(camera.right).toEqualEpsilon( import__430.Cartesian3.negate(dir, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); expect(camera.position).toEqualEpsilon( import__430.Cartesian3.UNIT_Y, import__431.Math.EPSILON15 ); }); it("rotates left", function() { camera.rotateLeft(rotateAmount); expect(camera.up).toEqualEpsilon(up, import__431.Math.EPSILON15); expect(camera.direction).toEqualEpsilon(right, import__431.Math.EPSILON15); expect(camera.right).toEqualEpsilon( import__430.Cartesian3.negate(dir, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); expect(camera.position).toEqualEpsilon( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_X, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); }); it("rotates left with contrained axis", function() { camera.constrainedAxis = import__430.Cartesian3.UNIT_Z; camera.rotateLeft(rotateAmount); expect(camera.up).toEqualEpsilon(import__430.Cartesian3.UNIT_X, import__431.Math.EPSILON15); expect(camera.direction).toEqualEpsilon( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); expect(camera.right).toEqualEpsilon( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Y, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); expect(camera.position).toEqualEpsilon( import__430.Cartesian3.UNIT_Z, import__431.Math.EPSILON15 ); }); it("rotates right", function() { camera.rotateRight(rotateAmount); expect(camera.up).toEqualEpsilon(up, import__431.Math.EPSILON15); expect(camera.direction).toEqualEpsilon( import__430.Cartesian3.negate(right, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); expect(camera.right).toEqualEpsilon(dir, import__431.Math.EPSILON15); expect(camera.position).toEqualEpsilon( import__430.Cartesian3.UNIT_X, import__431.Math.EPSILON15 ); }); it("rotates right with contrained axis", function() { camera.constrainedAxis = import__430.Cartesian3.UNIT_Z; camera.rotateRight(rotateAmount); expect(camera.up).toEqualEpsilon( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_X, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); expect(camera.direction).toEqualEpsilon( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); expect(camera.right).toEqualEpsilon( import__430.Cartesian3.UNIT_Y, import__431.Math.EPSILON15 ); expect(camera.position).toEqualEpsilon( import__430.Cartesian3.UNIT_Z, import__431.Math.EPSILON15 ); }); it("rotates", function() { const axis = import__430.Cartesian3.normalize( new import__430.Cartesian3( Math.cos(import__431.Math.PI_OVER_FOUR), Math.sin(import__431.Math.PI_OVER_FOUR), 0 ), new import__430.Cartesian3() ); const angle = import__431.Math.PI_OVER_TWO; camera.rotate(axis, angle); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(-axis.x, axis.y, 0), import__431.Math.EPSILON15 ); expect(camera.direction).toEqualEpsilon( import__430.Cartesian3.negate( import__430.Cartesian3.normalize(camera.position, new import__430.Cartesian3()), new import__430.Cartesian3() ), import__431.Math.EPSILON15 ); expect(camera.right).toEqualEpsilon( import__430.Cartesian3.normalize(new import__430.Cartesian3(0.5, 0.5, axis.x), new import__430.Cartesian3()), import__431.Math.EPSILON15 ); expect(camera.up).toEqualEpsilon( import__430.Cartesian3.cross(camera.right, camera.direction, new import__430.Cartesian3()), import__431.Math.EPSILON15 ); }); it("rotate past constrained axis stops at constained axis", function() { camera.constrainedAxis = import__430.Cartesian3.UNIT_Y; camera.rotateUp(Math.PI); expect(camera.up).toEqualEpsilon( import__430.Cartesian3.negate(dir, new import__430.Cartesian3()), import__431.Math.EPSILON4 ); expect(camera.direction).toEqualEpsilon(up, import__431.Math.EPSILON4); expect(camera.right).toEqualEpsilon(right, import__431.Math.EPSILON4); expect(camera.position).toEqualEpsilon( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Y, new import__430.Cartesian3()), import__431.Math.EPSILON4 ); }); it("zooms out 2D", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; camera.frustum = frustum; camera.update(import__430.SceneMode.SCENE2D); camera.zoomOut(zoomAmount); expect(camera.frustum.right).toEqualEpsilon(2.5, import__431.Math.EPSILON10); expect(camera.frustum.left).toEqual(-2.5, import__431.Math.EPSILON10); expect(camera.frustum.top).toEqual(1.25, import__431.Math.EPSILON10); expect(camera.frustum.bottom).toEqual(-1.25, import__431.Math.EPSILON10); }); it("zooms out 2D when frustrum has greater height than width", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -1; frustum.right = 1; frustum.top = 2; frustum.bottom = -2; camera.frustum = frustum; camera.update(import__430.SceneMode.SCENE2D); camera.zoomOut(zoomAmount); expect(camera.frustum.right).toEqualEpsilon(1.25, import__431.Math.EPSILON10); expect(camera.frustum.left).toEqual(-1.25, import__431.Math.EPSILON10); expect(camera.frustum.top).toEqual(2.5, import__431.Math.EPSILON10); expect(camera.frustum.bottom).toEqual(-2.5, import__431.Math.EPSILON10); }); it("zooms in 2D", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; camera.frustum = frustum; camera.update(import__430.SceneMode.SCENE2D); camera.zoomIn(zoomAmount); expect(camera.frustum.right).toEqualEpsilon(1.5, import__431.Math.EPSILON10); expect(camera.frustum.left).toEqual(-1.5, import__431.Math.EPSILON10); expect(camera.frustum.top).toEqual(0.75, import__431.Math.EPSILON10); expect(camera.frustum.bottom).toEqual(-0.75, import__431.Math.EPSILON10); }); it("zooms in 2D when frustrum has greater height than width", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -1; frustum.right = 1; frustum.top = 2; frustum.bottom = -2; camera.frustum = frustum; camera.update(import__430.SceneMode.SCENE2D); camera.zoomIn(zoomAmount); expect(camera.frustum.right).toEqualEpsilon(0.75, import__431.Math.EPSILON10); expect(camera.frustum.left).toEqual(-0.75, import__431.Math.EPSILON10); expect(camera.frustum.top).toEqual(1.5, import__431.Math.EPSILON10); expect(camera.frustum.bottom).toEqual(-1.5, import__431.Math.EPSILON10); }); it("clamps zoom out in 2D", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; camera.frustum = frustum; camera.update(import__430.SceneMode.SCENE2D); const max = scene2.mapProjection.project( new import__430.Cartographic(Math.PI, import__431.Math.toRadians(85.05112878)) ); const factor = 1e3; const dx = max.x * factor; const ratio = frustum.top / frustum.right; camera.zoomOut(dx); expect(frustum.right).toBeLessThan(dx); expect(frustum.left).toBeGreaterThan(-dx); expect(frustum.top).toEqual(frustum.right * ratio); expect(frustum.bottom).toEqual(-frustum.top); }); it("clamps zoom in in 2D", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; camera.frustum = frustum; camera.update(import__430.SceneMode.SCENE2D); const max = scene2.mapProjection.project( new import__430.Cartographic(Math.PI, import__431.Math.toRadians(85.05112878)) ); const factor = 1e3; const dx = max.x * factor; camera.zoomIn(dx * 2); expect(frustum.right).toEqual(1); expect(frustum.left).toEqual(-1); }); it("zooms in 3D", function() { camera.zoomIn(zoomAmount); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(0, 0, 1 - zoomAmount), import__431.Math.EPSILON10 ); expect(camera.up).toEqual(up); expect(camera.direction).toEqual(dir); expect(camera.right).toEqual(right); }); it("zooms out in 3D", function() { camera.zoomOut(zoomAmount); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(0, 0, 1 + zoomAmount), import__431.Math.EPSILON10 ); expect(camera.up).toEqual(up); expect(camera.direction).toEqual(dir); expect(camera.right).toEqual(right); }); it("zooms in throws with undefined OrthogrphicFrustum properties 2D", function() { camera._mode = import__430.SceneMode.SCENE2D; camera.frustum = new import__430.OrthographicOffCenterFrustum(); expect(function() { camera.zoomIn(zoomAmount); }).toThrowDeveloperError(); }); it("lookAt", function() { const target = import__430.Cartesian3.fromDegrees(0, 0); const offset = new import__430.Cartesian3(0, -1, 0); const tempCamera = import__430.Camera.clone(camera); tempCamera.lookAt(target, offset); expect(tempCamera.position).toEqualEpsilon(offset, import__431.Math.EPSILON11); expect(tempCamera.direction).toEqualEpsilon( import__430.Cartesian3.negate( import__430.Cartesian3.normalize(offset, new import__430.Cartesian3()), new import__430.Cartesian3() ), import__431.Math.EPSILON11 ); expect(tempCamera.right).toEqualEpsilon( import__430.Cartesian3.cross( tempCamera.direction, import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3() ), import__431.Math.EPSILON11 ); expect(tempCamera.up).toEqualEpsilon( import__430.Cartesian3.cross( tempCamera.right, tempCamera.direction, new import__430.Cartesian3() ), import__431.Math.EPSILON11 ); expect(1 - import__430.Cartesian3.magnitude(tempCamera.direction)).toBeLessThan( import__431.Math.EPSILON14 ); expect(1 - import__430.Cartesian3.magnitude(tempCamera.up)).toBeLessThan( import__431.Math.EPSILON14 ); expect(1 - import__430.Cartesian3.magnitude(tempCamera.right)).toBeLessThan( import__431.Math.EPSILON14 ); }); it("lookAt with heading, pitch and range", function() { const target = import__430.Cartesian3.fromDegrees(0, 0); const heading = import__431.Math.toRadians(45); const pitch = import__431.Math.toRadians(-45); const range = 2; const tempCamera = import__430.Camera.clone(camera); tempCamera.lookAt(target, new import__430.HeadingPitchRange(heading, pitch, range)); tempCamera.lookAtTransform(import__430.Matrix4.IDENTITY); expect(import__430.Cartesian3.distance(tempCamera.position, target)).toEqualEpsilon( range, import__431.Math.EPSILON6 ); expect(tempCamera.heading).toEqualEpsilon(heading, import__431.Math.EPSILON6); expect(tempCamera.pitch).toEqualEpsilon(pitch, import__431.Math.EPSILON6); expect(1 - import__430.Cartesian3.magnitude(tempCamera.direction)).toBeLessThan( import__431.Math.EPSILON14 ); expect(1 - import__430.Cartesian3.magnitude(tempCamera.up)).toBeLessThan( import__431.Math.EPSILON14 ); expect(1 - import__430.Cartesian3.magnitude(tempCamera.right)).toBeLessThan( import__431.Math.EPSILON14 ); }); it("lookAt when target is zero", function() { const target = import__430.Cartesian3.clone(import__430.Cartesian3.ZERO); const offset = new import__430.Cartesian3(0, -1, 0); const tempCamera = import__430.Camera.clone(camera); tempCamera.lookAt(target, offset); expect(tempCamera.position).toEqualEpsilon(offset, import__431.Math.EPSILON11); expect(tempCamera.direction).toEqualEpsilon( import__430.Cartesian3.negate( import__430.Cartesian3.normalize(offset, new import__430.Cartesian3()), new import__430.Cartesian3() ), import__431.Math.EPSILON11 ); expect(tempCamera.right).toEqualEpsilon( import__430.Cartesian3.cross( tempCamera.direction, import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3() ), import__431.Math.EPSILON11 ); expect(tempCamera.up).toEqualEpsilon( import__430.Cartesian3.cross( tempCamera.right, tempCamera.direction, new import__430.Cartesian3() ), import__431.Math.EPSILON11 ); }); it("lookAt when target and camera are zero", function() { const target = import__430.Cartesian3.clone(import__430.Cartesian3.ZERO); const offset = new import__430.Cartesian3(0, -1, 0); const tempCamera = import__430.Camera.clone(camera); tempCamera.position = import__430.Cartesian3.clone(import__430.Cartesian3.ZERO); tempCamera.lookAt(target, offset); expect(tempCamera.position).toEqualEpsilon(offset, import__431.Math.EPSILON11); expect(tempCamera.direction).toEqualEpsilon( import__430.Cartesian3.negate( import__430.Cartesian3.normalize(offset, new import__430.Cartesian3()), new import__430.Cartesian3() ), import__431.Math.EPSILON11 ); expect(tempCamera.right).toEqualEpsilon( import__430.Cartesian3.cross( tempCamera.direction, import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3() ), import__431.Math.EPSILON11 ); expect(tempCamera.up).toEqualEpsilon( import__430.Cartesian3.cross( tempCamera.right, tempCamera.direction, new import__430.Cartesian3() ), import__431.Math.EPSILON11 ); }); it("lookAt throws with no target parameter", function() { expect(function() { camera.lookAt(void 0, import__430.Cartesian3.ZERO); }).toThrowDeveloperError(); }); it("lookAt throws with no offset parameter", function() { expect(function() { camera.lookAt(import__430.Cartesian3.ZERO, void 0); }).toThrowDeveloperError(); }); it("lookAt in 2D mode", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; const tempCamera = import__430.Camera.clone(camera); tempCamera.frustum = frustum; tempCamera.update(import__430.SceneMode.SCENE2D); const target = import__430.Cartesian3.fromDegrees(0, 0); const offset = new import__430.Cartesian3(1e4, 1e4, 3e4); tempCamera.lookAt(target, offset); expect(import__430.Cartesian2.clone(tempCamera.position)).toEqual(import__430.Cartesian2.ZERO); expect(tempCamera.direction).toEqual( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3()) ); expect(tempCamera.up).toEqualEpsilon( import__430.Cartesian3.normalize( import__430.Cartesian3.fromElements(-offset.x, -offset.y, 0), new import__430.Cartesian3() ), import__431.Math.EPSILON11 ); expect(tempCamera.right).toEqualEpsilon( import__430.Cartesian3.cross(tempCamera.direction, tempCamera.up, new import__430.Cartesian3()), import__431.Math.EPSILON11 ); expect(tempCamera.frustum.right).toEqual( import__430.Cartesian3.magnitude(offset) * 0.5 ); expect(tempCamera.frustum.left).toEqual( -import__430.Cartesian3.magnitude(offset) * 0.5 ); }); it("lookAt in 2D mode with heading, pitch and range", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; const tempCamera = import__430.Camera.clone(camera); tempCamera.frustum = frustum; tempCamera.update(import__430.SceneMode.SCENE2D); const target = import__430.Cartesian3.fromDegrees(0, 0); const heading = import__431.Math.toRadians(90); const pitch = import__431.Math.toRadians(-45); const range = 2; tempCamera.lookAt(target, new import__430.HeadingPitchRange(heading, pitch, range)); expect(import__430.Cartesian2.clone(tempCamera.position)).toEqual(import__430.Cartesian2.ZERO); tempCamera.lookAtTransform(import__430.Matrix4.IDENTITY); expect(tempCamera.direction).toEqual( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3()) ); expect(tempCamera.heading).toEqualEpsilon(heading, import__431.Math.EPSILON6); expect(tempCamera.frustum.right).toEqual(range * 0.5); expect(tempCamera.frustum.left).toEqual(-range * 0.5); }); it("lookAt throws when morphing", function() { camera.update(import__430.SceneMode.MORPHING); expect(function() { camera.lookAt(import__430.Cartesian3.ZERO, import__430.Cartesian3.UNIT_X); }).toThrowDeveloperError(); }); it("lookAtTransform", function() { const target = new import__430.Cartesian3(-1, -1, 0); const offset = new import__430.Cartesian3(1, 1, 0); const transform = import__430.Transforms.eastNorthUpToFixedFrame( target, import__430.Ellipsoid.UNIT_SPHERE ); const tempCamera = import__430.Camera.clone(camera); tempCamera.lookAtTransform(transform, offset); expect(tempCamera.position).toEqualEpsilon(offset, import__431.Math.EPSILON11); expect(tempCamera.direction).toEqualEpsilon( import__430.Cartesian3.negate( import__430.Cartesian3.normalize(offset, new import__430.Cartesian3()), new import__430.Cartesian3() ), import__431.Math.EPSILON11 ); expect(tempCamera.right).toEqualEpsilon( import__430.Cartesian3.cross( tempCamera.direction, import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3() ), import__431.Math.EPSILON11 ); expect(tempCamera.up).toEqualEpsilon( import__430.Cartesian3.cross( tempCamera.right, tempCamera.direction, new import__430.Cartesian3() ), import__431.Math.EPSILON11 ); expect(1 - import__430.Cartesian3.magnitude(tempCamera.direction)).toBeLessThan( import__431.Math.EPSILON14 ); expect(1 - import__430.Cartesian3.magnitude(tempCamera.up)).toBeLessThan( import__431.Math.EPSILON14 ); expect(1 - import__430.Cartesian3.magnitude(tempCamera.right)).toBeLessThan( import__431.Math.EPSILON14 ); }); it("lookAtTransform with no offset parameter", function() { const ellipsoid = import__430.Ellipsoid.WGS84; const cartOrigin = import__430.Cartographic.fromDegrees(-75.59777, 40.03883); const origin = ellipsoid.cartographicToCartesian(cartOrigin); const transform = import__430.Transforms.eastNorthUpToFixedFrame(origin); const height = 1e3; cartOrigin.height = height; camera.position = ellipsoid.cartographicToCartesian(cartOrigin); camera.direction = import__430.Cartesian3.negate( import__430.Cartesian3.fromCartesian4( import__430.Matrix4.getColumn(transform, 2, new import__430.Cartesian4()) ), new import__430.Cartesian3() ); camera.up = import__430.Cartesian3.fromCartesian4( import__430.Matrix4.getColumn(transform, 1, new import__430.Cartesian4(), new import__430.Matrix4()) ); camera.right = import__430.Cartesian3.fromCartesian4( import__430.Matrix4.getColumn(transform, 0, new import__430.Cartesian4()) ); camera.lookAtTransform(transform); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(0, 0, height), import__431.Math.EPSILON9 ); expect(camera.direction).toEqualEpsilon( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3()), import__431.Math.EPSILON9 ); expect(camera.up).toEqualEpsilon(import__430.Cartesian3.UNIT_Y, import__431.Math.EPSILON9); expect(camera.right).toEqualEpsilon(import__430.Cartesian3.UNIT_X, import__431.Math.EPSILON9); }); it("lookAtTransform with heading, pitch and range", function() { const target = import__430.Cartesian3.fromDegrees(0, 0); const heading = import__431.Math.toRadians(45); const pitch = import__431.Math.toRadians(-45); const range = 2; const transform = import__430.Transforms.eastNorthUpToFixedFrame(target); const tempCamera = import__430.Camera.clone(camera); tempCamera.lookAtTransform( transform, new import__430.HeadingPitchRange(heading, pitch, range) ); tempCamera.lookAtTransform(import__430.Matrix4.IDENTITY); expect(import__430.Cartesian3.distance(tempCamera.position, target)).toEqualEpsilon( range, import__431.Math.EPSILON6 ); expect(tempCamera.heading).toEqualEpsilon(heading, import__431.Math.EPSILON6); expect(tempCamera.pitch).toEqualEpsilon(pitch, import__431.Math.EPSILON6); expect(1 - import__430.Cartesian3.magnitude(tempCamera.direction)).toBeLessThan( import__431.Math.EPSILON14 ); expect(1 - import__430.Cartesian3.magnitude(tempCamera.up)).toBeLessThan( import__431.Math.EPSILON14 ); expect(1 - import__430.Cartesian3.magnitude(tempCamera.right)).toBeLessThan( import__431.Math.EPSILON14 ); }); it("lookAtTransform throws with no transform parameter", function() { expect(function() { camera.lookAtTransform(void 0, import__430.Cartesian3.ZERO); }).toThrowDeveloperError(); }); it("lookAtTransform in 2D mode", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; const tempCamera = import__430.Camera.clone(camera); tempCamera.frustum = frustum; tempCamera.update(import__430.SceneMode.SCENE2D); const transform = import__430.Transforms.eastNorthUpToFixedFrame( import__430.Cartesian3.fromDegrees(0, 0) ); const offset = new import__430.Cartesian3(1e4, 1e4, 3e4); tempCamera.lookAtTransform(transform, offset); expect(import__430.Cartesian2.clone(tempCamera.position)).toEqual(import__430.Cartesian2.ZERO); expect(tempCamera.direction).toEqual( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3()) ); expect(tempCamera.up).toEqualEpsilon( import__430.Cartesian3.normalize( import__430.Cartesian3.fromElements(-offset.x, -offset.y, 0), new import__430.Cartesian3() ), import__431.Math.EPSILON11 ); expect(tempCamera.right).toEqualEpsilon( import__430.Cartesian3.cross(tempCamera.direction, tempCamera.up, new import__430.Cartesian3()), import__431.Math.EPSILON11 ); expect(tempCamera.frustum.right).toEqual( import__430.Cartesian3.magnitude(offset) * 0.5 ); expect(tempCamera.frustum.left).toEqual( -import__430.Cartesian3.magnitude(offset) * 0.5 ); }); it("lookAtTransform in 2D mode with heading, pitch and range", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; const tempCamera = import__430.Camera.clone(camera); tempCamera.frustum = frustum; tempCamera.update(import__430.SceneMode.SCENE2D); const target = import__430.Cartesian3.fromDegrees(0, 0); const heading = import__431.Math.toRadians(90); const pitch = import__431.Math.toRadians(-45); const range = 2; const transform = import__430.Transforms.eastNorthUpToFixedFrame(target); tempCamera.lookAtTransform( transform, new import__430.HeadingPitchRange(heading, pitch, range) ); expect(import__430.Cartesian2.clone(tempCamera.position)).toEqual(import__430.Cartesian2.ZERO); tempCamera.lookAtTransform(import__430.Matrix4.IDENTITY); expect(tempCamera.direction).toEqual( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3()) ); expect(tempCamera.heading).toEqualEpsilon(heading, import__431.Math.EPSILON6); expect(tempCamera.frustum.right).toEqual(range * 0.5); expect(tempCamera.frustum.left).toEqual(-range * 0.5); }); it("lookAtTransform in 3D with orthographic projection", function() { const target = new import__430.Cartesian3(-1, -1, 0); const offset = new import__430.Cartesian3(1, 1, 0); const transform = import__430.Transforms.eastNorthUpToFixedFrame( target, import__430.Ellipsoid.UNIT_SPHERE ); const tempCamera = import__430.Camera.clone(camera); tempCamera.frustum = new import__430.OrthographicFrustum(); tempCamera.frustum.aspectRatio = scene2.drawingBufferWidth / scene2.drawingBufferHeight; tempCamera.frustum.width = tempCamera.positionCartographic.height; tempCamera.lookAtTransform(transform, offset); expect(tempCamera.position).toEqualEpsilon(offset, import__431.Math.EPSILON11); expect(tempCamera.direction).toEqualEpsilon( import__430.Cartesian3.negate( import__430.Cartesian3.normalize(offset, new import__430.Cartesian3()), new import__430.Cartesian3() ), import__431.Math.EPSILON11 ); expect(tempCamera.right).toEqualEpsilon( import__430.Cartesian3.cross( tempCamera.direction, import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3() ), import__431.Math.EPSILON11 ); expect(tempCamera.up).toEqualEpsilon( import__430.Cartesian3.cross( tempCamera.right, tempCamera.direction, new import__430.Cartesian3() ), import__431.Math.EPSILON11 ); expect(1 - import__430.Cartesian3.magnitude(tempCamera.direction)).toBeLessThan( import__431.Math.EPSILON14 ); expect(1 - import__430.Cartesian3.magnitude(tempCamera.up)).toBeLessThan( import__431.Math.EPSILON14 ); expect(1 - import__430.Cartesian3.magnitude(tempCamera.right)).toBeLessThan( import__431.Math.EPSILON14 ); expect(tempCamera.frustum.width).toEqual( import__430.Cartesian3.magnitude(tempCamera.position) ); }); it("lookAtTransform throws when morphing", function() { camera.update(import__430.SceneMode.MORPHING); expect(function() { camera.lookAtTransform(import__430.Matrix4.IDENTITY, import__430.Cartesian3.UNIT_X); }).toThrowDeveloperError(); }); it("setView rectangle in 3D (1)", function() { const rectangle = new import__430.Rectangle( -Math.PI, -import__431.Math.PI_OVER_TWO, Math.PI, import__431.Math.PI_OVER_TWO ); camera.setView({ destination: rectangle }); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(14680290639204923e-9, 0, 0), import__431.Math.EPSILON6 ); expect(camera.direction).toEqualEpsilon( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_X, new import__430.Cartesian3()), import__431.Math.EPSILON10 ); expect(camera.up).toEqualEpsilon(import__430.Cartesian3.UNIT_Z, import__431.Math.EPSILON10); expect(camera.right).toEqualEpsilon( import__430.Cartesian3.UNIT_Y, import__431.Math.EPSILON10 ); }); it("setView rectangle in 3D (2)", function() { const rectangle = new import__430.Rectangle( import__431.Math.toRadians(21.25), import__431.Math.toRadians(41.23), import__431.Math.toRadians(21.51), import__431.Math.toRadians(41.38) ); camera.setView({ destination: rectangle }); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(4481555454147325e-9, 1.7544980086281248e6, 4200627581953675e-9), import__431.Math.EPSILON6 ); expect(camera.direction).toEqualEpsilon( new import__430.Cartesian3( -0.6995046749050446, -0.27385124912628594, -0.6600747708691498 ), import__431.Math.EPSILON10 ); expect(camera.up).toEqualEpsilon( new import__430.Cartesian3( -0.6146504879783901, -0.2406314209863035, 0.7511999047271233 ), import__431.Math.EPSILON10 ); expect(camera.right).toEqualEpsilon( new import__430.Cartesian3(-0.36455176232452213, 0.9311831251617939, 0), import__431.Math.EPSILON10 ); }); it("setView rectangle in 3D (3)", function() { const rectangle = new import__430.Rectangle( import__431.Math.toRadians(90), import__431.Math.toRadians(-50), import__431.Math.toRadians(157), import__431.Math.toRadians(0) ); camera.setView({ destination: rectangle }); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(-601760325625715e-8, 909160678076493e-8, -5075070862292178e-9), import__431.Math.EPSILON6 ); expect(camera.direction).toEqualEpsilon( new import__430.Cartesian3( 0.49978034145251155, -0.7550857289433265, 0.42434084442077485 ), import__431.Math.EPSILON10 ); expect(camera.up).toEqualEpsilon( new import__430.Cartesian3( -0.2342094064143758, 0.35385181388649406, 0.905502538790623 ), import__431.Math.EPSILON10 ); expect(camera.right).toEqualEpsilon( new import__430.Cartesian3(-0.8338858220671682, -0.5519369853120581, 0), import__431.Math.EPSILON10 ); }); it("setView rectangle in 3D (4)", function() { const rectangle = new import__430.Rectangle( import__431.Math.toRadians(90), import__431.Math.toRadians(-62), import__431.Math.toRadians(174), import__431.Math.toRadians(-4) ); camera.setView({ destination: rectangle }); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(-7307919685704952e-9, 8116267060310548e-9, -7085995891547672e-9), import__431.Math.EPSILON6 ); expect(camera.direction).toEqualEpsilon( new import__430.Cartesian3( 0.5602119862713765, -0.6221784429103113, 0.5468605998017956 ), import__431.Math.EPSILON10 ); expect(camera.up).toEqualEpsilon( new import__430.Cartesian3( -0.3659211647391443, 0.40639662500016843, 0.8372236764356468 ), import__431.Math.EPSILON10 ); expect(camera.right).toEqualEpsilon( new import__430.Cartesian3(-0.7431448254773944, -0.6691306063588581, 0), import__431.Math.EPSILON10 ); }); it("views rectangle in 3D across IDL", function() { const rectangle = new import__430.Rectangle( 0.1, -import__431.Math.PI_OVER_TWO, -0.1, import__431.Math.PI_OVER_TWO ); camera.setView({ destination: rectangle }); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(-14680290639204923e-9, 0, 0), import__431.Math.EPSILON6 ); expect(camera.direction).toEqualEpsilon( import__430.Cartesian3.UNIT_X, import__431.Math.EPSILON10 ); expect(camera.up).toEqualEpsilon(import__430.Cartesian3.UNIT_Z, import__431.Math.EPSILON10); expect(camera.right).toEqualEpsilon( import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Y, new import__430.Cartesian3()), import__431.Math.EPSILON10 ); }); it("setView rectangle in 2D with larger longitude", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.left = -10; frustum.right = 10; frustum.bottom = -10; frustum.top = 10; frustum.near = 1; frustum.far = 21; camera.frustum = frustum; const rectangle = new import__430.Rectangle( -import__431.Math.PI_OVER_TWO, -import__431.Math.PI_OVER_FOUR, import__431.Math.PI_OVER_TWO, import__431.Math.PI_OVER_FOUR ); const projection = new import__430.GeographicProjection(); const edge = projection.project( new import__430.Cartographic(import__431.Math.PI_OVER_TWO, import__431.Math.PI_OVER_FOUR) ); const expected = Math.max(edge.x, edge.y); camera._mode = import__430.SceneMode.SCENE2D; camera._projection = projection; camera.setView({ destination: rectangle }); expect(camera.position.x).toEqual(0); expect(camera.position.y).toEqual(0); expect(frustum.right - expected <= import__431.Math.EPSILON14).toEqual(true); expect(frustum.left + expected <= import__431.Math.EPSILON14).toEqual(true); expect(frustum.top - expected <= import__431.Math.EPSILON14).toEqual(true); expect(frustum.bottom + expected <= import__431.Math.EPSILON14).toEqual(true); }); it("setView rectangle in 2D with larger latitude", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.left = -10; frustum.right = 10; frustum.bottom = -10; frustum.top = 10; frustum.near = 1; frustum.far = 21; camera.frustum = frustum; const rectangle = new import__430.Rectangle( -import__431.Math.PI_OVER_FOUR, -import__431.Math.PI_OVER_TWO, import__431.Math.PI_OVER_FOUR, import__431.Math.PI_OVER_TWO ); const projection = new import__430.GeographicProjection(); const edge = projection.project( new import__430.Cartographic(import__431.Math.PI_OVER_FOUR, import__431.Math.PI_OVER_TWO) ); const expected = Math.max(edge.x, edge.y); camera._mode = import__430.SceneMode.SCENE2D; camera._projection = projection; camera.setView({ destination: rectangle }); expect(camera.position.x).toEqual(0); expect(camera.position.y).toEqual(0); expect(frustum.right - expected <= import__431.Math.EPSILON14).toEqual(true); expect(frustum.left + expected <= import__431.Math.EPSILON14).toEqual(true); expect(frustum.top - expected <= import__431.Math.EPSILON14).toEqual(true); expect(frustum.bottom + expected <= import__431.Math.EPSILON14).toEqual(true); }); it("setView rectangle in Columbus View", function() { const rectangle = new import__430.Rectangle( -import__431.Math.PI_OVER_TWO, -import__431.Math.PI_OVER_TWO, import__431.Math.PI_OVER_TWO, import__431.Math.PI_OVER_TWO ); const projection = new import__430.GeographicProjection(); camera._mode = import__430.SceneMode.COLUMBUS_VIEW; camera._projection = projection; camera.setView({ destination: rectangle }); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(0, 0, 2313732167119748e-8), import__431.Math.EPSILON8 ); expect(camera.direction).toEqualEpsilon( new import__430.Cartesian3(0, 0, -1), import__431.Math.EPSILON2 ); expect(camera.up).toEqualEpsilon( new import__430.Cartesian3(0, 1, 0), import__431.Math.EPSILON2 ); expect(camera.right).toEqualEpsilon( new import__430.Cartesian3(1, 0, 0), import__431.Math.EPSILON10 ); }); it("setView rectangle in 3D with orthographic frustum", function() { camera.setView({ destination: import__430.Cartesian3.fromDegrees(-75, 42, 100) }); camera.frustum = new import__430.OrthographicFrustum(); camera.frustum.aspectRatio = 1135 / 630; camera.frustum.width = camera.positionCartographic.height; expect(camera.frustum.projectionMatrix).toBeDefined(); const rectangle = new import__430.Rectangle( import__431.Math.toRadians(21.25), import__431.Math.toRadians(41.23), import__431.Math.toRadians(21.51), import__431.Math.toRadians(41.38) ); const projection = new import__430.GeographicProjection(); camera._mode = import__430.SceneMode.SCENE3D; camera._projection = projection; camera.setView({ destination: rectangle }); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(4489090849577177e-9, 1.7574480638960265e6, 420773807588144e-8), import__431.Math.EPSILON6 ); expect(camera.direction).toEqualEpsilon( new import__430.Cartesian3( -0.6995012374560863, -0.2738499033887593, -0.6600789719506079 ), import__431.Math.EPSILON10 ); expect(camera.up).toEqualEpsilon( new import__430.Cartesian3( -0.6146543999545513, -0.2406329524979527, 0.7511962132416727 ), import__431.Math.EPSILON10 ); expect(camera.right).toEqualEpsilon( new import__430.Cartesian3(-0.36455176232452197, 0.931183125161794, 0), import__431.Math.EPSILON10 ); }); it("setView rectangle in Columbus view with orthographic frustum", function() { camera.setView({ destination: import__430.Cartesian3.fromDegrees(-75, 42, 100) }); camera.frustum = new import__430.OrthographicFrustum(); camera.frustum.aspectRatio = 1135 / 630; camera.frustum.width = camera.positionCartographic.height; expect(camera.frustum.projectionMatrix).toBeDefined(); const rectangle = new import__430.Rectangle( import__431.Math.toRadians(21.25), import__431.Math.toRadians(41.23), import__431.Math.toRadians(21.51), import__431.Math.toRadians(41.38) ); const projection = new import__430.GeographicProjection(); camera._mode = import__430.SceneMode.COLUMBUS_VIEW; camera._projection = projection; camera.setView({ destination: rectangle }); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(2380010713160189e-9, 4598051567216165e-9, 28943.06760625122), import__431.Math.EPSILON6 ); expect(camera.direction).toEqualEpsilon( new import__430.Cartesian3(0, 0, -1), import__431.Math.EPSILON10 ); expect(camera.up).toEqualEpsilon(import__430.Cartesian3.UNIT_Y, import__431.Math.EPSILON10); expect(camera.right).toEqualEpsilon( import__430.Cartesian3.UNIT_X, import__431.Math.EPSILON10 ); }); it("getRectangleCameraCoordinates throws without rectangle", function() { expect(function() { camera.getRectangleCameraCoordinates(); }).toThrowDeveloperError(); }); it("getRectangleCameraCoordinates rectangle in 3D", function() { const rectangle = new import__430.Rectangle( -Math.PI, -import__431.Math.PI_OVER_TWO, Math.PI, import__431.Math.PI_OVER_TWO ); const position2 = import__430.Cartesian3.clone(camera.position); const direction = import__430.Cartesian3.clone(camera.direction); const up2 = import__430.Cartesian3.clone(camera.up); const right2 = import__430.Cartesian3.clone(camera.right); camera._mode = import__430.SceneMode.SCENE3D; camera.getRectangleCameraCoordinates(rectangle, position2); expect(position2).toEqualEpsilon( new import__430.Cartesian3(14680290639204923e-9, 0, 0), import__431.Math.EPSILON6 ); expect(camera.direction).toEqual(direction); expect(camera.up).toEqual(up2); expect(camera.right).toEqual(right2); }); it("gets coordinates for rectangle in 3D across IDL", function() { const rectangle = new import__430.Rectangle( 0.1, -import__431.Math.PI_OVER_TWO, -0.1, import__431.Math.PI_OVER_TWO ); let position2 = new import__430.Cartesian3(); const direction = import__430.Cartesian3.clone(camera.direction); const up2 = import__430.Cartesian3.clone(camera.up); const right2 = import__430.Cartesian3.clone(camera.right); camera._mode = import__430.SceneMode.SCENE3D; position2 = camera.getRectangleCameraCoordinates(rectangle); expect(position2).toEqualEpsilon( new import__430.Cartesian3(-14680290639204923e-9, 0, 0), import__431.Math.EPSILON6 ); expect(camera.direction).toEqual(direction); expect(camera.up).toEqual(up2); expect(camera.right).toEqual(right2); }); it("views rectangle in 2D with larger latitude", function() { const rectangle = new import__430.Rectangle( -import__431.Math.PI_OVER_FOUR, -import__431.Math.PI_OVER_TWO, import__431.Math.PI_OVER_FOUR, import__431.Math.PI_OVER_TWO ); const projection = new import__430.GeographicProjection(); const cam = new import__430.Camera(scene2); const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.right = 1; frustum.left = -1; frustum.top = 1; frustum.bottom = -1; frustum.near = 1; frustum.far = 2; cam.frustum = frustum; const z = cam.position.z; cam._mode = import__430.SceneMode.SCENE2D; cam._projection = projection; camera.position = cam.getRectangleCameraCoordinates(rectangle); expect(camera.position.x).toEqual(0); expect(camera.position.y).toEqual(0); expect(camera.position.z).not.toEqual(z); expect(cam.frustum.left).toEqual(-1); expect(cam.frustum.far).toEqual(2); }); it("gets coordinates for rectangle in Columbus View", function() { const rectangle = new import__430.Rectangle( -import__431.Math.PI_OVER_TWO, -import__431.Math.PI_OVER_TWO, import__431.Math.PI_OVER_TWO, import__431.Math.PI_OVER_TWO ); const projection = new import__430.GeographicProjection(); camera._mode = import__430.SceneMode.COLUMBUS_VIEW; camera._projection = projection; const direction = import__430.Cartesian3.clone(camera.direction); const up2 = import__430.Cartesian3.clone(camera.up); const right2 = import__430.Cartesian3.clone(camera.right); camera.position = camera.getRectangleCameraCoordinates(rectangle); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(0, 0, 2313732167119748e-8), import__431.Math.EPSILON8 ); expect(camera.direction).toEqual(direction); expect(camera.up).toEqual(up2); expect(camera.right).toEqual(right2); }); it("get rectangle coordinate returns camera position if scene mode is morphing", function() { const rectangle = new import__430.Rectangle( -import__431.Math.PI_OVER_TWO, -import__431.Math.PI_OVER_TWO, import__431.Math.PI_OVER_TWO, import__431.Math.PI_OVER_TWO ); const projection = new import__430.GeographicProjection(); camera._mode = import__430.SceneMode.MORPHING; camera._projection = projection; const position2 = import__430.Cartesian3.clone(camera.position); const direction = import__430.Cartesian3.clone(camera.direction); const up2 = import__430.Cartesian3.clone(camera.up); const right2 = import__430.Cartesian3.clone(camera.right); camera.getRectangleCameraCoordinates(rectangle, camera.position); expect(camera.position).toEqual(position2); expect(camera.direction).toEqual(direction); expect(camera.up).toEqual(up2); expect(camera.right).toEqual(right2); }); it("pick ellipsoid throws without a position", function() { expect(function() { camera.pickEllipsoid(); }).toThrowDeveloperError(); }); it("pick ellipsoid returns undefined if height is 0", function() { scene2.canvas.clientHeight = 0; expect(camera.pickEllipsoid(import__430.Cartesian2.ZERO)).toBeUndefined(); }); it("pick ellipsoid returns undefined if width is 0", function() { scene2.canvas.clientWidth = 0; expect(camera.pickEllipsoid(import__430.Cartesian2.ZERO)).toBeUndefined(); }); it("pick ellipsoid", function() { const ellipsoid = import__430.Ellipsoid.WGS84; const maxRadii = ellipsoid.maximumRadius; camera.position = import__430.Cartesian3.multiplyByScalar( import__430.Cartesian3.UNIT_X, 2 * maxRadii, new import__430.Cartesian3() ); camera.direction = import__430.Cartesian3.normalize( import__430.Cartesian3.negate(camera.position, new import__430.Cartesian3()), new import__430.Cartesian3() ); camera.up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Z); camera.right = import__430.Cartesian3.cross( camera.direction, camera.up, new import__430.Cartesian3() ); const frustum = new import__430.PerspectiveFrustum(); frustum.fov = import__431.Math.toRadians(60); frustum.aspectRatio = scene2.drawingBufferWidth / scene2.drawingBufferHeight; frustum.near = 100; frustum.far = 60 * maxRadii; camera.frustum = frustum; const windowCoord = new import__430.Cartesian2( scene2.canvas.clientWidth * 0.5, scene2.canvas.clientHeight * 0.5 ); let p = camera.pickEllipsoid(windowCoord, ellipsoid); const c = ellipsoid.cartesianToCartographic(p); expect(c).toEqual(new import__430.Cartographic(0, 0, 0)); p = camera.pickEllipsoid(import__430.Cartesian2.ZERO, ellipsoid); expect(p).toBeUndefined(); }); it("pickEllipsoid works near the surface", function() { const ellipsoid = import__430.Ellipsoid.WGS84; const minRadii = ellipsoid.minimumRadius; camera.position = new import__430.Cartesian3(0, 0, minRadii + 10); camera.direction = new import__430.Cartesian3(0, 0, -1); camera.up = new import__430.Cartesian3(1, 0, 0); camera.right = new import__430.Cartesian3(0, 1, 0); const p = camera.pickEllipsoid(import__430.Cartesian2.ZERO, ellipsoid); expect(p.z).toEqualEpsilon(minRadii, 1e-4); }); it("pick map in 2D", function() { const ellipsoid = import__430.Ellipsoid.WGS84; const projection = new import__430.GeographicProjection(ellipsoid); const maxRadii = ellipsoid.maximumRadius; camera.position = new import__430.Cartesian3(0, 0, 2 * maxRadii); camera.direction = import__430.Cartesian3.normalize( import__430.Cartesian3.negate(camera.position, new import__430.Cartesian3()), new import__430.Cartesian3() ); camera.up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Y); const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.right = maxRadii * Math.PI; frustum.left = -frustum.right; frustum.top = frustum.right * (scene2.drawingBufferHeight / scene2.drawingBufferWidth); frustum.bottom = -frustum.top; frustum.near = 0.01 * maxRadii; frustum.far = 60 * maxRadii; camera.frustum = frustum; camera._mode = import__430.SceneMode.SCENE2D; camera._projection = projection; const windowCoord = new import__430.Cartesian2( scene2.canvas.clientWidth * 0.5, scene2.canvas.clientHeight * 0.5 ); const p = camera.pickEllipsoid(windowCoord); const c = ellipsoid.cartesianToCartographic(p); expect(c).toEqual(new import__430.Cartographic(0, 0, 0)); }); it("pick rotated map in 2D", function() { const ellipsoid = import__430.Ellipsoid.WGS84; const projection = new import__430.GeographicProjection(ellipsoid); const maxRadii = ellipsoid.maximumRadius; camera.position = new import__430.Cartesian3(0, 0, 2 * maxRadii); camera.direction = import__430.Cartesian3.normalize( import__430.Cartesian3.negate(camera.position, new import__430.Cartesian3()), new import__430.Cartesian3() ); camera.up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Y); const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.right = maxRadii * Math.PI; frustum.left = -frustum.right; frustum.top = frustum.right * (scene2.drawingBufferHeight / scene2.drawingBufferWidth); frustum.bottom = -frustum.top; frustum.near = 0.01 * maxRadii; frustum.far = 60 * maxRadii; camera.frustum = frustum; camera._mode = import__430.SceneMode.SCENE2D; camera._projection = projection; const windowCoord = new import__430.Cartesian2( scene2.canvas.clientWidth * 0.5, scene2.canvas.clientHeight * 0.5 + 1 ); let p = camera.pickEllipsoid(windowCoord); let c = ellipsoid.cartesianToCartographic(p); expect(c.longitude).toEqual(0); expect(c.latitude).toBeLessThan(0); camera.up = import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_X, new import__430.Cartesian3()); camera.right = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Y); p = camera.pickEllipsoid(windowCoord); c = ellipsoid.cartesianToCartographic(p); expect(c.latitude).toEqual(0); expect(c.longitude).toBeGreaterThan(0); }); it("pick map in columbus view", function() { const ellipsoid = import__430.Ellipsoid.WGS84; const maxRadii = ellipsoid.maximumRadius; camera.position = import__430.Cartesian3.multiplyByScalar( import__430.Cartesian3.normalize(new import__430.Cartesian3(0, -1, 1), new import__430.Cartesian3()), 5 * maxRadii, new import__430.Cartesian3() ); camera.direction = import__430.Cartesian3.normalize( import__430.Cartesian3.subtract(import__430.Cartesian3.ZERO, camera.position, new import__430.Cartesian3()), new import__430.Cartesian3() ); camera.right = import__430.Cartesian3.normalize( import__430.Cartesian3.cross(camera.direction, import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3()), new import__430.Cartesian3() ); camera.up = import__430.Cartesian3.cross( camera.right, camera.direction, new import__430.Cartesian3() ); const frustum = new import__430.PerspectiveFrustum(); frustum.fov = import__431.Math.toRadians(60); frustum.aspectRatio = scene2.drawingBufferWidth / scene2.drawingBufferHeight; frustum.near = 0.01 * maxRadii; frustum.far = 60 * maxRadii; camera.frustum = frustum; camera.update(import__430.SceneMode.COLUMBUS_VIEW); const windowCoord = new import__430.Cartesian2( scene2.canvas.clientWidth * 0.5, scene2.canvas.clientHeight * 0.5 ); let p = camera.pickEllipsoid(windowCoord); const c = ellipsoid.cartesianToCartographic(p); expect(c).toEqual(new import__430.Cartographic(0, 0, 0)); p = camera.pickEllipsoid(import__430.Cartesian2.ZERO); expect(p).toBeUndefined(); }); it("pick map in morph", function() { const ellipsoid = import__430.Ellipsoid.WGS84; const maxRadii = ellipsoid.maximumRadius; camera.position = import__430.Cartesian3.multiplyByScalar( import__430.Cartesian3.UNIT_X, 2 * maxRadii, new import__430.Cartesian3() ); camera.direction = import__430.Cartesian3.normalize( import__430.Cartesian3.negate(camera.position, new import__430.Cartesian3()), new import__430.Cartesian3() ); camera.up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Z); camera.right = import__430.Cartesian3.cross( camera.direction, camera.up, new import__430.Cartesian3() ); const frustum = new import__430.PerspectiveFrustum(); frustum.fov = import__431.Math.toRadians(60); frustum.aspectRatio = scene2.drawingBufferWidth / scene2.drawingBufferHeight; frustum.near = 100; frustum.far = 60 * maxRadii; camera.frustum = frustum; camera.update(import__430.SceneMode.MORPHING); const windowCoord = new import__430.Cartesian2( scene2.canvas.clientWidth * 0.5, scene2.canvas.clientHeight * 0.5 ); const p = camera.pickEllipsoid(windowCoord); expect(p).toBeUndefined(); }); it("get pick ray throws without a position", function() { expect(function() { camera.getPickRay(); }).toThrowDeveloperError(); }); it("get pick ray returns undefined if the Scene is not fully rendered", function() { const windowCoord = new import__430.Cartesian2( scene2.canvas.clientWidth / 2, scene2.canvas.clientHeight ); scene2.canvas.clientWidth = 0; const ray = camera.getPickRay(windowCoord); expect(ray).toBeUndefined(); }); it("get pick ray perspective", function() { const windowCoord = new import__430.Cartesian2( scene2.canvas.clientWidth / 2, scene2.canvas.clientHeight ); const ray = camera.getPickRay(windowCoord); const windowHeight = camera.frustum.near * Math.tan(camera.frustum.fovy * 0.5); const expectedDirection = import__430.Cartesian3.normalize( new import__430.Cartesian3(0, -windowHeight, -1), new import__430.Cartesian3() ); expect(ray.origin).toEqual(camera.position); expect(ray.direction).toEqualEpsilon( expectedDirection, import__431.Math.EPSILON15 ); }); it("get pick ray orthographic in 2D", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.left = -10; frustum.right = 10; frustum.bottom = -10; frustum.top = 10; frustum.near = 1; frustum.far = 21; camera.frustum = frustum; camera.update(import__430.SceneMode.SCENE2D); const windowCoord = new import__430.Cartesian2( 3 / 5 * scene2.canvas.clientWidth, (1 - 3 / 5) * scene2.canvas.clientHeight ); const ray = camera.getPickRay(windowCoord); const cameraPosition = camera.position; const expectedPosition = new import__430.Cartesian3( cameraPosition.z, cameraPosition.x + 2, cameraPosition.y + 2 ); expect(ray.origin).toEqualEpsilon(expectedPosition, import__431.Math.EPSILON14); expect(ray.direction).toEqual(camera.directionWC); }); it("get pick ray orthographic in 3D", function() { const frustum = new import__430.OrthographicFrustum(); frustum.aspectRatio = 1; frustum.width = 20; frustum.near = 1; frustum.far = 21; camera.frustum = frustum; expect(frustum.projectionMatrix).toBeDefined(); camera.update(import__430.SceneMode.SCENE3D); const windowCoord = new import__430.Cartesian2( 3 / 5 * scene2.canvas.clientWidth, (1 - 3 / 5) * scene2.canvas.clientHeight ); const ray = camera.getPickRay(windowCoord); const cameraPosition = camera.position; const expectedPosition = new import__430.Cartesian3( cameraPosition.x + 2, cameraPosition.y + 2, cameraPosition.z ); expect(ray.origin).toEqualEpsilon(expectedPosition, import__431.Math.EPSILON14); expect(ray.direction).toEqual(camera.directionWC); }); it("get pick ray orthographic in Columbus view", function() { const frustum = new import__430.OrthographicFrustum(); frustum.aspectRatio = 1; frustum.width = 20; frustum.near = 1; frustum.far = 21; camera.frustum = frustum; expect(frustum.projectionMatrix).toBeDefined(); camera.update(import__430.SceneMode.COLUMBUS_VIEW); const windowCoord = new import__430.Cartesian2( 3 / 5 * scene2.canvas.clientWidth, (1 - 3 / 5) * scene2.canvas.clientHeight ); const ray = camera.getPickRay(windowCoord); const cameraPosition = camera.position; const expectedPosition = new import__430.Cartesian3( cameraPosition.z, cameraPosition.x + 2, cameraPosition.y + 2 ); expect(ray.origin).toEqualEpsilon(expectedPosition, import__431.Math.EPSILON14); expect(ray.direction).toEqual(camera.directionWC); }); it("gets magnitude in 2D", function() { const ellipsoid = import__430.Ellipsoid.WGS84; const projection = new import__430.GeographicProjection(ellipsoid); const maxRadii = ellipsoid.maximumRadius; camera._mode = import__430.SceneMode.SCENE2D; camera._projection = projection; const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.right = maxRadii * Math.PI; frustum.left = -frustum.right; frustum.top = frustum.right * (scene2.drawingBufferHeight / scene2.drawingBufferWidth); frustum.bottom = -frustum.top; frustum.near = 0.01 * maxRadii; frustum.far = 60 * maxRadii; camera.frustum = frustum; expect(camera.getMagnitude()).toEqual(frustum.right - frustum.left); }); it("gets magnitude in Columbus view", function() { camera._mode = import__430.SceneMode.COLUMBUS_VIEW; expect(camera.getMagnitude()).toEqual(camera.position.z); }); it("gets magnitude in 3D", function() { expect(camera.getMagnitude()).toEqual( import__430.Cartesian3.magnitude(camera.position) ); }); it("create animation throws without a duration", function() { expect(function() { camera.createCorrectPositionTween(); }).toThrowDeveloperError(); }); it("does not animate in 3D", function() { expect(camera.createCorrectPositionTween(0.05)).not.toBeDefined(); }); it("does not animate in 2D", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; camera.frustum = frustum; camera.update(import__430.SceneMode.SCENE2D); const max = scene2.mapProjection.project( new import__430.Cartographic(Math.PI, import__431.Math.PI_OVER_TWO) ); const factor = 1e3; const dx = max.x * factor; const dy = max.y * factor; camera.moveUp(dy); camera.moveRight(dx); expect(camera.createCorrectPositionTween(0.05)).not.toBeDefined(); }); it("animates position to visible map in Columbus view", function() { const maxRadii = import__430.Ellipsoid.WGS84.maximumRadius; const frustum = new import__430.PerspectiveFrustum(); frustum.fov = import__431.Math.toRadians(60); frustum.aspectRatio = scene2.drawingBufferWidth / scene2.drawingBufferHeight; frustum.near = 100; frustum.far = 60 * maxRadii; camera.frustum = frustum; camera.position = import__430.Cartesian3.multiplyByScalar( import__430.Cartesian3.UNIT_Z, maxRadii * 5, new import__430.Cartesian3() ); camera.update(import__430.SceneMode.COLUMBUS_VIEW); const max = scene2.mapProjection.project( new import__430.Cartographic(Math.PI, import__431.Math.PI_OVER_TWO) ); const factor = 1e3; const dx = max.x * factor; const dy = max.y * factor; const tweens = new import__430.TweenCollection(); camera.moveUp(dy); camera.moveRight(dx); let correctAnimation = camera.createCorrectPositionTween(0.05); expect(correctAnimation).toBeDefined(); let animation = tweens.add(correctAnimation); while (tweens.contains(animation)) { tweens.update(); } expect(camera.position.x).toEqualEpsilon(max.x, import__431.Math.EPSILON6); expect(camera.position.y).toEqualEpsilon(max.y, import__431.Math.EPSILON6); camera.moveDown(dy); camera.moveLeft(dx); correctAnimation = camera.createCorrectPositionTween(0.05); expect(correctAnimation).toBeDefined(); animation = tweens.add(correctAnimation); while (tweens.contains(animation)) { tweens.update(); } expect(camera.position.x).toEqualEpsilon(-max.x, import__431.Math.EPSILON6); expect(camera.position.y).toEqualEpsilon(-max.y, import__431.Math.EPSILON6); }); it("animates position to visible map in Columbus view with web mercator projection", function() { const projection = new import__430.WebMercatorProjection(); const mercatorCamera = new import__430.Camera(new FakeScene(projection)); mercatorCamera.position = import__430.Cartesian3.clone(position); mercatorCamera.up = import__430.Cartesian3.clone(up); mercatorCamera.direction = import__430.Cartesian3.clone(dir); mercatorCamera.right = import__430.Cartesian3.clone(right); mercatorCamera.minimumZoomDistance = 0; mercatorCamera.update(import__430.SceneMode.COLUMBUS_VIEW); const maxRadii = import__430.Ellipsoid.WGS84.maximumRadius; const frustum = new import__430.PerspectiveFrustum(); frustum.fov = import__431.Math.toRadians(60); frustum.aspectRatio = scene2.drawingBufferWidth / scene2.drawingBufferHeight; frustum.near = 100; frustum.far = 60 * maxRadii; mercatorCamera.frustum = frustum; mercatorCamera.position = import__430.Cartesian3.multiplyByScalar( import__430.Cartesian3.UNIT_Z, maxRadii * 5, new import__430.Cartesian3() ); const max = projection.project( new import__430.Cartographic(Math.PI, import__431.Math.PI_OVER_TWO) ); const factor = 1e3; const dx = max.x * factor; const dy = max.y * factor; const tweens = new import__430.TweenCollection(); mercatorCamera.moveUp(dy); mercatorCamera.moveRight(dx); let correctAnimation = mercatorCamera.createCorrectPositionTween(0.05); expect(correctAnimation).toBeDefined(); let animation = tweens.add(correctAnimation); while (tweens.contains(animation)) { tweens.update(); } expect(mercatorCamera.position.x).toEqualEpsilon( max.x, import__431.Math.EPSILON6 ); expect(mercatorCamera.position.y).toEqualEpsilon( max.y, import__431.Math.EPSILON6 ); mercatorCamera.moveDown(dy); mercatorCamera.moveLeft(dx); correctAnimation = mercatorCamera.createCorrectPositionTween(0.05); expect(correctAnimation).toBeDefined(); animation = tweens.add(correctAnimation); while (tweens.contains(animation)) { tweens.update(); } expect(mercatorCamera.position.x).toEqualEpsilon( -max.x, import__431.Math.EPSILON6 ); expect(mercatorCamera.position.y).toEqualEpsilon( -max.y, import__431.Math.EPSILON6 ); }); it("flyTo uses CameraFlightPath", function() { spyOn(import__430.CameraFlightPath, "createTween").and.returnValue({ startObject: {}, stopObject: {}, duration: 1e-3 }); const options = { destination: import__430.Cartesian3.fromDegrees(-117.16, 32.71, 15e3), orientation: { heading: 0, pitch: 1, roll: 2 }, duration: 3, complete: function() { }, cancel: function() { }, endTransform: new import__430.Matrix4(), convert: true, maximumHeight: 100, pitchAdjustHeight: 101, flyOverLongitude: 1, flyOverLongitudeWeight: 20, easingFunction: function() { } }; camera.flyTo(options); const args = import__430.CameraFlightPath.createTween.calls.argsFor(0); const passedOptions = args[1]; expect(import__430.CameraFlightPath.createTween).toHaveBeenCalled(); expect(args[0]).toBe(scene2); expect(passedOptions.destination).toBe(options.destination); expect(passedOptions.heading).toBe(options.orientation.heading); expect(passedOptions.pitch).toBe(options.orientation.pitch); expect(passedOptions.roll).toBe(options.orientation.roll); expect(typeof passedOptions.complete).toBe("function"); expect(passedOptions.cancel).toBe(options.cancel); expect(passedOptions.endTransform).toBe(options.endTransform); expect(passedOptions.convert).toBe(options.convert); expect(passedOptions.maximumHeight).toBe(options.maximumHeight); expect(passedOptions.easingFunction).toBe(options.easingFunction); expect(passedOptions.pitchAdjustHeight).toBe(options.pitchAdjustHeight); expect(passedOptions.flyOverLongitude).toBe(options.flyOverLongitude); expect(passedOptions.flyOverLongitudeWeight).toBe( options.flyOverLongitudeWeight ); }); it("can cancel a flight", function() { spyOn(import__430.CameraFlightPath, "createTween").and.returnValue({ startObject: {}, stopObject: {}, duration: 1e-3, complete: jasmine.createSpy("complete"), cancelTween: jasmine.createSpy("cancelTween") }); const options = { destination: import__430.Cartesian3.fromDegrees(-117.16, 32.71, 15e3) }; camera.flyTo(options); expect(camera._currentFlight).toBeDefined(); const createdTween = camera._currentFlight; spyOn(createdTween, "cancelTween"); camera.cancelFlight(); expect(createdTween.cancelTween).toHaveBeenCalled(); expect(createdTween.complete).not.toHaveBeenCalled(); expect(camera._currentFlight).toBeUndefined(); }); it("can complete a flight", function() { spyOn(import__430.CameraFlightPath, "createTween").and.returnValue({ startObject: {}, stopObject: {}, duration: 1e-3, complete: jasmine.createSpy("complete"), cancelTween: jasmine.createSpy("cancelTween") }); spyOn(camera, "setView"); const options = { destination: import__430.Cartesian3.fromDegrees(-117.16, 32.71, 15e3), orientation: { heading: 1, pitch: 2, roll: 3 } }; camera.flyTo(options); expect(camera._currentFlight).toBeDefined(); const createdTween = camera._currentFlight; spyOn(createdTween, "cancelTween"); camera.completeFlight(); expect(createdTween.cancelTween).toHaveBeenCalled(); expect(createdTween.complete).toHaveBeenCalled(); expect(camera._currentFlight).toBeUndefined(); expect(camera.setView).toHaveBeenCalledWith(options); }); it("flyTo with heading, pitch and roll", function() { scene2.mode = import__430.SceneMode.SCENE3D; const heading = import__431.Math.toRadians(180); const pitch = 0; const roll = import__431.Math.toRadians(45); const options = { destination: import__430.Cartesian3.fromDegrees(-117.16, 32.71, 0), orientation: { heading, pitch, roll }, duration: 0 }; camera.flyTo(options); expect(camera.heading).toEqualEpsilon(heading, import__431.Math.EPSILON6); expect(camera.pitch).toEqualEpsilon(pitch, import__431.Math.EPSILON6); expect(camera.roll).toEqualEpsilon(roll, import__431.Math.EPSILON6); }); it("flyTo with direction, up", function() { scene2.mode = import__430.SceneMode.SCENE3D; const direction = import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3()); const up2 = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Y); const options = { destination: import__430.Cartesian3.fromDegrees(-117.16, 32.71, 0), orientation: { direction, up: up2 }, duration: 0 }; camera.flyTo(options); expect(camera.direction).toEqualEpsilon(direction, import__431.Math.EPSILON6); expect(camera.up).toEqualEpsilon(up2, import__431.Math.EPSILON6); }); it("flyHome works in 3D", function() { camera._mode = import__430.SceneMode.SCENE3D; const destination = import__430.Cartesian3.fromDegrees(30, 20, 1e3); camera.setView({ destination }); camera.flyHome(0); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3( 2515865110478756e-9, -19109892759980734e-9, 13550929353715947e-9 ), import__431.Math.EPSILON8 ); expect(camera.direction).toEqualEpsilon( new import__430.Cartesian3( -0.10654051334260287, 0.8092555423939248, -0.5777149696185906 ), import__431.Math.EPSILON8 ); expect(camera.up).toEqualEpsilon( new import__430.Cartesian3( -0.07540693517283716, 0.5727725379670786, 0.8162385765685121 ), import__431.Math.EPSILON8 ); }); it("flyHome works in 2D", function() { camera._mode = import__430.SceneMode.SCENE2D; const destination = import__430.Cartesian3.fromDegrees(30, 20, 1e3); camera.setView({ destination }); camera.flyHome(0); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(-9183857990445068e-9, 3.8961821777645755e6, 1), import__431.Math.EPSILON8 ); expect(camera.direction).toEqualEpsilon( new import__430.Cartesian3(0, 0, -1), import__431.Math.EPSILON8 ); expect(camera.up).toEqualEpsilon(import__430.Cartesian3.UNIT_Y, import__431.Math.EPSILON8); }); it("flyHome works in CV", function() { const sq2Over2 = Math.sqrt(2) * 0.5; camera._mode = import__430.SceneMode.COLUMBUS_VIEW; const destination = import__430.Cartesian3.fromDegrees(30, 20, 1e3); camera.setView({ destination }); camera.flyHome(0); expect(camera.position).toEqualEpsilon( new import__430.Cartesian3(0, -22550119620184112e-9, 2255011962018411e-8), import__431.Math.EPSILON8 ); expect(camera.direction).toEqualEpsilon( new import__430.Cartesian3(0, sq2Over2, -sq2Over2), import__431.Math.EPSILON8 ); expect(camera.up).toEqualEpsilon( new import__430.Cartesian3(0, sq2Over2, sq2Over2), import__431.Math.EPSILON8 ); }); it("viewBoundingSphere", function() { scene2.mode = import__430.SceneMode.SCENE3D; const sphere = new import__430.BoundingSphere( import__430.Cartesian3.fromDegrees(-117.16, 32.71, 0), 1e4 ); camera.viewBoundingSphere(sphere); camera._setTransform(import__430.Matrix4.IDENTITY); const distance = import__430.Cartesian3.distance(camera.position, sphere.center); expect(distance).toBeGreaterThan(sphere.radius); expect(distance).toBeLessThan(sphere.radius * 3); }); it("viewBoundingSphere with offset", function() { scene2.mode = import__430.SceneMode.SCENE3D; const heading = import__431.Math.toRadians(45); const pitch = import__431.Math.toRadians(-45); const range = 15; const sphere = new import__430.BoundingSphere( import__430.Cartesian3.fromDegrees(-117.16, 32.71, 0), 10 ); camera.viewBoundingSphere( sphere, new import__430.HeadingPitchRange(heading, pitch, range) ); camera._setTransform(import__430.Matrix4.IDENTITY); const distance = import__430.Cartesian3.distance(camera.position, sphere.center); expect(distance).toEqualEpsilon(range, import__431.Math.EPSILON10); expect(camera.heading).toEqualEpsilon(heading, import__431.Math.EPSILON6); expect(camera.pitch).toEqualEpsilon(pitch, import__431.Math.EPSILON5); }); it("viewBoundingSphere does not modify offset.range when it is zero", function() { scene2.mode = import__430.SceneMode.SCENE3D; const heading = import__431.Math.toRadians(45); const pitch = import__431.Math.toRadians(-45); const range = 0; const offset = new import__430.HeadingPitchRange(heading, pitch, range); const sphere = new import__430.BoundingSphere( import__430.Cartesian3.fromDegrees(-117.16, 32.71, 0), 10 ); camera.viewBoundingSphere(sphere, offset); camera._setTransform(import__430.Matrix4.IDENTITY); expect(offset.heading).toEqual(import__431.Math.toRadians(45)); expect(offset.pitch).toEqual(import__431.Math.toRadians(-45)); expect(offset.range).toEqual(0); }); it("viewBoundingSphere in 2D", function() { const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.left = -10; frustum.right = 10; frustum.bottom = -10; frustum.top = 10; frustum.near = 1; frustum.far = 21; camera.frustum = frustum; camera.update(import__430.SceneMode.SCENE2D); const sphere = new import__430.BoundingSphere( import__430.Cartesian3.fromDegrees(-117.16, 32.71, 0), 1e4 ); camera.viewBoundingSphere(sphere); camera._setTransform(import__430.Matrix4.IDENTITY); const distance = frustum.right - frustum.left; expect(distance).toBeGreaterThan(sphere.radius); expect(distance).toBeLessThan(sphere.radius * 3); }); it("viewBoundingSphere in 3D with orthographic", function() { const frustum = new import__430.OrthographicFrustum(); frustum.aspectRatio = 1; frustum.width = 20; frustum.near = 1; frustum.far = 21; camera.frustum = frustum; camera.update(import__430.SceneMode.SCENE3D); expect(frustum.projectionMatrix).toBeDefined(); const sphere = new import__430.BoundingSphere( import__430.Cartesian3.fromDegrees(-117.16, 32.71, 0), 1e4 ); camera.viewBoundingSphere(sphere); camera._setTransform(import__430.Matrix4.IDENTITY); const distance = frustum.width; expect(distance).toBeGreaterThan(sphere.radius); expect(distance).toBeLessThan(sphere.radius * 3); }); it("viewBoundingSphere throws when morphing", function() { camera._mode = import__430.SceneMode.MORPHING; expect(function() { camera.viewBoundingSphere(new import__430.BoundingSphere()); }).toThrowDeveloperError(); }); it("viewBoundingSphere throws without bounding sphere", function() { camera._mode = import__430.SceneMode.MORPHING; expect(function() { camera.viewBoundingSphere(void 0); }).toThrowDeveloperError(); }); it("flyToBoundingSphere uses CameraFlightPath", function() { spyOn(import__430.CameraFlightPath, "createTween").and.returnValue({ startObject: {}, stopObject: {}, duration: 0 }); const sphere = new import__430.BoundingSphere( import__430.Cartesian3.fromDegrees(-117.16, 32.71, 0), 1e5 ); camera.flyToBoundingSphere(sphere); expect(import__430.CameraFlightPath.createTween).toHaveBeenCalled(); }); it("flyToBoundingSphere uses CameraFlightPath", function() { scene2.mode = import__430.SceneMode.SCENE3D; const sphere = new import__430.BoundingSphere( import__430.Cartesian3.fromDegrees(-117.16, 32.71, 0), 1e4 ); camera.flyToBoundingSphere(sphere, { duration: 0 }); const distance = import__430.Cartesian3.distance(camera.position, sphere.center); expect(distance).toBeGreaterThan(sphere.radius); expect(distance).toBeLessThan(sphere.radius * 3); }); it("flyToBoundingSphere does not zoom closer than minimumZoomDistance", function() { scene2.mode = import__430.SceneMode.SCENE3D; const minValue = 1e3; scene2.screenSpaceCameraController.minimumZoomDistance = minValue; const sphere = new import__430.BoundingSphere( import__430.Cartesian3.fromDegrees(-117.16, 32.71, 0), 10 ); camera.flyToBoundingSphere(sphere, { duration: 0 }); const distance = import__430.Cartesian3.distance(camera.position, sphere.center); expect(import__431.Math.equalsEpsilon(distance, minValue, 0.1)).toBe(true); }); it("flyToBoundingSphere does not zoom further than maximumZoomDistance", function() { scene2.mode = import__430.SceneMode.SCENE3D; const maxValue = 1e4; scene2.screenSpaceCameraController.maximumZoomDistance = maxValue; const sphere = new import__430.BoundingSphere( import__430.Cartesian3.fromDegrees(-117.16, 32.71, 0), 1e5 ); camera.flyToBoundingSphere(sphere, { duration: 0 }); const distance = import__430.Cartesian3.distance(camera.position, sphere.center); expect(import__431.Math.equalsEpsilon(distance, maxValue, 0.1)).toBe(true); }); it("flyToBoundingSphere does not modify options.offset range if it is zero ", function() { scene2.mode = import__430.SceneMode.SCENE3D; const options = { offset: new import__430.HeadingPitchRange(0, -1.5, 0) }; const sphere = new import__430.BoundingSphere( import__430.Cartesian3.fromDegrees(-117.16, 32.71, 0), 1e5 ); camera.flyToBoundingSphere(sphere, options); expect(options.offset.heading).toEqual(0); expect(options.offset.pitch).toEqual(-1.5); expect(options.offset.range).toEqual(0); }); it("distanceToBoundingSphere", function() { scene2.mode = import__430.SceneMode.SCENE3D; const sphere = new import__430.BoundingSphere(import__430.Cartesian3.ZERO, 0.5); const distance = camera.distanceToBoundingSphere(sphere); expect(distance).toEqual(0.5); }); it("distanceToBoundingSphere throws when there is no bounding sphere", function() { scene2.mode = import__430.SceneMode.SCENE3D; expect(function() { camera.distanceToBoundingSphere(); }).toThrowDeveloperError(); }); it("getPixelSize", function() { scene2.mode = import__430.SceneMode.SCENE3D; const oldPixelRatio = scene2.pixelRatio; scene2.pixelRatio = 1; const sphere = new import__430.BoundingSphere(import__430.Cartesian3.ZERO, 0.5); const context = scene2.context; const drawingBufferWidth = context.drawingBufferWidth; const drawingBufferHeight = context.drawingBufferHeight; const distance = camera.distanceToBoundingSphere(sphere); const pixelDimensions = camera.frustum.getPixelDimensions( drawingBufferWidth, drawingBufferHeight, distance, scene2.pixelRatio, new import__430.Cartesian2() ); const expectedPixelSize = Math.max(pixelDimensions.x, pixelDimensions.y); const pixelSize = camera.getPixelSize( sphere, drawingBufferWidth, drawingBufferHeight ); expect(pixelSize).toEqual(expectedPixelSize); scene2.pixelRatio = oldPixelRatio; }); it("getPixelSize throws when there is no bounding sphere", function() { scene2.mode = import__430.SceneMode.SCENE3D; expect(function() { camera.getPixelSize(); }).toThrowDeveloperError(); }); it("getPixelSize throws when there is no drawing buffer width", function() { scene2.mode = import__430.SceneMode.SCENE3D; const sphere = new import__430.BoundingSphere(import__430.Cartesian3.ZERO, 0.5); expect(function() { camera.getPixelSize(sphere); }).toThrowDeveloperError(); }); it("getPixelSize throws when there is no drawing buffer height", function() { scene2.mode = import__430.SceneMode.SCENE3D; const sphere = new import__430.BoundingSphere(import__430.Cartesian3.ZERO, 0.5); expect(function() { camera.getPixelSize(sphere, 10); }).toThrowDeveloperError(); }); it("computeViewRectangle when zoomed in", function() { scene2.mode = import__430.SceneMode.SCENE3D; const position2 = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_X); import__430.Cartesian3.multiplyByScalar(position2, 7e6, position2); camera.position = position2; camera.up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Z); camera.direction = import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_X, new import__430.Cartesian3()); camera.right = import__430.Cartesian3.cross( camera.direction, camera.up, new import__430.Cartesian3() ); const correctResult = new import__430.Rectangle( -0.05789100547374969, -0.04365869998457809, 0.05789100547374969, 0.04365869998457809 ); const rect = camera.computeViewRectangle(); expect(rect).toEqualEpsilon(correctResult, import__431.Math.EPSILON10); }); it("computeViewRectangle when zoomed in to pole", function() { scene2.mode = import__430.SceneMode.SCENE3D; const position2 = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Z); import__430.Cartesian3.multiplyByScalar(position2, 7e6, position2); camera.position = position2; camera.up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Y); camera.direction = import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3()); camera.right = import__430.Cartesian3.cross( camera.direction, camera.up, new import__430.Cartesian3() ); const correctResult = new import__430.Rectangle( -import__431.Math.PI, 1.4961779388065022, import__431.Math.PI, import__431.Math.PI_OVER_TWO ); const rect = camera.computeViewRectangle(); expect(rect).toEqual(correctResult); }); it("computeViewRectangle when zoomed in to IDL", function() { scene2.mode = import__430.SceneMode.SCENE3D; const position2 = import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_X, new import__430.Cartesian3()); import__430.Cartesian3.multiplyByScalar(position2, 7e6, position2); camera.position = position2; camera.up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Z); camera.direction = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_X, new import__430.Cartesian3()); camera.right = import__430.Cartesian3.cross( camera.direction, camera.up, new import__430.Cartesian3() ); const correctResult = new import__430.Rectangle( 3.0837016481160435, -0.04365869998457809, -3.0837016481160435, 0.04365869998457809 ); const rect = camera.computeViewRectangle(); expect(rect).toEqualEpsilon(correctResult, import__431.Math.EPSILON10); }); it("computeViewRectangle when zoomed out", function() { scene2.mode = import__430.SceneMode.SCENE3D; const position2 = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_X); import__430.Cartesian3.multiplyByScalar(position2, 25e6, position2); camera.position = position2; camera.up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Z); camera.direction = import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_X, new import__430.Cartesian3()); camera.right = import__430.Cartesian3.cross( camera.direction, camera.up, new import__430.Cartesian3() ); const rect = camera.computeViewRectangle(); expect(rect).toEqual(import__430.Rectangle.MAX_VALUE); }); it("computeViewRectangle when globe isn't visible", function() { scene2.mode = import__430.SceneMode.SCENE3D; const position2 = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_X); import__430.Cartesian3.multiplyByScalar(position2, 7e6, position2); camera.position = position2; camera.up = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Z); camera.direction = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_X); camera.right = import__430.Cartesian3.cross( camera.direction, camera.up, new import__430.Cartesian3() ); const rect = camera.computeViewRectangle(); expect(rect).not.toBeDefined(); }); it("flyTo rectangle in 2D", function() { const tweenSpy = spyOn(import__430.CameraFlightPath, "createTween").and.returnValue({}); spyOn(scene2.tweens, "add"); camera._mode = import__430.SceneMode.SCENE2D; const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.left = -10; frustum.right = 10; frustum.bottom = -10; frustum.top = 10; frustum.near = 1; frustum.far = 21; camera.frustum = frustum; const west = 0.3323436621771766; const south = 0.8292930502744068; const east = 0.3325710961342694; const north = 0.8297059734014236; const rectangle = new import__430.Rectangle(west, south, east, north); const expectedDestination = camera.getRectangleCameraCoordinates(rectangle); camera.flyTo({ destination: rectangle }); expect( tweenSpy.calls.mostRecent().args[1].destination.equalsEpsilon(expectedDestination, 0.1) ).toBe(true); }); it("flyTo rectangle in CV", function() { const tweenSpy = spyOn(import__430.CameraFlightPath, "createTween").and.returnValue({}); spyOn(scene2.tweens, "add"); camera._mode = import__430.SceneMode.COLUMBUS_VIEW; const west = 0.3323436621771766; const south = 0.8292930502744068; const east = 0.3325710961342694; const north = 0.8297059734014236; const rectangle = new import__430.Rectangle(west, south, east, north); const expectedDestination = camera.getRectangleCameraCoordinates(rectangle); camera.flyTo({ destination: rectangle }); expect( tweenSpy.calls.mostRecent().args[1].destination.equalsEpsilon(expectedDestination, 0.1) ).toBe(true); }); it("flyTo rectangle in 3D", function() { const tweenSpy = spyOn(import__430.CameraFlightPath, "createTween").and.returnValue({}); spyOn(scene2.tweens, "add"); camera._mode = import__430.SceneMode.SCENE3D; const west = 0.3323436621771766; const south = 0.8292930502744068; const east = 0.3325710961342694; const north = 0.8297059734014236; const rectangle = new import__430.Rectangle(west, south, east, north); const expectedDestination = camera.getRectangleCameraCoordinates(rectangle); camera.flyTo({ destination: rectangle }); expect( tweenSpy.calls.mostRecent().args[1].destination.equalsEpsilon(expectedDestination, 0.1) ).toBe(true); }); it("flyTo rectangle with orientation", function() { scene2.mode = import__430.SceneMode.SCENE3D; const direction = import__430.Cartesian3.negate(import__430.Cartesian3.UNIT_Z, new import__430.Cartesian3()); const up2 = import__430.Cartesian3.clone(import__430.Cartesian3.UNIT_Y); const west = 0.3323436621771766; const south = 0.8292930502744068; const east = 0.3325710961342694; const north = 0.8297059734014236; const rectangle = new import__430.Rectangle(west, south, east, north); const expectedDestination = camera.getRectangleCameraCoordinates(rectangle); camera.flyTo({ destination: rectangle, orientation: { direction, up: up2 }, duration: 0 }); expect(camera.direction).toEqualEpsilon(direction, import__431.Math.EPSILON6); expect(camera.up).toEqualEpsilon(up2, import__431.Math.EPSILON6); expect(camera.position).toEqualEpsilon( expectedDestination, import__431.Math.EPSILON1 ); }); it("flyTo does not zoom closer than minimumZoomDistance", function() { const tweenSpy = spyOn(import__430.CameraFlightPath, "createTween").and.returnValue({}); spyOn(scene2.tweens, "add"); scene2.mode = import__430.SceneMode.SCENE3D; scene2.screenSpaceCameraController.minimumZoomDistance = 1e3; scene2.screenSpaceCameraController.maximumZoomDistance = 1e4; const sourceDestination = import__430.Cartesian3.fromDegrees(-117.16, 32.71, 100); const expectedDestination = import__430.Cartesian3.clone(sourceDestination); expectedDestination.z = import__430.Cartesian3.fromDegrees(-117.16, 32.71, 1e3).z; camera.flyTo({ destination: sourceDestination }); expect( tweenSpy.calls.mostRecent().args[1].destination.equalsEpsilon(expectedDestination, 0.1) ).toBe(true); }); it("flyTo does not zoom further than maximumZoomDistance", function() { const tweenSpy = spyOn(import__430.CameraFlightPath, "createTween").and.returnValue({}); spyOn(scene2.tweens, "add"); scene2.mode = import__430.SceneMode.SCENE3D; scene2.screenSpaceCameraController.minimumZoomDistance = 1e3; scene2.screenSpaceCameraController.maximumZoomDistance = 1e4; const sourceDestination = import__430.Cartesian3.fromDegrees(-117.16, 32.71, 1e5); const expectedDestination = import__430.Cartesian3.clone(sourceDestination); expectedDestination.z = import__430.Cartesian3.fromDegrees(-117.16, 32.71, 1e4).z; camera.flyTo({ destination: sourceDestination }); expect( tweenSpy.calls.mostRecent().args[1].destination.equalsEpsilon(expectedDestination, 0.1) ).toBe(true); }); it("flyTo zooms in between minimumZoomDistance and maximumZoomDistance", function() { const tweenSpy = spyOn(import__430.CameraFlightPath, "createTween").and.returnValue({}); spyOn(scene2.tweens, "add"); scene2.mode = import__430.SceneMode.SCENE3D; scene2.screenSpaceCameraController.minimumZoomDistance = 1e3; scene2.screenSpaceCameraController.maximumZoomDistance = 1e4; const sourceDestination = import__430.Cartesian3.fromDegrees(-117.16, 32.71, 5e3); const expectedDestination = import__430.Cartesian3.clone(sourceDestination); camera.flyTo({ destination: sourceDestination }); expect( tweenSpy.calls.mostRecent().args[1].destination.equalsEpsilon(expectedDestination, 0.1) ).toBe(true); }); it("_currentFlight is not set for a flight that doesn't go anywhere", function() { const complete = jasmine.createSpy("complete"); spyOn(import__430.CameraFlightPath, "createTween").and.returnValue({ complete, duration: 0 }); spyOn(scene2.tweens, "add"); camera.flyTo({ complete, destination: import__430.Cartesian3.fromDegrees(-117.16, 32.71, 5e3) }); expect(complete).toHaveBeenCalled(); expect(camera._currentFlight).toBeUndefined(); }); it("switches projections", function() { expect(camera.frustum).toBeInstanceOf(import__430.PerspectiveFrustum); camera.switchToOrthographicFrustum(); expect(camera.frustum).toBeInstanceOf(import__430.OrthographicFrustum); camera.switchToPerspectiveFrustum(); expect(camera.frustum).toBeInstanceOf(import__430.PerspectiveFrustum); }); it("does not switch projection in 2D", function() { const ellipsoid = import__430.Ellipsoid.WGS84; const projection = new import__430.GeographicProjection(ellipsoid); const maxRadii = ellipsoid.maximumRadius; camera._mode = import__430.SceneMode.SCENE2D; camera._projection = projection; const frustum = new import__430.OrthographicOffCenterFrustum(); frustum.right = maxRadii * Math.PI; frustum.left = -frustum.right; frustum.top = frustum.right * (scene2.drawingBufferHeight / scene2.drawingBufferWidth); frustum.bottom = -frustum.top; frustum.near = 0.01 * maxRadii; frustum.far = 60 * maxRadii; camera.frustum = frustum; expect(camera.frustum).toBeInstanceOf(import__430.OrthographicOffCenterFrustum); camera.switchToOrthographicFrustum(); expect(camera.frustum).toBeInstanceOf(import__430.OrthographicOffCenterFrustum); camera.switchToPerspectiveFrustum(); expect(camera.frustum).toBeInstanceOf(import__430.OrthographicOffCenterFrustum); }); it("normalizes WC members", function() { const transform = import__430.Matrix4.fromScale(new import__430.Cartesian3(2, 2, 2)); camera.lookAtTransform(transform); expect(import__430.Cartesian3.magnitude(camera.directionWC)).toEqualEpsilon( 1, import__431.Math.EPSILON15 ); expect(import__430.Cartesian3.magnitude(camera.rightWC)).toEqualEpsilon( 1, import__431.Math.EPSILON15 ); expect(import__430.Cartesian3.magnitude(camera.upWC)).toEqualEpsilon( 1, import__431.Math.EPSILON15 ); }); it("get camera deltas", function() { camera._updateCameraChanged(); expect(camera.positionWCDeltaMagnitude).toEqual(0); expect(camera.positionWCDeltaMagnitudeLastFrame).toEqual(0); camera.moveUp(moveAmount); camera._updateCameraChanged(); expect(camera.positionWCDeltaMagnitude).toEqualEpsilon( moveAmount, import__431.Math.EPSILON10 ); expect(camera.positionWCDeltaMagnitudeLastFrame).toEqual(0); camera._updateCameraChanged(); expect(camera.positionWCDeltaMagnitude).toEqual(0); expect(camera.positionWCDeltaMagnitudeLastFrame).toEqualEpsilon( moveAmount, import__431.Math.EPSILON10 ); }); }); // packages/engine/Specs/Scene/Cesium3DContentGroupSpec.js var import__432 = __toESM(require_Cesium(), 1); describe("Scene/Cesium3DContentGroup", function() { const mockMetadata = {}; it("constructs", function() { const group = new import__432.Cesium3DContentGroup({ metadata: mockMetadata }); expect(group.metadata).toBe(mockMetadata); }); it("throws without metadata", function() { expect(function() { return new import__432.Cesium3DContentGroup({ metadata: void 0 }); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/Cesium3DTileBatchTableSpec.js var import__433 = __toESM(require_Cesium(), 1); // Specs/concatTypedArrays.js function concatTypedArrays(arrays) { let i; const length2 = arrays.length; let byteLength = 0; for (i = 0; i < length2; ++i) { byteLength += arrays[i].byteLength; } const buffer = new Uint8Array(byteLength); let byteOffset = 0; for (i = 0; i < length2; ++i) { const array = arrays[i]; const data = new Uint8Array( array.buffer, array.byteOffset, array.byteLength ); buffer.set(data, byteOffset); byteOffset += data.length; } return buffer; } var concatTypedArrays_default = concatTypedArrays; // packages/engine/Specs/Scene/Cesium3DTileBatchTableSpec.js xdescribe( "Scene/Cesium3DTileBatchTable", function() { let scene2; const centerLongitude = -1.31968; const centerLatitude = 0.698874; const withBatchTableUrl = "./Data/Cesium3DTiles/Batched/BatchedWithBatchTable/tileset.json"; const withoutBatchTableUrl = "./Data/Cesium3DTiles/Batched/BatchedWithoutBatchTable/tileset.json"; const withBatchTableBinaryUrl = "./Data/Cesium3DTiles/Batched/BatchedWithBatchTableBinary/tileset.json"; const noBatchIdsUrl = "./Data/Cesium3DTiles/Batched/BatchedNoBatchIds/tileset.json"; const batchTableHierarchyUrl = "./Data/Cesium3DTiles/Hierarchy/BatchTableHierarchy/tileset.json"; const batchTableHierarchyBinaryUrl = "./Data/Cesium3DTiles/Hierarchy/BatchTableHierarchyBinary/tileset.json"; const batchTableHierarchyMultipleParentsUrl = "./Data/Cesium3DTiles/Hierarchy/BatchTableHierarchyMultipleParents/tileset.json"; const batchTableHierarchyNoParentsUrl = "./Data/Cesium3DTiles/Hierarchy/BatchTableHierarchyNoParents/tileset.json"; const batchTableHierarchyLegacyUrl = "./Data/Cesium3DTiles/Hierarchy/BatchTableHierarchyLegacy/tileset.json"; const result = new import__433.Color(); const mockTileset = { statistics: { texturesByteLength: 0 }, getFeature: function(batchId) { return { batchId }; } }; mockTileset.tileset = mockTileset; beforeAll(function() { scene2 = createScene_default(); const center = import__433.Cartesian3.fromRadians(centerLongitude, centerLatitude); scene2.camera.lookAt(center, new import__433.HeadingPitchRange(0, -1.57, 20)); spyOn(import__433.Cesium3DTileBatchTable, "_deprecationWarning"); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.primitives.removeAll(); }); it("setShow throws with invalid batchId", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.setShow(); }).toThrowDeveloperError(); expect(function() { batchTable.setShow(-1); }).toThrowDeveloperError(); expect(function() { batchTable.setShow(1); }).toThrowDeveloperError(); }); it("setShow throws with undefined value", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.setShow(0); }).toThrowDeveloperError(); }); it("setShow sets show", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(batchTable.getShow(0)).toBe(true); batchTable.setShow(0, false); batchTable.update(mockTileset, scene2.frameState); expect(batchTable.getShow(0)).toEqual(false); }); it("getShow throws with invalid batchId", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.getShow(); }).toThrowDeveloperError(); expect(function() { batchTable.getShow(-1); }).toThrowDeveloperError(); expect(function() { batchTable.getShow(1); }).toThrowDeveloperError(); }); it("getShow", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(batchTable.getShow(0)).toEqual(true); batchTable.setShow(0, false); expect(batchTable.getShow(0)).toEqual(false); }); it("setColor throws with invalid batchId", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.setColor(); }).toThrowDeveloperError(); expect(function() { batchTable.setColor(-1); }).toThrowDeveloperError(); expect(function() { batchTable.setColor(1); }).toThrowDeveloperError(); }); it("setColor throws with undefined value", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.setColor(0); }).toThrowDeveloperError(); }); it("setColor", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); batchTable.setColor(0, import__433.Color.YELLOW); batchTable.update(mockTileset, scene2.frameState); expect(batchTable.getColor(0, result)).toEqual(import__433.Color.YELLOW); }); it("setAllColor throws with undefined value", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.setAllColor(); }).toThrowDeveloperError(); }); it("setAllColor", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 2); batchTable.setAllColor(import__433.Color.YELLOW); expect(batchTable.getColor(0, result)).toEqual(import__433.Color.YELLOW); expect(batchTable.getColor(1, result)).toEqual(import__433.Color.YELLOW); }); it("setAllShow throws with undefined value", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.setAllShow(); }).toThrowDeveloperError(); }); it("setAllShow", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 2); batchTable.setAllShow(false); expect(batchTable.getShow(0)).toBe(false); expect(batchTable.getShow(1)).toBe(false); }); it("getColor throws with invalid batchId", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.getColor(); }).toThrowDeveloperError(); expect(function() { batchTable.getColor(-1); }).toThrowDeveloperError(); expect(function() { batchTable.getColor(1); }).toThrowDeveloperError(); }); it("getColor throws with undefined result", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.getColor(0); }).toThrowDeveloperError(); }); it("getColor", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(batchTable.getColor(0, result)).toEqual(import__433.Color.WHITE); batchTable.setColor(0, import__433.Color.YELLOW); expect(batchTable.getColor(0, result)).toEqual(import__433.Color.YELLOW); }); it("hasProperty throws with invalid batchId", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.hasProperty(); }).toThrowDeveloperError(); expect(function() { batchTable.hasProperty(-1); }).toThrowDeveloperError(); expect(function() { batchTable.hasProperty(1); }).toThrowDeveloperError(); }); it("hasProperty throws with undefined name", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.hasProperty(0); }).toThrowDeveloperError(); }); it("hasProperty", function() { const batchTableJson = { height: [0] }; const batchTable = new import__433.Cesium3DTileBatchTable( mockTileset, 1, batchTableJson ); expect(batchTable.hasProperty(0, "height")).toEqual(true); expect(batchTable.hasProperty(0, "id")).toEqual(false); }); it("getPropertyIds throws with invalid batchId", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.getPropertyIds(); }).toThrowDeveloperError(); expect(function() { batchTable.getPropertyIds(-1); }).toThrowDeveloperError(); expect(function() { batchTable.getPropertyIds(1); }).toThrowDeveloperError(); }); it("getPropertyIds", function() { let batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(batchTable.getPropertyIds(0)).toEqual([]); const batchTableJson = { height: [0], id: [0] }; batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1, batchTableJson); expect(batchTable.getPropertyIds(0)).toEqual(["height", "id"]); }); it("getPropertyIds works with results argument", function() { const batchTableJson = { height: [0], id: [0] }; const batchTable = new import__433.Cesium3DTileBatchTable( mockTileset, 1, batchTableJson ); const results = []; const names = batchTable.getPropertyIds(0, results); expect(names).toBe(results); expect(names).toEqual(["height", "id"]); }); it("getProperty throws with invalid batchId", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.getProperty(); }).toThrowDeveloperError(); expect(function() { batchTable.getProperty(-1); }).toThrowDeveloperError(); expect(function() { batchTable.getProperty(1); }).toThrowDeveloperError(); }); it("getProperty throws with undefined name", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.getProperty(0); }).toThrowDeveloperError(); }); it("getProperty", function() { let batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(batchTable.getProperty(0, "height")).toBeUndefined(); const batchTableJson = { height: [1] }; batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1, batchTableJson); expect(batchTable.getProperty(0, "height")).toEqual(1); expect(batchTable.getProperty(0, "id")).toBeUndefined(); }); it("setProperty throws with invalid batchId", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.setProperty(); }).toThrowDeveloperError(); expect(function() { batchTable.setProperty(-1); }).toThrowDeveloperError(); expect(function() { batchTable.setProperty(1); }).toThrowDeveloperError(); }); it("setProperty throws with undefined name", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.setProperty(0); }).toThrowDeveloperError(); }); it("setProperty without existing batch table", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 3); batchTable.setProperty(0, "height", 1); expect(batchTable._properties.height.length).toEqual(3); expect(batchTable.getProperty(0, "height")).toEqual(1); expect(batchTable.getProperty(1, "height")).toBeUndefined(); expect(batchTable.getProperty(2, "height")).toBeUndefined(); }); it("setProperty with existing batch table", function() { const batchTableJson = { height: [1, 2] }; const batchTable = new import__433.Cesium3DTileBatchTable( mockTileset, 2, batchTableJson ); batchTable.setProperty(0, "height", 3); expect(batchTable.getProperty(0, "height")).toEqual(3); expect(batchTable.getProperty(1, "height")).toEqual(2); }); it("setProperty with object value", function() { const batchTableJson = { info: [ { name: "building0", year: 2e3 }, { name: "building1", year: 2001 } ] }; const batchTable = new import__433.Cesium3DTileBatchTable( mockTileset, 2, batchTableJson ); batchTable.setProperty(0, "info", { name: "building0_new", year: 2002 }); expect(batchTable.getProperty(0, "info")).toEqual({ name: "building0_new", year: 2002 }); expect(batchTable.getProperty(1, "info")).toEqual({ name: "building1", year: 2001 }); }); it("setProperty with array value", function() { const batchTableJson = { rooms: [ ["room1", "room2"], ["room3", "room4"] ] }; const batchTable = new import__433.Cesium3DTileBatchTable( mockTileset, 2, batchTableJson ); batchTable.setProperty(0, "rooms", ["room1_new", "room2"]); expect(batchTable.getProperty(0, "rooms")).toEqual([ "room1_new", "room2" ]); expect(batchTable.getProperty(1, "rooms")).toEqual(["room3", "room4"]); }); it("throws if the binary property does not specify a componentType", function() { const batchTableJson = { propertyScalar: { byteOffset: 0, type: "SCALAR" } }; const batchTableBinary = new Float64Array([0, 1]); expect(function() { return new import__433.Cesium3DTileBatchTable( mockTileset, 2, batchTableJson, batchTableBinary ); }).toThrowError(import__433.RuntimeError); }); it("throws if the binary property does not specify a type", function() { const batchTableJson = { propertyScalar: { byteOffset: 0, componentType: "DOUBLE" } }; const batchTableBinary = new Float64Array([0, 1]); expect(function() { return new import__433.Cesium3DTileBatchTable( mockTileset, 2, batchTableJson, batchTableBinary ); }).toThrowError(import__433.RuntimeError); }); it("throws if a binary property exists but there is no batchTableBinary", function() { const batchTableJson = { propertyScalar: { byteOffset: 0, componentType: "DOUBLE", type: "SCALAR" } }; expect(function() { return new import__433.Cesium3DTileBatchTable(mockTileset, 2, batchTableJson); }).toThrowError(import__433.RuntimeError); }); it("getProperty and setProperty work for binary properties", function() { const propertyScalarBinary = new Float64Array([0, 1]); const propertyVec2Binary = new Float32Array([2, 3, 4, 5]); const propertyVec3Binary = new Int32Array([6, 7, 8, 9, 10, 11]); const propertyVec4Binary = new Uint32Array([ 12, 13, 14, 15, 16, 17, 18, 19 ]); const propertyMat2Binary = new Int16Array([ 20, 21, 22, 23, 24, 25, 26, 27 ]); const propertyMat3Binary = new Uint16Array([ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45 ]); const propertyMat4Binary = new Uint8Array([ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77 ]); const buffers = [ propertyScalarBinary, propertyVec2Binary, propertyVec3Binary, propertyVec4Binary, propertyMat2Binary, propertyMat3Binary, propertyMat4Binary ]; const batchTableBinary = concatTypedArrays_default(buffers); const batchTableJson = { propertyScalar: { byteOffset: 0, componentType: "DOUBLE", type: "SCALAR" }, propertyVec2: { byteOffset: 16, componentType: "FLOAT", type: "VEC2" }, propertyVec3: { byteOffset: 32, componentType: "INT", type: "VEC3" }, propertyVec4: { byteOffset: 56, componentType: "UNSIGNED_INT", type: "VEC4" }, propertyMat2: { byteOffset: 88, componentType: "SHORT", type: "MAT2" }, propertyMat3: { byteOffset: 104, componentType: "UNSIGNED_SHORT", type: "MAT3" }, propertyMat4: { byteOffset: 140, componentType: "UNSIGNED_BYTE", type: "MAT4" } }; const batchTable = new import__433.Cesium3DTileBatchTable( mockTileset, 2, batchTableJson, batchTableBinary ); expect(batchTable.getProperty(1, "propertyScalar")).toEqual(1); expect(batchTable.getProperty(1, "propertyVec2")).toEqual( new import__433.Cartesian2(4, 5) ); expect(batchTable.getProperty(1, "propertyVec3")).toEqual( new import__433.Cartesian3(9, 10, 11) ); expect(batchTable.getProperty(1, "propertyVec4")).toEqual( new import__433.Cartesian4(16, 17, 18, 19) ); expect(batchTable.getProperty(1, "propertyMat2")).toEqual( new import__433.Matrix2(24, 26, 25, 27) ); expect(batchTable.getProperty(1, "propertyMat3")).toEqual( new import__433.Matrix3(37, 40, 43, 38, 41, 44, 39, 42, 45) ); expect(batchTable.getProperty(1, "propertyMat4")).toEqual( new import__433.Matrix4( 62, 66, 70, 74, 63, 67, 71, 75, 64, 68, 72, 76, 65, 69, 73, 77 ) ); batchTable.setProperty(1, "propertyScalar", 2); batchTable.setProperty(1, "propertyVec2", new import__433.Cartesian2(5, 6)); batchTable.setProperty(1, "propertyVec3", new import__433.Cartesian3(10, 11, 12)); batchTable.setProperty(1, "propertyVec4", new import__433.Cartesian4(17, 18, 19, 20)); batchTable.setProperty(1, "propertyMat2", new import__433.Matrix2(25, 27, 26, 28)); batchTable.setProperty( 1, "propertyMat3", new import__433.Matrix3(38, 41, 44, 39, 42, 45, 40, 43, 46) ); batchTable.setProperty( 1, "propertyMat4", new import__433.Matrix4( 63, 67, 71, 75, 64, 68, 72, 76, 65, 69, 73, 77, 66, 70, 74, 78 ) ); expect(batchTable.getProperty(1, "propertyScalar")).toEqual(2); expect(batchTable.getProperty(1, "propertyVec2")).toEqual( new import__433.Cartesian2(5, 6) ); expect(batchTable.getProperty(1, "propertyVec3")).toEqual( new import__433.Cartesian3(10, 11, 12) ); expect(batchTable.getProperty(1, "propertyVec4")).toEqual( new import__433.Cartesian4(17, 18, 19, 20) ); expect(batchTable.getProperty(1, "propertyMat2")).toEqual( new import__433.Matrix2(25, 27, 26, 28) ); expect(batchTable.getProperty(1, "propertyMat3")).toEqual( new import__433.Matrix3(38, 41, 44, 39, 42, 45, 40, 43, 46) ); expect(batchTable.getProperty(1, "propertyMat4")).toEqual( new import__433.Matrix4( 63, 67, 71, 75, 64, 68, 72, 76, 65, 69, 73, 77, 66, 70, 74, 78 ) ); }); it("renders tileset with batch table", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(tileset) { const content = tileset.root.content; expect(content.getFeature(2).getProperty("id")).toEqual(2); expect(content.getFeature(2).getProperty("rooms")).toEqual([ "room2_a", "room2_b", "room2_c" ]); expect(content.getFeature(2).getProperty("info")).toEqual({ name: "building2", year: 2 }); Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); } ); }); it("renders tileset without batch table", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withoutBatchTableUrl).then( function(tileset) { const content = tileset.root.content; expect(content.getFeature(2).getProperty("id")).toBeUndefined(); Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); } ); }); it("renders when vertex texture fetch is not supported", function() { const maximumVertexTextureImageUnits = import__433.ContextLimits.maximumVertexTextureImageUnits; import__433.ContextLimits._maximumVertexTextureImageUnits = 0; return Cesium3DTilesTester_default.loadTileset(scene2, withoutBatchTableUrl).then( function(tileset) { Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); import__433.ContextLimits._maximumVertexTextureImageUnits = maximumVertexTextureImageUnits; } ); }); it("renders with featuresLength greater than maximumTextureSize", function() { const maximumTextureSize = import__433.ContextLimits.maximumTextureSize; import__433.ContextLimits._maximumTextureSize = 4; return Cesium3DTilesTester_default.loadTileset(scene2, withoutBatchTableUrl).then( function(tileset) { const content = tileset.root.content; expect(content.featuresLength).toBeGreaterThan( import__433.ContextLimits._maximumTextureSize ); Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); import__433.ContextLimits._maximumTextureSize = maximumTextureSize; } ); }); it("renders with featuresLength of zero", function() { return Cesium3DTilesTester_default.loadTileset(scene2, noBatchIdsUrl).then( function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); expect(scene2).toPickAndCall(function(result2) { expect(result2).toBeDefined(); expect(result2.primitive).toBe(tileset); }); } ); }); function expectRenderTranslucent(tileset) { const batchTable = tileset.root.content.batchTable; let opaqueColor; Cesium3DTilesTester_default.expectRender(scene2, tileset, function(rgba) { opaqueColor = rgba; }); batchTable.setAllColor(new import__433.Color(1, 1, 1, 0.5)); Cesium3DTilesTester_default.expectRender(scene2, tileset, function(rgba) { expect(rgba).not.toEqual(opaqueColor); }); batchTable.setAllColor(import__433.Color.WHITE); Cesium3DTilesTester_default.expectRender(scene2, tileset, function(rgba) { expect(rgba).toEqual(opaqueColor); }); batchTable.setColor(0, new import__433.Color(1, 1, 1, 0.5)); Cesium3DTilesTester_default.expectRender(scene2, tileset); batchTable.setAllColor(new import__433.Color(1, 1, 1, 0)); Cesium3DTilesTester_default.expectRenderBlank(scene2, tileset); } it("renders translucent style", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withoutBatchTableUrl).then( function(tileset) { expectRenderTranslucent(tileset); } ); }); it("renders translucent style when vertex texture fetch is not supported", function() { const maximumVertexTextureImageUnits = import__433.ContextLimits.maximumVertexTextureImageUnits; import__433.ContextLimits._maximumVertexTextureImageUnits = 0; return Cesium3DTilesTester_default.loadTileset(scene2, withoutBatchTableUrl).then( function(tileset) { expectRenderTranslucent(tileset); import__433.ContextLimits._maximumVertexTextureImageUnits = maximumVertexTextureImageUnits; } ); }); it("isExactClass throws with invalid batchId", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.isExactClass(); }).toThrowDeveloperError(); expect(function() { batchTable.isExactClass(1, "door"); }).toThrowDeveloperError(); expect(function() { batchTable.isExactClass(-1, "door"); }).toThrowDeveloperError(); }); it("isExactClass throws with undefined className", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.isExactClass(0); }).toThrowDeveloperError(); }); it("isClass throws with invalid batchId", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.isClass(); }).toThrowDeveloperError(); expect(function() { batchTable.isClass(1, "door"); }).toThrowDeveloperError(); expect(function() { batchTable.isClass(-1, "door"); }).toThrowDeveloperError(); }); it("isClass throws with undefined className", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.isClass(0); }).toThrowDeveloperError(); }); it("getExactClassName throws with invalid batchId", function() { const batchTable = new import__433.Cesium3DTileBatchTable(mockTileset, 1); expect(function() { batchTable.getExactClassName(); }).toThrowDeveloperError(); expect(function() { batchTable.getExactClassName(1); }).toThrowDeveloperError(); expect(function() { batchTable.getExactClassName(-1); }).toThrowDeveloperError(); }); function checkHierarchyStyling(tileset) { tileset.style = new import__433.Cesium3DTileStyle({ color: "${height} === 6.0 ? color('red') : color('green')" }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); }); tileset.style = new import__433.Cesium3DTileStyle({ color: "${roof_name} === 'roof2' ? color('red') : color('green')" }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); }); tileset.style = new import__433.Cesium3DTileStyle({ color: "${building_name} === 'building2' ? color('red') : color('green')" }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); }); tileset.style = new import__433.Cesium3DTileStyle({ color: "isExactClass('roof') ? color('red') : color('green')" }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); }); tileset.style = new import__433.Cesium3DTileStyle({ color: "isExactClass('door') ? color('red') : color('green')" }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[1]).toBeGreaterThan(1); }); tileset.style = new import__433.Cesium3DTileStyle({ color: "isClass('roof') ? color('red') : color('green')" }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); }); tileset.style = new import__433.Cesium3DTileStyle({ color: "isClass('zone') ? color('red') : color('green')" }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); }); tileset.style = new import__433.Cesium3DTileStyle({ color: "getExactClassName() === 'roof' ? color('red') : color('green')" }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); }); tileset.style = new import__433.Cesium3DTileStyle({ color: "getExactClassName() === 'zone' ? color('red') : color('green')" }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[1]).toBeGreaterThan(0); }); } function checkHierarchyStylingNoParents(tileset) { tileset.style = new import__433.Cesium3DTileStyle({ color: "${height} === 6.0 ? color('red') : color('green')" }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); }); tileset.style = new import__433.Cesium3DTileStyle({ color: "${roof_name} === 'roof2' ? color('red') : color('green')" }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); }); tileset.style = new import__433.Cesium3DTileStyle({ color: "isExactClass('roof') ? color('red') : color('green')" }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); }); tileset.style = new import__433.Cesium3DTileStyle({ color: "isClass('roof') ? color('red') : color('green')" }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); }); tileset.style = new import__433.Cesium3DTileStyle({ color: "getExactClassName() === 'roof' ? color('red') : color('green')" }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); }); } function checkHierarchyProperties(tileset, multipleParents) { const content = tileset.root.content; const batchTable = content.batchTable; const hierarchy = batchTable._batchTableHierarchy; const doorFeature = content.getFeature(4); const roofFeature = content.getFeature(8); expect(doorFeature.isExactClass("door")).toBe(true); expect(doorFeature.isExactClass("building")).toBe(false); expect(doorFeature.isClass("door")).toBe(true); expect(doorFeature.isClass("doorknob")).toBe(false); expect(doorFeature.isClass("building")).toBe(true); expect(doorFeature.getExactClassName()).toBe("door"); expect(doorFeature.hasProperty("door_name")).toBe(true); expect(doorFeature.hasProperty("height")).toBe(true); const expectedPropertyIds = [ "height", "area", "door_mass", "door_width", "door_name", "building_area", "building_name", "zone_buildings", "zone_name" ]; if (multipleParents) { expectedPropertyIds.push("year", "color", "name", "architect"); expectedPropertyIds.push("description", "inspection"); } const propertyIds = doorFeature.getPropertyIds(); expect(expectedPropertyIds.sort()).toEqual(propertyIds.sort()); expect(doorFeature.getProperty("height")).toBe(5); expect(doorFeature.getProperty("door_name")).toBe("door0"); expect(doorFeature.getProperty("building_name")).toBe("building0"); doorFeature.setProperty("height", 10); expect(doorFeature.getProperty("height")).toBe(10); doorFeature.setProperty("door_name", "new_door"); expect(doorFeature.getProperty("door_name")).toBe("new_door"); expect(roofFeature.getProperty("door_name")).toBeUndefined(); expect(function() { doorFeature.setProperty("building_name", "new_building"); }).toThrowDeveloperError(); batchTable._batchTableHierarchy = void 0; expect(doorFeature.isExactClass("door")).toBe(false); expect(doorFeature.isClass("door")).toBe(false); expect(doorFeature.getExactClassName()).toBeUndefined(); expect(doorFeature.hasProperty("door_name")).toBe(false); expect(doorFeature.hasProperty("height")).toBe(true); expect(doorFeature.getPropertyIds()).toEqual(["height", "area"]); expect(doorFeature.getProperty("height")).toBe(10); expect(doorFeature.getProperty("door_name")).toBeUndefined(); expect(doorFeature.getProperty("building_name")).toBeUndefined(); batchTable._batchTableHierarchy = hierarchy; } function checkHierarchyPropertiesNoParents(tileset) { const content = tileset.root.content; const doorFeature = content.getFeature(4); expect(doorFeature.isExactClass("door")).toBe(true); expect(doorFeature.isExactClass("doorknob")).toBe(false); expect(doorFeature.isClass("door")).toBe(true); expect(doorFeature.isClass("doorknob")).toBe(false); expect(doorFeature.getExactClassName()).toBe("door"); expect(doorFeature.hasProperty("door_name")).toBe(true); expect(doorFeature.hasProperty("height")).toBe(true); const expectedPropertyIds = [ "height", "area", "door_mass", "door_width", "door_name" ]; const propertyIds = doorFeature.getPropertyIds(); expect(expectedPropertyIds.sort()).toEqual(propertyIds.sort()); expect(doorFeature.getProperty("height")).toBe(5); expect(doorFeature.getProperty("door_name")).toBe("door0"); doorFeature.setProperty("height", 10); expect(doorFeature.getProperty("height")).toBe(10); doorFeature.setProperty("door_name", "new_door"); expect(doorFeature.getProperty("door_name")).toBe("new_door"); } function checkBatchTableHierarchy(url, multipleParents) { return Cesium3DTilesTester_default.loadTileset(scene2, url).then(function(tileset) { checkHierarchyStyling(tileset); checkHierarchyProperties(tileset, multipleParents); }); } function checkBatchTableHierarchyNoParents(url) { return Cesium3DTilesTester_default.loadTileset(scene2, url).then(function(tileset) { checkHierarchyStylingNoParents(tileset); checkHierarchyPropertiesNoParents(tileset); }); } it("renders tileset with batch table hierarchy extension", function() { return checkBatchTableHierarchy(batchTableHierarchyUrl, false); }); it("renders tileset with batch table hierarchy using binary properties", function() { return checkBatchTableHierarchy(batchTableHierarchyBinaryUrl, true); }); it("renders tileset with batch table hierarchy with multiple parent classes", function() { return checkBatchTableHierarchy( batchTableHierarchyMultipleParentsUrl, true ); }); it("renders tileset with batch table hierarchy with no parents", function() { return checkBatchTableHierarchyNoParents(batchTableHierarchyNoParentsUrl); }); it("renders tileset with legacy batch table hierarchy (pre-version 1.0)", function() { return checkBatchTableHierarchy(batchTableHierarchyLegacyUrl, false); }); it("warns about deprecated batch hierarchy (pre-version 1.0)", function() { return checkBatchTableHierarchy(batchTableHierarchyLegacyUrl, false).then( function(tileset) { expect(import__433.Cesium3DTileBatchTable._deprecationWarning).toHaveBeenCalled(); } ); }); it("computes batchTableByteLength without a batch table", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withoutBatchTableUrl).then( function(tileset) { const content = tileset.root.content; const batchTable = content.batchTable; expect(batchTable.batchTableByteLength).toBe(0); scene2.pickForSpecs(); const batchTextureSize = batchTable._batchTexture.byteLength; expect(batchTable.batchTableByteLength).toBe(batchTextureSize); } ); }); it("batchTableByteLength does not count JSON batch table properties", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(tileset) { const content = tileset.root.content; const batchTable = content.batchTable; expect(batchTable.batchTableByteLength).toBe(0); scene2.pickForSpecs(); const batchTextureSize = batchTable._batchTexture.byteLength; expect(batchTable.batchTableByteLength).toBe(batchTextureSize); } ); }); it("computes batchTableByteLength for binary batch table", function() { return Cesium3DTilesTester_default.loadTileset( scene2, withBatchTableBinaryUrl ).then(function(tileset) { const content = tileset.root.content; const batchTable = content.batchTable; const binaryPropertiesByteLength = batchTable._binaryPropertiesByteLength; expect(batchTable.batchTableByteLength).toBe( binaryPropertiesByteLength ); scene2.pickForSpecs(); const batchTextureSize = batchTable._batchTexture.byteLength; expect(batchTable.batchTableByteLength).toBe( binaryPropertiesByteLength + batchTextureSize ); }); }); it("computes batchTableByteLength with a batch table hierarchy", function() { return Cesium3DTilesTester_default.loadTileset( scene2, batchTableHierarchyUrl ).then(function(tileset) { const content = tileset.root.content; const batchTable = content.batchTable; const hierarchySize = batchTable._batchTableHierarchy.byteLength; expect(batchTable.batchTableByteLength).toBe(hierarchySize); scene2.pickForSpecs(); const batchTextureSize = batchTable._batchTexture.byteLength; expect(batchTable.batchTableByteLength).toBe( hierarchySize + batchTextureSize ); }); }); it("destroys", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withoutBatchTableUrl).then( function(tileset) { const content = tileset.root.content; const batchTable = content.batchTable; expect(batchTable.isDestroyed()).toEqual(false); scene2.primitives.remove(tileset); expect(batchTable.isDestroyed()).toEqual(true); } ); }); }, "WebGL" ); // packages/engine/Specs/Scene/Cesium3DTileContentSpec.js var import__434 = __toESM(require_Cesium(), 1); describe("Scene/Cesium3DTileContent", function() { it("throws", function() { const content = new import__434.Cesium3DTileContent(); expect(function() { return content.featuresLength; }).toThrowDeveloperError(); expect(function() { return content.pointsLength; }).toThrowDeveloperError(); expect(function() { return content.trianglesLength; }).toThrowDeveloperError(); expect(function() { return content.geometryByteLength; }).toThrowDeveloperError(); expect(function() { return content.texturesByteLength; }).toThrowDeveloperError(); expect(function() { return content.batchTableByteLength; }).toThrowDeveloperError(); expect(function() { return content.innerContents; }).toThrowDeveloperError(); expect(function() { return content.tileset; }).toThrowDeveloperError(); expect(function() { return content.tile; }).toThrowDeveloperError(); expect(function() { return content.url; }).toThrowDeveloperError(); expect(function() { return content.batchTable; }).toThrowDeveloperError(); expect(function() { return content.group; }).toThrowDeveloperError(); expect(function() { content.group = {}; }).toThrowDeveloperError(); expect(function() { return content.hasProperty(0, "height"); }).toThrowDeveloperError(); expect(function() { return content.getFeature(0); }).toThrowDeveloperError(); expect(function() { content.applyDebugSettings(); }).toThrowDeveloperError(); expect(function() { content.applyStyle(); }).toThrowDeveloperError(); expect(function() { content.update(); }).toThrowDeveloperError(); expect(function() { content.isDestroyed(); }).toThrowDeveloperError(); expect(function() { content.destroy(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/Cesium3DTileContentTypeSpec.js var import__435 = __toESM(require_Cesium(), 1); describe("Scene/Cesium3DTileContentType", function() { it("isBinaryFormat correctly identifies binary contents", function() { const types = [ "b3dm", "i3dm", "glb", "vctr", "geom", "subt", "cmpt", "pnts" ]; types.map(function(type) { expect(import__435.Cesium3DTileContentType.isBinaryFormat(type)).toBe(true); }); }); it("isBinaryFormat returns false for other content types", function() { const types = [ "gltf", "subtreeJson", "externalTileset", "multipleContent", "geoJson", "notAMagic" ]; types.map(function(type) { expect(import__435.Cesium3DTileContentType.isBinaryFormat(type)).toBe(false); }); }); }); // packages/engine/Specs/Scene/Cesium3DTileFeatureSpec.js var import__436 = __toESM(require_Cesium(), 1); describe( "Scene/Cesium3DTileFeature", function() { describe("polylinePositions", function() { const vectorPolylinesWithBatchIds = "./Data/Cesium3DTiles/Vector/VectorTilePolylinesWithBatchIds/tileset.json"; const b3dmWithBatchIds = "Data/Cesium3DTiles/Batched/BatchedWithBatchTable/tileset.json"; let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { scene2.primitives.removeAll(); }); it("polylinePositions gets positions for polyline vector data", function() { const tilesetRectangle = import__436.Rectangle.fromDegrees( -0.01, -0.01, 0.01, 0.01 ); const ellipsoid = import__436.Ellipsoid.WGS84; scene2.camera.lookAt( ellipsoid.cartographicToCartesian(import__436.Rectangle.center(tilesetRectangle)), new import__436.Cartesian3(0, 0, 0.01) ); return Cesium3DTilesTester_default.loadTileset( scene2, vectorPolylinesWithBatchIds, { vectorKeepDecodedPositions: true } ).then(function(tileset) { const feature = tileset.root.children[0].content.getFeature(0); const polylinePositions = feature.polylinePositions; expect(polylinePositions.length).toBe(60); expect(polylinePositions[0]).toEqualEpsilon( 6378136806372941e-9, import__436.Math.EPSILON7 ); expect(polylinePositions[1]).toEqualEpsilon( -1113.194885441724, import__436.Math.EPSILON7 ); expect(polylinePositions[2]).toEqualEpsilon( 1105.675261474196, import__436.Math.EPSILON7 ); }); }); it("polylinePositions returns undefined for non polyline features", function() { const centerLongitude2 = -1.31968; const centerLatitude2 = 0.698874; const center = import__436.Cartesian3.fromRadians(centerLongitude2, centerLatitude2); scene2.camera.lookAt(center, new import__436.HeadingPitchRange(0, -1.57, 15)); return Cesium3DTilesTester_default.loadTileset(scene2, b3dmWithBatchIds, { vectorKeepDecodedPositions: true }).then(function(tileset) { const feature = tileset.root.content.getFeature(0); const polylinePositions = feature.polylinePositions; expect(polylinePositions).toBeUndefined(); }); }); }); const centerLongitude = -1.31968; const centerLatitude = 0.698874; const headingPitchRange = new import__436.HeadingPitchRange(0, -1.57, 15); describe("metadata", function() { const tilesetWithMetadataUrl = "Data/Cesium3DTiles/Metadata/AllMetadataTypes/tileset_1.1.json"; let scene2; let tileset; beforeAll(function() { scene2 = createScene_default(); const center = import__436.Cartesian3.fromRadians(centerLongitude, centerLatitude); scene2.camera.lookAt(center, headingPitchRange); return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithMetadataUrl ).then(function(result) { tileset = result; }); }); afterAll(function() { scene2.destroyForSpecs(); }); let parentContent; const childContents = {}; beforeEach(function() { parentContent = tileset.root.content; const children = tileset.root.children; children.forEach(function(child) { const uri = child._header.content.uri; childContents[uri] = child.content; }); }); it("getPropertyInherited returns undefined for unknown property", function() { const feature = new import__436.Cesium3DTileFeature(childContents["ll.b3dm"], 0); expect(feature.getPropertyInherited("unknown")).not.toBeDefined(); }); it("getPropertyInherited returns content property by semantic", function() { const feature = new import__436.Cesium3DTileFeature(childContents["ll.b3dm"], 0); expect(feature.getPropertyInherited("HIGHLIGHT_COLOR")).toEqual( new import__436.Cartesian4(255, 0, 0, 1) ); }); it("getPropertyInherited returns content property", function() { const feature = new import__436.Cesium3DTileFeature(childContents["ll.b3dm"], 0); expect(feature.getPropertyInherited("HIGHLIGHT_COLOR")).toEqual( new import__436.Cartesian4(255, 0, 0, 1) ); expect(feature.getPropertyInherited("triangleCount")).toBe(15e3); }); it("getPropertyInherited returns tile property by semantic", function() { const feature = new import__436.Cesium3DTileFeature(childContents["ll.b3dm"], 0); expect(feature.getPropertyInherited("COLOR")).toEqual( new import__436.Cartesian4(255, 255, 0, 1) ); }); it("getPropertyInherited returns tile property", function() { const feature = new import__436.Cesium3DTileFeature(childContents["ll.b3dm"], 0); expect(feature.getPropertyInherited("color")).toEqual( new import__436.Cartesian4(255, 255, 0, 1) ); expect(feature.getPropertyInherited("population")).toBe(50); }); it("getPropertyInherited returns default value", function() { const feature = new import__436.Cesium3DTileFeature(childContents["ll.b3dm"], 0); expect(feature.getPropertyInherited("defaultColor")).toEqual( new import__436.Cartesian4(255, 255, 255, 255) ); }); it("getPropertyInherited handles noData", function() { let feature = new import__436.Cesium3DTileFeature(childContents["ll.b3dm"], 0); expect(feature.getPropertyInherited("averageTemperature")).toEqual(24); feature = new import__436.Cesium3DTileFeature(childContents["ur.b3dm"], 0); expect( feature.getPropertyInherited("averageTemperature") ).not.toBeDefined(); }); it("getPropertyInherited returns group property by semantic", function() { let feature = new import__436.Cesium3DTileFeature(childContents["lr.b3dm"], 0); expect(feature.getPropertyInherited("GROUP_NAME")).toBe("commercial"); feature = new import__436.Cesium3DTileFeature(childContents["ll.b3dm"], 0); expect(feature.getPropertyInherited("GROUP_NAME")).toBe("residential"); }); it("getPropertyInherited returns group property", function() { const feature = new import__436.Cesium3DTileFeature(childContents["lr.b3dm"], 0); expect(feature.getPropertyInherited("majorIndustries")).toEqual([ "Finance", "Manufacturing" ]); expect(feature.getPropertyInherited("businessCount")).toBe(143); }); it("getPropertyInherited returns tileset property by semantic", function() { const feature = new import__436.Cesium3DTileFeature(parentContent, 0); expect(feature.getPropertyInherited("DATE_ISO_8601")).toBe( "2021-04-07" ); expect(feature.getPropertyInherited("AUTHOR")).toBe("Cesium"); }); it("getPropertyInherited returns tileset property", function() { const feature = new import__436.Cesium3DTileFeature(parentContent, 0); expect(feature.getPropertyInherited("centerCartographic")).toEqual( new import__436.Cartesian3( -1.3196816996258511, 0.6988767486400521, 45.78600543644279 ) ); expect(feature.getPropertyInherited("date")).toBe("2021-04-07"); expect(feature.getPropertyInherited("author")).toBe("Cesium"); expect(feature.getPropertyInherited("tileCount")).toBe(5); }); it("resolves conflicting names from most specific to most general", function() { const feature = new import__436.Cesium3DTileFeature(childContents["ll.b3dm"], 0); expect(feature.getPropertyInherited("highlightColor")).toEqual( new import__436.Cartesian4(255, 0, 0, 1) ); expect(feature.getPropertyInherited("author")).toEqual("First Author"); expect(feature.getPropertyInherited("color")).toEqual( new import__436.Cartesian4(255, 255, 0, 1) ); expect(feature.getPropertyInherited("tileCount")).toEqual(2); }); }); describe("3DTILES_metadata", function() { const tilesetWithMetadataExtensionUrl = "Data/Cesium3DTiles/Metadata/AllMetadataTypes/tileset_1.0.json"; let scene2; let tileset; beforeAll(function() { scene2 = createScene_default(); const center = import__436.Cartesian3.fromRadians(centerLongitude, centerLatitude); scene2.camera.lookAt(center, headingPitchRange); return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithMetadataExtensionUrl ).then(function(result) { tileset = result; }); }); afterAll(function() { scene2.destroyForSpecs(); }); let parentContent; const childContents = {}; beforeEach(function() { parentContent = tileset.root.content; const children = tileset.root.children; children.forEach(function(child) { const uri = child._header.content.uri; childContents[uri] = child.content; }); }); it("getPropertyInherited returns undefined for unknown property", function() { const feature = new import__436.Cesium3DTileFeature(childContents["ll.b3dm"], 0); expect(feature.getPropertyInherited("unknown")).not.toBeDefined(); }); it("getPropertyInherited returns content property by semantic", function() { const feature = new import__436.Cesium3DTileFeature(childContents["ll.b3dm"], 0); expect(feature.getPropertyInherited("HIGHLIGHT_COLOR")).toEqual( new import__436.Cartesian4(255, 0, 0, 1) ); }); it("getPropertyInherited returns content property", function() { const feature = new import__436.Cesium3DTileFeature(childContents["ll.b3dm"], 0); expect(feature.getPropertyInherited("HIGHLIGHT_COLOR")).toEqual( new import__436.Cartesian4(255, 0, 0, 1) ); expect(feature.getPropertyInherited("triangleCount")).toBe(15e3); }); it("getPropertyInherited returns tile property by semantic", function() { const feature = new import__436.Cesium3DTileFeature(childContents["ll.b3dm"], 0); expect(feature.getPropertyInherited("COLOR")).toEqual( new import__436.Cartesian4(255, 255, 0, 1) ); }); it("getPropertyInherited returns tile property", function() { const feature = new import__436.Cesium3DTileFeature(childContents["ll.b3dm"], 0); expect(feature.getPropertyInherited("color")).toEqual( new import__436.Cartesian4(255, 255, 0, 1) ); expect(feature.getPropertyInherited("population")).toBe(50); }); it("getPropertyInherited returns default value", function() { const feature = new import__436.Cesium3DTileFeature(childContents["ll.b3dm"], 0); expect(feature.getPropertyInherited("defaultColor")).toEqual( new import__436.Cartesian4(255, 255, 255, 255) ); }); it("getPropertyInherited returns group property by semantic", function() { let feature = new import__436.Cesium3DTileFeature(childContents["lr.b3dm"], 0); expect(feature.getPropertyInherited("GROUP_NAME")).toBe("commercial"); feature = new import__436.Cesium3DTileFeature(childContents["ll.b3dm"], 0); expect(feature.getPropertyInherited("GROUP_NAME")).toBe("residential"); }); it("getPropertyInherited returns group property", function() { const feature = new import__436.Cesium3DTileFeature(childContents["lr.b3dm"], 0); expect(feature.getPropertyInherited("majorIndustries")).toEqual([ "Finance", "Manufacturing" ]); expect(feature.getPropertyInherited("businessCount")).toBe(143); }); it("getPropertyInherited returns tileset property by semantic", function() { const feature = new import__436.Cesium3DTileFeature(parentContent, 0); expect(feature.getPropertyInherited("DATE_ISO_8601")).toBe( "2021-04-07" ); expect(feature.getPropertyInherited("AUTHOR")).toBe("Cesium"); }); it("getPropertyInherited returns tileset property", function() { const feature = new import__436.Cesium3DTileFeature(parentContent, 0); expect(feature.getPropertyInherited("centerCartographic")).toEqual( new import__436.Cartesian3( -1.3196816996258511, 0.6988767486400521, 45.78600543644279 ) ); expect(feature.getPropertyInherited("date")).toBe("2021-04-07"); expect(feature.getPropertyInherited("author")).toBe("Cesium"); expect(feature.getPropertyInherited("tileCount")).toBe(5); }); it("resolves conflicting names from most specific to most general", function() { const feature = new import__436.Cesium3DTileFeature(childContents["ll.b3dm"], 0); expect(feature.getPropertyInherited("highlightColor")).toEqual( new import__436.Cartesian4(255, 0, 0, 1) ); expect(feature.getPropertyInherited("author")).toEqual("First Author"); expect(feature.getPropertyInherited("color")).toEqual( new import__436.Cartesian4(255, 255, 0, 1) ); expect(feature.getPropertyInherited("tileCount")).toEqual(2); }); }); describe("implicit tiling metadata", function() { describe("subtree metadata", function() { const tilesetWithSubtreeMetadataUrl = "Data/Cesium3DTiles/Metadata/ImplicitSubtreeMetadata/tileset_1.1.json"; let scene2; let tilesetWithSubtree; beforeAll(function() { scene2 = createScene_default(); const center = import__436.Cartesian3.fromRadians( centerLongitude, centerLatitude ); scene2.camera.lookAt(center, new import__436.HeadingPitchRange(0, -1.57, 15)); return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithSubtreeMetadataUrl ).then(function(result) { tilesetWithSubtree = result; }); }); let subtreeRootContent; const subtreeChildContents = {}; beforeEach(function() { const rootChildren = tilesetWithSubtree.root.children; const rootChild = rootChildren[0]; subtreeRootContent = rootChild.content; const children = rootChild.children; children.forEach(function(child) { const uri = child._header.contents[0].uri; subtreeChildContents[uri] = child.content; }); }); it("getPropertyInherited returns subtree property by semantic at root level", function() { const feature = new import__436.Cesium3DTileFeature(subtreeRootContent, 0); expect(feature.getPropertyInherited("AUTHOR")).toEqual("Cesium"); }); it("getPropertyInherited returns subtree property at root level", function() { const feature = new import__436.Cesium3DTileFeature(subtreeRootContent, 0); expect(feature.getPropertyInherited("author")).toEqual("Cesium"); expect(feature.getPropertyInherited("credits")).toEqual([ "Data Company 1", "Data Company 2", "Data Company 3" ]); }); it("getPropertyInherited returns subtree property by semantic at child level", function() { const feature = new import__436.Cesium3DTileFeature( subtreeChildContents["content/1/0/0.b3dm"], 0 ); expect(feature.getPropertyInherited("AUTHOR")).toEqual("Cesium"); }); it("getPropertyInherited returns subtree property at root level", function() { const feature = new import__436.Cesium3DTileFeature( subtreeChildContents["content/1/0/0.b3dm"], 0 ); expect(feature.getPropertyInherited("author")).toEqual("Cesium"); expect(feature.getPropertyInherited("credits")).toEqual([ "Data Company 1", "Data Company 2", "Data Company 3" ]); }); it("getPropertyInherited returns tile property that is shared by subtree at root level", function() { const feature = new import__436.Cesium3DTileFeature(subtreeRootContent, 0); expect(feature.getPropertyInherited("Height")).toBeInstanceOf(Number); expect(feature.getPropertyInherited("Height")).not.toEqual(1e3); }); it("getPropertyInherited returns tile property that is shared by subtree at child level", function() { const childFeature = new import__436.Cesium3DTileFeature( subtreeChildContents["content/1/0/0.b3dm"], 0 ); const rootFeature = new import__436.Cesium3DTileFeature(subtreeRootContent, 0); const childHeight = childFeature.getPropertyInherited("Height"); const rootHeight = rootFeature.getPropertyInherited("Height"); expect(rootHeight).toBeInstanceOf(Number); expect(childHeight).toBeInstanceOf(Number); expect(childHeight).not.toEqual(1e3); expect(childHeight).not.toEqual(rootHeight); }); }); describe("implicit content metadata", function() { const tilesetWithImplicitContentMetadataUrl = "Data/Cesium3DTiles/Metadata/ImplicitContentMetadata/tileset_1.1.json"; let scene2; let tilesetWithImplicitContentMetadata; beforeAll(function() { scene2 = createScene_default(); const center = import__436.Cartesian3.fromRadians( centerLongitude, centerLatitude ); scene2.camera.lookAt(center, new import__436.HeadingPitchRange(0, -1.57, 15)); return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithImplicitContentMetadataUrl ).then(function(result) { tilesetWithImplicitContentMetadata = result; }); }); let subtreeRootContent; const subtreeChildContents = {}; beforeEach(function() { const rootChildren = tilesetWithImplicitContentMetadata.root.children; const rootChild = rootChildren[0]; subtreeRootContent = rootChild.content; const children = rootChild.children; children.forEach(function(child) { const uri = child._header.contents[0].uri; subtreeChildContents[uri] = child.content; }); }); it("getPropertyInherited returns content property by semantic", function() { const rootFeature = new import__436.Cesium3DTileFeature(subtreeRootContent, 0); const childFeature = new import__436.Cesium3DTileFeature( subtreeChildContents["content/1/0/0.b3dm"], 0 ); expect(rootFeature.getPropertyInherited("_BUILDING_HEIGHT")).toEqual( 10 ); expect(childFeature.getPropertyInherited("_BUILDING_HEIGHT")).toEqual( 20 ); }); it("getPropertyInherited returns content property", function() { const rootFeature = new import__436.Cesium3DTileFeature(subtreeRootContent, 0); expect(rootFeature.getPropertyInherited("height")).toEqual(10); expect(rootFeature.getPropertyInherited("color")).toEqual( new import__436.Cartesian3(255, 255, 255) ); }); it("getPropertyInherited returns content property by semantic for different contents", function() { const childFeature = new import__436.Cesium3DTileFeature( subtreeChildContents["content/1/0/0.b3dm"], 0 ); const secondChildFeature = new import__436.Cesium3DTileFeature( subtreeChildContents["content/1/1/1.b3dm"], 0 ); expect(childFeature.getPropertyInherited("_BUILDING_HEIGHT")).toEqual( 20 ); expect( secondChildFeature.getPropertyInherited("_BUILDING_HEIGHT") ).toEqual(40); }); it("getPropertyInherited returns content property for different contents", function() { const childFeature = new import__436.Cesium3DTileFeature( subtreeChildContents["content/1/0/0.b3dm"], 0 ); const secondChildFeature = new import__436.Cesium3DTileFeature( subtreeChildContents["content/1/1/1.b3dm"], 0 ); expect(childFeature.getPropertyInherited("height")).toEqual(20); expect(secondChildFeature.getPropertyInherited("height")).toEqual(40); expect(childFeature.getPropertyInherited("color")).toEqual( new import__436.Cartesian3(255, 0, 0) ); expect(secondChildFeature.getPropertyInherited("color")).toEqual( new import__436.Cartesian3(0, 0, 255) ); }); it("getPropertyInherited returns tile property with same property name by semantic", function() { const feature = new import__436.Cesium3DTileFeature(subtreeRootContent, 0); expect(feature.getPropertyInherited("Height")).toBeInstanceOf(Number); expect(feature.getPropertyInherited("Height")).not.toEqual(10); }); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Cesium3DTileFeatureTableSpec.js var import__437 = __toESM(require_Cesium(), 1); describe("Scene/Cesium3DTileFeatureTable", function() { it("loads from JSON", function() { const featureTable = new import__437.Cesium3DTileFeatureTable({ TEST: [0, 1, 2, 3, 4, 5] }); featureTable.featuresLength = 3; expect(featureTable.hasProperty("TEST")).toBe(true); const all = featureTable.getGlobalProperty( "TEST", import__437.ComponentDatatype.UNSIGNED_BYTE ); expect(all).toEqual([0, 1, 2, 3, 4, 5]); const feature = featureTable.getProperty( "TEST", import__437.ComponentDatatype.UNSIGNED_BYTE, 2, 1, new Array(2) ); expect(feature).toEqual([2, 3]); const properties = featureTable.getPropertyArray( "TEST", import__437.ComponentDatatype.UNSIGNED_BYTE, 2 ); expect(properties).toEqual([0, 1, 2, 3, 4, 5]); }); it("loads from binary", function() { const featureTable = new import__437.Cesium3DTileFeatureTable( { TEST: { byteOffset: 4 } }, new Uint8Array([0, 0, 0, 0, 0, 1, 2, 3, 4, 5]) ); featureTable.featuresLength = 3; expect(featureTable.hasProperty("TEST")).toBe(true); const all = featureTable.getGlobalProperty( "TEST", import__437.ComponentDatatype.UNSIGNED_BYTE, 6 ); expect(all).toEqual([0, 1, 2, 3, 4, 5]); const feature = featureTable.getProperty( "TEST", import__437.ComponentDatatype.UNSIGNED_BYTE, 2, 1, new Array(2) ); expect(feature).toEqual([2, 3]); const properties = featureTable.getPropertyArray( "TEST", import__437.ComponentDatatype.UNSIGNED_BYTE, 2 ); expect(properties).toEqual([0, 1, 2, 3, 4, 5]); }); }); // packages/engine/Specs/Scene/Cesium3DTilePassStateSpec.js var import__438 = __toESM(require_Cesium(), 1); describe("Scene/Cesium3DTilePassState", function() { it("sets default values", function() { const passState = new import__438.Cesium3DTilePassState({ pass: import__438.Cesium3DTilePass.RENDER }); expect(passState.pass).toBe(import__438.Cesium3DTilePass.RENDER); expect(passState.commandList).toBeUndefined(); expect(passState.camera).toBeUndefined(); expect(passState.cullingVolume).toBeUndefined(); expect(passState.ready).toBe(false); }); it("constructed with options", function() { const mockCommandList = []; const mockCamera = {}; const mockCullingVolume = {}; const passState = new import__438.Cesium3DTilePassState({ pass: import__438.Cesium3DTilePass.RENDER, commandList: mockCommandList, camera: mockCamera, cullingVolume: mockCullingVolume }); expect(passState.pass).toBe(import__438.Cesium3DTilePass.RENDER); expect(passState.commandList).toBe(mockCommandList); expect(passState.camera).toBe(mockCamera); expect(passState.cullingVolume).toBe(mockCullingVolume); }); it("throws if options is undefined", function() { expect(function() { return new import__438.Cesium3DTilePassState(); }).toThrowDeveloperError(); }); it("throws if options.pass is undefined", function() { expect(function() { return new import__438.Cesium3DTilePassState({}); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/Cesium3DTileSpec.js var import__439 = __toESM(require_Cesium(), 1); describe( "Scene/Cesium3DTile", function() { const tileWithBoundingSphere = { geometricError: 1, refine: "REPLACE", children: [], boundingVolume: { sphere: [0, 0, 0, 5] } }; const tileWithContentBoundingSphere = { geometricError: 1, refine: "REPLACE", content: { url: "0/0.b3dm", boundingVolume: { sphere: [0, 0, 1, 5] } }, children: [], boundingVolume: { sphere: [0, 0, 1, 5] } }; const tileWithBoundingRegion = { geometricError: 1, refine: "REPLACE", children: [], boundingVolume: { region: [-1.2, -1.2, 0, 0, -34, -30] } }; const tileWithContentBoundingRegion = { geometricError: 1, refine: "REPLACE", children: [], content: { url: "0/0.b3dm", boundingVolume: { region: [-1.2, -1.2, 0, 0, -30, -34] } }, boundingVolume: { region: [-1.2, -1.2, 0, 0, -30, -34] } }; const tileWithEmptyContentUri = { geometricError: 1, refine: "REPLACE", children: [], content: { uri: "" }, boundingVolume: { region: [-1.2, -1.2, 0, 0, -30, -34] } }; const tileWithBoundingBox = { geometricError: 1, refine: "REPLACE", children: [], boundingVolume: { box: [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1] } }; const tileWithContentBoundingBox = { geometricError: 1, refine: "REPLACE", children: [], content: { url: "0/0.b3dm", boundingVolume: { box: [0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 2] } }, boundingVolume: { box: [0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 2] } }; const tileWithViewerRequestVolume = { geometricError: 1, refine: "REPLACE", children: [], boundingVolume: { box: [0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 2] }, viewerRequestVolume: { box: [0, 0, 1, 2, 0, 0, 0, 2, 0, 0, 0, 2] } }; const mockTileset = { debugShowBoundingVolume: true, debugShowViewerRequestVolume: true, modelMatrix: import__439.Matrix4.IDENTITY, _geometricError: 2, _scaledGeometricError: 2, _heatmap: new import__439.Cesium3DTilesetHeatmap() }; const centerLongitude = -1.31968; const centerLatitude = 0.698874; function getTileTransform(longitude, latitude, height = 0) { const transformCenter = import__439.Cartesian3.fromRadians( longitude, latitude, height ); const hpr = new import__439.HeadingPitchRoll(); const transformMatrix = import__439.Transforms.headingPitchRollToFixedFrame( transformCenter, hpr ); return import__439.Matrix4.pack(transformMatrix, new Array(16)); } it("destroys", function() { const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithBoundingSphere, void 0 ); expect(tile.isDestroyed()).toEqual(false); tile.destroy(); expect(tile.isDestroyed()).toEqual(true); }); it("throws if boundingVolume is undefined", function() { const tileWithoutBoundingVolume = (0, import__439.clone)(tileWithBoundingSphere, true); delete tileWithoutBoundingVolume.boundingVolume; expect(function() { return new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithoutBoundingVolume, void 0 ); }).toThrowError(import__439.RuntimeError); }); it("throws if boundingVolume does not contain a sphere, region, or box", function() { const tileWithoutBoundingVolume = (0, import__439.clone)(tileWithBoundingSphere, true); delete tileWithoutBoundingVolume.boundingVolume.sphere; expect(function() { return new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithoutBoundingVolume, void 0 ); }).toThrowError(import__439.RuntimeError); }); it("logs deprecation warning if refine is lowercase", function() { spyOn(import__439.Cesium3DTile, "_deprecationWarning"); const header = (0, import__439.clone)(tileWithBoundingSphere, true); header.refine = "replace"; const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", header, void 0 ); expect(tile.refine).toBe(import__439.Cesium3DTileRefine.REPLACE); expect(import__439.Cesium3DTile._deprecationWarning).toHaveBeenCalled(); }); it("logs deprecation warning and loads empty tile if content.uri is an empty string", function() { spyOn(import__439.Cesium3DTile, "_deprecationWarning"); const header = (0, import__439.clone)(tileWithEmptyContentUri, true); const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", header, void 0 ); expect(tile.content).toBeDefined(); expect(tile.content).toBeInstanceOf(import__439.Empty3DTileContent); expect(import__439.Cesium3DTile._deprecationWarning).toHaveBeenCalled(); }); it("logs deprecation warning if geometric error is undefined", function() { spyOn(import__439.Cesium3DTile, "_deprecationWarning"); const geometricErrorMissing = (0, import__439.clone)(tileWithBoundingSphere, true); delete geometricErrorMissing.geometricError; const parent = new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithBoundingSphere, void 0 ); const child = new import__439.Cesium3DTile( mockTileset, "/some_url", geometricErrorMissing, parent ); expect(child.geometricError).toBe(parent.geometricError); expect(child.geometricError).toBe(1); const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", geometricErrorMissing, void 0 ); expect(tile.geometricError).toBe(mockTileset._geometricError); expect(tile.geometricError).toBe(2); expect(import__439.Cesium3DTile._deprecationWarning.calls.count()).toBe(2); }); describe("bounding volumes", function() { it("returns the tile bounding volume if the content bounding volume is undefined", function() { const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithBoundingSphere, void 0 ); expect(tile.boundingVolume).toBeDefined(); expect(tile.contentBoundingVolume).toBe(tile.boundingVolume); }); it("can have a bounding sphere", function() { const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithBoundingSphere, void 0 ); const radius = tileWithBoundingSphere.boundingVolume.sphere[3]; expect(tile.boundingVolume).toBeDefined(); expect(tile.boundingVolume.boundingVolume.radius).toEqual(radius); expect(tile.boundingVolume.boundingVolume.center).toEqual( import__439.Cartesian3.ZERO ); }); it("can have a content bounding sphere", function() { const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithContentBoundingSphere, void 0 ); const radius = tileWithContentBoundingSphere.content.boundingVolume.sphere[3]; expect(tile.contentBoundingVolume).toBeDefined(); expect(tile.contentBoundingVolume.boundingVolume.radius).toEqual( radius ); expect(tile.contentBoundingVolume.boundingVolume.center).toEqual( new import__439.Cartesian3(0, 0, 1) ); }); it("can have a bounding region", function() { const box = tileWithBoundingRegion.boundingVolume.region; const rectangle = new import__439.Rectangle(box[0], box[1], box[2], box[3]); const minimumHeight = tileWithBoundingRegion.boundingVolume.region[4]; const maximumHeight = tileWithBoundingRegion.boundingVolume.region[5]; const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithBoundingRegion, void 0 ); const tbr = new import__439.TileBoundingRegion({ rectangle, minimumHeight, maximumHeight }); expect(tile.boundingVolume).toBeDefined(); expect(tile.boundingVolume).toEqual(tbr); }); it("can have a content bounding region", function() { const region = tileWithContentBoundingRegion.content.boundingVolume.region; const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithContentBoundingRegion, void 0 ); expect(tile.contentBoundingVolume).toBeDefined(); const tbb = new import__439.TileBoundingRegion({ rectangle: new import__439.Rectangle(region[0], region[1], region[2], region[3]), minimumHeight: region[4], maximumHeight: region[5] }); expect(tile.contentBoundingVolume).toEqual(tbb); }); it("can have an oriented bounding box", function() { const box = tileWithBoundingBox.boundingVolume.box; const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithBoundingBox, void 0 ); expect(tile.boundingVolume).toBeDefined(); const center = new import__439.Cartesian3(box[0], box[1], box[2]); const halfAxes = import__439.Matrix3.fromArray(box, 3); const obb = new import__439.TileOrientedBoundingBox(center, halfAxes); expect(tile.boundingVolume).toEqual(obb); }); it("does not crash for bounding box with 0 volume", function() { const tileWithBoundingBox0Volume = JSON.parse( JSON.stringify(tileWithBoundingBox) ); const boxes = []; for (let x = 0; x < 2; ++x) { for (let y = 0; y < 2; ++y) { for (let z = 0; z < 2; ++z) { boxes.push([ 0, 0, 0, x, 0, 0, 0, y, 0, 0, 0, z ]); } } } for (let i = 0; i < boxes.length; ++i) { const box = boxes[i]; tileWithBoundingBox0Volume.boundingVolume.box = box; const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithBoundingBox0Volume, void 0 ); expect(tile.boundingVolume).toBeDefined(); const center = new import__439.Cartesian3(box[0], box[1], box[2]); const halfAxes = import__439.Matrix3.fromArray(box, 3); const obb = new import__439.TileOrientedBoundingBox(center, halfAxes); expect(tile.boundingVolume).toEqual(obb); } }); it("can have a content oriented bounding box", function() { const box = tileWithContentBoundingBox.boundingVolume.box; const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithContentBoundingBox, void 0 ); expect(tile.contentBoundingVolume).toBeDefined(); const center = new import__439.Cartesian3(box[0], box[1], box[2]); const halfAxes = import__439.Matrix3.fromArray(box, 3); const obb = new import__439.TileOrientedBoundingBox(center, halfAxes); expect(tile.contentBoundingVolume).toEqual(obb); }); it("tile transform affects bounding sphere", function() { const header = (0, import__439.clone)(tileWithContentBoundingSphere, true); header.transform = getTileTransform(centerLongitude, centerLatitude); const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", header, void 0 ); const boundingSphere = tile.boundingVolume.boundingVolume; const contentBoundingSphere = tile.contentBoundingVolume.boundingVolume; const boundingVolumeCenter = import__439.Cartesian3.fromRadians( centerLongitude, centerLatitude, 1 ); expect(boundingSphere.center).toEqualEpsilon( boundingVolumeCenter, import__439.Math.EPSILON4 ); expect(boundingSphere.radius).toEqual(5); expect(contentBoundingSphere.center).toEqualEpsilon( boundingVolumeCenter, import__439.Math.EPSILON4 ); expect(contentBoundingSphere.radius).toEqual(5); }); it("tile transform affects oriented bounding box", function() { const header = (0, import__439.clone)(tileWithContentBoundingBox, true); header.transform = getTileTransform(centerLongitude, centerLatitude); const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", header, void 0 ); const boundingBox = tile.boundingVolume.boundingVolume; const contentBoundingBox = tile.contentBoundingVolume.boundingVolume; const boundingVolumeCenter = import__439.Cartesian3.fromRadians( centerLongitude, centerLatitude, 1 ); expect(boundingBox.center).toEqualEpsilon( boundingVolumeCenter, import__439.Math.EPSILON7 ); expect(contentBoundingBox.center).toEqualEpsilon( boundingVolumeCenter, import__439.Math.EPSILON7 ); }); it("tile transform does not affect bounding region", function() { const header = (0, import__439.clone)(tileWithContentBoundingRegion, true); header.transform = getTileTransform(centerLongitude, centerLatitude); const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", header, void 0 ); const boundingRegion = tile.boundingVolume; const contentBoundingRegion = tile.contentBoundingVolume; const region = header.boundingVolume.region; const rectangle = import__439.Rectangle.unpack(region); expect(boundingRegion.rectangle).toEqual(rectangle); expect(contentBoundingRegion.rectangle).toEqual(rectangle); }); it("tile transform affects viewer request volume", function() { const header = (0, import__439.clone)(tileWithViewerRequestVolume, true); header.transform = getTileTransform(centerLongitude, centerLatitude); const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", header, void 0 ); const requestVolume = tile._viewerRequestVolume.boundingVolume; const requestVolumeCenter = import__439.Cartesian3.fromRadians( centerLongitude, centerLatitude, 1 ); expect(requestVolume.center).toEqualEpsilon( requestVolumeCenter, import__439.Math.EPSILON7 ); }); it("tile transform changes", function() { const mockTileset2 = { modelMatrix: import__439.Matrix4.IDENTITY }; const header = (0, import__439.clone)(tileWithBoundingSphere, true); header.transform = getTileTransform(centerLongitude, centerLatitude); const tile = new import__439.Cesium3DTile( mockTileset2, "/some_url", header, void 0 ); const boundingSphere = tile.boundingVolume.boundingVolume; const boundingVolumeCenter = import__439.Cartesian3.fromRadians( centerLongitude, centerLatitude ); expect(boundingSphere.center).toEqualEpsilon( boundingVolumeCenter, import__439.Math.EPSILON7 ); const newLongitude = -1.012; const newLatitude = 0.698874; tile.transform = getTileTransform(newLongitude, newLatitude); tile.updateTransform(); const newCenter = import__439.Cartesian3.fromRadians(newLongitude, newLatitude); expect(boundingSphere.center).toEqualEpsilon( newCenter, import__439.Math.EPSILON7 ); }); it("TILE_BOUNDING_XXX metadata semantics override bounding volume", function() { const tileset = (0, import__439.clone)(mockTileset, true); tileset.schema = import__439.MetadataSchema.fromJson({ id: "test-schema", classes: { tile: { properties: { tileBoundingBox: { type: "SCALAR", componentType: "FLOAT64", array: true, count: 12, semantic: "TILE_BOUNDING_BOX" } } } } }); const header = (0, import__439.clone)(tileWithBoundingRegion, true); header.metadata = { class: "tile", properties: { tileBoundingBox: [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1] } }; const tile = new import__439.Cesium3DTile(tileset, "/some_url", header, void 0); const boundingBox = tile.boundingVolume.boundingVolume; const expectedCenter = new import__439.Cartesian3(); const expectedHalfAxes = import__439.Matrix3.IDENTITY; expect(boundingBox.center).toEqual(expectedCenter); expect(boundingBox.halfAxes).toEqual(expectedHalfAxes); }); }); describe("vertical exaggeration", function() { let scene2; beforeEach(function() { scene2 = createScene_default(); scene2.frameState.passes.render = true; }); afterEach(function() { scene2.destroyForSpecs(); }); it("applies vertical exaggeration to bounding box", function() { const header = (0, import__439.clone)(tileWithContentBoundingBox, true); header.transform = getTileTransform(0, 0, 100); const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", header, void 0 ); const boundingBox = tile.boundingVolume.boundingVolume; const boundingVolumeCenter = import__439.Cartesian3.fromRadians(0, 0, 101); expect(boundingBox.center).toEqualEpsilon( boundingVolumeCenter, import__439.Math.EPSILON7 ); const boundingVolumeHalfAxes = import__439.Matrix3.fromArray([ 0, 1, 0, 0, 0, 1, 2, 0, 0 ]); expect(boundingBox.halfAxes).toEqualEpsilon( boundingVolumeHalfAxes, import__439.Math.EPSILON7 ); scene2.verticalExaggeration = 2; scene2.updateFrameState(); tile.updateTransform(void 0, scene2.frameState); const exaggeratedCenter = import__439.Cartesian3.fromRadians(0, 0, 202); expect(boundingBox.center).toEqualEpsilon( exaggeratedCenter, import__439.Math.EPSILON7 ); const exaggeratedHalfAxes = import__439.Matrix3.fromArray([ 4, 0, 0, 0, 1, 0, 0, 0, 1 ]); expect(boundingBox.halfAxes).toEqualEpsilon( exaggeratedHalfAxes, import__439.Math.EPSILON4 ); }); it("applies vertical exaggeration to bounding region", function() { const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithBoundingRegion, void 0 ); const tileBoundingRegion = tile.boundingVolume; expect(tileBoundingRegion.minimumHeight).toEqualEpsilon( -34, import__439.Math.EPSILON7 ); expect(tileBoundingRegion.maximumHeight).toEqualEpsilon( -30, import__439.Math.EPSILON7 ); const rectangle = import__439.Rectangle.pack( tileBoundingRegion.rectangle, new Array(4) ); expect(rectangle).toEqualEpsilon( [-1.2, -1.2, 0, 0], import__439.Math.EPSILON7 ); scene2.verticalExaggeration = 2; scene2.verticalExaggerationRelativeHeight = -34; scene2.updateFrameState(); tile.updateTransform(void 0, scene2.frameState); expect(tileBoundingRegion.minimumHeight).toEqualEpsilon( -34, import__439.Math.EPSILON7 ); expect(tileBoundingRegion.maximumHeight).toEqualEpsilon( -26, import__439.Math.EPSILON7 ); const exaggeratedRectangle = import__439.Rectangle.pack( tileBoundingRegion.rectangle, new Array(4) ); expect(exaggeratedRectangle).toEqualEpsilon( [-1.2, -1.2, 0, 0], import__439.Math.EPSILON7 ); }); it("applies vertical exaggeration to bounding sphere", function() { const header = (0, import__439.clone)(tileWithBoundingSphere, true); header.transform = getTileTransform( centerLongitude, centerLatitude, 100 ); const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", header, void 0 ); const boundingSphere = tile.boundingVolume.boundingVolume; const boundingVolumeCenter = import__439.Cartesian3.fromRadians( centerLongitude, centerLatitude, 100 ); expect(boundingSphere.center).toEqualEpsilon( boundingVolumeCenter, import__439.Math.EPSILON7 ); expect(boundingSphere.radius).toEqualEpsilon(5, import__439.Math.EPSILON7); scene2.verticalExaggeration = 2; scene2.updateFrameState(); tile.updateTransform(void 0, scene2.frameState); const exaggeratedCenter = import__439.Cartesian3.fromRadians( centerLongitude, centerLatitude, 200 ); expect(boundingSphere.center).toEqualEpsilon( exaggeratedCenter, import__439.Math.EPSILON7 ); expect(boundingSphere.radius).toEqualEpsilon(10, import__439.Math.EPSILON7); }); }); describe("debug bounding volumes", function() { let scene2; beforeEach(function() { scene2 = createScene_default(); scene2.frameState.passes.render = true; }); afterEach(function() { scene2.destroyForSpecs(); }); it("can be a bounding region", function() { const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithBoundingRegion, void 0 ); const passOptions = import__439.Cesium3DTilePass.getPassOptions( import__439.Cesium3DTilePass.RENDER ); tile.update(mockTileset, scene2.frameState, passOptions); expect(tile._debugBoundingVolume).toBeDefined(); }); it("can be an oriented bounding box", function() { const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithBoundingBox, void 0 ); const passOptions = import__439.Cesium3DTilePass.getPassOptions( import__439.Cesium3DTilePass.RENDER ); tile.update(mockTileset, scene2.frameState, passOptions); expect(tile._debugBoundingVolume).toBeDefined(); }); it("can be a bounding sphere", function() { const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithBoundingSphere, void 0 ); const passOptions = import__439.Cesium3DTilePass.getPassOptions( import__439.Cesium3DTilePass.RENDER ); tile.update(mockTileset, scene2.frameState, passOptions); expect(tile._debugBoundingVolume).toBeDefined(); }); it("creates debug bounding volume for viewer request volume", function() { const tile = new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithViewerRequestVolume, void 0 ); const passOptions = import__439.Cesium3DTilePass.getPassOptions( import__439.Cesium3DTilePass.RENDER ); tile.update(mockTileset, scene2.frameState, passOptions); expect(tile._debugViewerRequestVolume).toBeDefined(); }); }); it("updates priority", function() { const tile1 = new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithBoundingSphere, void 0 ); tile1._priorityHolder = tile1; tile1._foveatedFactor = 0; tile1._distanceToCamera = 1; tile1._depth = 0; tile1._priorityProgressiveResolution = true; const tile2 = new import__439.Cesium3DTile( mockTileset, "/some_url", tileWithBoundingSphere, void 0 ); tile2._priorityHolder = tile1; tile2._foveatedFactor = 1; tile2._distanceToCamera = 0; tile2._depth = 1; tile2._priorityProgressiveResolution = true; mockTileset._minimumPriority = { depth: 0, distance: 0, foveatedFactor: 0 }; mockTileset._maximumPriority = { depth: 1, distance: 1, foveatedFactor: 1 }; tile1.updatePriority(); tile2.updatePriority(); const nonPreloadFlightPenalty = 1e10; const tile1ExpectedPriority = nonPreloadFlightPenalty + 0; const tile2ExpectedPriority = nonPreloadFlightPenalty + 1; expect( import__439.Math.equalsEpsilon( tile1._priority, tile1ExpectedPriority, import__439.Math.EPSILON2 ) ).toBe(true); expect( import__439.Math.equalsEpsilon( tile2._priority, tile2ExpectedPriority, import__439.Math.EPSILON2 ) ).toBe(true); tile2._priorityProgressiveResolution = false; tile2.updatePriority(); const nonProgressiveResoutionPenalty = 1e8; expect(tile2._priority).toBeGreaterThan(nonProgressiveResoutionPenalty); tile2._priorityProgressiveResolution = true; tile2.priorityDeferred = true; tile2.updatePriority(); const foveatedDeferralPenalty = 1e7; expect(tile2._priority).toBeGreaterThanOrEqual(foveatedDeferralPenalty); tile2._priorityDeferred = false; }); it("tile transform scales geometric error", function() { const header = (0, import__439.clone)(tileWithContentBoundingSphere, true); header.transform = import__439.Matrix4.pack( import__439.Matrix4.fromUniformScale(2), new Array(16) ); const mockTilesetScaled = (0, import__439.clone)(mockTileset, true); const tile = new import__439.Cesium3DTile( mockTilesetScaled, "/some_url", header, void 0 ); expect(tile._geometricError).toBe(1); expect(tile.geometricError).toBe(2); expect(mockTilesetScaled._geometricError).toBe(2); expect(mockTilesetScaled._scaledGeometricError).toBe(4); }); }, "WebGL" ); // packages/engine/Specs/Scene/Cesium3DTileStyleSpec.js var import__440 = __toESM(require_Cesium(), 1); describe("Scene/Cesium3DTileStyle", function() { function MockFeature() { this._properties = {}; } MockFeature.prototype.addProperty = function(name, value) { this._properties[name] = value; }; MockFeature.prototype.getPropertyInherited = function(name) { return this._properties[name]; }; const feature1 = new MockFeature(); feature1.addProperty("ZipCode", "19341"); feature1.addProperty("County", "Chester"); feature1.addProperty("YearBuilt", 1979); feature1.addProperty("Temperature", 78); feature1.addProperty("red", 38); feature1.addProperty("green", 255); feature1.addProperty("blue", 82); feature1.addProperty("volume", 128); feature1.addProperty("Height", 100); feature1.addProperty("Width", 20); feature1.addProperty("Depth", 20); feature1.addProperty("id", 11); feature1.addProperty("name", "Hello"); const feature2 = new MockFeature(); feature2.addProperty("ZipCode", "19342"); feature2.addProperty("County", "Delaware"); feature2.addProperty("YearBuilt", 1979); feature2.addProperty("Temperature", 92); feature2.addProperty("red", 255); feature2.addProperty("green", 30); feature2.addProperty("blue", 30); feature2.addProperty("volume", 50); feature2.addProperty("Height", 38); feature2.addProperty("id", 12); const styleUrl = "./Data/Cesium3DTiles/Style/style.json"; it("fromUrl rejects with undefined url", function() { return import__440.Cesium3DTileStyle.fromUrl("invalid.json").then(function(style) { fail("should not resolve"); }).catch(function(error) { expect(error.statusCode).toEqual(404); }); }); it("loads style from uri", function() { return import__440.Cesium3DTileStyle.fromUrl(styleUrl).then(function(style) { expect(style.style).toEqual({ color: "color('red')", show: "${id} < 100.0", pointSize: "${id} / 100.0", pointOutlineColor: "color('blue')", pointOutlineWidth: "5.0", labelColor: "color('yellow')", labelOutlineColor: "color('orange')", labelOutlineWidth: "6.0", font: "'24px Helvetica'", labelStyle: "1", labelText: "'label text'", backgroundColor: "color('coral')", backgroundPadding: "vec2(1.0, 2.0)", backgroundEnabled: "true", scaleByDistance: "vec4(1.0, 2.0, 3.0, 4.0)", translucencyByDistance: "vec4(5.0, 6.0, 7.0, 8.0)", distanceDisplayCondition: "vec2(3.0, 4.0)", heightOffset: "10.0", anchorLineEnabled: "true", anchorLineColor: "color('fuchsia')", image: "'url/to/invalid/image'", disableDepthTestDistance: "1000.0", horizontalOrigin: "0", verticalOrigin: "0", labelHorizontalOrigin: "0", labelVerticalOrigin: "0" }); expect(style.color).toEqual(new import__440.Expression("color('red')")); expect(style.show).toEqual(new import__440.Expression("${id} < 100.0")); expect(style.pointSize).toEqual(new import__440.Expression("${id} / 100.0")); expect(style.pointOutlineColor).toEqual(new import__440.Expression("color('blue')")); expect(style.pointOutlineWidth).toEqual(new import__440.Expression("5.0")); expect(style.labelColor).toEqual(new import__440.Expression("color('yellow')")); expect(style.labelOutlineColor).toEqual( new import__440.Expression("color('orange')") ); expect(style.labelOutlineWidth).toEqual(new import__440.Expression("6.0")); expect(style.font).toEqual(new import__440.Expression("'24px Helvetica'")); expect(style.labelStyle).toEqual(new import__440.Expression("1")); expect(style.labelText).toEqual(new import__440.Expression("'label text'")); expect(style.backgroundColor).toEqual(new import__440.Expression("color('coral')")); expect(style.backgroundPadding).toEqual(new import__440.Expression("vec2(1.0, 2.0)")); expect(style.backgroundEnabled).toEqual(new import__440.Expression("true")); expect(style.scaleByDistance).toEqual( new import__440.Expression("vec4(1.0, 2.0, 3.0, 4.0)") ); expect(style.translucencyByDistance).toEqual( new import__440.Expression("vec4(5.0, 6.0, 7.0, 8.0)") ); expect(style.distanceDisplayCondition).toEqual( new import__440.Expression("vec2(3.0, 4.0)") ); expect(style.heightOffset).toEqual(new import__440.Expression("10.0")); expect(style.anchorLineEnabled).toEqual(new import__440.Expression("true")); expect(style.anchorLineColor).toEqual(new import__440.Expression("color('fuchsia')")); expect(style.image).toEqual(new import__440.Expression("'url/to/invalid/image'")); expect(style.disableDepthTestDistance).toEqual(new import__440.Expression("1000.0")); expect(style.horizontalOrigin).toEqual(new import__440.Expression("0")); expect(style.verticalOrigin).toEqual(new import__440.Expression("0")); expect(style.labelHorizontalOrigin).toEqual(new import__440.Expression("0")); expect(style.labelVerticalOrigin).toEqual(new import__440.Expression("0")); }); }); it("fromUrl loads style from Resource", function() { return import__440.Cesium3DTileStyle.fromUrl( new import__440.Resource({ url: styleUrl }) ).then(function(style) { expect(style.style).toEqual({ color: "color('red')", show: "${id} < 100.0", pointSize: "${id} / 100.0", pointOutlineColor: "color('blue')", pointOutlineWidth: "5.0", labelColor: "color('yellow')", labelOutlineColor: "color('orange')", labelOutlineWidth: "6.0", font: "'24px Helvetica'", labelStyle: "1", labelText: "'label text'", backgroundColor: "color('coral')", backgroundPadding: "vec2(1.0, 2.0)", backgroundEnabled: "true", scaleByDistance: "vec4(1.0, 2.0, 3.0, 4.0)", translucencyByDistance: "vec4(5.0, 6.0, 7.0, 8.0)", distanceDisplayCondition: "vec2(3.0, 4.0)", heightOffset: "10.0", anchorLineEnabled: "true", anchorLineColor: "color('fuchsia')", image: "'url/to/invalid/image'", disableDepthTestDistance: "1000.0", horizontalOrigin: "0", verticalOrigin: "0", labelHorizontalOrigin: "0", labelVerticalOrigin: "0" }); expect(style.color).toEqual(new import__440.Expression("color('red')")); expect(style.show).toEqual(new import__440.Expression("${id} < 100.0")); expect(style.pointSize).toEqual(new import__440.Expression("${id} / 100.0")); expect(style.pointOutlineColor).toEqual(new import__440.Expression("color('blue')")); expect(style.pointOutlineWidth).toEqual(new import__440.Expression("5.0")); expect(style.labelColor).toEqual(new import__440.Expression("color('yellow')")); expect(style.labelOutlineColor).toEqual( new import__440.Expression("color('orange')") ); expect(style.labelOutlineWidth).toEqual(new import__440.Expression("6.0")); expect(style.font).toEqual(new import__440.Expression("'24px Helvetica'")); expect(style.labelStyle).toEqual(new import__440.Expression("1")); expect(style.labelText).toEqual(new import__440.Expression("'label text'")); expect(style.backgroundColor).toEqual(new import__440.Expression("color('coral')")); expect(style.backgroundPadding).toEqual(new import__440.Expression("vec2(1.0, 2.0)")); expect(style.backgroundEnabled).toEqual(new import__440.Expression("true")); expect(style.scaleByDistance).toEqual( new import__440.Expression("vec4(1.0, 2.0, 3.0, 4.0)") ); expect(style.translucencyByDistance).toEqual( new import__440.Expression("vec4(5.0, 6.0, 7.0, 8.0)") ); expect(style.distanceDisplayCondition).toEqual( new import__440.Expression("vec2(3.0, 4.0)") ); expect(style.heightOffset).toEqual(new import__440.Expression("10.0")); expect(style.anchorLineEnabled).toEqual(new import__440.Expression("true")); expect(style.anchorLineColor).toEqual(new import__440.Expression("color('fuchsia')")); expect(style.image).toEqual(new import__440.Expression("'url/to/invalid/image'")); expect(style.disableDepthTestDistance).toEqual(new import__440.Expression("1000.0")); expect(style.horizontalOrigin).toEqual(new import__440.Expression("0")); expect(style.verticalOrigin).toEqual(new import__440.Expression("0")); expect(style.labelHorizontalOrigin).toEqual(new import__440.Expression("0")); expect(style.labelVerticalOrigin).toEqual(new import__440.Expression("0")); }); }); it("sets show value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.show).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.show).toBeUndefined(); }); it("sets show value to expression", function() { let style = new import__440.Cesium3DTileStyle({ show: "true" }); expect(style.show).toEqual(new import__440.Expression("true")); style = new import__440.Cesium3DTileStyle({ show: "false" }); expect(style.show).toEqual(new import__440.Expression("false")); style = new import__440.Cesium3DTileStyle({ show: "${height} * 10 >= 1000" }); expect(style.show).toEqual(new import__440.Expression("${height} * 10 >= 1000")); style = new import__440.Cesium3DTileStyle({ show: true }); expect(style.show).toEqual(new import__440.Expression("true")); style = new import__440.Cesium3DTileStyle({ show: false }); expect(style.show).toEqual(new import__440.Expression("false")); }); it("sets show value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "false"], ["true", "true"] ] }; const style = new import__440.Cesium3DTileStyle({ show: jsonExp }); expect(style.show).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets show expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "false"], ["true", "true"] ] }); style.show = condExp; expect(style.show).toEqual(condExp); const exp = new import__440.Expression("false"); style.show = exp; expect(style.show).toEqual(exp); }); it("sets show values in setter", function() { const defines = { showFactor: 10 }; const style = new import__440.Cesium3DTileStyle({ defines }); style.show = "${height} * ${showFactor} >= 1000"; expect(style.show).toEqual( new import__440.Expression("${height} * ${showFactor} >= 1000", defines) ); style.show = false; expect(style.show).toEqual(new import__440.Expression("false")); const jsonExp = { conditions: [ ["${height} > ${showFactor}", "false"], ["true", "true"] ] }; style.show = jsonExp; expect(style.show).toEqual(new import__440.ConditionsExpression(jsonExp, defines)); style.show = void 0; expect(style.show).toBeUndefined(); }); it("sets style.show values in setter", function() { const style = new import__440.Cesium3DTileStyle({}); style.show = "${height} * ${showFactor} >= 1000"; expect(style.style.show).toEqual("${height} * ${showFactor} >= 1000"); style.show = false; expect(style.style.show).toEqual("false"); const jsonExp = { conditions: [ ["${height} > ${showFactor}", "false"], ["true", "true"] ] }; style.show = jsonExp; expect(style.style.show).toEqual(jsonExp); style.show = void 0; expect(style.style.show).toBeUndefined(); }); it("sets color value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.color).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.color).toBeUndefined(); }); it("sets color value to expression", function() { let style = new import__440.Cesium3DTileStyle({ color: 'color("red")' }); expect(style.color).toEqual(new import__440.Expression('color("red")')); style = new import__440.Cesium3DTileStyle({ color: "rgba(30, 30, 30, 0.5)" }); expect(style.color).toEqual(new import__440.Expression("rgba(30, 30, 30, 0.5)")); style = new import__440.Cesium3DTileStyle({ color: '(${height} * 10 >= 1000) ? rgba(0.0, 0.0, 1.0, 0.5) : color("blue")' }); expect(style.color).toEqual( new import__440.Expression( '(${height} * 10 >= 1000) ? rgba(0.0, 0.0, 1.0, 0.5) : color("blue")' ) ); }); it("sets color value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }; const style = new import__440.Cesium3DTileStyle({ color: jsonExp }); expect(style.color).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets color expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); const exp = new import__440.Expression('color("red")'); style.color = exp; expect(style.color).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }); style.color = condExp; expect(style.color).toEqual(condExp); style.color = void 0; expect(style.color).toBeUndefined(); }); it("sets style.color expression in setter", function() { const style = new import__440.Cesium3DTileStyle(); const stringExp = 'color("red")'; style.color = new import__440.Expression(stringExp); expect(style.style.color).toEqual(stringExp); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }; style.color = new import__440.ConditionsExpression(jsonExp); expect(style.style.color).toEqual(jsonExp); style.color = void 0; expect(style.style.color).toBeUndefined(); }); it("sets color values in setter", function() { const defines = { targetColor: "red" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.color = 'color("${targetColor}")'; expect(style.color).toEqual( new import__440.Expression('color("${targetColor}")', defines) ); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("${targetColor}")'] ] }; style.color = jsonExp; expect(style.color).toEqual(new import__440.ConditionsExpression(jsonExp, defines)); }); it("sets style.color values in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.color = 'color("${targetColor}")'; expect(style.style.color).toEqual('color("${targetColor}")'); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("${targetColor}")'] ] }; style.color = jsonExp; expect(style.style.color).toEqual(jsonExp); }); it("sets pointSize value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.pointSize).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.pointSize).toBeUndefined(); }); it("sets pointSize value to expression", function() { let style = new import__440.Cesium3DTileStyle({ pointSize: "2" }); expect(style.pointSize).toEqual(new import__440.Expression("2")); style = new import__440.Cesium3DTileStyle({ pointSize: "${height} / 10" }); expect(style.pointSize).toEqual(new import__440.Expression("${height} / 10")); style = new import__440.Cesium3DTileStyle({ pointSize: 2 }); expect(style.pointSize).toEqual(new import__440.Expression("2")); }); it("sets pointSize value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "2.0"] ] }; const style = new import__440.Cesium3DTileStyle({ pointSize: jsonExp }); expect(style.pointSize).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets pointSize expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.pointSize = 2; expect(style.pointSize).toEqual(new import__440.Expression("2")); const exp = new import__440.Expression("2"); style.pointSize = exp; expect(style.pointSize).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "1.0"], ["true", "2.0"] ] }); style.pointSize = condExp; expect(style.pointSize).toEqual(condExp); style.pointSize = void 0; expect(style.pointSize).toBeUndefined(); }); it("sets style.pointSize expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.pointSize = new import__440.Expression("2"); expect(style.style.pointSize).toEqual("2"); const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "2.0"] ] }; style.pointSize = new import__440.ConditionsExpression(jsonExp); expect(style.style.pointSize).toEqual(jsonExp); const customExpression = { evaluate: function() { return 1; } }; style.pointSize = customExpression; expect(style.style.pointSize).toEqual(customExpression); style.pointSize = void 0; expect(style.style.pointSize).toBeUndefined(); }); it("sets pointSize values in setter", function() { const defines = { targetPointSize: "2.0" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.pointSize = 2; expect(style.pointSize).toEqual(new import__440.Expression("2")); style.pointSize = "${targetPointSize} + 1.0"; expect(style.pointSize).toEqual( new import__440.Expression("${targetPointSize} + 1.0", defines) ); const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "${targetPointSize}"] ] }; style.pointSize = jsonExp; expect(style.pointSize).toEqual(new import__440.ConditionsExpression(jsonExp, defines)); }); it("sets style.pointSize values in setter", function() { const defines = { targetPointSize: "2.0" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.pointSize = 2; expect(style.style.pointSize).toEqual("2"); style.pointSize = "${targetPointSize} + 1.0"; expect(style.style.pointSize).toEqual("${targetPointSize} + 1.0"); const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "${targetPointSize}"] ] }; style.pointSize = jsonExp; expect(style.style.pointSize).toEqual(jsonExp); }); it("sets pointOutlineColor value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.pointOutlineColor).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.pointOutlineColor).toBeUndefined(); }); it("sets pointOutlineColor value to expression", function() { let style = new import__440.Cesium3DTileStyle({ pointOutlineColor: 'color("red")' }); expect(style.pointOutlineColor).toEqual(new import__440.Expression('color("red")')); style = new import__440.Cesium3DTileStyle({ pointOutlineColor: "rgba(30, 30, 30, 0.5)" }); expect(style.pointOutlineColor).toEqual( new import__440.Expression("rgba(30, 30, 30, 0.5)") ); style = new import__440.Cesium3DTileStyle({ pointOutlineColor: '(${height} * 10 >= 1000) ? rgba(0.0, 0.0, 1.0, 0.5) : color("blue")' }); expect(style.pointOutlineColor).toEqual( new import__440.Expression( '(${height} * 10 >= 1000) ? rgba(0.0, 0.0, 1.0, 0.5) : color("blue")' ) ); }); it("sets pointOutlineColor value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }; const style = new import__440.Cesium3DTileStyle({ pointOutlineColor: jsonExp }); expect(style.pointOutlineColor).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets pointOutlineColor expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); const exp = new import__440.Expression('color("red")'); style.pointOutlineColor = exp; expect(style.pointOutlineColor).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }); style.pointOutlineColor = condExp; expect(style.pointOutlineColor).toEqual(condExp); style.pointOutlineColor = void 0; expect(style.pointOutlineColor).toBeUndefined(); }); it("sets style.pointOutlineColor expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.pointOutlineColor = new import__440.Expression('color("red")'); expect(style.style.pointOutlineColor).toEqual('color("red")'); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }; style.pointOutlineColor = new import__440.ConditionsExpression(jsonExp); expect(style.style.pointOutlineColor).toEqual(jsonExp); const customExpression = { evaluate: function() { return import__440.Color.RED; }, evaluateColor: function() { return import__440.Color.RED; } }; style.pointOutlineColor = customExpression; expect(style.style.pointOutlineColor).toEqual(customExpression); style.pointOutlineColor = void 0; expect(style.style.pointOutlineColor).toBeUndefined(); }); it("sets pointOutlineColor values in setter", function() { const defines = { targetColor: "red" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.pointOutlineColor = 'color("${targetColor}")'; expect(style.pointOutlineColor).toEqual( new import__440.Expression('color("${targetColor}")', defines) ); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("${targetColor}")'] ] }; style.pointOutlineColor = jsonExp; expect(style.pointOutlineColor).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); }); it("sets style.pointOutlineColor values in setter", function() { const defines = { targetColor: "red" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.pointOutlineColor = 'color("${targetColor}")'; expect(style.style.pointOutlineColor).toEqual('color("${targetColor}")'); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("${targetColor}")'] ] }; style.pointOutlineColor = jsonExp; expect(style.style.pointOutlineColor).toEqual(jsonExp); }); it("sets pointOutlineWidth value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.pointOutlineWidth).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.pointOutlineWidth).toBeUndefined(); }); it("sets pointOutlineWidth value to expression", function() { let style = new import__440.Cesium3DTileStyle({ pointOutlineWidth: "2" }); expect(style.pointOutlineWidth).toEqual(new import__440.Expression("2")); style = new import__440.Cesium3DTileStyle({ pointOutlineWidth: "${height} / 10" }); expect(style.pointOutlineWidth).toEqual(new import__440.Expression("${height} / 10")); style = new import__440.Cesium3DTileStyle({ pointOutlineWidth: 2 }); expect(style.pointOutlineWidth).toEqual(new import__440.Expression("2")); }); it("sets pointOutlineWidth value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "2.0"] ] }; const style = new import__440.Cesium3DTileStyle({ pointOutlineWidth: jsonExp }); expect(style.pointOutlineWidth).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets pointOutlineWidth expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.pointOutlineWidth = 2; expect(style.pointOutlineWidth).toEqual(new import__440.Expression("2")); const exp = new import__440.Expression("2"); style.pointOutlineWidth = exp; expect(style.pointOutlineWidth).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "1.0"], ["true", "2.0"] ] }); style.pointOutlineWidth = condExp; expect(style.pointOutlineWidth).toEqual(condExp); style.pointOutlineWidth = void 0; expect(style.pointOutlineWidth).toBeUndefined(); }); it("sets style.pointOutlineWidth expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.pointOutlineWidth = new import__440.Expression("2"); expect(style.style.pointOutlineWidth).toEqual("2"); const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "2.0"] ] }; style.pointOutlineWidth = new import__440.ConditionsExpression(jsonExp); expect(style.style.pointOutlineWidth).toEqual(jsonExp); const customExpression = { evaluate: function() { return 1; } }; style.pointOutlineWidth = customExpression; expect(style.style.pointOutlineWidth).toEqual(customExpression); style.pointOutlineWidth = void 0; expect(style.style.pointOutlineWidth).toBeUndefined(); }); it("sets pointOutlineWidth values in setter", function() { const defines = { targetPointSize: "2.0" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.pointOutlineWidth = 2; expect(style.pointOutlineWidth).toEqual(new import__440.Expression("2")); style.pointOutlineWidth = "${targetPointSize} + 1.0"; expect(style.pointOutlineWidth).toEqual( new import__440.Expression("${targetPointSize} + 1.0", defines) ); const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "${targetPointSize}"] ] }; style.pointOutlineWidth = jsonExp; expect(style.pointOutlineWidth).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); }); it("sets style.pointOutlineWidth values in setter", function() { const defines = { targetPointSize: "2.0" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.pointOutlineWidth = 2; expect(style.style.pointOutlineWidth).toEqual("2"); style.pointOutlineWidth = "${targetPointSize} + 1.0"; expect(style.style.pointOutlineWidth).toEqual("${targetPointSize} + 1.0"); const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "${targetPointSize}"] ] }; style.pointOutlineWidth = jsonExp; expect(style.style.pointOutlineWidth).toEqual(jsonExp); }); it("sets labelColor value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.labelColor).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.labelColor).toBeUndefined(); }); it("sets labelColor value to expression", function() { let style = new import__440.Cesium3DTileStyle({ labelColor: 'color("red")' }); expect(style.labelColor).toEqual(new import__440.Expression('color("red")')); style = new import__440.Cesium3DTileStyle({ labelColor: "rgba(30, 30, 30, 0.5)" }); expect(style.labelColor).toEqual(new import__440.Expression("rgba(30, 30, 30, 0.5)")); style = new import__440.Cesium3DTileStyle({ labelColor: '(${height} * 10 >= 1000) ? rgba(0.0, 0.0, 1.0, 0.5) : color("blue")' }); expect(style.labelColor).toEqual( new import__440.Expression( '(${height} * 10 >= 1000) ? rgba(0.0, 0.0, 1.0, 0.5) : color("blue")' ) ); }); it("sets labelColor value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }; const style = new import__440.Cesium3DTileStyle({ labelColor: jsonExp }); expect(style.labelColor).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets labelColor expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); const exp = new import__440.Expression('color("red")'); style.labelColor = exp; expect(style.labelColor).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }); style.labelColor = condExp; expect(style.labelColor).toEqual(condExp); style.labelColor = void 0; expect(style.labelColor).toBeUndefined(); }); it("sets style.labelColor expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.labelColor = new import__440.Expression('color("red")'); expect(style.style.labelColor).toEqual('color("red")'); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }; style.labelColor = new import__440.ConditionsExpression(jsonExp); expect(style.style.labelColor).toEqual(jsonExp); const customExpression = { evaluate: function() { return import__440.Color.RED; }, evaluateColor: function() { return import__440.Color.RED; } }; style.labelColor = customExpression; expect(style.style.labelColor).toEqual(customExpression); style.labelColor = void 0; expect(style.style.labelColor).toBeUndefined(); }); it("sets labelColor values in setter", function() { const defines = { targetColor: "red" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.labelColor = 'color("${targetColor}")'; expect(style.labelColor).toEqual( new import__440.Expression('color("${targetColor}")', defines) ); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("${targetColor}")'] ] }; style.labelColor = jsonExp; expect(style.labelColor).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); }); it("sets style.labelColor values in setter", function() { const defines = { targetColor: "red" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.labelColor = 'color("${targetColor}")'; expect(style.style.labelColor).toEqual('color("${targetColor}")'); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("${targetColor}")'] ] }; style.labelColor = jsonExp; expect(style.style.labelColor).toEqual(jsonExp); }); it("sets labelOutlineColor value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.labelOutlineColor).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.labelOutlineColor).toBeUndefined(); }); it("sets labelOutlineColor value to expression", function() { let style = new import__440.Cesium3DTileStyle({ labelOutlineColor: 'color("red")' }); expect(style.labelOutlineColor).toEqual(new import__440.Expression('color("red")')); style = new import__440.Cesium3DTileStyle({ labelOutlineColor: "rgba(30, 30, 30, 0.5)" }); expect(style.labelOutlineColor).toEqual( new import__440.Expression("rgba(30, 30, 30, 0.5)") ); style = new import__440.Cesium3DTileStyle({ labelOutlineColor: '(${height} * 10 >= 1000) ? rgba(0.0, 0.0, 1.0, 0.5) : color("blue")' }); expect(style.labelOutlineColor).toEqual( new import__440.Expression( '(${height} * 10 >= 1000) ? rgba(0.0, 0.0, 1.0, 0.5) : color("blue")' ) ); }); it("sets labelOutlineColor value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }; const style = new import__440.Cesium3DTileStyle({ labelOutlineColor: jsonExp }); expect(style.labelOutlineColor).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets labelOutlineColor expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); const exp = new import__440.Expression('color("red")'); style.labelOutlineColor = exp; expect(style.labelOutlineColor).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }); style.labelOutlineColor = condExp; expect(style.labelOutlineColor).toEqual(condExp); style.labelOutlineColor = void 0; expect(style.labelOutlineColor).toBeUndefined(); }); it("sets style.labelOutlineColor expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.labelOutlineColor = new import__440.Expression('color("red")'); expect(style.style.labelOutlineColor).toEqual('color("red")'); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }; style.labelOutlineColor = new import__440.ConditionsExpression(jsonExp); expect(style.style.labelOutlineColor).toEqual(jsonExp); const customExpression = { evaluate: function() { return import__440.Color.RED; }, evaluateColor: function() { return import__440.Color.RED; } }; style.labelOutlineColor = customExpression; expect(style.style.labelOutlineColor).toEqual(customExpression); style.labelOutlineColor = void 0; expect(style.style.labelOutlineColor).toBeUndefined(); }); it("sets labelOutlineColor values in setter", function() { const defines = { targetColor: "red" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.labelOutlineColor = 'color("${targetColor}")'; expect(style.labelOutlineColor).toEqual( new import__440.Expression('color("${targetColor}")', defines) ); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("${targetColor}")'] ] }; style.labelOutlineColor = jsonExp; expect(style.labelOutlineColor).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); }); it("sets style.labelOutlineColor values in setter", function() { const defines = { targetColor: "red" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.labelOutlineColor = 'color("${targetColor}")'; expect(style.style.labelOutlineColor).toEqual('color("${targetColor}")'); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("${targetColor}")'] ] }; style.labelOutlineColor = jsonExp; expect(style.style.labelOutlineColor).toEqual(jsonExp); }); it("sets labelOutlineWidth value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.labelOutlineWidth).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.labelOutlineWidth).toBeUndefined(); }); it("sets labelOutlineWidth value to expression", function() { let style = new import__440.Cesium3DTileStyle({ labelOutlineWidth: "2" }); expect(style.labelOutlineWidth).toEqual(new import__440.Expression("2")); style = new import__440.Cesium3DTileStyle({ labelOutlineWidth: "${height} / 10" }); expect(style.labelOutlineWidth).toEqual(new import__440.Expression("${height} / 10")); style = new import__440.Cesium3DTileStyle({ labelOutlineWidth: 2 }); expect(style.labelOutlineWidth).toEqual(new import__440.Expression("2")); }); it("sets labelOutlineWidth value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "2.0"] ] }; const style = new import__440.Cesium3DTileStyle({ labelOutlineWidth: jsonExp }); expect(style.labelOutlineWidth).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets labelOutlineWidth expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.labelOutlineWidth = 2; expect(style.labelOutlineWidth).toEqual(new import__440.Expression("2")); const exp = new import__440.Expression("2"); style.labelOutlineWidth = exp; expect(style.labelOutlineWidth).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "1.0"], ["true", "2.0"] ] }); style.labelOutlineWidth = condExp; expect(style.labelOutlineWidth).toEqual(condExp); style.labelOutlineWidth = void 0; expect(style.labelOutlineWidth).toBeUndefined(); }); it("sets style.labelOutlineWidth expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.labelOutlineWidth = new import__440.Expression("2"); expect(style.style.labelOutlineWidth).toEqual("2"); const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "2.0"] ] }; style.labelOutlineWidth = new import__440.ConditionsExpression(jsonExp); expect(style.style.labelOutlineWidth).toEqual(jsonExp); const customExpression = { evaluate: function() { return 1; } }; style.labelOutlineWidth = customExpression; expect(style.style.labelOutlineWidth).toEqual(customExpression); style.labelOutlineWidth = void 0; expect(style.style.labelOutlineWidth).toBeUndefined(); }); it("sets labelOutlineWidth values in setter", function() { const defines = { targetLabelSize: "2.0" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.labelOutlineWidth = 2; expect(style.labelOutlineWidth).toEqual(new import__440.Expression("2")); style.labelOutlineWidth = "${targetLabelSize} + 1.0"; expect(style.labelOutlineWidth).toEqual( new import__440.Expression("${targetLabelSize} + 1.0", defines) ); const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "${targetLabelSize}"] ] }; style.labelOutlineWidth = jsonExp; expect(style.labelOutlineWidth).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); }); it("sets style.labelOutlineWidth values in setter", function() { const defines = { targetLabelSize: "2.0" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.labelOutlineWidth = 2; expect(style.style.labelOutlineWidth).toEqual("2"); style.labelOutlineWidth = "${targetLabelSize} + 1.0"; expect(style.style.labelOutlineWidth).toEqual("${targetLabelSize} + 1.0"); const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "${targetLabelSize}"] ] }; style.labelOutlineWidth = jsonExp; expect(style.style.labelOutlineWidth).toEqual(jsonExp); }); it("sets font value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.font).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.font).toBeUndefined(); }); it("sets font value to expression", function() { let style = new import__440.Cesium3DTileStyle({ font: "'24px Helvetica'" }); expect(style.font).toEqual(new import__440.Expression("'24px Helvetica'")); style = new import__440.Cesium3DTileStyle({ font: "${font}" }); expect(style.font).toEqual(new import__440.Expression("${font}")); style = new import__440.Cesium3DTileStyle({ font: "'24px Helvetica'" }); expect(style.font).toEqual(new import__440.Expression("'24px Helvetica'")); }); it("sets font value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "'30px Helvetica'"], ["true", "'24px Helvetica'"] ] }; const style = new import__440.Cesium3DTileStyle({ font: jsonExp }); expect(style.font).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets font expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.font = "'24px Helvetica'"; expect(style.font).toEqual(new import__440.Expression("'24px Helvetica'")); const exp = new import__440.Expression("'24px Helvetica'"); style.font = exp; expect(style.font).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "'30px Helvetica'"], ["true", "'24px Helvetica'"] ] }); style.font = condExp; expect(style.font).toEqual(condExp); style.font = void 0; expect(style.font).toBeUndefined(); }); it("sets style.font expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.font = new import__440.Expression("'24px Helvetica'"); expect(style.style.font).toEqual("'24px Helvetica'"); const jsonExp = { conditions: [ ["${height} > 2", "'30px Helvetica'"], ["true", "'24px Helvetica'"] ] }; style.font = new import__440.ConditionsExpression(jsonExp); expect(style.style.font).toEqual(jsonExp); const customExpression = { evaluate: function() { return "'24px Helvetica'"; } }; style.font = customExpression; expect(style.style.font).toEqual(customExpression); style.font = void 0; expect(style.style.font).toBeUndefined(); }); it("sets font values in setter", function() { const defines = { targetFont: "'30px Helvetica'" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.font = "'24px Helvetica'"; expect(style.font).toEqual(new import__440.Expression("'24px Helvetica'")); style.font = "${targetFont}"; expect(style.font).toEqual(new import__440.Expression("${targetFont}", defines)); const jsonExp = { conditions: [ ["${height} > 2", "'24px Helvetica'"], ["true", "${targetFont}"] ] }; style.font = jsonExp; expect(style.font).toEqual(new import__440.ConditionsExpression(jsonExp, defines)); }); it("sets style.font values in setter", function() { const defines = { targetFont: "'30px Helvetica'" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.font = "'24px Helvetica'"; expect(style.style.font).toEqual("'24px Helvetica'"); style.font = "${targetFont}"; expect(style.style.font).toEqual("${targetFont}"); const jsonExp = { conditions: [ ["${height} > 2", "'24px Helvetica'"], ["true", "${targetFont}"] ] }; style.font = jsonExp; expect(style.style.font).toEqual(jsonExp); }); it("sets labelStyle value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.labelStyle).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.labelStyle).toBeUndefined(); }); it("sets labelStyle value to expression", function() { const style = new import__440.Cesium3DTileStyle({ labelStyle: "2" }); expect(style.labelStyle).toEqual(new import__440.Expression("2")); }); it("sets labelStyle value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "2"] ] }; const style = new import__440.Cesium3DTileStyle({ labelStyle: jsonExp }); expect(style.labelStyle).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets labelStyle expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.labelStyle = 2; expect(style.labelStyle).toEqual(new import__440.Expression("2")); const exp = new import__440.Expression("2"); style.labelStyle = exp; expect(style.labelStyle).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "1"], ["true", "2"] ] }); style.labelStyle = condExp; expect(style.labelStyle).toEqual(condExp); style.labelStyle = void 0; expect(style.labelStyle).toBeUndefined(); }); it("sets style.labelStyle expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.labelStyle = new import__440.Expression("2"); expect(style.style.labelStyle).toEqual("2"); const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "2"] ] }; style.labelStyle = new import__440.ConditionsExpression(jsonExp); expect(style.style.labelStyle).toEqual(jsonExp); const customExpression = { evaluate: function() { return 0; } }; style.labelStyle = customExpression; expect(style.style.labelStyle).toEqual(customExpression); style.labelStyle = void 0; expect(style.style.labelStyle).toBeUndefined(); }); it("sets labelStyle values in setter", function() { const defines = { targetLabelStyle: "2" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.labelStyle = 2; expect(style.labelStyle).toEqual(new import__440.Expression("2")); style.labelStyle = "${targetLabelStyle}"; expect(style.labelStyle).toEqual( new import__440.Expression("${targetLabelStyle}", defines) ); const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "${targetLabelStyle}"] ] }; style.labelStyle = jsonExp; expect(style.labelStyle).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); }); it("sets style.labelStyle values in setter", function() { const defines = { targetLabelStyle: "2" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.labelStyle = 2; expect(style.style.labelStyle).toEqual("2"); style.labelStyle = "${targetLabelStyle}"; expect(style.style.labelStyle).toEqual("${targetLabelStyle}"); const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "${targetLabelStyle}"] ] }; style.labelStyle = jsonExp; expect(style.style.labelStyle).toEqual(jsonExp); }); it("sets labelText value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.labelText).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.labelText).toBeUndefined(); }); it("sets labelText value to expression", function() { let style = new import__440.Cesium3DTileStyle({ labelText: "'test text'" }); expect(style.labelText).toEqual(new import__440.Expression("'test text'")); style = new import__440.Cesium3DTileStyle({ labelText: "${text}" }); expect(style.labelText).toEqual(new import__440.Expression("${text}")); style = new import__440.Cesium3DTileStyle({ labelText: "'test text'" }); expect(style.labelText).toEqual(new import__440.Expression("'test text'")); }); it("sets labelText value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "'test text 1'"], ["true", "'test text 2'"] ] }; const style = new import__440.Cesium3DTileStyle({ labelText: jsonExp }); expect(style.labelText).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets labelText expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.labelText = "'test text'"; expect(style.labelText).toEqual(new import__440.Expression("'test text'")); const exp = new import__440.Expression("'test text'"); style.labelText = exp; expect(style.labelText).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "'test text 1'"], ["true", "'test text 2'"] ] }); style.labelText = condExp; expect(style.labelText).toEqual(condExp); style.labelText = void 0; expect(style.labelText).toBeUndefined(); }); it("sets style.labelText expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.labelText = new import__440.Expression("'test text'"); expect(style.style.labelText).toEqual("'test text'"); const jsonExp = { conditions: [ ["${height} > 2", "'test text 1'"], ["true", "'test text 2'"] ] }; style.labelText = new import__440.ConditionsExpression(jsonExp); expect(style.style.labelText).toEqual(jsonExp); const customExpression = { evaluate: function() { return "'test text 1'"; } }; style.labelText = customExpression; expect(style.style.labelText).toEqual(customExpression); style.labelText = void 0; expect(style.style.labelText).toBeUndefined(); }); it("sets labelText values in setter", function() { const defines = { targetText: "'test text 1'" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.labelText = "'test text'"; expect(style.labelText).toEqual(new import__440.Expression("'test text'")); style.labelText = "${targetText}"; expect(style.labelText).toEqual(new import__440.Expression("${targetText}", defines)); const jsonExp = { conditions: [ ["${height} > 2", "'test text 2'"], ["true", "${targetText}"] ] }; style.labelText = jsonExp; expect(style.labelText).toEqual(new import__440.ConditionsExpression(jsonExp, defines)); }); it("sets style.labelText values in setter", function() { const defines = { targetText: "'test text 1'" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.labelText = "'test text'"; expect(style.style.labelText).toEqual("'test text'"); style.labelText = "${targetText}"; expect(style.style.labelText).toEqual("${targetText}"); const jsonExp = { conditions: [ ["${height} > 2", "'test text 2'"], ["true", "${targetText}"] ] }; style.labelText = jsonExp; expect(style.style.labelText).toEqual(jsonExp); }); it("sets backgroundColor value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.backgroundColor).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.backgroundColor).toBeUndefined(); }); it("sets backgroundColor value to expression", function() { let style = new import__440.Cesium3DTileStyle({ backgroundColor: 'color("red")' }); expect(style.backgroundColor).toEqual(new import__440.Expression('color("red")')); style = new import__440.Cesium3DTileStyle({ backgroundColor: "rgba(30, 30, 30, 0.5)" }); expect(style.backgroundColor).toEqual( new import__440.Expression("rgba(30, 30, 30, 0.5)") ); style = new import__440.Cesium3DTileStyle({ backgroundColor: '(${height} * 10 >= 1000) ? rgba(0.0, 0.0, 1.0, 0.5) : color("blue")' }); expect(style.backgroundColor).toEqual( new import__440.Expression( '(${height} * 10 >= 1000) ? rgba(0.0, 0.0, 1.0, 0.5) : color("blue")' ) ); }); it("sets backgroundColor value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }; const style = new import__440.Cesium3DTileStyle({ backgroundColor: jsonExp }); expect(style.backgroundColor).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets backgroundColor expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); const exp = new import__440.Expression('color("red")'); style.backgroundColor = exp; expect(style.backgroundColor).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }); style.backgroundColor = condExp; expect(style.backgroundColor).toEqual(condExp); style.backgroundColor = void 0; expect(style.backgroundColor).toBeUndefined(); }); it("sets style.backgroundColor expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.backgroundColor = new import__440.Expression('color("red")'); expect(style.style.backgroundColor).toEqual('color("red")'); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }; style.backgroundColor = new import__440.ConditionsExpression(jsonExp); expect(style.style.backgroundColor).toEqual(jsonExp); const customExpression = { evaluate: function() { return import__440.Color.RED; }, evaluateColor: function() { return import__440.Color.RED; } }; style.backgroundColor = customExpression; expect(style.style.backgroundColor).toEqual(customExpression); style.backgroundColor = void 0; expect(style.style.backgroundColor).toBeUndefined(); }); it("sets backgroundColor values in setter", function() { const defines = { targetColor: "red" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.backgroundColor = 'color("${targetColor}")'; expect(style.backgroundColor).toEqual( new import__440.Expression('color("${targetColor}")', defines) ); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("${targetColor}")'] ] }; style.backgroundColor = jsonExp; expect(style.backgroundColor).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); }); it("sets style.backgroundColor values in setter", function() { const defines = { targetColor: "red" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.backgroundColor = 'color("${targetColor}")'; expect(style.style.backgroundColor).toEqual('color("${targetColor}")'); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("${targetColor}")'] ] }; style.backgroundColor = jsonExp; expect(style.style.backgroundColor).toEqual(jsonExp); }); it("sets backgroundPadding value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.backgroundPadding).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.backgroundPadding).toBeUndefined(); }); it("sets backgroundPadding value to expression", function() { let style = new import__440.Cesium3DTileStyle({ backgroundPadding: "vec2(1.0, 2.0)" }); expect(style.backgroundPadding).toEqual(new import__440.Expression("vec2(1.0, 2.0)")); style = new import__440.Cesium3DTileStyle({ backgroundPadding: "vec2(3.0, 4.0)" }); expect(style.backgroundPadding).toEqual(new import__440.Expression("vec2(3.0, 4.0)")); style = new import__440.Cesium3DTileStyle({ backgroundPadding: "(${height} * 10 >= 1000) ? vec2(1.0, 2.0) : vec2(3.0, 4.0)" }); expect(style.backgroundPadding).toEqual( new import__440.Expression( "(${height} * 10 >= 1000) ? vec2(1.0, 2.0) : vec2(3.0, 4.0)" ) ); }); it("sets backgroundPadding value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "vec2(1.0, 2.0)"], ["true", "vec2(3.0, 4.0)"] ] }; const style = new import__440.Cesium3DTileStyle({ backgroundPadding: jsonExp }); expect(style.backgroundPadding).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets backgroundPadding expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); const exp = new import__440.Expression("vec2(1.0, 2.0)"); style.backgroundPadding = exp; expect(style.backgroundPadding).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "vec2(1.0, 2.0)"], ["true", "vec2(3.0, 4.0)"] ] }); style.backgroundPadding = condExp; expect(style.backgroundPadding).toEqual(condExp); style.backgroundPadding = void 0; expect(style.backgroundPadding).toBeUndefined(); }); it("sets style.backgroundPadding expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.backgroundPadding = new import__440.Expression("vec2(1.0, 2.0)"); expect(style.style.backgroundPadding).toEqual("vec2(1.0, 2.0)"); const jsonExp = { conditions: [ ["${height} > 2", "vec2(1.0, 2.0)"], ["true", "vec2(3.0, 4.0)"] ] }; const customExpression = { evaluate: function() { return new import__440.Cartesian2(1, 2); } }; style.labelText = customExpression; expect(style.style.labelText).toEqual(customExpression); style.backgroundPadding = new import__440.ConditionsExpression(jsonExp); expect(style.style.backgroundPadding).toEqual(jsonExp); style.backgroundPadding = void 0; expect(style.style.backgroundPadding).toBeUndefined(); }); it("sets backgroundPadding values in setter", function() { const defines = { targetPadding: "3.0, 4.0" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.backgroundPadding = 'vec2("${targetPadding}")'; expect(style.backgroundPadding).toEqual( new import__440.Expression('vec2("${targetPadding}")', defines) ); const jsonExp = { conditions: [ ["${height} > 2", "vec2(1.0, 2.0)"], ["true", 'vec2("${targetPadding}")'] ] }; style.backgroundPadding = jsonExp; expect(style.backgroundPadding).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); }); it("sets style.backgroundPadding values in setter", function() { const defines = { targetPadding: "3.0, 4.0" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.backgroundPadding = 'vec2("${targetPadding}")'; expect(style.style.backgroundPadding).toEqual('vec2("${targetPadding}")'); const jsonExp = { conditions: [ ["${height} > 2", "vec2(1.0, 2.0)"], ["true", 'vec2("${targetPadding}")'] ] }; style.backgroundPadding = jsonExp; expect(style.style.backgroundPadding).toEqual(jsonExp); }); it("sets backgroundEnabled value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.backgroundEnabled).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.backgroundEnabled).toBeUndefined(); }); it("sets backgroundEnabled value to expression", function() { let style = new import__440.Cesium3DTileStyle({ backgroundEnabled: "true" }); expect(style.backgroundEnabled).toEqual(new import__440.Expression("true")); style = new import__440.Cesium3DTileStyle({ backgroundEnabled: "false" }); expect(style.backgroundEnabled).toEqual(new import__440.Expression("false")); style = new import__440.Cesium3DTileStyle({ backgroundEnabled: "${height} * 10 >= 1000" }); expect(style.backgroundEnabled).toEqual( new import__440.Expression("${height} * 10 >= 1000") ); style = new import__440.Cesium3DTileStyle({ backgroundEnabled: true }); expect(style.backgroundEnabled).toEqual(new import__440.Expression("true")); style = new import__440.Cesium3DTileStyle({ backgroundEnabled: false }); expect(style.backgroundEnabled).toEqual(new import__440.Expression("false")); }); it("sets backgroundEnabled value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "false"], ["true", "true"] ] }; const style = new import__440.Cesium3DTileStyle({ backgroundEnabled: jsonExp }); expect(style.backgroundEnabled).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets backgroundEnabled expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "false"], ["true", "true"] ] }); style.backgroundEnabled = condExp; expect(style.backgroundEnabled).toEqual(condExp); const exp = new import__440.Expression("false"); style.backgroundEnabled = exp; expect(style.backgroundEnabled).toEqual(exp); }); it("sets style.backgroundEnabled expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.backgroundEnabled = new import__440.Expression("false"); expect(style.style.backgroundEnabled).toEqual("false"); const jsonExp = { conditions: [ ["${height} > 2", "false"], ["true", "true"] ] }; style.backgroundEnabled = new import__440.ConditionsExpression(jsonExp); expect(style.style.backgroundEnabled).toEqual(jsonExp); const customExpression = { evaluate: function() { return true; } }; style.backgroundEnabled = customExpression; expect(style.style.backgroundEnabled).toEqual(customExpression); }); it("sets backgroundEnabled values in setter", function() { const defines = { backgroundFactor: 10 }; const style = new import__440.Cesium3DTileStyle({ defines }); style.backgroundEnabled = "${height} * ${backgroundFactor} >= 1000"; expect(style.backgroundEnabled).toEqual( new import__440.Expression("${height} * ${backgroundFactor} >= 1000", defines) ); style.backgroundEnabled = false; expect(style.backgroundEnabled).toEqual(new import__440.Expression("false")); const jsonExp = { conditions: [ ["${height} > ${backgroundFactor}", "false"], ["true", "true"] ] }; style.backgroundEnabled = jsonExp; expect(style.backgroundEnabled).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); style.backgroundEnabled = void 0; expect(style.backgroundEnabled).toBeUndefined(); }); it("sets style.backgroundEnabled values in setter", function() { const defines = { backgroundFactor: 10 }; const style = new import__440.Cesium3DTileStyle({ defines }); style.backgroundEnabled = "${height} * ${backgroundFactor} >= 1000"; expect(style.style.backgroundEnabled).toEqual( "${height} * ${backgroundFactor} >= 1000" ); style.backgroundEnabled = false; expect(style.style.backgroundEnabled).toEqual("false"); const jsonExp = { conditions: [ ["${height} > ${backgroundFactor}", "false"], ["true", "true"] ] }; style.backgroundEnabled = jsonExp; expect(style.style.backgroundEnabled).toEqual(jsonExp); style.backgroundEnabled = void 0; expect(style.style.backgroundEnabled).toBeUndefined(); }); it("sets scaleByDistance value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.scaleByDistance).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.scaleByDistance).toBeUndefined(); }); it("sets scaleByDistance value to expression", function() { let style = new import__440.Cesium3DTileStyle({ scaleByDistance: "vec4(1.0, 2.0, 3.0, 4.0)" }); expect(style.scaleByDistance).toEqual( new import__440.Expression("vec4(1.0, 2.0, 3.0, 4.0)") ); style = new import__440.Cesium3DTileStyle({ scaleByDistance: "vec4(5.0, 6.0, 7.0, 8.0)" }); expect(style.scaleByDistance).toEqual( new import__440.Expression("vec4(5.0, 6.0, 7.0, 8.0)") ); style = new import__440.Cesium3DTileStyle({ scaleByDistance: "(${height} * 10 >= 1000) ? vec4(1.0, 2.0, 3.0, 4.0) : vec4(5.0, 6.0, 7.0, 8.0)" }); expect(style.scaleByDistance).toEqual( new import__440.Expression( "(${height} * 10 >= 1000) ? vec4(1.0, 2.0, 3.0, 4.0) : vec4(5.0, 6.0, 7.0, 8.0)" ) ); }); it("sets scaleByDistance value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "vec4(1.0, 2.0, 3.0, 4.0)"], ["true", "vec4(5.0, 6.0, 7.0, 8.0)"] ] }; const style = new import__440.Cesium3DTileStyle({ scaleByDistance: jsonExp }); expect(style.scaleByDistance).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets scaleByDistance expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); const exp = new import__440.Expression("vec4(5.0, 6.0, 7.0, 8.0)"); style.scaleByDistance = exp; expect(style.scaleByDistance).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "vec4(1.0, 2.0, 3.0, 4.0)"], ["true", "vec4(5.0, 6.0, 7.0, 8.0)"] ] }); style.scaleByDistance = condExp; expect(style.scaleByDistance).toEqual(condExp); style.scaleByDistance = void 0; expect(style.scaleByDistance).toBeUndefined(); }); it("sets style.scaleByDistance expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.scaleByDistance = new import__440.Expression("vec4(5.0, 6.0, 7.0, 8.0)"); expect(style.style.scaleByDistance).toEqual("vec4(5.0, 6.0, 7.0, 8.0)"); const jsonExp = { conditions: [ ["${height} > 2", "vec4(1.0, 2.0, 3.0, 4.0)"], ["true", "vec4(5.0, 6.0, 7.0, 8.0)"] ] }; style.scaleByDistance = new import__440.ConditionsExpression(jsonExp); expect(style.style.scaleByDistance).toEqual(jsonExp); const customExpression = { evaluate: function() { return new import__440.Cartesian4(1, 2, 3, 4); } }; style.scaleByDistance = customExpression; expect(style.style.scaleByDistance).toEqual(customExpression); style.scaleByDistance = void 0; expect(style.style.scaleByDistance).toBeUndefined(); }); it("sets scaleByDistance values in setter", function() { const defines = { targetScale: "1.0, 2.0, 3.0, 4." }; const style = new import__440.Cesium3DTileStyle({ defines }); style.scaleByDistance = 'vec4("${targetScale}")'; expect(style.scaleByDistance).toEqual( new import__440.Expression('vec4("${targetScale}")', defines) ); const jsonExp = { conditions: [ ["${height} > 2", "vec4(5.0, 6.0, 7.0, 8.0)"], ["true", 'vec4("${targetScale}")'] ] }; style.scaleByDistance = jsonExp; expect(style.scaleByDistance).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); }); it("sets style.scaleByDistance values in setter", function() { const defines = { targetScale: "1.0, 2.0, 3.0, 4." }; const style = new import__440.Cesium3DTileStyle({ defines }); style.scaleByDistance = 'vec4("${targetScale}")'; expect(style.style.scaleByDistance).toEqual('vec4("${targetScale}")'); const jsonExp = { conditions: [ ["${height} > 2", "vec4(5.0, 6.0, 7.0, 8.0)"], ["true", 'vec4("${targetScale}")'] ] }; style.scaleByDistance = jsonExp; expect(style.style.scaleByDistance).toEqual(jsonExp); }); it("sets distanceDisplayCondition value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.distanceDisplayCondition).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.distanceDisplayCondition).toBeUndefined(); }); it("sets distanceDisplayCondition value to expression", function() { let style = new import__440.Cesium3DTileStyle({ distanceDisplayCondition: "vec4(1.0, 2.0, 3.0, 4.0)" }); expect(style.distanceDisplayCondition).toEqual( new import__440.Expression("vec4(1.0, 2.0, 3.0, 4.0)") ); style = new import__440.Cesium3DTileStyle({ distanceDisplayCondition: "vec4(5.0, 6.0, 7.0, 8.0)" }); expect(style.distanceDisplayCondition).toEqual( new import__440.Expression("vec4(5.0, 6.0, 7.0, 8.0)") ); style = new import__440.Cesium3DTileStyle({ distanceDisplayCondition: "(${height} * 10 >= 1000) ? vec4(1.0, 2.0, 3.0, 4.0) : vec4(5.0, 6.0, 7.0, 8.0)" }); expect(style.distanceDisplayCondition).toEqual( new import__440.Expression( "(${height} * 10 >= 1000) ? vec4(1.0, 2.0, 3.0, 4.0) : vec4(5.0, 6.0, 7.0, 8.0)" ) ); }); it("sets distanceDisplayCondition value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "vec4(1.0, 2.0, 3.0, 4.0)"], ["true", "vec4(5.0, 6.0, 7.0, 8.0)"] ] }; const style = new import__440.Cesium3DTileStyle({ distanceDisplayCondition: jsonExp }); expect(style.distanceDisplayCondition).toEqual( new import__440.ConditionsExpression(jsonExp) ); }); it("sets distanceDisplayCondition expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); const exp = new import__440.Expression("vec4(5.0, 6.0, 7.0, 8.0)"); style.distanceDisplayCondition = exp; expect(style.distanceDisplayCondition).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "vec4(1.0, 2.0, 3.0, 4.0)"], ["true", "vec4(5.0, 6.0, 7.0, 8.0)"] ] }); style.distanceDisplayCondition = condExp; expect(style.distanceDisplayCondition).toEqual(condExp); style.distanceDisplayCondition = void 0; expect(style.distanceDisplayCondition).toBeUndefined(); }); it("sets style.distanceDisplayCondition expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.distanceDisplayCondition = new import__440.Expression("vec4(5.0, 6.0, 7.0, 8.0)"); expect(style.style.distanceDisplayCondition).toEqual( "vec4(5.0, 6.0, 7.0, 8.0)" ); const jsonExp = { conditions: [ ["${height} > 2", "vec4(1.0, 2.0, 3.0, 4.0)"], ["true", "vec4(5.0, 6.0, 7.0, 8.0)"] ] }; style.distanceDisplayCondition = new import__440.ConditionsExpression(jsonExp); expect(style.style.distanceDisplayCondition).toEqual(jsonExp); const customExpression = { evaluate: function() { return new import__440.Cartesian4(1, 2, 3, 4); } }; style.distanceDisplayCondition = customExpression; expect(style.style.distanceDisplayCondition).toEqual(customExpression); style.distanceDisplayCondition = void 0; expect(style.style.distanceDisplayCondition).toBeUndefined(); }); it("sets distanceDisplayCondition values in setter", function() { const defines = { targetTranslucency: "1.0, 2.0, 3.0, 4." }; const style = new import__440.Cesium3DTileStyle({ defines }); style.distanceDisplayCondition = 'vec4("${targetTranslucency}")'; expect(style.distanceDisplayCondition).toEqual( new import__440.Expression('vec4("${targetTranslucency}")', defines) ); const jsonExp = { conditions: [ ["${height} > 2", "vec4(5.0, 6.0, 7.0, 8.0)"], ["true", 'vec4("${targetTranslucency}")'] ] }; style.distanceDisplayCondition = jsonExp; expect(style.distanceDisplayCondition).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); }); it("sets style.distanceDisplayCondition values in setter", function() { const defines = { targetTranslucency: "1.0, 2.0, 3.0, 4." }; const style = new import__440.Cesium3DTileStyle({ defines }); style.distanceDisplayCondition = 'vec4("${targetTranslucency}")'; expect(style.style.distanceDisplayCondition).toEqual( 'vec4("${targetTranslucency}")' ); const jsonExp = { conditions: [ ["${height} > 2", "vec4(5.0, 6.0, 7.0, 8.0)"], ["true", 'vec4("${targetTranslucency}")'] ] }; style.distanceDisplayCondition = jsonExp; expect(style.style.distanceDisplayCondition).toEqual(jsonExp); }); it("sets heightOffset value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.heightOffset).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.heightOffset).toBeUndefined(); }); it("sets heightOffset value to expression", function() { let style = new import__440.Cesium3DTileStyle({ heightOffset: "2" }); expect(style.heightOffset).toEqual(new import__440.Expression("2")); style = new import__440.Cesium3DTileStyle({ heightOffset: "${height} / 10" }); expect(style.heightOffset).toEqual(new import__440.Expression("${height} / 10")); style = new import__440.Cesium3DTileStyle({ heightOffset: 2 }); expect(style.heightOffset).toEqual(new import__440.Expression("2")); }); it("sets heightOffset value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "2.0"] ] }; const style = new import__440.Cesium3DTileStyle({ heightOffset: jsonExp }); expect(style.heightOffset).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets heightOffset expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.heightOffset = 2; expect(style.heightOffset).toEqual(new import__440.Expression("2")); const exp = new import__440.Expression("2"); style.heightOffset = exp; expect(style.heightOffset).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "1.0"], ["true", "2.0"] ] }); style.heightOffset = condExp; expect(style.heightOffset).toEqual(condExp); style.heightOffset = void 0; expect(style.heightOffset).toBeUndefined(); }); it("sets style.heightOffset expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.heightOffset = new import__440.Expression("2"); expect(style.style.heightOffset).toEqual("2"); const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "2.0"] ] }; style.heightOffset = new import__440.ConditionsExpression(jsonExp); expect(style.style.heightOffset).toEqual(jsonExp); const customExpression = { evaluate: function() { return 2; } }; style.heightOffset = customExpression; expect(style.style.heightOffset).toEqual(customExpression); style.heightOffset = void 0; expect(style.style.heightOffset).toBeUndefined(); }); it("sets heightOffset values in setter", function() { const defines = { targetHeight: "2.0" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.heightOffset = 2; expect(style.heightOffset).toEqual(new import__440.Expression("2")); style.heightOffset = "${targetHeight} + 1.0"; expect(style.heightOffset).toEqual( new import__440.Expression("${targetHeight} + 1.0", defines) ); const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "${targetHeight}"] ] }; style.heightOffset = jsonExp; expect(style.heightOffset).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); }); it("sets style.heightOffset values in setter", function() { const defines = { targetHeight: "2.0" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.heightOffset = "${targetHeight} + 1.0"; expect(style.style.heightOffset).toEqual("${targetHeight} + 1.0"); const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "${targetHeight}"] ] }; style.heightOffset = jsonExp; expect(style.style.heightOffset).toEqual(jsonExp); }); it("sets anchorLineEnabled value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.anchorLineEnabled).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.anchorLineEnabled).toBeUndefined(); }); it("sets anchorLineEnabled value to expression", function() { let style = new import__440.Cesium3DTileStyle({ anchorLineEnabled: "true" }); expect(style.anchorLineEnabled).toEqual(new import__440.Expression("true")); style = new import__440.Cesium3DTileStyle({ anchorLineEnabled: "false" }); expect(style.anchorLineEnabled).toEqual(new import__440.Expression("false")); style = new import__440.Cesium3DTileStyle({ anchorLineEnabled: "${height} * 10 >= 1000" }); expect(style.anchorLineEnabled).toEqual( new import__440.Expression("${height} * 10 >= 1000") ); style = new import__440.Cesium3DTileStyle({ anchorLineEnabled: true }); expect(style.anchorLineEnabled).toEqual(new import__440.Expression("true")); style = new import__440.Cesium3DTileStyle({ anchorLineEnabled: false }); expect(style.anchorLineEnabled).toEqual(new import__440.Expression("false")); }); it("sets anchorLineEnabled value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "false"], ["true", "true"] ] }; const style = new import__440.Cesium3DTileStyle({ anchorLineEnabled: jsonExp }); expect(style.anchorLineEnabled).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets anchorLineEnabled expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "false"], ["true", "true"] ] }); style.anchorLineEnabled = condExp; expect(style.anchorLineEnabled).toEqual(condExp); const exp = new import__440.Expression("false"); style.anchorLineEnabled = exp; expect(style.anchorLineEnabled).toEqual(exp); }); it("sets style.anchorLineEnabled expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.anchorLineEnabled = new import__440.Expression("false"); expect(style.style.anchorLineEnabled).toEqual("false"); const jsonExp = { conditions: [ ["${height} > 2", "false"], ["true", "true"] ] }; style.anchorLineEnabled = new import__440.ConditionsExpression(jsonExp); expect(style.style.anchorLineEnabled).toEqual(jsonExp); const customExpression = { evaluate: function() { return true; } }; style.anchorLineEnabled = customExpression; expect(style.style.anchorLineEnabled).toEqual(customExpression); }); it("sets anchorLineEnabled values in setter", function() { const defines = { anchorFactor: 10 }; const style = new import__440.Cesium3DTileStyle({ defines }); style.anchorLineEnabled = "${height} * ${anchorFactor} >= 1000"; expect(style.anchorLineEnabled).toEqual( new import__440.Expression("${height} * ${anchorFactor} >= 1000", defines) ); style.anchorLineEnabled = false; expect(style.anchorLineEnabled).toEqual(new import__440.Expression("false")); const jsonExp = { conditions: [ ["${height} > ${anchorFactor}", "false"], ["true", "true"] ] }; style.anchorLineEnabled = jsonExp; expect(style.anchorLineEnabled).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); style.anchorLineEnabled = void 0; expect(style.anchorLineEnabled).toBeUndefined(); }); it("sets style.anchorLineEnabled values in setter", function() { const defines = { anchorFactor: 10 }; const style = new import__440.Cesium3DTileStyle({ defines }); style.anchorLineEnabled = "${height} * ${anchorFactor} >= 1000"; expect(style.style.anchorLineEnabled).toEqual( "${height} * ${anchorFactor} >= 1000" ); style.anchorLineEnabled = false; expect(style.style.anchorLineEnabled).toEqual("false"); const jsonExp = { conditions: [ ["${height} > ${anchorFactor}", "false"], ["true", "true"] ] }; style.anchorLineEnabled = jsonExp; expect(style.style.anchorLineEnabled).toEqual(jsonExp); style.anchorLineEnabled = void 0; expect(style.style.anchorLineEnabled).toBeUndefined(); }); it("sets anchorLineColor value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.anchorLineColor).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.anchorLineColor).toBeUndefined(); }); it("sets anchorLineColor value to expression", function() { let style = new import__440.Cesium3DTileStyle({ anchorLineColor: 'color("red")' }); expect(style.anchorLineColor).toEqual(new import__440.Expression('color("red")')); style = new import__440.Cesium3DTileStyle({ anchorLineColor: "rgba(30, 30, 30, 0.5)" }); expect(style.anchorLineColor).toEqual( new import__440.Expression("rgba(30, 30, 30, 0.5)") ); style = new import__440.Cesium3DTileStyle({ anchorLineColor: '(${height} * 10 >= 1000) ? rgba(0.0, 0.0, 1.0, 0.5) : color("blue")' }); expect(style.anchorLineColor).toEqual( new import__440.Expression( '(${height} * 10 >= 1000) ? rgba(0.0, 0.0, 1.0, 0.5) : color("blue")' ) ); }); it("sets anchorLineColor value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }; const style = new import__440.Cesium3DTileStyle({ anchorLineColor: jsonExp }); expect(style.anchorLineColor).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets anchorLineColor expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); const exp = new import__440.Expression('color("red")'); style.anchorLineColor = exp; expect(style.anchorLineColor).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }); style.anchorLineColor = condExp; expect(style.anchorLineColor).toEqual(condExp); style.anchorLineColor = void 0; expect(style.anchorLineColor).toBeUndefined(); }); it("sets style.anchorLineColor expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.anchorLineColor = new import__440.Expression('color("red")'); expect(style.style.anchorLineColor).toEqual('color("red")'); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("blue")'] ] }; style.anchorLineColor = new import__440.ConditionsExpression(jsonExp); expect(style.style.anchorLineColor).toEqual(jsonExp); const customExpression = { evaluate: function() { return import__440.Color.RED; }, evaluateColor: function() { return import__440.Color.RED; } }; style.anchorLineColor = customExpression; expect(style.style.anchorLineColor).toEqual(customExpression); style.anchorLineColor = void 0; expect(style.style.anchorLineColor).toBeUndefined(); }); it("sets anchorLineColor values in setter", function() { const defines = { targetColor: "red" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.anchorLineColor = 'color("${targetColor}")'; expect(style.anchorLineColor).toEqual( new import__440.Expression('color("${targetColor}")', defines) ); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("${targetColor}")'] ] }; style.anchorLineColor = jsonExp; expect(style.anchorLineColor).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); }); it("sets style.anchorLineColor values in setter", function() { const defines = { targetColor: "red" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.anchorLineColor = 'color("${targetColor}")'; expect(style.style.anchorLineColor).toEqual('color("${targetColor}")'); const jsonExp = { conditions: [ ["${height} > 2", 'color("cyan")'], ["true", 'color("${targetColor}")'] ] }; style.anchorLineColor = jsonExp; expect(style.style.anchorLineColor).toEqual(jsonExp); }); it("sets image value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.image).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.image).toBeUndefined(); }); it("sets image value to expression", function() { let style = new import__440.Cesium3DTileStyle({ image: "'url/to/image'" }); expect(style.image).toEqual(new import__440.Expression("'url/to/image'")); style = new import__440.Cesium3DTileStyle({ image: "${url}" }); expect(style.image).toEqual(new import__440.Expression("${url}")); style = new import__440.Cesium3DTileStyle({ image: "'url/to/image'" }); expect(style.image).toEqual(new import__440.Expression("'url/to/image'")); }); it("sets image value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "'url/to/image1'"], ["true", "'url/to/image2'"] ] }; const style = new import__440.Cesium3DTileStyle({ image: jsonExp }); expect(style.image).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets image expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.image = "'url/to/image'"; expect(style.image).toEqual(new import__440.Expression("'url/to/image'")); const exp = new import__440.Expression("'url/to/image'"); style.image = exp; expect(style.image).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "'url/to/image1'"], ["true", "'url/to/image2'"] ] }); style.image = condExp; expect(style.image).toEqual(condExp); style.image = void 0; expect(style.image).toBeUndefined(); }); it("sets style.image expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.image = new import__440.Expression("'url/to/image'"); expect(style.style.image).toEqual("'url/to/image'"); const jsonExp = { conditions: [ ["${height} > 2", "'url/to/image1'"], ["true", "'url/to/image2'"] ] }; style.image = new import__440.ConditionsExpression(jsonExp); expect(style.style.image).toEqual(jsonExp); const customExpression = { evaluate: function() { return "'url/to/image1'"; } }; style.image = customExpression; expect(style.style.image).toEqual(customExpression); style.image = void 0; expect(style.style.image).toBeUndefined(); }); it("sets image values in setter", function() { const defines = { targetUrl: "'url/to/image1'" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.image = "'url/to/image'"; expect(style.image).toEqual(new import__440.Expression("'url/to/image'")); style.image = "${targetUrl}"; expect(style.image).toEqual(new import__440.Expression("${targetUrl}", defines)); const jsonExp = { conditions: [ ["${height} > 2", "'url/to/image2'"], ["true", "${targetUrl}"] ] }; style.image = jsonExp; expect(style.image).toEqual(new import__440.ConditionsExpression(jsonExp, defines)); }); it("sets style.image values in setter", function() { const defines = { targetUrl: "'url/to/image1'" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.image = "'url/to/image'"; expect(style.style.image).toEqual("'url/to/image'"); style.image = "${targetUrl}"; expect(style.style.image).toEqual("${targetUrl}"); const jsonExp = { conditions: [ ["${height} > 2", "'url/to/image2'"], ["true", "${targetUrl}"] ] }; style.image = jsonExp; expect(style.style.image).toEqual(jsonExp); }); it("sets disableDepthTestDistance value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.disableDepthTestDistance).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.disableDepthTestDistance).toBeUndefined(); }); it("sets disableDepthTestDistance value to expression", function() { let style = new import__440.Cesium3DTileStyle({ disableDepthTestDistance: "2" }); expect(style.disableDepthTestDistance).toEqual(new import__440.Expression("2")); style = new import__440.Cesium3DTileStyle({ disableDepthTestDistance: "${height} / 10" }); expect(style.disableDepthTestDistance).toEqual( new import__440.Expression("${height} / 10") ); style = new import__440.Cesium3DTileStyle({ disableDepthTestDistance: 2 }); expect(style.disableDepthTestDistance).toEqual(new import__440.Expression("2")); }); it("sets disableDepthTestDistance value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "2.0"] ] }; const style = new import__440.Cesium3DTileStyle({ disableDepthTestDistance: jsonExp }); expect(style.disableDepthTestDistance).toEqual( new import__440.ConditionsExpression(jsonExp) ); }); it("sets disableDepthTestDistance expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.disableDepthTestDistance = 2; expect(style.disableDepthTestDistance).toEqual(new import__440.Expression("2")); const exp = new import__440.Expression("2"); style.disableDepthTestDistance = exp; expect(style.disableDepthTestDistance).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "1.0"], ["true", "2.0"] ] }); style.disableDepthTestDistance = condExp; expect(style.disableDepthTestDistance).toEqual(condExp); style.disableDepthTestDistance = void 0; expect(style.disableDepthTestDistance).toBeUndefined(); }); it("sets style.disableDepthTestDistance expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.disableDepthTestDistance = new import__440.Expression("2"); expect(style.style.disableDepthTestDistance).toEqual("2"); const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "2.0"] ] }; style.disableDepthTestDistance = new import__440.ConditionsExpression(jsonExp); expect(style.style.disableDepthTestDistance).toEqual(jsonExp); const customExpression = { evaluate: function() { return 1; } }; style.disableDepthTestDistance = customExpression; expect(style.style.disableDepthTestDistance).toEqual(customExpression); style.disableDepthTestDistance = void 0; expect(style.style.disableDepthTestDistance).toBeUndefined(); }); it("sets disableDepthTestDistance values in setter", function() { const defines = { targetDistance: "2.0" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.disableDepthTestDistance = 2; expect(style.disableDepthTestDistance).toEqual(new import__440.Expression("2")); style.disableDepthTestDistance = "${targetDistance} + 1.0"; expect(style.disableDepthTestDistance).toEqual( new import__440.Expression("${targetDistance} + 1.0", defines) ); const jsonExp = { conditions: [ ["${height} > 2", "1.0"], ["true", "${targetDistance}"] ] }; style.disableDepthTestDistance = jsonExp; expect(style.disableDepthTestDistance).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); }); it("sets horizontalOrigin value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.horizontalOrigin).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.horizontalOrigin).toBeUndefined(); }); it("sets horizontalOrigin value to expression", function() { const style = new import__440.Cesium3DTileStyle({ horizontalOrigin: "1" }); expect(style.horizontalOrigin).toEqual(new import__440.Expression("1")); }); it("sets horizontalOrigin value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "-1"] ] }; const style = new import__440.Cesium3DTileStyle({ horizontalOrigin: jsonExp }); expect(style.horizontalOrigin).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets horizontalOrigin expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.horizontalOrigin = 1; expect(style.horizontalOrigin).toEqual(new import__440.Expression("1")); const exp = new import__440.Expression("1"); style.horizontalOrigin = exp; expect(style.horizontalOrigin).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "1"], ["true", "-1"] ] }); style.horizontalOrigin = condExp; expect(style.horizontalOrigin).toEqual(condExp); style.horizontalOrigin = void 0; expect(style.horizontalOrigin).toBeUndefined(); }); it("sets style.horizontalOrigin expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.horizontalOrigin = new import__440.Expression("1"); expect(style.style.horizontalOrigin).toEqual("1"); const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "-1"] ] }; style.horizontalOrigin = new import__440.ConditionsExpression(jsonExp); expect(style.style.horizontalOrigin).toEqual(jsonExp); const customExpression = { evaluate: function() { return 1; } }; style.horizontalOrigin = customExpression; expect(style.style.horizontalOrigin).toEqual(customExpression); style.horizontalOrigin = void 0; expect(style.style.horizontalOrigin).toBeUndefined(); }); it("sets horizontalOrigin values in setter", function() { const defines = { targetOrigin: "-1" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.horizontalOrigin = -1; expect(style.horizontalOrigin).toEqual(new import__440.Expression("-1")); style.horizontalOrigin = "${targetOrigin}"; expect(style.horizontalOrigin).toEqual( new import__440.Expression("${targetOrigin}", defines) ); const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "${targetOrigin}"] ] }; style.horizontalOrigin = jsonExp; expect(style.horizontalOrigin).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); }); it("sets style.horizontalOrigin values in setter", function() { const defines = { targetOrigin: "-1" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.horizontalOrigin = -1; expect(style.style.horizontalOrigin).toEqual("-1"); style.horizontalOrigin = "${targetOrigin}"; expect(style.style.horizontalOrigin).toEqual("${targetOrigin}"); const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "${targetOrigin}"] ] }; style.horizontalOrigin = jsonExp; expect(style.style.horizontalOrigin).toEqual(jsonExp); }); it("sets verticalOrigin value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.verticalOrigin).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.verticalOrigin).toBeUndefined(); }); it("sets verticalOrigin value to expression", function() { const style = new import__440.Cesium3DTileStyle({ verticalOrigin: "1" }); expect(style.verticalOrigin).toEqual(new import__440.Expression("1")); }); it("sets verticalOrigin value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "-1"] ] }; const style = new import__440.Cesium3DTileStyle({ verticalOrigin: jsonExp }); expect(style.verticalOrigin).toEqual(new import__440.ConditionsExpression(jsonExp)); }); it("sets verticalOrigin expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.verticalOrigin = 1; expect(style.verticalOrigin).toEqual(new import__440.Expression("1")); const exp = new import__440.Expression("1"); style.verticalOrigin = exp; expect(style.verticalOrigin).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "1"], ["true", "-1"] ] }); style.verticalOrigin = condExp; expect(style.verticalOrigin).toEqual(condExp); style.verticalOrigin = void 0; expect(style.verticalOrigin).toBeUndefined(); }); it("sets style.verticalOrigin expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.verticalOrigin = new import__440.Expression("1"); expect(style.style.verticalOrigin).toEqual("1"); const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "-1"] ] }; style.verticalOrigin = new import__440.ConditionsExpression(jsonExp); expect(style.style.verticalOrigin).toEqual(jsonExp); const customExpression = { evaluate: function() { return 1; } }; style.verticalOrigin = customExpression; expect(style.style.verticalOrigin).toEqual(customExpression); style.verticalOrigin = void 0; expect(style.style.verticalOrigin).toBeUndefined(); }); it("sets verticalOrigin values in setter", function() { const defines = { targetOrigin: "-1" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.verticalOrigin = -1; expect(style.verticalOrigin).toEqual(new import__440.Expression("-1")); style.verticalOrigin = "${targetOrigin}"; expect(style.verticalOrigin).toEqual( new import__440.Expression("${targetOrigin}", defines) ); const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "${targetOrigin}"] ] }; style.verticalOrigin = jsonExp; expect(style.verticalOrigin).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); }); it("sets style.verticalOrigin values in setter", function() { const defines = { targetOrigin: "-1" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.verticalOrigin = -1; expect(style.style.verticalOrigin).toEqual("-1"); style.verticalOrigin = "${targetOrigin}"; expect(style.style.verticalOrigin).toEqual("${targetOrigin}"); const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "${targetOrigin}"] ] }; style.verticalOrigin = jsonExp; expect(style.style.verticalOrigin).toEqual(jsonExp); }); it("sets labelHorizontalOrigin value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.labelHorizontalOrigin).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.labelHorizontalOrigin).toBeUndefined(); }); it("sets labelHorizontalOrigin value to expression", function() { const style = new import__440.Cesium3DTileStyle({ labelHorizontalOrigin: "1" }); expect(style.labelHorizontalOrigin).toEqual(new import__440.Expression("1")); }); it("sets labelHorizontalOrigin value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "-1"] ] }; const style = new import__440.Cesium3DTileStyle({ labelHorizontalOrigin: jsonExp }); expect(style.labelHorizontalOrigin).toEqual( new import__440.ConditionsExpression(jsonExp) ); }); it("sets labelHorizontalOrigin expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.labelHorizontalOrigin = 1; expect(style.labelHorizontalOrigin).toEqual(new import__440.Expression("1")); const exp = new import__440.Expression("1"); style.labelHorizontalOrigin = exp; expect(style.labelHorizontalOrigin).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "1"], ["true", "-1"] ] }); style.labelHorizontalOrigin = condExp; expect(style.labelHorizontalOrigin).toEqual(condExp); style.labelHorizontalOrigin = void 0; expect(style.labelHorizontalOrigin).toBeUndefined(); }); it("sets style.labelHorizontalOrigin expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.labelHorizontalOrigin = new import__440.Expression("1"); expect(style.style.labelHorizontalOrigin).toEqual("1"); const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "-1"] ] }; style.labelHorizontalOrigin = new import__440.ConditionsExpression(jsonExp); expect(style.style.labelHorizontalOrigin).toEqual(jsonExp); const customExpression = { evaluate: function() { return 1; } }; style.labelHorizontalOrigin = customExpression; expect(style.style.labelHorizontalOrigin).toEqual(customExpression); style.labelHorizontalOrigin = void 0; expect(style.style.labelHorizontalOrigin).toBeUndefined(); }); it("sets labelHorizontalOrigin values in setter", function() { const defines = { targetOrigin: "-1" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.labelHorizontalOrigin = -1; expect(style.labelHorizontalOrigin).toEqual(new import__440.Expression("-1")); style.labelHorizontalOrigin = "${targetOrigin}"; expect(style.labelHorizontalOrigin).toEqual( new import__440.Expression("${targetOrigin}", defines) ); const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "${targetOrigin}"] ] }; style.labelHorizontalOrigin = jsonExp; expect(style.labelHorizontalOrigin).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); }); it("sets style.labelHorizontalOrigin values in setter", function() { const defines = { targetOrigin: "-1" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.labelHorizontalOrigin = -1; expect(style.style.labelHorizontalOrigin).toEqual("-1"); style.labelHorizontalOrigin = "${targetOrigin}"; expect(style.style.labelHorizontalOrigin).toEqual("${targetOrigin}"); const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "${targetOrigin}"] ] }; style.labelHorizontalOrigin = jsonExp; expect(style.style.labelHorizontalOrigin).toEqual(jsonExp); }); it("sets labelVerticalOrigin value to undefined if value not present", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.labelVerticalOrigin).toBeUndefined(); style = new import__440.Cesium3DTileStyle(); expect(style.labelVerticalOrigin).toBeUndefined(); }); it("sets labelVerticalOrigin value to expression", function() { const style = new import__440.Cesium3DTileStyle({ labelVerticalOrigin: "1" }); expect(style.labelVerticalOrigin).toEqual(new import__440.Expression("1")); }); it("sets labelVerticalOrigin value to conditional", function() { const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "-1"] ] }; const style = new import__440.Cesium3DTileStyle({ labelVerticalOrigin: jsonExp }); expect(style.labelVerticalOrigin).toEqual( new import__440.ConditionsExpression(jsonExp) ); }); it("sets labelVerticalOrigin expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.labelVerticalOrigin = 1; expect(style.labelVerticalOrigin).toEqual(new import__440.Expression("1")); const exp = new import__440.Expression("1"); style.labelVerticalOrigin = exp; expect(style.labelVerticalOrigin).toEqual(exp); const condExp = new import__440.ConditionsExpression({ conditions: [ ["${height} > 2", "1"], ["true", "-1"] ] }); style.labelVerticalOrigin = condExp; expect(style.labelVerticalOrigin).toEqual(condExp); style.labelVerticalOrigin = void 0; expect(style.labelVerticalOrigin).toBeUndefined(); }); it("sets style.labelVerticalOrigin expressions in setter", function() { const style = new import__440.Cesium3DTileStyle(); style.labelVerticalOrigin = new import__440.Expression("1"); expect(style.style.labelVerticalOrigin).toEqual("1"); const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "-1"] ] }; style.labelVerticalOrigin = new import__440.ConditionsExpression(jsonExp); expect(style.style.labelVerticalOrigin).toEqual(jsonExp); const customExpression = { evaluate: function() { return 1; } }; style.labelVerticalOrigin = customExpression; expect(style.style.labelVerticalOrigin).toEqual(customExpression); style.labelVerticalOrigin = void 0; expect(style.style.labelVerticalOrigin).toBeUndefined(); }); it("sets labelVerticalOrigin values in setter", function() { const defines = { targetOrigin: "-1" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.labelVerticalOrigin = -1; expect(style.labelVerticalOrigin).toEqual(new import__440.Expression("-1")); style.labelVerticalOrigin = "${targetOrigin}"; expect(style.labelVerticalOrigin).toEqual( new import__440.Expression("${targetOrigin}", defines) ); const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "${targetOrigin}"] ] }; style.labelVerticalOrigin = jsonExp; expect(style.labelVerticalOrigin).toEqual( new import__440.ConditionsExpression(jsonExp, defines) ); }); it("sets style.labelVerticalOrigin values in setter", function() { const defines = { targetOrigin: "-1" }; const style = new import__440.Cesium3DTileStyle({ defines }); style.labelVerticalOrigin = -1; expect(style.style.labelVerticalOrigin).toEqual("-1"); style.labelVerticalOrigin = "${targetOrigin}"; expect(style.style.labelVerticalOrigin).toEqual("${targetOrigin}"); const jsonExp = { conditions: [ ["${height} > 2", "1"], ["true", "${targetOrigin}"] ] }; style.labelVerticalOrigin = jsonExp; expect(style.style.labelVerticalOrigin).toEqual(jsonExp); }); it("sets meta properties", function() { let style = new import__440.Cesium3DTileStyle({ meta: { description: '"Hello, ${name}"' } }); expect(style.meta.description.evaluate(feature1)).toEqual("Hello, Hello"); style = new import__440.Cesium3DTileStyle({ meta: { featureColor: "rgb(${red}, ${green}, ${blue})", volume: "${Height} * ${Width} * ${Depth}" } }); expect(style.meta.featureColor.evaluateColor(feature1)).toEqual( import__440.Color.fromBytes(38, 255, 82) ); expect(style.meta.volume.evaluate(feature1)).toEqual(20 * 20 * 100); }); it("default meta has no properties", function() { let style = new import__440.Cesium3DTileStyle({}); expect(style.meta).toEqual({}); style = new import__440.Cesium3DTileStyle({ meta: {} }); expect(style.meta).toEqual({}); }); it("applies default style", function() { const style = new import__440.Cesium3DTileStyle({ show: "true", color: "color('#ffffff')", pointSize: "1.0" }); expect(style.show.evaluate(void 0)).toEqual(true); expect(style.color.evaluateColor(void 0)).toEqual(import__440.Color.WHITE); expect(style.pointSize.evaluate(void 0)).toEqual(1); }); it("applies show style with variable", function() { const style = new import__440.Cesium3DTileStyle({ show: "${ZipCode} === '19341'" }); expect(style.show.evaluate(feature1)).toEqual(true); expect(style.show.evaluate(feature2)).toEqual(false); }); it("applies show style with regexp and variables", function() { const style = new import__440.Cesium3DTileStyle({ show: "(regExp('^Chest').test(${County})) && (${YearBuilt} >= 1970)" }); expect(style.show.evaluate(feature1)).toEqual(true); expect(style.show.evaluate(feature2)).toEqual(false); }); it("applies show style with conditional", function() { const style = new import__440.Cesium3DTileStyle({ show: { conditions: [ ["(${Height} >= 100.0)", "false"], ["(${Height} >= 70.0)", "true"], ["(${Height} >= 50.0)", "false"], ["(${Height} >= 30.0)", "true"], ["(${Height} >= 10.0)", "false"], ["(${Height} >= 1.0)", "true"] ] } }); expect(style.show.evaluate(feature1)).toEqual(false); expect(style.show.evaluate(feature2)).toEqual(true); }); it("applies color style variables", function() { const style = new import__440.Cesium3DTileStyle({ color: "(${Temperature} > 90) ? color('red') : color('white')" }); expect(style.color.evaluateColor(feature1)).toEqual(import__440.Color.WHITE); expect(style.color.evaluateColor(feature2)).toEqual(import__440.Color.RED); }); it("applies color style with new color", function() { const style = new import__440.Cesium3DTileStyle({ color: "rgba(${red}, ${green}, ${blue}, (${volume} > 100 ? 0.5 : 1.0))" }); expect(style.color.evaluateColor(feature1)).toEqual( new import__440.Color(38 / 255, 255 / 255, 82 / 255, 0.5) ); expect(style.color.evaluateColor(feature2)).toEqual( new import__440.Color(255 / 255, 30 / 255, 30 / 255, 1) ); }); it("applies color style that maps id to color", function() { const style = new import__440.Cesium3DTileStyle({ defines: { id: "regExp('^1(\\d)').exec(String(${id}))" }, color: { conditions: [ ["${id} === '1'", "color('#FF0000')"], ["${id} === '2'", "color('#00FF00')"], ["true", "color('#FFFFFF')"] ] } }); expect(style.color.evaluateColor(feature1)).toEqual(import__440.Color.RED); expect(style.color.evaluateColor(feature2)).toEqual(import__440.Color.LIME); }); it("applies color style with conditional", function() { const style = new import__440.Cesium3DTileStyle({ color: { conditions: [ ["(${Height} >= 100.0)", "color('#0000FF')"], ["(${Height} >= 70.0)", "color('#00FFFF')"], ["(${Height} >= 50.0)", "color('#00FF00')"], ["(${Height} >= 30.0)", "color('#FFFF00')"], ["(${Height} >= 10.0)", "color('#FF0000')"], ["(${Height} >= 1.0)", "color('#FF00FF')"] ] } }); expect(style.color.evaluateColor(feature1)).toEqual(import__440.Color.BLUE); expect(style.color.evaluateColor(feature2)).toEqual(import__440.Color.YELLOW); }); it("applies pointSize style with variable", function() { const style = new import__440.Cesium3DTileStyle({ pointSize: "${Temperature} / 10.0" }); expect(style.pointSize.evaluate(feature1)).toEqual(7.8); expect(style.pointSize.evaluate(feature2)).toEqual(9.2); }); it("applies pointSize style with regexp and variables", function() { const style = new import__440.Cesium3DTileStyle({ pointSize: "(regExp('^Chest').test(${County})) ? 2.0 : 1.0" }); expect(style.pointSize.evaluate(feature1)).toEqual(2); expect(style.pointSize.evaluate(feature2)).toEqual(1); }); it("applies pointSize style with conditional", function() { const style = new import__440.Cesium3DTileStyle({ pointSize: { conditions: [ ["(${Height} >= 100.0)", "6"], ["(${Height} >= 70.0)", "5"], ["(${Height} >= 50.0)", "4"], ["(${Height} >= 30.0)", "3"], ["(${Height} >= 10.0)", "2"], ["(${Height} >= 1.0)", "1"] ] } }); expect(style.pointSize.evaluate(feature1)).toEqual(6); expect(style.pointSize.evaluate(feature2)).toEqual(3); }); it("applies with defines", function() { const style = new import__440.Cesium3DTileStyle({ defines: { halfHeight: "${Height} / 2", quarterHeight: "${Height} / 4", halfVolume: "${volume} / 2" }, color: { conditions: [ ["(${halfHeight} >= 25.0)", "color('red')"], ["(${Height} >= 1.0)", "color('blue')"] ] }, show: "(${quarterHeight} >= 20.0)", pointSize: "${halfVolume} + ${halfHeight}", meta: { description: "'Half height is ' + ${halfHeight}" } }); expect(style.color.evaluateColor(feature1)).toEqual(import__440.Color.RED); expect(style.color.evaluateColor(feature2)).toEqual(import__440.Color.BLUE); expect(style.show.evaluate(feature1)).toEqual(true); expect(style.show.evaluate(feature2)).toEqual(false); expect(style.pointSize.evaluate(feature1)).toEqual(114); expect(style.pointSize.evaluate(feature2)).toEqual(44); expect(style.meta.description.evaluate(feature1)).toEqual( "Half height is 50" ); expect(style.meta.description.evaluate(feature2)).toEqual( "Half height is 19" ); }); it("return undefined shader functions when the style is empty", function() { const style = new import__440.Cesium3DTileStyle({}); const colorFunction = style.getColorShaderFunction("getColor", {}, {}); const showFunction = style.getShowShaderFunction("getShow", {}, {}); const pointSizeFunction = style.getPointSizeShaderFunction( "getPointSize", {}, {} ); expect(colorFunction).toBeUndefined(); expect(showFunction).toBeUndefined(); expect(pointSizeFunction).toBeUndefined(); }); it("gets variables", function() { const style = new import__440.Cesium3DTileStyle({ pointSize: { conditions: [ ["(${Height} >= 100.0)", "6"], ["true", "${PointSize}"] ] }, color: "${Height} * color('red')", show: "${Floors} > 10" }); const variables = style.getVariables(); expect(variables.sort()).toEqual(["Floors", "Height", "PointSize"]); }); }); // packages/engine/Specs/Scene/Cesium3DTilesVoxelProviderSpec.js var import__441 = __toESM(require_Cesium(), 1); describe("Scene/Cesium3DTilesVoxelProvider", function() { afterEach(function() { import__441.ResourceCache.clearForSpecs(); }); it("conforms to VoxelProvider interface", function() { expect(import__441.Cesium3DTilesVoxelProvider).toConformToInterface(import__441.VoxelProvider); }); it("fromUrl creates a voxel provider", async function() { const url = "./Data/Cesium3DTiles/Voxel/VoxelEllipsoid3DTiles/tileset.json"; const provider = await import__441.Cesium3DTilesVoxelProvider.fromUrl(url); expect(provider).toBeInstanceOf(import__441.Cesium3DTilesVoxelProvider); expect(provider.globalTransform).toEqual(import__441.Matrix4.IDENTITY); expect(provider.shapeTransform).toEqualEpsilon( import__441.Matrix4.fromScale(import__441.Ellipsoid.WGS84.radii), import__441.Math.EPSILON10 ); expect(provider.shape).toEqual(import__441.VoxelShapeType.ELLIPSOID); expect(provider.minBounds).toEqual(new import__441.Cartesian3(0, 0, -1)); expect(provider.maxBounds).toEqual(new import__441.Cartesian3(1, 1, 0)); expect(provider.dimensions).toEqual(new import__441.Cartesian3(2, 2, 2)); expect(provider.paddingBefore).toBeUndefined(); expect(provider.paddingAfter).toBeUndefined(); expect(provider.names).toEqual(["a"]); expect(provider.types).toEqual([import__441.MetadataType.SCALAR]); expect(provider.componentTypes).toEqual([import__441.MetadataComponentType.FLOAT32]); expect(provider.minimumValues).toEqual([[0]]); expect(provider.maximumValues).toEqual([[1]]); }); it("requestData works for root tile", async function() { const url = "./Data/Cesium3DTiles/Voxel/VoxelEllipsoid3DTiles/tileset.json"; const provider = await import__441.Cesium3DTilesVoxelProvider.fromUrl(url); const data = await provider.requestData(); expect(data.length).toEqual(1); const dimensions = provider.dimensions; const voxelCount = dimensions.x * dimensions.y * dimensions.z; const componentCount = import__441.MetadataType.getComponentCount(provider.types[0]); const expectedLength = voxelCount * componentCount; expect(data[0].length).toEqual(expectedLength); }); it("requestData loads multiple attributes correctly", async function() { const url = "./Data/Cesium3DTiles/Voxel/VoxelMultiAttribute3DTiles/tileset.json"; const provider = await import__441.Cesium3DTilesVoxelProvider.fromUrl(url); const data = await provider.requestData(); expect(data.length).toBe(3); expect(data[0][0]).toBe(0); expect(data[1][0]).toBe(0.5); expect(data[2][0]).toBe(1); }); }); // packages/engine/Specs/Scene/Cesium3DTilesetBaseTraversalSpec.js var import__442 = __toESM(require_Cesium(), 1); describe("Scene/Cesium3DTilesetBaseTraversal", function() { it("conforms to Cesium3DTilesetTraversal interface", function() { expect(import__442.Cesium3DTilesetBaseTraversal).toConformToInterface( import__442.Cesium3DTilesetTraversal ); }); }); // packages/engine/Specs/Scene/Cesium3DTilesetHeatmapSpec.js var import__443 = __toESM(require_Cesium(), 1); describe("Scene/Cesium3DTilesetHeatmap", function() { const tileWithBoundingSphere = { geometricError: 1, refine: "REPLACE", children: [], boundingVolume: { sphere: [0, 0, 0, 5] } }; const mockTileset = { debugShowBoundingVolume: true, debugShowViewerRequestVolume: true, modelMatrix: import__443.Matrix4.IDENTITY, _geometricError: 2 }; let scene2; beforeEach(function() { scene2 = createScene_default(); scene2.frameState.passes.render = true; }); afterEach(function() { scene2.destroyForSpecs(); }); function verifyColor(tileColor, expectedColor) { const diff = new import__443.Color( Math.abs(expectedColor.red - tileColor.red), Math.abs(expectedColor.green - tileColor.green), Math.abs(expectedColor.blue - tileColor.blue) ); const threshold = 0.11; expect(diff.red).toBeLessThan(threshold); expect(diff.green).toBeLessThan(threshold); expect(diff.blue).toBeLessThan(threshold); } it("resetMinimumMaximum", function() { const heatmap = new import__443.Cesium3DTilesetHeatmap("_centerZDepth"); heatmap._minimum = -1; heatmap._maximum = 1; heatmap.resetMinimumMaximum(); expect(heatmap._minimum).toBe(Number.MAX_VALUE); expect(heatmap._maximum).toBe(-Number.MAX_VALUE); expect(heatmap._previousMinimum).toBe(-1); expect(heatmap._previousMaximum).toBe(1); }); it("uses reference minimum maximum", function() { const tilePropertyName = "_loadTimestamp"; const heatmap = new import__443.Cesium3DTilesetHeatmap(tilePropertyName); const referenceMinimumJulianDate = new import__443.JulianDate(); const referenceMaximumJulianDate = new import__443.JulianDate(); import__443.JulianDate.now(referenceMinimumJulianDate); import__443.JulianDate.addSeconds( referenceMinimumJulianDate, 10, referenceMaximumJulianDate ); heatmap.setReferenceMinimumMaximum( referenceMinimumJulianDate, referenceMaximumJulianDate, tilePropertyName ); const referenceMinimum = heatmap._referenceMinimum[tilePropertyName]; const referenceMaximum = heatmap._referenceMaximum[tilePropertyName]; heatmap._minimum = -1; heatmap._maximum = 1; heatmap.resetMinimumMaximum(); expect(heatmap._minimum).toBe(Number.MAX_VALUE); expect(heatmap._maximum).toBe(-Number.MAX_VALUE); expect(heatmap._previousMinimum).toBe(referenceMinimum); expect(heatmap._previousMaximum).toBe(referenceMaximum); }); it("expected color", function() { const heatmap = new import__443.Cesium3DTilesetHeatmap("_centerZDepth"); const tile = new import__443.Cesium3DTile( mockTileset, "/some_url", tileWithBoundingSphere, void 0 ); tile._contentState = import__443.Cesium3DTileContentState.READY; tile.hasEmptyContent = false; const frameState2 = scene2.frameState; tile._selectedFrame = frameState2.frameNumber; const originalColor = tile._debugColor; tile._centerZDepth = 1; heatmap.colorize(tile, frameState2); tile._centerZDepth = -1; heatmap.colorize(tile, frameState2); expect(heatmap._minimum).toBe(-1); expect(heatmap._maximum).toBe(1); verifyColor(tile._debugColor, originalColor); heatmap.resetMinimumMaximum(); tile._centerZDepth = -1; heatmap.colorize(tile, frameState2); const expectedColor = import__443.Color.BLACK; verifyColor(tile._debugColor, expectedColor); }); }); // packages/engine/Specs/Scene/Cesium3DTilesetMetadataSpec.js var import__444 = __toESM(require_Cesium(), 1); describe("Scene/Cesium3DTilesetMetadata", function() { const schemaJson = { classes: { city: { properties: { name: { type: "STRING" } } }, neighborhood: { properties: { color: { type: "STRING" } } }, tree: { properties: { species: { type: "STRING" } } } } }; it("creates 3D Tiles metadata with default values", function() { const schema = import__444.MetadataSchema.fromJson(schemaJson); const metadata = new import__444.Cesium3DTilesetMetadata({ metadataJson: {}, schema }); expect(metadata.schema).toBe(schema); expect(metadata.groups).toEqual([]); expect(metadata.groupIds).toEqual([]); expect(metadata.tileset).toBeUndefined(); expect(metadata.statistics).toBeUndefined(); expect(metadata.extras).toBeUndefined(); expect(metadata.extensions).toBeUndefined(); }); it("creates 3D Tiles metadata", function() { const statistics = { classes: { tree: { count: 100, properties: { height: { min: 10, max: 20 } } } } }; const extras = { description: "Extra" }; const extensions = { EXT_other_extension: {} }; const tilesetJson = { schema: schemaJson, groups: [ { class: "neighborhood", properties: { color: "RED" } }, { class: "neighborhood", properties: { color: "GREEN" } } ], metadata: { class: "city", properties: { name: "City" } }, statistics, extras, extensions }; const schema = import__444.MetadataSchema.fromJson(schemaJson); const metadata = new import__444.Cesium3DTilesetMetadata({ metadataJson: tilesetJson, schema }); const cityClass = metadata.schema.classes.city; const neighborhoodClass = metadata.schema.classes.neighborhood; const treeClass = metadata.schema.classes.tree; expect(cityClass.id).toBe("city"); expect(neighborhoodClass.id).toBe("neighborhood"); expect(treeClass.id).toBe("tree"); const tilesetMetadata = metadata.tileset; expect(tilesetMetadata.class).toBe(cityClass); expect(tilesetMetadata.getProperty("name")).toBe("City"); const neighborhoodA = metadata.groups[0]; const neighborhoodB = metadata.groups[1]; expect(neighborhoodA.class).toBe(neighborhoodClass); expect(neighborhoodA.getProperty("color")).toBe("RED"); expect(neighborhoodB.class).toBe(neighborhoodClass); expect(neighborhoodB.getProperty("color")).toBe("GREEN"); expect(metadata.statistics).toBe(statistics); expect(metadata.extras).toBe(extras); expect(metadata.extensions).toBe(extensions); }); it("creates 3D Tiles metadata (legacy)", function() { const statistics = { classes: { tree: { count: 100, properties: { height: { min: 10, max: 20 } } } } }; const extras = { description: "Extra" }; const extensions = { EXT_other_extension: {} }; const extension = { schema: schemaJson, groups: { neighborhoodA: { class: "neighborhood", properties: { color: "RED" } }, neighborhoodB: { class: "neighborhood", properties: { color: "GREEN" } } }, tileset: { class: "city", properties: { name: "City" } }, statistics, extras, extensions }; const schema = import__444.MetadataSchema.fromJson(schemaJson); const metadata = new import__444.Cesium3DTilesetMetadata({ metadataJson: extension, schema }); const cityClass = metadata.schema.classes.city; const neighborhoodClass = metadata.schema.classes.neighborhood; const treeClass = metadata.schema.classes.tree; expect(cityClass.id).toBe("city"); expect(neighborhoodClass.id).toBe("neighborhood"); expect(treeClass.id).toBe("tree"); const tilesetMetadata = metadata.tileset; expect(tilesetMetadata.class).toBe(cityClass); expect(tilesetMetadata.getProperty("name")).toBe("City"); const neighborhoodA = metadata.groups[0]; const neighborhoodB = metadata.groups[1]; expect(neighborhoodA.id).toBe("neighborhoodA"); expect(neighborhoodA.class).toBe(neighborhoodClass); expect(neighborhoodA.getProperty("color")).toBe("RED"); expect(neighborhoodB.id).toBe("neighborhoodB"); expect(neighborhoodB.class).toBe(neighborhoodClass); expect(neighborhoodB.getProperty("color")).toBe("GREEN"); expect(metadata.statistics).toBe(statistics); expect(metadata.extras).toBe(extras); expect(metadata.extensions).toBe(extensions); }); it("constructor throws without metadataJson", function() { const schema = import__444.MetadataSchema.fromJson(schemaJson); expect(function() { return new import__444.Cesium3DTilesetMetadata({ schema }); }).toThrowDeveloperError(); }); it("constructor throws without schema", function() { expect(function() { return new import__444.Cesium3DTilesetMetadata({ metadataJson: {} }); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/Cesium3DTilesetMostDetailedTraversalSpec.js var import__445 = __toESM(require_Cesium(), 1); describe("Scene/Cesium3DTilesetMostDetailedTraversal", function() { it("conforms to Cesium3DTilesetTraversal interface", function() { expect(import__445.Cesium3DTilesetMostDetailedTraversal).toConformToInterface( import__445.Cesium3DTilesetTraversal ); }); }); // packages/engine/Specs/Scene/Cesium3DTilesetSkipTraversalSpec.js var import__446 = __toESM(require_Cesium(), 1); describe("Scene/Cesium3DTilesetSkipTraversal", function() { it("conforms to Cesium3DTilesetTraversal interface", function() { expect(import__446.Cesium3DTilesetSkipTraversal).toConformToInterface( import__446.Cesium3DTilesetTraversal ); }); }); // packages/engine/Specs/Scene/Cesium3DTilesetSpec.js var import__447 = __toESM(require_Cesium(), 1); // Specs/generateJsonBuffer.js var import_engine20 = __toESM(require_Cesium(), 1); function generateJsonBuffer(json, byteOffset, boundary) { let i; const jsonString = JSON.stringify(json); byteOffset = (0, import_engine20.defaultValue)(byteOffset, 0); boundary = (0, import_engine20.defaultValue)(boundary, 1); const byteLength = jsonString.length; const remainder = (byteOffset + byteLength) % boundary; const padding = remainder === 0 ? 0 : boundary - remainder; const buffer = new Uint8Array(byteLength + padding); for (i = 0; i < byteLength; ++i) { buffer[i] = jsonString.charCodeAt(i); } for (i = 0; i < padding; ++i) { buffer[byteLength + i] = 32; } return buffer; } var generateJsonBuffer_default = generateJsonBuffer; // packages/engine/Source/Core/Cartesian2.js function Cartesian258(x, y) { this.x = defaultValue_default(x, 0); this.y = defaultValue_default(y, 0); } Cartesian258.fromElements = function(x, y, result) { if (!defined_default(result)) { return new Cartesian258(x, y); } result.x = x; result.y = y; return result; }; Cartesian258.clone = function(cartesian, result) { if (!defined_default(cartesian)) { return void 0; } if (!defined_default(result)) { return new Cartesian258(cartesian.x, cartesian.y); } result.x = cartesian.x; result.y = cartesian.y; return result; }; Cartesian258.fromCartesian3 = Cartesian258.clone; Cartesian258.fromCartesian4 = Cartesian258.clone; Cartesian258.packedLength = 2; Cartesian258.pack = function(value, array, startingIndex) { Check_default.typeOf.object("value", value); Check_default.defined("array", array); startingIndex = defaultValue_default(startingIndex, 0); array[startingIndex++] = value.x; array[startingIndex] = value.y; return array; }; Cartesian258.unpack = function(array, startingIndex, result) { Check_default.defined("array", array); startingIndex = defaultValue_default(startingIndex, 0); if (!defined_default(result)) { result = new Cartesian258(); } result.x = array[startingIndex++]; result.y = array[startingIndex]; return result; }; Cartesian258.packArray = function(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) { Cartesian258.pack(array[i], result, i * 2); } return result; }; Cartesian258.unpackArray = function(array, result) { Check_default.defined("array", array); Check_default.typeOf.number.greaterThanOrEquals("array.length", array.length, 2); if (array.length % 2 !== 0) { throw new DeveloperError_default("array length must be a multiple of 2."); } const 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] = Cartesian258.unpack(array, i, result[index]); } return result; }; Cartesian258.fromArray = Cartesian258.unpack; Cartesian258.maximumComponent = function(cartesian) { Check_default.typeOf.object("cartesian", cartesian); return Math.max(cartesian.x, cartesian.y); }; Cartesian258.minimumComponent = function(cartesian) { Check_default.typeOf.object("cartesian", cartesian); return Math.min(cartesian.x, cartesian.y); }; Cartesian258.minimumByComponent = function(first, second, result) { Check_default.typeOf.object("first", first); Check_default.typeOf.object("second", second); Check_default.typeOf.object("result", result); result.x = Math.min(first.x, second.x); result.y = Math.min(first.y, second.y); return result; }; Cartesian258.maximumByComponent = function(first, second, result) { Check_default.typeOf.object("first", first); Check_default.typeOf.object("second", second); Check_default.typeOf.object("result", result); result.x = Math.max(first.x, second.x); result.y = Math.max(first.y, second.y); return result; }; Cartesian258.clamp = function(value, min, max, result) { Check_default.typeOf.object("value", value); Check_default.typeOf.object("min", min); Check_default.typeOf.object("max", max); Check_default.typeOf.object("result", result); const x = Math_default.clamp(value.x, min.x, max.x); const y = Math_default.clamp(value.y, min.y, max.y); result.x = x; result.y = y; return result; }; Cartesian258.magnitudeSquared = function(cartesian) { Check_default.typeOf.object("cartesian", cartesian); return cartesian.x * cartesian.x + cartesian.y * cartesian.y; }; Cartesian258.magnitude = function(cartesian) { return Math.sqrt(Cartesian258.magnitudeSquared(cartesian)); }; var distanceScratch = new Cartesian258(); Cartesian258.distance = function(left, right) { Check_default.typeOf.object("left", left); Check_default.typeOf.object("right", right); Cartesian258.subtract(left, right, distanceScratch); return Cartesian258.magnitude(distanceScratch); }; Cartesian258.distanceSquared = function(left, right) { Check_default.typeOf.object("left", left); Check_default.typeOf.object("right", right); Cartesian258.subtract(left, right, distanceScratch); return Cartesian258.magnitudeSquared(distanceScratch); }; Cartesian258.normalize = function(cartesian, result) { Check_default.typeOf.object("cartesian", cartesian); Check_default.typeOf.object("result", result); const magnitude = Cartesian258.magnitude(cartesian); result.x = cartesian.x / magnitude; result.y = cartesian.y / magnitude; if (isNaN(result.x) || isNaN(result.y)) { throw new DeveloperError_default("normalized result is not a number"); } return result; }; Cartesian258.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; }; Cartesian258.cross = function(left, right) { Check_default.typeOf.object("left", left); Check_default.typeOf.object("right", right); return left.x * right.y - left.y * right.x; }; Cartesian258.multiplyComponents = function(left, right, result) { Check_default.typeOf.object("left", left); Check_default.typeOf.object("right", right); Check_default.typeOf.object("result", result); result.x = left.x * right.x; result.y = left.y * right.y; return result; }; Cartesian258.divideComponents = function(left, right, result) { Check_default.typeOf.object("left", left); Check_default.typeOf.object("right", right); Check_default.typeOf.object("result", result); result.x = left.x / right.x; result.y = left.y / right.y; return result; }; Cartesian258.add = function(left, right, result) { Check_default.typeOf.object("left", left); Check_default.typeOf.object("right", right); Check_default.typeOf.object("result", result); result.x = left.x + right.x; result.y = left.y + right.y; return result; }; Cartesian258.subtract = function(left, right, result) { Check_default.typeOf.object("left", left); Check_default.typeOf.object("right", right); Check_default.typeOf.object("result", result); result.x = left.x - right.x; result.y = left.y - right.y; return result; }; Cartesian258.multiplyByScalar = function(cartesian, scalar, result) { Check_default.typeOf.object("cartesian", cartesian); Check_default.typeOf.number("scalar", scalar); Check_default.typeOf.object("result", result); result.x = cartesian.x * scalar; result.y = cartesian.y * scalar; return result; }; Cartesian258.divideByScalar = function(cartesian, scalar, result) { Check_default.typeOf.object("cartesian", cartesian); Check_default.typeOf.number("scalar", scalar); Check_default.typeOf.object("result", result); result.x = cartesian.x / scalar; result.y = cartesian.y / scalar; return result; }; Cartesian258.negate = function(cartesian, result) { Check_default.typeOf.object("cartesian", cartesian); Check_default.typeOf.object("result", result); result.x = -cartesian.x; result.y = -cartesian.y; return result; }; Cartesian258.abs = function(cartesian, result) { Check_default.typeOf.object("cartesian", cartesian); Check_default.typeOf.object("result", result); result.x = Math.abs(cartesian.x); result.y = Math.abs(cartesian.y); return result; }; var lerpScratch = new Cartesian258(); Cartesian258.lerp = function(start, end, t, result) { Check_default.typeOf.object("start", start); Check_default.typeOf.object("end", end); Check_default.typeOf.number("t", t); Check_default.typeOf.object("result", result); Cartesian258.multiplyByScalar(end, t, lerpScratch); result = Cartesian258.multiplyByScalar(start, 1 - t, result); return Cartesian258.add(lerpScratch, result, result); }; var angleBetweenScratch = new Cartesian258(); var angleBetweenScratch2 = new Cartesian258(); Cartesian258.angleBetween = function(left, right) { Check_default.typeOf.object("left", left); Check_default.typeOf.object("right", right); Cartesian258.normalize(left, angleBetweenScratch); Cartesian258.normalize(right, angleBetweenScratch2); return Math_default.acosClamped( Cartesian258.dot(angleBetweenScratch, angleBetweenScratch2) ); }; var mostOrthogonalAxisScratch = new Cartesian258(); Cartesian258.mostOrthogonalAxis = function(cartesian, result) { Check_default.typeOf.object("cartesian", cartesian); Check_default.typeOf.object("result", result); const f = Cartesian258.normalize(cartesian, mostOrthogonalAxisScratch); Cartesian258.abs(f, f); if (f.x <= f.y) { result = Cartesian258.clone(Cartesian258.UNIT_X, result); } else { result = Cartesian258.clone(Cartesian258.UNIT_Y, result); } return result; }; Cartesian258.equals = function(left, right) { return left === right || defined_default(left) && defined_default(right) && left.x === right.x && left.y === right.y; }; Cartesian258.equalsArray = function(cartesian, array, offset) { return cartesian.x === array[offset] && cartesian.y === array[offset + 1]; }; Cartesian258.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) { return left === right || defined_default(left) && defined_default(right) && Math_default.equalsEpsilon( left.x, right.x, relativeEpsilon, absoluteEpsilon ) && Math_default.equalsEpsilon( left.y, right.y, relativeEpsilon, absoluteEpsilon ); }; Cartesian258.ZERO = Object.freeze(new Cartesian258(0, 0)); Cartesian258.ONE = Object.freeze(new Cartesian258(1, 1)); Cartesian258.UNIT_X = Object.freeze(new Cartesian258(1, 0)); Cartesian258.UNIT_Y = Object.freeze(new Cartesian258(0, 1)); Cartesian258.prototype.clone = function(result) { return Cartesian258.clone(this, result); }; Cartesian258.prototype.equals = function(right) { return Cartesian258.equals(this, right); }; Cartesian258.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) { return Cartesian258.equalsEpsilon( this, right, relativeEpsilon, absoluteEpsilon ); }; Cartesian258.prototype.toString = function() { return `(${this.x}, ${this.y})`; }; var Cartesian2_default = Cartesian258; // packages/engine/Source/Core/Cartesian3.js function Cartesian3157(x, y, z) { this.x = defaultValue_default(x, 0); this.y = defaultValue_default(y, 0); this.z = defaultValue_default(z, 0); } Cartesian3157.fromSpherical = function(spherical, result) { Check_default.typeOf.object("spherical", spherical); if (!defined_default(result)) { result = new Cartesian3157(); } const clock = spherical.clock; const cone = spherical.cone; const magnitude = defaultValue_default(spherical.magnitude, 1); const radial = magnitude * Math.sin(cone); result.x = radial * Math.cos(clock); result.y = radial * Math.sin(clock); result.z = magnitude * Math.cos(cone); return result; }; Cartesian3157.fromElements = function(x, y, z, result) { if (!defined_default(result)) { return new Cartesian3157(x, y, z); } result.x = x; result.y = y; result.z = z; return result; }; Cartesian3157.clone = function(cartesian, result) { if (!defined_default(cartesian)) { return void 0; } if (!defined_default(result)) { return new Cartesian3157(cartesian.x, cartesian.y, cartesian.z); } result.x = cartesian.x; result.y = cartesian.y; result.z = cartesian.z; return result; }; Cartesian3157.fromCartesian4 = Cartesian3157.clone; Cartesian3157.packedLength = 3; Cartesian3157.pack = function(value, array, startingIndex) { Check_default.typeOf.object("value", value); Check_default.defined("array", array); startingIndex = defaultValue_default(startingIndex, 0); array[startingIndex++] = value.x; array[startingIndex++] = value.y; array[startingIndex] = value.z; return array; }; Cartesian3157.unpack = function(array, startingIndex, result) { Check_default.defined("array", array); startingIndex = defaultValue_default(startingIndex, 0); if (!defined_default(result)) { result = new Cartesian3157(); } result.x = array[startingIndex++]; result.y = array[startingIndex++]; result.z = array[startingIndex]; return result; }; Cartesian3157.packArray = function(array, result) { Check_default.defined("array", array); const length2 = array.length; const resultLength = length2 * 3; 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 * 3 elements" ); } else if (result.length !== resultLength) { result.length = resultLength; } for (let i = 0; i < length2; ++i) { Cartesian3157.pack(array[i], result, i * 3); } return result; }; Cartesian3157.unpackArray = function(array, result) { Check_default.defined("array", array); Check_default.typeOf.number.greaterThanOrEquals("array.length", array.length, 3); if (array.length % 3 !== 0) { throw new DeveloperError_default("array length must be a multiple of 3."); } const length2 = array.length; if (!defined_default(result)) { result = new Array(length2 / 3); } else { result.length = length2 / 3; } for (let i = 0; i < length2; i += 3) { const index = i / 3; result[index] = Cartesian3157.unpack(array, i, result[index]); } return result; }; Cartesian3157.fromArray = Cartesian3157.unpack; Cartesian3157.maximumComponent = function(cartesian) { Check_default.typeOf.object("cartesian", cartesian); return Math.max(cartesian.x, cartesian.y, cartesian.z); }; Cartesian3157.minimumComponent = function(cartesian) { Check_default.typeOf.object("cartesian", cartesian); return Math.min(cartesian.x, cartesian.y, cartesian.z); }; Cartesian3157.minimumByComponent = function(first, second, result) { Check_default.typeOf.object("first", first); Check_default.typeOf.object("second", second); Check_default.typeOf.object("result", result); result.x = Math.min(first.x, second.x); result.y = Math.min(first.y, second.y); result.z = Math.min(first.z, second.z); return result; }; Cartesian3157.maximumByComponent = function(first, second, result) { Check_default.typeOf.object("first", first); Check_default.typeOf.object("second", second); Check_default.typeOf.object("result", result); result.x = Math.max(first.x, second.x); result.y = Math.max(first.y, second.y); result.z = Math.max(first.z, second.z); return result; }; Cartesian3157.clamp = function(value, min, max, result) { Check_default.typeOf.object("value", value); Check_default.typeOf.object("min", min); Check_default.typeOf.object("max", max); Check_default.typeOf.object("result", result); const x = Math_default.clamp(value.x, min.x, max.x); const y = Math_default.clamp(value.y, min.y, max.y); const z = Math_default.clamp(value.z, min.z, max.z); result.x = x; result.y = y; result.z = z; return result; }; Cartesian3157.magnitudeSquared = function(cartesian) { Check_default.typeOf.object("cartesian", cartesian); return cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z; }; Cartesian3157.magnitude = function(cartesian) { return Math.sqrt(Cartesian3157.magnitudeSquared(cartesian)); }; var distanceScratch2 = new Cartesian3157(); Cartesian3157.distance = function(left, right) { Check_default.typeOf.object("left", left); Check_default.typeOf.object("right", right); Cartesian3157.subtract(left, right, distanceScratch2); return Cartesian3157.magnitude(distanceScratch2); }; Cartesian3157.distanceSquared = function(left, right) { Check_default.typeOf.object("left", left); Check_default.typeOf.object("right", right); Cartesian3157.subtract(left, right, distanceScratch2); return Cartesian3157.magnitudeSquared(distanceScratch2); }; Cartesian3157.normalize = function(cartesian, result) { Check_default.typeOf.object("cartesian", cartesian); Check_default.typeOf.object("result", result); const magnitude = Cartesian3157.magnitude(cartesian); result.x = cartesian.x / magnitude; result.y = cartesian.y / magnitude; result.z = cartesian.z / magnitude; if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z)) { throw new DeveloperError_default("normalized result is not a number"); } return result; }; Cartesian3157.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; }; Cartesian3157.multiplyComponents = function(left, right, result) { Check_default.typeOf.object("left", left); Check_default.typeOf.object("right", right); Check_default.typeOf.object("result", result); result.x = left.x * right.x; result.y = left.y * right.y; result.z = left.z * right.z; return result; }; Cartesian3157.divideComponents = function(left, right, result) { Check_default.typeOf.object("left", left); Check_default.typeOf.object("right", right); Check_default.typeOf.object("result", result); result.x = left.x / right.x; result.y = left.y / right.y; result.z = left.z / right.z; return result; }; Cartesian3157.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; return result; }; Cartesian3157.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; return result; }; Cartesian3157.multiplyByScalar = function(cartesian, scalar, result) { Check_default.typeOf.object("cartesian", cartesian); Check_default.typeOf.number("scalar", scalar); Check_default.typeOf.object("result", result); result.x = cartesian.x * scalar; result.y = cartesian.y * scalar; result.z = cartesian.z * scalar; return result; }; Cartesian3157.divideByScalar = function(cartesian, scalar, result) { Check_default.typeOf.object("cartesian", cartesian); Check_default.typeOf.number("scalar", scalar); Check_default.typeOf.object("result", result); result.x = cartesian.x / scalar; result.y = cartesian.y / scalar; result.z = cartesian.z / scalar; return result; }; Cartesian3157.negate = function(cartesian, result) { Check_default.typeOf.object("cartesian", cartesian); Check_default.typeOf.object("result", result); result.x = -cartesian.x; result.y = -cartesian.y; result.z = -cartesian.z; return result; }; Cartesian3157.abs = function(cartesian, result) { Check_default.typeOf.object("cartesian", cartesian); Check_default.typeOf.object("result", result); result.x = Math.abs(cartesian.x); result.y = Math.abs(cartesian.y); result.z = Math.abs(cartesian.z); return result; }; var lerpScratch2 = new Cartesian3157(); Cartesian3157.lerp = function(start, end, t, result) { Check_default.typeOf.object("start", start); Check_default.typeOf.object("end", end); Check_default.typeOf.number("t", t); Check_default.typeOf.object("result", result); Cartesian3157.multiplyByScalar(end, t, lerpScratch2); result = Cartesian3157.multiplyByScalar(start, 1 - t, result); return Cartesian3157.add(lerpScratch2, result, result); }; var angleBetweenScratch3 = new Cartesian3157(); var angleBetweenScratch22 = new Cartesian3157(); Cartesian3157.angleBetween = function(left, right) { Check_default.typeOf.object("left", left); Check_default.typeOf.object("right", right); Cartesian3157.normalize(left, angleBetweenScratch3); Cartesian3157.normalize(right, angleBetweenScratch22); const cosine = Cartesian3157.dot(angleBetweenScratch3, angleBetweenScratch22); const sine = Cartesian3157.magnitude( Cartesian3157.cross( angleBetweenScratch3, angleBetweenScratch22, angleBetweenScratch3 ) ); return Math.atan2(sine, cosine); }; var mostOrthogonalAxisScratch2 = new Cartesian3157(); Cartesian3157.mostOrthogonalAxis = function(cartesian, result) { Check_default.typeOf.object("cartesian", cartesian); Check_default.typeOf.object("result", result); const f = Cartesian3157.normalize(cartesian, mostOrthogonalAxisScratch2); Cartesian3157.abs(f, f); if (f.x <= f.y) { if (f.x <= f.z) { result = Cartesian3157.clone(Cartesian3157.UNIT_X, result); } else { result = Cartesian3157.clone(Cartesian3157.UNIT_Z, result); } } else if (f.y <= f.z) { result = Cartesian3157.clone(Cartesian3157.UNIT_Y, result); } else { result = Cartesian3157.clone(Cartesian3157.UNIT_Z, result); } return result; }; Cartesian3157.projectVector = function(a, b, result) { Check_default.defined("a", a); Check_default.defined("b", b); Check_default.defined("result", result); const scalar = Cartesian3157.dot(a, b) / Cartesian3157.dot(b, b); return Cartesian3157.multiplyByScalar(b, scalar, result); }; Cartesian3157.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; }; Cartesian3157.equalsArray = function(cartesian, array, offset) { return cartesian.x === array[offset] && cartesian.y === array[offset + 1] && cartesian.z === array[offset + 2]; }; Cartesian3157.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) { return left === right || defined_default(left) && defined_default(right) && Math_default.equalsEpsilon( left.x, right.x, relativeEpsilon, absoluteEpsilon ) && Math_default.equalsEpsilon( left.y, right.y, relativeEpsilon, absoluteEpsilon ) && Math_default.equalsEpsilon( left.z, right.z, relativeEpsilon, absoluteEpsilon ); }; Cartesian3157.cross = 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 rightX = right.x; const rightY = right.y; const rightZ = right.z; const x = leftY * rightZ - leftZ * rightY; const y = leftZ * rightX - leftX * rightZ; const z = leftX * rightY - leftY * rightX; result.x = x; result.y = y; result.z = z; return result; }; Cartesian3157.midpoint = 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) * 0.5; result.y = (left.y + right.y) * 0.5; result.z = (left.z + right.z) * 0.5; return result; }; Cartesian3157.fromDegrees = function(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 Cartesian3157.fromRadians(longitude, latitude, height, ellipsoid, result); }; var scratchN = new Cartesian3157(); var scratchK = new Cartesian3157(); var wgs84RadiiSquared = new Cartesian3157( 6378137 * 6378137, 6378137 * 6378137, 6356752314245179e-9 * 6356752314245179e-9 ); Cartesian3157.fromRadians = function(longitude, latitude, height, ellipsoid, result) { Check_default.typeOf.number("longitude", longitude); Check_default.typeOf.number("latitude", latitude); height = defaultValue_default(height, 0); const radiiSquared = defined_default(ellipsoid) ? ellipsoid.radiiSquared : wgs84RadiiSquared; const cosLatitude = Math.cos(latitude); scratchN.x = cosLatitude * Math.cos(longitude); scratchN.y = cosLatitude * Math.sin(longitude); scratchN.z = Math.sin(latitude); scratchN = Cartesian3157.normalize(scratchN, scratchN); Cartesian3157.multiplyComponents(radiiSquared, scratchN, scratchK); const gamma = Math.sqrt(Cartesian3157.dot(scratchN, scratchK)); scratchK = Cartesian3157.divideByScalar(scratchK, gamma, scratchK); scratchN = Cartesian3157.multiplyByScalar(scratchN, height, scratchN); if (!defined_default(result)) { result = new Cartesian3157(); } return Cartesian3157.add(scratchK, scratchN, result); }; Cartesian3157.fromDegreesArray = function(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] = Cartesian3157.fromDegrees( longitude, latitude, 0, ellipsoid, result[index] ); } return result; }; Cartesian3157.fromRadiansArray = function(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] = Cartesian3157.fromRadians( longitude, latitude, 0, ellipsoid, result[index] ); } return result; }; Cartesian3157.fromDegreesArrayHeights = function(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] = Cartesian3157.fromDegrees( longitude, latitude, height, ellipsoid, result[index] ); } return result; }; Cartesian3157.fromRadiansArrayHeights = function(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] = Cartesian3157.fromRadians( longitude, latitude, height, ellipsoid, result[index] ); } return result; }; Cartesian3157.ZERO = Object.freeze(new Cartesian3157(0, 0, 0)); Cartesian3157.ONE = Object.freeze(new Cartesian3157(1, 1, 1)); Cartesian3157.UNIT_X = Object.freeze(new Cartesian3157(1, 0, 0)); Cartesian3157.UNIT_Y = Object.freeze(new Cartesian3157(0, 1, 0)); Cartesian3157.UNIT_Z = Object.freeze(new Cartesian3157(0, 0, 1)); Cartesian3157.prototype.clone = function(result) { return Cartesian3157.clone(this, result); }; Cartesian3157.prototype.equals = function(right) { return Cartesian3157.equals(this, right); }; Cartesian3157.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) { return Cartesian3157.equalsEpsilon( this, right, relativeEpsilon, absoluteEpsilon ); }; Cartesian3157.prototype.toString = function() { return `(${this.x}, ${this.y}, ${this.z})`; }; var Cartesian3_default = Cartesian3157; // packages/engine/Source/Core/scaleToGeodeticSurface.js var scaleToGeodeticSurfaceIntersection = new Cartesian3_default(); var scaleToGeodeticSurfaceGradient = new Cartesian3_default(); function scaleToGeodeticSurface(cartesian, oneOverRadii, oneOverRadiiSquared, centerToleranceSquared, result) { if (!defined_default(cartesian)) { 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 = cartesian.x; const positionY = cartesian.y; const positionZ = cartesian.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( cartesian, 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(cartesian) / (0.5 * Cartesian3_default.magnitude(gradient)); let correction = 0; let func; let denominator; let xMultiplier; let yMultiplier; let zMultiplier; let xMultiplier2; let yMultiplier2; let zMultiplier2; let xMultiplier3; let yMultiplier3; let zMultiplier3; do { lambda -= correction; xMultiplier = 1 / (1 + lambda * oneOverRadiiSquaredX); yMultiplier = 1 / (1 + lambda * oneOverRadiiSquaredY); zMultiplier = 1 / (1 + lambda * oneOverRadiiSquaredZ); xMultiplier2 = xMultiplier * xMultiplier; yMultiplier2 = yMultiplier * yMultiplier; zMultiplier2 = zMultiplier * zMultiplier; xMultiplier3 = xMultiplier2 * xMultiplier; yMultiplier3 = yMultiplier2 * yMultiplier; zMultiplier3 = zMultiplier2 * zMultiplier; func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1; denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ; const derivative = -2 * denominator; correction = func / derivative; } while (Math.abs(func) > Math_default.EPSILON12); if (!defined_default(result)) { return new Cartesian3_default( positionX * xMultiplier, positionY * yMultiplier, positionZ * zMultiplier ); } result.x = positionX * xMultiplier; result.y = positionY * yMultiplier; result.z = positionZ * zMultiplier; return result; } var scaleToGeodeticSurface_default = scaleToGeodeticSurface; // packages/engine/Source/Core/Cartographic.js function Cartographic25(longitude, latitude, height) { this.longitude = defaultValue_default(longitude, 0); this.latitude = defaultValue_default(latitude, 0); this.height = defaultValue_default(height, 0); } Cartographic25.fromRadians = function(longitude, latitude, height, result) { Check_default.typeOf.number("longitude", longitude); Check_default.typeOf.number("latitude", latitude); height = defaultValue_default(height, 0); if (!defined_default(result)) { return new Cartographic25(longitude, latitude, height); } result.longitude = longitude; result.latitude = latitude; result.height = height; return result; }; Cartographic25.fromDegrees = function(longitude, latitude, height, result) { Check_default.typeOf.number("longitude", longitude); Check_default.typeOf.number("latitude", latitude); longitude = Math_default.toRadians(longitude); latitude = Math_default.toRadians(latitude); return Cartographic25.fromRadians(longitude, latitude, height, result); }; var cartesianToCartographicN = new Cartesian3_default(); var cartesianToCartographicP = new Cartesian3_default(); var cartesianToCartographicH = new Cartesian3_default(); var wgs84OneOverRadii = new Cartesian3_default( 1 / 6378137, 1 / 6378137, 1 / 6356752314245179e-9 ); var wgs84OneOverRadiiSquared = new Cartesian3_default( 1 / (6378137 * 6378137), 1 / (6378137 * 6378137), 1 / (6356752314245179e-9 * 6356752314245179e-9) ); var wgs84CenterToleranceSquared = Math_default.EPSILON1; Cartographic25.fromCartesian = function(cartesian, ellipsoid, result) { const oneOverRadii = defined_default(ellipsoid) ? ellipsoid.oneOverRadii : wgs84OneOverRadii; const oneOverRadiiSquared = defined_default(ellipsoid) ? ellipsoid.oneOverRadiiSquared : wgs84OneOverRadiiSquared; const centerToleranceSquared = defined_default(ellipsoid) ? ellipsoid._centerToleranceSquared : wgs84CenterToleranceSquared; const p = scaleToGeodeticSurface_default( cartesian, oneOverRadii, oneOverRadiiSquared, centerToleranceSquared, cartesianToCartographicP ); if (!defined_default(p)) { return void 0; } let n = Cartesian3_default.multiplyComponents( p, oneOverRadiiSquared, cartesianToCartographicN ); n = Cartesian3_default.normalize(n, n); const h = Cartesian3_default.subtract(cartesian, p, cartesianToCartographicH); const longitude = Math.atan2(n.y, n.x); const latitude = Math.asin(n.z); const height = Math_default.sign(Cartesian3_default.dot(h, cartesian)) * Cartesian3_default.magnitude(h); if (!defined_default(result)) { return new Cartographic25(longitude, latitude, height); } result.longitude = longitude; result.latitude = latitude; result.height = height; return result; }; Cartographic25.toCartesian = function(cartographic, ellipsoid, result) { Check_default.defined("cartographic", cartographic); return Cartesian3_default.fromRadians( cartographic.longitude, cartographic.latitude, cartographic.height, ellipsoid, result ); }; Cartographic25.clone = function(cartographic, result) { if (!defined_default(cartographic)) { return void 0; } if (!defined_default(result)) { return new Cartographic25( cartographic.longitude, cartographic.latitude, cartographic.height ); } result.longitude = cartographic.longitude; result.latitude = cartographic.latitude; result.height = cartographic.height; return result; }; Cartographic25.equals = function(left, right) { return left === right || defined_default(left) && defined_default(right) && left.longitude === right.longitude && left.latitude === right.latitude && left.height === right.height; }; Cartographic25.equalsEpsilon = function(left, right, epsilon) { epsilon = defaultValue_default(epsilon, 0); return left === right || defined_default(left) && defined_default(right) && Math.abs(left.longitude - right.longitude) <= epsilon && Math.abs(left.latitude - right.latitude) <= epsilon && Math.abs(left.height - right.height) <= epsilon; }; Cartographic25.ZERO = Object.freeze(new Cartographic25(0, 0, 0)); Cartographic25.prototype.clone = function(result) { return Cartographic25.clone(this, result); }; Cartographic25.prototype.equals = function(right) { return Cartographic25.equals(this, right); }; Cartographic25.prototype.equalsEpsilon = function(right, epsilon) { return Cartographic25.equalsEpsilon(this, right, epsilon); }; Cartographic25.prototype.toString = function() { return `(${this.longitude}, ${this.latitude}, ${this.height})`; }; var Cartographic_default = Cartographic25; // packages/engine/Source/Core/Ellipsoid.js function initialize(ellipsoid, x, y, z) { x = defaultValue_default(x, 0); y = defaultValue_default(y, 0); z = defaultValue_default(z, 0); Check_default.typeOf.number.greaterThanOrEquals("x", x, 0); Check_default.typeOf.number.greaterThanOrEquals("y", y, 0); Check_default.typeOf.number.greaterThanOrEquals("z", z, 0); ellipsoid._radii = new Cartesian3_default(x, y, z); ellipsoid._radiiSquared = new Cartesian3_default(x * x, y * y, z * z); ellipsoid._radiiToTheFourth = new Cartesian3_default( x * x * x * x, y * y * y * y, z * z * z * z ); ellipsoid._oneOverRadii = new Cartesian3_default( x === 0 ? 0 : 1 / x, y === 0 ? 0 : 1 / y, z === 0 ? 0 : 1 / z ); ellipsoid._oneOverRadiiSquared = new Cartesian3_default( x === 0 ? 0 : 1 / (x * x), y === 0 ? 0 : 1 / (y * y), z === 0 ? 0 : 1 / (z * z) ); ellipsoid._minimumRadius = Math.min(x, y, z); ellipsoid._maximumRadius = Math.max(x, y, z); ellipsoid._centerToleranceSquared = Math_default.EPSILON1; if (ellipsoid._radiiSquared.z !== 0) { ellipsoid._squaredXOverSquaredZ = ellipsoid._radiiSquared.x / ellipsoid._radiiSquared.z; } } function Ellipsoid59(x, y, z) { this._radii = void 0; this._radiiSquared = void 0; this._radiiToTheFourth = void 0; this._oneOverRadii = void 0; this._oneOverRadiiSquared = void 0; this._minimumRadius = void 0; this._maximumRadius = void 0; this._centerToleranceSquared = void 0; this._squaredXOverSquaredZ = void 0; initialize(this, x, y, z); } Object.defineProperties(Ellipsoid59.prototype, { /** * Gets the radii of the ellipsoid. * @memberof Ellipsoid.prototype * @type {Cartesian3} * @readonly */ radii: { get: function() { return this._radii; } }, /** * Gets the squared radii of the ellipsoid. * @memberof Ellipsoid.prototype * @type {Cartesian3} * @readonly */ radiiSquared: { get: function() { return this._radiiSquared; } }, /** * Gets the radii of the ellipsoid raise to the fourth power. * @memberof Ellipsoid.prototype * @type {Cartesian3} * @readonly */ radiiToTheFourth: { get: function() { return this._radiiToTheFourth; } }, /** * Gets one over the radii of the ellipsoid. * @memberof Ellipsoid.prototype * @type {Cartesian3} * @readonly */ oneOverRadii: { get: function() { return this._oneOverRadii; } }, /** * Gets one over the squared radii of the ellipsoid. * @memberof Ellipsoid.prototype * @type {Cartesian3} * @readonly */ oneOverRadiiSquared: { get: function() { return this._oneOverRadiiSquared; } }, /** * Gets the minimum radius of the ellipsoid. * @memberof Ellipsoid.prototype * @type {number} * @readonly */ minimumRadius: { get: function() { return this._minimumRadius; } }, /** * Gets the maximum radius of the ellipsoid. * @memberof Ellipsoid.prototype * @type {number} * @readonly */ maximumRadius: { get: function() { return this._maximumRadius; } } }); Ellipsoid59.clone = function(ellipsoid, result) { if (!defined_default(ellipsoid)) { return void 0; } const radii = ellipsoid._radii; if (!defined_default(result)) { return new Ellipsoid59(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; }; Ellipsoid59.fromCartesian3 = function(cartesian, result) { if (!defined_default(result)) { result = new Ellipsoid59(); } if (!defined_default(cartesian)) { return result; } initialize(result, cartesian.x, cartesian.y, cartesian.z); return result; }; Ellipsoid59.WGS84 = Object.freeze( new Ellipsoid59(6378137, 6378137, 6356752314245179e-9) ); Ellipsoid59.UNIT_SPHERE = Object.freeze(new Ellipsoid59(1, 1, 1)); Ellipsoid59.MOON = Object.freeze( new Ellipsoid59( Math_default.LUNAR_RADIUS, Math_default.LUNAR_RADIUS, Math_default.LUNAR_RADIUS ) ); Ellipsoid59.prototype.clone = function(result) { return Ellipsoid59.clone(this, result); }; Ellipsoid59.packedLength = Cartesian3_default.packedLength; Ellipsoid59.pack = function(value, array, startingIndex) { Check_default.typeOf.object("value", value); Check_default.defined("array", array); startingIndex = defaultValue_default(startingIndex, 0); Cartesian3_default.pack(value._radii, array, startingIndex); return array; }; Ellipsoid59.unpack = function(array, startingIndex, result) { Check_default.defined("array", array); startingIndex = defaultValue_default(startingIndex, 0); const radii = Cartesian3_default.unpack(array, startingIndex); return Ellipsoid59.fromCartesian3(radii, result); }; Ellipsoid59.prototype.geocentricSurfaceNormal = Cartesian3_default.normalize; Ellipsoid59.prototype.geodeticSurfaceNormalCartographic = function(cartographic, result) { Check_default.typeOf.object("cartographic", cartographic); const longitude = cartographic.longitude; const latitude = cartographic.latitude; const cosLatitude = Math.cos(latitude); const x = cosLatitude * Math.cos(longitude); const y = cosLatitude * Math.sin(longitude); const z = Math.sin(latitude); if (!defined_default(result)) { result = new Cartesian3_default(); } result.x = x; result.y = y; result.z = z; return Cartesian3_default.normalize(result, result); }; Ellipsoid59.prototype.geodeticSurfaceNormal = function(cartesian, result) { Check_default.typeOf.object("cartesian", cartesian); if (isNaN(cartesian.x) || isNaN(cartesian.y) || isNaN(cartesian.z)) { throw new DeveloperError_default("cartesian has a NaN component"); } if (Cartesian3_default.equalsEpsilon(cartesian, Cartesian3_default.ZERO, Math_default.EPSILON14)) { return void 0; } if (!defined_default(result)) { result = new Cartesian3_default(); } result = Cartesian3_default.multiplyComponents( cartesian, this._oneOverRadiiSquared, result ); return Cartesian3_default.normalize(result, result); }; var cartographicToCartesianNormal = new Cartesian3_default(); var cartographicToCartesianK = new Cartesian3_default(); Ellipsoid59.prototype.cartographicToCartesian = function(cartographic, result) { const n = cartographicToCartesianNormal; const k = cartographicToCartesianK; this.geodeticSurfaceNormalCartographic(cartographic, n); Cartesian3_default.multiplyComponents(this._radiiSquared, n, k); const gamma = Math.sqrt(Cartesian3_default.dot(n, k)); Cartesian3_default.divideByScalar(k, gamma, k); Cartesian3_default.multiplyByScalar(n, cartographic.height, n); if (!defined_default(result)) { result = new Cartesian3_default(); } return Cartesian3_default.add(k, n, result); }; Ellipsoid59.prototype.cartographicArrayToCartesianArray = function(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; }; var cartesianToCartographicN2 = new Cartesian3_default(); var cartesianToCartographicP2 = new Cartesian3_default(); var cartesianToCartographicH2 = new Cartesian3_default(); Ellipsoid59.prototype.cartesianToCartographic = function(cartesian, result) { const p = this.scaleToGeodeticSurface(cartesian, cartesianToCartographicP2); if (!defined_default(p)) { return void 0; } const n = this.geodeticSurfaceNormal(p, cartesianToCartographicN2); const h = Cartesian3_default.subtract(cartesian, p, cartesianToCartographicH2); const longitude = Math.atan2(n.y, n.x); const latitude = Math.asin(n.z); const height = Math_default.sign(Cartesian3_default.dot(h, cartesian)) * 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; }; Ellipsoid59.prototype.cartesianArrayToCartographicArray = 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.cartesianToCartographic(cartesians[i], result[i]); } return result; }; Ellipsoid59.prototype.scaleToGeodeticSurface = function(cartesian, result) { return scaleToGeodeticSurface_default( cartesian, this._oneOverRadii, this._oneOverRadiiSquared, this._centerToleranceSquared, result ); }; Ellipsoid59.prototype.scaleToGeocentricSurface = function(cartesian, result) { Check_default.typeOf.object("cartesian", cartesian); if (!defined_default(result)) { result = new Cartesian3_default(); } const positionX = cartesian.x; const positionY = cartesian.y; const positionZ = cartesian.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(cartesian, beta, result); }; Ellipsoid59.prototype.transformPositionToScaledSpace = function(position, result) { if (!defined_default(result)) { result = new Cartesian3_default(); } return Cartesian3_default.multiplyComponents(position, this._oneOverRadii, result); }; Ellipsoid59.prototype.transformPositionFromScaledSpace = function(position, result) { if (!defined_default(result)) { result = new Cartesian3_default(); } return Cartesian3_default.multiplyComponents(position, this._radii, result); }; Ellipsoid59.prototype.equals = function(right) { return this === right || defined_default(right) && Cartesian3_default.equals(this._radii, right._radii); }; Ellipsoid59.prototype.toString = function() { return this._radii.toString(); }; Ellipsoid59.prototype.getSurfaceNormalIntersectionWithZAxis = function(position, buffer, result) { Check_default.typeOf.object("position", position); if (!Math_default.equalsEpsilon( this._radii.x, this._radii.y, Math_default.EPSILON15 )) { throw new DeveloperError_default( "Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y)" ); } Check_default.typeOf.number.greaterThan("Ellipsoid.radii.z", this._radii.z, 0); buffer = defaultValue_default(buffer, 0); const squaredXOverSquaredZ = this._squaredXOverSquaredZ; if (!defined_default(result)) { result = new Cartesian3_default(); } result.x = 0; result.y = 0; result.z = position.z * (1 - squaredXOverSquaredZ); if (Math.abs(result.z) >= this._radii.z - buffer) { return void 0; } return result; }; var scratchEndpoint = new Cartesian3_default(); Ellipsoid59.prototype.getLocalCurvature = function(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 ); }; 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(a, b, func) { Check_default.typeOf.number("a", a); Check_default.typeOf.number("b", b); Check_default.typeOf.func("func", func); const xMean = 0.5 * (b + a); const xRange = 0.5 * (b - a); 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; } Ellipsoid59.prototype.surfaceArea = function(rectangle) { Check_default.typeOf.object("rectangle", rectangle); const minLongitude = rectangle.west; let maxLongitude = rectangle.east; const minLatitude = rectangle.south; const maxLatitude = rectangle.north; while (maxLongitude < minLongitude) { maxLongitude += Math_default.TWO_PI; } const radiiSquared = this._radiiSquared; const a2 = radiiSquared.x; const b2 = radiiSquared.y; const c2 = radiiSquared.z; const a2b2 = a2 * 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 + c2 * (b2 * cosTheta * cosTheta + a2 * sinTheta * sinTheta) * sinPhi * sinPhi ); }); }); }; var Ellipsoid_default = Ellipsoid59; // packages/engine/Specs/Scene/Cesium3DTilesetSpec.js describe( "Scene/Cesium3DTileset", function() { const webglStub = !!window.webglStub; let scene2; const centerLongitude = -1.31968; const centerLatitude = 0.698874; let options; const tilesetUrl = "Data/Cesium3DTiles/Tilesets/Tileset/tileset.json"; const tilesetEmptyRootUrl = "Data/Cesium3DTiles/Tilesets/TilesetEmptyRoot/tileset.json"; const tilesetUniform = "Data/Cesium3DTiles/Tilesets/TilesetUniform/tileset.json"; const tilesetReplacement1Url = "Data/Cesium3DTiles/Tilesets/TilesetReplacement1/tileset.json"; const tilesetReplacement2Url = "Data/Cesium3DTiles/Tilesets/TilesetReplacement2/tileset.json"; const tilesetReplacement3Url = "Data/Cesium3DTiles/Tilesets/TilesetReplacement3/tileset.json"; const tilesetRefinementMix = "Data/Cesium3DTiles/Tilesets/TilesetRefinementMix/tileset.json"; const tilesetOfTilesetsUrl = "Data/Cesium3DTiles/Tilesets/TilesetOfTilesets/tileset.json"; const withoutBatchTableUrl = "Data/Cesium3DTiles/Batched/BatchedWithoutBatchTable/tileset.json"; const withBatchTableUrl = "Data/Cesium3DTiles/Batched/BatchedWithBatchTable/tileset.json"; const noBatchIdsUrl = "Data/Cesium3DTiles/Batched/BatchedNoBatchIds/tileset.json"; const withBatchTableHierarchyUrl = "Data/Cesium3DTiles/Hierarchy/BatchTableHierarchy/tileset.json"; const withTransformBoxUrl = "Data/Cesium3DTiles/Batched/BatchedWithTransformBox/tileset.json"; const withTransformSphereUrl = "Data/Cesium3DTiles/Batched/BatchedWithTransformSphere/tileset.json"; const withTransformRegionUrl = "Data/Cesium3DTiles/Batched/BatchedWithTransformRegion/tileset.json"; const withBoundingSphereUrl = "Data/Cesium3DTiles/Batched/BatchedWithBoundingSphere/tileset.json"; const compositeUrl = "Data/Cesium3DTiles/Composite/Composite/tileset.json"; const instancedUrl = "Data/Cesium3DTiles/Instanced/InstancedWithBatchTable/tileset.json"; const instancedRedMaterialUrl = "Data/Cesium3DTiles/Instanced/InstancedRedMaterial/tileset.json"; const instancedAnimationUrl = "Data/Cesium3DTiles/Instanced/InstancedAnimated/tileset.json"; const gltfContentUrl = "Data/Cesium3DTiles/GltfContent/glTF/tileset.json"; const glbContentUrl = "Data/Cesium3DTiles/GltfContent/glb/tileset.json"; const gltfContentWithCopyrightUrl = "Data/Cesium3DTiles/GltfContentWithCopyright/glTF/tileset.json"; const gltfContentWithRepeatedCopyrightsUrl = "Data/Cesium3DTiles/GltfContentWithRepeatedCopyrights/glTF/tileset.json"; const colorsUrl = "Data/Cesium3DTiles/Batched/BatchedColors/tileset.json"; const texturedUrl = "Data/Cesium3DTiles/Batched/BatchedTextured/tileset.json"; const translucentUrl = "Data/Cesium3DTiles/Batched/BatchedTranslucent/tileset.json"; const translucentOpaqueMixUrl = "Data/Cesium3DTiles/Batched/BatchedTranslucentOpaqueMix/tileset.json"; const tilesetWithTransformsUrl = "Data/Cesium3DTiles/Tilesets/TilesetWithTransforms/tileset.json"; const tilesetWithViewerRequestVolumeUrl = "Data/Cesium3DTiles/Tilesets/TilesetWithViewerRequestVolume/tileset.json"; const tilesetReplacementWithViewerRequestVolumeUrl = "Data/Cesium3DTiles/Tilesets/TilesetReplacementWithViewerRequestVolume/tileset.json"; const tilesetWithExternalResourcesUrl = "Data/Cesium3DTiles/Tilesets/TilesetWithExternalResources/tileset.json"; const tilesetUrlWithContentUri = "Data/Cesium3DTiles/Batched/BatchedWithContentDataUri/tileset.json"; const tilesetEastNorthUpUrl = "Data/Cesium3DTiles/EastNorthUpContent/tileset_1.1.json"; const tilesetSubtreeExpirationUrl = "Data/Cesium3DTiles/Tilesets/TilesetSubtreeExpiration/tileset.json"; const tilesetSubtreeUrl = "Data/Cesium3DTiles/Tilesets/TilesetSubtreeExpiration/subtree.json"; const batchedExpirationUrl = "Data/Cesium3DTiles/Batched/BatchedExpiration/tileset.json"; const batchedColorsB3dmUrl = "Data/Cesium3DTiles/Batched/BatchedColors/batchedColors.b3dm"; const batchedVertexColorsUrl = "Data/Cesium3DTiles/Batched/BatchedWithVertexColors/tileset.json"; const batchedAnimationUrl = "Data/Cesium3DTiles/Batched/BatchedAnimated/tileset.json"; const styleUrl = "Data/Cesium3DTiles/Style/style.json"; const pointCloudUrl = "Data/Cesium3DTiles/PointCloud/PointCloudRGB/tileset.json"; const pointCloudBatchedUrl = "Data/Cesium3DTiles/PointCloud/PointCloudBatched/tileset.json"; function endsWith(string, suffix) { const slicePoint = string.length - suffix.length; return string.slice(slicePoint) === suffix; } beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { import__447.RequestScheduler.clearForSpecs(); scene2.morphTo3D(0); const camera = scene2.camera; camera.frustum = new import__447.PerspectiveFrustum(); camera.frustum.aspectRatio = scene2.drawingBufferWidth / scene2.drawingBufferHeight; camera.frustum.fov = import__447.Math.toRadians(60); viewAllTiles(); options = { cullRequestsWhileMoving: false }; }); afterEach(function() { scene2.verticalExaggeration = 1; scene2.primitives.removeAll(); import__447.ResourceCache.clearForSpecs(); }); function setZoom(distance) { const center = import__447.Cartesian3.fromRadians(centerLongitude, centerLatitude); scene2.camera.lookAt(center, new import__447.HeadingPitchRange(0, -1.57, distance)); } function viewAllTiles() { setZoom(15); } function viewRootOnly() { setZoom(100); } function viewNothing() { setZoom(200); } function viewSky() { const center = import__447.Cartesian3.fromRadians( centerLongitude, centerLatitude, 100 ); scene2.camera.lookAt(center, new import__447.HeadingPitchRange(0, 1.57, 10)); } function viewBottomLeft() { viewAllTiles(); scene2.camera.moveLeft(200); scene2.camera.moveDown(200); } function viewInstances() { setZoom(30); } function viewPointCloud() { setZoom(5); } function viewGltfContent() { setZoom(100); } function isSelected(tileset, tile) { return tileset._selectedTiles.indexOf(tile) > -1; } it("loads json with static loadJson method", async function() { const tilesetJson = { asset: { version: 1.1 } }; const uri = `data:text/plain;base64,${btoa(JSON.stringify(tilesetJson))}`; await expectAsync(import__447.Cesium3DTileset.loadJson(uri)).toBeResolvedTo( tilesetJson ); }); it("fromUrl throws without url", async function() { await expectAsync( import__447.Cesium3DTileset.fromUrl() ).toBeRejectedWithDeveloperError( "url is required, actual value was undefined" ); }); it("fromUrl throws with unsupported version", async function() { const tilesetJson = { asset: { version: "2.0" } }; const uri = `data:text/plain;base64,${btoa(JSON.stringify(tilesetJson))}`; await expectAsync(import__447.Cesium3DTileset.fromUrl(uri)).toBeRejectedWithError( import__447.RuntimeError, "The tileset must be 3D Tiles version 0.0, 1.0, or 1.1" ); }); it("fromUrl throws with unsupported extension", async function() { const tilesetJson = { asset: { version: "1.0" }, extensionsUsed: ["unsupported_extension"], extensionsRequired: ["unsupported_extension"] }; const uri = `data:text/plain;base64,${btoa(JSON.stringify(tilesetJson))}`; await expectAsync(import__447.Cesium3DTileset.fromUrl(uri)).toBeRejectedWithError( import__447.RuntimeError, "Unsupported 3D Tiles Extension: unsupported_extension" ); }); it("fromUrl throws with invalid tileset JSON file", async function() { await expectAsync(import__447.Cesium3DTileset.fromUrl("invalid.json")).toBeRejected(); }); it("fromUrl resolves with file resource", async function() { const resource = new import__447.Resource({ url: "Data/Cesium3DTiles/Tilesets/TilesetOfTilesets/tileset.json" }); const tileset = await import__447.Cesium3DTileset.fromUrl(resource); expect(tileset).toBeInstanceOf(import__447.Cesium3DTileset); }); it("url and tilesetUrl set up correctly given tileset JSON filepath", async function() { const path = "Data/Cesium3DTiles/Tilesets/TilesetOfTilesets/tileset.json"; const tileset = await import__447.Cesium3DTileset.fromUrl(path); expect(tileset.resource.url).toEqual(path); }); it("url and tilesetUrl set up correctly given path with query string", async function() { const path = "Data/Cesium3DTiles/Tilesets/TilesetOfTilesets/tileset.json"; const param = "?param1=1¶m2=2"; const tileset = await import__447.Cesium3DTileset.fromUrl(path + param); expect(tileset.resource.url).toEqual(path + param); }); it("fromIonAssetId throws without assetId", async function() { await expectAsync( import__447.Cesium3DTileset.fromIonAssetId() ).toBeRejectedWithDeveloperError( "assetId is required, actual value was undefined" ); }); it("loads tileset JSON file", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const asset = tileset.asset; expect(asset).toBeDefined(); expect(asset.version).toEqual("1.0"); expect(asset.tilesetVersion).toEqual("1.2.3"); const properties = tileset.properties; expect(properties).toBeDefined(); expect(properties.id).toBeDefined(); expect(properties.id.minimum).toEqual(0); expect(properties.id.maximum).toEqual(9); expect(tileset._geometricError).toEqual(240); expect(tileset.root).toBeDefined(); expect(tileset.resource.url).toEqual(tilesetUrl); }); }); it("loads tileset with extras", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { expect(tileset.extras).toEqual({ name: "Sample Tileset" }); expect(tileset.root.extras).toBeUndefined(); const length2 = tileset.root.children.length; let taggedChildren = 0; for (let i = 0; i < length2; ++i) { if ((0, import__447.defined)(tileset.root.children[i].extras)) { expect(tileset.root.children[i].extras).toEqual({ id: "Special Tile" }); ++taggedChildren; } } expect(taggedChildren).toEqual(1); }); }); it("gets root tile", async function() { const tileset = await import__447.Cesium3DTileset.fromUrl(tilesetUrl, options); expect(tileset.root).toBeDefined(); }); it("hasExtension returns true if the tileset JSON file uses the specified extension", function() { return Cesium3DTilesTester_default.loadTileset( scene2, withBatchTableHierarchyUrl ).then(function(tileset) { expect(tileset.hasExtension("3DTILES_batch_table_hierarchy")).toBe( true ); expect(tileset.hasExtension("3DTILES_nonexistant_extension")).toBe( false ); }); }); it("passes version in query string to tiles", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { expect(tileset.root.content._resource.url).toEqual( (0, import__447.getAbsoluteUri)( tilesetUrl.replace("tileset.json", "parent.b3dm?v=1.2.3") ) ); }); }); it("passes version in query string to all external resources", function() { spyOn(import__447.Resource._Implementations, "loadWithXhr").and.callThrough(); const queryParams = "?a=1&b=boy"; const queryParamsWithVersion = "?a=1&b=boy&v=1.2.3"; return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithExternalResourcesUrl + queryParams ).then(function(tileset) { const calls = import__447.Resource._Implementations.loadWithXhr.calls.all(); const callsLength = calls.length; for (let i = 0; i < callsLength; ++i) { const url = calls[0].args[0]; if (url.indexOf(tilesetWithExternalResourcesUrl) >= 0) { const query = url.slice(url.indexOf("?")); if (url.indexOf("tileset.json") >= 0) { expect(query).toBe(queryParams); } else { expect(query).toBe(queryParamsWithVersion); } } } }); }); it("requests tile with invalid magic", async function() { const invalidMagicBuffer = Cesium3DTilesTester_default.generateBatchedTileBuffer({ magic: [120, 120, 120, 120] }); const tileset = await import__447.Cesium3DTileset.fromUrl(tilesetUrl, options); scene2.primitives.add(tileset); const failedSpy = jasmine.createSpy("listenerSpy"); tileset.tileFailed.addEventListener(failedSpy); spyOn(import__447.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(invalidMagicBuffer) ); scene2.renderForSpecs(); const root = tileset.root; await pollToPromise_default(() => { scene2.renderForSpecs(); return root.contentFailed || root.contentReady; }); expect(failedSpy).toHaveBeenCalledWith( jasmine.objectContaining({ message: "Invalid tile content." }) ); expect(root.contentFailed).toBeTrue(); }); it("handles failed tile requests", async function() { viewRootOnly(); const tileset = await import__447.Cesium3DTileset.fromUrl(tilesetUrl, options); scene2.primitives.add(tileset); const failedSpy = jasmine.createSpy("listenerSpy"); tileset.tileFailed.addEventListener(failedSpy); spyOn(import__447.Resource.prototype, "fetchArrayBuffer").and.callFake(() => { return Promise.reject(new Error("404")); }); scene2.renderForSpecs(); const root = tileset.root; await pollToPromise_default(() => { scene2.renderForSpecs(); return root.contentFailed || root.contentReady; }); expect(root.contentFailed).toBeTrue(); expect(failedSpy).toHaveBeenCalledWith( jasmine.objectContaining({ message: "404" }) ); const statistics = tileset.statistics; expect(statistics.numberOfAttemptedRequests).toBe(0); expect(statistics.numberOfPendingRequests).toBe(0); expect(statistics.numberOfTilesProcessing).toBe(0); expect(statistics.numberOfTilesWithContentReady).toBe(0); }); it("handles failed tile processing", async function() { viewRootOnly(); const tileset = await import__447.Cesium3DTileset.fromUrl(tilesetUrl, options); scene2.primitives.add(tileset); const failedSpy = jasmine.createSpy("listenerSpy"); tileset.tileFailed.addEventListener(failedSpy); spyOn(import__447.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve( Cesium3DTilesTester_default.generateBatchedTileBuffer({ version: 0 // Invalid version }) ) ); scene2.renderForSpecs(); const root = tileset.root; await pollToPromise_default(() => { scene2.renderForSpecs(); return root.contentFailed || root.contentReady; }); expect(root.contentFailed).toBeTrue(); expect(failedSpy).toHaveBeenCalledWith( jasmine.objectContaining({ message: "Only Batched 3D Model version 1 is supported. Version 0 is not." }) ); const statistics = tileset.statistics; expect(statistics.numberOfAttemptedRequests).toBe(0); expect(statistics.numberOfPendingRequests).toBe(0); expect(statistics.numberOfTilesProcessing).toBe(0); expect(statistics.numberOfTilesWithContentReady).toBe(0); }); it("renders tileset", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(5); expect(statistics.numberOfCommands).toEqual(5); }); }); function checkAnimation(url) { return Cesium3DTilesTester_default.loadTileset(scene2, url).then(function(tileset) { const renderOptions = { scene: scene2, time: new import__447.JulianDate(271.828) }; expect(renderOptions).toRenderAndCall(function(rgba) { const commandList = scene2.frameState.commandList; const modelMatrix1 = import__447.Matrix4.clone(commandList[0].modelMatrix); renderOptions.time.secondsOfDay += 0.5; expect(renderOptions).toRenderAndCall(function(rgba2) { const modelMatrix2 = import__447.Matrix4.clone(commandList[0].modelMatrix); expect(modelMatrix1).not.toEqual(modelMatrix2); }); }); }); } it("animates instanced tileset", function() { return checkAnimation(instancedAnimationUrl); }); it("animates batched tileset", function() { return checkAnimation(batchedAnimationUrl); }); it("renders tileset in CV", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { scene2.morphToColumbusView(0); scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.visited).toEqual(5); expect(statistics.numberOfCommands).toEqual(5); }); }); it("renders tileset in CV with projectTo2D option", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl, { projectTo2D: true }).then(function(tileset) { scene2.morphToColumbusView(0); scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.visited).toEqual(5); expect(statistics.numberOfCommands).toEqual(5); }); }); it("renders tileset in 2D", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { scene2.morphTo2D(0); tileset.maximumScreenSpaceError = 3; scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.visited).toEqual(5); expect(statistics.numberOfCommands).toEqual(5); }); }); it("renders tileset in 2D with projectTo2D option", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl, { projectTo2D: true }).then(function(tileset) { scene2.morphTo2D(0); tileset.maximumScreenSpaceError = 3; scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.visited).toEqual(5); expect(statistics.numberOfCommands).toEqual(5); }); }); it("does not render during morph", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const commandList = scene2.frameState.commandList; scene2.renderForSpecs(); expect(commandList.length).toBeGreaterThan(0); scene2.morphToColumbusView(1); scene2.renderForSpecs(); expect(commandList.length).toBe(0); }); }); it("renders tileset with empty root tile", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetEmptyRootUrl).then( function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(5); expect(statistics.numberOfCommands).toEqual(4); } ); }); it("renders tileset with custom up and forward axes", function() { const center = import__447.Cartesian3.fromRadians( centerLongitude, centerLatitude, 10 ); const viewEast = new import__447.HeadingPitchRange(-1.57, 0, 3); const viewNorth = new import__447.HeadingPitchRange(3.14, 0, 3); const viewUp = new import__447.HeadingPitchRange(0, -1.57, 3); const tilesetOptions = { modelMatrix: import__447.Transforms.eastNorthUpToFixedFrame(center), modelUpAxis: import__447.Axis.Z, modelForwardAxis: import__447.Axis.X }; const renderOptions = { scene: scene2, time: import__447.JulianDate.fromIso8601("2022-06-09T10:30:00Z") }; scene2.camera.lookAt(center, viewEast); return Cesium3DTilesTester_default.loadTileset( scene2, tilesetEastNorthUpUrl, tilesetOptions ).then(function(tileset) { scene2.camera.lookAt(center, viewEast); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(190); expect(rgba[1]).toBeLessThan(64); expect(rgba[2]).toBeLessThan(64); expect(rgba[3]).toEqual(255); }); scene2.camera.lookAt(center, viewNorth); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeLessThan(64); expect(rgba[1]).toBeGreaterThan(190); expect(rgba[2]).toBeLessThan(64); expect(rgba[3]).toEqual(255); }); scene2.camera.lookAt(center, viewUp); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeLessThan(64); expect(rgba[1]).toBeLessThan(64); expect(rgba[2]).toBeGreaterThan(190); expect(rgba[3]).toEqual(255); }); }); }); it("verify statistics", async function() { const tileset = await import__447.Cesium3DTileset.fromUrl(tilesetUrl, options); const statistics = tileset._statistics; expect(statistics.visited).toEqual(0); expect(statistics.numberOfCommands).toEqual(0); expect(statistics.numberOfPendingRequests).toEqual(0); expect(statistics.numberOfTilesProcessing).toEqual(0); scene2.primitives.add(tileset); await Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); expect(statistics.visited).toEqual(5); expect(statistics.numberOfCommands).toEqual(5); expect(statistics.numberOfPendingRequests).toEqual(0); expect(statistics.numberOfTilesProcessing).toEqual(0); }); function checkPointAndFeatureCounts(tileset, features, points, triangles) { const statistics = tileset._statistics; expect(statistics.numberOfFeaturesSelected).toEqual(0); expect(statistics.numberOfFeaturesLoaded).toEqual(0); expect(statistics.numberOfPointsSelected).toEqual(0); expect(statistics.numberOfPointsLoaded).toEqual(0); expect(statistics.numberOfTrianglesSelected).toEqual(0); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(statistics.numberOfFeaturesSelected).toEqual(features); expect(statistics.numberOfFeaturesLoaded).toEqual(features); expect(statistics.numberOfPointsSelected).toEqual(points); expect(statistics.numberOfPointsLoaded).toEqual(points); expect(statistics.numberOfTrianglesSelected).toEqual(triangles); viewNothing(); scene2.renderForSpecs(); expect(statistics.numberOfFeaturesSelected).toEqual(0); expect(statistics.numberOfFeaturesLoaded).toEqual(features); expect(statistics.numberOfPointsSelected).toEqual(0); expect(statistics.numberOfPointsLoaded).toEqual(points); expect(statistics.numberOfTrianglesSelected).toEqual(0); tileset.trimLoadedTiles(); scene2.renderForSpecs(); expect(statistics.numberOfFeaturesSelected).toEqual(0); expect(statistics.numberOfFeaturesLoaded).toEqual(0); expect(statistics.numberOfPointsSelected).toEqual(0); expect(statistics.numberOfPointsLoaded).toEqual(0); expect(statistics.numberOfTrianglesSelected).toEqual(0); } ); } it("verify batched features statistics", async function() { const tileset = await import__447.Cesium3DTileset.fromUrl(withBatchTableUrl, options); scene2.primitives.add(tileset); return checkPointAndFeatureCounts(tileset, 10, 0, 120); }); it("verify no batch table features statistics", async function() { const tileset = await import__447.Cesium3DTileset.fromUrl(noBatchIdsUrl, options); scene2.primitives.add(tileset); return checkPointAndFeatureCounts(tileset, 0, 0, 120); }); it("verify instanced features statistics", async function() { const tileset = await import__447.Cesium3DTileset.fromUrl( instancedRedMaterialUrl, options ); scene2.primitives.add(tileset); return checkPointAndFeatureCounts(tileset, 25, 0, 12); }); it("verify composite features statistics", async function() { const tileset = await import__447.Cesium3DTileset.fromUrl(compositeUrl, options); scene2.primitives.add(tileset); return checkPointAndFeatureCounts(tileset, 35, 0, 132); }); it("verify tileset of tilesets features statistics", async function() { const tileset = await import__447.Cesium3DTileset.fromUrl( tilesetOfTilesetsUrl, options ); scene2.primitives.add(tileset); return checkPointAndFeatureCounts(tileset, 50, 0, 600); }); it("verify points statistics", async function() { viewPointCloud(); const tileset = await import__447.Cesium3DTileset.fromUrl(pointCloudUrl, options); scene2.primitives.add(tileset); return checkPointAndFeatureCounts(tileset, 0, 1e3, 0); }); it("verify triangle statistics", async function() { const tileset = await import__447.Cesium3DTileset.fromUrl( tilesetEmptyRootUrl, options ); scene2.primitives.add(tileset); return checkPointAndFeatureCounts(tileset, 40, 0, 480); }); it("verify batched points statistics", async function() { viewPointCloud(); const tileset = await import__447.Cesium3DTileset.fromUrl( pointCloudBatchedUrl, options ); scene2.primitives.add(tileset); return checkPointAndFeatureCounts(tileset, 8, 1e3, 0); }); it("verify memory usage statistics", function() { const singleTileGeometryMemory = 7440; const singleTileTextureMemory = 0; const singleTileBatchTextureMemory = 40; const singleTilePickTextureMemory = 40; const tilesLength = 5; viewNothing(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.geometryByteLength).toEqual(0); expect(statistics.texturesByteLength).toEqual(0); expect(statistics.batchTableByteLength).toEqual(0); viewRootOnly(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(statistics.geometryByteLength).toEqual( singleTileGeometryMemory ); expect(statistics.texturesByteLength).toEqual( singleTileTextureMemory ); expect(statistics.batchTableByteLength).toEqual(0); viewAllTiles(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(statistics.geometryByteLength).toEqual( singleTileGeometryMemory * tilesLength ); expect(statistics.texturesByteLength).toEqual( singleTileTextureMemory * tilesLength ); expect(statistics.batchTableByteLength).toEqual(0); tileset.root.content.getFeature(0).color = import__447.Color.RED; scene2.renderForSpecs(); expect(statistics.geometryByteLength).toEqual( singleTileGeometryMemory * tilesLength ); expect(statistics.texturesByteLength).toEqual( singleTileTextureMemory * tilesLength ); expect(statistics.batchTableByteLength).toEqual( singleTileBatchTextureMemory ); scene2.pickForSpecs(); expect(statistics.geometryByteLength).toEqual( singleTileGeometryMemory * tilesLength ); expect(statistics.texturesByteLength).toEqual( singleTileTextureMemory * tilesLength ); expect(statistics.batchTableByteLength).toEqual( singleTileBatchTextureMemory + singleTilePickTextureMemory * tilesLength ); viewNothing(); scene2.renderForSpecs(); expect(statistics.geometryByteLength).toEqual( singleTileGeometryMemory * tilesLength ); expect(statistics.texturesByteLength).toEqual( singleTileTextureMemory * tilesLength ); expect(statistics.batchTableByteLength).toEqual( singleTileBatchTextureMemory + singleTilePickTextureMemory * tilesLength ); tileset.trimLoadedTiles(); scene2.renderForSpecs(); expect(statistics.geometryByteLength).toEqual(0); expect(statistics.texturesByteLength).toEqual(0); expect(statistics.batchTableByteLength).toEqual(0); } ); } ); }); }); it("verify memory usage statistics for shared resources", function() { import__447.ResourceCache.statistics.clear(); const b3dmGeometryMemory = 840; const i3dmGeometryMemory = 840; const texturesByteLength = 65536; const expectedGeometryMemory = b3dmGeometryMemory * 2 + i3dmGeometryMemory * 3; const expectedTextureMemory = texturesByteLength * 5; return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithExternalResourcesUrl ).then(function(tileset) { const statistics = import__447.ResourceCache.statistics; expect(statistics.geometryByteLength).toBe(expectedGeometryMemory); expect(statistics.texturesByteLength).toBe(expectedTextureMemory); }); }); it("does not process tileset when screen space error is not met", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(5); expect(statistics.numberOfCommands).toEqual(5); viewNothing(); scene2.renderForSpecs(); expect(statistics.visited).toEqual(0); expect(statistics.numberOfCommands).toEqual(0); }); }); it("does not select tiles when outside of view frustum", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(5); expect(statistics.numberOfCommands).toEqual(5); viewSky(); scene2.renderForSpecs(); expect(statistics.visited).toEqual(0); expect(statistics.numberOfCommands).toEqual(0); expect( tileset.root.visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).toEqual(import__447.CullingVolume.MASK_OUTSIDE); }); }); it("does not load additive tiles that are out of view", function() { viewBottomLeft(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.numberOfTilesWithContentReady).toEqual(2); }); }); it("culls with content box", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(5); expect(statistics.numberOfCommands).toEqual(5); viewBottomLeft(); scene2.renderForSpecs(); expect(statistics.visited).toEqual(2); expect(statistics.numberOfCommands).toEqual(1); expect(tileset._selectedTiles[0]).not.toBe(tileset.root); tileset.root._contentBoundingVolume = void 0; scene2.renderForSpecs(); expect(statistics.visited).toEqual(2); expect(statistics.numberOfCommands).toEqual(2); }); }); function findTileByUri(tiles, uri) { const length2 = tiles.length; for (let i = 0; i < length2; ++i) { const tile = tiles[i]; const contentHeader = tile._header.content; if ((0, import__447.defined)(contentHeader)) { if (contentHeader.uri.indexOf(uri) >= 0) { return tile; } } } return void 0; } it("selects children in front to back order", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { scene2.camera.moveLeft(1); scene2.camera.moveDown(0.5); scene2.renderForSpecs(); const root = tileset.root; const llTile = findTileByUri(root.children, "ll.b3dm"); const lrTile = findTileByUri(root.children, "lr.b3dm"); const urTile = findTileByUri(root.children, "ur.b3dm"); const ulTile = findTileByUri(root.children, "ul.b3dm"); const selectedTiles = tileset._selectedTiles; expect(selectedTiles[0]).toBe(root); expect(selectedTiles[1]).toBe(llTile); expect(selectedTiles[2]).toBe(ulTile); expect(selectedTiles[3]).toBe(lrTile); expect(selectedTiles[4]).toBe(urTile); }); }); async function testDynamicScreenSpaceError(url, distance) { const tileset = await Cesium3DTilesTester_default.loadTileset(scene2, url); const statistics = tileset._statistics; const center = import__447.Cartesian3.fromRadians(centerLongitude, centerLatitude); scene2.camera.lookAt(center, new import__447.HeadingPitchRange(0, 0, distance)); tileset.dynamicScreenSpaceError = false; scene2.renderForSpecs(); expect(statistics.visited).toEqual(1); expect(statistics.numberOfCommands).toEqual(1); tileset.dynamicScreenSpaceError = true; tileset.dynamicScreenSpaceErrorDensity = 1; tileset.dynamicScreenSpaceErrorFactor = 10; scene2.renderForSpecs(); expect(statistics.visited).toEqual(0); expect(statistics.numberOfCommands).toEqual(0); } function numberOfChildrenWithoutContent(tile) { const children = tile.children; const length2 = children.length; let count = 0; for (let i = 0; i < length2; ++i) { const child = children[i]; if (!child.contentReady) { ++count; } } return count; } it("uses dynamic screen space error for tileset with region", function() { return testDynamicScreenSpaceError(withTransformRegionUrl, 103); }); it("uses dynamic screen space error for tileset with bounding sphere", function() { return testDynamicScreenSpaceError(withBoundingSphereUrl, 137); }); it("uses dynamic screen space error for local tileset with box", function() { return testDynamicScreenSpaceError(withTransformBoxUrl, 103); }); it("uses dynamic screen space error for local tileset with sphere", function() { return testDynamicScreenSpaceError(withTransformSphereUrl, 144); }); it("dynamic screen space error constructor options work", async function() { const options2 = { dynamicScreenSpaceError: true, dynamicScreenSpaceErrorDensity: 1, dynamicScreenSpaceErrorFactor: 10, dynamicScreenSpaceErrorHeightFalloff: 0.5 }; const distance = 103; const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, withTransformBoxUrl, options2 ); expect(tileset.dynamicScreenSpaceError).toBe(true); expect(tileset.dynamicScreenSpaceErrorDensity).toBe(1); expect(tileset.dynamicScreenSpaceErrorFactor).toBe(10); expect(tileset.dynamicScreenSpaceErrorHeightFalloff).toBe(0.5); const statistics = tileset._statistics; const center = import__447.Cartesian3.fromRadians(centerLongitude, centerLatitude); scene2.camera.lookAt(center, new import__447.HeadingPitchRange(0, 0, distance)); scene2.renderForSpecs(); expect(statistics.visited).toEqual(0); expect(statistics.numberOfCommands).toEqual(0); }); it("additive refinement - selects root when sse is met", function() { viewRootOnly(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(1); expect(statistics.numberOfCommands).toEqual(1); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); }); it("additive refinement - selects all tiles when sse is not met", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(5); expect(statistics.numberOfCommands).toEqual(5); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); }); it("additive refinement - use parent's geometric error on child's box for early refinement", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(5); expect(statistics.numberOfCommands).toEqual(5); scene2.camera.moveLeft(50); scene2.renderForSpecs(); expect(statistics.visited).toEqual(3); expect(statistics.numberOfCommands).toEqual(3); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); }); it("additive refinement - selects tile when inside viewer request volume", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithViewerRequestVolumeUrl ).then(function(tileset) { const statistics = tileset._statistics; tileset.maximumScreenSpaceError = 0; setZoom(20); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(5); setZoom(1500); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(4); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); }); it("replacement refinement - selects root when sse is met", function() { viewRootOnly(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { tileset.root.refine = import__447.Cesium3DTileRefine.REPLACE; scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.visited).toEqual(1); expect(statistics.numberOfCommands).toEqual(1); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); }); it("replacement refinement - selects children when sse is not met", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { tileset.root.refine = import__447.Cesium3DTileRefine.REPLACE; scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.visited).toEqual(5); expect(statistics.numberOfCommands).toEqual(4); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); }); it("replacement refinement - selects root when sse is not met and children are not ready", function() { viewRootOnly(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const root = tileset.root; root.refine = import__447.Cesium3DTileRefine.REPLACE; viewAllTiles(); scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.visited).toEqual(5); expect(statistics.numberOfCommands).toEqual(1); expect(statistics.numberOfPendingRequests).toEqual(4); expect(numberOfChildrenWithoutContent(root)).toEqual(4); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); }); it("replacement refinement - selects tile when inside viewer request volume", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithViewerRequestVolumeUrl, { skipLevelOfDetail: false } ).then(function(tileset) { const statistics = tileset._statistics; const root = tileset.root; root.refine = import__447.Cesium3DTileRefine.REPLACE; root.hasEmptyContent = false; tileset.maximumScreenSpaceError = 0; setZoom(20); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(5); expect(isSelected(tileset, root)).toBe(false); setZoom(1500); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(4); expect(isSelected(tileset, root)).toBe(true); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); }); it("replacement refinement - selects root when sse is not met and subtree is not refinable (1)", function() { viewRootOnly(); return Cesium3DTilesTester_default.loadTileset( scene2, tilesetReplacement1Url ).then(function(tileset) { tileset.skipLevelOfDetail = false; viewAllTiles(); scene2.renderForSpecs(); const statistics = tileset._statistics; const root = tileset.root; expect(numberOfChildrenWithoutContent(root)).toEqual(0); expect(statistics.numberOfPendingRequests).toEqual(4); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(4); } ); }); }); it("replacement refinement - selects root when sse is not met and subtree is not refinable (2)", function() { viewRootOnly(); return Cesium3DTilesTester_default.loadTileset( scene2, tilesetReplacement2Url ).then(function(tileset) { tileset.skipLevelOfDetail = false; const statistics = tileset._statistics; return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(statistics.numberOfCommands).toEqual(1); setZoom(5); scene2.renderForSpecs(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(statistics.numberOfCommands).toEqual(2); } ); } ); }); }); it("replacement refinement - selects root when sse is not met and subtree is not refinable (3)", async function() { viewRootOnly(); const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, tilesetReplacement3Url ); tileset.skipLevelOfDetail = false; const statistics = tileset._statistics; const root = tileset.root; expect(statistics.numberOfCommands).toEqual(1); viewAllTiles(); scene2.renderForSpecs(); await pollToPromise_default(() => { scene2.renderForSpecs(); return root.children[0].contentFailed || root.children[0].contentReady; }); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(1); expect(statistics.numberOfPendingRequests).toEqual(4); await Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); expect(isSelected(tileset, root)).toEqual(false); expect(statistics.numberOfCommands).toEqual(4); }); it("replacement refinement - refines if descendant is empty leaf tile", function() { viewAllTiles(); const originalLoadJson = import__447.Cesium3DTileset.loadJson; spyOn(import__447.Cesium3DTileset, "loadJson").and.callFake(function(tilesetUrl2) { return originalLoadJson(tilesetUrl2).then(function(tilesetJson) { tilesetJson.root.refine = "REPLACE"; tilesetJson.root.children[3].content = void 0; return tilesetJson; }); }); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { tileset.skipLevelOfDetail = false; const statistics = tileset._statistics; scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(3); }); }); it("replacement and additive refinement", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetRefinementMix).then( function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(7); expect(statistics.numberOfCommands).toEqual(6); } ); }); describe("children bound union optimization", function() { it("does not select visible tiles with invisible children", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetReplacementWithViewerRequestVolumeUrl ).then(function(tileset) { const center = import__447.Cartesian3.fromRadians( centerLongitude, centerLatitude, 22 ); scene2.camera.lookAt(center, new import__447.HeadingPitchRange(0, 1.57, 1)); const root = tileset.root; const childRoot = root.children[0]; scene2.renderForSpecs(); expect( childRoot.visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[0].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[1].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[2].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[3].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect(tileset._selectedTiles.length).toEqual(0); expect(isSelected(tileset, childRoot)).toBe(false); }); }); it("does not select external tileset whose root has invisible children", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetOfTilesetsUrl ).then(function(tileset) { const center = import__447.Cartesian3.fromRadians( centerLongitude, centerLatitude, 50 ); scene2.camera.lookAt(center, new import__447.HeadingPitchRange(0, 1.57, 1)); const root = tileset.root; const externalRoot = root.children[0]; externalRoot.refine = import__447.Cesium3DTileRefine.REPLACE; scene2.renderForSpecs(); expect(isSelected(tileset, root)).toBe(false); expect(isSelected(tileset, externalRoot)).toBe(false); expect(root._visible).toBe(false); expect(externalRoot._visible).toBe(false); expect(tileset.statistics.numberOfTilesCulledWithChildrenUnion).toBe( 1 ); }); }); it("does not select visible tiles not meeting SSE with visible children", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetReplacementWithViewerRequestVolumeUrl ).then(function(tileset) { const root = tileset.root; const childRoot = root.children[0]; childRoot.geometricError = 240; scene2.renderForSpecs(); expect( childRoot.visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[0].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[1].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[2].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[3].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect(isSelected(tileset, childRoot)).toBe(false); }); }); it("does select visible tiles meeting SSE with visible children", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetReplacementWithViewerRequestVolumeUrl ).then(function(tileset) { const root = tileset.root; const childRoot = root.children[0]; childRoot.geometricError = 0; scene2.renderForSpecs(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function(tileset2) { expect( childRoot.visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[0].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[1].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[2].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[3].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect(isSelected(tileset2, childRoot)).toBe(true); } ); }); }); it("does select visible tiles with visible children failing request volumes", function() { viewRootOnly(); return Cesium3DTilesTester_default.loadTileset( scene2, tilesetReplacementWithViewerRequestVolumeUrl, { cullWithChildrenBounds: false } ).then(function(tileset) { const root = tileset.root; const childRoot = root.children[0]; expect( childRoot.visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[0].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[1].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[2].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[3].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect(tileset._selectedTiles.length).toEqual(1); expect(isSelected(tileset, childRoot)).toBe(true); }); }); it("does select visible tiles with visible children passing request volumes", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetReplacementWithViewerRequestVolumeUrl ).then(function(tileset) { const root = tileset.root; const childRoot = root.children[0]; childRoot.geometricError = 0; return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function(tileset2) { expect( childRoot.visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[0].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[1].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[2].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect( childRoot.children[3].visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect(tileset2._selectedTiles.length).toEqual(1); expect(isSelected(tileset2, childRoot)).toBe(true); childRoot.geometricError = 200; scene2.renderForSpecs(); expect(tileset2._selectedTiles.length).toEqual(4); expect(isSelected(tileset2, childRoot)).toBe(false); } ); }); }); }); it("loads tileset with external tileset JSON file", async function() { viewNothing(); const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, tilesetOfTilesetsUrl ); const root = tileset.root; expect(root.children.length).toEqual(0); viewRootOnly(); scene2.renderForSpecs(); await pollToPromise_default(() => { scene2.renderForSpecs(); return root.contentFailed || root.contentReady; }); expect(root.contentReady).toEqual(true); expect(root.hasTilesetContent).toEqual(true); expect(root.children.length).toEqual(1); const subtreeRoot = root.children[0]; expect(root.refine).toEqual(subtreeRoot.refine); expect(root.contentBoundingVolume.boundingVolume).toEqual( subtreeRoot.contentBoundingVolume.boundingVolume ); expect(subtreeRoot.hasTilesetContent).toEqual(false); expect(subtreeRoot.children.length).toEqual(4); }); it("preserves query string with external tileset JSON file", async function() { viewNothing(); spyOn(import__447.Resource._Implementations, "loadWithXhr").and.callThrough(); const queryParams = "a=1&b=boy"; let expectedUrl = `Data/Cesium3DTiles/Tilesets/TilesetOfTilesets/tileset.json?${queryParams}`; const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, `${tilesetOfTilesetsUrl}?${queryParams}` ); expect(import__447.Resource._Implementations.loadWithXhr.calls.argsFor(0)[0]).toEqual( expectedUrl ); import__447.Resource._Implementations.loadWithXhr.calls.reset(); viewRootOnly(); scene2.renderForSpecs(); await pollToPromise_default(() => { scene2.renderForSpecs(); return tileset.tilesLoaded; }); expectedUrl = (0, import__447.getAbsoluteUri)( `Data/Cesium3DTiles/Tilesets/TilesetOfTilesets/tileset2.json?v=1.2.3&${queryParams}` ); expect(import__447.Resource._Implementations.loadWithXhr.calls.argsFor(0)[0]).toEqual( expectedUrl ); }); it("renders tileset with external tileset JSON file", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetOfTilesetsUrl).then( function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(7); expect(statistics.numberOfCommands).toEqual(5); } ); }); it("always visits external tileset root", function() { viewRootOnly(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetOfTilesetsUrl).then( function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(2); expect(statistics.numberOfCommands).toEqual(1); } ); }); it("set tile color", function() { return Cesium3DTilesTester_default.loadTileset(scene2, noBatchIdsUrl).then( function(tileset) { let color; Cesium3DTilesTester_default.expectRender(scene2, tileset, function(rgba) { color = rgba; }); tileset.root.color = import__447.Color.RED; Cesium3DTilesTester_default.expectRender(scene2, tileset, function(rgba) { expect(rgba).not.toEqual(color); }); } ); }); it("debugFreezeFrame", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { viewRootOnly(); scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.visited).toEqual(1); expect(statistics.numberOfCommands).toEqual(1); tileset.debugFreezeFrame = true; viewAllTiles(); scene2.renderForSpecs(); expect(statistics.visited).toEqual(0); expect(statistics.numberOfCommands).toEqual(1); }); }); function checkDebugColorizeTiles(url) { import__447.Math.setRandomNumberSeed(0); return Cesium3DTilesTester_default.loadTileset(scene2, url).then(function(tileset) { let color; Cesium3DTilesTester_default.expectRender(scene2, tileset, function(rgba) { color = rgba; }); tileset.debugColorizeTiles = true; Cesium3DTilesTester_default.expectRender(scene2, tileset, function(rgba) { expect(rgba).not.toEqual(color); }); tileset.debugColorizeTiles = false; Cesium3DTilesTester_default.expectRender(scene2, tileset, function(rgba) { expect(rgba).toEqual(color); }); }); } it("debugColorizeTiles for b3dm with batch table", function() { return checkDebugColorizeTiles(withBatchTableUrl); }); it("debugColorizeTiles for b3dm without batch table", function() { return checkDebugColorizeTiles(noBatchIdsUrl); }); it("debugColorizeTiles for i3dm", function() { viewInstances(); return checkDebugColorizeTiles(instancedUrl); }); it("debugColorizeTiles for cmpt", function() { return checkDebugColorizeTiles(compositeUrl); }); it("debugColorizeTiles for pnts with batch table", function() { viewPointCloud(); return checkDebugColorizeTiles(pointCloudBatchedUrl); }); it("debugColorizeTiles for pnts without batch table", function() { viewPointCloud(); return checkDebugColorizeTiles(pointCloudUrl); }); it("debugColorizeTiles for glTF", function() { viewGltfContent(); return checkDebugColorizeTiles(gltfContentUrl); }); it("debugColorizeTiles for glb", function() { viewGltfContent(); return checkDebugColorizeTiles(glbContentUrl); }); it("debugWireframe", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl, { enableDebugWireframe: true }).then(function(tileset) { viewRootOnly(); tileset.debugWireframe = true; scene2.renderForSpecs(); let commands = scene2.frameState.commandList; const length2 = commands.length; let i; for (i = 0; i < length2; ++i) { expect(commands[i].primitiveType).toEqual(import__447.PrimitiveType.LINES); } tileset.debugWireframe = false; scene2.renderForSpecs(); commands = scene2.frameState.commandList; for (i = 0; i < length2; ++i) { expect(commands[i].primitiveType).toEqual(import__447.PrimitiveType.TRIANGLES); } }); }); it("debugShowBoundingVolume", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { viewRootOnly(); tileset.debugShowBoundingVolume = true; scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.visited).toEqual(1); expect(statistics.numberOfCommands).toEqual(2); tileset.debugShowBoundingVolume = false; scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(1); }); }); it("debugShowContentBoundingVolume", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { viewRootOnly(); tileset.debugShowContentBoundingVolume = true; scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.visited).toEqual(1); expect(statistics.numberOfCommands).toEqual(2); tileset.debugShowContentBoundingVolume = false; scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(1); }); }); it("debugShowViewerRequestVolume", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithViewerRequestVolumeUrl ).then(function(tileset) { tileset.debugShowViewerRequestVolume = true; scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.visited).toEqual(6); expect(statistics.numberOfCommands).toEqual(6); tileset.debugShowViewerRequestVolume = false; scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(5); }); }); it("show tile debug labels with regions", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { tileset.debugShowGeometricError = true; scene2.renderForSpecs(); expect(tileset._tileDebugLabels).toBeDefined(); expect(tileset._tileDebugLabels.length).toEqual(5); const root = tileset.root; expect(tileset._tileDebugLabels._labels[0].text).toEqual( `Geometric error: ${root.geometricError}` ); expect(tileset._tileDebugLabels._labels[1].text).toEqual( `Geometric error: ${root.children[0].geometricError}` ); expect(tileset._tileDebugLabels._labels[2].text).toEqual( `Geometric error: ${root.children[1].geometricError}` ); expect(tileset._tileDebugLabels._labels[3].text).toEqual( `Geometric error: ${root.children[2].geometricError}` ); expect(tileset._tileDebugLabels._labels[4].text).toEqual( `Geometric error: ${root.children[3].geometricError}` ); tileset.debugShowGeometricError = false; scene2.renderForSpecs(); expect(tileset._tileDebugLabels).not.toBeDefined(); }); }); it("show tile debug labels with boxes", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithTransformsUrl ).then(function(tileset) { tileset.debugShowGeometricError = true; scene2.renderForSpecs(); expect(tileset._tileDebugLabels).toBeDefined(); expect(tileset._tileDebugLabels.length).toEqual(2); const root = tileset.root; expect(tileset._tileDebugLabels._labels[0].text).toEqual( `Geometric error: ${root.geometricError}` ); expect(tileset._tileDebugLabels._labels[1].text).toEqual( `Geometric error: ${root.children[0].geometricError}` ); tileset.debugShowGeometricError = false; scene2.renderForSpecs(); expect(tileset._tileDebugLabels).not.toBeDefined(); }); }); it("show tile debug labels with bounding spheres", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithViewerRequestVolumeUrl ).then(function(tileset) { tileset.debugShowGeometricError = true; scene2.renderForSpecs(); const length2 = tileset._selectedTiles.length; expect(tileset._tileDebugLabels).toBeDefined(); expect(tileset._tileDebugLabels.length).toEqual(length2); for (let i = 0; i < length2; ++i) { expect(tileset._tileDebugLabels._labels[i].text).toEqual( `Geometric error: ${tileset._selectedTiles[i].geometricError}` ); } tileset.debugShowGeometricError = false; scene2.renderForSpecs(); expect(tileset._tileDebugLabels).not.toBeDefined(); }); }); it("show tile debug labels with rendering statistics", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { tileset.debugShowRenderingStatistics = true; viewRootOnly(); scene2.renderForSpecs(); expect(tileset._tileDebugLabels).toBeDefined(); expect(tileset._tileDebugLabels.length).toEqual(1); const content = tileset.root.content; const expected = `Commands: ${tileset.root.commandsLength} Triangles: ${content.trianglesLength} Features: ${content.featuresLength}`; expect(tileset._tileDebugLabels._labels[0].text).toEqual(expected); tileset.debugShowRenderingStatistics = false; scene2.renderForSpecs(); expect(tileset._tileDebugLabels).not.toBeDefined(); }); }); it("show tile debug labels with memory usage", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { tileset.debugShowMemoryUsage = true; viewRootOnly(); scene2.renderForSpecs(); expect(tileset._tileDebugLabels).toBeDefined(); expect(tileset._tileDebugLabels.length).toEqual(1); const expected = `Texture Memory: 0 Geometry Memory: ${7e-3.toLocaleString()}`; expect(tileset._tileDebugLabels._labels[0].text).toEqual(expected); tileset.debugShowMemoryUsage = false; scene2.renderForSpecs(); expect(tileset._tileDebugLabels).not.toBeDefined(); }); }); it("show tile debug labels with all statistics", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { tileset.debugShowGeometricError = true; tileset.debugShowRenderingStatistics = true; tileset.debugShowMemoryUsage = true; tileset.debugShowUrl = true; viewRootOnly(); scene2.renderForSpecs(); expect(tileset._tileDebugLabels).toBeDefined(); const expected = `Geometric error: 70 Commands: 1 Triangles: 120 Features: 10 Texture Memory: 0 Geometry Memory: ${7e-3.toLocaleString()} Url: parent.b3dm`; expect(tileset._tileDebugLabels._labels[0].text).toEqual(expected); tileset.debugShowGeometricError = false; tileset.debugShowRenderingStatistics = false; tileset.debugShowMemoryUsage = false; tileset.debugShowUrl = false; scene2.renderForSpecs(); expect(tileset._tileDebugLabels).not.toBeDefined(); }); }); it("show only picked tile debug label with all stats", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { tileset.debugShowGeometricError = true; tileset.debugShowRenderingStatistics = true; tileset.debugShowMemoryUsage = true; tileset.debugShowUrl = true; tileset.debugPickedTileLabelOnly = true; const scratchPosition = new import__447.Cartesian3(1, 1, 1); tileset.debugPickedTile = tileset.root; tileset.debugPickPosition = scratchPosition; scene2.renderForSpecs(); expect(tileset._tileDebugLabels).toBeDefined(); const expected = `Geometric error: 70 Commands: 1 Triangles: 120 Features: 10 Texture Memory: 0 Geometry Memory: ${7e-3.toLocaleString()} Url: parent.b3dm`; expect(tileset._tileDebugLabels.get(0).text).toEqual(expected); expect(tileset._tileDebugLabels.get(0).position).toEqual( scratchPosition ); tileset.debugPickedTile = void 0; scene2.renderForSpecs(); expect(tileset._tileDebugLabels.length).toEqual(0); }); }); it("does not request tiles when picking", function() { viewNothing(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { viewRootOnly(); scene2.pickForSpecs(); expect(tileset._statistics.numberOfPendingRequests).toEqual(0); scene2.renderForSpecs(); expect(tileset._statistics.numberOfPendingRequests).toEqual(1); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); }); it("does not process tiles when picking", async function() { viewNothing(); const tileset = await Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl); viewRootOnly(); scene2.renderForSpecs(); expect(tileset._statistics.numberOfPendingRequests).toEqual(1); await pollToPromise_default(() => { scene2.renderForSpecs(); return tileset.root._contentState === import__447.Cesium3DTileContentState.PROCESSING; }); const spy = spyOn(import__447.Cesium3DTile.prototype, "process").and.callThrough(); scene2.pickForSpecs(); expect(spy).not.toHaveBeenCalled(); await Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); expect(spy).toHaveBeenCalled(); }); xit("does not request tiles when the request scheduler is full", function() { viewRootOnly(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl, { skipLevelOfDetail: false }).then(function(tileset) { const oldMaximumRequestsPerServer = import__447.RequestScheduler.maximumRequestsPerServer; import__447.RequestScheduler.maximumRequestsPerServer = 3; viewAllTiles(); scene2.renderForSpecs(); expect(tileset._statistics.numberOfPendingRequests).toEqual(3); expect(tileset._statistics.numberOfAttemptedRequests).toEqual(1); import__447.RequestScheduler.maximumRequestsPerServer = oldMaximumRequestsPerServer; return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); }); it("load progress events are raised", function() { const results = [ [1, 0], [0, 1], [0, 0] ]; const spyUpdate = jasmine.createSpy("listener"); viewNothing(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { tileset.loadProgress.addEventListener(spyUpdate); viewRootOnly(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(spyUpdate.calls.count()).toEqual(3); expect(spyUpdate.calls.allArgs()).toEqual(results); } ); }); }); it("tilesLoaded", async function() { const tileset = await import__447.Cesium3DTileset.fromUrl(tilesetUrl, options); scene2.primitives.add(tileset); expect(tileset.tilesLoaded).toBe(false); await Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); expect(tileset.tilesLoaded).toBe(true); }); it("all tiles loaded event is raised", async function() { const spyUpdate1 = jasmine.createSpy("listener"); const spyUpdate2 = jasmine.createSpy("listener"); viewRootOnly(); const tileset = await import__447.Cesium3DTileset.fromUrl(tilesetUrl, options); tileset.allTilesLoaded.addEventListener(spyUpdate1); tileset.initialTilesLoaded.addEventListener(spyUpdate2); scene2.primitives.add(tileset); await Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); viewAllTiles(); await Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); expect(spyUpdate1.calls.count()).toEqual(2); expect(spyUpdate2.calls.count()).toEqual(1); }); it("tile visible event is raised", function() { viewRootOnly(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const spyUpdate = jasmine.createSpy("listener"); tileset.tileVisible.addEventListener(spyUpdate); scene2.renderForSpecs(); expect( tileset.root.visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect(spyUpdate.calls.count()).toEqual(1); expect(spyUpdate.calls.argsFor(0)[0]).toBe(tileset.root); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); }); it("tile load event is raised", function() { viewNothing(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const spyUpdate = jasmine.createSpy("listener"); tileset.tileLoad.addEventListener(spyUpdate); tileset.cacheBytes = 0; viewRootOnly(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(spyUpdate.calls.count()).toEqual(1); expect(spyUpdate.calls.argsFor(0)[0]).toBe(tileset.root); spyUpdate.calls.reset(); viewNothing(); scene2.renderForSpecs(); expect(tileset.statistics.numberOfTilesWithContentReady).toEqual(0); viewRootOnly(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(spyUpdate.calls.count()).toEqual(1); expect(spyUpdate.calls.argsFor(0)[0]).toBe(tileset.root); } ); } ); }); }); it("tile failed event is raised", function() { viewNothing(); const spyUpdate = jasmine.createSpy("listener"); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { spyOn(import__447.Resource._Implementations, "loadWithXhr").and.callFake( function(url, responseType, method, data, headers, deferred, overrideMimeType) { deferred.reject("404"); } ); tileset.tileFailed.addEventListener(spyUpdate); tileset.cacheBytes = 0; viewRootOnly(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }).finally(function() { expect(spyUpdate.calls.count()).toEqual(1); const arg = spyUpdate.calls.argsFor(0)[0]; expect(arg).toBeDefined(); expect(arg.url).toContain("parent.b3dm"); expect(arg.message).toBeDefined(); }); }); it("picks", async function() { const tileset = await Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl, { enablePick: !scene2.frameState.context.webgl2 }); viewRootOnly(); scene2.renderForSpecs(); const ray = scene2.camera.getPickRay( new import__447.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); const expected = new import__447.Cartesian3( 1.2150268094312553e6, -4736367339076743e-9, 4081652238842398e-9 ); expect(tileset.pick(ray, scene2.frameState)).toEqualEpsilon( expected, import__447.Math.EPSILON12 ); }); it("picks tileset of tilesets", async function() { const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, tilesetOfTilesetsUrl, { enablePick: !scene2.frameState.context.webgl2 } ); viewRootOnly(); scene2.renderForSpecs(); const ray = scene2.camera.getPickRay( new import__447.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); const expected = new import__447.Cartesian3( 1.2150268094312553e6, -4736367339076743e-9, 4081652238842398e-9 ); expect(tileset.pick(ray, scene2.frameState)).toEqualEpsilon( expected, import__447.Math.EPSILON12 ); }); it("picks instanced tileset", async function() { const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, instancedUrl, { enablePick: !scene2.frameState.context.webgl2 } ); viewInstances(); scene2.renderForSpecs(); const ray = scene2.camera.getPickRay( new import__447.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); const expected = new import__447.Cartesian3( 1.2150157820120894e6, -4736324352446682e-9, 4081615004915994e-9 ); expect(tileset.pick(ray, scene2.frameState)).toEqualEpsilon( expected, import__447.Math.EPSILON12 ); }); it("picks translucent tileset", async function() { const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, translucentUrl, { enablePick: !scene2.frameState.context.webgl2 } ); viewAllTiles(); scene2.renderForSpecs(); const ray = scene2.camera.getPickRay( new import__447.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); const expected = new import__447.Cartesian3( 1.2150131035421563e6, -4736313911345786e-9, 408160596109977e-8 ); expect(tileset.pick(ray, scene2.frameState)).toEqualEpsilon( expected, import__447.Math.EPSILON12 ); }); it("picks tileset with transforms", async function() { const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithTransformsUrl, { enablePick: !scene2.frameState.context.webgl2 } ); viewAllTiles(); scene2.renderForSpecs(); const ray = scene2.camera.getPickRay( new import__447.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); const expected = new import__447.Cartesian3( 1.2150131035421563e6, -4736313911345786e-9, 408160596109977e-8 ); expect(tileset.pick(ray, scene2.frameState)).toEqualEpsilon( expected, import__447.Math.EPSILON12 ); }); it("picking point cloud tileset returns undefined", async function() { const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, pointCloudUrl, { enablePick: !scene2.frameState.context.webgl2 } ); viewAllTiles(); scene2.renderForSpecs(); const ray = scene2.camera.getPickRay( new import__447.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); expect(tileset.pick(ray, scene2.frameState)).toBeUndefined(); }); it("getHeight samples height at a cartographic position", async function() { const tileset = await Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl, { enablePick: !scene2.frameState.context.webgl2 }); viewRootOnly(); await Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); scene2.renderForSpecs(); const center = Ellipsoid_default.WGS84.cartesianToCartographic( tileset.boundingSphere.center ); const height = tileset.getHeight(center, scene2); expect(height).toEqualEpsilon(78.1558019795064, import__447.Math.EPSILON12); }); it("getHeight samples height accounting for vertical exaggeration", async function() { const tileset = await Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl, { enablePick: !scene2.frameState.context.webgl2 }); viewRootOnly(); await Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); scene2.verticalExaggeration = 2; scene2.renderForSpecs(); const center = Ellipsoid_default.WGS84.cartesianToCartographic( tileset.boundingSphere.center ); const height = tileset.getHeight(center, scene2); expect(height).toEqualEpsilon(156.31161477299992, import__447.Math.EPSILON12); }); it("destroys", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const root = tileset.root; expect(tileset.isDestroyed()).toEqual(false); scene2.primitives.remove(tileset); expect(tileset.isDestroyed()).toEqual(true); expect(root.isDestroyed()).toEqual(true); expect(root.children[0].isDestroyed()).toEqual(true); expect(root.children[1].isDestroyed()).toEqual(true); expect(root.children[2].isDestroyed()).toEqual(true); expect(root.children[3].isDestroyed()).toEqual(true); }); }); it("destroys before external tileset JSON file finishes loading", async function() { viewNothing(); const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, tilesetOfTilesetsUrl ); const root = tileset.root; viewRootOnly(); scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.numberOfPendingRequests).toEqual(1); scene2.primitives.remove(tileset); await pollToPromise_default(() => { scene2.renderForSpecs(); return statistics.numberOfPendingRequests === 0; }); expect(root.content).toBeUndefined(); expect(root.children.length).toEqual(0); }); it("destroys before tile finishes loading", async function() { viewRootOnly(); const tileset = await import__447.Cesium3DTileset.fromUrl(tilesetUrl, options); scene2.primitives.add(tileset); const root = tileset.root; scene2.renderForSpecs(); scene2.primitives.remove(tileset); await pollToPromise_default(() => { scene2.renderForSpecs(); return tileset._statistics.numberOfPendingRequests === 0; }); expect(root.content).toBeUndefined(); }); it("renders with imageBaseLightingFactor", function() { const renderOptions = { scene: scene2, time: new import__447.JulianDate(2457522154792e-6) }; return Cesium3DTilesTester_default.loadTileset(scene2, withoutBatchTableUrl).then( function(tileset) { const ibl = tileset.imageBasedLighting; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); ibl.imageBasedLightingFactor = new import__447.Cartesian2(0, 0); expect(renderOptions).notToRender(rgba); }); } ); }); it("renders with lightColor", function() { const renderOptions = { scene: scene2, time: new import__447.JulianDate(2457522154792e-6) }; return Cesium3DTilesTester_default.loadTileset(scene2, withoutBatchTableUrl).then( function(tileset) { const ibl = tileset.imageBasedLighting; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); ibl.imageBasedLightingFactor = new import__447.Cartesian2(0, 0); expect(renderOptions).toRenderAndCall(function(rgba2) { expect(rgba2).not.toEqual(rgba); tileset.lightColor = new import__447.Cartesian3(5, 5, 5); expect(renderOptions).notToRender(rgba2); }); }); } ); }); function testBackFaceCulling(url, setViewOptions) { const renderOptions = { scene: scene2, time: new import__447.JulianDate(2457522154792e-6) }; return Cesium3DTilesTester_default.loadTileset(scene2, url).then(function(tileset) { scene2.camera.setView(setViewOptions); scene2.backgroundColor = new import__447.Color(0, 0, 1, 1); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).toEqual([0, 0, 255, 255]); tileset.backFaceCulling = false; expect(renderOptions).toRenderAndCall(function(rgba2) { expect(rgba2).not.toEqual(rgba); }); }); scene2.backgroundColor = new import__447.Color(0, 0, 0, 1); }); } it("renders b3dm tileset when back-face culling is disabled", function() { const setViewOptions = { destination: new import__447.Cartesian3( 1.2150126853779217e6, -4736313101374343e-9, 4.0816034657718465e6 ), orientation: new import__447.HeadingPitchRoll( 6.283185307179584, -0.49999825387267993, 6.283185307179586 ), endTransform: import__447.Matrix4.IDENTITY }; return testBackFaceCulling(withoutBatchTableUrl, setViewOptions); }); it("renders glTF tileset when back-face culling is disabled", function() { const setViewOptions = { destination: new import__447.Cartesian3( 1.2150126853779217e6, -4736313101374343e-9, 4.0816034657718465e6 ), orientation: new import__447.HeadingPitchRoll( 6.283185307179584, -0.49999825387267993, 6.283185307179586 ), endTransform: import__447.Matrix4.IDENTITY }; return testBackFaceCulling(gltfContentUrl, setViewOptions); }); it("renders glb tileset when back-face culling is disabled", function() { const setViewOptions = { destination: new import__447.Cartesian3( 1.2150126853779217e6, -4736313101374343e-9, 4.0816034657718465e6 ), orientation: new import__447.HeadingPitchRoll( 6.283185307179584, -0.49999825387267993, 6.283185307179586 ), endTransform: import__447.Matrix4.IDENTITY }; return testBackFaceCulling(glbContentUrl, setViewOptions); }); it("renders i3dm tileset when back-face culling is disabled", function() { const setViewOptions = { destination: new import__447.Cartesian3( 1.2150158599828142e6, -473632465638894e-8, 4081609967056947e-9 ), orientation: new import__447.HeadingPitchRoll( 6.283185307179585, -0.5000006393986758, 6.283185307179586 ), endTransform: import__447.Matrix4.IDENTITY }; return testBackFaceCulling(instancedUrl, setViewOptions); }); it("applies show style to a tileset", function() { let tileset, hideStyle; return Cesium3DTilesTester_default.loadTileset(scene2, withoutBatchTableUrl).then( function(t) { tileset = t; hideStyle = new import__447.Cesium3DTileStyle({ show: "false" }); tileset.style = hideStyle; expect(tileset.style).toBe(hideStyle); expect(scene2).toRender([0, 0, 0, 255]); tileset.style = new import__447.Cesium3DTileStyle({ show: "true" }); expect(scene2).notToRender([0, 0, 0, 255]); } ); }); it("applies show style to a tileset without features", function() { let tileset; let hideStyle; return Cesium3DTilesTester_default.loadTileset(scene2, noBatchIdsUrl).then( function(t) { tileset = t; hideStyle = new import__447.Cesium3DTileStyle({ show: "false" }); tileset.style = hideStyle; expect(tileset.style).toBe(hideStyle); expect(scene2).toRender([0, 0, 0, 255]); tileset.style = new import__447.Cesium3DTileStyle({ show: "true" }); expect(scene2).notToRender([0, 0, 0, 255]); } ); }); it("applies style with complex show expression to a tileset", function() { let tileset; return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(t) { tileset = t; tileset.style = new import__447.Cesium3DTileStyle({ show: "${id} >= 50 * 2" }); expect(scene2).toRender([0, 0, 0, 255]); tileset.style = new import__447.Cesium3DTileStyle({ show: "${id} < 200 / 2" }); expect(scene2).notToRender([0, 0, 0, 255]); } ); }); it("applies show style to a tileset with a composite tile", function() { let tileset; return Cesium3DTilesTester_default.loadTileset(scene2, compositeUrl).then( function(t) { tileset = t; tileset.style = new import__447.Cesium3DTileStyle({ show: "false" }); expect(scene2).toRender([0, 0, 0, 255]); tileset.style = new import__447.Cesium3DTileStyle({ show: "true" }); expect(scene2).notToRender([0, 0, 0, 255]); } ); }); it("applies show style to a tileset with glTF content", function() { let tileset; let hideStyle; return Cesium3DTilesTester_default.loadTileset(scene2, gltfContentUrl).then( function(t) { tileset = t; viewGltfContent(); hideStyle = new import__447.Cesium3DTileStyle({ show: "false" }); tileset.style = hideStyle; expect(tileset.style).toBe(hideStyle); expect(scene2).toRender([0, 0, 0, 255]); tileset.style = new import__447.Cesium3DTileStyle({ show: "true" }); expect(scene2).notToRender([0, 0, 0, 255]); } ); }); it("applies show style to a tileset with glb content", function() { let tileset; let hideStyle; return Cesium3DTilesTester_default.loadTileset(scene2, glbContentUrl).then( function(t) { tileset = t; viewGltfContent(); hideStyle = new import__447.Cesium3DTileStyle({ show: "false" }); tileset.style = hideStyle; expect(tileset.style).toBe(hideStyle); expect(scene2).toRender([0, 0, 0, 255]); tileset.style = new import__447.Cesium3DTileStyle({ show: "true" }); expect(scene2).notToRender([0, 0, 0, 255]); } ); }); function expectColorStyle(tileset) { let color; expect(scene2).toRenderAndCall(function(rgba) { color = rgba; }); tileset.style = new import__447.Cesium3DTileStyle({ color: 'color("blue")' }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toEqual(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toBeGreaterThan(0); expect(rgba[3]).toEqual(255); }); tileset.style = new import__447.Cesium3DTileStyle({ color: 'color("blue", 0.0)' }); expect(scene2).toRender([0, 0, 0, 255]); tileset.style = new import__447.Cesium3DTileStyle({ color: 'color("cyan")' }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toEqual(0); expect(rgba[1]).toBeGreaterThan(0); expect(rgba[2]).toBeGreaterThan(0); expect(rgba[3]).toEqual(255); }); tileset.style = void 0; expect(scene2).toRender(color); } it("applies color style to a tileset", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withoutBatchTableUrl).then( function(tileset) { return expectColorStyle(tileset); } ); }); it("applies color style to a tileset with translucent tiles", function() { return Cesium3DTilesTester_default.loadTileset(scene2, translucentUrl).then( function(tileset) { return expectColorStyle(tileset); } ); }); it("applies color style to a tileset with translucent and opaque tiles", function() { return Cesium3DTilesTester_default.loadTileset( scene2, translucentOpaqueMixUrl ).then(function(tileset) { return expectColorStyle(tileset); }); }); it("applies color style to tileset without features", function() { return Cesium3DTilesTester_default.loadTileset(scene2, noBatchIdsUrl).then( function(tileset) { return expectColorStyle(tileset); } ); }); it("applies color style to tileset with glTF content", function() { return Cesium3DTilesTester_default.loadTileset(scene2, gltfContentUrl).then( function(tileset) { viewGltfContent(); return expectColorStyle(tileset); } ); }); it("applies color style to tileset with glb content", function() { return Cesium3DTilesTester_default.loadTileset(scene2, glbContentUrl).then( function(tileset) { viewGltfContent(); return expectColorStyle(tileset); } ); }); it("applies style when feature properties change", function() { let tileset; return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(t) { tileset = t; tileset.style = new import__447.Cesium3DTileStyle({ show: "${id} < 10" }); expect(scene2).notToRender([0, 0, 0, 255]); const content = tileset.root.content; const length2 = content.featuresLength; let i; let feature; for (i = 0; i < length2; ++i) { feature = content.getFeature(i); feature.setProperty("id", feature.getProperty("id") + 10); } expect(scene2).toRender([0, 0, 0, 255]); for (i = 0; i < length2; ++i) { feature = content.getFeature(i); feature.setProperty("id", feature.getProperty("id") - 10); } expect(scene2).notToRender([0, 0, 0, 255]); } ); }); it("applies style when tile is selected after new style is applied", function() { let tileset; let feature; return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(t) { tileset = t; feature = tileset.root.content.getFeature(0); tileset.style = new import__447.Cesium3DTileStyle({ color: 'color("red")' }); scene2.renderForSpecs(); expect(feature.color).toEqual(import__447.Color.RED); tileset.style = new import__447.Cesium3DTileStyle({ color: 'color("blue")' }); scene2.renderForSpecs(); expect(feature.color).toEqual(import__447.Color.BLUE); viewNothing(); tileset.style = new import__447.Cesium3DTileStyle({ color: 'color("lime")' }); scene2.renderForSpecs(); expect(feature.color).toEqual(import__447.Color.BLUE); viewAllTiles(); scene2.renderForSpecs(); expect(feature.color).toEqual(import__447.Color.LIME); feature.show = false; scene2.renderForSpecs(); expect(feature.show).toBe(false); viewNothing(); scene2.renderForSpecs(); expect(feature.show).toBe(false); viewAllTiles(); expect(feature.show).toBe(false); } ); }); it("does not reapply style during pick pass", function() { let tileset; return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(t) { tileset = t; tileset.style = new import__447.Cesium3DTileStyle({ color: 'color("red")' }); scene2.renderForSpecs(); expect( tileset._statisticsPerPass[import__447.Cesium3DTilePass.RENDER].numberOfTilesStyled ).toBe(1); scene2.pickForSpecs(); expect( tileset._statisticsPerPass[import__447.Cesium3DTilePass.PICK].numberOfTilesStyled ).toBe(0); } ); }); it("applies style with complex color expression to a tileset", function() { let tileset; return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(t) { tileset = t; tileset.style = new import__447.Cesium3DTileStyle({ color: '(${id} >= 50 * 2) ? color("red") : color("blue")' }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toEqual(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toBeGreaterThan(0); expect(rgba[3]).toEqual(255); }); tileset.style = new import__447.Cesium3DTileStyle({ color: '(${id} < 50 * 2) ? color("red") : color("blue")' }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); } ); }); it("applies conditional color style to a tileset", function() { let tileset; return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(t) { tileset = t; tileset.style = new import__447.Cesium3DTileStyle({ color: { conditions: [ ["${id} < 10", 'color("red")'], ["true", 'color("blue")'] ] } }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); tileset.style = new import__447.Cesium3DTileStyle({ color: { conditions: [ ["${id} >= 10", 'color("red")'], ["true", 'color("blue")'] ] } }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toEqual(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toBeGreaterThan(0); expect(rgba[3]).toEqual(255); }); } ); }); it("handle else case when applying conditional color style to a tileset", function() { let tileset; return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(t) { tileset = t; tileset.style = new import__447.Cesium3DTileStyle({ color: { conditions: [["${id} > 0", 'color("black")']] } }); scene2.renderForSpecs(); expect(tileset.root.content.getFeature(0).color).toEqual(import__447.Color.WHITE); expect(tileset.root.content.getFeature(1).color).toEqual(import__447.Color.BLACK); } ); }); it("handle else case when applying conditional show to a tileset", function() { let tileset; return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(t) { tileset = t; tileset.style = new import__447.Cesium3DTileStyle({ show: { conditions: [["${id} > 0", "true"]] } }); scene2.renderForSpecs(); expect(tileset.root.content.getFeature(0).show).toBe(true); expect(tileset.root.content.getFeature(1).show).toBe(true); tileset.style = new import__447.Cesium3DTileStyle({ show: { conditions: [["${id} > 0", "false"]] } }); scene2.renderForSpecs(); expect(tileset.root.content.getFeature(0).show).toBe(true); expect(tileset.root.content.getFeature(1).show).toBe(false); } ); }); it("loads style from uri", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(tileset) { return import__447.Cesium3DTileStyle.fromUrl(styleUrl).then(function(style) { tileset.style = style; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); }); } ); }); it("applies custom style to a tileset", function() { const style = new import__447.Cesium3DTileStyle(); style.show = { evaluate: function(feature) { return this._value; }, _value: false }; style.color = { evaluateColor: function(feature, result) { return import__447.Color.clone(import__447.Color.WHITE, result); } }; return Cesium3DTilesTester_default.loadTileset(scene2, withoutBatchTableUrl).then( function(tileset) { tileset.style = style; expect(tileset.style).toBe(style); expect(scene2).toRender([0, 0, 0, 255]); style.show._value = true; tileset.makeStyleDirty(); expect(scene2).notToRender([0, 0, 0, 255]); } ); }); it("applies style after show is toggled", function() { let tileset; return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(t) { tileset = t; tileset.show = false; tileset.style = new import__447.Cesium3DTileStyle({ color: 'color("red")' }); scene2.renderForSpecs(); tileset.show = true; const renderOptions = { scene: scene2, time: new import__447.JulianDate(2457522154792e-6) }; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toBe(0); expect(rgba[2]).toBe(0); expect(rgba[3]).toEqual(255); }); } ); }); it("doesn't re-evaluate style during the next update", function() { let tileset; return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(t) { tileset = t; tileset.show = false; tileset.preloadWhenHidden = true; tileset.style = new import__447.Cesium3DTileStyle({ color: 'color("red")' }); scene2.renderForSpecs(); const statistics = tileset._statisticsPerPass[import__447.Cesium3DTilePass.PRELOAD]; expect(statistics.numberOfTilesStyled).toBe(1); scene2.renderForSpecs(); expect(statistics.numberOfTilesStyled).toBe(0); } ); }); it("doesn't re-evaluate style if the style being set is the same as the active style", function() { let tileset; let style; return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(t) { tileset = t; style = new import__447.Cesium3DTileStyle({ color: 'color("red")' }); tileset.style = style; scene2.renderForSpecs(); const statistics = tileset._statisticsPerPass[import__447.Cesium3DTilePass.RENDER]; expect(statistics.numberOfTilesStyled).toBe(1); tileset.style = style; scene2.renderForSpecs(); expect(statistics.numberOfTilesStyled).toBe(0); } ); }); function testColorBlendMode(url) { let sourceRed; let sourceGreen; let replaceRed; let replaceGreen; const renderOptions = { scene: scene2, time: new import__447.JulianDate(2457522154792e-6) }; let tileset; return Cesium3DTilesTester_default.loadTileset(scene2, url).then(function(t) { tileset = t; tileset.luminanceAtZenith = void 0; expect(renderOptions).toRenderAndCall(function(rgba) { sourceRed = rgba[0]; sourceGreen = rgba[1]; }); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(200); expect(rgba[1]).toBeLessThan(25); expect(rgba[2]).toBeLessThan(25); expect(rgba[3]).toEqual(255); }); tileset.colorBlendMode = import__447.Cesium3DTileColorBlendMode.HIGHLIGHT; tileset.style = new import__447.Cesium3DTileStyle({ color: "rgb(128, 128, 0)" }); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(100); expect(rgba[0]).toBeLessThan(sourceRed); expect(rgba[1]).toBeLessThan(25); expect(rgba[2]).toBeLessThan(25); expect(rgba[3]).toEqual(255); }); tileset.style = new import__447.Cesium3DTileStyle({ color: "rgba(255, 255, 0, 0.5)" }); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(100); expect(rgba[0]).toBeLessThan(sourceRed); expect(rgba[1]).toBeLessThan(25); expect(rgba[2]).toBeLessThan(25); expect(rgba[3]).toEqual(255); }); tileset.colorBlendMode = import__447.Cesium3DTileColorBlendMode.REPLACE; tileset.style = new import__447.Cesium3DTileStyle({ color: "rgb(128, 128, 0)" }); expect(renderOptions).toRenderAndCall(function(rgba) { replaceRed = rgba[0]; replaceGreen = rgba[1]; expect(rgba[0]).toBeGreaterThan(100); expect(rgba[0]).toBeLessThan(255); expect(rgba[1]).toBeGreaterThan(100); expect(rgba[1]).toBeLessThan(255); expect(rgba[2]).toBeLessThan(25); expect(rgba[3]).toEqual(255); }); tileset.style = new import__447.Cesium3DTileStyle({ color: "rgba(255, 255, 0, 0.5)" }); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(100); expect(rgba[0]).toBeLessThan(255); expect(rgba[1]).toBeGreaterThan(100); expect(rgba[1]).toBeLessThan(255); expect(rgba[2]).toBeLessThan(25); expect(rgba[3]).toEqual(255); }); tileset.colorBlendMode = import__447.Cesium3DTileColorBlendMode.MIX; tileset.colorBlendAmount = 0.5; tileset.style = new import__447.Cesium3DTileStyle({ color: "rgb(128, 128, 0)" }); let mixRed; let mixGreen; expect(renderOptions).toRenderAndCall(function(rgba) { mixRed = rgba[0]; mixGreen = rgba[1]; expect(rgba[0]).toBeGreaterThan(replaceRed); expect(rgba[0]).toBeLessThan(sourceRed); expect(rgba[1]).toBeGreaterThan(sourceGreen); expect(rgba[1]).toBeLessThan(replaceGreen); expect(rgba[2]).toBeLessThan(25); expect(rgba[3]).toEqual(255); }); tileset.colorBlendAmount = 0.25; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(mixRed); expect(rgba[0]).toBeLessThan(sourceRed); expect(rgba[1]).toBeGreaterThan(0); expect(rgba[1]).toBeLessThan(mixGreen); expect(rgba[2]).toBeLessThan(25); expect(rgba[3]).toEqual(255); }); tileset.colorBlendAmount = 0; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toEqual(sourceRed); expect(rgba[1]).toBeLessThan(25); expect(rgba[2]).toBeLessThan(25); expect(rgba[3]).toEqual(255); }); tileset.colorBlendAmount = 1; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toEqual(replaceRed); expect(rgba[1]).toEqual(replaceGreen); expect(rgba[2]).toBeLessThan(25); expect(rgba[3]).toEqual(255); }); tileset.colorBlendAmount = 0.5; tileset.style = new import__447.Cesium3DTileStyle({ color: "rgba(255, 255, 0, 0.5)" }); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toBeGreaterThan(0); expect(rgba[2]).toBeLessThan(25); expect(rgba[3]).toEqual(255); }); }); } it("sets colorBlendMode", function() { return testColorBlendMode(colorsUrl); }); it("sets colorBlendMode when vertex texture fetch is not supported", function() { const maximumVertexTextureImageUnits = import__447.ContextLimits.maximumVertexTextureImageUnits; import__447.ContextLimits._maximumVertexTextureImageUnits = 0; return testColorBlendMode(colorsUrl).then(function() { import__447.ContextLimits._maximumVertexTextureImageUnits = maximumVertexTextureImageUnits; }); }); it("sets colorBlendMode for textured tileset", function() { return testColorBlendMode(texturedUrl); }); it("sets colorBlendMode for instanced tileset", function() { viewInstances(); return testColorBlendMode(instancedRedMaterialUrl); }); it("sets colorBlendMode for vertex color tileset", function() { return testColorBlendMode(batchedVertexColorsUrl); }); it("Unload all cached tiles not required to meet SSE using cacheBytes", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { tileset.cacheBytes = 0; viewAllTiles(); scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.numberOfCommands).toEqual(5); expect(statistics.numberOfTilesWithContentReady).toEqual(5); expect(tileset.totalMemoryUsageInBytes).toEqual(37200); viewRootOnly(); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(1); expect(statistics.numberOfTilesWithContentReady).toEqual(1); expect(tileset.totalMemoryUsageInBytes).toEqual(7440); viewAllTiles(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(statistics.numberOfCommands).toEqual(5); expect(statistics.numberOfTilesWithContentReady).toEqual(5); expect(tileset.totalMemoryUsageInBytes).toEqual(37200); } ); }); }); it("Unload some cached tiles not required to meet SSE using cacheBytes", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { tileset.cacheBytes = 0.025 * 1024 * 1024; viewAllTiles(); scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.numberOfCommands).toEqual(5); expect(statistics.numberOfTilesWithContentReady).toEqual(5); viewRootOnly(); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(1); expect(statistics.numberOfTilesWithContentReady).toEqual(3); viewAllTiles(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(statistics.numberOfCommands).toEqual(5); expect(statistics.numberOfTilesWithContentReady).toEqual(5); } ); }); }); it("Restrict tileset memory usage with maximumCacheOverflowBytes", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { tileset.cacheBytes = 0.025 * 1024 * 1024; tileset.maximumCacheOverflowBytes = 0; expect(tileset.memoryAdjustedScreenSpaceError).toEqual(16); viewRootOnly(); scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.numberOfCommands).toEqual(1); expect(statistics.numberOfTilesWithContentReady).toEqual(3); viewAllTiles(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(statistics.numberOfCommands).toEqual(3); expect(statistics.numberOfTilesWithContentReady).toEqual(3); expect(tileset.memoryAdjustedScreenSpaceError).toBeGreaterThan(16); } ); }); }); it("Unloads cached tiles outside of the view frustum using cacheBytes", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { tileset.cacheBytes = 0; scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.numberOfCommands).toEqual(5); expect(statistics.numberOfTilesWithContentReady).toEqual(5); viewSky(); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(0); expect(statistics.numberOfTilesWithContentReady).toEqual(0); viewAllTiles(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(statistics.numberOfCommands).toEqual(5); expect(statistics.numberOfTilesWithContentReady).toEqual(5); } ); }); }); it("Unloads cached tiles in a tileset with external tileset JSON file using cacheBytes", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetOfTilesetsUrl).then( function(tileset) { const statistics = tileset._statistics; const cacheList = tileset._cache._list; tileset.cacheBytes = 0.02 * 1024 * 1024; scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(5); expect(statistics.numberOfTilesWithContentReady).toEqual(5); expect(cacheList.length - 1).toEqual(5); viewRootOnly(); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(1); expect(statistics.numberOfTilesWithContentReady).toEqual(2); expect(cacheList.length - 1).toEqual(2); viewAllTiles(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(statistics.numberOfCommands).toEqual(5); expect(statistics.numberOfTilesWithContentReady).toEqual(5); expect(cacheList.length - 1).toEqual(5); } ); } ); }); it("Unloads cached tiles in a tileset with empty tiles using cacheBytes", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetEmptyRootUrl).then( function(tileset) { const statistics = tileset._statistics; tileset.cacheBytes = 0.02 * 1024 * 1024; scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(4); expect(statistics.numberOfTilesWithContentReady).toEqual(4); viewSky(); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(0); expect(statistics.numberOfTilesWithContentReady).toEqual(2); viewAllTiles(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(statistics.numberOfCommands).toEqual(4); expect(statistics.numberOfTilesWithContentReady).toEqual(4); } ); } ); }); it("Unload cached tiles when a tileset uses replacement refinement using cacheBytes", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetReplacement1Url ).then(function(tileset) { tileset.cacheBytes = 0; viewAllTiles(); scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.numberOfCommands).toEqual(4); expect(statistics.numberOfTilesWithContentReady).toEqual(5); viewRootOnly(); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(1); expect(statistics.numberOfTilesWithContentReady).toEqual(1); viewAllTiles(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(statistics.numberOfCommands).toEqual(4); expect(statistics.numberOfTilesWithContentReady).toEqual(5); } ); }); }); it("Explicitly unloads cached tiles with trimLoadedTiles", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { tileset.cacheBytes = 0.05 * 1024 * 1024; viewAllTiles(); scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.numberOfCommands).toEqual(5); expect(statistics.numberOfTilesWithContentReady).toEqual(5); viewRootOnly(); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(1); expect(statistics.numberOfTilesWithContentReady).toEqual(5); tileset.trimLoadedTiles(); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(1); expect(statistics.numberOfTilesWithContentReady).toEqual(1); }); }); it("tileUnload event is raised", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { tileset.cacheBytes = 0; viewAllTiles(); scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.numberOfCommands).toEqual(5); expect(statistics.numberOfTilesWithContentReady).toEqual(5); viewRootOnly(); const spyUpdate = jasmine.createSpy("listener"); tileset.tileUnload.addEventListener(spyUpdate); scene2.renderForSpecs(); expect( tileset.root.visibility( scene2.frameState, import__447.CullingVolume.MASK_INDETERMINATE ) ).not.toEqual(import__447.CullingVolume.MASK_OUTSIDE); expect(spyUpdate.calls.count()).toEqual(4); expect(spyUpdate.calls.argsFor(0)[0]).toBe(tileset.root.children[0]); expect(spyUpdate.calls.argsFor(1)[0]).toBe(tileset.root.children[1]); expect(spyUpdate.calls.argsFor(2)[0]).toBe(tileset.root.children[2]); expect(spyUpdate.calls.argsFor(3)[0]).toBe(tileset.root.children[3]); }); }); it("cacheBytes throws when negative", async function() { const tileset = await import__447.Cesium3DTileset.fromUrl(tilesetUrl, options); expect(function() { tileset.cacheBytes = -1; }).toThrowDeveloperError(); }); it("maximumCacheOverflowBytes throws when negative", async function() { const tileset = await import__447.Cesium3DTileset.fromUrl(tilesetUrl, options); expect(function() { tileset.maximumCacheOverflowBytes = -1; }).toThrowDeveloperError(); }); it("maximumScreenSpaceError throws when negative", async function() { const tileset = await import__447.Cesium3DTileset.fromUrl(tilesetUrl, options); expect(function() { tileset.maximumScreenSpaceError = -1; }).toThrowDeveloperError(); }); it("propagates tile transform down the tree", function() { const b3dmCommands = 1; const i3dmCommands = scene2.context.instancedArrays ? 1 : 25; const totalCommands = b3dmCommands + i3dmCommands; return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithTransformsUrl ).then(function(tileset) { const statistics = tileset._statistics; const root = tileset.root; const rootTransform = import__447.Matrix4.unpack(root._header.transform); const child = root.children[0]; const childTransform = import__447.Matrix4.unpack(child._header.transform); let computedTransform = import__447.Matrix4.multiply( rootTransform, childTransform, new import__447.Matrix4() ); expect(statistics.numberOfCommands).toBe(totalCommands); expect(root.computedTransform).toEqual(rootTransform); expect(child.computedTransform).toEqual(computedTransform); const tilesetTransform = import__447.Matrix4.fromTranslation( new import__447.Cartesian3(0, 1, 0) ); tileset.modelMatrix = tilesetTransform; computedTransform = import__447.Matrix4.multiply( tilesetTransform, computedTransform, computedTransform ); scene2.renderForSpecs(); expect(child.computedTransform).toEqual(computedTransform); tileset.modelMatrix = import__447.Matrix4.fromTranslation( new import__447.Cartesian3(0, 1e5, 0) ); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toBe(0); tileset.modelMatrix = import__447.Matrix4.IDENTITY; scene2.renderForSpecs(); expect(statistics.numberOfCommands).toBe(totalCommands); child.transform = import__447.Matrix4.fromTranslation( new import__447.Cartesian3(0, 1e5, 0) ); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toBe(1); child.transform = import__447.Matrix4.IDENTITY; scene2.renderForSpecs(); expect(statistics.numberOfCommands).toBe(totalCommands); }); }); const skipLevelOfDetailOptions = { skipLevelOfDetail: true }; it("does not mark tileset as refining when tiles have selection depth 0", function() { viewRootOnly(); return Cesium3DTilesTester_default.loadTileset( scene2, tilesetUrl, skipLevelOfDetailOptions ).then(function(tileset) { viewAllTiles(); scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.numberOfTilesWithContentReady).toEqual(1); expect(tileset._selectedTiles[0]._selectionDepth).toEqual(0); expect(tileset.hasMixedContent).toBe(false); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function(tileset2) { expect(statistics.numberOfTilesWithContentReady).toEqual(5); expect(tileset2.hasMixedContent).toBe(false); } ); }); }); it("marks tileset as mixed when tiles have nonzero selection depth", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetReplacement3Url, skipLevelOfDetailOptions ).then(function(tileset) { const statistics = tileset._statistics; tileset.root.children[0].children[0].children[0].unloadContent(); tileset.root.children[0].children[0].children[1].unloadContent(); tileset.root.children[0].children[0].children[2].unloadContent(); statistics.numberOfTilesWithContentReady -= 3; scene2.renderForSpecs(); expect(tileset.hasMixedContent).toBe(true); expect(statistics.numberOfTilesWithContentReady).toEqual(2); expect( tileset.root.children[0].children[0].children[3]._selectionDepth ).toEqual(1); expect(tileset.root._selectionDepth).toEqual(0); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function(tileset2) { expect(statistics.numberOfTilesWithContentReady).toEqual(5); expect(tileset2.hasMixedContent).toBe(false); } ); }); }); it("adds stencil clear command first when unresolved", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetReplacement3Url, skipLevelOfDetailOptions ).then(function(tileset) { tileset.root.children[0].children[0].children[0].unloadContent(); tileset.root.children[0].children[0].children[1].unloadContent(); tileset.root.children[0].children[0].children[2].unloadContent(); scene2.renderForSpecs(); const commandList = scene2.frameState.commandList; expect(commandList[0]).toBeInstanceOf(import__447.ClearCommand); expect(commandList[0].stencil).toBe(0); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); }); it("creates duplicate backface commands", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetReplacement3Url, skipLevelOfDetailOptions ).then(function(tileset) { const statistics = tileset._statistics; const root = tileset.root; tileset.root.children[0].children[0].children[0].unloadContent(); tileset.root.children[0].children[0].children[1].unloadContent(); tileset.root.children[0].children[0].children[2].unloadContent(); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(4); expect(isSelected(tileset, root)).toBe(true); expect(root._finalResolution).toBe(false); expect( isSelected(tileset, root.children[0].children[0].children[3]) ).toBe(true); expect(root.children[0].children[0].children[3]._finalResolution).toBe( true ); expect(tileset.hasMixedContent).toBe(true); const commandList = scene2.frameState.commandList; const rs = commandList[1].renderState; expect(rs.cull.enabled).toBe(true); expect(rs.cull.face).toBe(import__447.CullFace.FRONT); expect(rs.polygonOffset.enabled).toBe(true); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); }); it("does not create duplicate backface commands if no selected descendants", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetReplacement3Url, skipLevelOfDetailOptions ).then(function(tileset) { const statistics = tileset._statistics; const root = tileset.root; tileset.root.children[0].children[0].children[0].unloadContent(); tileset.root.children[0].children[0].children[1].unloadContent(); tileset.root.children[0].children[0].children[2].unloadContent(); tileset.root.children[0].children[0].children[3].unloadContent(); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(1); expect(isSelected(tileset, root)).toBe(true); expect(root._finalResolution).toBe(true); expect( isSelected(tileset, root.children[0].children[0].children[0]) ).toBe(false); expect( isSelected(tileset, root.children[0].children[0].children[1]) ).toBe(false); expect( isSelected(tileset, root.children[0].children[0].children[2]) ).toBe(false); expect( isSelected(tileset, root.children[0].children[0].children[3]) ).toBe(false); expect(tileset.hasMixedContent).toBe(false); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); }); it("does not add commands or stencil clear command with no selected tiles", async function() { options.skipLevelOfDetail = true; const tileset = await import__447.Cesium3DTileset.fromUrl(tilesetUrl, options); scene2.primitives.add(tileset); scene2.renderForSpecs(); const statistics = tileset._statistics; expect(tileset._selectedTiles.length).toEqual(0); expect(statistics.numberOfCommands).toEqual(0); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); it("does not add stencil clear command or backface commands when fully resolved", function() { viewAllTiles(); return Cesium3DTilesTester_default.loadTileset( scene2, tilesetReplacement3Url, skipLevelOfDetailOptions ).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.numberOfCommands).toEqual( tileset._selectedTiles.length ); const commandList = scene2.frameState.commandList; const length2 = commandList.length; for (let i = 0; i < length2; ++i) { const command = commandList[i]; expect(command).not.toBeInstanceOf(import__447.ClearCommand); expect(command.renderState.cull.face).not.toBe(import__447.CullFace.FRONT); } }); }); it("loadSiblings", function() { viewBottomLeft(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetReplacement3Url, { skipLevelOfDetail: true, loadSiblings: false, foveatedTimeDelay: 0 }).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.numberOfTilesWithContentReady).toBe(2); tileset.loadSiblings = true; scene2.renderForSpecs(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function(tileset2) { expect(statistics.numberOfTilesWithContentReady).toBe(5); } ); }); }); it("immediatelyLoadDesiredLevelOfDetail", function() { viewNothing(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl, { skipLevelOfDetail: true, immediatelyLoadDesiredLevelOfDetail: true }).then(function(tileset) { const root = tileset.root; const child = findTileByUri(root.children, "ll.b3dm"); tileset.root.refine = import__447.Cesium3DTileRefine.REPLACE; tileset._allTilesAdditive = false; viewBottomLeft(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function(tileset2) { expect(isSelected(tileset2, child)); expect(!isSelected(tileset2, root)); expect(root.contentUnloaded).toBe(true); viewRootOnly(); scene2.renderForSpecs(); expect(isSelected(tileset2, child)); expect(!isSelected(tileset2, root)); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset2).then( function(tileset3) { expect(!isSelected(tileset3, child)); expect(isSelected(tileset3, root)); } ); } ); }); }); it("selects children if no ancestors available", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetOfTilesetsUrl, skipLevelOfDetailOptions ).then(function(tileset) { const statistics = tileset._statistics; const parent = tileset.root.children[0]; const child = parent.children[3].children[0]; parent.refine = import__447.Cesium3DTileRefine.REPLACE; parent.unloadContent(); viewBottomLeft(); scene2.renderForSpecs(); expect(child.contentReady).toBe(true); expect(parent.contentReady).toBe(false); expect(isSelected(tileset, child)).toBe(true); expect(isSelected(tileset, parent)).toBe(false); expect(statistics.numberOfCommands).toEqual(1); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); }); it("tile expires", function() { return Cesium3DTilesTester_default.loadTileset(scene2, batchedExpirationUrl).then( function(tileset) { spyOn(import__447.Resource._Implementations, "loadWithXhr").and.callFake( function(url2, responseType, method, data, headers, deferred, overrideMimeType) { import__447.Resource._DefaultImplementations.loadWithXhr( batchedColorsB3dmUrl, responseType, method, data, headers, deferred, overrideMimeType ); } ); const tile = tileset.root; const statistics = tileset._statistics; tileset.style = new import__447.Cesium3DTileStyle({ color: 'color("red")' }); const expireDate = import__447.JulianDate.addSeconds( import__447.JulianDate.now(), 5, new import__447.JulianDate() ); expect( import__447.JulianDate.secondsDifference(tile.expireDate, expireDate) ).toEqualEpsilon(0, import__447.Math.EPSILON1); expect(tile.expireDuration).toBe(5); expect(tile.contentExpired).toBe(false); expect(tile.contentReady).toBe(true); expect(tile.contentAvailable).toBe(true); expect(tile._expiredContent).toBeUndefined(); expect(statistics.numberOfCommands).toBe(1); expect(statistics.numberOfTilesTotal).toBe(1); tile.expireDate = import__447.JulianDate.addSeconds( import__447.JulianDate.now(), -1, new import__447.JulianDate() ); const originalMaximumRequests = import__447.RequestScheduler.maximumRequests; import__447.RequestScheduler.maximumRequests = 0; scene2.renderForSpecs(); import__447.RequestScheduler.maximumRequests = originalMaximumRequests; const expiredContent = tile._expiredContent; expect(tile.contentExpired).toBe(true); expect(tile.contentAvailable).toBe(true); expect(expiredContent).toBeDefined(); expect(statistics.numberOfCommands).toBe(1); expect(statistics.numberOfTilesTotal).toBe(1); scene2.renderForSpecs(); expect(tile.contentExpired).toBe(false); expect(tile.contentReady).toBe(false); expect(tile.contentAvailable).toBe(true); expect(tile._contentState).toBe(import__447.Cesium3DTileContentState.LOADING); expect(tile._expiredContent).toBeDefined(); const url = import__447.Resource._Implementations.loadWithXhr.calls.first().args[0]; expect(url.indexOf("expired=") >= 0).toBe(true); expect(statistics.numberOfCommands).toBe(1); expect(statistics.numberOfTilesTotal).toBe(1); return pollToPromise_default(function() { expect(statistics.numberOfCommands).toBe(1); scene2.renderForSpecs(); return tile.contentReady; }).then(function() { scene2.renderForSpecs(); expect(tile._expiredContent).toBeUndefined(); expect(expiredContent.isDestroyed()).toBe(true); expect(statistics.numberOfCommands).toBe(10); expect(statistics.numberOfTilesTotal).toBe(1); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); } ); }); function modifySubtreeBuffer(arrayBuffer) { const uint8Array = new Uint8Array(arrayBuffer); const json = (0, import__447.getJsonFromTypedArray)(uint8Array); json.root.children.splice(0, 1); return generateJsonBuffer_default(json).buffer; } it("tile with tileset content expires", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetSubtreeExpirationUrl ).then(async function(tileset) { spyOn(import__447.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { const newDeferred = (0, import__447.defer)(); import__447.Resource._DefaultImplementations.loadWithXhr( tilesetSubtreeUrl, responseType, method, data, headers, newDeferred, overrideMimeType ); newDeferred.promise.then(function(arrayBuffer) { deferred.resolve(modifySubtreeBuffer(arrayBuffer)); }); }); const subtreeRoot = tileset.root.children[0]; const subtreeChildren = subtreeRoot.children[0].children; const childrenLength = subtreeChildren.length; const statistics = tileset._statistics; expect(statistics.numberOfCommands).toBe(5); expect(statistics.numberOfTilesTotal).toBe(7); expect(statistics.numberOfTilesWithContentReady).toBe(5); subtreeRoot.expireDate = import__447.JulianDate.addSeconds( import__447.JulianDate.now(), -1, new import__447.JulianDate() ); const spyUpdate = jasmine.createSpy("listener"); tileset.tileUnload.addEventListener(spyUpdate); scene2.renderForSpecs(); scene2.renderForSpecs(); expect(subtreeRoot.children).toEqual([]); for (let i = 0; i < childrenLength; ++i) { expect(subtreeChildren[0].isDestroyed()).toBe(true); } expect(spyUpdate.calls.count()).toEqual(4); import__447.Resource._Implementations.loadWithXhr = import__447.Resource._DefaultImplementations.loadWithXhr; return pollToPromise_default(function() { scene2.renderForSpecs(); return subtreeRoot.contentReady && tileset.tilesLoaded; }).then(function() { scene2.renderForSpecs(); expect(statistics.numberOfCommands).toBe(4); expect(statistics.numberOfTilesTotal).toBe(6); expect(statistics.numberOfTilesWithContentReady).toBe(4); }); }); }); it("tile expires and request fails", async function() { const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, batchedExpirationUrl ); spyOn(import__447.Resource.prototype, "fetchArrayBuffer").and.callFake(() => { return Promise.reject(new Error("404")); }); const tile = tileset.root; const statistics = tileset._statistics; tile.expireDate = import__447.JulianDate.addSeconds( import__447.JulianDate.now(), -1, new import__447.JulianDate() ); const failedSpy = jasmine.createSpy("listenerSpy"); tileset.tileFailed.addEventListener(failedSpy); scene2.renderForSpecs(); await pollToPromise_default(() => { scene2.renderForSpecs(); return tileset.tilesLoaded; }); expect(failedSpy).toHaveBeenCalledWith( jasmine.objectContaining({ message: "404" }) ); expect(statistics.numberOfCommands).toBe(0); expect(statistics.numberOfTilesTotal).toBe(1); }); it("tile expiration date", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const tile = tileset.root; tile.expireDate = import__447.JulianDate.addSeconds( import__447.JulianDate.now(), -1, new import__447.JulianDate() ); const originalMaxmimumRequests = import__447.RequestScheduler.maximumRequests; import__447.RequestScheduler.maximumRequests = 0; scene2.renderForSpecs(); import__447.RequestScheduler.maximumRequests = originalMaxmimumRequests; expect(tile.contentExpired).toBe(true); return pollToPromise_default(function() { scene2.renderForSpecs(); return tile.contentReady; }).then(function() { scene2.renderForSpecs(); expect(tile._expiredContent).toBeUndefined(); expect(tile.expireDate).toBeUndefined(); }); }); }); it("supports content data URIs", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetUrlWithContentUri ).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(1); expect(statistics.numberOfCommands).toEqual(1); }); }); it("destroys attached ClippingPlaneCollections and ClippingPlaneCollections that have been detached", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const clippingPlaneCollection1 = new import__447.ClippingPlaneCollection({ planes: [new import__447.ClippingPlane(import__447.Cartesian3.UNIT_Z, -1e8)] }); expect(clippingPlaneCollection1.owner).not.toBeDefined(); tileset.clippingPlanes = clippingPlaneCollection1; const clippingPlaneCollection2 = new import__447.ClippingPlaneCollection({ planes: [new import__447.ClippingPlane(import__447.Cartesian3.UNIT_Z, -1e8)] }); tileset.clippingPlanes = clippingPlaneCollection2; expect(clippingPlaneCollection1.isDestroyed()).toBe(true); scene2.primitives.remove(tileset); expect(clippingPlaneCollection2.isDestroyed()).toBe(true); }); }); it("throws a DeveloperError when given a ClippingPlaneCollection attached to another Tileset", function() { let clippingPlanes; return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset1) { clippingPlanes = new import__447.ClippingPlaneCollection({ planes: [new import__447.ClippingPlane(import__447.Cartesian3.UNIT_X, 0)] }); tileset1.clippingPlanes = clippingPlanes; return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl); }).then(function(tileset2) { expect(function() { tileset2.clippingPlanes = clippingPlanes; }).toThrowDeveloperError(); }); }); it("clipping planes cull hidden tiles", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { let visibility = tileset.root.visibility( scene2.frameState, import__447.CullingVolume.MASK_INSIDE ); expect(visibility).not.toBe(import__447.CullingVolume.MASK_OUTSIDE); const plane = new import__447.ClippingPlane(import__447.Cartesian3.UNIT_Z, -1e8); tileset.clippingPlanes = new import__447.ClippingPlaneCollection({ planes: [plane] }); visibility = tileset.root.visibility( scene2.frameState, import__447.CullingVolume.MASK_INSIDE ); expect(visibility).toBe(import__447.CullingVolume.MASK_OUTSIDE); plane.distance = 0; visibility = tileset.root.visibility( scene2.frameState, import__447.CullingVolume.MASK_INSIDE ); expect(visibility).not.toBe(import__447.CullingVolume.MASK_OUTSIDE); }); }); it("clipping planes cull hidden content", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { let visibility = tileset.root.contentVisibility(scene2.frameState); expect(visibility).not.toBe(import__447.Intersect.OUTSIDE); const plane = new import__447.ClippingPlane(import__447.Cartesian3.UNIT_Z, -1e8); tileset.clippingPlanes = new import__447.ClippingPlaneCollection({ planes: [plane] }); visibility = tileset.root.contentVisibility(scene2.frameState); expect(visibility).toBe(import__447.Intersect.OUTSIDE); plane.distance = 0; visibility = tileset.root.contentVisibility(scene2.frameState); expect(visibility).not.toBe(import__447.Intersect.OUTSIDE); }); }); it("clipping planes cull tiles completely inside clipping region", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { const statistics = tileset._statistics; const root = tileset.root; scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(5); tileset.update(scene2.frameState); const radius = 287.0736139905632; const plane = new import__447.ClippingPlane(import__447.Cartesian3.UNIT_X, radius); tileset.clippingPlanes = new import__447.ClippingPlaneCollection({ planes: [plane] }); tileset.update(scene2.frameState); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(5); expect(root._isClipped).toBe(false); plane.distance = -1; tileset.update(scene2.frameState); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(3); expect(root._isClipped).toBe(true); plane.distance = -radius; tileset.update(scene2.frameState); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(0); expect(root._isClipped).toBe(true); }); }); it("clipping planes cull tiles completely inside clipping region for i3dm", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithExternalResourcesUrl ).then(function(tileset) { const statistics = tileset._statistics; const root = tileset.root; scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(6); tileset.update(scene2.frameState); const radius = 142.19001637409772; const plane = new import__447.ClippingPlane(import__447.Cartesian3.UNIT_Z, radius); tileset.clippingPlanes = new import__447.ClippingPlaneCollection({ planes: [plane] }); tileset.update(scene2.frameState); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(6); expect(root._isClipped).toBe(false); plane.distance = 0; tileset.update(scene2.frameState); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(6); expect(root._isClipped).toBe(true); plane.distance = -radius; tileset.update(scene2.frameState); scene2.renderForSpecs(); expect(statistics.numberOfCommands).toEqual(0); expect(root._isClipped).toBe(true); }); }); it("clippingPlanesOriginMatrix has correct orientation", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withTransformBoxUrl).then( function(tileset) { let offsetMatrix = tileset.clippingPlanesOriginMatrix; expect( import__447.Matrix4.equals(offsetMatrix, tileset.root.computedTransform) ).toBe(true); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then( function(tileset2) { offsetMatrix = tileset2.clippingPlanesOriginMatrix; expect( import__447.Matrix4.equals(offsetMatrix, tileset2.root.computedTransform) ).toBe(false); const clippingPlanesOrigin = import__447.Matrix4.getTranslation( offsetMatrix, new import__447.Cartesian3() ); expect( import__447.Cartesian3.equals( tileset2.root.boundingSphere.center, clippingPlanesOrigin ) ).toBe(true); } ); } ); }); it("clippingPlanesOriginMatrix matches root tile bounding sphere", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetOfTilesetsUrl).then( function(tileset) { let offsetMatrix = import__447.Matrix4.clone( tileset.clippingPlanesOriginMatrix, new import__447.Matrix4() ); let boundingSphereEastNorthUp = import__447.Transforms.eastNorthUpToFixedFrame( tileset.root.boundingSphere.center ); expect(import__447.Matrix4.equals(offsetMatrix, boundingSphereEastNorthUp)).toBe( true ); tileset.modelMatrix = import__447.Matrix4.fromTranslation( new import__447.Cartesian3(100, 0, 0) ); scene2.renderForSpecs(); expect( import__447.Matrix4.equals(offsetMatrix, tileset.clippingPlanesOriginMatrix) ).toBe(false); boundingSphereEastNorthUp = import__447.Transforms.eastNorthUpToFixedFrame( tileset.root.boundingSphere.center ); offsetMatrix = tileset.clippingPlanesOriginMatrix; expect(offsetMatrix).toEqualEpsilon( boundingSphereEastNorthUp, import__447.Math.EPSILON3 ); } ); }); describe("clippingPolygons", () => { const positions = import__447.Cartesian3.fromRadiansArray([ -1.3194369277314022, 0.6988062530900625, -1.31941, 0.69879, -1.3193955980204217, 0.6988091578771254, -1.3193931220959367, 0.698743632490865, -1.3194358224045408, 0.6987471965556998 ]); let polygon; beforeEach(() => { polygon = new import__447.ClippingPolygon({ positions }); }); it("destroys attached ClippingPolygonCollections and ClippingPolygonCollections that have been detached", async function() { const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, tilesetUrl ); const collectionA = new import__447.ClippingPolygonCollection({ polygons: [polygon] }); expect(collectionA.owner).not.toBeDefined(); tileset.clippingPolygons = collectionA; const collectionB = new import__447.ClippingPolygonCollection({ polygons: [polygon] }); tileset.clippingPolygons = collectionB; expect(collectionA.isDestroyed()).toBe(true); scene2.primitives.remove(tileset); expect(collectionB.isDestroyed()).toBe(true); }); it("throws a DeveloperError when given a ClippingPolygonCollection attached to another tileset", async function() { const tilesetA = await Cesium3DTilesTester_default.loadTileset( scene2, tilesetUrl ); const tilesetB = await Cesium3DTilesTester_default.loadTileset( scene2, tilesetUrl ); const collection = new import__447.ClippingPolygonCollection({ polygons: [polygon] }); tilesetA.clippingPolygons = collection; expect(function() { tilesetB.clippingPolygons = collection; }).toThrowDeveloperError(); }); it("cull hidden content", async function() { if (!scene2.context.webgl2) { return; } const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, tilesetUrl ); let visibility = tileset.root.contentVisibility(scene2.frameState); expect(visibility).not.toBe(import__447.Intersect.OUTSIDE); expect(visibility).not.toBe(import__447.Intersect.MASK_OUTSIDE); tileset.clippingPolygons = new import__447.ClippingPolygonCollection({ polygons: [polygon] }); visibility = tileset.root.contentVisibility(scene2.frameState); expect(visibility).not.toBe(import__447.Intersect.OUTSIDE); expect(visibility).not.toBe(import__447.Intersect.MASK_OUTSIDE); tileset.clippingPolygons.inverse = true; visibility = tileset.root.contentVisibility(scene2.frameState); expect(visibility).toBe(import__447.Intersect.OUTSIDE); }); }); it("throws if pointCloudShading is set to undefined", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then(function(tileset) { expect(function() { tileset.pointCloudShading = void 0; }).toThrowDeveloperError(); }); }); describe("updateForPass", function() { it("updates for pass", function() { viewAllTiles(); const passCamera = import__447.Camera.clone(scene2.camera); const passCullingVolume = passCamera.frustum.computeCullingVolume( passCamera.positionWC, passCamera.directionWC, passCamera.upWC ); viewNothing(); const preloadFlightPassState = new import__447.Cesium3DTilePassState({ pass: import__447.Cesium3DTilePass.PRELOAD_FLIGHT, camera: passCamera, cullingVolume: passCullingVolume }); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then( function(tileset) { expect(tileset.statistics.selected).toBe(0); tileset.updateForPass(scene2.frameState, preloadFlightPassState); expect(tileset._requestedTiles.length).toBe(5); } ); }); it("uses custom command list", function() { const passCommandList = []; const renderPassState = new import__447.Cesium3DTilePassState({ pass: import__447.Cesium3DTilePass.RENDER, commandList: passCommandList }); viewAllTiles(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl).then( function(tileset) { tileset.updateForPass(scene2.frameState, renderPassState); expect(passCommandList.length).toBe(5); } ); }); it("throws if frameState is undefined", async function() { const tileset = await import__447.Cesium3DTileset.fromUrl(tilesetUrl, options); expect(function() { tileset.updateForPass(); }).toThrowDeveloperError(); }); it("throws if tilesetPassState is undefined", async function() { const tileset = await import__447.Cesium3DTileset.fromUrl(tilesetUrl, options); expect(function() { tileset.updateForPass(scene2.frameState); }).toThrowDeveloperError(); }); }); function sampleHeightMostDetailed(cartographics, objectsToExclude) { let result; let completed = false; scene2.sampleHeightMostDetailed(cartographics, objectsToExclude).then(function(pickResult) { result = pickResult; completed = true; }); return pollToPromise_default(function() { scene2.render(); return completed; }).then(function() { return result; }); } function drillPickFromRayMostDetailed(ray, limit, objectsToExclude) { let result; let completed = false; scene2.drillPickFromRayMostDetailed(ray, limit, objectsToExclude).then(function(pickResult) { result = pickResult; completed = true; }); return pollToPromise_default(function() { scene2.render(); return completed; }).then(function() { return result; }); } describe("most detailed height queries", function() { it("tileset is offscreen", function() { if (webglStub) { return; } viewNothing(); const centerCartographic = new import__447.Cartographic( -1.3196799798348215, 0.6988740001506679, 2.4683731133709323 ); const cartographics = [centerCartographic]; return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUniform).then( function(tileset) { return sampleHeightMostDetailed(cartographics).then(function() { expect(centerCartographic.height).toEqualEpsilon( 2.47, import__447.Math.EPSILON1 ); const statisticsMostDetailedPick = tileset._statisticsPerPass[import__447.Cesium3DTilePass.MOST_DETAILED_PICK]; const statisticsRender = tileset._statisticsPerPass[import__447.Cesium3DTilePass.RENDER]; expect(statisticsMostDetailedPick.numberOfCommands).toBe(1); expect( statisticsMostDetailedPick.numberOfTilesWithContentReady ).toBe(1); expect(statisticsMostDetailedPick.selected).toBe(1); expect(statisticsMostDetailedPick.visited).toBeGreaterThan(1); expect(statisticsMostDetailedPick.numberOfTilesTotal).toBe(21); expect(statisticsRender.selected).toBe(0); }); } ); }); it("tileset is onscreen", function() { if (webglStub) { return; } viewAllTiles(); const centerCartographic = new import__447.Cartographic( -1.3196799798348215, 0.6988740001506679, 2.4683731133709323 ); const cartographics = [centerCartographic]; return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUniform).then( function(tileset) { return sampleHeightMostDetailed(cartographics).then(function() { expect(centerCartographic.height).toEqualEpsilon( 2.47, import__447.Math.EPSILON1 ); const statisticsMostDetailedPick = tileset._statisticsPerPass[import__447.Cesium3DTilePass.MOST_DETAILED_PICK]; const statisticsRender = tileset._statisticsPerPass[import__447.Cesium3DTilePass.RENDER]; expect(statisticsMostDetailedPick.numberOfCommands).toBe(1); expect( statisticsMostDetailedPick.numberOfTilesWithContentReady ).toBeGreaterThan(1); expect(statisticsMostDetailedPick.selected).toBe(1); expect(statisticsMostDetailedPick.visited).toBeGreaterThan(1); expect(statisticsMostDetailedPick.numberOfTilesTotal).toBe(21); expect(statisticsRender.selected).toBeGreaterThan(0); }); } ); }); it("tileset uses additive refinement", function() { if (webglStub) { return; } viewNothing(); const originalLoadJson = import__447.Cesium3DTileset.loadJson; spyOn(import__447.Cesium3DTileset, "loadJson").and.callFake(function(tilesetUrl2) { return originalLoadJson(tilesetUrl2).then(function(tilesetJson) { tilesetJson.root.refine = "ADD"; return tilesetJson; }); }); const offcenterCartographic = new import__447.Cartographic( -1.3196754112739246, 0.6988705057695633, 2.467395745774971 ); const cartographics = [offcenterCartographic]; return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUniform).then( function(tileset) { return sampleHeightMostDetailed(cartographics).then(function() { const statistics = tileset._statisticsPerPass[import__447.Cesium3DTilePass.MOST_DETAILED_PICK]; expect(offcenterCartographic.height).toEqualEpsilon( 7.407, import__447.Math.EPSILON1 ); expect(statistics.numberOfCommands).toBe(3); expect( statistics.numberOfTilesWithContentReady ).toBeGreaterThanOrEqual(3); expect(statistics.selected).toBe(3); expect(statistics.visited).toBeGreaterThan(3); expect(statistics.numberOfTilesTotal).toBe(21); }); } ); }); it("drill picks multiple features when tileset uses additive refinement", function() { if (webglStub) { return; } viewNothing(); const ray = new import__447.Ray(scene2.camera.positionWC, scene2.camera.directionWC); const originalLoadJson = import__447.Cesium3DTileset.loadJson; spyOn(import__447.Cesium3DTileset, "loadJson").and.callFake(function(tilesetUrl2) { return originalLoadJson(tilesetUrl2).then(function(tilesetJson) { tilesetJson.root.refine = "ADD"; return tilesetJson; }); }); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUniform).then( function(tileset) { return drillPickFromRayMostDetailed(ray).then(function(results) { expect(results.length).toBe(3); expect( results[0].object.content.url.indexOf("0_0_0.b3dm") > -1 ).toBe(true); expect( results[1].object.content.url.indexOf("1_1_1.b3dm") > -1 ).toBe(true); expect( results[2].object.content.url.indexOf("2_4_4.b3dm") > -1 ).toBe(true); }); } ); }); it("works when tileset cache is disabled", function() { if (webglStub) { return; } viewNothing(); const centerCartographic = new import__447.Cartographic( -1.3196799798348215, 0.6988740001506679, 2.4683731133709323 ); const cartographics = [centerCartographic]; return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUniform).then( function(tileset) { tileset.cacheBytes = 0; return sampleHeightMostDetailed(cartographics).then(function() { expect(centerCartographic.height).toEqualEpsilon( 2.47, import__447.Math.EPSILON1 ); }); } ); }); it("multiple samples", function() { if (webglStub) { return; } viewNothing(); const centerCartographic = new import__447.Cartographic( -1.3196799798348215, 0.6988740001506679 ); const offcenterCartographic = new import__447.Cartographic( -1.3196754112739246, 0.6988705057695633 ); const missCartographic = new import__447.Cartographic( -1.3196096042084076, 0.6988703290845706 ); const cartographics = [ centerCartographic, offcenterCartographic, missCartographic ]; return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUniform).then( function(tileset) { return sampleHeightMostDetailed(cartographics).then(function() { expect(centerCartographic.height).toEqualEpsilon( 2.47, import__447.Math.EPSILON1 ); expect(offcenterCartographic.height).toEqualEpsilon( 2.47, import__447.Math.EPSILON1 ); expect(missCartographic.height).toBeUndefined(); const statistics = tileset._statisticsPerPass[import__447.Cesium3DTilePass.MOST_DETAILED_PICK]; expect(statistics.numberOfTilesWithContentReady).toBe(2); }); } ); }); }); it("cancels out-of-view tiles", function() { viewNothing(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUniform).then( function(tileset) { viewAllTiles(); scene2.renderForSpecs(); const requestedTilesInFlight = tileset._requestedTilesInFlight; const requestedTilesInFlightLength = requestedTilesInFlight.length; expect(requestedTilesInFlightLength).toBeGreaterThan(0); const oldRequests = []; let i; for (i = 0; i < requestedTilesInFlightLength; i++) { oldRequests.push(requestedTilesInFlight[i]); } viewNothing(); scene2.renderForSpecs(); expect(requestedTilesInFlight.length).toBe(0); let allCancelled = true; const oldRequestsLength = oldRequests.length; for (i = 0; i < oldRequestsLength; i++) { const tile = oldRequests[i]; allCancelled = allCancelled && tile._request.cancelled; } expect(allCancelled).toBe(true); } ); }); it("sorts requests by priority", function() { viewNothing(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUniform).then( function(tileset) { viewAllTiles(); scene2.renderForSpecs(); const requestedTilesInFlight = tileset._requestedTilesInFlight; const requestedTilesInFlightLength = requestedTilesInFlight.length; expect(requestedTilesInFlightLength).toBeGreaterThan(0); let allSorted = true; let lastPriority = -Number.MAX_VALUE; let thisPriority; for (let i = 0; i < requestedTilesInFlightLength; i++) { thisPriority = requestedTilesInFlight[i]._priority; allSorted = allSorted && thisPriority >= lastPriority; lastPriority = thisPriority; } expect(allSorted).toBe(true); expect(lastPriority).not.toEqual(requestedTilesInFlight[0]._priority); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); } ); }); it("defers requests when foveatedScreenSpaceError is true", function() { viewNothing(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetRefinementMix).then( function(tileset) { tileset.foveatedScreenSpaceError = true; tileset.foveatedConeSize = 0; tileset.maximumScreenSpaceError = 8; tileset.foveatedTimeDelay = 0; viewAllTiles(); scene2.camera.moveLeft(205); scene2.camera.moveDown(205); scene2.renderForSpecs(); const requestedTilesInFlight = tileset._requestedTilesInFlight; expect(requestedTilesInFlight.length).toBe(1); expect(requestedTilesInFlight[0].priorityDeferred).toBe(true); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); } ); }); it("loads deferred requests only after time delay.", function() { viewNothing(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetRefinementMix).then( function(tileset) { tileset.foveatedScreenSpaceError = true; tileset.foveatedConeSize = 0; tileset.maximumScreenSpaceError = 8; tileset.foveatedTimeDelay = 0.1; viewAllTiles(); scene2.camera.moveLeft(205); scene2.camera.moveDown(205); scene2.renderForSpecs(); expect(tileset._requestedTilesInFlight.length).toBe(0); return pollToPromise_default(function() { scene2.renderForSpecs(); return tileset._requestedTilesInFlight.length !== 0; }).then(function() { expect(tileset._requestedTilesInFlight[0].priorityDeferred).toBe( true ); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); }); } ); }); it("preloads tiles", function() { viewAllTiles(); scene2.preloadFlightCamera = import__447.Camera.clone(scene2.camera); scene2.preloadFlightCullingVolume = scene2.camera.frustum.computeCullingVolume( scene2.camera.positionWC, scene2.camera.directionWC, scene2.camera.upWC ); viewNothing(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUniform).then( function(tileset) { spyOn(import__447.Camera.prototype, "canPreloadFlight").and.callFake(function() { return true; }); scene2.renderForSpecs(); expect(tileset._requestedTilesInFlight.length).toBeGreaterThan(0); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); } ); }); it("does not fetch tiles while camera is moving", function() { viewNothing(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUniform).then( function(tileset) { tileset.cullRequestsWhileMoving = true; viewAllTiles(); scene2.renderForSpecs(); expect(tileset._requestedTilesInFlight.length).toEqual(0); } ); }); it("does not apply cullRequestWhileMoving optimization if tileset is moving", function() { viewNothing(); return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUniform).then( function(tileset) { tileset.cullRequestsWhileMoving = true; tileset.modelMatrix[12] += 1; viewAllTiles(); scene2.renderForSpecs(); expect(tileset._requestedTilesInFlight.length).toEqual(2); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); } ); }); it("loads tiles when preloadWhenHidden is true", function() { const options2 = { show: false, preloadWhenHidden: true }; return Cesium3DTilesTester_default.loadTileset(scene2, tilesetUrl, options2).then( function(tileset) { const selectedLength = tileset.statistics.selected; expect(selectedLength).toBeGreaterThan(0); tileset.show = true; scene2.renderForSpecs(); expect(tileset.statistics.selected).toBe(selectedLength); expect(tileset.statistics.numberOfPendingRequests).toBe(0); } ); }); it("displays copyrights for all glTF content", function() { return Cesium3DTilesTester_default.loadTileset( scene2, gltfContentWithCopyrightUrl ).then(function(tileset) { setZoom(10); scene2.renderForSpecs(); const expectedCredits = [ "Parent Copyright", "Lower Left Copyright", "Lower Right Copyright 1", "Lower Right Copyright 2", "Upper Right Copyright", "Upper Left Copyright" ]; const creditDisplay = scene2.frameState.creditDisplay; const credits = creditDisplay._currentFrameCredits.lightboxCredits.values; const length2 = credits.length; expect(length2).toEqual(expectedCredits.length); for (let i = 0; i < length2; i++) { const creditInfo = credits[i]; const creditString = creditInfo.credit.html; expect(expectedCredits.includes(creditString)).toBe(true); } }); }); it("displays copyrights only for glTF content in view", function() { return Cesium3DTilesTester_default.loadTileset( scene2, gltfContentWithCopyrightUrl ).then(function(tileset) { const creditDisplay = scene2.frameState.creditDisplay; const credits = creditDisplay._currentFrameCredits.lightboxCredits; setZoom(10); scene2.camera.moveLeft(150); scene2.camera.moveDown(150); scene2.renderForSpecs(); expect(credits.values.length).toEqual(1); expect(credits.values[0].credit.html).toEqual("Lower Left Copyright"); setZoom(10); scene2.camera.moveRight(150); scene2.camera.moveDown(150); scene2.renderForSpecs(); expect(credits.values.length).toEqual(2); expect(credits.values[0].credit.html).toEqual( "Lower Right Copyright 1" ); expect(credits.values[1].credit.html).toEqual( "Lower Right Copyright 2" ); setZoom(10); scene2.camera.moveRight(150); scene2.camera.moveUp(150); scene2.renderForSpecs(); expect(credits.values.length).toEqual(1); expect(credits.values[0].credit.html).toEqual("Upper Right Copyright"); setZoom(10); scene2.camera.moveLeft(150); scene2.camera.moveUp(150); scene2.renderForSpecs(); expect(credits.values.length).toEqual(1); expect(credits.values[0].credit.html).toEqual("Upper Left Copyright"); }); }); it("displays copyrights for glTF content in sorted order", function() { return Cesium3DTilesTester_default.loadTileset( scene2, gltfContentWithRepeatedCopyrightsUrl ).then(function(tileset) { setZoom(10); scene2.renderForSpecs(); const mostFrequentCopyright = new import__447.Credit("Most Frequent Copyright"); const secondRepeatedCopyright = new import__447.Credit("Second Repeated Copyright"); const lastRepeatedCopyright = new import__447.Credit("Last Repeated Copyright"); const uniqueCopyright = new import__447.Credit("Unique Copyright"); const expectedCredits = [ mostFrequentCopyright, secondRepeatedCopyright, lastRepeatedCopyright, uniqueCopyright ]; const creditDisplay = scene2.frameState.creditDisplay; const creditContainer = creditDisplay._lightboxCredits.childNodes[2]; const creditList = creditContainer.childNodes; const length2 = creditList.length; expect(length2).toEqual(4); for (let i = 0; i < length2; i++) { const credit = creditList[i].childNodes[0]; expect(credit).toEqual(expectedCredits[i].element); } }); }); it("shows credits on screen", function() { const options2 = { showCreditsOnScreen: true }; return Cesium3DTilesTester_default.loadTileset( scene2, gltfContentWithCopyrightUrl, options2 ).then(function(tileset) { setZoom(10); scene2.renderForSpecs(); const expectedCredits = [ "Parent Copyright", "Lower Left Copyright", "Lower Right Copyright 1", "Lower Right Copyright 2", "Upper Right Copyright", "Upper Left Copyright" ]; const creditDisplay = scene2.frameState.creditDisplay; const credits = creditDisplay._currentFrameCredits.screenCredits.values; const length2 = credits.length; expect(length2).toEqual(expectedCredits.length); for (let i = 0; i < length2; i++) { const creditInfo = credits[i]; const creditString = creditInfo.credit.html; expect(expectedCredits.includes(creditString)).toBe(true); } }); }); it("toggles showing credits on screen", function() { const options2 = { showCreditsOnScreen: false }; return Cesium3DTilesTester_default.loadTileset( scene2, gltfContentWithCopyrightUrl, options2 ).then(function(tileset) { setZoom(10); scene2.renderForSpecs(); const expectedCredits = [ "Parent Copyright", "Lower Left Copyright", "Lower Right Copyright 1", "Lower Right Copyright 2", "Upper Right Copyright", "Upper Left Copyright" ]; const creditDisplay = scene2.frameState.creditDisplay; const lightboxCredits = creditDisplay._currentFrameCredits.lightboxCredits.values; const screenCredits = creditDisplay._currentFrameCredits.screenCredits.values; let length2 = lightboxCredits.length; expect(length2).toEqual(expectedCredits.length); for (let i = 0; i < length2; i++) { const creditInfo = lightboxCredits[i]; const creditString = creditInfo.credit.html; expect(expectedCredits.includes(creditString)).toBe(true); } expect(screenCredits.length).toEqual(0); tileset.showCreditsOnScreen = true; scene2.renderForSpecs(); length2 = screenCredits.length; expect(length2).toEqual(expectedCredits.length); for (let i = 0; i < length2; i++) { const creditInfo = screenCredits[i]; const creditString = creditInfo.credit.html; expect(expectedCredits.includes(creditString)).toBe(true); } expect(lightboxCredits.length).toEqual(0); tileset.showCreditsOnScreen = false; scene2.renderForSpecs(); length2 = lightboxCredits.length; expect(length2).toEqual(expectedCredits.length); for (let i = 0; i < length2; i++) { const creditInfo = lightboxCredits[i]; const creditString = creditInfo.credit.html; expect(expectedCredits.includes(creditString)).toBe(true); } expect(screenCredits.length).toEqual(0); }); }); describe("implicit tiling", function() { const implicitTilesetUrl = "Data/Cesium3DTiles/Implicit/ImplicitTileset/tileset_1.1.json"; const implicitTilesetWithJsonUrl = "Data/Cesium3DTiles/Implicit/ImplicitTilesetWithJsonSubtree/tileset_1.1.json"; const implicitRootUrl = "Data/Cesium3DTiles/Implicit/ImplicitRootTile/tileset_1.1.json"; const implicitChildUrl = "Data/Cesium3DTiles/Implicit/ImplicitChildTile/tileset_1.1.json"; it("renders tileset", function() { return Cesium3DTilesTester_default.loadTileset(scene2, implicitTilesetUrl).then( function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(6); expect(statistics.numberOfCommands).toEqual(5); } ); }); it("renders tileset with JSON subtree file", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitTilesetWithJsonUrl ).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(6); expect(statistics.numberOfCommands).toEqual(5); }); }); it("detects and initializes an implicit tileset in root tile", function() { viewNothing(); return Cesium3DTilesTester_default.loadTileset(scene2, implicitRootUrl).then( function(tileset) { const implicitTile = tileset.root; expect( endsWith( implicitTile._contentResource.url, "subtrees/0/0/0/0.subtree" ) ).toEqual(true); expect(implicitTile.implicitTileset).toBeDefined(); expect(implicitTile.implicitCoordinates).toBeDefined(); expect(implicitTile.implicitCoordinates.level).toEqual(0); expect(implicitTile.implicitCoordinates.x).toEqual(0); expect(implicitTile.implicitCoordinates.y).toEqual(0); expect(implicitTile.implicitCoordinates.z).toEqual(0); } ); }); it("detects and initializes an implicit tileset in child tile", function() { viewNothing(); return Cesium3DTilesTester_default.loadTileset(scene2, implicitChildUrl).then( function(tileset) { const parentTile = tileset.root; const implicitTile = parentTile.children[0]; expect( endsWith( implicitTile._contentResource.url, "subtrees/0/0/0.subtree" ) ).toEqual(true); expect(implicitTile.implicitTileset).toBeDefined(); expect(implicitTile.implicitCoordinates).toBeDefined(); expect(implicitTile.implicitCoordinates.level).toEqual(0); expect(implicitTile.implicitCoordinates.x).toEqual(0); expect(implicitTile.implicitCoordinates.y).toEqual(0); } ); }); it("debugShowUrl works for implicit tiling", function() { return Cesium3DTilesTester_default.loadTileset(scene2, implicitTilesetUrl).then( function(tileset) { tileset.debugShowUrl = true; scene2.renderForSpecs(); const expectedLabels = [ "Url: content/0/0/0.b3dm", "Url: content/1/0/0.b3dm", "Url: content/1/1/0.b3dm", "Url: content/1/1/1.b3dm", "Url: content/1/0/1.b3dm", "Url: subtrees/0.0.0.subtree" ]; const debugLabels = tileset._tileDebugLabels._labels; const length2 = debugLabels.length; expect(length2).toBe(expectedLabels.length); for (let i = 0; i < length2; i++) { expect(debugLabels[i].text).toEqual(expectedLabels[i]); } tileset.debugShowUrl = false; scene2.renderForSpecs(); expect(tileset._tileDebugLabels).not.toBeDefined(); } ); }); }); describe("3DTILES_implicit_tiling", function() { const implicitTilesetLegacyUrl = "Data/Cesium3DTiles/Implicit/ImplicitTileset/tileset_1.0.json"; const implicitTilesetWithJsonLegacyUrl = "Data/Cesium3DTiles/Implicit/ImplicitTilesetWithJsonSubtree/tileset_1.0.json"; const implicitRootLegacyUrl = "Data/Cesium3DTiles/Implicit/ImplicitRootTile/tileset_1.0.json"; const implicitChildLegacyUrl = "Data/Cesium3DTiles/Implicit/ImplicitChildTile/tileset_1.0.json"; it("renders tileset (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitTilesetLegacyUrl ).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(6); expect(statistics.numberOfCommands).toEqual(5); }); }); it("renders tileset with JSON subtree file (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitTilesetWithJsonLegacyUrl ).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(6); expect(statistics.numberOfCommands).toEqual(5); }); }); it("detects and initializes an implicit tileset in root tile (legacy)", function() { viewNothing(); return Cesium3DTilesTester_default.loadTileset( scene2, implicitRootLegacyUrl ).then(function(tileset) { const implicitTile = tileset.root; expect( endsWith( implicitTile._contentResource.url, "subtrees/0/0/0/0.subtree" ) ).toEqual(true); expect(implicitTile.implicitTileset).toBeDefined(); expect(implicitTile.implicitCoordinates).toBeDefined(); expect(implicitTile.implicitCoordinates.level).toEqual(0); expect(implicitTile.implicitCoordinates.x).toEqual(0); expect(implicitTile.implicitCoordinates.y).toEqual(0); expect(implicitTile.implicitCoordinates.z).toEqual(0); }); }); it("detects and initializes an implicit tileset in child tile (legacy)", function() { viewNothing(); return Cesium3DTilesTester_default.loadTileset( scene2, implicitChildLegacyUrl ).then(function(tileset) { const parentTile = tileset.root; const implicitTile = parentTile.children[0]; expect( endsWith( implicitTile._contentResource.url, "subtrees/0/0/0.subtree" ) ).toEqual(true); expect(implicitTile.implicitTileset).toBeDefined(); expect(implicitTile.implicitCoordinates).toBeDefined(); expect(implicitTile.implicitCoordinates.level).toEqual(0); expect(implicitTile.implicitCoordinates.x).toEqual(0); expect(implicitTile.implicitCoordinates.y).toEqual(0); }); }); it("debugShowUrl works for implicit tiling (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitTilesetLegacyUrl ).then(function(tileset) { tileset.debugShowUrl = true; scene2.renderForSpecs(); const expectedLabels = [ "Url: content/0/0/0.b3dm", "Url: content/1/0/0.b3dm", "Url: content/1/1/0.b3dm", "Url: content/1/1/1.b3dm", "Url: content/1/0/1.b3dm", "Url: subtrees/0.0.0.subtree" ]; const debugLabels = tileset._tileDebugLabels._labels; const length2 = debugLabels.length; expect(length2).toBe(expectedLabels.length); for (let i = 0; i < length2; i++) { expect(debugLabels[i].text).toEqual(expectedLabels[i]); } tileset.debugShowUrl = false; scene2.renderForSpecs(); expect(tileset._tileDebugLabels).not.toBeDefined(); }); }); }); describe("multiple contents", function() { const multipleContentsUrl = "Data/Cesium3DTiles/MultipleContents/MultipleContents/tileset_1.1.json"; const implicitMultipleContentsUrl = "Data/Cesium3DTiles/Implicit/ImplicitMultipleContents/tileset_1.1.json"; it("request statistics are updated correctly on success", function() { return Cesium3DTilesTester_default.loadTileset(scene2, multipleContentsUrl).then( function(tileset) { const statistics = tileset.statistics; expect(statistics.numberOfAttemptedRequests).toBe(0); expect(statistics.numberOfPendingRequests).toBe(0); expect(statistics.numberOfTilesProcessing).toBe(0); expect(statistics.numberOfTilesWithContentReady).toBe(1); } ); }); it("request statistics are updated for partial success", async function() { const originalLoadJson = import__447.Cesium3DTileset.loadJson; spyOn(import__447.Cesium3DTileset, "loadJson").and.callFake(function(tilesetUrl2) { return originalLoadJson(tilesetUrl2).then(function(tilesetJson) { const contents = tilesetJson.root.contents; const badTile = { uri: "nonexistent.b3dm" }; contents.splice(1, 0, badTile); return tilesetJson; }); }); viewNothing(); const tileset = await import__447.Cesium3DTileset.fromUrl(multipleContentsUrl); scene2.primitives.add(tileset); viewAllTiles(); scene2.renderForSpecs(); const statistics = tileset.statistics; expect(statistics.numberOfAttemptedRequests).toBe(0); expect(statistics.numberOfPendingRequests).toBe(3); expect(statistics.numberOfTilesProcessing).toBe(0); expect(statistics.numberOfTilesWithContentReady).toBe(0); await pollToPromise_default(() => { scene2.renderForSpecs(); return tileset.root._contentState === import__447.Cesium3DTileContentState.PROCESSING; }); expect(statistics.numberOfAttemptedRequests).toBe(0); expect(statistics.numberOfPendingRequests).toBe(0); expect(statistics.numberOfTilesProcessing).toBe(1); expect(statistics.numberOfTilesWithContentReady).toBe(0); await Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); expect(statistics.numberOfAttemptedRequests).toBe(0); expect(statistics.numberOfPendingRequests).toBe(0); expect(statistics.numberOfTilesProcessing).toBe(0); expect(statistics.numberOfTilesWithContentReady).toBe(1); }); it("request statistics are updated correctly if requests are not scheduled", function() { viewNothing(); return Cesium3DTilesTester_default.loadTileset(scene2, multipleContentsUrl).then( function(tileset) { const oldMaximumRequestsPerServer = import__447.RequestScheduler.maximumRequestsPerServer; import__447.RequestScheduler.maximumRequestsPerServer = 1; viewAllTiles(); scene2.renderForSpecs(); const statistics = tileset.statistics; expect(statistics.numberOfAttemptedRequests).toBe(2); expect(statistics.numberOfPendingRequests).toBe(0); expect(statistics.numberOfTilesProcessing).toBe(0); expect(statistics.numberOfTilesWithContentReady).toBe(0); import__447.RequestScheduler.maximumRequestsPerServer = oldMaximumRequestsPerServer; } ); }); it("statistics update correctly if tile is canceled", async function() { viewNothing(); const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, multipleContentsUrl ); let callCount = 0; tileset.tileFailed.addEventListener(function(event) { callCount++; }); viewAllTiles(); scene2.renderForSpecs(); const statistics = tileset.statistics; expect(statistics.numberOfAttemptedRequests).toBe(0); expect(statistics.numberOfPendingRequests).toBe(2); expect(statistics.numberOfTilesProcessing).toBe(0); expect(statistics.numberOfTilesWithContentReady).toBe(0); const multipleContents = tileset.root.content; multipleContents.cancelRequests(); await pollToPromise_default(() => { return tileset.root._contentState !== import__447.Cesium3DTileContentState.LOADING; }); expect(statistics.numberOfAttemptedRequests).toBe(2); expect(statistics.numberOfPendingRequests).toBe(0); expect(statistics.numberOfTilesProcessing).toBe(0); expect(statistics.numberOfTilesWithContentReady).toBe(0); await Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); expect(callCount).toBe(0); expect(statistics.numberOfAttemptedRequests).toBe(0); expect(statistics.numberOfPendingRequests).toBe(0); expect(statistics.numberOfTilesProcessing).toBe(0); expect(statistics.numberOfTilesWithContentReady).toBe(1); }); it("verify multiple content statistics", async function() { const tileset = await import__447.Cesium3DTileset.fromUrl( multipleContentsUrl, options ); scene2.primitives.add(tileset); return checkPointAndFeatureCounts(tileset, 35, 0, 132); }); it("calls tileFailed for each content with errors", function() { const originalLoadJson = import__447.Cesium3DTileset.loadJson; spyOn(import__447.Cesium3DTileset, "loadJson").and.callFake(function(tilesetUrl2) { return originalLoadJson(tilesetUrl2).then(function(tilesetJson) { const contents = [ { uri: "nonexistent1.b3dm" }, { uri: "nonexistent2.b3dm" }, { uri: "nonexistent3.b3dm" } ]; tilesetJson.root.contents = contents; return tilesetJson; }); }); const uris = []; viewNothing(); return Cesium3DTilesTester_default.loadTileset(scene2, multipleContentsUrl).then( function(tileset) { tileset.tileFailed.addEventListener(function(event) { uris.push(event.url); }); viewAllTiles(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(uris.length).toBe(3); uris.sort(); const expected = [ "nonexistent1.b3dm", "nonexistent2.b3dm", "nonexistent3.b3dm" ]; for (let i = 0; i < expected.length; i++) { expect(endsWith(uris[i], expected[i])).toBe(true); } } ); } ); }); it("raises tileFailed for external tileset inside multiple contents", async function() { const originalLoadJson = import__447.Cesium3DTileset.loadJson; spyOn(import__447.Cesium3DTileset, "loadJson").and.callFake(function(tilesetUrl2) { return originalLoadJson(tilesetUrl2).then(function(tilesetJson) { const contents = [ { uri: "external.json" }, { uri: "other.json" } ]; tilesetJson.root.contents = contents; return tilesetJson; }); }); viewNothing(); let errorCount = 0; const tileset = await import__447.Cesium3DTileset.fromUrl(multipleContentsUrl); tileset.tileFailed.addEventListener(function(event) { errorCount++; expect(endsWith(event.url, ".json")).toBe(true); expect(event.message).toEqual( "External tilesets are disallowed inside multiple contents" ); }); scene2.primitives.add(tileset); spyOn(import__447.Resource.prototype, "fetchArrayBuffer").and.callFake(function() { const externalTileset = { asset: { version: "1.1" }, root: {} }; const buffer = generateJsonBuffer_default(externalTileset).buffer; return Promise.resolve(buffer); }); viewAllTiles(); await Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); expect(errorCount).toBe(2); }); it("debugColorizeTiles for multiple contents", function() { return checkDebugColorizeTiles(multipleContentsUrl); }); it("debugShowUrl lists each URI", function() { return Cesium3DTilesTester_default.loadTileset(scene2, multipleContentsUrl).then( function(tileset) { tileset.debugShowUrl = true; scene2.renderForSpecs(); expect(tileset._tileDebugLabels).toBeDefined(); const expected = "Urls:\n- batched.b3dm\n- instanced.i3dm"; expect(tileset._tileDebugLabels._labels[0].text).toEqual(expected); tileset.debugShowUrl = false; scene2.renderForSpecs(); expect(tileset._tileDebugLabels).not.toBeDefined(); } ); }); it("renders tileset with multiple contents", function() { const b3dmCommands = 1; const i3dmCommands = scene2.context.instancedArrays ? 1 : 25; const totalCommands = b3dmCommands + i3dmCommands; return Cesium3DTilesTester_default.loadTileset(scene2, multipleContentsUrl).then( function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(1); expect(statistics.numberOfCommands).toEqual(totalCommands); } ); }); it("renders implicit tileset with multiple contents", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitMultipleContentsUrl ).then(function(tileset) { scene2.renderForSpecs(); const statistics = tileset._statistics; expect(statistics.visited).toEqual(6); expect(statistics.numberOfCommands).toEqual(9); }); }); }); describe("3DTILES_multiple_contents", function() { const multipleContentsLegacyUrl = "Data/Cesium3DTiles/MultipleContents/MultipleContents/tileset_1.0.json"; const implicitMultipleContentsLegacyUrl = "Data/Cesium3DTiles/Implicit/ImplicitMultipleContents/tileset_1.0.json"; const multipleContentsLegacyWithContentUrl = "Data/Cesium3DTiles/MultipleContents/MultipleContents/tileset_1.0_content.json"; const implicitMultipleContentsLegacyWithContentUrl = "Data/Cesium3DTiles/Implicit/ImplicitMultipleContents/tileset_1.0_content.json"; it("request statistics are updated correctly on success (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, multipleContentsLegacyUrl ).then(function(tileset) { const statistics = tileset.statistics; expect(statistics.numberOfAttemptedRequests).toBe(0); expect(statistics.numberOfPendingRequests).toBe(0); expect(statistics.numberOfTilesProcessing).toBe(0); expect(statistics.numberOfTilesWithContentReady).toBe(1); }); }); it("request statistics are updated for partial success (legacy)", async function() { const originalLoadJson = import__447.Cesium3DTileset.loadJson; spyOn(import__447.Cesium3DTileset, "loadJson").and.callFake(function(tilesetUrl2) { return originalLoadJson(tilesetUrl2).then(function(tilesetJson) { const content = tilesetJson.root.extensions["3DTILES_multiple_contents"].contents; const badTile = { uri: "nonexistent.b3dm" }; content.splice(1, 0, badTile); return tilesetJson; }); }); viewNothing(); const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, multipleContentsLegacyUrl ); viewAllTiles(); scene2.renderForSpecs(); const statistics = tileset.statistics; expect(statistics.numberOfAttemptedRequests).toBe(0); expect(statistics.numberOfPendingRequests).toBe(3); expect(statistics.numberOfTilesProcessing).toBe(0); expect(statistics.numberOfTilesWithContentReady).toBe(0); await pollToPromise_default(() => { scene2.renderForSpecs(); return tileset.root._contentState === import__447.Cesium3DTileContentState.PROCESSING; }); expect(statistics.numberOfAttemptedRequests).toBe(0); expect(statistics.numberOfPendingRequests).toBe(0); expect(statistics.numberOfTilesProcessing).toBe(1); expect(statistics.numberOfTilesWithContentReady).toBe(0); await Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); expect(statistics.numberOfAttemptedRequests).toBe(0); expect(statistics.numberOfPendingRequests).toBe(0); expect(statistics.numberOfTilesProcessing).toBe(0); expect(statistics.numberOfTilesWithContentReady).toBe(1); }); it("request statistics are updated correctly if requests are not scheduled (legacy)", function() { viewNothing(); return Cesium3DTilesTester_default.loadTileset( scene2, multipleContentsLegacyUrl ).then(function(tileset) { const oldMaximumRequestsPerServer = import__447.RequestScheduler.maximumRequestsPerServer; import__447.RequestScheduler.maximumRequestsPerServer = 1; viewAllTiles(); scene2.renderForSpecs(); const statistics = tileset.statistics; expect(statistics.numberOfAttemptedRequests).toBe(2); expect(statistics.numberOfPendingRequests).toBe(0); expect(statistics.numberOfTilesProcessing).toBe(0); expect(statistics.numberOfTilesWithContentReady).toBe(0); import__447.RequestScheduler.maximumRequestsPerServer = oldMaximumRequestsPerServer; }); }); it("statistics update correctly if tile is canceled (legacy)", async function() { viewNothing(); const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, multipleContentsLegacyUrl ); let callCount = 0; tileset.tileFailed.addEventListener(function(event) { callCount++; }); viewAllTiles(); scene2.renderForSpecs(); const statistics = tileset.statistics; expect(statistics.numberOfAttemptedRequests).toBe(0); expect(statistics.numberOfPendingRequests).toBe(2); expect(statistics.numberOfTilesProcessing).toBe(0); expect(statistics.numberOfTilesWithContentReady).toBe(0); const multipleContents = tileset.root.content; multipleContents.cancelRequests(); await pollToPromise_default(() => { return tileset.root._contentState !== import__447.Cesium3DTileContentState.LOADING; }); expect(statistics.numberOfAttemptedRequests).toBe(2); expect(statistics.numberOfPendingRequests).toBe(0); expect(statistics.numberOfTilesProcessing).toBe(0); expect(statistics.numberOfTilesWithContentReady).toBe(0); await Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); expect(callCount).toBe(0); expect(statistics.numberOfAttemptedRequests).toBe(0); expect(statistics.numberOfPendingRequests).toBe(0); expect(statistics.numberOfTilesProcessing).toBe(0); expect(statistics.numberOfTilesWithContentReady).toBe(1); }); it("verify multiple content statistics (legacy)", async function() { const tileset = await import__447.Cesium3DTileset.fromUrl( multipleContentsLegacyUrl, options ); scene2.primitives.add(tileset); return checkPointAndFeatureCounts(tileset, 35, 0, 132); }); it("calls tileFailed for each content with errors (legacy)", function() { const originalLoadJson = import__447.Cesium3DTileset.loadJson; spyOn(import__447.Cesium3DTileset, "loadJson").and.callFake(function(tilesetUrl2) { return originalLoadJson(tilesetUrl2).then(function(tilesetJson) { const extension = tilesetJson.root.extensions["3DTILES_multiple_contents"]; extension.contents = [ { uri: "nonexistent1.b3dm" }, { uri: "nonexistent2.b3dm" }, { uri: "nonexistent3.b3dm" } ]; return tilesetJson; }); }); const uris = []; viewNothing(); return Cesium3DTilesTester_default.loadTileset( scene2, multipleContentsLegacyUrl ).then(function(tileset) { tileset.tileFailed.addEventListener(function(event) { uris.push(event.url); }); viewAllTiles(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(uris.length).toBe(3); uris.sort(); const expected = [ "nonexistent1.b3dm", "nonexistent2.b3dm", "nonexistent3.b3dm" ]; for (let i = 0; i < expected.length; i++) { expect(endsWith(uris[i], expected[i])).toBe(true); } } ); }); }); it("raises tileFailed for external tileset inside multiple contents (legacy)", function() { const originalLoadJson = import__447.Cesium3DTileset.loadJson; spyOn(import__447.Cesium3DTileset, "loadJson").and.callFake(function(tilesetUrl2) { return originalLoadJson(tilesetUrl2).then(function(tilesetJson) { const extension = tilesetJson.root.extensions["3DTILES_multiple_contents"]; extension.contents = [ { uri: "external.json" }, { uri: "other.json" } ]; return tilesetJson; }); }); spyOn(import__447.Resource.prototype, "fetchArrayBuffer").and.callFake(function() { const externalTileset = { asset: { version: "1.0" }, root: {} }; const buffer = generateJsonBuffer_default(externalTileset).buffer; return Promise.resolve(buffer); }); viewNothing(); return Cesium3DTilesTester_default.loadTileset( scene2, multipleContentsLegacyUrl ).then(function(tileset) { let errorCount = 0; tileset.tileFailed.addEventListener(function(event) { errorCount++; expect(endsWith(event.url, ".json")).toBe(true); expect(event.message).toEqual( "External tilesets are disallowed inside multiple contents" ); }); viewAllTiles(); scene2.renderForSpecs(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(errorCount).toBe(2); } ); }); }); it("debugColorizeTiles for multiple contents (legacy)", function() { return checkDebugColorizeTiles(multipleContentsLegacyUrl); }); it("debugShowUrl lists each URI (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, multipleContentsLegacyUrl ).then(function(tileset) { tileset.debugShowUrl = true; scene2.renderForSpecs(); expect(tileset._tileDebugLabels).toBeDefined(); const expected = "Urls:\n- batched.b3dm\n- instanced.i3dm"; expect(tileset._tileDebugLabels._labels[0].text).toEqual(expected); tileset.debugShowUrl = false; scene2.renderForSpecs(); expect(tileset._tileDebugLabels).not.toBeDefined(); }); }); it("renders tileset with multiple contents (legacy)", function() { const b3dmCommands = 1; const i3dmCommands = scene2.context.instancedArrays ? 1 : 25; const totalCommands = b3dmCommands + i3dmCommands; return Cesium3DTilesTester_default.loadTileset( scene2, multipleContentsLegacyUrl ).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(1); expect(statistics.numberOfCommands).toEqual(totalCommands); }); }); it("renders tileset with multiple contents (legacy with 'content')", function() { const b3dmCommands = 1; const i3dmCommands = scene2.context.instancedArrays ? 1 : 25; const totalCommands = b3dmCommands + i3dmCommands; return Cesium3DTilesTester_default.loadTileset( scene2, multipleContentsLegacyWithContentUrl ).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(1); expect(statistics.numberOfCommands).toEqual(totalCommands); }); }); it("renders implicit tileset with multiple contents (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitMultipleContentsLegacyUrl ).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(6); expect(statistics.numberOfCommands).toEqual(9); }); }); it("renders implicit tileset with multiple contents (legacy with 'content')", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitMultipleContentsLegacyWithContentUrl ).then(function(tileset) { const statistics = tileset._statistics; expect(statistics.visited).toEqual(6); expect(statistics.numberOfCommands).toEqual(9); }); }); }); const tilesetProperties = { author: "Cesium", date: "2021-03-23", centerCartographic: [ -1.3196816996258511, 0.6988767486400521, 45.78600543644279 ], tileCount: 5 }; describe("select feature IDs", function() { const tilesetWithFeatureIdsUrl = "Data/Cesium3DTiles/Metadata/StructuralMetadata/tileset.json"; it("featureIdLabel sets from string", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithFeatureIdsUrl ).then(function(tileset) { expect(tileset.featureIdLabel).toBe("featureId_0"); tileset.featureIdLabel = "buildings"; expect(tileset.featureIdLabel).toBe("buildings"); }); }); it("featureIdLabel sets from integer", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithFeatureIdsUrl ).then(function(tileset) { expect(tileset.featureIdLabel).toBe("featureId_0"); tileset.featureIdLabel = 1; expect(tileset.featureIdLabel).toBe("featureId_1"); }); }); it("instanceFeatureIdLabel sets from string", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithFeatureIdsUrl ).then(function(tileset) { expect(tileset.instanceFeatureIdLabel).toBe("instanceFeatureId_0"); tileset.instanceFeatureIdLabel = "perInstance"; expect(tileset.instanceFeatureIdLabel).toBe("perInstance"); }); }); it("instanceFeatureIdLabel sets from integer", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithFeatureIdsUrl ).then(function(tileset) { expect(tileset.instanceFeatureIdLabel).toBe("instanceFeatureId_0"); tileset.instanceFeatureIdLabel = 1; expect(tileset.instanceFeatureIdLabel).toBe("instanceFeatureId_1"); }); }); }); describe("metadata", function() { const tilesetMetadataUrl = "Data/Cesium3DTiles/Metadata/TilesetMetadata/tileset_1.1.json"; const tilesetWithExternalSchemaUrl = "Data/Cesium3DTiles/Metadata/ExternalSchema/tileset_1.1.json"; const tilesetWithGroupMetadataUrl = "Data/Cesium3DTiles/Metadata/GroupMetadata/tileset_1.1.json"; const tilesetWithExplicitTileMetadataUrl = "Data/Cesium3DTiles/Metadata/TileMetadata/tileset_1.1.json"; const tilesetWithImplicitTileMetadataUrl = "Data/Cesium3DTiles/Metadata/ImplicitTileMetadata/tileset_1.1.json"; const tilesetWithExplicitContentMetadataUrl = "Data/Cesium3DTiles/Metadata/ContentMetadata/tileset_1.1.json"; const tilesetWithImplicitContentMetadataUrl = "Data/Cesium3DTiles/Metadata/ImplicitContentMetadata/tileset_1.1.json"; const tilesetWithExplicitMultipleContentsMetadataUrl = "Data/Cesium3DTiles/Metadata/MultipleContentsWithMetadata/tileset_1.1.json"; const tilesetWithImplicitMultipleContentsMetadataUrl = "Data/Cesium3DTiles/Metadata/ImplicitMultipleContentsWithMetadata/tileset_1.1.json"; const tilesetWithoutRootSchemaTileMetadataUrl = "Data/Cesium3DTiles/Metadata/ExternalTilesetNoRootSchema/ExternalTileMetadata.json"; const tilesetWithoutRootSchemaContentMetadataUrl = "Data/Cesium3DTiles/Metadata/ExternalTilesetNoRootSchema/ExternalContentMetadata.json"; it("loads tileset metadata", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetMetadataUrl).then( function(tileset) { const tilesetMetadata = tileset.metadata; expect(function() { return tilesetMetadata.getProperty("name"); }).toThrowDeveloperError(); expect(tilesetMetadata.getProperty("author")).toBe( tilesetProperties.author ); expect(tilesetMetadata.getPropertyBySemantic("DATE_ISO_8601")).toBe( tilesetProperties.date ); expect(tilesetMetadata.getProperty("centerCartographic")).toEqual( import__447.Cartesian3.unpack(tilesetProperties.centerCartographic) ); expect(tilesetMetadata.getProperty("tileCount")).toBe( tilesetProperties.tileCount ); } ); }); it("loads group metadata", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithGroupMetadataUrl ).then(function(tileset) { const metadata = tileset.metadataExtension; expect(metadata).toBeDefined(); const groups = metadata.groups; expect(groups).toBeDefined(); let group = groups[1]; expect(group).toBeDefined(); expect(group.getProperty("businessCount")).toBe(143); group = groups[0]; expect(group).toBeDefined(); expect(group.getProperty("population")).toBe(3e5); expect(group.getProperty("neighborhoods")).toEqual([ "Hillside", "Middletown", "Western Heights" ]); }); }); it("can access group metadata through contents", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithGroupMetadataUrl ).then(function(tileset) { const metadata = tileset.metadataExtension; const commercialDistrict = metadata.groups[1]; const residentialDistrict = metadata.groups[0]; const parent = tileset.root; const group = parent.content.group; expect(group).not.toBeDefined(); const expected = { "ul.b3dm": residentialDistrict, "ll.b3dm": residentialDistrict, "ur.b3dm": commercialDistrict, "lr.b3dm": commercialDistrict }; const childrenTiles = parent.children; childrenTiles.forEach(function(tile) { const uri = tile._header.content.uri; expect(tile.content.group.metadata).toBe(expected[uri]); }); }); }); it("loads metadata with embedded schema", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetMetadataUrl).then( function(tileset) { const schema = tileset.schema; expect(schema).toBeDefined(); const classes = schema.classes; expect(classes.tileset).toBeDefined(); } ); }); it("loads metadata with external schema", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithExternalSchemaUrl ).then(function(tileset) { const schema = tileset.schema; expect(schema).toBeDefined(); const classes = schema.classes; expect(classes.tileset).toBeDefined(); }); }); it("loads explicit tileset with tile metadata", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithExplicitTileMetadataUrl ).then(function(tileset) { const expected = { "parent.b3dm": { color: new import__447.Cartesian4(0.5, 0, 1, 1), population: 530, areaPercentage: 100 }, "ll.b3dm": { color: new import__447.Cartesian4(1, 1, 0, 1), population: 50, areaPercentage: 25 }, "lr.b3dm": { color: new import__447.Cartesian4(1, 0, 0.5, 1), population: 230, areaPercentage: 25 }, "ur.b3dm": { color: new import__447.Cartesian4(1, 0.5, 0, 1), population: 150, areaPercentage: 25 }, "ul.b3dm": { color: new import__447.Cartesian4(1, 0, 0, 1), population: 100, areaPercentage: 25 } }; const parent = tileset.root; const tiles = [parent].concat(parent.children); tiles.forEach(function(tile) { const uri = tile._header.content.uri; const expectedValues = expected[uri]; const metadata = tile.metadata; expect(metadata.getProperty("color")).toEqual(expectedValues.color); expect(metadata.getProperty("population")).toEqual( expectedValues.population ); expect(metadata.getProperty("areaPercentage")).toEqualEpsilon( expectedValues.areaPercentage, import__447.Math.EPSILON2 ); }); }); }); it("loads implicit tileset with tile metadata", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithImplicitTileMetadataUrl ).then(function(tileset) { const placeholderTile = tileset.root; const transcodedRoot = placeholderTile.children[0]; const subtree = transcodedRoot.implicitSubtree; expect(subtree).toBeDefined(); const metadataTable = subtree.tileMetadataTable; expect(metadataTable).toBeDefined(); expect(metadataTable.count).toBe(4); expect(metadataTable.hasProperty("color")).toBe(true); expect(metadataTable.hasProperty("quadrant")).toBe(true); const tileCount = 4; const expectedQuadrants = [ "None", "Southwest", "", "Northwest", "Northeast" ]; const expectedColors = [ new import__447.Cartesian3(255, 255, 255), new import__447.Cartesian3(255, 0, 0), import__447.Cartesian3.ZERO, new import__447.Cartesian3(0, 255, 0), new import__447.Cartesian3(0, 0, 255) ]; const tiles = [transcodedRoot].concat(transcodedRoot.children); expect(tiles.length).toBe(tileCount); let i; for (i = 0; i < tileCount; i++) { const tile = tiles[i]; const index = tile.implicitCoordinates.tileIndex; const metadata = tile.metadata; if (!subtree.tileIsAvailableAtIndex(index)) { expect(metadata.getProperty("quadrant")).not.toBeDefined(); expect(metadata.getProperty("color")).not.toBeDefined(); } else { expect(metadata.getProperty("quadrant")).toBe( expectedQuadrants[index] ); expect(metadata.getProperty("color")).toEqual( expectedColors[index] ); } } }); }); it("gracefully handles external tileset with tile metadata but no root schema", function() { spyOn(import__447.findTileMetadata, "_oneTimeWarning"); return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithoutRootSchemaTileMetadataUrl ).then(function(tileset) { expect(import__447.findTileMetadata._oneTimeWarning).toHaveBeenCalledTimes(5); const parent = tileset.root.children[0]; const tiles = [parent].concat(parent.children); tiles.forEach(function(tile) { expect(tile.metadata).not.toBeDefined(); }); }); }); it("loads explicit tileset with content metadata", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithExplicitContentMetadataUrl ).then(function(tileset) { const expected = { "parent.b3dm": { highlightColor: new import__447.Cartesian3(255, 0, 0), author: "Cesium" }, "ll.b3dm": { highlightColor: new import__447.Cartesian3(255, 255, 255), author: "First Company" }, "lr.b3dm": { highlightColor: new import__447.Cartesian3(255, 0, 255), author: "Second Company" }, "ur.b3dm": { highlightColor: new import__447.Cartesian3(0, 255, 0), author: "Third Company" }, "ul.b3dm": { highlightColor: new import__447.Cartesian3(0, 0, 255), author: "Fourth Company" } }; const parent = tileset.root; const tiles = [parent].concat(parent.children); tiles.forEach(function(tile) { const uri = tile._header.content.uri; const content = tile.content; const expectedValues = expected[uri]; const metadata = content.metadata; expect(metadata.getProperty("highlightColor")).toEqual( expectedValues.highlightColor ); expect(metadata.getProperty("author")).toEqual( expectedValues.author ); }); }); }); it("loads implicit tileset with content metadata", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithImplicitContentMetadataUrl ).then(function(tileset) { const placeholderTile = tileset.root; const transcodedRoot = placeholderTile.children[0]; const subtree = transcodedRoot.implicitSubtree; expect(subtree).toBeDefined(); const metadataTables = subtree.contentMetadataTables; expect(metadataTables.length).toBe(1); const metadataTable = metadataTables[0]; expect(metadataTable.count).toBe(4); expect(metadataTable.hasProperty("height")).toBe(true); expect(metadataTable.hasProperty("color")).toBe(true); const tileCount = 4; const expectedHeights = [10, 20, 0, 30, 40]; const expectedColors = [ new import__447.Cartesian3(255, 255, 255), new import__447.Cartesian3(255, 0, 0), import__447.Cartesian3.ZERO, new import__447.Cartesian3(0, 255, 0), new import__447.Cartesian3(0, 0, 255) ]; const tiles = [transcodedRoot].concat(transcodedRoot.children); expect(tiles.length).toBe(tileCount); let i; for (i = 0; i < tileCount; i++) { const tile = tiles[i]; const content = tile.content; const index = tile.implicitCoordinates.tileIndex; const metadata = content.metadata; if (!subtree.contentIsAvailableAtIndex(index, 0)) { expect(metadata.getProperty("height")).not.toBeDefined(); expect(metadata.getProperty("color")).not.toBeDefined(); } else { expect(metadata.getProperty("height")).toBe( expectedHeights[index] ); expect(metadata.getProperty("color")).toEqual( expectedColors[index] ); } } }); }); it("gracefully handles external tileset with content metadata but no root schema", function() { spyOn(import__447.findContentMetadata, "_oneTimeWarning"); return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithoutRootSchemaContentMetadataUrl ).then(function(tileset) { expect(import__447.findContentMetadata._oneTimeWarning).toHaveBeenCalledTimes(5); const parent = tileset.root.children[0]; const tiles = [parent].concat(parent.children); tiles.forEach(function(tile) { expect(tile.content).toBeDefined(); expect(tile.content.metadata).not.toBeDefined(); }); }); }); it("loads explicit tileset with multiple contents with metadata", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithExplicitMultipleContentsMetadataUrl ).then(function(tileset) { const content = tileset.root.content; const batchedContent = content.innerContents[0]; const batchedContentMetadata = batchedContent.metadata; expect(batchedContentMetadata.getProperty("highlightColor")).toEqual( new import__447.Cartesian3(0, 0, 255) ); expect(batchedContentMetadata.getProperty("author")).toEqual( "Cesium" ); expect(batchedContentMetadata.hasProperty("numberOfInstances")).toBe( false ); const instancedContent = content.innerContents[1]; const instancedContentMetadata = instancedContent.metadata; expect( instancedContentMetadata.getProperty("numberOfInstances") ).toEqual(50); expect(instancedContentMetadata.getProperty("author")).toEqual( "Sample Author" ); expect(instancedContentMetadata.hasProperty("highlightColor")).toBe( false ); }); }); it("loads implicit tileset with multiple contents with metadata", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithImplicitMultipleContentsMetadataUrl ).then(function(tileset) { const placeholderTile = tileset.root; const transcodedRoot = placeholderTile.children[0]; const subtree = transcodedRoot.implicitSubtree; expect(subtree).toBeDefined(); const metadataTables = subtree.contentMetadataTables; expect(metadataTables.length).toBe(2); const buildingMetadataTable = metadataTables[0]; const treeMetadataTable = metadataTables[1]; expect(buildingMetadataTable.count).toBe(5); expect(buildingMetadataTable.hasProperty("height")).toBe(true); expect(buildingMetadataTable.hasProperty("color")).toBe(true); expect(treeMetadataTable.count).toBe(4); expect(treeMetadataTable.hasProperty("age")).toBe(true); const tileCount = 5; const expectedHeights = [10, 20, 30, 40, 50]; const expectedColors = [ new import__447.Cartesian3(255, 255, 255), new import__447.Cartesian3(255, 0, 0), new import__447.Cartesian3(255, 255, 0), new import__447.Cartesian3(0, 255, 0), new import__447.Cartesian3(0, 0, 255) ]; const expectedAges = [21, 7, 11, 16]; const tiles = [transcodedRoot].concat(transcodedRoot.children); expect(tiles.length).toBe(tileCount); let i; for (i = 0; i < tileCount; i++) { const tile = tiles[i]; const index = tile.implicitCoordinates.tileIndex; let buildingMetadata; if (i > 0) { expect(tile.hasMultipleContents).toBe(true); const buildingContent = tile.content.innerContents[0]; buildingMetadata = buildingContent.metadata; } else { expect(tile.hasMultipleContents).toBe(false); buildingMetadata = tile.content.metadata; } expect(buildingMetadata.getProperty("height")).toBe( expectedHeights[index] ); expect(buildingMetadata.getProperty("color")).toEqual( expectedColors[index] ); if (i === 0) { continue; } const treeContent = tile.content.innerContents[1]; const treeMetadata = treeContent.metadata; expect(treeMetadata.getProperty("age")).toEqual( expectedAges[index - 1] ); } }); }); }); describe("3DTILES_metadata", function() { const tilesetMetadataLegacyUrl = "Data/Cesium3DTiles/Metadata/TilesetMetadata/tileset_1.0.json"; const tilesetWithExternalSchemaLegacyUrl = "Data/Cesium3DTiles/Metadata/ExternalSchema/tileset_1.0.json"; const tilesetWithGroupMetadataLegacyUrl = "Data/Cesium3DTiles/Metadata/GroupMetadata/tileset_1.0.json"; const tilesetWithExplicitTileMetadataLegacyUrl = "Data/Cesium3DTiles/Metadata/TileMetadata/tileset_1.0.json"; const tilesetWithImplicitTileMetadataLegacyUrl = "Data/Cesium3DTiles/Metadata/ImplicitTileMetadata/tileset_1.0.json"; const tilesetWithExplicitContentMetadataLegacyUrl = "Data/Cesium3DTiles/Metadata/ContentMetadata/tileset_1.0.json"; const tilesetWithImplicitContentMetadataLegacyUrl = "Data/Cesium3DTiles/Metadata/ImplicitContentMetadata/tileset_1.0.json"; const tilesetWithExplicitMultipleContentsMetadataLegacyUrl = "Data/Cesium3DTiles/Metadata/MultipleContentsWithMetadata/tileset_1.0.json"; const tilesetWithImplicitMultipleContentsMetadataLegacyUrl = "Data/Cesium3DTiles/Metadata/ImplicitMultipleContentsWithMetadata/tileset_1.0.json"; it("loads tileset metadata (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetMetadataLegacyUrl ).then(function(tileset) { const metadata = tileset.metadataExtension; expect(metadata).toBeDefined(); const tilesetMetadata = metadata.tileset; expect(function() { return tilesetMetadata.getProperty("name"); }).toThrowDeveloperError(); expect(tilesetMetadata.getProperty("author")).toBe( tilesetProperties.author ); expect(tilesetMetadata.getPropertyBySemantic("DATE_ISO_8601")).toBe( tilesetProperties.date ); expect(tilesetMetadata.getProperty("centerCartographic")).toEqual( import__447.Cartesian3.unpack(tilesetProperties.centerCartographic) ); expect(tilesetMetadata.getProperty("tileCount")).toBe( tilesetProperties.tileCount ); }); }); it("loads group metadata (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithGroupMetadataLegacyUrl ).then(function(tileset) { const metadata = tileset.metadataExtension; expect(metadata).toBeDefined(); const groups = metadata.groups; const groupIds = metadata.groupIds; expect(groups).toBeDefined(); expect(groupIds).toEqual([ "commercialDistrict", "residentialDistrict" ]); let group = groups[0]; expect(group).toBeDefined(); expect(group.getProperty("businessCount")).toBe(143); group = groups[1]; expect(group).toBeDefined(); expect(group.getProperty("population")).toBe(3e5); expect(group.getProperty("neighborhoods")).toEqual([ "Hillside", "Middletown", "Western Heights" ]); }); }); it("can access group metadata through contents (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithGroupMetadataLegacyUrl ).then(function(tileset) { const metadata = tileset.metadataExtension; const commercialDistrict = metadata.groups[0]; const residentialDistrict = metadata.groups[1]; const parent = tileset.root; const group = parent.content.group; expect(group).not.toBeDefined(); const expected = { "ul.b3dm": residentialDistrict, "ll.b3dm": residentialDistrict, "ur.b3dm": commercialDistrict, "lr.b3dm": commercialDistrict }; const childrenTiles = parent.children; childrenTiles.forEach(function(tile) { const uri = tile._header.content.uri; expect(tile.content.group.metadata).toBe(expected[uri]); }); }); }); it("loads metadata with embedded schema (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetMetadataLegacyUrl ).then(function(tileset) { const schema = tileset.schema; expect(schema).toBeDefined(); const classes = schema.classes; expect(classes.tileset).toBeDefined(); }); }); it("loads metadata with external schema and extension (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithExternalSchemaLegacyUrl ).then(function(tileset) { const schema = tileset.schema; expect(schema).toBeDefined(); const classes = schema.classes; expect(classes.tileset).toBeDefined(); }); }); it("loads explicit tileset with tile metadata (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithExplicitTileMetadataLegacyUrl ).then(function(tileset) { const expected = { "parent.b3dm": { color: new import__447.Cartesian4(0.5, 0, 1, 1), population: 530, areaPercentage: 100 }, "ll.b3dm": { color: new import__447.Cartesian4(1, 1, 0, 1), population: 50, areaPercentage: 25 }, "lr.b3dm": { color: new import__447.Cartesian4(1, 0, 0.5, 1), population: 230, areaPercentage: 25 }, "ur.b3dm": { color: new import__447.Cartesian4(1, 0.5, 0, 1), population: 150, areaPercentage: 25 }, "ul.b3dm": { color: new import__447.Cartesian4(1, 0, 0, 1), population: 100, areaPercentage: 25 } }; const parent = tileset.root; const tiles = [parent].concat(parent.children); tiles.forEach(function(tile) { const uri = tile._header.content.uri; const expectedValues = expected[uri]; const metadata = tile.metadata; expect(metadata.getProperty("color")).toEqual(expectedValues.color); expect(metadata.getProperty("population")).toEqual( expectedValues.population ); expect(metadata.getProperty("areaPercentage")).toEqualEpsilon( expectedValues.areaPercentage, import__447.Math.EPSILON2 ); }); }); }); it("loads implicit tileset with tile metadata (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithImplicitTileMetadataLegacyUrl ).then(function(tileset) { const placeholderTile = tileset.root; const transcodedRoot = placeholderTile.children[0]; const subtree = transcodedRoot.implicitSubtree; expect(subtree).toBeDefined(); const metadataTable = subtree.tileMetadataTable; expect(metadataTable).toBeDefined(); expect(metadataTable.count).toBe(4); expect(metadataTable.hasProperty("color")).toBe(true); expect(metadataTable.hasProperty("quadrant")).toBe(true); const tileCount = 4; const expectedQuadrants = [ "None", "Southwest", "", "Northwest", "Northeast" ]; const expectedColors = [ new import__447.Cartesian3(255, 255, 255), new import__447.Cartesian3(255, 0, 0), import__447.Cartesian3.ZERO, new import__447.Cartesian3(0, 255, 0), new import__447.Cartesian3(0, 0, 255) ]; const tiles = [transcodedRoot].concat(transcodedRoot.children); expect(tiles.length).toBe(tileCount); let i; for (i = 0; i < tileCount; i++) { const tile = tiles[i]; const index = tile.implicitCoordinates.tileIndex; const metadata = tile.metadata; if (!subtree.tileIsAvailableAtIndex(index)) { expect(metadata.getProperty("quadrant")).not.toBeDefined(); expect(metadata.getProperty("color")).not.toBeDefined(); } else { expect(metadata.getProperty("quadrant")).toBe( expectedQuadrants[index] ); expect(metadata.getProperty("color")).toEqual( expectedColors[index] ); } } }); }); it("loads explicit tileset with content metadata (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithExplicitContentMetadataLegacyUrl ).then(function(tileset) { const expected = { "parent.b3dm": { highlightColor: new import__447.Cartesian3(255, 0, 0), author: "Cesium" }, "ll.b3dm": { highlightColor: new import__447.Cartesian3(255, 255, 255), author: "First Company" }, "lr.b3dm": { highlightColor: new import__447.Cartesian3(255, 0, 255), author: "Second Company" }, "ur.b3dm": { highlightColor: new import__447.Cartesian3(0, 255, 0), author: "Third Company" }, "ul.b3dm": { highlightColor: new import__447.Cartesian3(0, 0, 255), author: "Fourth Company" } }; const parent = tileset.root; const tiles = [parent].concat(parent.children); tiles.forEach(function(tile) { const uri = tile._header.content.uri; const content = tile.content; const expectedValues = expected[uri]; const metadata = content.metadata; expect(metadata.getProperty("highlightColor")).toEqual( expectedValues.highlightColor ); expect(metadata.getProperty("author")).toEqual( expectedValues.author ); }); }); }); it("loads implicit tileset with content metadata (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithImplicitContentMetadataLegacyUrl ).then(function(tileset) { const placeholderTile = tileset.root; const transcodedRoot = placeholderTile.children[0]; const subtree = transcodedRoot.implicitSubtree; expect(subtree).toBeDefined(); const metadataTables = subtree.contentMetadataTables; expect(metadataTables.length).toBe(1); const metadataTable = metadataTables[0]; expect(metadataTable.count).toBe(4); expect(metadataTable.hasProperty("height")).toBe(true); expect(metadataTable.hasProperty("color")).toBe(true); const tileCount = 4; const expectedHeights = [10, 20, 0, 30, 40]; const expectedColors = [ new import__447.Cartesian3(255, 255, 255), new import__447.Cartesian3(255, 0, 0), import__447.Cartesian3.ZERO, new import__447.Cartesian3(0, 255, 0), new import__447.Cartesian3(0, 0, 255) ]; const tiles = [transcodedRoot].concat(transcodedRoot.children); expect(tiles.length).toBe(tileCount); let i; for (i = 0; i < tileCount; i++) { const tile = tiles[i]; const content = tile.content; const index = tile.implicitCoordinates.tileIndex; const metadata = content.metadata; if (!subtree.contentIsAvailableAtIndex(index, 0)) { expect(metadata.getProperty("height")).not.toBeDefined(); expect(metadata.getProperty("color")).not.toBeDefined(); } else { expect(metadata.getProperty("height")).toBe( expectedHeights[index] ); expect(metadata.getProperty("color")).toEqual( expectedColors[index] ); } } }); }); it("loads explicit tileset with multiple contents with metadata (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithExplicitMultipleContentsMetadataLegacyUrl ).then(function(tileset) { const content = tileset.root.content; const batchedContent = content.innerContents[0]; const batchedContentMetadata = batchedContent.metadata; expect(batchedContentMetadata.getProperty("highlightColor")).toEqual( new import__447.Cartesian3(0, 0, 255) ); expect(batchedContentMetadata.getProperty("author")).toEqual( "Cesium" ); expect(batchedContentMetadata.hasProperty("numberOfInstances")).toBe( false ); const instancedContent = content.innerContents[1]; const instancedContentMetadata = instancedContent.metadata; expect( instancedContentMetadata.getProperty("numberOfInstances") ).toEqual(50); expect(instancedContentMetadata.getProperty("author")).toEqual( "Sample Author" ); expect(instancedContentMetadata.hasProperty("highlightColor")).toBe( false ); }); }); it("loads implicit tileset with multiple contents with metadata (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithImplicitMultipleContentsMetadataLegacyUrl ).then(function(tileset) { const placeholderTile = tileset.root; const transcodedRoot = placeholderTile.children[0]; const subtree = transcodedRoot.implicitSubtree; expect(subtree).toBeDefined(); const metadataTables = subtree.contentMetadataTables; expect(metadataTables.length).toBe(2); const buildingMetadataTable = metadataTables[0]; const treeMetadataTable = metadataTables[1]; expect(buildingMetadataTable.count).toBe(5); expect(buildingMetadataTable.hasProperty("height")).toBe(true); expect(buildingMetadataTable.hasProperty("color")).toBe(true); expect(treeMetadataTable.count).toBe(4); expect(treeMetadataTable.hasProperty("age")).toBe(true); const tileCount = 5; const expectedHeights = [10, 20, 30, 40, 50]; const expectedColors = [ new import__447.Cartesian3(255, 255, 255), new import__447.Cartesian3(255, 0, 0), new import__447.Cartesian3(255, 255, 0), new import__447.Cartesian3(0, 255, 0), new import__447.Cartesian3(0, 0, 255) ]; const expectedAges = [21, 7, 11, 16]; const tiles = [transcodedRoot].concat(transcodedRoot.children); expect(tiles.length).toBe(tileCount); let i; for (i = 0; i < tileCount; i++) { const tile = tiles[i]; const index = tile.implicitCoordinates.tileIndex; let buildingMetadata; if (i > 0) { expect(tile.hasMultipleContents).toBe(true); const buildingContent = tile.content.innerContents[0]; buildingMetadata = buildingContent.metadata; } else { expect(tile.hasMultipleContents).toBe(false); buildingMetadata = tile.content.metadata; } expect(buildingMetadata.getProperty("height")).toBe( expectedHeights[index] ); expect(buildingMetadata.getProperty("color")).toEqual( expectedColors[index] ); if (i === 0) { continue; } const treeContent = tile.content.innerContents[1]; const treeMetadata = treeContent.metadata; expect(treeMetadata.getProperty("age")).toEqual( expectedAges[index - 1] ); } }); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/CircleEmitterSpec.js var import__448 = __toESM(require_Cesium(), 1); describe("Scene/CircleEmitter", function() { let emitter; it("default constructor", function() { emitter = new import__448.CircleEmitter(); expect(emitter.radius).toEqual(1); }); it("constructor", function() { emitter = new import__448.CircleEmitter(5); expect(emitter.radius).toEqual(5); }); it("constructor throws with invalid radius", function() { expect(function() { emitter = new import__448.CircleEmitter(0); }).toThrowDeveloperError(); expect(function() { emitter = new import__448.CircleEmitter(-1); }).toThrowDeveloperError(); }); it("radius setter", function() { emitter = new import__448.CircleEmitter(); emitter.radius = 5; expect(emitter.radius).toEqual(5); }); it("radius setter throws with invalid value", function() { emitter = new import__448.CircleEmitter(); expect(function() { emitter.radius = void 0; }).toThrowDeveloperError(); expect(function() { emitter.radius = 0; }).toThrowDeveloperError(); expect(function() { emitter.radius = -1; }).toThrowDeveloperError(); }); it("emits", function() { emitter = new import__448.CircleEmitter(5); const particle = new import__448.Particle(); for (let i = 0; i < 1e3; ++i) { emitter.emit(particle); expect(import__448.Cartesian3.magnitude(particle.position)).toBeLessThanOrEqual( emitter.radius ); expect(particle.position.z).toEqual(0); expect(particle.velocity).toEqual(import__448.Cartesian3.UNIT_Z); } }); }); // packages/engine/Specs/Scene/ClassificationPrimitiveSpec.js var import__449 = __toESM(require_Cesium(), 1); describe( "Scene/ClassificationPrimitive", function() { let scene2; let ellipsoid; let rectangle; let depthColor; let boxColor; let boxInstance; let primitive; let globePrimitive; let tilesetPrimitive; let reusableGlobePrimitive; let reusableTilesetPrimitive; function createPrimitive(rectangle2, pass) { let renderState; if (pass === import__449.Pass.CESIUM_3D_TILE) { renderState = import__449.RenderState.fromCache({ stencilTest: import__449.StencilConstants.setCesium3DTileBit(), stencilMask: import__449.StencilConstants.CESIUM_3D_TILE_MASK, depthTest: { enabled: true } }); } const depthColorAttribute = import__449.ColorGeometryInstanceAttribute.fromColor( new import__449.Color(0, 0, 1, 1) ); depthColor = depthColorAttribute.value; return new import__449.Primitive({ geometryInstances: new import__449.GeometryInstance({ geometry: new import__449.RectangleGeometry({ ellipsoid: import__449.Ellipsoid.WGS84, rectangle: rectangle2 }), id: "depth rectangle", attributes: { color: depthColorAttribute } }), appearance: new import__449.PerInstanceColorAppearance({ translucent: false, flat: true, renderState }), asynchronous: false }); } function MockPrimitive(primitive2, pass) { this._primitive = primitive2; this._pass = pass; this.show = true; } MockPrimitive.prototype.update = function(frameState2) { if (!this.show) { return; } const commandList = frameState2.commandList; const startLength = commandList.length; this._primitive.update(frameState2); for (let i = startLength; i < commandList.length; ++i) { const command = commandList[i]; command.pass = this._pass; } }; MockPrimitive.prototype.isDestroyed = function() { return false; }; MockPrimitive.prototype.destroy = function() { return (0, import__449.destroyObject)(this); }; beforeAll(function() { scene2 = createScene_default(); scene2.postProcessStages.fxaa.enabled = false; ellipsoid = import__449.Ellipsoid.WGS84; rectangle = import__449.Rectangle.fromDegrees(-75, 25, -70, 30); reusableGlobePrimitive = createPrimitive(rectangle, import__449.Pass.GLOBE); reusableTilesetPrimitive = createPrimitive( rectangle, import__449.Pass.CESIUM_3D_TILE ); }); afterAll(function() { reusableGlobePrimitive.destroy(); reusableTilesetPrimitive.destroy(); scene2.destroyForSpecs(); }); beforeEach(function() { scene2.morphTo3D(0); globePrimitive = new MockPrimitive(reusableGlobePrimitive, import__449.Pass.GLOBE); tilesetPrimitive = new MockPrimitive( reusableTilesetPrimitive, import__449.Pass.CESIUM_3D_TILE ); const center = import__449.Rectangle.center(rectangle); const origin = ellipsoid.cartographicToCartesian(center); const modelMatrix = import__449.Transforms.eastNorthUpToFixedFrame(origin); const dimensions = new import__449.Cartesian3(1e6, 1e6, 1e6); const boxColorAttribute = import__449.ColorGeometryInstanceAttribute.fromColor( new import__449.Color(1, 1, 0, 1) ); boxColor = boxColorAttribute.value; boxInstance = new import__449.GeometryInstance({ geometry: import__449.BoxGeometry.fromDimensions({ dimensions }), modelMatrix, id: "box", attributes: { color: boxColorAttribute } }); }); afterEach(function() { scene2.primitives.removeAll(); primitive = primitive && !primitive.isDestroyed() && primitive.destroy(); globePrimitive = globePrimitive && !globePrimitive.isDestroyed() && globePrimitive.destroy(); tilesetPrimitive = tilesetPrimitive && !tilesetPrimitive.isDestroyed() && tilesetPrimitive.destroy(); }); it("default constructs", function() { primitive = new import__449.ClassificationPrimitive(); expect(primitive.geometryInstances).not.toBeDefined(); expect(primitive.show).toEqual(true); expect(primitive.vertexCacheOptimize).toEqual(false); expect(primitive.interleave).toEqual(false); expect(primitive.compressVertices).toEqual(true); expect(primitive.releaseGeometryInstances).toEqual(true); expect(primitive.allowPicking).toEqual(true); expect(primitive.asynchronous).toEqual(true); expect(primitive.debugShowBoundingVolume).toEqual(false); expect(primitive.debugShowShadowVolume).toEqual(false); }); it("constructs with options", function() { const geometryInstances = []; primitive = new import__449.ClassificationPrimitive({ geometryInstances, show: false, vertexCacheOptimize: true, interleave: true, compressVertices: false, releaseGeometryInstances: false, allowPicking: false, asynchronous: false, debugShowBoundingVolume: true, debugShowShadowVolume: true }); expect(primitive.geometryInstances).toEqual(geometryInstances); expect(primitive.show).toEqual(false); expect(primitive.vertexCacheOptimize).toEqual(true); expect(primitive.interleave).toEqual(true); expect(primitive.compressVertices).toEqual(false); expect(primitive.releaseGeometryInstances).toEqual(false); expect(primitive.allowPicking).toEqual(false); expect(primitive.asynchronous).toEqual(false); expect(primitive.debugShowBoundingVolume).toEqual(true); expect(primitive.debugShowShadowVolume).toEqual(true); }); it("releases geometry instances when releaseGeometryInstances is true", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, releaseGeometryInstances: true, asynchronous: false }); expect(primitive.geometryInstances).toBeDefined(); scene2.primitives.add(primitive); scene2.renderForSpecs(); expect(primitive.geometryInstances).not.toBeDefined(); }); it("does not release geometry instances when releaseGeometryInstances is false", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, releaseGeometryInstances: false, asynchronous: false }); expect(primitive.geometryInstances).toBeDefined(); scene2.primitives.add(primitive); scene2.renderForSpecs(); expect(primitive.geometryInstances).toBeDefined(); }); it("does not render when geometryInstances is undefined", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: void 0, appearance: new import__449.PerInstanceColorAppearance(), asynchronous: false }); scene2.primitives.add(primitive); scene2.renderForSpecs(); expect(scene2.frameState.commandList.length).toEqual(0); }); it("does not render when show is false", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); scene2.primitives.add(primitive); scene2.renderForSpecs(); expect(scene2.frameState.commandList.length).toBeGreaterThan(0); primitive.show = false; scene2.renderForSpecs(); expect(scene2.frameState.commandList.length).toEqual(0); }); it("becomes ready when show is false", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = scene2.primitives.add( new import__449.ClassificationPrimitive({ geometryInstances: boxInstance }) ); primitive.show = false; return pollToPromise_default(function() { scene2.renderForSpecs(); return primitive.ready; }).then(function() { expect(primitive.ready).toEqual(true); }); }); it("does not render other than for the color or pick pass", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); const frameState2 = scene2.frameState; frameState2.passes.render = false; frameState2.passes.pick = false; primitive.update(frameState2); expect(frameState2.commandList.length).toEqual(0); }); function expectRender(color) { expect(scene2).toRender(color); } function expectRenderBlank() { expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba[0]).toEqual(0); }); } function verifyClassificationPrimitiveRender(primitive2, color) { scene2.camera.setView({ destination: rectangle }); scene2.primitives.add(globePrimitive); scene2.primitives.add(tilesetPrimitive); expectRenderBlank(); scene2.primitives.add(primitive2); primitive2.classificationType = import__449.ClassificationType.BOTH; globePrimitive.show = false; tilesetPrimitive.show = true; expectRender(color); globePrimitive.show = true; tilesetPrimitive.show = false; expectRender(color); primitive2.classificationType = import__449.ClassificationType.CESIUM_3D_TILE; globePrimitive.show = false; tilesetPrimitive.show = true; expectRender(color); globePrimitive.show = true; tilesetPrimitive.show = false; expectRenderBlank(); primitive2.classificationType = import__449.ClassificationType.TERRAIN; globePrimitive.show = false; tilesetPrimitive.show = true; expectRenderBlank(); globePrimitive.show = true; tilesetPrimitive.show = false; expectRender(color); globePrimitive.show = true; tilesetPrimitive.show = true; } it("renders in 3D", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); verifyClassificationPrimitiveRender(primitive, boxColor); }); xit("renders in Columbus view when scene3DOnly is false", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); scene2.morphToColumbusView(0); verifyClassificationPrimitiveRender(primitive, boxColor); }); xit("renders in 2D when scene3DOnly is false", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); scene2.morphTo2D(0); verifyClassificationPrimitiveRender(primitive, boxColor); }); it("renders batched instances", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } const neCarto = import__449.Rectangle.northeast(rectangle); const nwCarto = import__449.Rectangle.northwest(rectangle); const ne = ellipsoid.cartographicToCartesian(neCarto); const nw = ellipsoid.cartographicToCartesian(nwCarto); const direction = import__449.Cartesian3.subtract(ne, nw, new import__449.Cartesian3()); const distance = import__449.Cartesian3.magnitude(direction) * 0.25; import__449.Cartesian3.normalize(direction, direction); import__449.Cartesian3.multiplyByScalar(direction, distance, direction); const center = import__449.Rectangle.center(rectangle); const origin = ellipsoid.cartographicToCartesian(center); const origin1 = import__449.Cartesian3.add(origin, direction, new import__449.Cartesian3()); let modelMatrix = import__449.Transforms.eastNorthUpToFixedFrame(origin1); const dimensions = new import__449.Cartesian3(5e5, 1e6, 1e6); const boxColorAttribute = import__449.ColorGeometryInstanceAttribute.fromColor( new import__449.Color(0, 1, 1, 1) ); const boxInstance1 = new import__449.GeometryInstance({ geometry: import__449.BoxGeometry.fromDimensions({ dimensions }), modelMatrix, id: "box1", attributes: { color: boxColorAttribute } }); import__449.Cartesian3.negate(direction, direction); const origin2 = import__449.Cartesian3.add(origin, direction, new import__449.Cartesian3()); modelMatrix = import__449.Transforms.eastNorthUpToFixedFrame(origin2); const boxInstance2 = new import__449.GeometryInstance({ geometry: import__449.BoxGeometry.fromDimensions({ dimensions }), modelMatrix, id: "box2", attributes: { color: boxColorAttribute } }); primitive = new import__449.ClassificationPrimitive({ geometryInstances: [boxInstance1, boxInstance2], asynchronous: false }); verifyClassificationPrimitiveRender(primitive, boxColorAttribute.value); }); it("renders with invert classification and an opaque color", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } scene2.invertClassification = true; scene2.invertClassificationColor = new import__449.Color(0.25, 0.25, 0.25, 1); boxInstance.attributes.show = new import__449.ShowGeometryInstanceAttribute(true); primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); scene2.camera.setView({ destination: rectangle }); const invertedColor = new Array(4); invertedColor[0] = import__449.Color.floatToByte( import__449.Color.byteToFloat(depthColor[0]) * scene2.invertClassificationColor.red ); invertedColor[1] = import__449.Color.floatToByte( import__449.Color.byteToFloat(depthColor[1]) * scene2.invertClassificationColor.green ); invertedColor[2] = import__449.Color.floatToByte( import__449.Color.byteToFloat(depthColor[2]) * scene2.invertClassificationColor.blue ); invertedColor[3] = 255; scene2.primitives.add(tilesetPrimitive); expect(scene2).toRender(invertedColor); scene2.primitives.add(primitive); expect(scene2).toRender(boxColor); primitive.getGeometryInstanceAttributes("box").show = [0]; expect(scene2).toRender(depthColor); scene2.invertClassification = false; }); it("renders with invert classification and a translucent color", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } if (!import__449.InvertClassification.isTranslucencySupported(scene2.context)) { return; } scene2.invertClassification = true; scene2.invertClassificationColor = new import__449.Color(0.25, 0.25, 0.25, 0.25); boxInstance.attributes.show = new import__449.ShowGeometryInstanceAttribute(true); primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); scene2.camera.setView({ destination: rectangle }); const invertedColor = new Array(4); invertedColor[0] = import__449.Color.floatToByte( import__449.Color.byteToFloat(depthColor[0]) * scene2.invertClassificationColor.red * scene2.invertClassificationColor.alpha ); invertedColor[1] = import__449.Color.floatToByte( import__449.Color.byteToFloat(depthColor[1]) * scene2.invertClassificationColor.green * scene2.invertClassificationColor.alpha ); invertedColor[2] = import__449.Color.floatToByte( import__449.Color.byteToFloat(depthColor[2]) * scene2.invertClassificationColor.blue * scene2.invertClassificationColor.alpha ); invertedColor[3] = 255; scene2.primitives.add(tilesetPrimitive); expect(scene2).toRender(invertedColor); scene2.primitives.add(primitive); expect(scene2).toRender(boxColor); primitive.getGeometryInstanceAttributes("box").show = [0]; expect(scene2).toRender(depthColor); scene2.invertClassification = false; }); it("renders bounding volume with debugShowBoundingVolume", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false, debugShowBoundingVolume: true }); scene2.primitives.add(primitive); scene2.camera.setView({ destination: rectangle }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[1]).toBeGreaterThanOrEqual(0); expect(rgba[1]).toBeGreaterThanOrEqual(0); expect(rgba[2]).toBeGreaterThanOrEqual(0); expect(rgba[3]).toEqual(255); }); }); it("renders shadow volume with debugShowShadowVolume", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false, debugShowShadowVolume: true }); scene2.primitives.add(primitive); scene2.camera.setView({ destination: rectangle }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[1]).toBeGreaterThanOrEqual(0); expect(rgba[1]).toBeGreaterThanOrEqual(0); expect(rgba[2]).toBeGreaterThanOrEqual(0); expect(rgba[3]).toEqual(255); }); }); it("get per instance attributes", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); verifyClassificationPrimitiveRender(primitive, boxColor); const attributes = primitive.getGeometryInstanceAttributes("box"); expect(attributes.color).toBeDefined(); }); it("modify color instance attribute", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); verifyClassificationPrimitiveRender(primitive, boxColor); scene2.primitives.destroyPrimitives = false; scene2.primitives.removeAll(); scene2.primitives.destroyPrimitives = true; scene2.primitives.destroyPrimitives = false; scene2.primitives.removeAll(); scene2.primitives.destroyPrimitives = true; const newColor = [255, 255, 255, 255]; const attributes = primitive.getGeometryInstanceAttributes("box"); expect(attributes.color).toBeDefined(); attributes.color = newColor; verifyClassificationPrimitiveRender(primitive, newColor); }); it("modify show instance attribute", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } boxInstance.attributes.show = new import__449.ShowGeometryInstanceAttribute(true); primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); verifyClassificationPrimitiveRender(primitive, boxColor); scene2.primitives.destroyPrimitives = false; scene2.primitives.removeAll(); scene2.primitives.destroyPrimitives = true; scene2.primitives.destroyPrimitives = false; scene2.primitives.removeAll(); scene2.primitives.destroyPrimitives = true; const attributes = primitive.getGeometryInstanceAttributes("box"); expect(attributes.show).toBeDefined(); attributes.show = [0]; verifyClassificationPrimitiveRender(primitive, depthColor); }); it("get bounding sphere from per instance attribute", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); verifyClassificationPrimitiveRender(primitive, boxColor); const attributes = primitive.getGeometryInstanceAttributes("box"); expect(attributes.boundingSphere).toBeDefined(); }); it("getGeometryInstanceAttributes returns same object each time", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); verifyClassificationPrimitiveRender(primitive, boxColor); const attributes = primitive.getGeometryInstanceAttributes("box"); const attributes2 = primitive.getGeometryInstanceAttributes("box"); expect(attributes).toBe(attributes2); }); it("picking", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); verifyClassificationPrimitiveRender(primitive, boxColor); expect(scene2).toPickAndCall(function(result) { expect(result.id).toEqual("box"); }); }); it("drill picking", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); verifyClassificationPrimitiveRender(primitive, boxColor); expect(scene2).toDrillPickAndCall(function(pickedObjects) { expect(pickedObjects.length).toEqual(3); expect(pickedObjects[0].primitive).toEqual(primitive); expect(pickedObjects[1].primitive).toEqual(globePrimitive._primitive); expect(pickedObjects[2].primitive).toEqual(tilesetPrimitive._primitive); }); }); it("does not pick when allowPicking is false", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, allowPicking: false, asynchronous: false }); verifyClassificationPrimitiveRender(primitive, boxColor); expect(scene2).notToPick(); }); it("internally invalid asynchronous geometry resolves promise and sets ready", async function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: new import__449.GeometryInstance({ geometry: import__449.PolygonGeometry.fromPositions({ positions: [] }), attributes: { color: import__449.ColorGeometryInstanceAttribute.fromColor(import__449.Color.RED) } }), compressVertices: false }); scene2.primitives.add(primitive); await pollToPromise_default(function() { scene2.renderForSpecs(); return primitive.ready; }); expect(primitive.ready).toBe(true); }); it("internally invalid synchronous geometry resolves promise and sets ready", async function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: new import__449.GeometryInstance({ geometry: import__449.PolygonGeometry.fromPositions({ positions: [] }), attributes: { color: import__449.ColorGeometryInstanceAttribute.fromColor(import__449.Color.RED) } }), asynchronous: false, compressVertices: false }); scene2.primitives.add(primitive); await pollToPromise_default(function() { scene2.renderForSpecs(); return primitive.ready; }); expect(primitive.ready).toBe(true); }); it("update throws when batched instance colors are different and no culling attributes are provided", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } const neCarto = import__449.Rectangle.northeast(rectangle); const nwCarto = import__449.Rectangle.northwest(rectangle); const ne = ellipsoid.cartographicToCartesian(neCarto); const nw = ellipsoid.cartographicToCartesian(nwCarto); const direction = import__449.Cartesian3.subtract(ne, nw, new import__449.Cartesian3()); const distance = import__449.Cartesian3.magnitude(direction) * 0.25; import__449.Cartesian3.normalize(direction, direction); import__449.Cartesian3.multiplyByScalar(direction, distance, direction); const center = import__449.Rectangle.center(rectangle); const origin = ellipsoid.cartographicToCartesian(center); const origin1 = import__449.Cartesian3.add(origin, direction, new import__449.Cartesian3()); let modelMatrix = import__449.Transforms.eastNorthUpToFixedFrame(origin1); const dimensions = new import__449.Cartesian3(5e5, 1e6, 1e6); const boxColorAttribute = import__449.ColorGeometryInstanceAttribute.fromColor( new import__449.Color(0, 1, 1, 1) ); const boxInstance1 = new import__449.GeometryInstance({ geometry: import__449.BoxGeometry.fromDimensions({ dimensions }), modelMatrix, id: "box1", attributes: { color: import__449.ColorGeometryInstanceAttribute.fromColor( new import__449.Color(0, 1, 1, 1) ) } }); import__449.Cartesian3.negate(direction, direction); const origin2 = import__449.Cartesian3.add(origin, direction, new import__449.Cartesian3()); modelMatrix = import__449.Transforms.eastNorthUpToFixedFrame(origin2); const boxInstance2 = new import__449.GeometryInstance({ geometry: import__449.BoxGeometry.fromDimensions({ dimensions }), modelMatrix, id: "box2", attributes: { color: import__449.ColorGeometryInstanceAttribute.fromColor( new import__449.Color(1, 0, 1, 1) ) } }); primitive = new import__449.ClassificationPrimitive({ geometryInstances: [boxInstance1, boxInstance2], asynchronous: false }); expect(function() { verifyClassificationPrimitiveRender(primitive, boxColorAttribute.value); }).toThrowDeveloperError(); }); it("update throws when one batched instance color is undefined", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } const neCarto = import__449.Rectangle.northeast(rectangle); const nwCarto = import__449.Rectangle.northwest(rectangle); const ne = ellipsoid.cartographicToCartesian(neCarto); const nw = ellipsoid.cartographicToCartesian(nwCarto); const direction = import__449.Cartesian3.subtract(ne, nw, new import__449.Cartesian3()); const distance = import__449.Cartesian3.magnitude(direction) * 0.25; import__449.Cartesian3.normalize(direction, direction); import__449.Cartesian3.multiplyByScalar(direction, distance, direction); const center = import__449.Rectangle.center(rectangle); const origin = ellipsoid.cartographicToCartesian(center); const origin1 = import__449.Cartesian3.add(origin, direction, new import__449.Cartesian3()); let modelMatrix = import__449.Transforms.eastNorthUpToFixedFrame(origin1); const dimensions = new import__449.Cartesian3(5e5, 1e6, 1e6); const boxColorAttribute = import__449.ColorGeometryInstanceAttribute.fromColor( new import__449.Color(0, 1, 1, 1) ); const boxInstance1 = new import__449.GeometryInstance({ geometry: import__449.BoxGeometry.fromDimensions({ dimensions }), modelMatrix, id: "box1", attributes: { color: import__449.ColorGeometryInstanceAttribute.fromColor( new import__449.Color(0, 1, 1, 1) ) } }); import__449.Cartesian3.negate(direction, direction); const origin2 = import__449.Cartesian3.add(origin, direction, new import__449.Cartesian3()); modelMatrix = import__449.Transforms.eastNorthUpToFixedFrame(origin2); const boxInstance2 = new import__449.GeometryInstance({ geometry: import__449.BoxGeometry.fromDimensions({ dimensions }), modelMatrix, id: "box2" }); primitive = new import__449.ClassificationPrimitive({ geometryInstances: [boxInstance1, boxInstance2], asynchronous: false }); expect(function() { verifyClassificationPrimitiveRender(primitive, boxColorAttribute.value); }).toThrowDeveloperError(); }); it("update throws when no batched instance colors are given for a PerInstanceColorAppearance", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } const neCarto = import__449.Rectangle.northeast(rectangle); const nwCarto = import__449.Rectangle.northwest(rectangle); const ne = ellipsoid.cartographicToCartesian(neCarto); const nw = ellipsoid.cartographicToCartesian(nwCarto); const direction = import__449.Cartesian3.subtract(ne, nw, new import__449.Cartesian3()); const distance = import__449.Cartesian3.magnitude(direction) * 0.25; import__449.Cartesian3.normalize(direction, direction); import__449.Cartesian3.multiplyByScalar(direction, distance, direction); const center = import__449.Rectangle.center(rectangle); const origin = ellipsoid.cartographicToCartesian(center); const origin1 = import__449.Cartesian3.add(origin, direction, new import__449.Cartesian3()); const modelMatrix = import__449.Transforms.eastNorthUpToFixedFrame(origin1); const dimensions = new import__449.Cartesian3(5e5, 1e6, 1e6); const boxInstance1 = new import__449.GeometryInstance({ geometry: import__449.BoxGeometry.fromDimensions({ dimensions }), modelMatrix, id: "box1" }); primitive = new import__449.ClassificationPrimitive({ geometryInstances: [boxInstance1], asynchronous: false, appearance: new import__449.PerInstanceColorAppearance() }); const boxColorAttribute = import__449.ColorGeometryInstanceAttribute.fromColor( new import__449.Color(0, 1, 1, 1) ); expect(function() { verifyClassificationPrimitiveRender(primitive, boxColorAttribute.value); }).toThrowDeveloperError(); }); it("update throws when the given Appearance is incompatible with the geometry instance attributes", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: [boxInstance], asynchronous: false, appearance: new import__449.MaterialAppearance() }); expect(function() { verifyClassificationPrimitiveRender(primitive, [255, 255, 255, 255]); }).toThrowDeveloperError(); }); it("update throws when an incompatible Appearance is set", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: [boxInstance], asynchronous: false, appearance: new import__449.PerInstanceColorAppearance() }); scene2.camera.setView({ destination: rectangle }); scene2.primitives.add(globePrimitive); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba[0]).toEqual(0); }); scene2.primitives.add(primitive); expect(scene2).toRender([255, 255, 0, 255]); primitive.appearance = new import__449.MaterialAppearance(); expect(function() { expect(scene2).toRender([255, 255, 255, 255]); }).toThrowDeveloperError(); }); it("setting per instance attribute throws when value is undefined", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); verifyClassificationPrimitiveRender(primitive, boxColor); const attributes = primitive.getGeometryInstanceAttributes("box"); expect(function() { attributes.color = void 0; }).toThrowDeveloperError(); }); it("can disable picking when asynchronous", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: true, allowPicking: false }); scene2.primitives.add(primitive); return pollToPromise_default(function() { scene2.renderForSpecs(); return primitive.ready; }).then(function() { const attributes = primitive.getGeometryInstanceAttributes("box"); expect(function() { attributes.color = void 0; }).toThrowDeveloperError(); }); }); it("getGeometryInstanceAttributes throws without id", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); verifyClassificationPrimitiveRender(primitive, boxColor); expect(function() { primitive.getGeometryInstanceAttributes(); }).toThrowDeveloperError(); }); it("getGeometryInstanceAttributes throws if update was not called", function() { primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); expect(function() { primitive.getGeometryInstanceAttributes("box"); }).toThrowDeveloperError(); }); it("getGeometryInstanceAttributes returns undefined if id does not exist", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance, asynchronous: false }); verifyClassificationPrimitiveRender(primitive, boxColor); expect( primitive.getGeometryInstanceAttributes("unknown") ).not.toBeDefined(); }); it("isDestroyed", function() { primitive = new import__449.ClassificationPrimitive(); expect(primitive.isDestroyed()).toEqual(false); primitive.destroy(); expect(primitive.isDestroyed()).toEqual(true); }); it("renders when using asynchronous pipeline", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance }); scene2.primitives.add(primitive); return pollToPromise_default(function() { scene2.renderForSpecs(); return primitive.ready; }).then(function() { scene2.primitives.destroyPrimitives = false; scene2.primitives.removeAll(); scene2.primitives.destroyPrimitives = true; verifyClassificationPrimitiveRender(primitive, boxColor); }); }); it("destroy before asynchronous pipeline is complete", function() { if (!import__449.ClassificationPrimitive.isSupported(scene2)) { return; } primitive = new import__449.ClassificationPrimitive({ geometryInstances: boxInstance }); scene2.primitives.add(primitive); scene2.renderForSpecs(); primitive.destroy(); expect(primitive.isDestroyed()).toEqual(true); scene2.primitives.destroyPrimitives = false; scene2.primitives.removeAll(); scene2.primitives.destroyPrimitives = true; }); }, "WebGL" ); // packages/engine/Specs/Scene/ClippingPlaneCollectionSpec.js var import__450 = __toESM(require_Cesium(), 1); describe("Scene/ClippingPlaneCollection", function() { let clippingPlanes; const planes = [ new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, 1), new import__450.ClippingPlane(import__450.Cartesian3.UNIT_Y, 2) ]; const transform = new import__450.Matrix4.fromTranslation(new import__450.Cartesian3(1, 3, 2)); const boundingVolume = new import__450.BoundingSphere(import__450.Cartesian3.ZERO, 1); function decodeUint8Plane(pixel1, pixel2) { const normal = import__450.AttributeCompression.octDecodeFromCartesian4( pixel1, new import__450.Cartesian3() ); const distance = import__450.Cartesian4.unpackFloat(pixel2); return new import__450.Plane(normal, distance); } it("default constructor", function() { clippingPlanes = new import__450.ClippingPlaneCollection(); expect(clippingPlanes._planes).toEqual([]); expect(clippingPlanes.enabled).toEqual(true); expect(clippingPlanes.modelMatrix).toEqual(import__450.Matrix4.IDENTITY); expect(clippingPlanes.edgeColor).toEqual(import__450.Color.WHITE); expect(clippingPlanes.edgeWidth).toEqual(0); expect(clippingPlanes.unionClippingRegions).toEqual(false); expect(clippingPlanes._testIntersection).not.toBeUndefined(); }); it("gets the length of the list of planes in the collection", function() { clippingPlanes = new import__450.ClippingPlaneCollection(); expect(clippingPlanes.length).toBe(0); clippingPlanes._planes = planes.slice(); expect(clippingPlanes.length).toBe(2); clippingPlanes._planes.push(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_Z, -1)); expect(clippingPlanes.length).toBe(3); clippingPlanes = new import__450.ClippingPlaneCollection({ planes }); expect(clippingPlanes.length).toBe(2); }); it("add adds a plane to the collection", function() { clippingPlanes = new import__450.ClippingPlaneCollection(); clippingPlanes.add(planes[0]); expect(clippingPlanes.length).toBe(1); expect(clippingPlanes._planes[0]).toBe(planes[0]); }); it("fires the planeAdded event when a plane is added", function() { clippingPlanes = new import__450.ClippingPlaneCollection(); const spy = jasmine.createSpy(); clippingPlanes.planeAdded.addEventListener(spy); clippingPlanes.add(planes[0]); expect(spy).toHaveBeenCalled(); }); it("gets the plane at an index", function() { clippingPlanes = new import__450.ClippingPlaneCollection({ planes }); let plane = clippingPlanes.get(0); expect(plane).toBe(planes[0]); plane = clippingPlanes.get(1); expect(plane).toBe(planes[1]); plane = clippingPlanes.get(2); expect(plane).toBeUndefined(); }); it("contain checks if the collection contains a plane", function() { clippingPlanes = new import__450.ClippingPlaneCollection({ planes }); expect(clippingPlanes.contains(planes[0])).toBe(true); expect( clippingPlanes.contains(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_Y, 2)) ).toBe(true); expect( clippingPlanes.contains(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_Z, 3)) ).toBe(false); }); it("remove removes and the first occurrence of a plane", function() { clippingPlanes = new import__450.ClippingPlaneCollection({ planes }); expect(clippingPlanes.contains(planes[0])).toBe(true); let result = clippingPlanes.remove(planes[0]); expect(clippingPlanes.contains(planes[0])).toBe(false); expect(clippingPlanes.length).toBe(1); expect(clippingPlanes.get(0)).toEqual(planes[1]); expect(result).toBe(true); result = clippingPlanes.remove(planes[0]); expect(result).toBe(false); }); it("remove fires planeRemoved event", function() { clippingPlanes = new import__450.ClippingPlaneCollection({ planes }); const spy = jasmine.createSpy(); clippingPlanes.planeRemoved.addEventListener(spy); clippingPlanes.remove(planes[0]); expect(spy).toHaveBeenCalled(); }); it("removeAll removes all of the planes in the collection", function() { clippingPlanes = new import__450.ClippingPlaneCollection({ planes }); expect(clippingPlanes.length).toEqual(planes.length); clippingPlanes.removeAll(); expect(clippingPlanes.length).toBe(0); }); it("removeAll fires planeRemoved event", function() { clippingPlanes = new import__450.ClippingPlaneCollection({ planes }); const spy = jasmine.createSpy(); clippingPlanes.planeRemoved.addEventListener(spy); clippingPlanes.removeAll(); expect(spy).toHaveBeenCalled(); }); describe("uint8 texture mode", function() { beforeEach(function() { spyOn(import__450.ClippingPlaneCollection, "useFloatTexture").and.returnValue(false); }); it("update creates a RGBA ubyte texture with no filtering or wrapping to house packed clipping planes", function() { const scene2 = createScene_default(); clippingPlanes = new import__450.ClippingPlaneCollection({ planes, enabled: false, edgeColor: import__450.Color.RED, modelMatrix: transform }); clippingPlanes.update(scene2.frameState); const packedTexture = clippingPlanes.texture; expect(packedTexture).toBeDefined(); expect(packedTexture.width).toEqual(4); expect(packedTexture.height).toEqual(2); expect(packedTexture.pixelFormat).toEqual(import__450.PixelFormat.RGBA); expect(packedTexture.pixelDatatype).toEqual(import__450.PixelDatatype.UNSIGNED_BYTE); const sampler = packedTexture.sampler; expect(sampler.wrapS).toEqual(import__450.TextureWrap.CLAMP_TO_EDGE); expect(sampler.wrapT).toEqual(import__450.TextureWrap.CLAMP_TO_EDGE); expect(sampler.minificationFilter).toEqual( import__450.TextureMinificationFilter.NEAREST ); expect(sampler.magnificationFilter).toEqual( import__450.TextureMinificationFilter.NEAREST ); clippingPlanes.destroy(); scene2.destroyForSpecs(); }); it("only creates texture when planes are added", function() { const scene2 = createScene_default(); clippingPlanes = new import__450.ClippingPlaneCollection(); clippingPlanes.update(scene2.frameState); expect(clippingPlanes.texture).toBeUndefined(); clippingPlanes.add(planes[0]); clippingPlanes.update(scene2.frameState); expect(clippingPlanes.texture).toBeDefined(); expect(isNaN(clippingPlanes.texture.width)).toBe(false); expect(isNaN(clippingPlanes.texture.height)).toBe(false); scene2.destroyForSpecs(); }); it("update fills the clipping plane texture with packed planes", function() { const scene2 = createScene_default(); clippingPlanes = new import__450.ClippingPlaneCollection({ planes, enabled: false, edgeColor: import__450.Color.RED, modelMatrix: transform }); let rgba; const gl = scene2.frameState.context._gl; spyOn(gl, "texImage2D").and.callFake(function(target, level, xoffset, yoffset, width, height, format, type, arrayBufferView) { rgba = arrayBufferView; }); clippingPlanes.update(scene2.frameState); expect(rgba).toBeDefined(); expect(rgba.length).toEqual(32); for (let i = 16; i < rgba.length; i++) { expect(rgba[i]).toEqual(0); } const pixel1 = import__450.Cartesian4.fromArray(rgba, 0); const pixel2 = import__450.Cartesian4.fromArray(rgba, 4); const pixel3 = import__450.Cartesian4.fromArray(rgba, 8); const pixel4 = import__450.Cartesian4.fromArray(rgba, 12); const plane1 = decodeUint8Plane(pixel1, pixel2); const plane2 = decodeUint8Plane(pixel3, pixel4); expect( import__450.Cartesian3.equalsEpsilon( plane1.normal, planes[0].normal, import__450.Math.EPSILON3 ) ).toEqual(true); expect( import__450.Cartesian3.equalsEpsilon( plane2.normal, planes[1].normal, import__450.Math.EPSILON3 ) ).toEqual(true); expect( import__450.Math.equalsEpsilon( plane1.distance, planes[0].distance, import__450.Math.EPSILON3 ) ).toEqual(true); expect( import__450.Math.equalsEpsilon( plane2.distance, planes[1].distance, import__450.Math.EPSILON3 ) ).toEqual(true); clippingPlanes.destroy(); scene2.destroyForSpecs(); }); it("reallocates textures when above capacity or below 1/4 capacity", function() { const scene2 = createScene_default(); clippingPlanes = new import__450.ClippingPlaneCollection({ planes, enabled: false, edgeColor: import__450.Color.RED, modelMatrix: transform }); clippingPlanes.update(scene2.frameState); let packedTexture = clippingPlanes.texture; expect(packedTexture.width).toEqual(4); expect(packedTexture.height).toEqual(2); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, 1)); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, 1)); clippingPlanes.update(scene2.frameState); expect(packedTexture.isDestroyed()).toBe(false); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, 1)); clippingPlanes.update(scene2.frameState); expect(packedTexture.isDestroyed()).toBe(true); packedTexture = clippingPlanes.texture; expect(packedTexture.width).toEqual(10); expect(packedTexture.height).toEqual(2); clippingPlanes.removeAll(); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, 1)); clippingPlanes.update(scene2.frameState); expect(packedTexture.isDestroyed()).toBe(true); packedTexture = clippingPlanes.texture; expect(packedTexture.width).toEqual(2); expect(packedTexture.height).toEqual(2); clippingPlanes.destroy(); scene2.destroyForSpecs(); }); it("performs partial updates when only a single plane has changed and full texture updates otherwise", function() { const scene2 = createScene_default(); const gl = scene2.frameState.context._gl; let copyWidth; let copyHeight; spyOn(gl, "texSubImage2D").and.callFake(function(target, level, xoffset, yoffset, width, height, format, type, arrayBufferView) { copyWidth = width; copyHeight = height; }); clippingPlanes = new import__450.ClippingPlaneCollection({ planes, enabled: false, edgeColor: import__450.Color.RED, modelMatrix: transform }); clippingPlanes.update(scene2.frameState); const packedTexture = clippingPlanes.texture; expect(packedTexture.width).toEqual(4); expect(packedTexture.height).toEqual(2); const targetPlane = new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, 1); clippingPlanes.add(targetPlane); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, 1)); clippingPlanes.update(scene2.frameState); expect(packedTexture.isDestroyed()).toBe(false); expect(gl.texSubImage2D.calls.count()).toEqual(1); expect(copyWidth).toEqual(packedTexture.width); expect(copyHeight).toEqual(packedTexture.height); targetPlane.distance += 1; clippingPlanes.update(scene2.frameState); expect(packedTexture.isDestroyed()).toBe(false); expect(gl.texSubImage2D.calls.count()).toEqual(2); expect(copyWidth).toEqual(2); expect(copyHeight).toEqual(1); clippingPlanes.destroy(); scene2.destroyForSpecs(); }); }); describe("float texture mode", function() { it("update creates a float texture with no filtering or wrapping to house packed clipping planes", function() { const scene2 = createScene_default(); if (!import__450.ClippingPlaneCollection.useFloatTexture(scene2.context)) { scene2.destroyForSpecs(); return; } clippingPlanes = new import__450.ClippingPlaneCollection({ planes, enabled: false, edgeColor: import__450.Color.RED, modelMatrix: transform }); clippingPlanes.update(scene2.frameState); const packedTexture = clippingPlanes.texture; expect(packedTexture).toBeDefined(); expect(packedTexture.width).toEqual(2); expect(packedTexture.height).toEqual(2); expect(packedTexture.pixelFormat).toEqual(import__450.PixelFormat.RGBA); expect(packedTexture.pixelDatatype).toEqual(import__450.PixelDatatype.FLOAT); const sampler = packedTexture.sampler; expect(sampler.wrapS).toEqual(import__450.TextureWrap.CLAMP_TO_EDGE); expect(sampler.wrapT).toEqual(import__450.TextureWrap.CLAMP_TO_EDGE); expect(sampler.minificationFilter).toEqual( import__450.TextureMinificationFilter.NEAREST ); expect(sampler.magnificationFilter).toEqual( import__450.TextureMinificationFilter.NEAREST ); clippingPlanes.destroy(); scene2.destroyForSpecs(); }); it("only creates texture when planes are added", function() { const scene2 = createScene_default(); if (!import__450.ClippingPlaneCollection.useFloatTexture(scene2.context)) { scene2.destroyForSpecs(); return; } clippingPlanes = new import__450.ClippingPlaneCollection(); clippingPlanes.update(scene2.frameState); expect(clippingPlanes.texture).toBeUndefined(); clippingPlanes.add(planes[0]); clippingPlanes.update(scene2.frameState); expect(clippingPlanes.texture).toBeDefined(); expect(isNaN(clippingPlanes.texture.width)).toBe(false); expect(isNaN(clippingPlanes.texture.height)).toBe(false); clippingPlanes.destroy(); scene2.destroyForSpecs(); }); it("update fills the clipping plane texture with packed planes", function() { const scene2 = createScene_default(); if (!import__450.ClippingPlaneCollection.useFloatTexture(scene2.context)) { scene2.destroyForSpecs(); return; } clippingPlanes = new import__450.ClippingPlaneCollection({ planes, enabled: false, edgeColor: import__450.Color.RED, modelMatrix: transform }); let rgba; const gl = scene2.frameState.context._gl; spyOn(gl, "texImage2D").and.callFake(function(target, level, xoffset, yoffset, width, height, format, type, arrayBufferView) { rgba = arrayBufferView; }); clippingPlanes.update(scene2.frameState); expect(rgba).toBeDefined(); expect(rgba.length).toEqual(16); for (let i = 8; i < rgba.length; i++) { expect(rgba[i]).toEqual(0); } const plane1 = import__450.Plane.fromCartesian4(import__450.Cartesian4.fromArray(rgba, 0)); const plane2 = import__450.Plane.fromCartesian4(import__450.Cartesian4.fromArray(rgba, 4)); expect( import__450.Cartesian3.equalsEpsilon( plane1.normal, planes[0].normal, import__450.Math.EPSILON3 ) ).toEqual(true); expect( import__450.Cartesian3.equalsEpsilon( plane2.normal, planes[1].normal, import__450.Math.EPSILON3 ) ).toEqual(true); expect( import__450.Math.equalsEpsilon( plane1.distance, planes[0].distance, import__450.Math.EPSILON3 ) ).toEqual(true); expect( import__450.Math.equalsEpsilon( plane2.distance, planes[1].distance, import__450.Math.EPSILON3 ) ).toEqual(true); clippingPlanes.destroy(); scene2.destroyForSpecs(); }); it("reallocates textures when above capacity or below 1/4 capacity", function() { const scene2 = createScene_default(); if (!import__450.ClippingPlaneCollection.useFloatTexture(scene2.context)) { scene2.destroyForSpecs(); return; } clippingPlanes = new import__450.ClippingPlaneCollection({ planes, enabled: false, edgeColor: import__450.Color.RED, modelMatrix: transform }); clippingPlanes.update(scene2.frameState); let packedTexture = clippingPlanes.texture; expect(packedTexture.width).toEqual(2); expect(packedTexture.height).toEqual(2); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, 1)); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, 1)); clippingPlanes.update(scene2.frameState); expect(packedTexture.isDestroyed()).toBe(false); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, 1)); clippingPlanes.update(scene2.frameState); expect(packedTexture.isDestroyed()).toBe(true); packedTexture = clippingPlanes.texture; expect(packedTexture.width).toEqual(5); expect(packedTexture.height).toEqual(2); clippingPlanes.removeAll(); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, 1)); clippingPlanes.update(scene2.frameState); expect(packedTexture.isDestroyed()).toBe(true); packedTexture = clippingPlanes.texture; expect(packedTexture.width).toEqual(1); expect(packedTexture.height).toEqual(2); clippingPlanes.destroy(); scene2.destroyForSpecs(); }); it("performs partial updates when only a single plane has changed and full texture updates otherwise", function() { const scene2 = createScene_default(); if (!import__450.ClippingPlaneCollection.useFloatTexture(scene2.context)) { scene2.destroyForSpecs(); return; } const gl = scene2.frameState.context._gl; let copyWidth; let copyHeight; spyOn(gl, "texSubImage2D").and.callFake(function(target, level, xoffset, yoffset, width, height, format, type, arrayBufferView) { copyWidth = width; copyHeight = height; }); clippingPlanes = new import__450.ClippingPlaneCollection({ planes, enabled: false, edgeColor: import__450.Color.RED, modelMatrix: transform }); clippingPlanes.update(scene2.frameState); const packedTexture = clippingPlanes.texture; expect(packedTexture.width).toEqual(2); expect(packedTexture.height).toEqual(2); const targetPlane = new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, 1); clippingPlanes.add(targetPlane); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, 1)); clippingPlanes.update(scene2.frameState); expect(packedTexture.isDestroyed()).toBe(false); expect(gl.texSubImage2D.calls.count()).toEqual(1); expect(copyWidth).toEqual(packedTexture.width); expect(copyHeight).toEqual(packedTexture.height); targetPlane.distance += 1; clippingPlanes.update(scene2.frameState); expect(packedTexture.isDestroyed()).toBe(false); expect(gl.texSubImage2D.calls.count()).toEqual(2); expect(copyWidth).toEqual(1); expect(copyHeight).toEqual(1); clippingPlanes.destroy(); scene2.destroyForSpecs(); }); }); it("does not perform texture updates if the planes are unchanged", function() { const scene2 = createScene_default(); const gl = scene2.frameState.context._gl; spyOn(gl, "texImage2D").and.callThrough(); clippingPlanes = new import__450.ClippingPlaneCollection({ planes, enabled: false, edgeColor: import__450.Color.RED, modelMatrix: transform }); expect(gl.texImage2D.calls.count()).toEqual(0); clippingPlanes.update(scene2.frameState); expect(gl.texImage2D.calls.count()).toEqual(2); clippingPlanes.update(scene2.frameState); expect(gl.texImage2D.calls.count()).toEqual(2); clippingPlanes.destroy(); scene2.destroyForSpecs(); }); it("provides a function for attaching the ClippingPlaneCollection to objects", function() { const clippedObject1 = { clippingPlanes: void 0 }; const clippedObject2 = { clippingPlanes: void 0 }; const clippingPlanes1 = new import__450.ClippingPlaneCollection({ planes, enabled: false, edgeColor: import__450.Color.RED, modelMatrix: transform }); import__450.ClippingPlaneCollection.setOwner( clippingPlanes1, clippedObject1, "clippingPlanes" ); expect(clippedObject1.clippingPlanes).toBe(clippingPlanes1); expect(clippingPlanes1._owner).toBe(clippedObject1); const clippingPlanes2 = new import__450.ClippingPlaneCollection({ planes, enabled: false, edgeColor: import__450.Color.RED, modelMatrix: transform }); import__450.ClippingPlaneCollection.setOwner( clippingPlanes2, clippedObject1, "clippingPlanes" ); expect(clippingPlanes1.isDestroyed()).toBe(true); import__450.ClippingPlaneCollection.setOwner( clippingPlanes2, clippedObject1, "clippingPlanes" ); expect(clippingPlanes2.isDestroyed()).toBe(false); expect(function() { import__450.ClippingPlaneCollection.setOwner( clippingPlanes2, clippedObject2, "clippingPlanes" ); }).toThrowDeveloperError(); }); it("setting unionClippingRegions updates testIntersection function", function() { clippingPlanes = new import__450.ClippingPlaneCollection(); const originalIntersectFunction = clippingPlanes._testIntersection; expect(clippingPlanes._testIntersection).not.toBeUndefined(); clippingPlanes.unionClippingRegions = true; expect(clippingPlanes._testIntersection).not.toBe( originalIntersectFunction ); }); it("computes intersections with bounding volumes when clipping regions are combined with an intersect operation", function() { clippingPlanes = new import__450.ClippingPlaneCollection(); let intersect = clippingPlanes.computeIntersectionWithBoundingVolume( boundingVolume ); expect(intersect).toEqual(import__450.Intersect.INSIDE); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, -2)); intersect = clippingPlanes.computeIntersectionWithBoundingVolume( boundingVolume ); expect(intersect).toEqual(import__450.Intersect.OUTSIDE); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_Y, 0)); intersect = clippingPlanes.computeIntersectionWithBoundingVolume( boundingVolume ); expect(intersect).toEqual(import__450.Intersect.INTERSECTING); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_Z, 1)); intersect = clippingPlanes.computeIntersectionWithBoundingVolume( boundingVolume ); expect(intersect).toEqual(import__450.Intersect.INSIDE); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_Z, 0)); intersect = clippingPlanes.computeIntersectionWithBoundingVolume( boundingVolume ); expect(intersect).toEqual(import__450.Intersect.INSIDE); }); it("computes intersections with bounding volumes when clipping planes are combined with a union operation", function() { clippingPlanes = new import__450.ClippingPlaneCollection({ unionClippingRegions: true }); let intersect = clippingPlanes.computeIntersectionWithBoundingVolume( boundingVolume ); expect(intersect).toEqual(import__450.Intersect.INSIDE); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_Z, 1)); intersect = clippingPlanes.computeIntersectionWithBoundingVolume( boundingVolume ); expect(intersect).toEqual(import__450.Intersect.INSIDE); const temp = new import__450.ClippingPlane(import__450.Cartesian3.UNIT_Y, -2); clippingPlanes.add(temp); intersect = clippingPlanes.computeIntersectionWithBoundingVolume( boundingVolume ); expect(intersect).toEqual(import__450.Intersect.OUTSIDE); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, 0)); intersect = clippingPlanes.computeIntersectionWithBoundingVolume( boundingVolume ); expect(intersect).toEqual(import__450.Intersect.OUTSIDE); clippingPlanes.remove(temp); intersect = clippingPlanes.computeIntersectionWithBoundingVolume( boundingVolume ); expect(intersect).toEqual(import__450.Intersect.INTERSECTING); }); it("compute intersections applies optional transform to planes", function() { clippingPlanes = new import__450.ClippingPlaneCollection(); let intersect = clippingPlanes.computeIntersectionWithBoundingVolume( boundingVolume, transform ); expect(intersect).toEqual(import__450.Intersect.INSIDE); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, -1)); intersect = clippingPlanes.computeIntersectionWithBoundingVolume( boundingVolume, transform ); expect(intersect).not.toEqual(import__450.Intersect.INSIDE); }); it("computes a description of the current shader for comparison", function() { clippingPlanes = new import__450.ClippingPlaneCollection(); clippingPlanes.add(new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, -1)); expect(clippingPlanes.clippingPlanesState).toEqual(-1); const holdThisPlane = new import__450.ClippingPlane(import__450.Cartesian3.UNIT_X, -1); clippingPlanes.add(holdThisPlane); expect(clippingPlanes.clippingPlanesState).toEqual(-2); clippingPlanes.unionClippingRegions = true; expect(clippingPlanes.clippingPlanesState).toEqual(2); clippingPlanes.remove(holdThisPlane); expect(clippingPlanes.clippingPlanesState).toEqual(1); }); it("provides a function for checking the texture resolution", function() { spyOn(import__450.ClippingPlaneCollection, "useFloatTexture").and.returnValue(false); const scene2 = createScene_default(); clippingPlanes = new import__450.ClippingPlaneCollection({ planes, enabled: false, edgeColor: import__450.Color.RED, modelMatrix: transform }); const predictedResolution = import__450.ClippingPlaneCollection.getTextureResolution( clippingPlanes, scene2.frameState.context, new import__450.Cartesian2() ); expect(predictedResolution.x).toEqual(4); expect(predictedResolution.y).toEqual(2); clippingPlanes.update(scene2.frameState); const actualResolution = import__450.ClippingPlaneCollection.getTextureResolution( clippingPlanes, scene2.frameState.context, new import__450.Cartesian2() ); expect(predictedResolution.x).toEqual(actualResolution.x); expect(predictedResolution.y).toEqual(actualResolution.y); clippingPlanes.destroy(); scene2.destroyForSpecs(); }); }); // packages/engine/Specs/Scene/ClippingPlaneSpec.js var import__451 = __toESM(require_Cesium(), 1); describe("Scene/ClippingPlane", function() { it("constructs", function() { const normal = import__451.Cartesian3.UNIT_X; const distance = 1; const clippingPlane = new import__451.ClippingPlane(normal, distance); expect(clippingPlane.normal).toEqual(normal); expect(clippingPlane.distance).toEqual(distance); }); it("runs onChangeCallback when changed", function() { const normal = import__451.Cartesian3.UNIT_X; const distance = 1; let changeCount = 0; const clippingPlane = new import__451.ClippingPlane(normal, distance); clippingPlane.onChangeCallback = function(index) { expect(index).toEqual(clippingPlane.index); changeCount++; }; clippingPlane.distance += 0.1; expect(changeCount).toEqual(1); clippingPlane.distance += 0; expect(changeCount).toEqual(1); clippingPlane.normal = import__451.Cartesian3.UNIT_Z; expect(changeCount).toEqual(2); clippingPlane.normal = import__451.Cartesian3.UNIT_Z; expect(changeCount).toEqual(2); clippingPlane.normal.x += 1; expect(changeCount).toEqual(3); }); it("can be instantiated from a Plane", function() { const plane = new import__451.Plane(import__451.Cartesian3.UNIT_X, 1); let clippingPlane = import__451.ClippingPlane.fromPlane(plane); expect(import__451.Cartesian3.equals(clippingPlane.normal, plane.normal)).toBe(true); expect(clippingPlane.distance).toEqual(plane.distance); const scratchClippingPlane = new import__451.ClippingPlane(import__451.Cartesian3.UNIT_Y, 0); clippingPlane = import__451.ClippingPlane.fromPlane(plane, scratchClippingPlane); expect(import__451.Cartesian3.equals(clippingPlane.normal, plane.normal)).toBe(true); expect(clippingPlane.distance).toEqual(plane.distance); expect(clippingPlane).toBe(scratchClippingPlane); }); it("clones", function() { const clippingPlane = new import__451.ClippingPlane(import__451.Cartesian3.UNIT_X, 1); let cloneClippingPlane = import__451.ClippingPlane.clone(clippingPlane); expect( import__451.Cartesian3.equals(clippingPlane.normal, cloneClippingPlane.normal) ).toBe(true); expect(clippingPlane.distance).toEqual(cloneClippingPlane.distance); const scratchClippingPlane = new import__451.ClippingPlane(import__451.Cartesian3.UNIT_Y, 0); cloneClippingPlane = import__451.ClippingPlane.clone( clippingPlane, scratchClippingPlane ); expect( import__451.Cartesian3.equals(clippingPlane.normal, cloneClippingPlane.normal) ).toBe(true); expect(clippingPlane.distance).toEqual(cloneClippingPlane.distance); expect(cloneClippingPlane).toBe(scratchClippingPlane); }); it("works with Plane math", function() { let normal = new import__451.Cartesian3(1, 2, 3); normal = import__451.Cartesian3.normalize(normal, normal); const clippingPlane = new import__451.ClippingPlane(normal, 12.34); let transform = import__451.Matrix4.fromUniformScale(2); transform = import__451.Matrix4.multiplyByMatrix3( transform, import__451.Matrix3.fromRotationY(Math.PI), transform ); const transformedPlane = import__451.Plane.transform(clippingPlane, transform); expect(transformedPlane.distance).toEqual(clippingPlane.distance * 2); expect(transformedPlane.normal.x).toEqualEpsilon( -clippingPlane.normal.x, import__451.Math.EPSILON10 ); expect(transformedPlane.normal.y).toEqual(clippingPlane.normal.y); expect(transformedPlane.normal.z).toEqual(-clippingPlane.normal.z); }); }); // packages/engine/Specs/Scene/ClippingPolygonCollectionSpec.js var import__452 = __toESM(require_Cesium(), 1); describe("Scene/ClippingPolygonCollection", function() { const positions = import__452.Cartesian3.fromRadiansArray([ -1.3194369277314022, 0.6988062530900625, -1.31941, 0.69879, -1.3193955980204217, 0.6988091578771254, -1.3193931220959367, 0.698743632490865, -1.3194358224045408, 0.6987471965556998 ]); const positionsB = import__452.Cartesian3.fromRadiansArray([ -1.3194369277314022, 0.6988062530900625, -1.31941, 0.69879, -1.3193931220959367, 0.698743632490865 ]); it("default constructor", function() { const polygons = new import__452.ClippingPolygonCollection(); expect(polygons.length).toEqual(0); expect(polygons.enabled).toBeTrue(); expect(polygons.inverse).toBeFalse(); expect(polygons.totalPositions).toBe(0); }); it("gets the length of the list of polygons", function() { const polygons = new import__452.ClippingPolygonCollection(); expect(polygons.length).toBe(0); const polygon = polygons.add(new import__452.ClippingPolygon({ positions })); polygons.add(new import__452.ClippingPolygon({ positions })); expect(polygons.length).toBe(2); polygons.remove(polygon); expect(polygons.length).toBe(1); }); it("add adds a polygon to the collection", function() { const polygons = new import__452.ClippingPolygonCollection(); polygons.add(new import__452.ClippingPolygon({ positions })); expect(polygons.length).toBe(1); }); it("fires the polygonAdded event when a polygon is added", function() { const polygons = new import__452.ClippingPolygonCollection(); const spy = jasmine.createSpy(); polygons.polygonAdded.addEventListener(spy); let polygon = polygons.add(new import__452.ClippingPolygon({ positions })); expect(spy).toHaveBeenCalledWith(polygon, 0); polygon = polygons.add(new import__452.ClippingPolygon({ positions: positionsB })); expect(spy).toHaveBeenCalledWith(polygon, 1); }); it("gets the polygon at an index", function() { const polygonA = new import__452.ClippingPolygon({ positions }); const polygonB = new import__452.ClippingPolygon({ positions: positionsB }); const polygons = new import__452.ClippingPolygonCollection({ polygons: [polygonA, polygonB] }); let polygon = polygons.get(0); expect(polygon).toBe(polygonA); polygon = polygons.get(1); expect(polygon).toBe(polygonB); }); it("contain checks if the collection contains a polygon", function() { const polygonA = new import__452.ClippingPolygon({ positions }); const polygonB = new import__452.ClippingPolygon({ positions: positionsB }); const polygons = new import__452.ClippingPolygonCollection({ polygons: [polygonA] }); expect(polygons.contains(polygonA)).toBeTrue(); expect(polygons.contains(polygonB)).toBeFalse(); }); it("remove removes the first occurrence of a polygon", function() { const polygonA = new import__452.ClippingPolygon({ positions }); const polygonB = new import__452.ClippingPolygon({ positions: positionsB }); const polygons = new import__452.ClippingPolygonCollection({ polygons: [polygonA, polygonB] }); let result = polygons.remove(polygonA); expect(polygons.contains(polygonA)).toBeFalse(); expect(polygons.length).toBe(1); expect(polygons.get(0)).toEqual(polygonB); expect(result).toBeTrue(); result = polygons.remove(polygonA); expect(result).toBeFalse(); }); it("remove fires polygonRemoved event", function() { const polygon = new import__452.ClippingPolygon({ positions }); const polygons = new import__452.ClippingPolygonCollection({ polygons: [polygon] }); const spy = jasmine.createSpy(); polygons.polygonRemoved.addEventListener(spy); polygons.remove(polygon); expect(spy).toHaveBeenCalledWith(polygon, 0); }); it("removeAll removes all of the polygons in the collection", function() { const polygonA = new import__452.ClippingPolygon({ positions }); const polygonB = new import__452.ClippingPolygon({ positions: positionsB }); const polygons = new import__452.ClippingPolygonCollection({ polygons: [polygonA, polygonB] }); expect(polygons.length).toEqual(2); polygons.removeAll(); expect(polygons.length).toBe(0); }); it("removeAll fires polygonRemoved event", function() { const polygonA = new import__452.ClippingPolygon({ positions }); const polygonB = new import__452.ClippingPolygon({ positions: positionsB }); const polygons = new import__452.ClippingPolygonCollection({ polygons: [polygonA, polygonB] }); const spy = jasmine.createSpy(); polygons.polygonRemoved.addEventListener(spy); polygons.removeAll(); expect(spy).toHaveBeenCalledWith(polygonA, 0); expect(spy).toHaveBeenCalledWith(polygonB, 1); }); it("throws on update if float textures aren't supported", function() { spyOn(import__452.ClippingPolygonCollection, "isSupported").and.returnValue(false); const polygons = new import__452.ClippingPolygonCollection(); const scene2 = createScene_default(); scene2.context._textureFloat = false; expect(() => { polygons.update(scene2.frameState); }).toThrowError( "ClippingPolygonCollections are only supported for WebGL 2." ); scene2.destroyForSpecs(); }); it("only creates textures and compute commands when polygons are added", function() { const scene2 = createScene_default(); if (!scene2.context.webgl2) { scene2.destroyForSpecs(); return; } const polygons = new import__452.ClippingPolygonCollection(); polygons.update(scene2.frameState); expect(polygons.extentsTexture).toBeUndefined(); expect(polygons.clippingTexture).toBeUndefined(); expect(polygons._polygonsTexture).toBeUndefined(); expect(polygons._signedDistanceComputeCommand).toBeUndefined(); polygons.destroy(); scene2.destroyForSpecs(); }); it("creates textures and compute commands when polygons are added", function() { const scene2 = createScene_default(); if (!scene2.context.webgl2) { scene2.destroyForSpecs(); return; } const polygon = new import__452.ClippingPolygon({ positions }); const polygons = new import__452.ClippingPolygonCollection({ polygons: [polygon] }); polygons.update(scene2.frameState); expect(polygons.extentsTexture).toBeDefined(); expect(polygons.extentsTexture.width).toBeGreaterThan(0); expect(polygons.extentsTexture.height).toBeGreaterThan(0); expect(polygons.clippingTexture).toBeDefined(); expect(polygons.clippingTexture.width).toBeGreaterThan(0); expect(polygons.clippingTexture.height).toBeGreaterThan(0); expect(polygons._polygonsTexture).toBeDefined(); expect(polygons._polygonsTexture.width).toBeGreaterThan(0); expect(polygons._polygonsTexture.height).toBeGreaterThan(0); expect(polygons._signedDistanceComputeCommand).toBeDefined(); polygons.destroy(); scene2.destroyForSpecs(); }); it("fills texture with packed polygon positions", function() { const scene2 = createScene_default(); if (!scene2.context.webgl2) { scene2.destroyForSpecs(); return; } const polygon = new import__452.ClippingPolygon({ positions }); const polygons = new import__452.ClippingPolygonCollection({ polygons: [polygon] }); const gl = scene2.frameState.context._gl; const spy = spyOn(gl, "texImage2D").and.callThrough(); polygons.update(scene2.frameState); const args = spy.calls.argsFor(spy.calls.count() - 2); const arrayBufferView = args[8]; expect(arrayBufferView).toBeDefined(); expect(arrayBufferView[0]).toBe(5); expect(arrayBufferView[1]).toBe(0); expect(arrayBufferView[2]).toEqualEpsilon( 0.6969271302223206, import__452.Math.EPSILON10 ); expect(arrayBufferView[3]).toEqualEpsilon( -1.3191630840301514, import__452.Math.EPSILON10 ); expect(arrayBufferView[10]).toEqualEpsilon( 0.6968677043914795, import__452.Math.EPSILON10 ); expect(arrayBufferView[11]).toEqualEpsilon( -1.3191620111465454, import__452.Math.EPSILON10 ); expect(arrayBufferView[12]).toBe(0); polygons.destroy(); scene2.destroyForSpecs(); }); it("fills texture with packed extents", function() { const scene2 = createScene_default(); if (!scene2.context.webgl2) { scene2.destroyForSpecs(); return; } const polygon = new import__452.ClippingPolygon({ positions }); const polygons = new import__452.ClippingPolygonCollection({ polygons: [polygon] }); const gl = scene2.frameState.context._gl; const spy = spyOn(gl, "texImage2D").and.callThrough(); polygons.update(scene2.frameState); const args = spy.calls.argsFor(spy.calls.count() - 3); const arrayBufferView = args[8]; expect(arrayBufferView).toBeDefined(); expect(arrayBufferView[0]).toEqualEpsilon( 0.6958641409873962, import__452.Math.EPSILON10 ); expect(arrayBufferView[1]).toEqualEpsilon( -1.3201631307601929, import__452.Math.EPSILON10 ); expect(arrayBufferView[2]).toEqualEpsilon( 484.0434265136719, import__452.Math.EPSILON10 ); expect(arrayBufferView[3]).toEqualEpsilon( 489.4261779785156, import__452.Math.EPSILON10 ); expect(arrayBufferView[4]).toBe(0); expect(arrayBufferView[5]).toBe(0); expect(arrayBufferView[6]).toBe(0); expect(arrayBufferView[7]).toBe(0); polygons.destroy(); scene2.destroyForSpecs(); }); it("Combines overlapping extents", function() { const scene2 = createScene_default(); if (!scene2.context.webgl2) { scene2.destroyForSpecs(); return; } const polygonA = new import__452.ClippingPolygon({ positions }); const polygonB = new import__452.ClippingPolygon({ positions: positionsB }); const polygons = new import__452.ClippingPolygonCollection({ polygons: [polygonA, polygonB] }); const gl = scene2.frameState.context._gl; const spy = spyOn(gl, "texImage2D").and.callThrough(); polygons.update(scene2.frameState); let args = spy.calls.argsFor(spy.calls.count() - 2); let arrayBufferView = args[8]; expect(arrayBufferView).toBeDefined(); expect(arrayBufferView[1]).toBe(0); expect(arrayBufferView[13]).toBe(0); args = spy.calls.argsFor(spy.calls.count() - 3); arrayBufferView = args[8]; expect(arrayBufferView).toBeDefined(); expect(arrayBufferView[0]).toEqualEpsilon( 0.6958641409873962, import__452.Math.EPSILON10 ); expect(arrayBufferView[1]).toEqualEpsilon( -1.3201631307601929, import__452.Math.EPSILON10 ); expect(arrayBufferView[2]).toEqualEpsilon( 484.0434265136719, import__452.Math.EPSILON10 ); expect(arrayBufferView[3]).toEqualEpsilon( 489.4261779785156, import__452.Math.EPSILON10 ); expect(arrayBufferView[4]).toBe(0); expect(arrayBufferView[5]).toBe(0); expect(arrayBufferView[6]).toBe(0); expect(arrayBufferView[7]).toBe(0); polygons.destroy(); scene2.destroyForSpecs(); }); it("does not perform texture updates if the polygons are unchanged", function() { const scene2 = createScene_default(); if (!scene2.context.webgl2) { scene2.destroyForSpecs(); return; } const polygon = new import__452.ClippingPolygon({ positions }); const polygons = new import__452.ClippingPolygonCollection({ polygons: [polygon] }); const gl = scene2.frameState.context._gl; const spy = spyOn(gl, "texImage2D").and.callThrough(); polygons.update(scene2.frameState); const currentCount = spy.calls.count(); polygons.update(scene2.frameState); expect(spy.calls.count()).toEqual(currentCount); polygons.destroy(); scene2.destroyForSpecs(); }); it("provides a function for attaching the ClippingPolygonCollection to objects", function() { const polygon = new import__452.ClippingPolygon({ positions }); const clippedObject1 = { polygons: void 0 }; const clippedObject2 = { polygons: void 0 }; const polygons1 = new import__452.ClippingPolygonCollection({ polygons: [polygon], enabled: false }); import__452.ClippingPolygonCollection.setOwner(polygons1, clippedObject1, "polygons"); expect(clippedObject1.polygons).toBe(polygons1); expect(polygons1._owner).toBe(clippedObject1); const polygons2 = new import__452.ClippingPolygonCollection({ polygons: [polygon], enabled: false }); import__452.ClippingPolygonCollection.setOwner(polygons2, clippedObject1, "polygons"); expect(polygons1.isDestroyed()).toBe(true); import__452.ClippingPolygonCollection.setOwner(polygons2, clippedObject1, "polygons"); expect(polygons2.isDestroyed()).toBe(false); expect(function() { import__452.ClippingPolygonCollection.setOwner(polygons2, clippedObject2, "polygons"); }).toThrowDeveloperError(); }); it("getClippingDistanceTextureResolution works before textures are created", function() { const polygon = new import__452.ClippingPolygon({ positions }); const polygons = new import__452.ClippingPolygonCollection({ polygons: [polygon] }); const scene2 = createScene_default(); import__452.ContextLimits._maximumTextureSize = 64; const result = import__452.ClippingPolygonCollection.getClippingDistanceTextureResolution( polygons, new import__452.Cartesian2() ); expect(result.x).toBe(64); expect(result.y).toBe(64); polygons.destroy(); scene2.destroyForSpecs(); }); it("getClippingExtentsTextureResolution works before textures are created", function() { const polygon = new import__452.ClippingPolygon({ positions }); const polygons = new import__452.ClippingPolygonCollection({ polygons: [polygon] }); const scene2 = createScene_default(); import__452.ContextLimits._maximumTextureSize = 64; const result = import__452.ClippingPolygonCollection.getClippingExtentsTextureResolution( polygons, new import__452.Cartesian2() ); expect(result.x).toBe(1); expect(result.y).toBe(2); polygons.destroy(); scene2.destroyForSpecs(); }); it("computes intersections with bounding volumes", function() { const polygons = new import__452.ClippingPolygonCollection(); let boundingVolume = new import__452.TileBoundingRegion({ rectangle: import__452.Rectangle.fromCartesianArray(positions) }); let intersect = polygons.computeIntersectionWithBoundingVolume( boundingVolume ); expect(intersect).toEqual(import__452.Intersect.OUTSIDE); polygons.add(new import__452.ClippingPolygon({ positions })); intersect = polygons.computeIntersectionWithBoundingVolume(boundingVolume); expect(intersect).toEqual(import__452.Intersect.INTERSECTING); const boundingSphere = import__452.BoundingSphere.fromPoints(positions); boundingVolume = new import__452.TileBoundingSphere( boundingSphere.center, boundingSphere.radius ); intersect = polygons.computeIntersectionWithBoundingVolume(boundingVolume); expect(intersect).toEqual(import__452.Intersect.INTERSECTING); const box = import__452.OrientedBoundingBox.fromPoints(positions); boundingVolume = new import__452.TileOrientedBoundingBox(box.center, box.halfAxes); intersect = polygons.computeIntersectionWithBoundingVolume(boundingVolume); expect(intersect).toEqual(import__452.Intersect.INTERSECTING); }); it("computes intersections with bounding volumes when inverse is true", function() { const polygons = new import__452.ClippingPolygonCollection({ inverse: true }); let boundingVolume = new import__452.TileBoundingRegion({ rectangle: import__452.Rectangle.fromCartesianArray(positions) }); let intersect = polygons.computeIntersectionWithBoundingVolume( boundingVolume ); expect(intersect).toEqual(import__452.Intersect.INSIDE); polygons.add(new import__452.ClippingPolygon({ positions })); intersect = polygons.computeIntersectionWithBoundingVolume(boundingVolume); expect(intersect).toEqual(import__452.Intersect.INTERSECTING); const boundingSphere = import__452.BoundingSphere.fromPoints(positions); boundingVolume = new import__452.TileBoundingSphere( boundingSphere.center, boundingSphere.radius ); intersect = polygons.computeIntersectionWithBoundingVolume(boundingVolume); expect(intersect).toEqual(import__452.Intersect.INTERSECTING); const box = import__452.OrientedBoundingBox.fromPoints(positions); boundingVolume = new import__452.TileOrientedBoundingBox(box.center, box.halfAxes); intersect = polygons.computeIntersectionWithBoundingVolume(boundingVolume); expect(intersect).toEqual(import__452.Intersect.INTERSECTING); }); }); // packages/engine/Specs/Scene/ClippingPolygonSpec.js var import__453 = __toESM(require_Cesium(), 1); describe("Scene/ClippingPolygon", function() { it("constructs", function() { const positions = import__453.Cartesian3.fromRadiansArray([ -1.3194369277314022, 0.6988062530900625, -1.31941, 0.69879, -1.3193955980204217, 0.6988091578771254, -1.3193931220959367, 0.698743632490865, -1.3194358224045408, 0.6987471965556998 ]); const polygon = new import__453.ClippingPolygon({ positions }); expect(polygon.length).toBe(5); expect(polygon.positions).toEqual(positions); expect(polygon.ellipsoid).toEqual(import__453.Ellipsoid.WGS84); }); it("throws when constructing polygon with fewer than 3 positions", function() { expect(() => { const polygon = new import__453.ClippingPolygon(); }).toThrowDeveloperError(); const positions = import__453.Cartesian3.fromRadiansArray([ -1.3194369277314022, 0.6988062530900625, -1.31941, 0.69879 ]); expect(() => { const polygon = new import__453.ClippingPolygon({ positions }); }).toThrowDeveloperError(); }); it("clones", function() { const positions = import__453.Cartesian3.fromRadiansArray([ -1.3194369277314022, 0.6988062530900625, -1.31941, 0.69879, -1.3193955980204217, 0.6988091578771254, -1.3193931220959367, 0.698743632490865, -1.3194358224045408, 0.6987471965556998 ]); const polygon = new import__453.ClippingPolygon({ ellipsoid: import__453.Ellipsoid.MOON, positions }); let clonedPolygon = import__453.ClippingPolygon.clone(polygon); expect(polygon.positions).toEqual(clonedPolygon.positions); expect(polygon.positions).not.toBe(clonedPolygon.positions); expect(polygon.ellipsoid).toEqual(clonedPolygon.ellipsoid); const scratchClippingPolygon = new import__453.ClippingPolygon({ positions: [new import__453.Cartesian3(), new import__453.Cartesian3(), new import__453.Cartesian3()] }); clonedPolygon = import__453.ClippingPolygon.clone(polygon, scratchClippingPolygon); expect(polygon.positions).toEqual(clonedPolygon.positions); expect(polygon.positions).not.toBe(clonedPolygon.positions); expect(polygon.ellipsoid).toEqual(clonedPolygon.ellipsoid); }); it("clone throws without argument", function() { expect(() => { import__453.ClippingPolygon.clone(void 0); }).toThrowDeveloperError(); }); it("equals verifies equality", function() { const positions = import__453.Cartesian3.fromRadiansArray([ -1.3194369277314022, 0.6988062530900625, -1.31941, 0.69879, -1.3193955980204217, 0.6988091578771254, -1.3193931220959367, 0.698743632490865, -1.3194358224045408, 0.6987471965556998 ]); const polygonA = new import__453.ClippingPolygon({ ellipsoid: import__453.Ellipsoid.MOON, positions }); let polygonB = new import__453.ClippingPolygon({ positions }); expect(import__453.ClippingPolygon.equals(polygonA, polygonB)).toBeFalse(); polygonB = new import__453.ClippingPolygon({ ellipsoid: import__453.Ellipsoid.MOON, positions: import__453.Cartesian3.fromRadiansArray([ -1.3194369277314022, 0.6988062530900625, -1.31941, 0.69879, -1.3193955980204217, 0.6988091578771254, -1.3193931220959367, 0.698743632490865, -1.3194358224045408, 0.6987471965556998 ]) }); expect(import__453.ClippingPolygon.equals(polygonA, polygonB)).toBeFalse(); polygonB = new import__453.ClippingPolygon({ ellipsoid: import__453.Ellipsoid.MOON, positions }); expect(import__453.ClippingPolygon.equals(polygonA, polygonA)).toBeTrue(); }); it("equals throws without arguments", function() { const positions = import__453.Cartesian3.fromRadiansArray([ -1.3194369277314022, 0.6988062530900625, -1.31941, 0.69879, -1.3193955980204217, 0.6988091578771254, -1.3193931220959367, 0.698743632490865, -1.3194358224045408, 0.6987471965556998 ]); const polygon = new import__453.ClippingPolygon({ positions }); expect(() => { import__453.ClippingPolygon.equals(polygon, void 0); }).toThrowDeveloperError(); expect(() => { import__453.ClippingPolygon.equals(void 0, polygon); }).toThrowDeveloperError(); }); it("computeRectangle returns rectangle enclosing the polygon", function() { const positions = import__453.Cartesian3.fromRadiansArray([ -1.3194369277314022, 0.6988062530900625, -1.31941, 0.69879, -1.3193955980204217, 0.6988091578771254, -1.3193931220959367, 0.698743632490865, -1.3194358224045408, 0.6987471965556998 ]); const polygon = new import__453.ClippingPolygon({ positions }); const result = polygon.computeRectangle(); expect(result).toBeInstanceOf(import__453.Rectangle); expect(result.west).toEqualEpsilon( -1.3194369277314024, import__453.Math.EPSILON10 ); expect(result.south).toEqualEpsilon( 0.6987436324908647, import__453.Math.EPSILON10 ); expect(result.east).toEqualEpsilon( -1.3193931220959367, import__453.Math.EPSILON10 ); expect(result.north).toEqualEpsilon( 0.6988091578771254, import__453.Math.EPSILON10 ); }); it("computeRectangle uses result parameter", function() { const positions = import__453.Cartesian3.fromRadiansArray([ -1.3194369277314022, 0.6988062530900625, -1.31941, 0.69879, -1.3193955980204217, 0.6988091578771254, -1.3193931220959367, 0.698743632490865, -1.3194358224045408, 0.6987471965556998 ]); const polygon = new import__453.ClippingPolygon({ positions }); const result = new import__453.Rectangle(); const returnedValue = polygon.computeRectangle(result); expect(returnedValue).toBe(result); expect(result.west).toEqualEpsilon( -1.3194369277314024, import__453.Math.EPSILON10 ); expect(result.south).toEqualEpsilon( 0.6987436324908647, import__453.Math.EPSILON10 ); expect(result.east).toEqualEpsilon( -1.3193931220959367, import__453.Math.EPSILON10 ); expect(result.north).toEqualEpsilon( 0.6988091578771254, import__453.Math.EPSILON10 ); }); it("computeSphericalExtents returns rectangle enclosing the polygon defined in spherical coordinates", function() { const positions = import__453.Cartesian3.fromRadiansArray([ -1.3194369277314022, 0.6988062530900625, -1.31941, 0.69879, -1.3193955980204217, 0.6988091578771254, -1.3193931220959367, 0.698743632490865, -1.3194358224045408, 0.6987471965556998 ]); const polygon = new import__453.ClippingPolygon({ positions }); const result = polygon.computeSphericalExtents(); expect(result).toBeInstanceOf(import__453.Rectangle); expect(result.west).toEqualEpsilon( -1.3191630776640944, import__453.Math.EPSILON10 ); expect(result.south).toEqualEpsilon( 0.6968641167123716, import__453.Math.EPSILON10 ); expect(result.east).toEqualEpsilon( -1.3191198686316543, import__453.Math.EPSILON10 ); expect(result.north).toEqualEpsilon( 0.6969300470954187, import__453.Math.EPSILON10 ); }); it("computeSphericalExtents uses result parameter", function() { const positions = import__453.Cartesian3.fromRadiansArray([ -1.3194369277314022, 0.6988062530900625, -1.31941, 0.69879, -1.3193955980204217, 0.6988091578771254, -1.3193931220959367, 0.698743632490865, -1.3194358224045408, 0.6987471965556998 ]); const polygon = new import__453.ClippingPolygon({ positions }); const result = new import__453.Rectangle(); const returnedValue = polygon.computeSphericalExtents(result); expect(returnedValue).toBe(result); expect(result.west).toEqualEpsilon( -1.3191630776640944, import__453.Math.EPSILON10 ); expect(result.south).toEqualEpsilon( 0.6968641167123716, import__453.Math.EPSILON10 ); expect(result.east).toEqualEpsilon( -1.3191198686316543, import__453.Math.EPSILON10 ); expect(result.north).toEqualEpsilon( 0.6969300470954187, import__453.Math.EPSILON10 ); }); }); // packages/engine/Specs/Scene/CloudCollectionSpec.js var import__454 = __toESM(require_Cesium(), 1); var import__455 = __toESM(require_Cesium(), 1); describe( "Scene/CloudCollection", function() { let scene2; let context; let camera; let clouds; beforeAll(function() { scene2 = createScene_default(); context = scene2.context; camera = scene2.camera; }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { scene2.morphTo3D(0); camera.position = new import__454.Cartesian3(10, 0, 0); camera.direction = import__454.Cartesian3.negate(import__454.Cartesian3.UNIT_X, new import__454.Cartesian3()); camera.up = import__454.Cartesian3.clone(import__454.Cartesian3.UNIT_Z); camera.frustum = new import__454.PerspectiveFrustum(); camera.frustum.aspectRatio = scene2.drawingBufferWidth / scene2.drawingBufferHeight; camera.frustum.fov = import__455.Math.toRadians(60); clouds = new import__454.CloudCollection({ debugBillboards: true }); scene2.primitives.add(clouds); }); afterEach(function() { scene2.primitives.removeAll(); }); it("constructs a default cloud", function() { const c = clouds.add(); expect(c.show).toEqual(true); expect(c.position).toEqual(import__454.Cartesian3.ZERO); expect(c.scale).toEqual(new import__454.Cartesian2(20, 12)); expect(c.maximumSize).toEqual(new import__454.Cartesian3(20, 12, 8)); expect(c.slice).toEqual(-1); expect(c.brightness).toEqual(1); }); it("explicitly constructs a cloud", function() { const c = clouds.add({ cloudType: import__454.CloudType.CUMULUS, show: false, position: new import__454.Cartesian3(1, 2, 3), scale: new import__454.Cartesian2(2, 3), maximumSize: new import__454.Cartesian3(4, 5, 6), slice: 0.5, brightness: 0.7 }); expect(c.show).toEqual(false); expect(c.position).toEqual(new import__454.Cartesian3(1, 2, 3)); expect(c.scale).toEqual(new import__454.Cartesian2(2, 3)); expect(c.maximumSize).toEqual(new import__454.Cartesian3(4, 5, 6)); expect(c.slice).toEqual(0.5); expect(c.brightness).toEqual(0.7); }); it("constructs cloud with only maximum size", function() { const c = clouds.add({ maximumSize: new import__454.Cartesian3(1, 2, 3) }); expect(c.maximumSize).toEqual(new import__454.Cartesian3(1, 2, 3)); expect(c.scale).toEqual(new import__454.Cartesian2(1, 2)); }); it("sets cloud properties", function() { const c = clouds.add(); c.show = false; c.position = new import__454.Cartesian3(1, 2, 3); c.scale = new import__454.Cartesian2(2, 3); c.maximumSize = new import__454.Cartesian3(4, 5, 6); c.slice = 0.5; c.brightness = 0.7; expect(c.show).toEqual(false); expect(c.position).toEqual(new import__454.Cartesian3(1, 2, 3)); expect(c.scale).toEqual(new import__454.Cartesian2(2, 3)); expect(c.maximumSize).toEqual(new import__454.Cartesian3(4, 5, 6)); expect(c.slice).toEqual(0.5); expect(c.brightness).toEqual(0.7); }); it("is not destroyed", function() { expect(clouds.isDestroyed()).toEqual(false); }); it("sets a removed cloud property", function() { const c = clouds.add(); clouds.remove(c); c.show = false; expect(c.show).toEqual(false); }); it("has zero clouds when constructed", function() { expect(clouds.length).toEqual(0); }); it("adds a cloud", function() { const c = clouds.add({ position: new import__454.Cartesian3(1, 2, 3) }); expect(clouds.length).toEqual(1); expect(clouds.get(0)).toBe(c); }); it("removes the first cloud", function() { const one = clouds.add({ position: new import__454.Cartesian3(1, 2, 3) }); const two = clouds.add({ position: new import__454.Cartesian3(4, 5, 6) }); expect(clouds.length).toEqual(2); expect(clouds.remove(one)).toEqual(true); expect(clouds.length).toEqual(1); expect(clouds.get(0)).toBe(two); }); it("removes the last cloud", function() { const one = clouds.add({ position: new import__454.Cartesian3(1, 2, 3) }); const two = clouds.add({ position: new import__454.Cartesian3(4, 5, 6) }); expect(clouds.length).toEqual(2); expect(clouds.remove(two)).toEqual(true); expect(clouds.length).toEqual(1); expect(clouds.get(0)).toBe(one); }); it("removes the same cloud twice", function() { const b = clouds.add({ position: new import__454.Cartesian3(1, 2, 3) }); expect(clouds.length).toEqual(1); expect(clouds.remove(b)).toEqual(true); expect(clouds.length).toEqual(0); expect(clouds.remove(b)).toEqual(false); expect(clouds.length).toEqual(0); }); it("returns false when removing undefined", function() { clouds.add({ position: new import__454.Cartesian3(1, 2, 3) }); expect(clouds.length).toEqual(1); expect(clouds.remove(void 0)).toEqual(false); expect(clouds.length).toEqual(1); }); it("adds and removes clouds", function() { const one = clouds.add({ position: new import__454.Cartesian3(1, 2, 3) }); const two = clouds.add({ position: new import__454.Cartesian3(4, 5, 6) }); expect(clouds.length).toEqual(2); expect(clouds.get(0)).toBe(one); expect(clouds.get(1)).toBe(two); expect(clouds.remove(two)).toEqual(true); expect(clouds.length).toEqual(1); const three = clouds.add({ position: new import__454.Cartesian3(7, 8, 9) }); expect(clouds.length).toEqual(2); expect(clouds.get(0)).toBe(one); expect(clouds.get(1)).toBe(three); }); it("removes all clouds", function() { clouds.add({ position: new import__454.Cartesian3(1, 2, 3) }); clouds.add({ position: new import__454.Cartesian3(4, 5, 6) }); expect(clouds.length).toEqual(2); clouds.removeAll(); expect(clouds.length).toEqual(0); }); it("can check if it contains a cloud", function() { const cloud = clouds.add(); expect(clouds.contains(cloud)).toEqual(true); }); it("returns false when checking if it contains a cloud it does not contain", function() { const cloud = clouds.add(); clouds.remove(cloud); expect(clouds.contains(cloud)).toEqual(false); }); it("does not contain undefined", function() { expect(clouds.contains(void 0)).toEqual(false); }); it("does not contain random other objects", function() { expect(clouds.contains({})).toEqual(false); expect(clouds.contains(new import__454.Cartesian2())).toEqual(false); }); it("does not render when constructed", function() { expect(scene2).toRender([0, 0, 0, 255]); }); it("renders a cloud", function() { clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian2(20, 12) }); expect(scene2).notToRender([0, 0, 0, 255]); }); it("adds and renders a cloud", function() { clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian2(20, 12) }); expect(scene2).notToRender([0, 0, 0, 255]); clouds.add({ position: new import__454.Cartesian3(1, 0, 0), scale: new import__454.Cartesian2(20, 12) }); expect(scene2).notToRender([0, 0, 0, 255]); }); it("modifies and removes a cloud, then renders", function() { const c = clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian2(20, 12) }); expect(scene2).notToRender([0, 0, 0, 255]); c.scale = new import__454.Cartesian2(10, 2); clouds.remove(c); expect(scene2).toRender([0, 0, 0, 255]); }); it("removes and renders a cloud", function() { clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian2(20, 12) }); const cloud = clouds.add({ position: new import__454.Cartesian3(1, 0, 0), // Closer to camera scale: new import__454.Cartesian2(20, 12) }); expect(scene2).notToRender([0, 0, 0, 255]); clouds.remove(cloud); expect(scene2).notToRender([0, 0, 0, 255]); }); it("removes all clouds and renders", function() { clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian2(20, 12) }); clouds.add({ position: new import__454.Cartesian3(1, 0, 0), scale: new import__454.Cartesian2(20, 12) }); expect(scene2).notToRender([0, 0, 0, 255]); clouds.removeAll(); expect(scene2).toRender([0, 0, 0, 255]); }); it("removes all clouds, adds a cloud, and renders", function() { clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian2(20, 12) }); clouds.add({ position: new import__454.Cartesian3(1, 0, 0), scale: new import__454.Cartesian2(20, 12) }); expect(scene2).notToRender([0, 0, 0, 255]); clouds.removeAll(); clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian2(20, 12) }); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders using cloud show property", function() { const c = clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian3(20, 12) }); expect(scene2).notToRender([0, 0, 0, 255]); c.show = false; expect(scene2).toRender([0, 0, 0, 255]); }); it("renders using cloud position property", function() { const c = clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian3(20, 12) }); expect(scene2).notToRender([0, 0, 0, 255]); c.position = new import__454.Cartesian3(40, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); c.position = new import__454.Cartesian3(1, 0, 0); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders using cloud scale property", function() { const c = clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian3(20, 12) }); expect(scene2).notToRender([0, 0, 0, 255]); c.scale = import__454.Cartesian2.ZERO; expect(scene2).toRender([0, 0, 0, 255]); c.scale = new import__454.Cartesian2(10, 5); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders using cloud maximum size property", function() { clouds.debugBillboards = false; clouds.debugEllipsoids = true; const c = clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian3(20, 12), maximumSize: new import__454.Cartesian3(20, 10, 8) }); expect(scene2).notToRender([0, 0, 0, 255]); c.maximumSize = import__454.Cartesian3.ZERO; expect(scene2).toRender([0, 0, 0, 255]); clouds.debugClouds = true; c.maximumSize = new import__454.Cartesian3(10, 5, 5); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders using cloud slice property", function() { clouds.debugBillboards = false; clouds.debugEllipsoids = true; const c = clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian3(20, 12) }); expect(scene2).notToRender([0, 0, 0, 255]); c.slice = 10; expect(scene2).toRender([0, 0, 0, 255]); c.slice = 0.5; expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders using cloud brightness property", function() { clouds.debugBillboards = false; clouds.debugEllipsoids = true; const c = clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian3(20, 12) }); expect(scene2).notToRender([0, 0, 0, 255]); c.brightness = 0; expect(scene2).toRender([0, 0, 0, 255]); c.brightness = 0.5; expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders using cloud color property", function() { clouds.debugBillboards = false; clouds.debugEllipsoids = true; const c = clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian3(20, 12) }); let initialRgba; expect(scene2).toRenderAndCall(function(rgba) { initialRgba = rgba; expect(initialRgba).not.toEqual([0, 0, 0, 255]); }); c.color = import__454.Color.RED; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual(initialRgba); }); }); it("updates 10% of clouds", function() { for (let i = 0; i < 10; ++i) { clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian2(20, 12), show: i === 3 }); } expect(scene2).notToRender([0, 0, 0, 255]); clouds.get(3).scale = import__454.Cartesian2.ZERO; expect(scene2).toRender([0, 0, 0, 255]); clouds.get(3).scale = new import__454.Cartesian3(2, 2); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders clouds when instancing is disabled", function() { const instancedArrays = context._instancedArrays; context._instancedArrays = void 0; expect(scene2).toRender([0, 0, 0, 255]); const c1 = clouds.add({ position: import__454.Cartesian3.ZERO, maximumScale: new import__454.Cartesian3(10, 5, 5) }); expect(scene2).notToRender([0, 0, 0, 255]); const c2 = clouds.add({ position: new import__454.Cartesian3(1, 0, 0), // Closer to camera maximumScale: new import__454.Cartesian3(10, 5, 5) }); expect(scene2).notToRender([0, 0, 0, 255]); clouds.remove(c2); expect(scene2).notToRender([0, 0, 0, 255]); clouds.remove(c1); expect(scene2).toRender([0, 0, 0, 255]); context._instancedArrays = instancedArrays; }); it("updates clouds when instancing is disabled", function() { const instancedArrays = context._instancedArrays; context._instancedArrays = void 0; expect(scene2).toRender([0, 0, 0, 255]); const c1 = clouds.add({ position: import__454.Cartesian3.ZERO, maximumScale: new import__454.Cartesian3(10, 5, 5) }); expect(scene2).notToRender([0, 0, 0, 255]); const c2 = clouds.add({ position: new import__454.Cartesian3(1, 0, 0), // Closer to camera maximumScale: new import__454.Cartesian3(10, 5, 5) }); expect(scene2).notToRender([0, 0, 0, 255]); c2.scale = import__454.Cartesian2.ZERO; expect(scene2).notToRender([0, 0, 0, 255]); c1.scale = import__454.Cartesian2.ZERO; expect(scene2).toRender([0, 0, 0, 255]); context._instancedArrays = instancedArrays; }); it("creates compute command with cloud texture shader", function() { clouds.debugBillboards = false; clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian3(20, 12) }); scene2.renderForSpecs(); const commandList = scene2._computeCommandList; const index = commandList.length - 1; const command = commandList[index]; expect(command instanceof import__454.ComputeCommand).toBe(true); expect(command.owner).toBe(clouds); }); it("creates draw command after texture is ready", function() { clouds.debugBillboards = false; clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian3(20, 12) }); return pollToPromise_default(function() { scene2.renderForSpecs(); return clouds._ready; }).then(function() { scene2.renderForSpecs(); const commandList = scene2.frameState.commandList; const index = commandList.length - 1; const command = commandList[index]; expect(command instanceof import__454.DrawCommand).toEqual(true); expect(command.owner).toBe(clouds); expect((0, import__454.defined)(clouds._noiseTexture)).toEqual(true); }); }); it("does not render if show is false", function() { clouds.add({ position: import__454.Cartesian3.ZERO, scale: new import__454.Cartesian2(20, 12) }); expect(scene2).notToRender([0, 0, 0, 255]); clouds.show = false; expect(scene2).toRender([0, 0, 0, 255]); }); it("throws when accessing without an index", function() { expect(function() { clouds.get(); }).toThrowDeveloperError(); }); it("throws when setting invalid cloud type property of cloud", function() { expect(function() { clouds.add({ cloudType: "not a cloud type" }); }).toThrowDeveloperError(); }); it("throws when setting invalid show property of cloud", function() { expect(function() { const c = clouds.add(); c.show = void 0; }).toThrowDeveloperError(); }); it("throws when setting undefined position property of cloud", function() { expect(function() { const c = clouds.add(); c.position = void 0; }).toThrowDeveloperError(); }); it("throws when setting undefined scale property of cloud", function() { expect(function() { const c = clouds.add(); c.scale = void 0; }).toThrowDeveloperError(); }); it("throws when setting undefined maximum size property of cloud", function() { expect(function() { const c = clouds.add(); c.maximumSize = void 0; }).toThrowDeveloperError(); }); it("throws when setting undefined slice property of cloud", function() { expect(function() { const c = clouds.add(); c.slice = void 0; }).toThrowDeveloperError(); }); it("throws when setting undefined brightness property of cloud", function() { expect(function() { const c = clouds.add(); c.brightness = void 0; }).toThrowDeveloperError(); }); it("throws with an invalid number of noise texture rows", function() { clouds.debugBillboards = false; clouds._textureSliceWidth = 8; clouds._noiseTextureRows = 16; expect(function() { scene2.renderForSpecs(); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Scene/Composite3DTileContentSpec.js var import__456 = __toESM(require_Cesium(), 1); describe( "Scene/Composite3DTileContent", function() { let scene2; const centerLongitude = -1.31968; const centerLatitude = 0.698874; const compositeUrl = "./Data/Cesium3DTiles/Composite/Composite/tileset.json"; const compositeOfComposite = "./Data/Cesium3DTiles/Composite/CompositeOfComposite/tileset.json"; const compositeOfInstanced = "./Data/Cesium3DTiles/Composite/CompositeOfInstanced/tileset.json"; beforeAll(function() { scene2 = createScene_default(); const center = import__456.Cartesian3.fromRadians(centerLongitude, centerLatitude); scene2.camera.lookAt(center, new import__456.HeadingPitchRange(0, -1.57, 26)); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.primitives.removeAll(); }); function expectRenderComposite(tileset) { expect(scene2).toPickAndCall(function(result) { const pickedBuilding = result; expect(pickedBuilding).toBeDefined(); pickedBuilding.color = import__456.Color.clone(import__456.Color.YELLOW, pickedBuilding.color); Cesium3DTilesTester_default.expectRender(scene2, tileset, function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toBeGreaterThan(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); pickedBuilding.show = false; let pickedInstance; expect(scene2).toPickAndCall(function(result2) { pickedInstance = result2; expect(pickedInstance).toBeDefined(); expect(pickedInstance).not.toEqual(pickedBuilding); }); pickedInstance.color = import__456.Color.clone(import__456.Color.GREEN, pickedInstance.color); Cesium3DTilesTester_default.expectRender(scene2, tileset, function(rgba) { expect(rgba[0]).toEqual(0); expect(rgba[1]).toBeGreaterThan(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); pickedInstance.show = false; Cesium3DTilesTester_default.expectRenderBlank(scene2, tileset); }); } it("throws with invalid version", async function() { const arrayBuffer = Cesium3DTilesTester_default.generateCompositeTileBuffer({ version: 2 }); await expectAsync( Cesium3DTilesTester_default.createContentForMockTile(arrayBuffer, "cmpt") ).toBeRejectedWithError( import__456.RuntimeError, "Only Composite Tile version 1 is supported. Version 2 is not." ); }); it("throws with invalid inner tile content type", async function() { const arrayBuffer = Cesium3DTilesTester_default.generateCompositeTileBuffer({ tiles: [ Cesium3DTilesTester_default.generateInstancedTileBuffer({ magic: [120, 120, 120, 120] }) ] }); await expectAsync( Cesium3DTilesTester_default.createContentForMockTile(arrayBuffer, "cmpt") ).toBeRejectedWithError( import__456.RuntimeError, "Unknown tile content type, xxxx, inside Composite tile" ); }); it("becomes ready", async function() { const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, compositeUrl ); expect(tileset.root.contentReady).toBeTrue(); expect(tileset.root.content).toBeDefined(); }); it("throws with invalid tile content", async function() { const arrayBuffer = Cesium3DTilesTester_default.generateCompositeTileBuffer({ tiles: [ Cesium3DTilesTester_default.generateInstancedTileBuffer({ gltfFormat: 0, gltfUri: "invalid" }) ] }); await expectAsync( Cesium3DTilesTester_default.createContentForMockTile(arrayBuffer, "cmpt") ).toBeRejectedWithError(import__456.RuntimeError); }); it("renders composite", function() { return Cesium3DTilesTester_default.loadTileset(scene2, compositeUrl).then( expectRenderComposite ); }); it("renders composite of composite", function() { return Cesium3DTilesTester_default.loadTileset(scene2, compositeOfComposite).then( expectRenderComposite ); }); it("renders multiple instanced tilesets", function() { return Cesium3DTilesTester_default.loadTileset(scene2, compositeOfInstanced).then( expectRenderComposite ); }); it("destroys", function() { return Cesium3DTilesTester_default.tileDestroys(scene2, compositeUrl); }); describe("metadata", function() { let metadataClass; let groupMetadata; let contentMetadataClass; let explicitMetadata; let implicitMetadata; beforeAll(function() { metadataClass = import__456.MetadataClass.fromJson({ id: "test", class: { properties: { name: { type: "STRING" }, height: { type: "SCALAR", componentType: "FLOAT32" } } } }); groupMetadata = new import__456.GroupMetadata({ id: "testGroup", group: { properties: { name: "Test Group", height: 35.6 } }, class: metadataClass }); contentMetadataClass = import__456.MetadataClass.fromJson({ id: "contentTest", class: { properties: { author: { type: "STRING" }, color: { type: "VEC3", componentType: "UINT8" } } } }); explicitMetadata = new import__456.ContentMetadata({ content: { properties: { author: "Test Author", color: [255, 0, 0] } }, class: contentMetadataClass }); implicitMetadata = new import__456.ImplicitMetadataView({ metadataTable: {}, class: {}, entityId: 0, propertyTableJson: {} }); }); it("assigning group metadata propagates to inner contents", function() { return Cesium3DTilesTester_default.loadTileset(scene2, compositeUrl).then( function(tileset) { const content = tileset.root.content; content.group = new import__456.Cesium3DContentGroup({ metadata: groupMetadata }); expect(content.group.metadata).toBe(groupMetadata); const innerContents = content.innerContents; for (let i = 0; i < innerContents.length; i++) { expect(innerContents[i].group.metadata).toBe(groupMetadata); } } ); }); it("assigning explicit content metadata propagates to inner contents", function() { return Cesium3DTilesTester_default.loadTileset(scene2, compositeUrl).then( function(tileset) { const content = tileset.root.content; content.metadata = explicitMetadata; expect(content.metadata).toBe(explicitMetadata); const innerContents = content.innerContents; for (let i = 0; i < innerContents.length; i++) { expect(innerContents[i].metadata).toBe(explicitMetadata); } } ); }); it("assigning implicit content metadata propagates to inner contents", function() { return Cesium3DTilesTester_default.loadTileset(scene2, compositeUrl).then( function(tileset) { const content = tileset.root.content; content.metadata = implicitMetadata; expect(content.metadata).toBe(implicitMetadata); const innerContents = content.innerContents; for (let i = 0; i < innerContents.length; i++) { expect(innerContents[i].metadata).toBe(implicitMetadata); } } ); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/ConditionsExpressionSpec.js var import__457 = __toESM(require_Cesium(), 1); describe("Scene/ConditionsExpression", function() { function MockFeature(value) { this._value = value; } MockFeature.prototype.getPropertyInherited = function() { return this._value; }; const jsonExp = { conditions: [ ["${Height} > 100", 'color("blue")'], ["${Height} > 50", 'color("red")'], ["true", 'color("lime")'] ] }; const defines = { halfHeight: "${Height}/2", quarterHeight: "${Height}/4" }; const jsonExpWithDefines = { conditions: [ ["${halfHeight} > 50 && ${halfHeight} < 100", 'color("blue")'], ["${quarterHeight} > 50 && ${quarterHeight} < 52", 'color("red")'], ["true", 'color("lime")'] ] }; const jsonExpMultipleVariables = { conditions: [ ["${Height} > 100", "${FloorColor}"], ["${Height} > 50", "${FloorColor} * 0.5"], ["true", 'color("lime")'] ] }; it("constructs", function() { const expression = new import__457.ConditionsExpression(jsonExp); expect(expression.conditionsExpression).toEqual(jsonExp); }); it("evaluates conditional", function() { const expression = new import__457.ConditionsExpression(jsonExp); expect(expression.evaluateColor(new MockFeature(101))).toEqual(import__457.Color.BLUE); expect(expression.evaluateColor(new MockFeature(52))).toEqual(import__457.Color.RED); expect(expression.evaluateColor(new MockFeature(3))).toEqual(import__457.Color.LIME); }); it("evaluates conditional with defines", function() { const expression = new import__457.ConditionsExpression(jsonExpWithDefines, defines); expect(expression.evaluateColor(new MockFeature(101))).toEqual(import__457.Color.BLUE); expect(expression.evaluateColor(new MockFeature(52))).toEqual(import__457.Color.LIME); expect(expression.evaluateColor(new MockFeature(3))).toEqual(import__457.Color.LIME); }); it("evaluate takes result argument", function() { const result = new import__457.Cartesian4(); const expression = new import__457.ConditionsExpression( jsonExpWithDefines, defines, result ); const value = expression.evaluate(new MockFeature(101), result); expect(value).toEqual(new import__457.Cartesian4(0, 0, 1, 1)); expect(value).toBe(result); }); it("evaluate takes a color result argument", function() { const result = new import__457.Color(); const expression = new import__457.ConditionsExpression( jsonExpWithDefines, defines, result ); const value = expression.evaluate(new MockFeature(101), result); expect(value).toEqual(import__457.Color.BLUE); expect(value).toBe(result); }); it("constructs and evaluates empty conditional", function() { const expression = new import__457.ConditionsExpression({ conditions: [] }); expect(expression._conditions).toEqual([]); expect(expression.evaluate(new MockFeature(101))).toEqual(void 0); expect(expression.evaluate(new MockFeature(52))).toEqual(void 0); expect(expression.evaluate(new MockFeature(3))).toEqual(void 0); }); it("constructs and evaluates empty", function() { const expression = new import__457.ConditionsExpression([]); expect(expression._conditions).toEqual(void 0); expect(expression.evaluate(new MockFeature(101))).toEqual(void 0); expect(expression.evaluate(new MockFeature(52))).toEqual(void 0); expect(expression.evaluate(new MockFeature(3))).toEqual(void 0); }); it("gets shader function", function() { const expression = new import__457.ConditionsExpression(jsonExp); const variableSubstitutionMap = { Height: "a_height" }; const shaderFunction = expression.getShaderFunction( "getColor()", variableSubstitutionMap, {}, "vec4" ); const expected = "vec4 getColor()\n{\n if ((a_height > 100.0))\n {\n return vec4(vec3(0.0, 0.0, 1.0), 1.0);\n }\n else if ((a_height > 50.0))\n {\n return vec4(vec3(1.0, 0.0, 0.0), 1.0);\n }\n else if (true)\n {\n return vec4(vec3(0.0, 1.0, 0.0), 1.0);\n }\n return vec4(1.0);\n}\n"; expect(shaderFunction).toEqual(expected); }); it("return undefined shader function when there are no conditions", function() { const expression = new import__457.ConditionsExpression([]); const shaderFunction = expression.getShaderFunction( "getColor", {}, {}, "vec4" ); expect(shaderFunction).toBeUndefined(); }); it("gets variables", function() { const expression = new import__457.ConditionsExpression(jsonExpMultipleVariables); const variables = expression.getVariables(); expect(variables.sort()).toEqual(["FloorColor", "Height"]); }); it("getVariables returns empty array when there are no conditions", function() { const expression = new import__457.ConditionsExpression([]); const variables = expression.getVariables(); expect(variables).toEqual([]); }); }); // packages/engine/Specs/Scene/ConeEmitterSpec.js var import__458 = __toESM(require_Cesium(), 1); var import__459 = __toESM(require_Cesium(), 1); describe("Scene/ConeEmitter", function() { it("default constructor", function() { const emitter = new import__458.ConeEmitter(); expect(emitter.angle).toEqual(import__459.Math.toRadians(30)); }); it("constructor", function() { const emitter = new import__458.ConeEmitter(import__459.Math.PI_OVER_SIX); expect(emitter.angle).toEqual(import__459.Math.PI_OVER_SIX); }); it("angle setter", function() { const emitter = new import__458.ConeEmitter(); emitter.angle = import__459.Math.PI_OVER_SIX; expect(emitter.angle).toEqual(import__459.Math.PI_OVER_SIX); }); it("angle setter throws with invalid value", function() { const emitter = new import__458.ConeEmitter(); expect(function() { emitter.angle = void 0; }).toThrowDeveloperError(); }); it("emits", function() { const emitter = new import__458.ConeEmitter(import__459.Math.PI_OVER_SIX); const particle = new import__458.Particle(); for (let i = 0; i < 1e3; ++i) { emitter.emit(particle); expect(particle.position).toEqual(import__458.Cartesian3.ZERO); expect(import__458.Cartesian3.magnitude(particle.velocity)).toEqualEpsilon( 1, import__459.Math.EPSILON14 ); expect(Math.acos(particle.velocity.z)).toBeLessThanOrEqual(emitter.angle); } }); }); // packages/engine/Specs/Scene/ContentMetadataSpec.js var import__460 = __toESM(require_Cesium(), 1); describe("Scene/ContentMetadata", function() { const contentClassWithNoProperties = import__460.MetadataClass.fromJson({ id: "content", class: {} }); const contentClass = import__460.MetadataClass.fromJson({ id: "content", class: { properties: { color: { type: "SCALAR", componentType: "UINT8", array: true, count: 3, semantic: "COLOR" }, author: { type: "STRING" } } } }); const contentMetadataJson = { class: "content", properties: { color: [255, 125, 0], author: "Cesium" } }; let contentMetadata; beforeEach(function() { contentMetadata = new import__460.ContentMetadata({ content: contentMetadataJson, class: contentClass }); }); it("throws without content", function() { expect(function() { contentMetadata = new import__460.ContentMetadata({ content: void 0, class: contentClass }); }).toThrowDeveloperError(); }); it("throws without class", function() { expect(function() { contentMetadata = new import__460.ContentMetadata({ content: {}, class: void 0 }); }).toThrowDeveloperError(); }); it("creates content metadata with default values", function() { const metadata = new import__460.ContentMetadata({ content: {}, class: contentClassWithNoProperties }); expect(metadata.extras).toBeUndefined(); expect(metadata.extensions).toBeUndefined(); }); it("creates content metadata", function() { const properties = { color: [0, 0, 255], author: "Sample Author" }; const extras = { version: "0.0" }; const extensions = { "3DTILES_extension": {} }; contentMetadata = new import__460.ContentMetadata({ content: { class: "content", properties, extras, extensions }, class: contentClass }); expect(contentMetadata.class).toBe(contentClass); expect(contentMetadata.getProperty("color")).toEqual(properties.color); expect(contentMetadata.getProperty("author")).toEqual(properties.author); expect(contentMetadata.extras).toBe(extras); expect(contentMetadata.extensions).toBe(extensions); }); it("hasProperty returns true if the content has this property", function() { expect(contentMetadata.hasProperty("color")).toBe(true); }); it("hasProperty returns false if the content does not have this property", function() { expect(contentMetadata.hasProperty("numberOfPoints")).toBe(false); }); it("hasPropertyBySemantic returns true if the content has a property with the given semantic", function() { expect(contentMetadata.hasPropertyBySemantic("COLOR")).toBe(true); }); it("hasPropertyBySemantic returns false if the content does not have a property with the given semantic", function() { expect(contentMetadata.hasProperty("NUMBER_OF_POINTS")).toBe(false); }); it("getPropertyIds returns array of property IDs", function() { const propertyIds = contentMetadata.getPropertyIds([]); propertyIds.sort(); expect(propertyIds).toEqual(["author", "color"]); }); it("getProperty throws if a property does not exist", function() { expect(function() { return contentMetadata.getProperty("numberOfPoints"); }).toThrowDeveloperError(); }); it("getProperty returns the property value", function() { expect(contentMetadata.getProperty("color")).toEqual([255, 125, 0]); expect(contentMetadata.getProperty("author")).toBe("Cesium"); }); it("setProperty returns false if property doesn't exist", function() { expect(contentMetadata.setProperty("numberOfPoints", 10)).toBe(false); }); it("setProperty sets property value", function() { expect(contentMetadata.getProperty("author")).toBe("Cesium"); expect(contentMetadata.setProperty("author", "Sample Author")).toBe(true); expect(contentMetadata.getProperty("author")).toBe("Sample Author"); }); it("getPropertyBySemantic returns undefined when there's no property with the given semantic", function() { expect(contentMetadata.getPropertyBySemantic("AUTHOR")).not.toBeDefined(); }); it("getPropertyBySemantic returns the property value", function() { expect(contentMetadata.getPropertyBySemantic("COLOR")).toEqual([ 255, 125, 0 ]); }); it("setPropertyBySemantic sets property value", function() { expect(contentMetadata.getPropertyBySemantic("COLOR")).toEqual([ 255, 125, 0 ]); expect(contentMetadata.setPropertyBySemantic("COLOR", [0, 0, 0])).toBe( true ); expect(contentMetadata.getPropertyBySemantic("COLOR")).toEqual([0, 0, 0]); }); it("setPropertyBySemantic returns false if the semantic doesn't exist", function() { expect(contentMetadata.setPropertyBySemantic("AUTHOR", "Test Author")).toBe( false ); }); }); // packages/engine/Specs/Scene/CreditDisplaySpec.js var import__461 = __toESM(require_Cesium(), 1); describe("Scene/CreditDisplay", function() { let container; let creditDisplay; let imageUrl; describe("Scene/CreditDisplay under document.head", function() { beforeEach(function() { imageUrl = absolutize_default("./Data/Images/Green.png"); container = document.createElement("div"); container.id = "credit-container"; document.body.appendChild(container); }); afterEach(function() { document.body.removeChild(container); import__461.CreditDisplay.cesiumCredit = void 0; import__461.CreditDisplay._cesiumCreditInitialized = false; if ((0, import__461.defined)(creditDisplay)) { creditDisplay.destroy(); creditDisplay = void 0; } }); runTests(); }); describe("Scene/CreditDisplay under shadowRoot", function() { beforeEach(function() { imageUrl = absolutize_default("./Data/Images/Green.png"); container = document.createElement("div"); container.id = "credit-container"; const outerContainer = document.createElement("div"); outerContainer.id = "credit-outer-container"; const shadowRoot = outerContainer.attachShadow({ mode: "open" }); shadowRoot.appendChild(container); document.body.appendChild(outerContainer); }); afterEach(function() { const element = document.querySelector("credit-outer-container"); if ((0, import__461.defined)(element)) { element.remove(); } import__461.CreditDisplay.cesiumCredit = void 0; import__461.CreditDisplay._cesiumCreditInitialized = false; if ((0, import__461.defined)(creditDisplay)) { creditDisplay.destroy(); creditDisplay = void 0; } }); runTests(); }); it("credit display throws with no container", function() { expect(function() { return new import__461.CreditDisplay(); }).toThrowDeveloperError(); }); it("credits have unique ids", function() { const credit1 = new import__461.Credit('credit1'); const credit2 = new import__461.Credit('credit2'); expect(credit1.id).not.toEqual(credit2.id); const credit3 = new import__461.Credit('credit1'); expect(credit1.id).toEqual(credit3.id); }); it("credit clone works", function() { const credit1 = new import__461.Credit('credit1'); const credit2 = import__461.Credit.clone(credit1); expect(credit1).toEqual(credit2); const credit3 = import__461.Credit.clone(void 0); expect(credit3).toBeUndefined(); }); function runTests() { function beginFrame(creditDisplay2) { creditDisplay2.beginFrame(); } it("addCreditToNextFrame throws when credit is undefined", function() { expect(function() { creditDisplay = new import__461.CreditDisplay(container); creditDisplay.addCreditToNextFrame(); }).toThrowDeveloperError(); }); it("addStaticCredit throws when credit is undefined", function() { expect(function() { creditDisplay = new import__461.CreditDisplay(container); creditDisplay.addStaticCredit(); }).toThrowDeveloperError(); }); it("removeStaticCredit throws when credit is undefined", function() { expect(function() { creditDisplay = new import__461.CreditDisplay(container); creditDisplay.removeStaticCredit(); }).toThrowDeveloperError(); }); it("credit display displays a credit", function() { creditDisplay = new import__461.CreditDisplay(container); const credit = new import__461.Credit( 'CesiumJS.org', true ); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit); creditDisplay.endFrame(); const creditContainer = container.childNodes[1]; expect(creditContainer.childNodes.length).toEqual(1); const child10 = creditContainer.childNodes[0]; expect(child10.childNodes.length).toEqual(1); }); it("credit display updates html when credits change", function() { const credit1 = new import__461.Credit("credit1", true); const credit2 = new import__461.Credit("credit2", true); creditDisplay = new import__461.CreditDisplay(container); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit1); creditDisplay.endFrame(); const innerHTMLWithCredit1 = container.innerHTML; const creditContainer = container.childNodes[1]; expect(creditContainer.childNodes.length).toEqual(1); expect(creditContainer.childNodes[0].innerHTML).toEqual("credit1"); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.endFrame(); const innerHTMLWithCredit2 = container.innerHTML; expect(innerHTMLWithCredit2).not.toEqual(innerHTMLWithCredit1); expect(creditContainer.childNodes.length).toEqual(1); expect(creditContainer.childNodes[0].innerHTML).toEqual("credit2"); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit1); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.endFrame(); const innerHTMLWithCredit1AndCredit2 = container.innerHTML; expect(innerHTMLWithCredit1AndCredit2).not.toEqual(innerHTMLWithCredit1); expect(innerHTMLWithCredit1AndCredit2).not.toEqual(innerHTMLWithCredit2); expect(creditContainer.childNodes.length).toEqual(3); expect(creditContainer.childNodes[0].innerHTML).toEqual("credit1"); expect(creditContainer.childNodes[2].innerHTML).toEqual("credit2"); beginFrame(creditDisplay); creditDisplay.endFrame(); expect(container.innerHTML).not.toEqual(innerHTMLWithCredit1); expect(container.innerHTML).not.toEqual(innerHTMLWithCredit2); expect(container.innerHTML).not.toEqual(innerHTMLWithCredit1AndCredit2); expect(creditContainer.childNodes.length).toEqual(0); }); it("credit display uses delimeter", function() { const credit1 = new import__461.Credit("credit1", true); const credit2 = new import__461.Credit("credit2", true); const delimiter = ", "; creditDisplay = new import__461.CreditDisplay(container, ", "); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit1); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.endFrame(); const creditContainer = container.childNodes[1]; expect(creditContainer.childNodes.length).toEqual(3); expect(creditContainer.childNodes[0].innerHTML).toEqual("credit1"); expect(creditContainer.childNodes[1].innerHTML).toEqual(delimiter); expect(creditContainer.childNodes[2].innerHTML).toEqual("credit2"); }); it("credit display manages delimeters correctly for text credits", function() { const credit1 = new import__461.Credit("credit1", true); const credit2 = new import__461.Credit("credit2", true); const credit3 = new import__461.Credit("credit3", true); const delimiter = ", "; creditDisplay = new import__461.CreditDisplay(container, delimiter); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit1); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.addCreditToNextFrame(credit3); creditDisplay.endFrame(); const creditContainer = container.childNodes[1]; expect(creditContainer.childNodes.length).toEqual(5); expect(creditContainer.childNodes[0]).toEqual(credit1.element); expect(creditContainer.childNodes[1].innerHTML).toEqual(delimiter); expect(creditContainer.childNodes[2]).toEqual(credit2.element); expect(creditContainer.childNodes[3].innerHTML).toEqual(delimiter); expect(creditContainer.childNodes[4]).toEqual(credit3.element); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.addCreditToNextFrame(credit3); creditDisplay.endFrame(); expect(creditContainer.childNodes.length).toEqual(3); expect(creditContainer.childNodes[0]).toEqual(credit2.element); expect(creditContainer.childNodes[1].innerHTML).toEqual(delimiter); expect(creditContainer.childNodes[2]).toEqual(credit3.element); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.endFrame(); expect(creditContainer.childNodes.length).toEqual(1); expect(creditContainer.childNodes[0]).toEqual(credit2.element); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.addCreditToNextFrame(credit3); creditDisplay.endFrame(); expect(creditContainer.childNodes.length).toEqual(3); expect(creditContainer.childNodes[0]).toEqual(credit2.element); expect(creditContainer.childNodes[1].innerHTML).toEqual(delimiter); expect(creditContainer.childNodes[2]).toEqual(credit3.element); }); it("credit display displays a static credit", function() { const defaultCredit = new import__461.Credit("default credit", true); const credit1 = new import__461.Credit("credit1", true); creditDisplay = new import__461.CreditDisplay(container, ", "); creditDisplay.addStaticCredit(defaultCredit); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit1); creditDisplay.endFrame(); const creditContainer = container.childNodes[1]; expect(creditContainer.childNodes.length).toEqual(3); expect(creditContainer.childNodes[0]).toEqual(defaultCredit.element); expect(creditContainer.childNodes[1].innerHTML).toEqual(", "); expect(creditContainer.childNodes[2]).toEqual(credit1.element); beginFrame(creditDisplay); creditDisplay.endFrame(); expect(creditContainer.childNodes.length).toEqual(1); expect(creditContainer.childNodes[0]).toEqual(defaultCredit.element); }); it("credit display displays credits when a static credit is removed", function() { const defaultCredit = new import__461.Credit("default credit", true); const credit1 = new import__461.Credit("credit1", true); creditDisplay = new import__461.CreditDisplay(container, ", "); creditDisplay.addStaticCredit(defaultCredit); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit1); creditDisplay.endFrame(); const creditContainer = container.childNodes[1]; expect(creditContainer.childNodes.length).toEqual(3); expect(creditContainer.childNodes[0]).toEqual(defaultCredit.element); expect(creditContainer.childNodes[1].innerHTML).toEqual(", "); expect(creditContainer.childNodes[2]).toEqual(credit1.element); creditDisplay.removeStaticCredit(defaultCredit); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit1); creditDisplay.endFrame(); expect(creditContainer.childNodes.length).toEqual(1); expect(creditContainer.childNodes[0]).toEqual(credit1.element); }); it("credit display only displays one if two credits are equal", function() { const credit1 = new import__461.Credit("credit1", true); const credit2 = new import__461.Credit("credit1", true); creditDisplay = new import__461.CreditDisplay(container); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit1); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.endFrame(); const creditContainer = container.childNodes[1]; expect(creditContainer.childNodes.length).toEqual(1); expect(creditContainer.childNodes[0].innerHTML).toEqual("credit1"); }); it("credit display keeps count of repeated credits", function() { const repeatedCreditCount = 4; creditDisplay = new import__461.CreditDisplay(container); beginFrame(creditDisplay); for (let i = 0; i < repeatedCreditCount; i++) { creditDisplay.addCreditToNextFrame(new import__461.Credit("credit1", true)); } creditDisplay.addCreditToNextFrame(new import__461.Credit("credit2", true)); const credits = creditDisplay._currentFrameCredits.screenCredits.values; expect(credits.length).toEqual(2); const firstCredit = credits[0]; expect(firstCredit.credit.html).toEqual("credit1"); expect(firstCredit.count).toEqual(repeatedCreditCount); const secondCredit = credits[1]; expect(secondCredit.credit.html).toEqual("credit2"); expect(secondCredit.count).toEqual(1); }); it("credit display sorts credits by frequency", function() { const creditCounts = [2, 10, 6, 1]; const credit1 = new import__461.Credit("credit1", true); const credit2 = new import__461.Credit("credit2", true); const credit3 = new import__461.Credit("credit3", true); const credit4 = new import__461.Credit("credit4", true); creditDisplay = new import__461.CreditDisplay(container); beginFrame(creditDisplay); for (let i = 0; i < creditCounts.length; i++) { const creditString = "credit".concat((i + 1).toString()); const count = creditCounts[i]; for (let j = 0; j < count; j++) { creditDisplay.addCreditToNextFrame(new import__461.Credit(creditString, true)); } } creditDisplay.endFrame(); const creditContainer = container.childNodes[1]; expect(creditContainer.childNodes.length).toEqual(7); expect(creditContainer.childNodes[0]).toEqual(credit2.element); expect(creditContainer.childNodes[2]).toEqual(credit3.element); expect(creditContainer.childNodes[4]).toEqual(credit1.element); expect(creditContainer.childNodes[6]).toEqual(credit4.element); }); it("credit display sorts credits by frequency with static credit", function() { const defaultCredit = new import__461.Credit("default credit", true); const creditCounts = [2, 10, 6, 1]; const credit1 = new import__461.Credit("credit1", true); const credit2 = new import__461.Credit("credit2", true); const credit3 = new import__461.Credit("credit3", true); const credit4 = new import__461.Credit("credit4", true); creditDisplay = new import__461.CreditDisplay(container); creditDisplay.addStaticCredit(defaultCredit); beginFrame(creditDisplay); for (let i = 0; i < creditCounts.length; i++) { const creditString = "credit".concat((i + 1).toString()); const count = creditCounts[i]; for (let j = 0; j < count; j++) { creditDisplay.addCreditToNextFrame(new import__461.Credit(creditString, true)); } } creditDisplay.endFrame(); const creditContainer = container.childNodes[1]; expect(creditContainer.childNodes.length).toEqual(9); expect(creditContainer.childNodes[0]).toEqual(defaultCredit.element); expect(creditContainer.childNodes[2]).toEqual(credit2.element); expect(creditContainer.childNodes[4]).toEqual(credit3.element); expect(creditContainer.childNodes[6]).toEqual(credit1.element); expect(creditContainer.childNodes[8]).toEqual(credit4.element); }); it("displays credits in a lightbox", function() { const credit1 = new import__461.Credit("credit1"); const credit2 = new import__461.Credit(``); creditDisplay = new import__461.CreditDisplay(container); const creditList = creditDisplay._creditList; creditDisplay.showLightbox(); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit1); creditDisplay.endFrame(); creditDisplay.update(); let innerHTML = creditList.innerHTML; expect(creditList.childNodes.length).toEqual(1); expect(creditList.childNodes[0].childNodes[0]).toEqual(credit1.element); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.endFrame(); creditDisplay.update(); expect(creditList.innerHTML).not.toEqual(innerHTML); innerHTML = creditList.innerHTML; expect(creditList.childNodes.length).toEqual(1); expect(creditList.childNodes[0].childNodes[0]).toEqual(credit2.element); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit1); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.endFrame(); creditDisplay.update(); expect(creditList.innerHTML).not.toEqual(innerHTML); innerHTML = creditList.innerHTML; expect(creditList.childNodes.length).toEqual(2); beginFrame(creditDisplay); creditDisplay.endFrame(); creditDisplay.update(); expect(creditList.innerHTML).not.toEqual(innerHTML); expect(creditList.childNodes.length).toEqual(0); creditDisplay.hideLightbox(); }); it("displays static credits in a lightbox", function() { const credit1 = new import__461.Credit("credit1"); const credit2 = new import__461.Credit(``); creditDisplay = new import__461.CreditDisplay(container); const creditList = creditDisplay._creditList; creditDisplay.addStaticCredit(credit1); creditDisplay.showLightbox(); beginFrame(creditDisplay); creditDisplay.endFrame(); creditDisplay.update(); let innerHTML = creditList.innerHTML; expect(creditList.childNodes.length).toEqual(1); expect(creditList.childNodes[0].childNodes[0]).toEqual(credit1.element); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.endFrame(); creditDisplay.update(); expect(creditList.innerHTML).not.toEqual(innerHTML); innerHTML = creditList.innerHTML; expect(creditList.childNodes.length).toEqual(2); expect(creditList.childNodes[0].childNodes[0]).toEqual(credit1.element); expect(creditList.childNodes[1].childNodes[0]).toEqual(credit2.element); beginFrame(creditDisplay); creditDisplay.endFrame(); expect(creditList.childNodes.length).toEqual(1); expect(creditList.childNodes[0].childNodes[0]).toEqual(credit1.element); creditDisplay.hideLightbox(); }); it("credit display displays credits when a static credit is removed from the lightbox", function() { const credit1 = new import__461.Credit("credit1"); const credit2 = new import__461.Credit(``); creditDisplay = new import__461.CreditDisplay(container, ", "); const creditList = creditDisplay._creditList; creditDisplay.showLightbox(); creditDisplay.addStaticCredit(credit1); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.endFrame(); creditDisplay.update(); expect(creditList.childNodes.length).toEqual(2); expect(creditList.childNodes[0].childNodes[0]).toEqual(credit1.element); expect(creditList.childNodes[1].childNodes[0]).toEqual(credit2.element); creditDisplay.removeStaticCredit(credit1); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.endFrame(); creditDisplay.update(); expect(creditList.childNodes.length).toEqual(1); expect(creditList.childNodes[0].childNodes[0]).toEqual(credit2.element); }); it("handles showOnScreen toggles at runtime", function() { const credit1 = new import__461.Credit("credit1", true); const credit2 = new import__461.Credit("credit2", true); creditDisplay = new import__461.CreditDisplay(container); creditDisplay.addStaticCredit(credit1); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.endFrame(); creditDisplay.update(); const screenCreditContainer = container.childNodes[1]; expect(screenCreditContainer.childNodes.length).toEqual(3); expect(screenCreditContainer.childNodes[0]).toEqual(credit1.element); expect(screenCreditContainer.childNodes[2]).toEqual(credit2.element); credit1.showOnScreen = false; credit2.showOnScreen = false; creditDisplay.showLightbox(); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.endFrame(); const lightboxCreditList = creditDisplay._creditList; expect(lightboxCreditList.childNodes.length).toEqual(2); expect(lightboxCreditList.childNodes[0].childNodes[0]).toEqual( credit1.element ); expect(lightboxCreditList.childNodes[1].childNodes[0]).toEqual( credit2.element ); credit1.showOnScreen = true; credit2.showOnScreen = true; creditDisplay.hideLightbox(); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.endFrame(); expect(screenCreditContainer.childNodes.length).toEqual(3); expect(screenCreditContainer.childNodes[0]).toEqual(credit1.element); expect(screenCreditContainer.childNodes[2]).toEqual(credit2.element); }); it("renders lightbox credits", function() { const credit1 = new import__461.Credit("credit1"); const credit2 = new import__461.Credit(``); creditDisplay = new import__461.CreditDisplay(container); const creditList = creditDisplay._creditList; beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit1); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.endFrame(); creditDisplay.update(); expect(creditList.childNodes.length).toEqual(2); creditDisplay.showLightbox(); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit1); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.endFrame(); creditDisplay.update(); expect(creditList.childNodes.length).toEqual(2); creditDisplay.hideLightbox(); }); it("updates lightbox when a new frames are not rendered", function() { const credit1 = new import__461.Credit("credit1"); const credit2 = new import__461.Credit(``); creditDisplay = new import__461.CreditDisplay(container); const creditList = creditDisplay._creditList; creditDisplay.update(); expect(creditList.childNodes.length).toEqual(0); beginFrame(creditDisplay); creditDisplay.addCreditToNextFrame(credit1); creditDisplay.addCreditToNextFrame(credit2); creditDisplay.endFrame(); creditDisplay.update(); expect(creditList.childNodes.length).toEqual(2); creditDisplay.showLightbox(); creditDisplay.update(); expect(creditList.childNodes.length).toEqual(2); creditDisplay.hideLightbox(); creditDisplay.update(); expect(creditList.childNodes.length).toEqual(2); creditDisplay.hideLightbox(); }); it("works if Cesium credit removed", function() { creditDisplay = new import__461.CreditDisplay(container); const cesiumCredit = import__461.CreditDisplay.cesiumCredit; import__461.CreditDisplay.cesiumCredit = void 0; creditDisplay.beginFrame(); creditDisplay.endFrame(); expect(creditDisplay._cesiumCreditContainer.childNodes.length).toBe(0); import__461.CreditDisplay.cesiumCredit = cesiumCredit; }); it("each credit display has a unique cesium credit", function() { creditDisplay = new import__461.CreditDisplay(container); const container2 = document.createElement("div"); const creditDisplay2 = new import__461.CreditDisplay(container2); expect(creditDisplay._currentCesiumCredit).toEqual( creditDisplay2._currentCesiumCredit ); expect(creditDisplay._currentCesiumCredit).not.toBe( creditDisplay2._currentCesiumCredit ); }); } }); // packages/engine/Specs/Scene/DebugAppearanceSpec.js var import__462 = __toESM(require_Cesium(), 1); describe( "Scene/DebugAppearance", function() { let scene2; let primitive; const rectangle = import__462.Rectangle.fromDegrees(-10, -10, 10, 10); beforeAll(function() { scene2 = createScene_default(); scene2.primitives.destroyPrimitives = false; scene2.frameState.scene3DOnly = false; }); beforeEach(function() { scene2.camera.setView({ destination: rectangle }); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.primitives.removeAll(); primitive = primitive && !primitive.isDestroyed() && primitive.destroy(); }); function createInstance(vertexFormat) { return new import__462.GeometryInstance({ geometry: new import__462.RectangleGeometry({ vertexFormat: (0, import__462.defaultValue)(vertexFormat, import__462.VertexFormat.ALL), rectangle }) }); } it("constructor throws without attributeName", function() { expect(function() { return new import__462.DebugAppearance(); }).toThrowDeveloperError(); }); it("default construct with normal, bitangent, or tangent attribute name", function() { const a = new import__462.DebugAppearance({ attributeName: "normal", perInstanceAttribute: false }); expect(a.vertexShaderSource).toBeDefined(); expect(a.vertexShaderSource.indexOf("normal")).toBeGreaterThan(-1); expect(a.vertexShaderSource.indexOf("v_normal")).toBeGreaterThan(-1); expect(a.fragmentShaderSource).toBeDefined(); expect(a.fragmentShaderSource.indexOf("v_normal")).toBeGreaterThan(-1); expect(a.material).not.toBeDefined(); expect(a.attributeName).toEqual("normal"); expect(a.glslDatatype).toEqual("vec3"); expect(a.renderState).toEqual( import__462.Appearance.getDefaultRenderState(false, false) ); expect(a.translucent).toEqual(false); expect(a.closed).toEqual(false); }); it("default construct with st attribute name", function() { const a = new import__462.DebugAppearance({ attributeName: "st", perInstanceAttribute: false }); expect(a.vertexShaderSource).toBeDefined(); expect(a.vertexShaderSource.indexOf("st")).toBeGreaterThan(-1); expect(a.vertexShaderSource.indexOf("v_st")).toBeGreaterThan(-1); expect(a.fragmentShaderSource).toBeDefined(); expect(a.fragmentShaderSource.indexOf("v_st")).toBeGreaterThan(-1); expect(a.material).not.toBeDefined(); expect(a.attributeName).toEqual("st"); expect(a.glslDatatype).toEqual("vec2"); expect(a.renderState).toEqual( import__462.Appearance.getDefaultRenderState(false, false) ); expect(a.translucent).toEqual(false); expect(a.closed).toEqual(false); }); it("debug appearance with float attribute name", function() { const a = new import__462.DebugAppearance({ attributeName: "rotation", glslDatatype: "float", perInstanceAttribute: true }); expect(a.vertexShaderSource).toBeDefined(); expect(a.vertexShaderSource.indexOf("rotation")).toBeGreaterThan(-1); expect(a.vertexShaderSource.indexOf("v_rotation")).toBeGreaterThan(-1); expect(a.fragmentShaderSource).toBeDefined(); expect(a.fragmentShaderSource.indexOf("v_rotation")).toBeGreaterThan(-1); expect(a.material).not.toBeDefined(); expect(a.attributeName).toEqual("rotation"); expect(a.glslDatatype).toEqual("float"); expect(a.renderState).toEqual( import__462.Appearance.getDefaultRenderState(false, false) ); expect(a.translucent).toEqual(false); expect(a.closed).toEqual(false); }); it("debug appearance with vec3 attribute name", function() { const a = new import__462.DebugAppearance({ attributeName: "str", glslDatatype: "vec3", perInstanceAttribute: false }); expect(a.vertexShaderSource).toBeDefined(); expect(a.vertexShaderSource.indexOf("str")).toBeGreaterThan(-1); expect(a.vertexShaderSource.indexOf("v_str")).toBeGreaterThan(-1); expect(a.fragmentShaderSource).toBeDefined(); expect(a.fragmentShaderSource.indexOf("v_str")).toBeGreaterThan(-1); expect(a.material).not.toBeDefined(); expect(a.attributeName).toEqual("str"); expect(a.glslDatatype).toEqual("vec3"); expect(a.renderState).toEqual( import__462.Appearance.getDefaultRenderState(false, false) ); expect(a.translucent).toEqual(false); expect(a.closed).toEqual(false); }); it("debug appearance with vec4 attribute name", function() { const a = new import__462.DebugAppearance({ attributeName: "quaternion", glslDatatype: "vec4", perInstanceAttribute: true }); expect(a.vertexShaderSource).toBeDefined(); expect(a.vertexShaderSource.indexOf("quaternion")).toBeGreaterThan(-1); expect(a.vertexShaderSource.indexOf("v_quaternion")).toBeGreaterThan(-1); expect(a.fragmentShaderSource).toBeDefined(); expect(a.fragmentShaderSource.indexOf("v_quaternion")).toBeGreaterThan( -1 ); expect(a.material).not.toBeDefined(); expect(a.attributeName).toEqual("quaternion"); expect(a.glslDatatype).toEqual("vec4"); expect(a.renderState).toEqual( import__462.Appearance.getDefaultRenderState(false, false) ); expect(a.translucent).toEqual(false); expect(a.closed).toEqual(false); }); it("debug appearance throws with invalid glsl datatype", function() { expect(function() { return new import__462.DebugAppearance({ attributeName: "invalid_datatype", glslDatatype: "invalid", perInstanceAttribute: true }); }).toThrowDeveloperError(); }); it("renders normal", function() { const vertexFormat = new import__462.VertexFormat({ position: true, normal: true }); primitive = new import__462.Primitive({ geometryInstances: createInstance(vertexFormat), appearance: new import__462.DebugAppearance({ attributeName: "normal", perInstanceAttribute: false }), asynchronous: false, compressVertices: false }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders bitangent", function() { const vertexFormat = new import__462.VertexFormat({ position: true, normal: true, bitangent: true }); primitive = new import__462.Primitive({ geometryInstances: createInstance(vertexFormat), appearance: new import__462.DebugAppearance({ attributeName: "bitangent", perInstanceAttribute: false }), asynchronous: false, compressVertices: false }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders tangent", function() { const vertexFormat = new import__462.VertexFormat({ position: true, normal: true, tangent: true }); primitive = new import__462.Primitive({ geometryInstances: createInstance(vertexFormat), appearance: new import__462.DebugAppearance({ attributeName: "tangent", perInstanceAttribute: false }), asynchronous: false, compressVertices: false }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders st", function() { const vertexFormat = new import__462.VertexFormat({ position: true, st: true }); primitive = new import__462.Primitive({ geometryInstances: createInstance(vertexFormat), appearance: new import__462.DebugAppearance({ attributeName: "st", perInstanceAttribute: false }), asynchronous: false, compressVertices: false }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders float", function() { const rectangleInstance = createInstance(); rectangleInstance.attributes = { debug: new import__462.GeometryInstanceAttribute({ componentDatatype: import__462.ComponentDatatype.FLOAT, componentsPerAttribute: 1, value: [1] }) }; primitive = new import__462.Primitive({ geometryInstances: rectangleInstance, appearance: new import__462.DebugAppearance({ attributeName: "debug", glslDatatype: "float", perInstanceAttribute: true }), asynchronous: false }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders vec2", function() { const rectangleInstance = createInstance(); rectangleInstance.attributes = { debug: new import__462.GeometryInstanceAttribute({ componentDatatype: import__462.ComponentDatatype.FLOAT, componentsPerAttribute: 2, value: [1, 2] }) }; primitive = new import__462.Primitive({ geometryInstances: rectangleInstance, appearance: new import__462.DebugAppearance({ attributeName: "debug", glslDatatype: "vec2", perInstanceAttribute: true }), asynchronous: false }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders vec3", function() { const rectangleInstance = createInstance(); rectangleInstance.attributes = { debug: new import__462.GeometryInstanceAttribute({ componentDatatype: import__462.ComponentDatatype.FLOAT, componentsPerAttribute: 3, value: [1, 2, 3] }) }; primitive = new import__462.Primitive({ geometryInstances: rectangleInstance, appearance: new import__462.DebugAppearance({ attributeName: "debug", glslDatatype: "vec3", perInstanceAttribute: true }), asynchronous: false }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders vec4", function() { const rectangleInstance = createInstance(); rectangleInstance.attributes = { debug: new import__462.GeometryInstanceAttribute({ componentDatatype: import__462.ComponentDatatype.FLOAT, componentsPerAttribute: 4, value: [1, 2, 3, 4] }) }; primitive = new import__462.Primitive({ geometryInstances: rectangleInstance, appearance: new import__462.DebugAppearance({ attributeName: "debug", glslDatatype: "vec4", perInstanceAttribute: true }), asynchronous: false }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive); expect(scene2).notToRender([0, 0, 0, 255]); }); }, "WebGL" ); // packages/engine/Specs/Scene/DebugCameraPrimitiveSpec.js var import__463 = __toESM(require_Cesium(), 1); describe( "Scene/DebugCameraPrimitive", function() { let scene2; let camera; beforeAll(function() { scene2 = createScene_default({ scene3DOnly: true }); scene2.camera.position = new import__463.Cartesian3(0, 0, 0); scene2.camera.direction = import__463.Cartesian3.negate( import__463.Cartesian3.UNIT_X, new import__463.Cartesian3() ); scene2.camera.up = import__463.Cartesian3.clone(import__463.Cartesian3.UNIT_Z); scene2.camera.frustum.near = 1; scene2.camera.frustum.far = 500; camera = import__463.Camera.clone(scene2.camera); scene2.camera.zoomOut(1); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.primitives.removeAll(); }); it("throws if options.camera is undefined", function() { expect(function() { return new import__463.DebugCameraPrimitive(); }).toThrowDeveloperError(); }); it("gets the default properties", function() { const p = new import__463.DebugCameraPrimitive({ camera }); expect(p.show).toEqual(true); expect(p.id).not.toBeDefined(); p.destroy(); }); it("constructs with options", function() { const p = new import__463.DebugCameraPrimitive({ camera, frustumSplits: [0.1, 1e3], color: import__463.Color.YELLOW, updateOnChange: false, show: false, id: "id" }); expect(p.show).toEqual(false); expect(p.id).toEqual("id"); p.destroy(); }); it("renders", function() { scene2.primitives.add( new import__463.DebugCameraPrimitive({ camera }) ); expect(scene2).notToRender([0, 0, 0, 255]); }); it("does not render when show is false", function() { scene2.primitives.add( new import__463.DebugCameraPrimitive({ camera, show: false }) ); expect(scene2).toRender([0, 0, 0, 255]); }); it("updates when underlying camera changes", function() { const p = scene2.primitives.add( new import__463.DebugCameraPrimitive({ camera }) ); scene2.renderForSpecs(); const primitive = p._outlinePrimitives[0]; scene2.renderForSpecs(); expect(p._outlinePrimitives[0]).not.toBe(primitive); }); it("does not update when updateOnChange is false", function() { const p = scene2.primitives.add( new import__463.DebugCameraPrimitive({ camera, updateOnChange: false }) ); scene2.renderForSpecs(); const primitive = p._primitive; scene2.renderForSpecs(); expect(p._primitive).toBe(primitive); }); it("is picked", function() { const p = scene2.primitives.add( new import__463.DebugCameraPrimitive({ camera, id: "id" }) ); expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toBe(p); expect(result.id).toBe("id"); }); }); it("isDestroyed", function() { const p = scene2.primitives.add( new import__463.DebugCameraPrimitive({ camera }) ); expect(p.isDestroyed()).toEqual(false); scene2.primitives.remove(p); expect(p.isDestroyed()).toEqual(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/DebugModelMatrixPrimitiveSpec.js var import__464 = __toESM(require_Cesium(), 1); describe( "Scene/DebugModelMatrixPrimitive", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); const camera = scene2.camera; camera.position = new import__464.Cartesian3(1.02, 0, 0); camera.direction = import__464.Cartesian3.negate(import__464.Cartesian3.UNIT_X, new import__464.Cartesian3()); camera.up = import__464.Cartesian3.clone(import__464.Cartesian3.UNIT_Z); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.primitives.removeAll(); }); it("gets the default properties", function() { const p = new import__464.DebugModelMatrixPrimitive(); expect(p.length).toEqual(1e7); expect(p.width).toEqual(2); expect(p.modelMatrix).toEqual(import__464.Matrix4.IDENTITY); expect(p.show).toEqual(true); expect(p.id).not.toBeDefined(); p.destroy(); }); it("Constructs with options", function() { const p = new import__464.DebugModelMatrixPrimitive({ length: 10, width: 1, modelMatrix: import__464.Matrix4.fromUniformScale(2), show: false, id: "id" }); expect(p.length).toEqual(10); expect(p.width).toEqual(1); expect(p.modelMatrix).toEqual(import__464.Matrix4.fromUniformScale(2)); expect(p.show).toEqual(false); expect(p.id).toEqual("id"); p.destroy(); }); it("renders", function() { const p = scene2.primitives.add(new import__464.DebugModelMatrixPrimitive()); expect(scene2).notToRender([0, 0, 0, 255]); p.length = 100; expect(scene2).notToRender([0, 0, 0, 255]); }); it("does not render when show is false", function() { scene2.primitives.add( new import__464.DebugModelMatrixPrimitive({ show: false }) ); expect(scene2).toRender([0, 0, 0, 255]); }); it("is picked", function() { const p = scene2.primitives.add( new import__464.DebugModelMatrixPrimitive({ id: "id" }) ); expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toBe(p); expect(result.id).toBe("id"); }); }); it("isDestroyed", function() { const p = new import__464.DebugModelMatrixPrimitive(); expect(p.isDestroyed()).toEqual(false); p.destroy(); expect(p.isDestroyed()).toEqual(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/DepthPlaneSpec.js var import__465 = __toESM(require_Cesium(), 1); describe("Scene/DepthPlane", function() { let context; beforeAll(function() { context = createContext_default(); }); afterAll(function() { context.destroyForSpecs(); }); it("should use the default depthPlaneEllipsoidOffset", function() { const frameState2 = createFrameState_default(context, createCamera_default()); const depthPlane = new import__465.DepthPlane(); depthPlane.update(frameState2); expect(depthPlane._command.boundingVolume.radius).toEqual(6378137); }); it("should use a provided depthPlaneEllipsoidOffset", function() { const frameState2 = createFrameState_default(context, createCamera_default()); const depthPlane = new import__465.DepthPlane(-8137); depthPlane.update(frameState2); expect(depthPlane._command.boundingVolume.radius).toEqual(637e4); }); }); // packages/engine/Specs/Scene/DeviceOrientationCameraControllerSpec.js var import__466 = __toESM(require_Cesium(), 1); var import__467 = __toESM(require_Cesium(), 1); describe("Scene/DeviceOrientationCameraController", function() { let scene2; let canvas; let camera; let controller; function MockScene2(canvas2, camera2) { this.canvas = canvas2; this.camera = camera2; } beforeAll(function() { canvas = createCanvas_default(); }); afterAll(function() { document.body.removeChild(canvas); }); beforeEach(function() { camera = createCamera_default({ canvas, offset: new import__466.Cartesian3(-1, 0, 0) }); scene2 = new MockScene2(canvas, camera); controller = new import__466.DeviceOrientationCameraController(scene2); }); afterEach(function() { controller = controller && !controller.isDestroyed() && controller.destroy(); }); function fireEvent(options) { DomEventSimulator_default.fireDeviceOrientation(window); controller.update(); DomEventSimulator_default.fireDeviceOrientation(window, options); controller.update(); } it("throws without scene", function() { expect(function() { return new import__466.DeviceOrientationCameraController(); }).toThrowDeveloperError(); }); it("rotates for alpha", function() { const position = import__466.Cartesian3.clone(camera.position); const up = import__466.Cartesian3.clone(camera.up); fireEvent({ alpha: 90 }); expect(camera.position).toEqual(position); expect(camera.direction).toEqualEpsilon( import__466.Cartesian3.UNIT_Y, import__467.Math.EPSILON14 ); expect(camera.up).toEqualEpsilon(up, import__467.Math.EPSILON14); expect(camera.right).toEqualEpsilon( import__466.Cartesian3.UNIT_X, import__467.Math.EPSILON14 ); }); it("rotates for beta", function() { const position = import__466.Cartesian3.clone(camera.position); const direction = import__466.Cartesian3.clone(camera.direction); fireEvent({ beta: 90 }); expect(camera.position).toEqual(position); expect(camera.direction).toEqualEpsilon(direction, import__467.Math.EPSILON14); expect(camera.up).toEqualEpsilon(import__466.Cartesian3.UNIT_Y, import__467.Math.EPSILON14); expect(camera.right).toEqualEpsilon( import__466.Cartesian3.UNIT_Z, import__467.Math.EPSILON14 ); }); it("rotates for gamma", function() { const position = import__466.Cartesian3.clone(camera.position); const right = import__466.Cartesian3.clone(camera.right); fireEvent({ gamma: 90 }); expect(camera.position).toEqual(position); expect(camera.direction).toEqualEpsilon( import__466.Cartesian3.negate(import__466.Cartesian3.UNIT_Z, new import__466.Cartesian3()), import__467.Math.EPSILON14 ); expect(camera.up).toEqualEpsilon(import__466.Cartesian3.UNIT_X, import__467.Math.EPSILON14); expect(camera.right).toEqualEpsilon(right, import__467.Math.EPSILON14); }); it("is destroyed", function() { expect(controller.isDestroyed()).toEqual(false); controller.destroy(); expect(controller.isDestroyed()).toEqual(true); }); }); // packages/engine/Specs/Scene/DirectionalLightSpec.js var import__468 = __toESM(require_Cesium(), 1); describe("Scene/DirectionalLight", function() { it("constructs with default options", function() { const light = new import__468.DirectionalLight({ direction: import__468.Cartesian3.UNIT_X }); expect(light.direction).toEqual(import__468.Cartesian3.UNIT_X); expect(light.direction).not.toBe(import__468.Cartesian3.UNIT_X); expect(light.color).toEqual(import__468.Color.WHITE); expect(light.intensity).toBe(1); }); it("constructs with all options", function() { const light = new import__468.DirectionalLight({ direction: import__468.Cartesian3.UNIT_X, color: import__468.Color.RED, intensity: 2 }); expect(light.direction).toEqual(import__468.Cartesian3.UNIT_X); expect(light.color).toEqual(import__468.Color.RED); expect(light.color).not.toBe(import__468.Color.RED); expect(light.intensity).toBe(2); }); it("throws if options is undefined", function() { expect(function() { return new import__468.DirectionalLight(); }).toThrowDeveloperError(); }); it("throws if options.direction is undefined", function() { expect(function() { return new import__468.DirectionalLight({ color: import__468.Color.RED }); }).toThrowDeveloperError(); }); it("throws if options.direction is zero-length", function() { expect(function() { return new import__468.DirectionalLight({ direction: import__468.Cartesian3.ZERO }); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/DiscardEmptyTileImagePolicySpec.js var import__469 = __toESM(require_Cesium(), 1); describe("Scene/DiscardEmptyTileImagePolicy", function() { afterEach(function() { import__469.Resource._Implementations.createImage = import__469.Resource._DefaultImplementations.createImage; import__469.Resource._Implementations.loadWithXhr = import__469.Resource._DefaultImplementations.loadWithXhr; }); describe("shouldDiscardImage", function() { it("does not discard a non-empty image", function() { const promises = []; promises.push(import__469.Resource.fetchImage("Data/Images/Green4x4.png")); const policy = new import__469.DiscardEmptyTileImagePolicy(); promises.push( pollToPromise_default(function() { return policy.isReady(); }) ); return Promise.all(promises, function(results) { const greenImage = results[0]; expect(policy.shouldDiscardImage(greenImage)).toEqual(false); }); }); it("discards an empty image", function() { const promises = []; promises.push(Promise.resolve(import__469.DiscardEmptyTileImagePolicy.EMPTY_IMAGE)); const policy = new import__469.DiscardEmptyTileImagePolicy(); promises.push( pollToPromise_default(function() { return policy.isReady(); }) ); return Promise.all(promises, function(results) { const emptyImage = results[0]; expect(policy.shouldDiscardImage(emptyImage)).toEqual(true); }); }); }); }); // packages/engine/Specs/Scene/DiscardMissingTileImagePolicySpec.js var import__470 = __toESM(require_Cesium(), 1); describe("Scene/DiscardMissingTileImagePolicy", function() { let supportsImageBitmapOptions; beforeAll(function() { return import__470.Resource.supportsImageBitmapOptions().then(function(result) { supportsImageBitmapOptions = result; }); }); afterEach(function() { import__470.Resource._Implementations.createImage = import__470.Resource._DefaultImplementations.createImage; import__470.Resource._Implementations.loadWithXhr = import__470.Resource._DefaultImplementations.loadWithXhr; }); describe("construction", function() { it("throws if missingImageUrl is not provided", function() { function constructWithoutMissingImageUrl() { return new import__470.DiscardMissingTileImagePolicy({ pixelsToCheck: [new import__470.Cartesian2(0, 0)] }); } expect(constructWithoutMissingImageUrl).toThrowDeveloperError(); }); it("throws if pixelsToCheck is not provided", function() { function constructWithoutPixelsToCheck() { return new import__470.DiscardMissingTileImagePolicy({ missingImageUrl: "http://some.host.invalid/missingImage.png" }); } expect(constructWithoutPixelsToCheck).toThrowDeveloperError(); }); it("requests the missing image url", function() { const missingImageUrl = "http://some.host.invalid/missingImage.png"; spyOn(import__470.Resource, "createImageBitmapFromBlob").and.callThrough(); spyOn(import__470.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const url = request.url; if (/^blob:/.test(url)) { import__470.Resource._DefaultImplementations.createImage( request, crossOrigin, deferred ); } else { expect(url).toEqual(missingImageUrl); import__470.Resource._DefaultImplementations.createImage( new Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); } }); import__470.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toEqual(missingImageUrl); return import__470.Resource._DefaultImplementations.loadWithXhr( "Data/Images/Red16x16.png", responseType, method, data, headers, deferred ); }; const policy = new import__470.DiscardMissingTileImagePolicy({ missingImageUrl, pixelsToCheck: [new import__470.Cartesian2(0, 0)] }); return pollToPromise_default(function() { return policy.isReady(); }).then(function() { if (supportsImageBitmapOptions) { expect(import__470.Resource.createImageBitmapFromBlob).toHaveBeenCalled(); } else { expect(import__470.Resource._Implementations.createImage).toHaveBeenCalled(); } }); }); }); describe("shouldDiscardImage", function() { it("discards an image that is identical to the missing image", function() { const promises = []; promises.push(import__470.Resource.fetchImage("Data/Images/Red16x16.png")); promises.push(import__470.Resource.fetchImage("Data/Images/Green4x4.png")); const missingImageUrl = "Data/Images/Red16x16.png"; const policy = new import__470.DiscardMissingTileImagePolicy({ missingImageUrl, pixelsToCheck: [new import__470.Cartesian2(0, 0)] }); promises.push( pollToPromise_default(function() { return policy.isReady(); }) ); return Promise.all(promises, function(results) { const redImage = results[0]; const greenImage = results[1]; expect(policy.shouldDiscardImage(redImage)).toEqual(true); expect(policy.shouldDiscardImage(greenImage)).toEqual(false); }); }); it("discards an image that is identical to the missing image even if the missing image is transparent", function() { const promises = []; promises.push(import__470.Resource.fetchImage("Data/Images/Transparent.png")); const missingImageUrl = "Data/Images/Transparent.png"; const policy = new import__470.DiscardMissingTileImagePolicy({ missingImageUrl, pixelsToCheck: [new import__470.Cartesian2(0, 0)] }); promises.push( pollToPromise_default(function() { return policy.isReady(); }) ); return Promise.all(promises, function(results) { const transparentImage = results[0]; expect(policy.shouldDiscardImage(transparentImage)).toEqual(true); }); }); it("does not discard at all when the missing image is transparent and disableCheckIfAllPixelsAreTransparent is set", function() { const promises = []; promises.push(import__470.Resource.fetchImage("Data/Images/Transparent.png")); const missingImageUrl = "Data/Images/Transparent.png"; const policy = new import__470.DiscardMissingTileImagePolicy({ missingImageUrl, pixelsToCheck: [new import__470.Cartesian2(0, 0)], disableCheckIfAllPixelsAreTransparent: true }); promises.push( pollToPromise_default(function() { return policy.isReady(); }) ); return Promise.all(promises, function(results) { const transparentImage = results[0]; expect(policy.shouldDiscardImage(transparentImage)).toEqual(false); }); }); it("throws if called before the policy is ready", function() { const policy = new import__470.DiscardMissingTileImagePolicy({ missingImageUrl: "Data/Images/Transparent.png", pixelsToCheck: [new import__470.Cartesian2(0, 0)], disableCheckIfAllPixelsAreTransparent: true }); expect(function() { policy.shouldDiscardImage(new Image()); }).toThrowDeveloperError(); }); }); }); // packages/engine/Specs/Scene/DynamicAtmosphereLightingTypeSpec.js var import__471 = __toESM(require_Cesium(), 1); describe("Scene/DynamicAtmosphereLightingType", function() { function mockGlobe() { return { enableLighting: false, dynamicAtmosphereLighting: false, dynamicAtmosphereLightingFromSun: false }; } it("returns OFF when lighting is disabled", function() { const globe2 = mockGlobe(); expect(import__471.DynamicAtmosphereLightingType.fromGlobeFlags(globe2)).toBe( import__471.DynamicAtmosphereLightingType.NONE ); globe2.enableLighting = true; expect(import__471.DynamicAtmosphereLightingType.fromGlobeFlags(globe2)).toBe( import__471.DynamicAtmosphereLightingType.NONE ); globe2.enableLighting = false; globe2.dynamicAtmosphereLighting = true; expect(import__471.DynamicAtmosphereLightingType.fromGlobeFlags(globe2)).toBe( import__471.DynamicAtmosphereLightingType.NONE ); }); it("selects a light type depending on globe.dynamicAtmosphereLightingFromSun", function() { const globe2 = mockGlobe(); globe2.enableLighting = true; globe2.dynamicAtmosphereLighting = true; globe2.dynamicAtmosphereLightingFromSun = true; expect(import__471.DynamicAtmosphereLightingType.fromGlobeFlags(globe2)).toBe( import__471.DynamicAtmosphereLightingType.SUNLIGHT ); globe2.dynamicAtmosphereLightingFromSun = false; expect(import__471.DynamicAtmosphereLightingType.fromGlobeFlags(globe2)).toBe( import__471.DynamicAtmosphereLightingType.SCENE_LIGHT ); }); }); // packages/engine/Specs/Scene/EllipsoidPrimitiveSpec.js var import__472 = __toESM(require_Cesium(), 1); describe( "Scene/EllipsoidPrimitive", function() { let scene2; let ellipsoid; beforeAll(function() { scene2 = createScene_default(); scene2.primitives.destroyPrimitives = false; scene2.frameState.scene3DOnly = false; }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { ellipsoid = new import__472.EllipsoidPrimitive(); const offset = new import__472.Cartesian3(1.02, 0, 0); scene2.camera.lookAtTransform(import__472.Matrix4.IDENTITY, offset); }); afterEach(function() { scene2.primitives.removeAll(); if ((0, import__472.defined)(ellipsoid) && !ellipsoid.isDestroyed()) { ellipsoid = ellipsoid.destroy(); } }); it("gets the default properties", function() { expect(ellipsoid.show).toEqual(true); expect(ellipsoid.center).toEqual(import__472.Cartesian3.ZERO); expect(ellipsoid.radii).toBeUndefined(); expect(ellipsoid.modelMatrix).toEqual(import__472.Matrix4.IDENTITY); expect(ellipsoid.material.type).toEqual(import__472.Material.ColorType); expect(ellipsoid.debugShowBoundingVolume).toEqual(false); }); it("Constructs with options", function() { const material = import__472.Material.fromType(import__472.Material.StripeType); const e = new import__472.EllipsoidPrimitive({ center: new import__472.Cartesian3(1, 2, 3), radii: new import__472.Cartesian3(4, 5, 6), modelMatrix: import__472.Matrix4.fromUniformScale(2), show: false, material, id: "id", debugShowBoundingVolume: true }); expect(e.center).toEqual(new import__472.Cartesian3(1, 2, 3)); expect(e.radii).toEqual(new import__472.Cartesian3(4, 5, 6)); expect(e.modelMatrix).toEqual(import__472.Matrix4.fromUniformScale(2)); expect(e.show).toEqual(false); expect(e.material).toBe(material); expect(e.id).toEqual("id"); expect(e.debugShowBoundingVolume).toEqual(true); e.destroy(); }); it("renders with the default material", function() { ellipsoid.radii = new import__472.Cartesian3(1, 1, 1); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(ellipsoid); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders with a custom modelMatrix", function() { ellipsoid.radii = new import__472.Cartesian3(0.1, 0.1, 0.1); ellipsoid.modelMatrix = import__472.Matrix4.fromScale( new import__472.Cartesian3(10, 10, 10) ); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(ellipsoid); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders two with a vertex array cache hit", function() { ellipsoid.radii = new import__472.Cartesian3(1, 1, 1); const ellipsoid2 = new import__472.EllipsoidPrimitive(); ellipsoid2.radii = new import__472.Cartesian3(1, 1, 1); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(ellipsoid); let result; expect(scene2).toRenderAndCall(function(rgba) { result = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); }); expect(scene2).toRender(result); scene2.primitives.add(ellipsoid2); expect(scene2).notToRender([0, 0, 0, 255]); expect(scene2).notToRender(result); ellipsoid2.destroy(); }); it("renders bounding volume with debugShowBoundingVolume", function() { const scene3 = createScene_default(); scene3.primitives.add( new import__472.EllipsoidPrimitive({ radii: new import__472.Cartesian3(1, 1, 1), debugShowBoundingVolume: true }) ); const camera = scene3.camera; camera.position = new import__472.Cartesian3(1.02, 0, 0); camera.direction = import__472.Cartesian3.negate(import__472.Cartesian3.UNIT_X, new import__472.Cartesian3()); camera.up = import__472.Cartesian3.clone(import__472.Cartesian3.UNIT_Z); expect(scene3).notToRender([0, 0, 0, 255]); scene3.destroyForSpecs(); }); it("does not render when show is false", function() { ellipsoid.radii = new import__472.Cartesian3(1, 1, 1); ellipsoid.show = false; expect(scene2).toRender([0, 0, 0, 255]); }); it("does not render without radii", function() { expect(scene2).toRender([0, 0, 0, 255]); }); it("does not render when not in view due to center", function() { ellipsoid.radii = new import__472.Cartesian3(1, 1, 1); ellipsoid.center = new import__472.Cartesian3(10, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(ellipsoid); expect(scene2).toRender([0, 0, 0, 255]); }); it("is picked", function() { ellipsoid.radii = new import__472.Cartesian3(1, 1, 1); ellipsoid.id = "id"; scene2.primitives.add(ellipsoid); expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toEqual(ellipsoid); expect(result.id).toEqual("id"); }); }); it("is not picked (show === false)", function() { ellipsoid.radii = new import__472.Cartesian3(1, 1, 1); ellipsoid.show = false; scene2.primitives.add(ellipsoid); expect(scene2).notToPick(); }); it("is not picked (alpha === 0.0)", function() { ellipsoid.radii = new import__472.Cartesian3(1, 1, 1); ellipsoid.material.uniforms.color.alpha = 0; scene2.primitives.add(ellipsoid); expect(scene2).notToPick(); }); it("isDestroyed", function() { expect(ellipsoid.isDestroyed()).toEqual(false); ellipsoid.destroy(); expect(ellipsoid.isDestroyed()).toEqual(true); }); it("throws when rendered without a material", function() { ellipsoid.radii = new import__472.Cartesian3(1, 1, 1); ellipsoid.material = void 0; scene2.primitives.add(ellipsoid); expect(function() { scene2.renderForSpecs(); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Scene/EllipsoidSurfaceAppearanceSpec.js var import__473 = __toESM(require_Cesium(), 1); describe( "Scene/EllipsoidSurfaceAppearance", function() { let scene2; let rectangle; let primitive; beforeAll(function() { scene2 = createScene_default(); scene2.primitives.destroyPrimitives = false; scene2.frameState.scene3DOnly = false; rectangle = import__473.Rectangle.fromDegrees(-10, -10, 10, 10); }); beforeEach(function() { scene2.camera.setView({ destination: rectangle }); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.primitives.removeAll(); primitive = primitive && !primitive.isDestroyed() && primitive.destroy(); }); it("constructor", function() { const a = new import__473.EllipsoidSurfaceAppearance(); expect(a.material).toBeDefined(); expect(a.material.type).toEqual(import__473.Material.ColorType); expect(a.vertexShaderSource).toBeDefined(); expect(a.fragmentShaderSource).toBeDefined(); expect(a.renderState).toEqual( import__473.Appearance.getDefaultRenderState(true, true) ); expect(a.vertexFormat).toEqual(import__473.EllipsoidSurfaceAppearance.VERTEX_FORMAT); expect(a.flat).toEqual(false); expect(a.faceForward).toEqual(false); expect(a.translucent).toEqual(true); expect(a.aboveGround).toEqual(false); expect(a.closed).toEqual(false); }); it("renders", function() { primitive = new import__473.Primitive({ geometryInstances: new import__473.GeometryInstance({ geometry: new import__473.RectangleGeometry({ rectangle, vertexFormat: import__473.EllipsoidSurfaceAppearance.VERTEX_FORMAT }), attributes: { color: new import__473.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }), asynchronous: false }); primitive.appearance = new import__473.EllipsoidSurfaceAppearance(); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive); expect(scene2).notToRender([0, 0, 0, 255]); }); }, "WebGL" ); // packages/engine/Specs/Scene/Empty3DTileContentSpec.js var import__474 = __toESM(require_Cesium(), 1); describe("Scene/Empty3DTileContent", function() { it("destroys", function() { const content = new import__474.Empty3DTileContent(); expect(content.isDestroyed()).toEqual(false); content.destroy(); expect(content.isDestroyed()).toEqual(true); }); it("gets properties", function() { const mockTileset = {}; const mockTile2 = {}; const content = new import__474.Empty3DTileContent(mockTileset, mockTile2); expect(content.featuresLength).toBe(0); expect(content.pointsLength).toBe(0); expect(content.trianglesLength).toBe(0); expect(content.geometryByteLength).toBe(0); expect(content.texturesByteLength).toBe(0); expect(content.batchTableByteLength).toBe(0); expect(content.innerContents).toBeUndefined(); expect(content.tileset).toBe(mockTileset); expect(content.tile).toBe(mockTile2); expect(content.url).toBeUndefined(); expect(content.batchTable).toBeUndefined(); }); describe("metadata", function() { it("contentMetadata returns undefined", function() { const mockTileset = {}; const mockTile2 = {}; const content = new import__474.Empty3DTileContent(mockTileset, mockTile2); expect(content.metadata).not.toBeDefined(); }); it("groupMetadata returns undefined", function() { const mockTileset = {}; const mockTile2 = {}; const content = new import__474.Empty3DTileContent(mockTileset, mockTile2); expect(content.group).not.toBeDefined(); }); it("assigning group throws", function() { expect(function() { const mockTileset = {}; const mockTile2 = {}; const content = new import__474.Empty3DTileContent(mockTileset, mockTile2); content.group = {}; }).toThrowDeveloperError(); }); it("assigning contentMetadata throws", function() { expect(function() { const mockTileset = {}; const mockTile2 = {}; const content = new import__474.Empty3DTileContent(mockTileset, mockTile2); content.metadata = {}; }).toThrowDeveloperError(); }); }); }); // packages/engine/Specs/Scene/ExpressionSpec.js var import__475 = __toESM(require_Cesium(), 1); var import__476 = __toESM(require_Cesium(), 1); describe("Scene/Expression", function() { function MockFeature() { this._properties = {}; this._className = void 0; this._inheritedClassName = void 0; this.content = { tileset: { timeSinceLoad: 0 } }; } MockFeature.prototype.addProperty = function(name, value) { this._properties[name] = value; }; MockFeature.prototype.getPropertyInherited = function(name) { return this._properties[name]; }; MockFeature.prototype.setClass = function(className) { this._className = className; }; MockFeature.prototype.setInheritedClass = function(className) { this._inheritedClassName = className; }; MockFeature.prototype.isExactClass = function(className) { return this._className === className; }; MockFeature.prototype.isClass = function(className) { return this._className === className || this._inheritedClassName === className; }; MockFeature.prototype.getExactClassName = function() { return this._className; }; it("parses backslashes", function() { const expression = new import__475.Expression('"\\he\\\\\\ll\\\\o"'); expect(expression.evaluate(void 0)).toEqual("\\he\\\\\\ll\\\\o"); }); it("evaluates variable", function() { const feature = new MockFeature(); feature.addProperty("height", 10); feature.addProperty("width", 5); feature.addProperty("string", "hello"); feature.addProperty("boolean", true); feature.addProperty("vector", import__475.Cartesian3.UNIT_X); feature.addProperty("null", null); feature.addProperty("undefined", void 0); let expression = new import__475.Expression("${height}"); expect(expression.evaluate(feature)).toEqual(10); expression = new import__475.Expression("'${height}'"); expect(expression.evaluate(feature)).toEqual("10"); expression = new import__475.Expression("${height}/${width}"); expect(expression.evaluate(feature)).toEqual(2); expression = new import__475.Expression("${string}"); expect(expression.evaluate(feature)).toEqual("hello"); expression = new import__475.Expression("'replace ${string}'"); expect(expression.evaluate(feature)).toEqual("replace hello"); expression = new import__475.Expression("'replace ${string} multiple ${height}'"); expect(expression.evaluate(feature)).toEqual("replace hello multiple 10"); expression = new import__475.Expression('"replace ${string}"'); expect(expression.evaluate(feature)).toEqual("replace hello"); expression = new import__475.Expression("'replace ${string'"); expect(expression.evaluate(feature)).toEqual("replace ${string"); expression = new import__475.Expression("${boolean}"); expect(expression.evaluate(feature)).toEqual(true); expression = new import__475.Expression("'${boolean}'"); expect(expression.evaluate(feature)).toEqual("true"); expression = new import__475.Expression("${vector}"); expect(expression.evaluate(feature)).toEqual(import__475.Cartesian3.UNIT_X); expression = new import__475.Expression("'${vector}'"); expect(expression.evaluate(feature)).toEqual(import__475.Cartesian3.UNIT_X.toString()); expression = new import__475.Expression("${null}"); expect(expression.evaluate(feature)).toEqual(null); expression = new import__475.Expression("'${null}'"); expect(expression.evaluate(feature)).toEqual(""); expression = new import__475.Expression("${undefined}"); expect(expression.evaluate(feature)).toEqual(void 0); expression = new import__475.Expression("'${undefined}'"); expect(expression.evaluate(feature)).toEqual(""); expression = new import__475.Expression( "abs(-${height}) + max(${height}, ${width}) + clamp(${height}, 0, 2)" ); expect(expression.evaluate(feature)).toEqual(22); expect(function() { return new import__475.Expression("${height"); }).toThrowError(import__475.RuntimeError); }); it("evaluates variable to undefined if feature is undefined", function() { let expression = new import__475.Expression("${height}"); expect(expression.evaluate(void 0)).toBeUndefined(); expression = new import__475.Expression("${vector.x}"); expect(expression.evaluate(void 0)).toBeUndefined(); expression = new import__475.Expression("${feature}"); expect(expression.evaluate(void 0)).toBeUndefined(); expression = new import__475.Expression("${feature.vector}"); expect(expression.evaluate(void 0)).toBeUndefined(); expression = new import__475.Expression('${vector["x"]}'); expect(expression.evaluate(void 0)).toBeUndefined(); expression = new import__475.Expression('${feature["vector"]}'); expect(expression.evaluate(void 0)).toBeUndefined(); expression = new import__475.Expression("'${height}'"); expect(expression.evaluate(void 0)).toBe(""); }); it("evaluates with defines", function() { const defines = { halfHeight: "${Height}/2" }; const feature = new MockFeature(); feature.addProperty("Height", 10); const expression = new import__475.Expression("${halfHeight}", defines); expect(expression.evaluate(feature)).toEqual(5); }); it("evaluates with defines, honoring order of operations", function() { const defines = { value: "1 + 2" }; const expression = new import__475.Expression("5.0 * ${value}", defines); expect(expression.evaluate(void 0)).toEqual(15); }); it("evaluate takes result argument", function() { const expression = new import__475.Expression("vec3(1.0)"); const result = new import__475.Cartesian3(); const value = expression.evaluate(void 0, result); expect(value).toEqual(new import__475.Cartesian3(1, 1, 1)); expect(value).toBe(result); }); it("evaluate takes a color result argument", function() { const expression = new import__475.Expression('color("red")'); const result = new import__475.Color(); const value = expression.evaluate(void 0, result); expect(value).toEqual(import__475.Color.RED); expect(value).toBe(result); }); it("gets expressions", function() { const expressionString = "(regExp('^Chest').test(${County})) && (${YearBuilt} >= 1970)"; const expression = new import__475.Expression(expressionString); expect(expression.expression).toEqual(expressionString); }); it("throws on invalid expressions", function() { expect(function() { return new import__475.Expression(false); }).toThrowDeveloperError(); expect(function() { return new import__475.Expression(""); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("this"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("2; 3;"); }).toThrowError(import__475.RuntimeError); }); it("throws on unknown characters", function() { expect(function() { return new import__475.Expression("#"); }).toThrowError(import__475.RuntimeError); }); it("throws on unmatched parenthesis", function() { expect(function() { return new import__475.Expression("((true)"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("(true))"); }).toThrowError(import__475.RuntimeError); }); it("throws on unknown identifiers", function() { expect(function() { return new import__475.Expression("flse"); }).toThrowError(import__475.RuntimeError); }); it("throws on unknown function calls", function() { expect(function() { return new import__475.Expression("unknown()"); }).toThrowError(import__475.RuntimeError); }); it("throws on unknown member function calls", function() { expect(function() { return new import__475.Expression("regExp().unknown()"); }).toThrowError(import__475.RuntimeError); }); it("throws with unsupported operators", function() { expect(function() { return new import__475.Expression("~1"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("2 | 3"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("2 & 3"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("2 << 3"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("2 >> 3"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("2 >>> 3"); }).toThrowError(import__475.RuntimeError); }); it("evaluates literal null", function() { const expression = new import__475.Expression("null"); expect(expression.evaluate(void 0)).toEqual(null); }); it("evaluates literal undefined", function() { const expression = new import__475.Expression("undefined"); expect(expression.evaluate(void 0)).toEqual(void 0); }); it("evaluates literal boolean", function() { let expression = new import__475.Expression("true"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("false"); expect(expression.evaluate(void 0)).toEqual(false); }); it("converts to literal boolean", function() { let expression = new import__475.Expression("Boolean()"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("Boolean(1)"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression('Boolean("true")'); expect(expression.evaluate(void 0)).toEqual(true); }); it("evaluates literal number", function() { let expression = new import__475.Expression("1"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("0"); expect(expression.evaluate(void 0)).toEqual(0); expression = new import__475.Expression("NaN"); expect(expression.evaluate(void 0)).toEqual(NaN); expression = new import__475.Expression("Infinity"); expect(expression.evaluate(void 0)).toEqual(Infinity); }); it("evaluates math constants", function() { let expression = new import__475.Expression("Math.PI"); expect(expression.evaluate(void 0)).toEqual(Math.PI); expression = new import__475.Expression("Math.E"); expect(expression.evaluate(void 0)).toEqual(Math.E); }); it("evaluates number constants", function() { const expression = new import__475.Expression("Number.POSITIVE_INFINITY"); expect(expression.evaluate(void 0)).toEqual(Number.POSITIVE_INFINITY); }); it("converts to literal number", function() { let expression = new import__475.Expression("Number()"); expect(expression.evaluate(void 0)).toEqual(0); expression = new import__475.Expression('Number("1")'); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("Number(true)"); expect(expression.evaluate(void 0)).toEqual(1); }); it("evaluates literal string", function() { let expression = new import__475.Expression("'hello'"); expect(expression.evaluate(void 0)).toEqual("hello"); expression = new import__475.Expression("'Cesium'"); expect(expression.evaluate(void 0)).toEqual("Cesium"); expression = new import__475.Expression('"Cesium"'); expect(expression.evaluate(void 0)).toEqual("Cesium"); }); it("converts to literal string", function() { let expression = new import__475.Expression("String()"); expect(expression.evaluate(void 0)).toEqual(""); expression = new import__475.Expression("String(1)"); expect(expression.evaluate(void 0)).toEqual("1"); expression = new import__475.Expression("String(true)"); expect(expression.evaluate(void 0)).toEqual("true"); }); it("evaluates literal color", function() { let expression = new import__475.Expression("color('#ffffff')"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.WHITE) ); expression = new import__475.Expression("color('#00FFFF')"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.CYAN) ); expression = new import__475.Expression("color('#fff')"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.WHITE) ); expression = new import__475.Expression("color('#0FF')"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.CYAN) ); expression = new import__475.Expression("color('white')"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.WHITE) ); expression = new import__475.Expression("color('cyan')"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.CYAN) ); expression = new import__475.Expression("color('white', 0.5)"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.fromAlpha(import__475.Color.WHITE, 0.5)) ); expression = new import__475.Expression("rgb(255, 255, 255)"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.WHITE) ); expression = new import__475.Expression("rgb(100, 255, 190)"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.fromBytes(100, 255, 190)) ); expression = new import__475.Expression("hsl(0, 0, 1)"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.WHITE) ); expression = new import__475.Expression("hsl(1.0, 0.6, 0.7)"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.fromHsl(1, 0.6, 0.7)) ); expression = new import__475.Expression("rgba(255, 255, 255, 0.5)"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.fromAlpha(import__475.Color.WHITE, 0.5)) ); expression = new import__475.Expression("rgba(100, 255, 190, 0.25)"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.fromBytes(100, 255, 190, 0.25 * 255)) ); expression = new import__475.Expression("hsla(0, 0, 1, 0.5)"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(new import__475.Color(1, 1, 1, 0.5)) ); expression = new import__475.Expression("hsla(1.0, 0.6, 0.7, 0.75)"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.fromHsl(1, 0.6, 0.7, 0.75)) ); expression = new import__475.Expression("color()"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.WHITE) ); }); it("evaluates literal color with result parameter", function() { const color = new import__475.Color(); let expression = new import__475.Expression("color('#0000ff')"); expect(expression.evaluate(void 0, color)).toEqual(import__475.Color.BLUE); expect(color).toEqual(import__475.Color.BLUE); expression = new import__475.Expression("color('#f00')"); expect(expression.evaluate(void 0, color)).toEqual(import__475.Color.RED); expect(color).toEqual(import__475.Color.RED); expression = new import__475.Expression("color('cyan')"); expect(expression.evaluate(void 0, color)).toEqual(import__475.Color.CYAN); expect(color).toEqual(import__475.Color.CYAN); expression = new import__475.Expression("color('white', 0.5)"); expect(expression.evaluate(void 0, color)).toEqual( new import__475.Color(1, 1, 1, 0.5) ); expect(color).toEqual(new import__475.Color(1, 1, 1, 0.5)); expression = new import__475.Expression("rgb(0, 0, 0)"); expect(expression.evaluate(void 0, color)).toEqual(import__475.Color.BLACK); expect(color).toEqual(import__475.Color.BLACK); expression = new import__475.Expression("hsl(0, 0, 1)"); expect(expression.evaluate(void 0, color)).toEqual(import__475.Color.WHITE); expect(color).toEqual(import__475.Color.WHITE); expression = new import__475.Expression("rgba(255, 0, 255, 0.5)"); expect(expression.evaluate(void 0, color)).toEqual( new import__475.Color(1, 0, 1, 0.5) ); expect(color).toEqual(new import__475.Color(1, 0, 1, 0.5)); expression = new import__475.Expression("hsla(0, 0, 1, 0.5)"); expect(expression.evaluate(void 0, color)).toEqual( new import__475.Color(1, 1, 1, 0.5) ); expect(color).toEqual(new import__475.Color(1, 1, 1, 0.5)); expression = new import__475.Expression("color()"); expect(expression.evaluate(void 0, color)).toEqual(import__475.Color.WHITE); expect(color).toEqual(import__475.Color.WHITE); }); it("evaluates color with expressions as arguments", function() { const feature = new MockFeature(); feature.addProperty("hex6", "#ffffff"); feature.addProperty("hex3", "#fff"); feature.addProperty("keyword", "white"); feature.addProperty("alpha", 0.2); let expression = new import__475.Expression("color(${hex6})"); expect(expression.evaluate(feature)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.WHITE) ); expression = new import__475.Expression("color(${hex3})"); expect(expression.evaluate(feature)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.WHITE) ); expression = new import__475.Expression("color(${keyword})"); expect(expression.evaluate(feature)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.WHITE) ); expression = new import__475.Expression("color(${keyword}, ${alpha} + 0.6)"); expect(expression.evaluate(feature).x).toEqual(1); expect(expression.evaluate(feature).y).toEqual(1); expect(expression.evaluate(feature).z).toEqual(1); expect(expression.evaluate(feature).w).toEqual(0.8); }); it("evaluates rgb with expressions as arguments", function() { const feature = new MockFeature(); feature.addProperty("red", 100); feature.addProperty("green", 200); feature.addProperty("blue", 255); let expression = new import__475.Expression("rgb(${red}, ${green}, ${blue})"); expect(expression.evaluate(feature)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.fromBytes(100, 200, 255)) ); expression = new import__475.Expression("rgb(${red}/2, ${green}/2, ${blue})"); expect(expression.evaluate(feature)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.fromBytes(50, 100, 255)) ); }); it("evaluates hsl with expressions as arguments", function() { const feature = new MockFeature(); feature.addProperty("h", 0); feature.addProperty("s", 0); feature.addProperty("l", 1); let expression = new import__475.Expression("hsl(${h}, ${s}, ${l})"); expect(expression.evaluate(feature)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.WHITE) ); expression = new import__475.Expression("hsl(${h} + 0.2, ${s} + 1.0, ${l} - 0.5)"); expect(expression.evaluate(feature)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.fromHsl(0.2, 1, 0.5)) ); }); it("evaluates rgba with expressions as arguments", function() { const feature = new MockFeature(); feature.addProperty("red", 100); feature.addProperty("green", 200); feature.addProperty("blue", 255); feature.addProperty("a", 0.3); let expression = new import__475.Expression("rgba(${red}, ${green}, ${blue}, ${a})"); expect(expression.evaluate(feature)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.fromBytes(100, 200, 255, 0.3 * 255)) ); expression = new import__475.Expression( "rgba(${red}/2, ${green}/2, ${blue}, ${a} * 2)" ); expect(expression.evaluate(feature)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.fromBytes(50, 100, 255, 0.6 * 255)) ); }); it("evaluates hsla with expressions as arguments", function() { const feature = new MockFeature(); feature.addProperty("h", 0); feature.addProperty("s", 0); feature.addProperty("l", 1); feature.addProperty("a", 1); let expression = new import__475.Expression("hsla(${h}, ${s}, ${l}, ${a})"); expect(expression.evaluate(feature)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.WHITE) ); expression = new import__475.Expression( "hsla(${h} + 0.2, ${s} + 1.0, ${l} - 0.5, ${a} / 4)" ); expect(expression.evaluate(feature)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.fromHsl(0.2, 1, 0.5, 0.25)) ); }); it("evaluates rgba with expressions as arguments", function() { const feature = new MockFeature(); feature.addProperty("red", 100); feature.addProperty("green", 200); feature.addProperty("blue", 255); feature.addProperty("alpha", 0.5); let expression = new import__475.Expression( "rgba(${red}, ${green}, ${blue}, ${alpha})" ); expect(expression.evaluate(feature)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.fromBytes(100, 200, 255, 0.5 * 255)) ); expression = new import__475.Expression( "rgba(${red}/2, ${green}/2, ${blue}, ${alpha} + 0.1)" ); expect(expression.evaluate(feature)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.fromBytes(50, 100, 255, 0.6 * 255)) ); }); it("color constructors throw with wrong number of arguments", function() { expect(function() { return new import__475.Expression("rgb(255, 255)"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("hsl(1, 1)"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("rgba(255, 255, 255)"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("hsla(1, 1, 1)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates color properties (r, g, b, a)", function() { let expression = new import__475.Expression("color('#ffffff').r"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("rgb(255, 255, 0).g"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression('color("cyan").b'); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("rgba(255, 255, 0, 0.5).a"); expect(expression.evaluate(void 0)).toEqual(0.5); }); it("evaluates color properties (x, y, z, w)", function() { let expression = new import__475.Expression("color('#ffffff').x"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("rgb(255, 255, 0).y"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression('color("cyan").z'); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("rgba(255, 255, 0, 0.5).w"); expect(expression.evaluate(void 0)).toEqual(0.5); }); it("evaluates color properties ([0], [1], [2]. [3])", function() { let expression = new import__475.Expression("color('#ffffff')[0]"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("rgb(255, 255, 0)[1]"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression('color("cyan")[2]'); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("rgba(255, 255, 0, 0.5)[3]"); expect(expression.evaluate(void 0)).toEqual(0.5); }); it('evaluates color properties (["r"], ["g"], ["b"], ["a"])', function() { let expression = new import__475.Expression(`color('#ffffff')["r"]`); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression('rgb(255, 255, 0)["g"]'); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression('color("cyan")["b"]'); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression('rgba(255, 255, 0, 0.5)["a"]'); expect(expression.evaluate(void 0)).toEqual(0.5); }); it('evaluates color properties (["x"], ["y"], ["z"], ["w"])', function() { let expression = new import__475.Expression(`color('#ffffff')["x"]`); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression('rgb(255, 255, 0)["y"]'); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression('color("cyan")["z"]'); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression('rgba(255, 255, 0, 0.5)["w"]'); expect(expression.evaluate(void 0)).toEqual(0.5); }); it("evaluates vec2", function() { let expression = new import__475.Expression("vec2(2.0)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(2, 2)); expression = new import__475.Expression("vec2(3.0, 4.0)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(3, 4)); expression = new import__475.Expression("vec2(vec2(3.0, 4.0))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(3, 4)); expression = new import__475.Expression("vec2(vec3(3.0, 4.0, 5.0))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(3, 4)); expression = new import__475.Expression("vec2(vec4(3.0, 4.0, 5.0, 6.0))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(3, 4)); }); it("throws if vec2 has invalid number of arguments", function() { let expression = new import__475.Expression("vec2()"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("vec2(3.0, 4.0, 5.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("vec2(vec2(3.0, 4.0), 5.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("throws if vec2 has invalid argument", function() { const expression = new import__475.Expression('vec2("1")'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates vec3", function() { let expression = new import__475.Expression("vec3(2.0)"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(2, 2, 2) ); expression = new import__475.Expression("vec3(3.0, 4.0, 5.0)"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(3, 4, 5) ); expression = new import__475.Expression("vec3(vec2(3.0, 4.0), 5.0)"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(3, 4, 5) ); expression = new import__475.Expression("vec3(3.0, vec2(4.0, 5.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(3, 4, 5) ); expression = new import__475.Expression("vec3(vec3(3.0, 4.0, 5.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(3, 4, 5) ); expression = new import__475.Expression("vec3(vec4(3.0, 4.0, 5.0, 6.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(3, 4, 5) ); }); it("throws if vec3 has invalid number of arguments", function() { let expression = new import__475.Expression("vec3()"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("vec3(3.0, 4.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("vec3(3.0, 4.0, 5.0, 6.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("vec3(vec2(3.0, 4.0), vec2(5.0, 6.0))"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("vec3(vec4(3.0, 4.0, 5.0, 6.0), 1.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("throws if vec3 has invalid argument", function() { const expression = new import__475.Expression('vec3(1.0, "1.0", 2.0)'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates vec4", function() { let expression = new import__475.Expression("vec4(2.0)"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(2, 2, 2, 2) ); expression = new import__475.Expression("vec4(3.0, 4.0, 5.0, 6.0)"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(3, 4, 5, 6) ); expression = new import__475.Expression("vec4(vec2(3.0, 4.0), 5.0, 6.0)"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(3, 4, 5, 6) ); expression = new import__475.Expression("vec4(3.0, vec2(4.0, 5.0), 6.0)"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(3, 4, 5, 6) ); expression = new import__475.Expression("vec4(3.0, 4.0, vec2(5.0, 6.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(3, 4, 5, 6) ); expression = new import__475.Expression("vec4(vec3(3.0, 4.0, 5.0), 6.0)"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(3, 4, 5, 6) ); expression = new import__475.Expression("vec4(3.0, vec3(4.0, 5.0, 6.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(3, 4, 5, 6) ); expression = new import__475.Expression("vec4(vec4(3.0, 4.0, 5.0, 6.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(3, 4, 5, 6) ); }); it("throws if vec4 has invalid number of arguments", function() { let expression = new import__475.Expression("vec4()"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("vec4(3.0, 4.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("vec4(3.0, 4.0, 5.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("vec4(3.0, 4.0, 5.0, 6.0, 7.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("vec4(vec3(3.0, 4.0, 5.0))"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("throws if vec4 has invalid argument", function() { const expression = new import__475.Expression('vec4(1.0, "2.0", 3.0, 4.0)'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates vector with expressions as arguments", function() { const feature = new MockFeature(); feature.addProperty("height", 2); feature.addProperty("width", 4); feature.addProperty("depth", 3); feature.addProperty("scale", 1); const expression = new import__475.Expression( "vec4(${height}, ${width}, ${depth}, ${scale})" ); expect(expression.evaluate(feature)).toEqual( new import__475.Cartesian4(2, 4, 3, 1) ); }); it("evaluates expression with multiple nested vectors", function() { const expression = new import__475.Expression( "vec4(vec2(1, 2)[vec3(6, 1, 5).y], 2, vec4(1.0).w, 5)" ); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(2, 2, 1, 5) ); }); it("evaluates vector properties (x, y, z, w)", function() { let expression = new import__475.Expression("vec4(1.0, 2.0, 3.0, 4.0).x"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("vec4(1.0, 2.0, 3.0, 4.0).y"); expect(expression.evaluate(void 0)).toEqual(2); expression = new import__475.Expression("vec4(1.0, 2.0, 3.0, 4.0).z"); expect(expression.evaluate(void 0)).toEqual(3); expression = new import__475.Expression("vec4(1.0, 2.0, 3.0, 4.0).w"); expect(expression.evaluate(void 0)).toEqual(4); }); it("evaluates vector properties (r, g, b, a)", function() { let expression = new import__475.Expression("vec4(1.0, 2.0, 3.0, 4.0).r"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("vec4(1.0, 2.0, 3.0, 4.0).g"); expect(expression.evaluate(void 0)).toEqual(2); expression = new import__475.Expression("vec4(1.0, 2.0, 3.0, 4.0).b"); expect(expression.evaluate(void 0)).toEqual(3); expression = new import__475.Expression("vec4(1.0, 2.0, 3.0, 4.0).a"); expect(expression.evaluate(void 0)).toEqual(4); }); it("evaluates vector properties ([0], [1], [2], [3])", function() { let expression = new import__475.Expression("vec4(1.0, 2.0, 3.0, 4.0)[0]"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("vec4(1.0, 2.0, 3.0, 4.0)[1]"); expect(expression.evaluate(void 0)).toEqual(2); expression = new import__475.Expression("vec4(1.0, 2.0, 3.0, 4.0)[2]"); expect(expression.evaluate(void 0)).toEqual(3); expression = new import__475.Expression("vec4(1.0, 2.0, 3.0, 4.0)[3]"); expect(expression.evaluate(void 0)).toEqual(4); }); it('evaluates vector properties (["x"], ["y"], ["z"]. ["w"])', function() { let expression = new import__475.Expression('vec4(1.0, 2.0, 3.0, 4.0)["x"]'); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression('vec4(1.0, 2.0, 3.0, 4.0)["y"]'); expect(expression.evaluate(void 0)).toEqual(2); expression = new import__475.Expression('vec4(1.0, 2.0, 3.0, 4.0)["z"]'); expect(expression.evaluate(void 0)).toEqual(3); expression = new import__475.Expression('vec4(1.0, 2.0, 3.0, 4.0)["w"]'); expect(expression.evaluate(void 0)).toEqual(4); }); it('evaluates vector properties (["r"], ["g"], ["b"]. ["a"])', function() { let expression = new import__475.Expression('vec4(1.0, 2.0, 3.0, 4.0)["r"]'); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression('vec4(1.0, 2.0, 3.0, 4.0)["g"]'); expect(expression.evaluate(void 0)).toEqual(2); expression = new import__475.Expression('vec4(1.0, 2.0, 3.0, 4.0)["b"]'); expect(expression.evaluate(void 0)).toEqual(3); expression = new import__475.Expression('vec4(1.0, 2.0, 3.0, 4.0)["a"]'); expect(expression.evaluate(void 0)).toEqual(4); }); it("evaluates unary not", function() { let expression = new import__475.Expression("!true"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("!!true"); expect(expression.evaluate(void 0)).toEqual(true); }); it("throws if unary not takes invalid argument", function() { const expression = new import__475.Expression('!"true"'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates unary negative", function() { let expression = new import__475.Expression("-5"); expect(expression.evaluate(void 0)).toEqual(-5); expression = new import__475.Expression("-(-5)"); expect(expression.evaluate(void 0)).toEqual(5); }); it("throws if unary negative takes invalid argument", function() { const expression = new import__475.Expression('-"56"'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates unary positive", function() { const expression = new import__475.Expression("+5"); expect(expression.evaluate(void 0)).toEqual(5); }); it("throws if unary positive takes invalid argument", function() { const expression = new import__475.Expression('+"56"'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates binary addition", function() { let expression = new import__475.Expression("1 + 2"); expect(expression.evaluate(void 0)).toEqual(3); expression = new import__475.Expression("1 + 2 + 3 + 4"); expect(expression.evaluate(void 0)).toEqual(10); }); it("evaluates binary addition with strings", function() { let expression = new import__475.Expression('1 + "10"'); expect(expression.evaluate(void 0)).toEqual("110"); expression = new import__475.Expression('"10" + 1'); expect(expression.evaluate(void 0)).toEqual("101"); expression = new import__475.Expression('"name_" + "building"'); expect(expression.evaluate(void 0)).toEqual("name_building"); expression = new import__475.Expression('"name_" + true'); expect(expression.evaluate(void 0)).toEqual("name_true"); expression = new import__475.Expression('"name_" + null'); expect(expression.evaluate(void 0)).toEqual("name_null"); expression = new import__475.Expression('"name_" + undefined'); expect(expression.evaluate(void 0)).toEqual("name_undefined"); expression = new import__475.Expression('"name_" + vec2(1.1)'); expect(expression.evaluate(void 0)).toEqual("name_(1.1, 1.1)"); expression = new import__475.Expression('"name_" + vec3(1.1)'); expect(expression.evaluate(void 0)).toEqual("name_(1.1, 1.1, 1.1)"); expression = new import__475.Expression('"name_" + vec4(1.1)'); expect(expression.evaluate(void 0)).toEqual("name_(1.1, 1.1, 1.1, 1.1)"); expression = new import__475.Expression('"name_" + regExp("a")'); expect(expression.evaluate(void 0)).toEqual("name_/a/"); }); it("throws if binary addition takes invalid arguments", function() { let expression = new import__475.Expression("vec2(1.0) + vec3(1.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("1.0 + vec3(1.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates binary subtraction", function() { let expression = new import__475.Expression("2 - 1"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("4 - 3 - 2 - 1"); expect(expression.evaluate(void 0)).toEqual(-2); }); it("throws if binary subtraction takes invalid arguments", function() { let expression = new import__475.Expression("vec2(1.0) - vec3(1.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("1.0 - vec3(1.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression('"name1" - "name2"'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates binary multiplication", function() { let expression = new import__475.Expression("1 * 2"); expect(expression.evaluate(void 0)).toEqual(2); expression = new import__475.Expression("1 * 2 * 3 * 4"); expect(expression.evaluate(void 0)).toEqual(24); }); it("throws if binary multiplication takes invalid arguments", function() { let expression = new import__475.Expression("vec2(1.0) * vec3(1.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression('vec2(1.0) * "name"'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates binary division", function() { let expression = new import__475.Expression("2 / 1"); expect(expression.evaluate(void 0)).toEqual(2); expression = new import__475.Expression("1/2"); expect(expression.evaluate(void 0)).toEqual(0.5); expression = new import__475.Expression("24 / -4 / 2"); expect(expression.evaluate(void 0)).toEqual(-3); }); it("throws if binary division takes invalid arguments", function() { let expression = new import__475.Expression("vec2(1.0) / vec3(1.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression('vec2(1.0) / "2.0"'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("1.0 / vec4(1.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates binary modulus", function() { let expression = new import__475.Expression("2 % 1"); expect(expression.evaluate(void 0)).toEqual(0); expression = new import__475.Expression("6 % 4 % 3"); expect(expression.evaluate(void 0)).toEqual(2); }); it("throws if binary modulus takes invalid arguments", function() { let expression = new import__475.Expression("vec2(1.0) % vec3(1.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression('vec2(1.0) % "2.0"'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("1.0 % vec4(1.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates binary equals strict", function() { let expression = new import__475.Expression("'hello' === 'hello'"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("1 === 2"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("false === true === false"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression('1 === "1"'); expect(expression.evaluate(void 0)).toEqual(false); }); it("evaluates binary not equals strict", function() { let expression = new import__475.Expression("'hello' !== 'hello'"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("1 !== 2"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("false !== true !== false"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression('1 !== "1"'); expect(expression.evaluate(void 0)).toEqual(true); }); it("evaluates binary less than", function() { let expression = new import__475.Expression("2 < 3"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("2 < 2"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("3 < 2"); expect(expression.evaluate(void 0)).toEqual(false); }); it("throws if binary less than takes invalid arguments", function() { let expression = new import__475.Expression("vec2(1.0) < vec2(2.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("1 < vec3(1.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("true < false"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("color('blue') < 10"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates binary less than or equals", function() { let expression = new import__475.Expression("2 <= 3"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("2 <= 2"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("3 <= 2"); expect(expression.evaluate(void 0)).toEqual(false); }); it("throws if binary less than or equals takes invalid arguments", function() { let expression = new import__475.Expression("vec2(1.0) <= vec2(2.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("1 <= vec3(1.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression('1.0 <= "5"'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("true <= false"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("color('blue') <= 10"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates binary greater than", function() { let expression = new import__475.Expression("2 > 3"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("2 > 2"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("3 > 2"); expect(expression.evaluate(void 0)).toEqual(true); }); it("throws if binary greater than takes invalid arguments", function() { let expression = new import__475.Expression("vec2(1.0) > vec2(2.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("1 > vec3(1.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression('1.0 > "5"'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("true > false"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("color('blue') > 10"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates binary greater than or equals", function() { let expression = new import__475.Expression("2 >= 3"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("2 >= 2"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("3 >= 2"); expect(expression.evaluate(void 0)).toEqual(true); }); it("throws if binary greater than or equals takes invalid arguments", function() { let expression = new import__475.Expression("vec2(1.0) >= vec2(2.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("1 >= vec3(1.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression('1.0 >= "5"'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("true >= false"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("color('blue') >= 10"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates logical and", function() { let expression = new import__475.Expression("false && false"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("false && true"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("true && true"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("2 && color('red')"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("throws with invalid and operands", function() { let expression = new import__475.Expression("2 && true"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("true && color('red')"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates logical or", function() { let expression = new import__475.Expression("false || false"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("false || true"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("true || true"); expect(expression.evaluate(void 0)).toEqual(true); }); it("throws with invalid or operands", function() { let expression = new import__475.Expression("2 || false"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("false || color('red')"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates color operations", function() { let expression = new import__475.Expression("+rgba(255, 0, 0, 1.0)"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.RED) ); expression = new import__475.Expression("rgba(255, 0, 0, 0.5) + rgba(0, 0, 255, 0.5)"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.MAGENTA) ); expression = new import__475.Expression("rgba(0, 255, 255, 1.0) - rgba(0, 255, 0, 0)"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.BLUE) ); expression = new import__475.Expression( "rgba(255, 255, 255, 1.0) * rgba(255, 0, 0, 1.0)" ); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.RED) ); expression = new import__475.Expression("rgba(255, 255, 0, 1.0) * 1.0"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.YELLOW) ); expression = new import__475.Expression("1 * rgba(255, 255, 0, 1.0)"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.YELLOW) ); expression = new import__475.Expression( "rgba(255, 255, 255, 1.0) / rgba(255, 255, 255, 1.0)" ); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(import__475.Color.WHITE) ); expression = new import__475.Expression("rgba(255, 255, 255, 1.0) / 2"); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(new import__475.Color(0.5, 0.5, 0.5, 0.5)) ); expression = new import__475.Expression( "rgba(255, 255, 255, 1.0) % rgba(255, 255, 255, 1.0)" ); expect(expression.evaluate(void 0)).toEqual( import__475.Cartesian4.fromColor(new import__475.Color(0, 0, 0, 0)) ); expression = new import__475.Expression("color('green') === color('green')"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("color('green') !== color('green')"); expect(expression.evaluate(void 0)).toEqual(false); }); it("evaluates vector operations", function() { let expression = new import__475.Expression("+vec2(1, 2)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(1, 2)); expression = new import__475.Expression("+vec3(1, 2, 3)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian3(1, 2, 3)); expression = new import__475.Expression("+vec4(1, 2, 3, 4)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian4(1, 2, 3, 4)); expression = new import__475.Expression("-vec2(1, 2)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(-1, -2)); expression = new import__475.Expression("-vec3(1, 2, 3)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian3(-1, -2, -3)); expression = new import__475.Expression("-vec4(1, 2, 3, 4)"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(-1, -2, -3, -4) ); expression = new import__475.Expression("vec2(1, 2) + vec2(3, 4)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(4, 6)); expression = new import__475.Expression("vec3(1, 2, 3) + vec3(3, 4, 5)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian3(4, 6, 8)); expression = new import__475.Expression("vec4(1, 2, 3, 4) + vec4(3, 4, 5, 6)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian4(4, 6, 8, 10)); expression = new import__475.Expression("vec2(1, 2) - vec2(3, 4)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(-2, -2)); expression = new import__475.Expression("vec3(1, 2, 3) - vec3(3, 4, 5)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian3(-2, -2, -2)); expression = new import__475.Expression("vec4(1, 2, 3, 4) - vec4(3, 4, 5, 6)"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(-2, -2, -2, -2) ); expression = new import__475.Expression("vec2(1, 2) * vec2(3, 4)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(3, 8)); expression = new import__475.Expression("vec2(1, 2) * 3.0"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(3, 6)); expression = new import__475.Expression("3.0 * vec2(1, 2)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(3, 6)); expression = new import__475.Expression("vec3(1, 2, 3) * vec3(3, 4, 5)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian3(3, 8, 15)); expression = new import__475.Expression("vec3(1, 2, 3) * 3.0"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian3(3, 6, 9)); expression = new import__475.Expression("3.0 * vec3(1, 2, 3)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian3(3, 6, 9)); expression = new import__475.Expression("vec4(1, 2, 3, 4) * vec4(3, 4, 5, 6)"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(3, 8, 15, 24) ); expression = new import__475.Expression("vec4(1, 2, 3, 4) * 3.0"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian4(3, 6, 9, 12)); expression = new import__475.Expression("3.0 * vec4(1, 2, 3, 4)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian4(3, 6, 9, 12)); expression = new import__475.Expression("vec2(1, 2) / vec2(2, 5)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(0.5, 0.4)); expression = new import__475.Expression("vec2(1, 2) / 2.0"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(0.5, 1)); expression = new import__475.Expression("vec3(1, 2, 3) / vec3(2, 5, 3)"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(0.5, 0.4, 1) ); expression = new import__475.Expression("vec3(1, 2, 3) / 2.0"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(0.5, 1, 1.5) ); expression = new import__475.Expression("vec4(1, 2, 3, 4) / vec4(2, 5, 3, 2)"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(0.5, 0.4, 1, 2) ); expression = new import__475.Expression("vec4(1, 2, 3, 4) / 2.0"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(0.5, 1, 1.5, 2) ); expression = new import__475.Expression("vec2(2, 3) % vec2(3, 3)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(2, 0)); expression = new import__475.Expression("vec3(2, 3, 4) % vec3(3, 3, 3)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian3(2, 0, 1)); expression = new import__475.Expression("vec4(2, 3, 4, 5) % vec4(3, 3, 3, 2)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian4(2, 0, 1, 1)); expression = new import__475.Expression("vec2(1, 2) === vec2(1, 2)"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("vec3(1, 2, 3) === vec3(1, 2, 3)"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("vec4(1, 2, 3, 4) === vec4(1, 2, 3, 4)"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("vec2(1, 2) !== vec2(1, 2)"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("vec3(1, 2, 3) !== vec3(1, 2, 3)"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("vec4(1, 2, 3, 4) !== vec4(1, 2, 3, 4)"); expect(expression.evaluate(void 0)).toEqual(false); }); it("evaluates color toString function", function() { let expression = new import__475.Expression('color("red").toString()'); expect(expression.evaluate(void 0)).toEqual("(1, 0, 0, 1)"); expression = new import__475.Expression("rgba(0, 0, 255, 0.5).toString()"); expect(expression.evaluate(void 0)).toEqual("(0, 0, 1, 0.5)"); }); it("evaluates vector toString function", function() { const feature = new MockFeature(); feature.addProperty("property", new import__475.Cartesian4(1, 2, 3, 4)); let expression = new import__475.Expression("vec2(1, 2).toString()"); expect(expression.evaluate(void 0)).toEqual("(1, 2)"); expression = new import__475.Expression("vec3(1, 2, 3).toString()"); expect(expression.evaluate(void 0)).toEqual("(1, 2, 3)"); expression = new import__475.Expression("vec4(1, 2, 3, 4).toString()"); expect(expression.evaluate(void 0)).toEqual("(1, 2, 3, 4)"); expression = new import__475.Expression("${property}.toString()"); expect(expression.evaluate(feature)).toEqual("(1, 2, 3, 4)"); }); it("evaluates isNaN function", function() { let expression = new import__475.Expression("isNaN()"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("isNaN(NaN)"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("isNaN(1)"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("isNaN(Infinity)"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("isNaN(null)"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("isNaN(true)"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression('isNaN("hello")'); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression('isNaN(color("white"))'); expect(expression.evaluate(void 0)).toEqual(true); }); it("evaluates isFinite function", function() { let expression = new import__475.Expression("isFinite()"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("isFinite(NaN)"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("isFinite(1)"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("isFinite(Infinity)"); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("isFinite(null)"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("isFinite(true)"); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression('isFinite("hello")'); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression('isFinite(color("white"))'); expect(expression.evaluate(void 0)).toEqual(false); }); it("evaluates isExactClass function", function() { const feature = new MockFeature(); feature.setClass("door"); let expression = new import__475.Expression('isExactClass("door")'); expect(expression.evaluate(feature)).toEqual(true); expression = new import__475.Expression('isExactClass("roof")'); expect(expression.evaluate(feature)).toEqual(false); expect(expression.evaluate(void 0)).toEqual(false); }); it("throws if isExactClass takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("isExactClass()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression('isExactClass("door", "roof")'); }).toThrowError(import__475.RuntimeError); }); it("evaluates isClass function", function() { const feature = new MockFeature(); feature.setClass("door"); feature.setInheritedClass("building"); const expression = new import__475.Expression('isClass("door") && isClass("building")'); expect(expression.evaluate(feature)).toEqual(true); expect(expression.evaluate(void 0)).toEqual(false); }); it("throws if isClass takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("isClass()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression('isClass("door", "building")'); }).toThrowError(import__475.RuntimeError); }); it("evaluates getExactClassName function", function() { const feature = new MockFeature(); feature.setClass("door"); const expression = new import__475.Expression("getExactClassName()"); expect(expression.evaluate(feature)).toEqual("door"); expect(expression.evaluate(void 0)).toBeUndefined(); }); it("throws if getExactClassName takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression('getExactClassName("door")'); }).toThrowError(import__475.RuntimeError); }); it("throws if built-in unary function is given an invalid argument", function() { const expression = new import__475.Expression('abs("-1")'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates abs function", function() { let expression = new import__475.Expression("abs(-1)"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("abs(1)"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("abs(vec2(-1.0, 1.0))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(1, 1)); expression = new import__475.Expression("abs(vec3(-1.0, 1.0, 0.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(1, 1, 0) ); expression = new import__475.Expression("abs(vec4(-1.0, 1.0, 0.0, -1.2))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(1, 1, 0, 1.2) ); }); it("throws if abs function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("abs()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("abs(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates cos function", function() { let expression = new import__475.Expression("cos(0)"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("cos(vec2(0, Math.PI))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian2(1, -1), import__476.Math.EPSILON7 ); expression = new import__475.Expression("cos(vec3(0, Math.PI, -Math.PI))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian3(1, -1, -1), import__476.Math.EPSILON7 ); expression = new import__475.Expression("cos(vec4(0, Math.PI, -Math.PI, 0))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian4(1, -1, -1, 1), import__476.Math.EPSILON7 ); }); it("throws if cos function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("cos()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("cos(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates sin function", function() { let expression = new import__475.Expression("sin(0)"); expect(expression.evaluate(void 0)).toEqual(0); expression = new import__475.Expression("sin(vec2(0, Math.PI/2))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian2(0, 1), import__476.Math.EPSILON7 ); expression = new import__475.Expression("sin(vec3(0, Math.PI/2, -Math.PI/2))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian3(0, 1, -1), import__476.Math.EPSILON7 ); expression = new import__475.Expression("sin(vec4(0, Math.PI/2, -Math.PI/2, 0))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian4(0, 1, -1, 0), import__476.Math.EPSILON7 ); }); it("throws if sin function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("sin()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("sin(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates tan function", function() { let expression = new import__475.Expression("tan(0)"); expect(expression.evaluate(void 0)).toEqual(0); expression = new import__475.Expression("tan(vec2(0, Math.PI/4))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian2(0, 1), import__476.Math.EPSILON7 ); expression = new import__475.Expression("tan(vec3(0, Math.PI/4, Math.PI))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian3(0, 1, 0), import__476.Math.EPSILON7 ); expression = new import__475.Expression("tan(vec4(0, Math.PI/4, Math.PI, -Math.PI/4))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian4(0, 1, 0, -1), import__476.Math.EPSILON7 ); }); it("throws if tan function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("tan()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("tan(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates acos function", function() { let expression = new import__475.Expression("acos(1)"); expect(expression.evaluate(void 0)).toEqual(0); expression = new import__475.Expression("acos(vec2(1, 0))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian2(0, import__476.Math.PI_OVER_TWO), import__476.Math.EPSILON7 ); expression = new import__475.Expression("acos(vec3(1, 0, 1))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian3(0, import__476.Math.PI_OVER_TWO, 0, import__476.Math.PI_OVER_TWO), import__476.Math.EPSILON7 ); expression = new import__475.Expression("acos(vec4(1, 0, 1, 0))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian4( 0, import__476.Math.PI_OVER_TWO, 0, import__476.Math.PI_OVER_TWO, 0 ), import__476.Math.EPSILON7 ); }); it("throws if acos function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("acos()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("acos(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates asin function", function() { let expression = new import__475.Expression("asin(0)"); expect(expression.evaluate(void 0)).toEqual(0); expression = new import__475.Expression("asin(vec2(0, 1))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian2(0, import__476.Math.PI_OVER_TWO), import__476.Math.EPSILON7 ); expression = new import__475.Expression("asin(vec3(0, 1, 0))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian3(0, import__476.Math.PI_OVER_TWO, 0, import__476.Math.PI_OVER_TWO), import__476.Math.EPSILON7 ); expression = new import__475.Expression("asin(vec4(0, 1, 0, 1))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian4( 0, import__476.Math.PI_OVER_TWO, 0, import__476.Math.PI_OVER_TWO, 0 ), import__476.Math.EPSILON7 ); }); it("throws if asin function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("asin()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("asin(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates atan function", function() { let expression = new import__475.Expression("atan(0)"); expect(expression.evaluate(void 0)).toEqual(0); expression = new import__475.Expression("atan(vec2(0, 1))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian2(0, import__476.Math.PI_OVER_FOUR), import__476.Math.EPSILON7 ); expression = new import__475.Expression("atan(vec3(0, 1, 0))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian3( 0, import__476.Math.PI_OVER_FOUR, 0, import__476.Math.PI_OVER_FOUR ), import__476.Math.EPSILON7 ); expression = new import__475.Expression("atan(vec4(0, 1, 0, 1))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian4( 0, import__476.Math.PI_OVER_FOUR, 0, import__476.Math.PI_OVER_FOUR, 0 ), import__476.Math.EPSILON7 ); }); it("throws if atan function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("atan()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("atan(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates radians function", function() { let expression = new import__475.Expression("radians(180)"); expect(expression.evaluate(void 0)).toEqualEpsilon( Math.PI, import__476.Math.EPSILON10 ); expression = new import__475.Expression("radians(vec2(180, 90))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian2(Math.PI, import__476.Math.PI_OVER_TWO), import__476.Math.EPSILON7 ); expression = new import__475.Expression("radians(vec3(180, 90, 180))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian3(Math.PI, import__476.Math.PI_OVER_TWO, Math.PI), import__476.Math.EPSILON7 ); expression = new import__475.Expression("radians(vec4(180, 90, 180, 90))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian4( Math.PI, import__476.Math.PI_OVER_TWO, Math.PI, import__476.Math.PI_OVER_TWO ), import__476.Math.EPSILON7 ); }); it("throws if radians function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("radians()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("radians(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates degrees function", function() { let expression = new import__475.Expression("degrees(2 * Math.PI)"); expect(expression.evaluate(void 0)).toEqualEpsilon( 360, import__476.Math.EPSILON10 ); expression = new import__475.Expression("degrees(vec2(2 * Math.PI, Math.PI))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian2(360, 180), import__476.Math.EPSILON7 ); expression = new import__475.Expression( "degrees(vec3(2 * Math.PI, Math.PI, 2 * Math.PI))" ); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian3(360, 180, 360), import__476.Math.EPSILON7 ); expression = new import__475.Expression( "degrees(vec4(2 * Math.PI, Math.PI, 2 * Math.PI, Math.PI))" ); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian4(360, 180, 360, 180), import__476.Math.EPSILON7 ); }); it("throws if degrees function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("degrees()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("degrees(1, 2)"); }); }); it("evaluates sqrt function", function() { let expression = new import__475.Expression("sqrt(1.0)"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("sqrt(4.0)"); expect(expression.evaluate(void 0)).toEqual(2); expression = new import__475.Expression("sqrt(-1.0)"); expect(expression.evaluate(void 0)).toEqual(NaN); expression = new import__475.Expression("sqrt(vec2(1.0, 4.0))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(1, 2)); expression = new import__475.Expression("sqrt(vec3(1.0, 4.0, 9.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(1, 2, 3) ); expression = new import__475.Expression("sqrt(vec4(1.0, 4.0, 9.0, 16.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(1, 2, 3, 4) ); }); it("throws if sqrt function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("sqrt()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("sqrt(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates sign function", function() { let expression = new import__475.Expression("sign(5.0)"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("sign(0.0)"); expect(expression.evaluate(void 0)).toEqual(0); expression = new import__475.Expression("sign(-5.0)"); expect(expression.evaluate(void 0)).toEqual(-1); expression = new import__475.Expression("sign(vec2(5.0, -5.0))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(1, -1)); expression = new import__475.Expression("sign(vec3(5.0, -5.0, 0.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(1, -1, 0) ); expression = new import__475.Expression("sign(vec4(5.0, -5.0, 0.0, 1.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(1, -1, 0, 1) ); }); it("throws if sign function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("sign()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("sign(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates floor function", function() { let expression = new import__475.Expression("floor(5.5)"); expect(expression.evaluate(void 0)).toEqual(5); expression = new import__475.Expression("floor(0.0)"); expect(expression.evaluate(void 0)).toEqual(0); expression = new import__475.Expression("floor(-1.2)"); expect(expression.evaluate(void 0)).toEqual(-2); expression = new import__475.Expression("floor(vec2(5.5, -1.2))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(5, -2)); expression = new import__475.Expression("floor(vec3(5.5, -1.2, 0.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(5, -2, 0) ); expression = new import__475.Expression("floor(vec4(5.5, -1.2, 0.0, -2.9))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(5, -2, 0, -3) ); }); it("throws if floor function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("floor()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("floor(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates ceil function", function() { let expression = new import__475.Expression("ceil(5.5)"); expect(expression.evaluate(void 0)).toEqual(6); expression = new import__475.Expression("ceil(0.0)"); expect(expression.evaluate(void 0)).toEqual(0); expression = new import__475.Expression("ceil(-1.2)"); expect(expression.evaluate(void 0)).toEqual(-1); expression = new import__475.Expression("ceil(vec2(5.5, -1.2))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(6, -1)); expression = new import__475.Expression("ceil(vec3(5.5, -1.2, 0.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(6, -1, 0) ); expression = new import__475.Expression("ceil(vec4(5.5, -1.2, 0.0, -2.9))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(6, -1, 0, -2) ); }); it("throws if ceil function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("ceil()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("ceil(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates round function", function() { let expression = new import__475.Expression("round(5.5)"); expect(expression.evaluate(void 0)).toEqual(6); expression = new import__475.Expression("round(0.0)"); expect(expression.evaluate(void 0)).toEqual(0); expression = new import__475.Expression("round(1.2)"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("round(vec2(5.5, -1.2))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(6, -1)); expression = new import__475.Expression("round(vec3(5.5, -1.2, 0.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(6, -1, 0) ); expression = new import__475.Expression("round(vec4(5.5, -1.2, 0.0, -2.9))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(6, -1, 0, -3) ); }); it("throws if round function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("round()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("round(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates exp function", function() { let expression = new import__475.Expression("exp(1.0)"); expect(expression.evaluate(void 0)).toEqualEpsilon( Math.E, import__476.Math.EPSILON10 ); expression = new import__475.Expression("exp(0.0)"); expect(expression.evaluate(void 0)).toEqualEpsilon( 1, import__476.Math.EPSILON10 ); expression = new import__475.Expression("exp(vec2(1.0, 0.0))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian2(Math.E, 1), import__476.Math.EPSILON10 ); expression = new import__475.Expression("exp(vec3(1.0, 0.0, 1.0))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian3(Math.E, 1, Math.E), import__476.Math.EPSILON10 ); expression = new import__475.Expression("exp(vec4(1.0, 0.0, 1.0, 0.0))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian4(Math.E, 1, Math.E, 1), import__476.Math.EPSILON10 ); }); it("throws if exp function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("exp()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("exp(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates exp2 function", function() { let expression = new import__475.Expression("exp2(1.0)"); expect(expression.evaluate(void 0)).toEqual(2); expression = new import__475.Expression("exp2(0.0)"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("exp2(2.0)"); expect(expression.evaluate(void 0)).toEqual(4); expression = new import__475.Expression("exp2(vec2(1.0, 0.0))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(2, 1)); expression = new import__475.Expression("exp2(vec3(1.0, 0.0, 2.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(2, 1, 4) ); expression = new import__475.Expression("exp2(vec4(1.0, 0.0, 2.0, 3.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(2, 1, 4, 8) ); }); it("throws if exp2 function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("exp2()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("exp2(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates log function", function() { let expression = new import__475.Expression("log(1.0)"); expect(expression.evaluate(void 0)).toEqual(0); expression = new import__475.Expression("log(10.0)"); expect(expression.evaluate(void 0)).toEqualEpsilon( 2.302585092994046, import__476.Math.EPSILON7 ); expression = new import__475.Expression("log(vec2(1.0, Math.E))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(0, 1)); expression = new import__475.Expression("log(vec3(1.0, Math.E, 1.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(0, 1, 0) ); expression = new import__475.Expression("log(vec4(1.0, Math.E, 1.0, Math.E))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(0, 1, 0, 1) ); }); it("throws if log function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("log()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("log(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates log2 function", function() { let expression = new import__475.Expression("log2(1.0)"); expect(expression.evaluate(void 0)).toEqual(0); expression = new import__475.Expression("log2(2.0)"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("log2(4.0)"); expect(expression.evaluate(void 0)).toEqual(2); expression = new import__475.Expression("log2(vec2(1.0, 2.0))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(0, 1)); expression = new import__475.Expression("log2(vec3(1.0, 2.0, 4.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(0, 1, 2) ); expression = new import__475.Expression("log2(vec4(1.0, 2.0, 4.0, 8.0))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian4(0, 1, 2, 3), import__476.Math.EPSILON10 ); }); it("throws if log2 function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("log2()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("log2(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates fract function", function() { let expression = new import__475.Expression("fract(1.0)"); expect(expression.evaluate(void 0)).toEqual(0); expression = new import__475.Expression("fract(2.25)"); expect(expression.evaluate(void 0)).toEqual(0.25); expression = new import__475.Expression("fract(-2.25)"); expect(expression.evaluate(void 0)).toEqual(0.75); expression = new import__475.Expression("fract(vec2(1.0, 2.25))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(0, 0.25)); expression = new import__475.Expression("fract(vec3(1.0, 2.25, -2.25))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(0, 0.25, 0.75) ); expression = new import__475.Expression("fract(vec4(1.0, 2.25, -2.25, 1.0))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(0, 0.25, 0.75, 0) ); }); it("throws if fract function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("fract()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("fract(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates length function", function() { let expression = new import__475.Expression("length(-3.0)"); expect(expression.evaluate(void 0)).toEqual(3); expression = new import__475.Expression("length(vec2(-3.0, 4.0))"); expect(expression.evaluate(void 0)).toEqual(5); expression = new import__475.Expression("length(vec3(2.0, 3.0, 6.0))"); expect(expression.evaluate(void 0)).toEqual(7); expression = new import__475.Expression("length(vec4(2.0, 4.0, 7.0, 10.0))"); expect(expression.evaluate(void 0)).toEqual(13); }); it("throws if length function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("length()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("length(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates normalize function", function() { let expression = new import__475.Expression("normalize(5.0)"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("normalize(vec2(3.0, 4.0))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(0.6, 0.8)); expression = new import__475.Expression("normalize(vec3(2.0, 3.0, -4.0))"); let length2 = Math.sqrt(2 * 2 + 3 * 3 + 4 * 4); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian3(2 / length2, 3 / length2, -4 / length2), import__476.Math.EPSILON10 ); expression = new import__475.Expression("normalize(vec4(-2.0, 3.0, -4.0, 5.0))"); length2 = Math.sqrt(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(-2 / length2, 3 / length2, -4 / length2, 5 / length2), import__476.Math.EPSILON10 ); }); it("throws if normalize function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("fract()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("fract(1, 2)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates clamp function", function() { let expression = new import__475.Expression("clamp(50.0, 0.0, 100.0)"); expect(expression.evaluate(void 0)).toEqual(50); expression = new import__475.Expression("clamp(50.0, 0.0, 25.0)"); expect(expression.evaluate(void 0)).toEqual(25); expression = new import__475.Expression("clamp(50.0, 75.0, 100.0)"); expect(expression.evaluate(void 0)).toEqual(75); expression = new import__475.Expression( "clamp(vec2(50.0,50.0), vec2(0.0,75.0), 100.0)" ); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(50, 75)); expression = new import__475.Expression( "clamp(vec2(50.0,50.0), vec2(0.0,75.0), vec2(25.0,100.0))" ); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(25, 75)); expression = new import__475.Expression( "clamp(vec3(50.0, 50.0, 50.0), vec3(0.0, 0.0, 75.0), vec3(100.0, 25.0, 100.0))" ); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(50, 25, 75) ); expression = new import__475.Expression( "clamp(vec4(50.0, 50.0, 50.0, 100.0), vec4(0.0, 0.0, 75.0, 75.0), vec4(100.0, 25.0, 100.0, 85.0))" ); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(50, 25, 75, 85) ); }); it("throws if clamp function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("clamp()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("clamp(1)"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("clamp(1, 2)"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("clamp(1, 2, 3, 4)"); }).toThrowError(import__475.RuntimeError); }); it("throws if clamp function takes mismatching types", function() { let expression = new import__475.Expression("clamp(0.0,vec2(0,1),0.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("clamp(vec2(0,1),vec3(0,1,2),0.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("clamp(vec2(0,1),vec2(0,1), vec3(1,2,3))"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates mix function", function() { let expression = new import__475.Expression("mix(0.0, 2.0, 0.5)"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("mix(vec2(0.0,1.0), vec2(2.0,3.0), 0.5)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(1, 2)); expression = new import__475.Expression( "mix(vec2(0.0,1.0), vec2(2.0,3.0), vec2(0.5,4.0))" ); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(1, 9)); expression = new import__475.Expression( "mix(vec3(0.0,1.0,2.0), vec3(2.0,3.0,4.0), vec3(0.5,4.0,5.0))" ); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(1, 9, 12) ); expression = new import__475.Expression( "mix(vec4(0.0,1.0,2.0,1.5), vec4(2.0,3.0,4.0,2.5), vec4(0.5,4.0,5.0,3.5))" ); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(1, 9, 12, 5) ); }); it("throws if mix function takes mismatching types", function() { let expression = new import__475.Expression("mix(0.0,vec2(0,1),0.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("mix(vec2(0,1),vec3(0,1,2),0.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("mix(vec2(0,1),vec2(0,1), vec3(1,2,3))"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("throws if mix function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("mix()"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("mix(1)"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("mix(1, 2)"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("mix(1, 2, 3, 4)"); }).toThrowError(import__475.RuntimeError); }); it("evaluates atan2 function", function() { let expression = new import__475.Expression("atan2(0,1)"); expect(expression.evaluate(void 0)).toEqualEpsilon( 0, import__476.Math.EPSILON10 ); expression = new import__475.Expression("atan2(1,0)"); expect(expression.evaluate(void 0)).toEqualEpsilon( 0.5 * Math.PI, import__476.Math.EPSILON10 ); expression = new import__475.Expression("atan2(vec2(0,1),vec2(1,0))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian2(0, 0.5 * Math.PI), import__476.Math.EPSILON10 ); expression = new import__475.Expression("atan2(vec3(0,1,0.5),vec3(1,0,0.5))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian3(0, 0.5 * Math.PI, 0.25 * Math.PI), import__476.Math.EPSILON10 ); expression = new import__475.Expression("atan2(vec4(0,1,0.5,1),vec4(1,0,0.5,0))"); expect(expression.evaluate(void 0)).toEqualEpsilon( new import__475.Cartesian4(0, 0.5 * Math.PI, 0.25 * Math.PI, 0.5 * Math.PI), import__476.Math.EPSILON10 ); }); it("throws if atan2 function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("atan2(0.0)"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("atan2(1, 2, 0)"); }).toThrowError(import__475.RuntimeError); }); it("throws if atan2 function takes mismatching types", function() { let expression = new import__475.Expression("atan2(0.0,vec2(0,1))"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("atan2(vec2(0,1),0.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("atan2(vec2(0,1),vec3(0,1,2))"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates pow function", function() { let expression = new import__475.Expression("pow(5,0)"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("pow(4,2)"); expect(expression.evaluate(void 0)).toEqual(16); expression = new import__475.Expression("pow(vec2(5,4),vec2(0,2))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(1, 16)); expression = new import__475.Expression("pow(vec3(5,4,3),vec3(0,2,3))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(1, 16, 27) ); expression = new import__475.Expression("pow(vec4(5,4,3,2),vec4(0,2,3,5))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(1, 16, 27, 32) ); }); it("throws if pow function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("pow(0.0)"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("pow(1, 2, 0)"); }).toThrowError(import__475.RuntimeError); }); it("throws if pow function takes mismatching types", function() { let expression = new import__475.Expression("pow(0.0, vec2(0,1))"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("pow(vec2(0,1),0.0)"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("pow(vec2(0,1),vec3(0,1,2))"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates min function", function() { let expression = new import__475.Expression("min(0,1)"); expect(expression.evaluate(void 0)).toEqual(0); expression = new import__475.Expression("min(-1,0)"); expect(expression.evaluate(void 0)).toEqual(-1); expression = new import__475.Expression("min(vec2(-1,1),0)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(-1, 0)); expression = new import__475.Expression("min(vec2(-1,2),vec2(0,1))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(-1, 1)); expression = new import__475.Expression("min(vec3(-1,2,1),vec3(0,1,2))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(-1, 1, 1) ); expression = new import__475.Expression("min(vec4(-1,2,1,4),vec4(0,1,2,3))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(-1, 1, 1, 3) ); }); it("throws if min function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("min(0.0)"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("min(1, 2, 0)"); }).toThrowError(import__475.RuntimeError); }); it("throws if min function takes mismatching types", function() { let expression = new import__475.Expression("min(0.0, vec2(0,1))"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("min(vec2(0,1),vec3(0,1,2))"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates max function", function() { let expression = new import__475.Expression("max(0,1)"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("max(-1,0)"); expect(expression.evaluate(void 0)).toEqual(0); expression = new import__475.Expression("max(vec2(-1,1),0)"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(0, 1)); expression = new import__475.Expression("max(vec2(-1,2),vec2(0,1))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian2(0, 2)); expression = new import__475.Expression("max(vec3(-1,2,1),vec3(0,1,2))"); expect(expression.evaluate(void 0)).toEqual(new import__475.Cartesian3(0, 2, 2)); expression = new import__475.Expression("max(vec4(-1,2,1,4),vec4(0,1,2,3))"); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian4(0, 2, 2, 4) ); }); it("throws if max function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("max(0.0)"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("max(1, 2, 0)"); }).toThrowError(import__475.RuntimeError); }); it("throws if max function takes mismatching types", function() { let expression = new import__475.Expression("max(0.0, vec2(0,1))"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("max(vec2(0,1),vec3(0,1,2))"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates the distance function", function() { let expression = new import__475.Expression("distance(0, 1)"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression("distance(vec2(1.0, 0.0), vec2(0.0, 0.0))"); expect(expression.evaluate(void 0)).toEqual(1); expression = new import__475.Expression( "distance(vec3(3.0, 2.0, 1.0), vec3(1.0, 0.0, 0.0))" ); expect(expression.evaluate(void 0)).toEqual(3); expression = new import__475.Expression( "distance(vec4(5.0, 5.0, 5.0, 5.0), vec4(0.0, 0.0, 0.0, 0.0))" ); expect(expression.evaluate(void 0)).toEqual(10); }); it("throws if distance function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("distance(0.0)"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("distance(1, 3, 0)"); }).toThrowError(import__475.RuntimeError); }); it("throws if distance function takes mismatching types of arguments", function() { expect(function() { return new import__475.Expression("distance(1, vec2(3.0, 2.0)").evaluate(void 0); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression( "distance(vec4(5.0, 2.0, 3.0, 1.0), vec3(4.0, 4.0, 4.0))" ).evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates the dot function", function() { let expression = new import__475.Expression("dot(1, 2)"); expect(expression.evaluate(void 0)).toEqual(2); expression = new import__475.Expression("dot(vec2(1.0, 1.0), vec2(2.0, 2.0))"); expect(expression.evaluate(void 0)).toEqual(4); expression = new import__475.Expression( "dot(vec3(1.0, 2.0, 3.0), vec3(2.0, 2.0, 1.0))" ); expect(expression.evaluate(void 0)).toEqual(9); expression = new import__475.Expression( "dot(vec4(5.0, 5.0, 2.0, 3.0), vec4(1.0, 2.0, 1.0, 1.0))" ); expect(expression.evaluate(void 0)).toEqual(20); }); it("throws if dot function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("dot(0.0)"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression("dot(1, 3, 0)"); }).toThrowError(import__475.RuntimeError); }); it("throws if dot function takes mismatching types of arguments", function() { expect(function() { return new import__475.Expression("dot(1, vec2(3.0, 2.0)").evaluate(void 0); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression( "dot(vec4(5.0, 2.0, 3.0, 1.0), vec3(4.0, 4.0, 4.0))" ).evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates the cross function", function() { let expression = new import__475.Expression( "cross(vec3(1.0, 1.0, 1.0), vec3(2.0, 2.0, 2.0))" ); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(0, 0, 0) ); expression = new import__475.Expression( "cross(vec3(-1.0, -1.0, -1.0), vec3(0.0, -2.0, -5.0))" ); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(3, -5, 2) ); expression = new import__475.Expression( "cross(vec3(5.0, -2.0, 1.0), vec3(-2.0, -6.0, -8.0))" ); expect(expression.evaluate(void 0)).toEqual( new import__475.Cartesian3(22, 38, -34) ); }); it("throws if cross function takes an invalid number of arguments", function() { expect(function() { return new import__475.Expression("cross(vec3(0.0, 0.0, 0.0))"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression( "cross(vec3(0.0, 0.0, 0.0), vec3(1.0, 1.0, 1.0), vec3(2.0, 2.0, 2.0))" ); }).toThrowError(import__475.RuntimeError); }); it("throws if cross function does not take vec3 arguments", function() { expect(function() { return new import__475.Expression("cross(vec2(1.0, 2.0), vec2(3.0, 2.0)").evaluate( void 0 ); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression( "cross(vec4(5.0, 2.0, 3.0, 1.0), vec3(4.0, 4.0, 4.0))" ).evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates ternary conditional", function() { let expression = new import__475.Expression('true ? "first" : "second"'); expect(expression.evaluate(void 0)).toEqual("first"); expression = new import__475.Expression('false ? "first" : "second"'); expect(expression.evaluate(void 0)).toEqual("second"); expression = new import__475.Expression( "(!(1 + 2 > 3)) ? (2 > 1 ? 1 + 1 : 0) : (2 > 1 ? -1 + -1 : 0)" ); expect(expression.evaluate(void 0)).toEqual(2); }); it("evaluates member expression with dot", function() { const feature = new MockFeature(); feature.addProperty("height", 10); feature.addProperty("width", 5); feature.addProperty("string", "hello"); feature.addProperty("boolean", true); feature.addProperty("vector", import__475.Cartesian4.UNIT_X); feature.addProperty("vector.x", "something else"); feature.addProperty("feature.vector", import__475.Cartesian4.UNIT_Y); feature.addProperty("feature", { vector: import__475.Cartesian4.UNIT_Z }); feature.addProperty("null", null); feature.addProperty("undefined", void 0); feature.addProperty("address", { street: "Example Street", city: "Example City" }); let expression = new import__475.Expression("${vector.x}"); expect(expression.evaluate(feature)).toEqual(1); expression = new import__475.Expression("${vector.z}"); expect(expression.evaluate(feature)).toEqual(0); expression = new import__475.Expression("${height.z}"); expect(expression.evaluate(feature)).toEqual(void 0); expression = new import__475.Expression("${undefined.z}"); expect(expression.evaluate(feature)).toEqual(void 0); expression = new import__475.Expression("${feature}"); expect(expression.evaluate(feature)).toEqual({ vector: import__475.Cartesian4.UNIT_Z }); expression = new import__475.Expression("${feature.vector}"); expect(expression.evaluate(feature)).toEqual(import__475.Cartesian4.UNIT_X); expression = new import__475.Expression("${feature.feature.vector}"); expect(expression.evaluate(feature)).toEqual(import__475.Cartesian4.UNIT_Z); expression = new import__475.Expression("${feature.vector.x}"); expect(expression.evaluate(feature)).toEqual(1); expression = new import__475.Expression("${address.street}"); expect(expression.evaluate(feature)).toEqual("Example Street"); expression = new import__475.Expression("${address.city}"); expect(expression.evaluate(feature)).toEqual("Example City"); }); it("evaluates member expression with brackets", function() { const feature = new MockFeature(); feature.addProperty("height", 10); feature.addProperty("width", 5); feature.addProperty("string", "hello"); feature.addProperty("boolean", true); feature.addProperty("vector", import__475.Cartesian4.UNIT_X); feature.addProperty("vector.x", "something else"); feature.addProperty("feature.vector", import__475.Cartesian4.UNIT_Y); feature.addProperty("feature", { vector: import__475.Cartesian4.UNIT_Z }); feature.addProperty("null", null); feature.addProperty("undefined", void 0); feature.addProperty("address.street", "Other Street"); feature.addProperty("address", { street: "Example Street", city: "Example City" }); let expression = new import__475.Expression('${vector["x"]}'); expect(expression.evaluate(feature)).toEqual(1); expression = new import__475.Expression('${vector["z"]}'); expect(expression.evaluate(feature)).toEqual(0); expression = new import__475.Expression('${height["z"]}'); expect(expression.evaluate(feature)).toEqual(void 0); expression = new import__475.Expression('${undefined["z"]}'); expect(expression.evaluate(feature)).toEqual(void 0); expression = new import__475.Expression('${feature["vector"]}'); expect(expression.evaluate(feature)).toEqual(import__475.Cartesian4.UNIT_X); expression = new import__475.Expression('${feature.vector["x"]}'); expect(expression.evaluate(feature)).toEqual(1); expression = new import__475.Expression('${feature["vector"].x}'); expect(expression.evaluate(feature)).toEqual(1); expression = new import__475.Expression('${feature["vector.x"]}'); expect(expression.evaluate(feature)).toEqual("something else"); expression = new import__475.Expression('${feature.feature["vector"]}'); expect(expression.evaluate(feature)).toEqual(import__475.Cartesian4.UNIT_Z); expression = new import__475.Expression('${feature["feature.vector"]}'); expect(expression.evaluate(feature)).toEqual(import__475.Cartesian4.UNIT_Y); expression = new import__475.Expression("${address.street}"); expect(expression.evaluate(feature)).toEqual("Example Street"); expression = new import__475.Expression("${feature.address.street}"); expect(expression.evaluate(feature)).toEqual("Example Street"); expression = new import__475.Expression('${feature["address"].street}'); expect(expression.evaluate(feature)).toEqual("Example Street"); expression = new import__475.Expression('${feature["address.street"]}'); expect(expression.evaluate(feature)).toEqual("Other Street"); expression = new import__475.Expression('${address["street"]}'); expect(expression.evaluate(feature)).toEqual("Example Street"); expression = new import__475.Expression('${address["city"]}'); expect(expression.evaluate(feature)).toEqual("Example City"); }); it("member expressions throw without variable notation", function() { expect(function() { return new import__475.Expression("color.r"); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression('color["r"]'); }).toThrowError(import__475.RuntimeError); }); it("member expression throws with variable property", function() { const feature = new MockFeature(); feature.addProperty("vector", import__475.Cartesian4.UNIT_X); feature.addProperty("vectorName", "UNIT_X"); expect(function() { return new import__475.Expression("${vector[${vectorName}]}"); }).toThrowError(import__475.RuntimeError); }); it("evaluates feature property", function() { const feature = new MockFeature(); feature.addProperty("feature", { vector: import__475.Cartesian4.UNIT_X }); let expression = new import__475.Expression("${feature}"); expect(expression.evaluate(feature)).toEqual({ vector: import__475.Cartesian4.UNIT_X }); expression = new import__475.Expression("${feature} === ${feature.feature}"); expect(expression.evaluate(feature)).toEqual(true); }); it("constructs regex", function() { const feature = new MockFeature(); feature.addProperty("pattern", "[abc]"); let expression = new import__475.Expression('regExp("a")'); expect(expression.evaluate(void 0)).toEqual(/a/); expect(expression._runtimeAst._type).toEqual( import__475.ExpressionNodeType.LITERAL_REGEX ); expression = new import__475.Expression('regExp("\\w")'); expect(expression.evaluate(void 0)).toEqual(/\w/); expect(expression._runtimeAst._type).toEqual( import__475.ExpressionNodeType.LITERAL_REGEX ); expression = new import__475.Expression("regExp(1 + 1)"); expect(expression.evaluate(void 0)).toEqual(/2/); expect(expression._runtimeAst._type).toEqual(import__475.ExpressionNodeType.REGEX); expression = new import__475.Expression("regExp(true)"); expect(expression.evaluate(void 0)).toEqual(/true/); expect(expression._runtimeAst._type).toEqual( import__475.ExpressionNodeType.LITERAL_REGEX ); expression = new import__475.Expression("regExp()"); expect(expression.evaluate(void 0)).toEqual(/(?:)/); expect(expression._runtimeAst._type).toEqual( import__475.ExpressionNodeType.LITERAL_REGEX ); expression = new import__475.Expression("regExp(${pattern})"); expect(expression.evaluate(feature)).toEqual(/[abc]/); expect(expression._runtimeAst._type).toEqual(import__475.ExpressionNodeType.REGEX); }); it("constructs regex with flags", function() { let expression = new import__475.Expression('regExp("a", "i")'); expect(expression.evaluate(void 0)).toEqual(/a/i); expect(expression._runtimeAst._type).toEqual( import__475.ExpressionNodeType.LITERAL_REGEX ); expression = new import__475.Expression('regExp("a", "m" + "g")'); expect(expression.evaluate(void 0)).toEqual(/a/gm); expect(expression._runtimeAst._type).toEqual(import__475.ExpressionNodeType.REGEX); }); it("does not throw SyntaxError if regex constructor has invalid pattern", function() { const expression = new import__475.Expression('regExp("(?<=\\s)" + ".")'); expect(function() { expression.evaluate(void 0); }).not.toThrowError(SyntaxError); expect(function() { return new import__475.Expression('regExp("(?<=\\s)")'); }).not.toThrowError(SyntaxError); }); it("throws if regex constructor has invalid flags", function() { const expression = new import__475.Expression('regExp("a" + "b", "q")'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression('regExp("a", "q")'); }).toThrowError(import__475.RuntimeError); }); it("evaluates regex test function", function() { const feature = new MockFeature(); feature.addProperty("property", "abc"); let expression = new import__475.Expression('regExp("a").test("abc")'); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression('regExp("a").test("bcd")'); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression( 'regExp("quick\\s(brown).+?(jumps)", "ig").test("The Quick Brown Fox Jumps Over The Lazy Dog")' ); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression('regExp("a").test()'); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("regExp(${property}).test(${property})"); expect(expression.evaluate(feature)).toEqual(true); }); it("throws if regex test function has invalid arguments", function() { let expression = new import__475.Expression('regExp("1").test(1)'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression('regExp("a").test(regExp("b"))'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates regex exec function", function() { const feature = new MockFeature(); feature.addProperty("property", "abc"); feature.addProperty("Name", "Building 1"); let expression = new import__475.Expression('regExp("a(.)", "i").exec("Abc")'); expect(expression.evaluate(void 0)).toEqual("b"); expression = new import__475.Expression('regExp("a(.)").exec("qbc")'); expect(expression.evaluate(void 0)).toEqual(null); expression = new import__475.Expression('regExp("a(.)").exec()'); expect(expression.evaluate(void 0)).toEqual(null); expression = new import__475.Expression( 'regExp("quick\\s(b.*n).+?(jumps)", "ig").exec("The Quick Brown Fox Jumps Over The Lazy Dog")' ); expect(expression.evaluate(void 0)).toEqual("Brown"); expression = new import__475.Expression( 'regExp("(" + ${property} + ")").exec(${property})' ); expect(expression.evaluate(feature)).toEqual("abc"); expression = new import__475.Expression('regExp("Building\\s(\\d)").exec(${Name})'); expect(expression.evaluate(feature)).toEqual("1"); }); it("throws if regex exec function has invalid arguments", function() { let expression = new import__475.Expression('regExp("1").exec(1)'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression('regExp("a").exec(regExp("b"))'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates regex match operator", function() { const feature = new MockFeature(); feature.addProperty("property", "abc"); let expression = new import__475.Expression('regExp("a") =~ "abc"'); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression('"abc" =~ regExp("a")'); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression('regExp("a") =~ "bcd"'); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression('"bcd" =~ regExp("a")'); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression( 'regExp("quick\\s(brown).+?(jumps)", "ig") =~ "The Quick Brown Fox Jumps Over The Lazy Dog"' ); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression("regExp(${property}) =~ ${property}"); expect(expression.evaluate(feature)).toEqual(true); }); it("throws if regex match operator has invalid arguments", function() { const feature = new MockFeature(); feature.addProperty("property", "abc"); let expression = new import__475.Expression('regExp("a") =~ 1'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression('1 =~ regExp("a")'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("1 =~ 1"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("evaluates regex not match operator", function() { const feature = new MockFeature(); feature.addProperty("property", "abc"); let expression = new import__475.Expression('regExp("a") !~ "abc"'); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression('"abc" !~ regExp("a")'); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression('regExp("a") !~ "bcd"'); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression('"bcd" !~ regExp("a")'); expect(expression.evaluate(void 0)).toEqual(true); expression = new import__475.Expression( 'regExp("quick\\s(brown).+?(jumps)", "ig") !~ "The Quick Brown Fox Jumps Over The Lazy Dog"' ); expect(expression.evaluate(void 0)).toEqual(false); expression = new import__475.Expression("regExp(${property}) !~ ${property}"); expect(expression.evaluate(feature)).toEqual(false); }); it("throws if regex not match operator has invalid arguments", function() { let expression = new import__475.Expression('regExp("a") !~ 1'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression('1 !~ regExp("a")'); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("1 !~ 1"); expect(function() { expression.evaluate(void 0); }).toThrowError(import__475.RuntimeError); }); it("throws if test is not called with a RegExp", function() { expect(function() { return new import__475.Expression('color("blue").test()'); }).toThrowError(import__475.RuntimeError); expect(function() { return new import__475.Expression('"blue".test()'); }).toThrowError(import__475.RuntimeError); }); it("evaluates regExp toString function", function() { const feature = new MockFeature(); feature.addProperty("property", "abc"); let expression = new import__475.Expression("regExp().toString()"); expect(expression.evaluate(void 0)).toEqual("/(?:)/"); expression = new import__475.Expression('regExp("\\d\\s\\d", "ig").toString()'); expect(expression.evaluate(void 0)).toEqual("/\\d\\s\\d/gi"); expression = new import__475.Expression("regExp(${property}).toString()"); expect(expression.evaluate(feature)).toEqual("/abc/"); }); it("throws when using toString on other type", function() { const feature = new MockFeature(); feature.addProperty("property", "abc"); const expression = new import__475.Expression("${property}.toString()"); expect(function() { return expression.evaluate(feature); }).toThrowError(import__475.RuntimeError); }); it("evaluates array expression", function() { const feature = new MockFeature(); feature.addProperty("property", "value"); feature.addProperty("array", [ import__475.Cartesian4.UNIT_X, import__475.Cartesian4.UNIT_Y, import__475.Cartesian4.UNIT_Z ]); feature.addProperty("complicatedArray", [ { subproperty: import__475.Cartesian4.UNIT_X, anotherproperty: import__475.Cartesian4.UNIT_Y }, { subproperty: import__475.Cartesian4.UNIT_Z, anotherproperty: import__475.Cartesian4.UNIT_W } ]); feature.addProperty("temperatures", { scale: "fahrenheit", values: [70, 80, 90] }); let expression = new import__475.Expression("[1, 2, 3]"); expect(expression.evaluate(void 0)).toEqual([1, 2, 3]); expression = new import__475.Expression( '[1+2, "hello", 2 < 3, color("blue"), ${property}]' ); expect(expression.evaluate(feature)).toEqual([ 3, "hello", true, import__475.Cartesian4.fromColor(import__475.Color.BLUE), "value" ]); expression = new import__475.Expression("${array[1]}"); expect(expression.evaluate(feature)).toEqual(import__475.Cartesian4.UNIT_Y); expression = new import__475.Expression("${complicatedArray[1].subproperty}"); expect(expression.evaluate(feature)).toEqual(import__475.Cartesian4.UNIT_Z); expression = new import__475.Expression('${complicatedArray[0]["anotherproperty"]}'); expect(expression.evaluate(feature)).toEqual(import__475.Cartesian4.UNIT_Y); expression = new import__475.Expression('${temperatures["scale"]}'); expect(expression.evaluate(feature)).toEqual("fahrenheit"); expression = new import__475.Expression("${temperatures.values[0]}"); expect(expression.evaluate(feature)).toEqual(70); expression = new import__475.Expression('${temperatures["values"][0]}'); expect(expression.evaluate(feature)).toEqual(70); }); it("evaluates tiles3d_tileset_time expression", function() { const feature = new MockFeature(); const expression = new import__475.Expression("${tiles3d_tileset_time}"); expect(expression.evaluate(feature)).toEqual(0); feature.content.tileset.timeSinceLoad = 1; expect(expression.evaluate(feature)).toEqual(1); expect(expression.evaluate(void 0)).toEqual(0); }); it("gets shader function", function() { const expression = new import__475.Expression("true"); const shaderFunction = expression.getShaderFunction( "getShow()", {}, {}, "bool" ); const expected = "bool getShow()\n{\n return true;\n}\n"; expect(shaderFunction).toEqual(expected); }); it("gets shader expression for variable", function() { const expression = new import__475.Expression("${property}"); const variableSubstitutionMap = { property: "a_property" }; const shaderExpression = expression.getShaderExpression( variableSubstitutionMap, {} ); const expected = "a_property"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for feature variable with bracket notation", function() { const expression = new import__475.Expression("${feature['property']}"); const variableSubstitutionMap = { property: "a_property" }; const shaderExpression = expression.getShaderExpression( variableSubstitutionMap, {} ); const expected = "a_property"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for feature variable with dot notation", function() { const expression = new import__475.Expression("${feature.property}"); const variableSubstitutionMap = { property: "a_property" }; const shaderExpression = expression.getShaderExpression( variableSubstitutionMap, {} ); const expected = "a_property"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for non-existent variable", function() { const expression = new import__475.Expression("${nonExistentProperty}"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "czm_infinity"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for unary not", function() { const expression = new import__475.Expression("!true"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "!true"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for unary negative", function() { const expression = new import__475.Expression("-5.0"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "-5.0"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for unary positive", function() { const expression = new import__475.Expression("+5.0"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "+5.0"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for converting to literal boolean", function() { const expression = new import__475.Expression("Boolean(1.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "bool(1.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for converting to literal number", function() { const expression = new import__475.Expression("Number(true)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "float(true)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for binary addition", function() { const expression = new import__475.Expression("1.0 + 2.0"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "(1.0 + 2.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for binary subtraction", function() { const expression = new import__475.Expression("1.0 - 2.0"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "(1.0 - 2.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for binary multiplication", function() { const expression = new import__475.Expression("1.0 * 2.0"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "(1.0 * 2.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for binary division", function() { const expression = new import__475.Expression("1.0 / 2.0"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "(1.0 / 2.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for binary modulus", function() { const expression = new import__475.Expression("1.0 % 2.0"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "mod(1.0, 2.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for binary equals strict", function() { const expression = new import__475.Expression("1.0 === 2.0"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "(1.0 == 2.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for binary not equals strict", function() { const expression = new import__475.Expression("1.0 !== 2.0"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "(1.0 != 2.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for binary less than", function() { const expression = new import__475.Expression("1.0 < 2.0"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "(1.0 < 2.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for binary less than or equals", function() { const expression = new import__475.Expression("1.0 <= 2.0"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "(1.0 <= 2.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for binary greater than", function() { const expression = new import__475.Expression("1.0 > 2.0"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "(1.0 > 2.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for binary greater than or equals", function() { const expression = new import__475.Expression("1.0 >= 2.0"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "(1.0 >= 2.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for logical and", function() { const expression = new import__475.Expression("true && false"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "(true && false)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for logical or", function() { const expression = new import__475.Expression("true || false"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "(true || false)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for ternary conditional", function() { const expression = new import__475.Expression("true ? 1.0 : 2.0"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "(true ? 1.0 : 2.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for array indexing", function() { const variableSubstitutionMap = { property: "property" }; let expression = new import__475.Expression("${property[0]}"); let shaderExpression = expression.getShaderExpression( variableSubstitutionMap, {} ); let expected = "property[0]"; expect(shaderExpression).toEqual(expected); expression = new import__475.Expression("${property[4 / 2]}"); shaderExpression = expression.getShaderExpression( variableSubstitutionMap, {} ); expected = "property[int((4.0 / 2.0))]"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for array", function() { let expression = new import__475.Expression("[1.0, 2.0]"); let shaderExpression = expression.getShaderExpression({}, {}); let expected = "vec2(1.0, 2.0)"; expect(shaderExpression).toEqual(expected); expression = new import__475.Expression("[1.0, 2.0, 3.0]"); shaderExpression = expression.getShaderExpression({}, {}); expected = "vec3(1.0, 2.0, 3.0)"; expect(shaderExpression).toEqual(expected); expression = new import__475.Expression("[1.0, 2.0, 3.0, 4.0]"); shaderExpression = expression.getShaderExpression({}, {}); expected = "vec4(1.0, 2.0, 3.0, 4.0)"; expect(shaderExpression).toEqual(expected); }); it("throws when getting shader expression for array of invalid length", function() { let expression = new import__475.Expression("[]"); expect(function() { return expression.getShaderExpression({}, {}); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("[1.0]"); expect(function() { return expression.getShaderExpression({}, {}); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression("[1.0, 2.0, 3.0, 4.0, 5.0]"); expect(function() { return expression.getShaderExpression({}, {}); }).toThrowError(import__475.RuntimeError); }); it("gets shader expression for boolean", function() { const expression = new import__475.Expression("true || false"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "(true || false)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for integer", function() { const expression = new import__475.Expression("1"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "1.0"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for float", function() { const expression = new import__475.Expression("1.02"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "1.02"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for color", function() { const variableSubstitutionMap = { property: "property" }; let shaderState = { translucent: false }; let expression = new import__475.Expression("color()"); let shaderExpression = expression.getShaderExpression( variableSubstitutionMap, shaderState ); let expected = "vec4(1.0)"; expect(shaderExpression).toEqual(expected); expect(shaderState.translucent).toBe(false); shaderState = { translucent: false }; expression = new import__475.Expression('color("red")'); shaderExpression = expression.getShaderExpression( variableSubstitutionMap, shaderState ); expected = "vec4(vec3(1.0, 0.0, 0.0), 1.0)"; expect(shaderExpression).toEqual(expected); expect(shaderState.translucent).toBe(false); shaderState = { translucent: false }; expression = new import__475.Expression('color("#FFF")'); shaderExpression = expression.getShaderExpression( variableSubstitutionMap, shaderState ); expected = "vec4(vec3(1.0, 1.0, 1.0), 1.0)"; expect(shaderExpression).toEqual(expected); expect(shaderState.translucent).toBe(false); shaderState = { translucent: false }; expression = new import__475.Expression('color("#FF0000")'); shaderExpression = expression.getShaderExpression( variableSubstitutionMap, shaderState ); expected = "vec4(vec3(1.0, 0.0, 0.0), 1.0)"; expect(shaderExpression).toEqual(expected); expect(shaderState.translucent).toBe(false); shaderState = { translucent: false }; expression = new import__475.Expression('color("rgb(255, 0, 0)")'); shaderExpression = expression.getShaderExpression( variableSubstitutionMap, shaderState ); expected = "vec4(vec3(1.0, 0.0, 0.0), 1.0)"; expect(shaderExpression).toEqual(expected); expect(shaderState.translucent).toBe(false); shaderState = { translucent: false }; expression = new import__475.Expression('color("red", 0.5)'); shaderExpression = expression.getShaderExpression( variableSubstitutionMap, shaderState ); expected = "vec4(vec3(1.0, 0.0, 0.0), 0.5)"; expect(shaderExpression).toEqual(expected); expect(shaderState.translucent).toBe(true); shaderState = { translucent: false }; expression = new import__475.Expression("rgb(255, 0, 0)"); shaderExpression = expression.getShaderExpression( variableSubstitutionMap, shaderState ); expected = "vec4(1.0, 0.0, 0.0, 1.0)"; expect(shaderExpression).toEqual(expected); expect(shaderState.translucent).toBe(false); shaderState = { translucent: false }; expression = new import__475.Expression("rgb(255, ${property}, 0)"); shaderExpression = expression.getShaderExpression( variableSubstitutionMap, shaderState ); expected = "vec4(255.0 / 255.0, property / 255.0, 0.0 / 255.0, 1.0)"; expect(shaderExpression).toEqual(expected); expect(shaderState.translucent).toBe(false); shaderState = { translucent: false }; expression = new import__475.Expression("rgba(255, 0, 0, 0.5)"); shaderExpression = expression.getShaderExpression( variableSubstitutionMap, shaderState ); expected = "vec4(1.0, 0.0, 0.0, 0.5)"; expect(shaderExpression).toEqual(expected); expect(shaderState.translucent).toBe(true); shaderState = { translucent: false }; expression = new import__475.Expression("rgba(255, ${property}, 0, 0.5)"); shaderExpression = expression.getShaderExpression( variableSubstitutionMap, shaderState ); expected = "vec4(255.0 / 255.0, property / 255.0, 0.0 / 255.0, 0.5)"; expect(shaderExpression).toEqual(expected); expect(shaderState.translucent).toBe(true); shaderState = { translucent: false }; expression = new import__475.Expression("hsl(1.0, 0.5, 0.5)"); shaderExpression = expression.getShaderExpression( variableSubstitutionMap, shaderState ); expected = "vec4(0.75, 0.25, 0.25, 1.0)"; expect(shaderExpression).toEqual(expected); expect(shaderState.translucent).toBe(false); shaderState = { translucent: false }; expression = new import__475.Expression("hsla(1.0, 0.5, 0.5, 0.5)"); shaderExpression = expression.getShaderExpression( variableSubstitutionMap, shaderState ); expected = "vec4(0.75, 0.25, 0.25, 0.5)"; expect(shaderExpression).toEqual(expected); expect(shaderState.translucent).toBe(true); shaderState = { translucent: false }; expression = new import__475.Expression("hsl(1.0, ${property}, 0.5)"); shaderExpression = expression.getShaderExpression( variableSubstitutionMap, shaderState ); expected = "vec4(czm_HSLToRGB(vec3(1.0, property, 0.5)), 1.0)"; expect(shaderExpression).toEqual(expected); expect(shaderState.translucent).toBe(false); shaderState = { translucent: false }; expression = new import__475.Expression("hsla(1.0, ${property}, 0.5, 0.5)"); shaderExpression = expression.getShaderExpression( variableSubstitutionMap, shaderState ); expected = "vec4(czm_HSLToRGB(vec3(1.0, property, 0.5)), 0.5)"; expect(shaderExpression).toEqual(expected); expect(shaderState.translucent).toBe(true); }); it("gets shader expression for color components", function() { let expression = new import__475.Expression( "color().r + color().g + color().b + color().a" ); let shaderExpression = expression.getShaderExpression({}, {}); const expected = "(((vec4(1.0)[0] + vec4(1.0)[1]) + vec4(1.0)[2]) + vec4(1.0)[3])"; expect(shaderExpression).toEqual(expected); expression = new import__475.Expression( "color().x + color().y + color().z + color().w" ); shaderExpression = expression.getShaderExpression({}, {}); expect(shaderExpression).toEqual(expected); expression = new import__475.Expression( "color()[0] + color()[1] + color()[2] + color()[3]" ); shaderExpression = expression.getShaderExpression({}, {}); expect(shaderExpression).toEqual(expected); }); it("gets shader expression for vector", function() { const variableSubstitutionMap = { property: "property" }; let expression = new import__475.Expression("vec4(1, 2, 3, 4)"); let shaderExpression = expression.getShaderExpression( variableSubstitutionMap, {} ); expect(shaderExpression).toEqual("vec4(1.0, 2.0, 3.0, 4.0)"); expression = new import__475.Expression("vec4(1) + vec4(2)"); shaderExpression = expression.getShaderExpression( variableSubstitutionMap, {} ); expect(shaderExpression).toEqual("(vec4(1.0) + vec4(2.0))"); expression = new import__475.Expression("vec4(1, ${property}, vec2(1, 2).x, 0)"); shaderExpression = expression.getShaderExpression( variableSubstitutionMap, {} ); expect(shaderExpression).toEqual( "vec4(1.0, property, vec2(1.0, 2.0)[0], 0.0)" ); expression = new import__475.Expression("vec4(vec3(2), 1.0)"); shaderExpression = expression.getShaderExpression( variableSubstitutionMap, {} ); expect(shaderExpression).toEqual("vec4(vec3(2.0), 1.0)"); }); it("gets shader expression for vector components", function() { let expression = new import__475.Expression( "vec4(1).x + vec4(1).y + vec4(1).z + vec4(1).w" ); let shaderExpression = expression.getShaderExpression({}, {}); const expected = "(((vec4(1.0)[0] + vec4(1.0)[1]) + vec4(1.0)[2]) + vec4(1.0)[3])"; expect(shaderExpression).toEqual(expected); expression = new import__475.Expression( "vec4(1)[0] + vec4(1)[1] + vec4(1)[2] + vec4(1)[3]" ); shaderExpression = expression.getShaderExpression({}, {}); expect(shaderExpression).toEqual(expected); }); it("gets shader expression for tiles3d_tileset_time", function() { const expression = new import__475.Expression("${tiles3d_tileset_time}"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "tiles3d_tileset_time"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for abs", function() { const expression = new import__475.Expression("abs(-1.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "abs(-1.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for cos", function() { const expression = new import__475.Expression("cos(0.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "cos(0.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for sin", function() { const expression = new import__475.Expression("sin(0.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "sin(0.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for tan", function() { const expression = new import__475.Expression("tan(0.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "tan(0.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for acos", function() { const expression = new import__475.Expression("acos(0.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "acos(0.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for asin", function() { const expression = new import__475.Expression("asin(0.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "asin(0.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for atan", function() { const expression = new import__475.Expression("atan(0.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "atan(0.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for sqrt", function() { const expression = new import__475.Expression("sqrt(1.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "sqrt(1.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for sign", function() { const expression = new import__475.Expression("sign(1.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "sign(1.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for floor", function() { const expression = new import__475.Expression("floor(1.5)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "floor(1.5)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for ceil", function() { const expression = new import__475.Expression("ceil(1.2)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "ceil(1.2)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for round", function() { const expression = new import__475.Expression("round(1.2)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "floor(1.2 + 0.5)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for exp", function() { const expression = new import__475.Expression("exp(1.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "exp(1.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for exp2", function() { const expression = new import__475.Expression("exp2(1.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "exp2(1.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for log", function() { const expression = new import__475.Expression("log(1.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "log(1.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for log2", function() { const expression = new import__475.Expression("log2(1.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "log2(1.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for fract", function() { const expression = new import__475.Expression("fract(1.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "fract(1.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for clamp", function() { const expression = new import__475.Expression("clamp(50.0, 0.0, 100.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "clamp(50.0, 0.0, 100.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for mix", function() { const expression = new import__475.Expression("mix(0.0, 2.0, 0.5)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "mix(0.0, 2.0, 0.5)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for atan2", function() { const expression = new import__475.Expression("atan2(0.0,1.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "atan(0.0, 1.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for pow", function() { const expression = new import__475.Expression("pow(2.0,2.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "pow(2.0, 2.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for min", function() { const expression = new import__475.Expression("min(3.0,5.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "min(3.0, 5.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for max", function() { const expression = new import__475.Expression("max(3.0,5.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "max(3.0, 5.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for length", function() { const expression = new import__475.Expression("length(3.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "length(3.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for normalize", function() { const expression = new import__475.Expression("normalize(3.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "normalize(3.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for distance", function() { const expression = new import__475.Expression("distance(0.0, 1.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "distance(0.0, 1.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for dot", function() { const expression = new import__475.Expression("dot(1.0, 2.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "dot(1.0, 2.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for cross", function() { const expression = new import__475.Expression( "cross(vec3(1.0, 1.0, 1.0), vec3(2.0, 2.0, 2.0))" ); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "cross(vec3(1.0, 1.0, 1.0), vec3(2.0, 2.0, 2.0))"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for isNaN", function() { const expression = new import__475.Expression("isNaN(1.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "(1.0 != 1.0)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for isFinite", function() { const expression = new import__475.Expression("isFinite(1.0)"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "(abs(1.0) < czm_infinity)"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for null", function() { const expression = new import__475.Expression("null"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "czm_infinity"; expect(shaderExpression).toEqual(expected); }); it("gets shader expression for undefined", function() { const expression = new import__475.Expression("undefined"); const shaderExpression = expression.getShaderExpression({}, {}); const expected = "czm_infinity"; expect(shaderExpression).toEqual(expected); }); it("gets variables", function() { const expression = new import__475.Expression( '${feature["w"]} + ${feature.x} + ${y} + ${y} + "${z}"' ); const variables = expression.getVariables(); expect(variables.sort()).toEqual(["w", "x", "y", "z"]); }); it("throws when getting shader expression for regex", function() { let expression = new import__475.Expression('regExp("a").test("abc")'); expect(function() { return expression.getShaderExpression({}, {}); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression('regExp("a(.)", "i").exec("Abc")'); expect(function() { return expression.getShaderExpression({}, {}); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression('regExp("a") =~ "abc"'); expect(function() { return expression.getShaderExpression({}, {}); }).toThrowError(import__475.RuntimeError); expression = new import__475.Expression('regExp("a") !~ "abc"'); expect(function() { return expression.getShaderExpression({}, {}); }).toThrowError(import__475.RuntimeError); }); it("throws when getting shader expression for member expression with dot", function() { const expression = new import__475.Expression("${property.name}"); expect(function() { return expression.getShaderExpression({}, {}); }).toThrowError(import__475.RuntimeError); }); it("throws when getting shader expression for string member expression with brackets", function() { const expression = new import__475.Expression('${property["name"]}'); expect(function() { return expression.getShaderExpression({}, {}); }).toThrowError(import__475.RuntimeError); }); it("throws when getting shader expression for String", function() { const expression = new import__475.Expression("String(1.0)"); expect(function() { return expression.getShaderExpression({}, {}); }).toThrowError(import__475.RuntimeError); }); it("throws when getting shader expression for toString", function() { const expression = new import__475.Expression('color("red").toString()'); expect(function() { return expression.getShaderExpression({}, {}); }).toThrowError(import__475.RuntimeError); }); it("throws when getting shader expression for literal string", function() { const expression = new import__475.Expression('"name"'); expect(function() { return expression.getShaderExpression({}, {}); }).toThrowError(import__475.RuntimeError); }); it("throws when getting shader expression for variable in string", function() { const expression = new import__475.Expression('"${property}"'); expect(function() { return expression.getShaderExpression({}, {}); }).toThrowError(import__475.RuntimeError); }); it("throws when getting shader expression for isExactClass", function() { const expression = new import__475.Expression('isExactClass("door")'); expect(function() { return expression.getShaderExpression({}, {}); }).toThrowError(import__475.RuntimeError); }); it("throws when getting shader expression for isClass", function() { const expression = new import__475.Expression('isClass("door")'); expect(function() { return expression.getShaderExpression({}, {}); }).toThrowError(import__475.RuntimeError); }); it("throws when getting shader expression for getExactClassName", function() { const expression = new import__475.Expression("getExactClassName()"); expect(function() { return expression.getShaderExpression({}, {}); }).toThrowError(import__475.RuntimeError); }); }); // packages/engine/Specs/Scene/FrameRateMonitorSpec.js var import__477 = __toESM(require_Cesium(), 1); describe( "Scene/FrameRateMonitor", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); let monitor; afterEach(function() { if ((0, import__477.defined)(monitor)) { monitor.destroy(); monitor = void 0; } }); function spinWait(milliseconds) { const endTime = (0, import__477.getTimestamp)() + milliseconds; while ((0, import__477.getTimestamp)() < endTime) { } } it("throws when constructed without a scene", function() { expect(function() { monitor = new import__477.FrameRateMonitor(); }).toThrowDeveloperError(); expect(function() { monitor = new import__477.FrameRateMonitor({}); }).toThrowDeveloperError(); }); it("can be constructed with just a scene", function() { monitor = new import__477.FrameRateMonitor({ scene: scene2 }); expect(monitor.samplingWindow).toBe(5); expect(monitor.quietPeriod).toBe(2); expect(monitor.warmupPeriod).toBe(5); expect(monitor.minimumFrameRateDuringWarmup).toBe(4); expect(monitor.minimumFrameRateAfterWarmup).toBe(8); expect(monitor.scene).toBe(scene2); expect(monitor.lowFrameRate.numberOfListeners).toBe(0); expect(monitor.nominalFrameRate.numberOfListeners).toBe(0); }); it("honors parameters to the constructor", function() { monitor = new import__477.FrameRateMonitor({ scene: scene2, samplingWindow: 3, quietPeriod: 1, warmupPeriod: 6, minimumFrameRateDuringWarmup: 1, minimumFrameRateAfterWarmup: 2 }); expect(monitor.samplingWindow).toBe(3); expect(monitor.quietPeriod).toBe(1); expect(monitor.warmupPeriod).toBe(6); expect(monitor.minimumFrameRateDuringWarmup).toBe(1); expect(monitor.minimumFrameRateAfterWarmup).toBe(2); expect(monitor.scene).toBe(scene2); }); it("raises the lowFrameRate event on low frame rate", function() { monitor = new import__477.FrameRateMonitor({ scene: scene2, quietPeriod: 1e-3, warmupPeriod: 1e-3, samplingWindow: 1e-3, minimumFrameRateDuringWarmup: 1e3, minimumFrameRateAfterWarmup: 1e3 }); const spyListener = jasmine.createSpy("listener"); monitor.lowFrameRate.addEventListener(spyListener); scene2.render(); spinWait(2); scene2.render(); spinWait(2); scene2.render(); expect(monitor.lastFramesPerSecond).toBeLessThan(1e3); expect(spyListener).toHaveBeenCalled(); }); it("does not monitor frame rate while paused", function() { monitor = new import__477.FrameRateMonitor({ scene: scene2, quietPeriod: 1e-3, warmupPeriod: 1e-3, samplingWindow: 1e-3, minimumFrameRateDuringWarmup: 1e3, minimumFrameRateAfterWarmup: 1e3 }); const spyListener = jasmine.createSpy("listener"); monitor.lowFrameRate.addEventListener(spyListener); scene2.render(); spinWait(2); scene2.render(); monitor.pause(); spinWait(2); scene2.render(); monitor.unpause(); scene2.render(); expect(spyListener).not.toHaveBeenCalled(); }); it("pausing multiple times requires unpausing multiple times", function() { monitor = new import__477.FrameRateMonitor({ scene: scene2, quietPeriod: 1e-3, warmupPeriod: 1e-3, samplingWindow: 1e-3, minimumFrameRateDuringWarmup: 1e3, minimumFrameRateAfterWarmup: 1e3 }); const spyListener = jasmine.createSpy("listener"); monitor.lowFrameRate.addEventListener(spyListener); monitor.pause(); monitor.pause(); monitor.unpause(); scene2.render(); spinWait(2); scene2.render(); spinWait(2); scene2.render(); monitor.unpause(); scene2.render(); expect(spyListener).not.toHaveBeenCalled(); }); it("does not report a low frame rate during the quiet period", function() { monitor = new import__477.FrameRateMonitor({ scene: scene2, quietPeriod: 1, warmupPeriod: 1e-3, samplingWindow: 1e-3, minimumFrameRateDuringWarmup: 1e3, minimumFrameRateAfterWarmup: 1e3 }); const spyListener = jasmine.createSpy("listener"); monitor.lowFrameRate.addEventListener(spyListener); scene2.render(); spinWait(2); scene2.render(); expect(spyListener).not.toHaveBeenCalled(); }); it("the nominalFrameRate event is raised after the warmup period if the frame rate returns to nominal", function() { monitor = new import__477.FrameRateMonitor({ scene: scene2, quietPeriod: 1e-3, warmupPeriod: 1e-3, samplingWindow: 1e-3, minimumFrameRateDuringWarmup: 10, minimumFrameRateAfterWarmup: 10 }); const lowListener = jasmine.createSpy("lowFrameRate"); monitor.lowFrameRate.addEventListener(lowListener); const nominalListener = jasmine.createSpy("nominalFrameRate"); monitor.nominalFrameRate.addEventListener(nominalListener); scene2.render(); spinWait(2); scene2.render(); spinWait(120); scene2.render(); expect(monitor.lastFramesPerSecond).toBeLessThan(10); expect(lowListener).toHaveBeenCalled(); const endTime = (0, import__477.getTimestamp)() + 50; while ((0, import__477.getTimestamp)() < endTime) { scene2.render(); } expect(monitor.lastFramesPerSecond).toBeGreaterThanOrEqual(10); expect(nominalListener).toHaveBeenCalled(); }); }, "WebGL" ); // packages/engine/Specs/Scene/FrustumCommandsSpec.js var import__478 = __toESM(require_Cesium(), 1); describe("Scene/FrustumCommands", function() { it("constructs without arguments", function() { const frustum = new import__478.FrustumCommands(); expect(frustum.near).toEqual(0); expect(frustum.far).toEqual(0); expect(frustum.commands).toBeDefined(); expect(frustum.commands.length).toEqual(import__478.Pass.NUMBER_OF_PASSES); expect(frustum.indices).toBeDefined(); expect(frustum.indices.length).toEqual(import__478.Pass.NUMBER_OF_PASSES); }); it("constructs with arguments", function() { const near = 1; const far = 2; const frustum = new import__478.FrustumCommands(near, far); expect(frustum.near).toEqual(near); expect(frustum.far).toEqual(far); expect(frustum.commands).toBeDefined(); expect(frustum.commands.length).toEqual(import__478.Pass.NUMBER_OF_PASSES); expect(frustum.indices).toBeDefined(); expect(frustum.indices.length).toEqual(import__478.Pass.NUMBER_OF_PASSES); }); }); // packages/engine/Specs/Scene/Geometry3DTileContentSpec.js var import__479 = __toESM(require_Cesium(), 1); describe( "Scene/Geometry3DTileContent", function() { const tilesetRectangle = import__479.Rectangle.fromDegrees(-0.01, -0.01, 0.01, 0.01); const geometryAll = "./Data/Cesium3DTiles/Geometry/GeometryTileAll/tileset.json"; const geometryAllBatchedChildren = "./Data/Cesium3DTiles/Geometry/GeometryTileAllBatchedChildren/tileset.json"; const geometryAllBatchedChildrenWithBatchTable = "./Data/Cesium3DTiles/Geometry/GeometryTileAllBatchedChildrenWithBatchTable/tileset.json"; const geometryAllWithBatchTable = "./Data/Cesium3DTiles/Geometry/GeometryTileAllWithBatchTable/tileset.json"; const geometryAllWithBatchIds = "./Data/Cesium3DTiles/Geometry/GeometryTileAllWithBatchIds/tileset.json"; const geometryBoxes = "./Data/Cesium3DTiles/Geometry/GeometryTileBoxes/tileset.json"; const geometryBoxesBatchedChildren = "./Data/Cesium3DTiles/Geometry/GeometryTileBoxesBatchedChildren/tileset.json"; const geometryBoxesBatchedChildrenWithBatchTable = "./Data/Cesium3DTiles/Geometry/GeometryTileBoxesBatchedChildrenWithBatchTable/tileset.json"; const geometryBoxesWithBatchTable = "./Data/Cesium3DTiles/Geometry/GeometryTileBoxesWithBatchTable/tileset.json"; const geometryBoxesWithBatchIds = "./Data/Cesium3DTiles/Geometry/GeometryTileBoxesWithBatchIds/tileset.json"; const geometryCylinders = "./Data/Cesium3DTiles/Geometry/GeometryTileCylinders/tileset.json"; const geometryCylindersBatchedChildren = "./Data/Cesium3DTiles/Geometry/GeometryTileCylindersBatchedChildren/tileset.json"; const geometryCylindersBatchedChildrenWithBatchTable = "./Data/Cesium3DTiles/Geometry/GeometryTileCylindersBatchedChildrenWithBatchTable/tileset.json"; const geometryCylindersWithBatchTable = "./Data/Cesium3DTiles/Geometry/GeometryTileCylindersWithBatchTable/tileset.json"; const geometryCylindersWithBatchIds = "./Data/Cesium3DTiles/Geometry/GeometryTileCylindersWithBatchIds/tileset.json"; const geometryEllipsoids = "./Data/Cesium3DTiles/Geometry/GeometryTileEllipsoids/tileset.json"; const geometryEllipsoidsBatchedChildren = "./Data/Cesium3DTiles/Geometry/GeometryTileEllipsoidsBatchedChildren/tileset.json"; const geometryEllipsoidsBatchedChildrenWithBatchTable = "./Data/Cesium3DTiles/Geometry/GeometryTileEllipsoidsBatchedChildrenWithBatchTable/tileset.json"; const geometryEllipsoidsWithBatchTable = "./Data/Cesium3DTiles/Geometry/GeometryTileEllipsoidsWithBatchTable/tileset.json"; const geometryEllipsoidsWithBatchIds = "./Data/Cesium3DTiles/Geometry/GeometryTileEllipsoidsWithBatchIds/tileset.json"; const geometrySpheres = "./Data/Cesium3DTiles/Geometry/GeometryTileSpheres/tileset.json"; const geometrySpheresBatchedChildren = "./Data/Cesium3DTiles/Geometry/GeometryTileSpheresBatchedChildren/tileset.json"; const geometrySpheresBatchedChildrenWithBatchTable = "./Data/Cesium3DTiles/Geometry/GeometryTileSpheresBatchedChildrenWithBatchTable/tileset.json"; const geometrySpheresWithBatchTable = "./Data/Cesium3DTiles/Geometry/GeometryTileSpheresWithBatchTable/tileset.json"; const geometrySpheresWithBatchIds = "./Data/Cesium3DTiles/Geometry/GeometryTileSpheresWithBatchIds/tileset.json"; let scene2; let rectangle; let tileset; let globePrimitive; let tilesetPrimitive; let reusableGlobePrimitive; let reusableTilesetPrimitive; let depthColor; const ellipsoid = import__479.Ellipsoid.WGS84; function createPrimitive(rectangle2, pass) { let renderState; if (pass === import__479.Pass.CESIUM_3D_TILE) { renderState = import__479.RenderState.fromCache({ stencilTest: import__479.StencilConstants.setCesium3DTileBit(), stencilMask: import__479.StencilConstants.CESIUM_3D_TILE_MASK, depthTest: { enabled: true } }); } const depthColorAttribute = import__479.ColorGeometryInstanceAttribute.fromColor( new import__479.Color(1, 0, 0, 1) ); depthColor = depthColorAttribute.value; return new import__479.Primitive({ geometryInstances: new import__479.GeometryInstance({ geometry: new import__479.RectangleGeometry({ ellipsoid: import__479.Ellipsoid.WGS84, rectangle: rectangle2 }), id: "depth rectangle", attributes: { color: depthColorAttribute } }), appearance: new import__479.PerInstanceColorAppearance({ translucent: false, flat: true, renderState }), asynchronous: false }); } function MockPrimitive(primitive, pass) { this._primitive = primitive; this._pass = pass; this.show = true; } MockPrimitive.prototype.update = function(frameState2) { if (!this.show) { return; } const commandList = frameState2.commandList; const startLength = commandList.length; this._primitive.update(frameState2); for (let i = startLength; i < commandList.length; ++i) { const command = commandList[i]; command.pass = this._pass; } }; MockPrimitive.prototype.isDestroyed = function() { return false; }; MockPrimitive.prototype.destroy = function() { return (0, import__479.destroyObject)(this); }; beforeAll(function() { scene2 = createScene_default(); rectangle = import__479.Rectangle.fromDegrees(-40, -40, 40, 40); reusableGlobePrimitive = createPrimitive(rectangle, import__479.Pass.GLOBE); reusableTilesetPrimitive = createPrimitive( rectangle, import__479.Pass.CESIUM_3D_TILE ); }); afterAll(function() { reusableGlobePrimitive.destroy(); reusableTilesetPrimitive.destroy(); scene2.destroyForSpecs(); }); beforeEach(function() { globePrimitive = new MockPrimitive(reusableGlobePrimitive, import__479.Pass.GLOBE); tilesetPrimitive = new MockPrimitive( reusableTilesetPrimitive, import__479.Pass.CESIUM_3D_TILE ); scene2.camera.lookAt( ellipsoid.cartographicToCartesian(import__479.Rectangle.center(tilesetRectangle)), new import__479.Cartesian3(0, 0, 0.01) ); }); afterEach(function() { scene2.primitives.removeAll(); globePrimitive = globePrimitive && !globePrimitive.isDestroyed() && globePrimitive.destroy(); tilesetPrimitive = tilesetPrimitive && !tilesetPrimitive.isDestroyed() && tilesetPrimitive.destroy(); tileset = tileset && !tileset.isDestroyed() && tileset.destroy(); }); function expectPick(scene3) { expect(scene3).toPickAndCall(function(result) { expect(result).toBeDefined(); result.color = import__479.Color.clone(import__479.Color.YELLOW, result.color); expect(scene3).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toBeGreaterThan(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); result.show = false; expect(scene3).toRender([255, 0, 0, 255]); result.show = true; expect(scene3).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toBeGreaterThan(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); }); } function verifyPick(scene3) { const center = import__479.Rectangle.center(tilesetRectangle); const ulRect = new import__479.Rectangle( tilesetRectangle.west, center.latitude, center.longitude, tilesetRectangle.north ); const urRect = new import__479.Rectangle( center.longitude, center.longitude, tilesetRectangle.east, tilesetRectangle.north ); const llRect = new import__479.Rectangle( tilesetRectangle.west, tilesetRectangle.south, center.longitude, center.latitude ); const lrRect = new import__479.Rectangle( center.longitude, tilesetRectangle.south, tilesetRectangle.east, center.latitude ); scene3.camera.lookAt( ellipsoid.cartographicToCartesian(import__479.Rectangle.center(ulRect)), new import__479.Cartesian3(0, 0, 5) ); expectPick(scene3); scene3.camera.lookAt( ellipsoid.cartographicToCartesian(import__479.Rectangle.center(urRect)), new import__479.Cartesian3(0, 0, 5) ); expectPick(scene3); scene3.camera.lookAt( ellipsoid.cartographicToCartesian(import__479.Rectangle.center(llRect)), new import__479.Cartesian3(0, 0, 5) ); expectPick(scene3); scene3.camera.lookAt( ellipsoid.cartographicToCartesian(import__479.Rectangle.center(lrRect)), new import__479.Cartesian3(0, 0, 5) ); expectPick(scene3); } function expectRender(scene3, color) { const center = import__479.Rectangle.center(tilesetRectangle); const ulRect = new import__479.Rectangle( tilesetRectangle.west, center.latitude, center.longitude, tilesetRectangle.north ); const urRect = new import__479.Rectangle( center.longitude, center.longitude, tilesetRectangle.east, tilesetRectangle.north ); const llRect = new import__479.Rectangle( tilesetRectangle.west, tilesetRectangle.south, center.longitude, center.latitude ); const lrRect = new import__479.Rectangle( center.longitude, tilesetRectangle.south, tilesetRectangle.east, center.latitude ); scene3.camera.lookAt( ellipsoid.cartographicToCartesian(import__479.Rectangle.center(ulRect)), new import__479.Cartesian3(0, 0, 5) ); expect(scene3).toRender(color); scene3.camera.lookAt( ellipsoid.cartographicToCartesian(import__479.Rectangle.center(urRect)), new import__479.Cartesian3(0, 0, 5) ); expect(scene3).toRender(color); scene3.camera.lookAt( ellipsoid.cartographicToCartesian(import__479.Rectangle.center(llRect)), new import__479.Cartesian3(0, 0, 5) ); expect(scene3).toRender(color); scene3.camera.lookAt( ellipsoid.cartographicToCartesian(import__479.Rectangle.center(lrRect)), new import__479.Cartesian3(0, 0, 5) ); expect(scene3).toRender(color); } function verifyRender(tileset2, scene3) { tileset2.style = void 0; expectRender(scene3, [255, 255, 255, 255]); tileset2.style = new import__479.Cesium3DTileStyle({ show: "false" }); expectRender(scene3, [255, 0, 0, 255]); tileset2.style = new import__479.Cesium3DTileStyle({ show: "true" }); expectRender(scene3, [255, 255, 255, 255]); tileset2.style = new import__479.Cesium3DTileStyle({ color: "rgba(0, 0, 255, 1.0)" }); expectRender(scene3, [0, 0, 255, 255]); return tileset2; } it("renders on 3D Tiles", function() { scene2.primitives.add(globePrimitive); scene2.primitives.add(tilesetPrimitive); return Cesium3DTilesTester_default.loadTileset(scene2, geometryBoxes, { classificationType: import__479.ClassificationType.CESIUM_3D_TILE }).then(function(tileset2) { globePrimitive.show = false; tilesetPrimitive.show = true; return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); globePrimitive.show = true; tilesetPrimitive.show = false; expectRender(scene2, depthColor); globePrimitive.show = true; tilesetPrimitive.show = true; }); }); it("renders on globe", function() { scene2.primitives.add(globePrimitive); scene2.primitives.add(tilesetPrimitive); return Cesium3DTilesTester_default.loadTileset(scene2, geometryBoxes, { classificationType: import__479.ClassificationType.TERRAIN }).then(function(tileset2) { globePrimitive.show = false; tilesetPrimitive.show = true; expectRender(scene2, depthColor); globePrimitive.show = true; tilesetPrimitive.show = false; return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); globePrimitive.show = true; tilesetPrimitive.show = true; }); }); it("renders on 3D Tiles and globe", function() { scene2.primitives.add(globePrimitive); scene2.primitives.add(tilesetPrimitive); return Cesium3DTilesTester_default.loadTileset(scene2, geometryBoxes, { classificationType: import__479.ClassificationType.BOTH }).then(function(tileset2) { globePrimitive.show = false; tilesetPrimitive.show = true; return verifyRender(tileset2, scene2); }).then(function(tileset2) { verifyPick(scene2); globePrimitive.show = true; tilesetPrimitive.show = false; return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); globePrimitive.show = true; tilesetPrimitive.show = true; }); }); it("renders boxes", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset(scene2, geometryBoxes).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders batched boxes", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, geometryBoxesBatchedChildren ).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders boxes with a batch table", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset(scene2, geometryBoxesWithBatchTable).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders batched boxes with a batch table", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, geometryBoxesBatchedChildrenWithBatchTable ).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders boxes with batch ids", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset(scene2, geometryBoxesWithBatchIds).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders cylinders", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset(scene2, geometryCylinders).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders batched cylinders", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, geometryCylindersBatchedChildren ).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders cylinders with a batch table", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, geometryCylindersWithBatchTable ).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders batched cylinders with a batch table", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, geometryCylindersBatchedChildrenWithBatchTable ).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders cylinders with batch ids", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, geometryCylindersWithBatchIds ).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders ellipsoids", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset(scene2, geometryEllipsoids).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders batched ellipsoids", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, geometryEllipsoidsBatchedChildren ).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders ellipsoids with a batch table", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, geometryEllipsoidsWithBatchTable ).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders batched ellipsoids with a batch table", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, geometryEllipsoidsBatchedChildrenWithBatchTable ).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders ellipsoids with batch ids", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, geometryEllipsoidsWithBatchIds ).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders spheres", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset(scene2, geometrySpheres).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders batched spheres", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, geometrySpheresBatchedChildren ).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders spheres with a batch table", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, geometrySpheresWithBatchTable ).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders batched spheres with a batch table", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, geometrySpheresBatchedChildrenWithBatchTable ).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders spheres with batch ids", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset(scene2, geometrySpheresWithBatchIds).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders all geometries", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset(scene2, geometryAll).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders batched all geometries", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset(scene2, geometryAllBatchedChildren).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders all geometries with a batch table", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset(scene2, geometryAllWithBatchTable).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders batched all geometries with a batch table", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, geometryAllBatchedChildrenWithBatchTable ).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders all geometries with batch ids", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset(scene2, geometryAllWithBatchIds).then(function(tileset2) { return verifyRender(tileset2, scene2); }).then(function() { verifyPick(scene2); }); }); it("renders all geometries with debug color", function() { scene2.primitives.add(globePrimitive); return Cesium3DTilesTester_default.loadTileset(scene2, geometryAllWithBatchTable, { debugColorizeTiles: true }).then(function(tileset2) { const center = import__479.Rectangle.center(tilesetRectangle); const ulRect = new import__479.Rectangle( tilesetRectangle.west, center.latitude, center.longitude, tilesetRectangle.north ); const urRect = new import__479.Rectangle( center.longitude, center.longitude, tilesetRectangle.east, tilesetRectangle.north ); const llRect = new import__479.Rectangle( tilesetRectangle.west, tilesetRectangle.south, center.longitude, center.latitude ); const lrRect = new import__479.Rectangle( center.longitude, tilesetRectangle.south, tilesetRectangle.east, center.latitude ); scene2.camera.lookAt( ellipsoid.cartographicToCartesian(import__479.Rectangle.center(ulRect)), new import__479.Cartesian3(0, 0, 5) ); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).not.toEqual([255, 255, 255, 255]); }); scene2.camera.lookAt( ellipsoid.cartographicToCartesian(import__479.Rectangle.center(urRect)), new import__479.Cartesian3(0, 0, 5) ); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).not.toEqual([255, 255, 255, 255]); }); scene2.camera.lookAt( ellipsoid.cartographicToCartesian(import__479.Rectangle.center(llRect)), new import__479.Cartesian3(0, 0, 5) ); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).not.toEqual([255, 255, 255, 255]); }); scene2.camera.lookAt( ellipsoid.cartographicToCartesian(import__479.Rectangle.center(lrRect)), new import__479.Cartesian3(0, 0, 5) ); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).not.toEqual([255, 255, 255, 255]); }); }); }); it("can get features and properties", function() { return Cesium3DTilesTester_default.loadTileset( scene2, geometryBoxesWithBatchTable ).then(function(tileset2) { const content = tileset2.root.content; expect(content.featuresLength).toBe(1); expect(content.innerContents).toBeUndefined(); expect(content.hasProperty(0, "name")).toBe(true); expect(content.getFeature(0)).toBeDefined(); }); }); it("throws when calling getFeature with invalid index", function() { return Cesium3DTilesTester_default.loadTileset( scene2, geometryBoxesWithBatchTable ).then(function(tileset2) { const content = tileset2.root.content; expect(function() { content.getFeature(-1); }).toThrowDeveloperError(); expect(function() { content.getFeature(1e3); }).toThrowDeveloperError(); expect(function() { content.getFeature(); }).toThrowDeveloperError(); }); }); it("throws with invalid version", async function() { const arrayBuffer = Cesium3DTilesTester_default.generateGeometryTileBuffer({ version: 2 }); await expectAsync( Cesium3DTilesTester_default.createContentForMockTile(arrayBuffer, "geom") ).toBeRejectedWithError( import__479.RuntimeError, "Only Geometry tile version 1 is supported. Version 2 is not." ); }); it("throws with empty async feature table", async function() { const arrayBuffer = Cesium3DTilesTester_default.generateGeometryTileBuffer({ defineFeatureTable: false }); await expectAsync( Cesium3DTilesTester_default.createContentForMockTile(arrayBuffer, "geom") ).toBeRejectedWithError( import__479.RuntimeError, "Feature table must have a byte length greater than zero" ); }); it("throws without all batch ids", async function() { const arrayBuffer = Cesium3DTilesTester_default.generateGeometryTileBuffer({ boxesLength: 1, cylindersLength: 1, ellipsoidsLength: 1, spheresLength: 1, boxBatchIds: [1], cylinderBatchIds: [0], ellipsoidBatchIds: [2] }); await expectAsync( Cesium3DTilesTester_default.createContentForMockTile(arrayBuffer, "geom") ).toBeRejectedWithError( import__479.RuntimeError, "If one group of batch ids is defined, then all batch ids must be defined" ); }); it("destroys", function() { return Cesium3DTilesTester_default.loadTileset( scene2, geometryBoxesWithBatchTable ).then(function(tileset2) { expect(tileset2.isDestroyed()).toEqual(false); scene2.primitives.remove(tileset2); expect(tileset2.isDestroyed()).toEqual(true); }); }); describe("metadata", function() { let metadataClass; let groupMetadata; let contentMetadataClass; let contentMetadata; beforeAll(function() { metadataClass = import__479.MetadataClass.fromJson({ id: "test", class: { properties: { name: { type: "STRING" }, height: { type: "SCALAR", componentType: "FLOAT32" } } } }); groupMetadata = new import__479.GroupMetadata({ id: "testGroup", group: { properties: { name: "Test Group", height: 35.6 } }, class: metadataClass }); contentMetadataClass = import__479.MetadataClass.fromJson({ id: "contentTest", class: { properties: { author: { type: "STRING" }, color: { type: "VEC3", componentType: "UINT8" } } } }); contentMetadata = new import__479.ContentMetadata({ content: { properties: { author: "Test Author", color: [255, 0, 0] } }, class: contentMetadataClass }); }); it("assigns group metadata", function() { return Cesium3DTilesTester_default.loadTileset(scene2, geometryAll).then( function(tileset2) { const content = tileset2.root.content; content.group = new import__479.Cesium3DContentGroup({ metadata: groupMetadata }); expect(content.group.metadata).toBe(groupMetadata); } ); }); it("assigns metadata", function() { return Cesium3DTilesTester_default.loadTileset(scene2, geometryAll).then( function(tileset2) { const content = tileset2.root.content; content.metadata = contentMetadata; expect(content.metadata).toBe(contentMetadata); } ); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/GeometryRenderingSpec.js var import__480 = __toESM(require_Cesium(), 1); var import__481 = __toESM(require_Cesium(), 1); describe( "Scene/GeometryRenderingSpec", function() { let scene2; let ellipsoid; let primitive; let geometry; beforeAll(function() { scene2 = createScene_default(); scene2.frameState.scene3DOnly = false; scene2.primitives.destroyPrimitives = false; ellipsoid = import__480.Ellipsoid.WGS84; }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { scene2.morphTo3D(0); const camera = scene2.camera; camera.frustum = new import__480.PerspectiveFrustum(); camera.frustum.aspectRatio = scene2.drawingBufferWidth / scene2.drawingBufferHeight; camera.frustum.fov = import__481.Math.toRadians(60); }); afterEach(function() { scene2.primitives.removeAll(); primitive = primitive && !primitive.isDestroyed() && primitive.destroy(); }); function render3D(instance, afterView, appearance) { if (!(0, import__480.defined)(appearance)) { appearance = new import__480.PerInstanceColorAppearance({ flat: true }); } primitive = new import__480.Primitive({ geometryInstances: instance, appearance, asynchronous: false }); scene2.mode = import__480.SceneMode.SCENE3D; scene2.morphTime = import__480.SceneMode.getMorphTime(scene2.mode); scene2.camera.update(scene2.mode); scene2.camera.viewBoundingSphere(geometry.boundingSphereWC); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive); if (typeof afterView === "function") { afterView(); } expect(scene2).notToRender([0, 0, 0, 255]); } function renderCV(instance, afterView, appearance) { if (!(0, import__480.defined)(appearance)) { appearance = new import__480.PerInstanceColorAppearance({ flat: true }); } primitive = new import__480.Primitive({ geometryInstances: instance, appearance, asynchronous: false }); scene2.mode = import__480.SceneMode.COLUMBUS_VIEW; scene2.morphTime = import__480.SceneMode.getMorphTime(scene2.mode); scene2.camera.update(scene2.mode); scene2.camera.viewBoundingSphere(geometry.boundingSphereWC); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive); if (typeof afterView === "function") { afterView(); } expect(scene2).notToRender([0, 0, 0, 255]); } function render2D(instance, appearance) { if (!(0, import__480.defined)(appearance)) { appearance = new import__480.PerInstanceColorAppearance({ flat: true }); } primitive = new import__480.Primitive({ geometryInstances: instance, appearance, asynchronous: false }); scene2.mode = import__480.SceneMode.SCENE2D; scene2.morphTime = import__480.SceneMode.getMorphTime(scene2.mode); scene2.camera.update(scene2.mode); scene2.camera.viewBoundingSphere(geometry.boundingSphereWC); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive); expect(scene2).notToRender([0, 0, 0, 255]); } function pickGeometry(instance, afterView, appearance) { if (!(0, import__480.defined)(appearance)) { appearance = new import__480.PerInstanceColorAppearance({ flat: true }); } const primitive2 = new import__480.Primitive({ geometryInstances: instance, appearance, asynchronous: false }); scene2.mode = import__480.SceneMode.SCENE3D; scene2.morphTime = import__480.SceneMode.getMorphTime(scene2.mode); scene2.camera.update(scene2.mode); scene2.camera.viewBoundingSphere(geometry.boundingSphereWC); scene2.primitives.add(primitive2); if (typeof afterView === "function") { afterView(); } expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toEqual(primitive2); expect(result.id).toEqual(instance.id); }); } function renderAsync(instance, afterView, appearance) { if (!(0, import__480.defined)(appearance)) { appearance = new import__480.PerInstanceColorAppearance({ flat: true }); } const primitive2 = new import__480.Primitive({ geometryInstances: instance, appearance }); scene2.mode = import__480.SceneMode.SCENE3D; scene2.morphTime = import__480.SceneMode.getMorphTime(scene2.mode); scene2.camera.update(scene2.mode); scene2.camera.viewBoundingSphere(geometry.boundingSphereWC); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive2); if (typeof afterView === "function") { afterView(); } primitive2.update(scene2.frameState); return pollToPromise_default(function() { scene2.renderForSpecs(); return primitive2.ready; }).then(function() { expect(scene2).notToRender([0, 0, 0, 255]); }); } describe( "BoxGeometry", function() { let instance; beforeAll(function() { instance = new import__480.GeometryInstance({ geometry: import__480.BoxGeometry.fromDimensions({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, dimensions: new import__480.Cartesian3(1e6, 1e6, 2e6) }), modelMatrix: import__480.Matrix4.multiplyByTranslation( import__480.Transforms.eastNorthUpToFixedFrame( import__480.Cartesian3.fromDegrees(-75.59777, 40.03883) ), new import__480.Cartesian3(0, 0, 1e5), new import__480.Matrix4() ), id: "box", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.BoxGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); it("async", function() { return renderAsync(instance); }); }, "WebGL" ); describe( "PlaneGeometry", function() { let instance; beforeAll(function() { instance = new import__480.GeometryInstance({ geometry: new import__480.PlaneGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT }), modelMatrix: import__480.Matrix4.multiplyByTranslation( import__480.Transforms.eastNorthUpToFixedFrame( import__480.Cartesian3.fromDegrees(-75.59777, 40.03883) ), new import__480.Cartesian3(0, 0, 1e5), new import__480.Matrix4() ), id: "plane", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.PlaneGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); it("async", function() { return renderAsync(instance); }); }, "WebGL" ); describe( "CircleGeometry", function() { let instance; beforeAll(function() { instance = new import__480.GeometryInstance({ geometry: new import__480.CircleGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, ellipsoid, center: import__480.Cartesian3.fromDegrees(-100, 20), radius: 1e6 }), id: "circle", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.CircleGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); it("async", function() { return renderAsync(instance); }); }, "WebGL" ); describe("CoplanarPolygonGeometry", function() { let instance; beforeAll(function() { instance = new import__480.GeometryInstance({ geometry: import__480.CoplanarPolygonGeometry.fromPositions({ positions: import__480.Cartesian3.fromDegreesArrayHeights([ 71, -10, 0, 70, 0, 2e4, 69, 0, 2e4, 68, -10, 0 ]), vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT }), id: "coplanar polygon", attributes: { color: new import__480.ColorGeometryInstanceAttribute( Math.random(), Math.random(), Math.random(), 0.5 ) } }); geometry = import__480.CoplanarPolygonGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); it("async", function() { return renderAsync(instance); }); }); describe( "CylinderGeometry", function() { let instance; beforeAll(function() { instance = new import__480.GeometryInstance({ geometry: new import__480.CylinderGeometry({ length: 5, topRadius: 3, bottomRadius: 5, vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT }), id: "cylinder", modelMatrix: import__480.Matrix4.multiplyByUniformScale( import__480.Matrix4.multiplyByTranslation( import__480.Transforms.eastNorthUpToFixedFrame( import__480.Cartesian3.fromDegrees(-90, 45) ), new import__480.Cartesian3(0, 0, 5e5), new import__480.Matrix4() ), 9e4, new import__480.Matrix4() ), attributes: { color: new import__480.ColorGeometryInstanceAttribute( Math.random(), Math.random(), Math.random(), 0.5 ) } }); geometry = import__480.CylinderGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); it("async", function() { return renderAsync(instance); }); }, "WebGL" ); describe( "EllipseGeometry", function() { let instance; beforeAll(function() { instance = new import__480.GeometryInstance({ geometry: new import__480.EllipseGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, ellipsoid, center: import__480.Cartesian3.fromDegrees(-100, 20), semiMinorAxis: 1e6, semiMajorAxis: 1e6 }), id: "ellipse", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.EllipseGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); it("async", function() { return renderAsync(instance); }); it("rotated", function() { const rotated = new import__480.GeometryInstance({ geometry: new import__480.EllipseGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, ellipsoid, center: import__480.Cartesian3.fromDegrees(-100, 20), semiMinorAxis: 1e6, semiMajorAxis: 1e6, rotation: import__481.Math.PI_OVER_FOUR }), id: "ellipse", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.EllipseGeometry.createGeometry(rotated.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); render3D(rotated); }); it("at height", function() { const atHeight = new import__480.GeometryInstance({ geometry: new import__480.EllipseGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, ellipsoid, center: import__480.Cartesian3.fromDegrees(-100, 20), semiMinorAxis: 1e6, semiMajorAxis: 1e6, height: 1e6 }), id: "ellipse", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.EllipseGeometry.createGeometry(atHeight.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); render3D(atHeight); }); }, "WebGL" ); describe( "Extruded EllipseGeometry", function() { let instance; let extrudedHeight; let geometryHeight; beforeAll(function() { extrudedHeight = 2e5; geometryHeight = 1e5; instance = new import__480.GeometryInstance({ geometry: new import__480.EllipseGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, ellipsoid, center: import__480.Cartesian3.fromDegrees(-100, 20), semiMinorAxis: 1e6, semiMajorAxis: 1e6, height: geometryHeight, extrudedHeight }), id: "extrudedEllipse", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.EllipseGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); it("async", function() { return renderAsync(instance); }); it("renders bottom", function() { function afterView() { const height = (extrudedHeight - geometryHeight) * 0.5; const transform = import__480.Matrix4.multiplyByTranslation( import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphere.center ), new import__480.Cartesian3(0, 0, height), new import__480.Matrix4() ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphere.radius) ); scene2.camera.rotateDown(import__481.Math.PI); } render3D(instance, afterView); }); it("renders wall", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphere.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphere.radius) ); scene2.camera.rotateDown(import__481.Math.PI_OVER_TWO); } render3D(instance, afterView); }); }, "WebGL" ); describe( "EllipsoidGeometry", function() { let instance; beforeAll(function() { instance = new import__480.GeometryInstance({ geometry: new import__480.EllipsoidGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, radii: new import__480.Cartesian3(1e6, 1e6, 5e5) }), modelMatrix: import__480.Matrix4.multiplyByTranslation( import__480.Transforms.eastNorthUpToFixedFrame( import__480.Cartesian3.fromDegrees(-100, 20) ), new import__480.Cartesian3(0, 0, 1e6), new import__480.Matrix4() ), id: "ellipsoid", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.EllipsoidGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); it("async", function() { return renderAsync(instance); }); }, "WebGL" ); describe( "SphereGeometry", function() { let instance; beforeAll(function() { instance = new import__480.GeometryInstance({ geometry: new import__480.SphereGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, radius: 1e6 }), modelMatrix: import__480.Matrix4.multiplyByTranslation( import__480.Transforms.eastNorthUpToFixedFrame( import__480.Cartesian3.fromDegrees(-100, 20) ), new import__480.Cartesian3(0, 0, 1e6), new import__480.Matrix4() ), id: "sphere", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.SphereGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); it("async", function() { return renderAsync(instance); }); }, "WebGL" ); describe( "RectangleGeometry", function() { let instance; let rectangle; beforeAll(function() { rectangle = import__480.Rectangle.fromDegrees(0, 0, 1, 1); instance = new import__480.GeometryInstance({ geometry: new import__480.RectangleGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, ellipsoid, rectangle }), id: "rectangle", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.RectangleGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); it("async", function() { return renderAsync(instance); }); it("rotated geometry", function() { const rotated = new import__480.GeometryInstance({ geometry: new import__480.RectangleGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, ellipsoid, rectangle, rotation: import__481.Math.PI_OVER_FOUR }), attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.RectangleGeometry.createGeometry(rotated.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); render3D(rotated); }); it("rotated texture", function() { const rotated = new import__480.GeometryInstance({ geometry: new import__480.RectangleGeometry({ vertexFormat: import__480.EllipsoidSurfaceAppearance.VERTEX_FORMAT, ellipsoid, rectangle, stRotation: import__481.Math.PI_OVER_TWO }) }); const appearance = new import__480.EllipsoidSurfaceAppearance({ material: import__480.Material.fromType("Stripe") }); geometry = import__480.RectangleGeometry.createGeometry(rotated.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); render3D(rotated, void 0, appearance); }); it("at height", function() { const atHeight = new import__480.GeometryInstance({ geometry: new import__480.RectangleGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, ellipsoid, rectangle, height: 1e5 }), attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.RectangleGeometry.createGeometry(atHeight.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); render3D(atHeight); }); }, "WebGL" ); describe( "Extruded RectangleGeometry", function() { let instance; let rectangle; let extrudedHeight; let geometryHeight; beforeAll(function() { rectangle = import__480.Rectangle.fromDegrees(-1, -1, 1, 1); extrudedHeight = 2e5; geometryHeight = 1e5; instance = new import__480.GeometryInstance({ geometry: new import__480.RectangleGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, ellipsoid, rectangle, height: geometryHeight, extrudedHeight }), id: "rectangle", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.RectangleGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); it("async", function() { return renderAsync(instance); }); it("renders bottom", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphereWC.radius) ); scene2.camera.rotateDown(import__481.Math.PI); } render3D(instance, afterView); }); it("renders north wall", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphereWC.radius) ); scene2.camera.rotateDown(-import__481.Math.PI_OVER_TWO); } render3D(instance, afterView); }); it("renders south wall", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphereWC.radius) ); scene2.camera.rotateDown(import__481.Math.PI_OVER_TWO); } render3D(instance, afterView); }); it("renders west wall", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphereWC.radius) ); scene2.camera.rotateRight(-import__481.Math.PI_OVER_TWO); } render3D(instance, afterView); }); it("renders east wall", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphereWC.radius) ); scene2.camera.rotateRight(import__481.Math.PI_OVER_TWO); } render3D(instance, afterView); }); }, "WebGL" ); describe( "PolygonGeometry", function() { let instance; beforeAll(function() { instance = new import__480.GeometryInstance({ geometry: import__480.PolygonGeometry.fromPositions({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, ellipsoid, positions: import__480.Cartesian3.fromDegreesArray([ 0, 45, 10, 45, 10, 55, 0, 55 ]) }), id: "polygon", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.PolygonGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); it("async", function() { return renderAsync(instance); }); it("at height", function() { const atHeight = new import__480.GeometryInstance({ geometry: import__480.PolygonGeometry.fromPositions({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, ellipsoid, positions: import__480.Cartesian3.fromDegreesArray([ 0, 45, 10, 45, 10, 55, 0, 55 ]), height: 3e6 }), id: "polygon", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.PolygonGeometry.createGeometry(atHeight.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, atHeight.modelMatrix ); render3D(atHeight); }); it("hierarchy", function() { const hierarchy = new import__480.GeometryInstance({ geometry: new import__480.PolygonGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, polygonHierarchy: { positions: import__480.Cartesian3.fromDegreesArray([ -109, 30, -95, 30, -95, 40, -109, 40 ]), holes: [ { positions: import__480.Cartesian3.fromDegreesArray([ -107, 31, -107, 39, -97, 39, -97, 31 ]), holes: [ { positions: import__480.Cartesian3.fromDegreesArray([ -106.5, 31.5, -97.5, 31.5, -97.5, 38.5, -106.5, 38.5 ]) } ] } ] } }), id: "polygon", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.PolygonGeometry.createGeometry(hierarchy.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, hierarchy.modelMatrix ); render3D(hierarchy); }); }, "WebGL" ); describe( "Extruded PolygonGeometry", function() { let instance; let extrudedHeight; let geometryHeight; beforeAll(function() { extrudedHeight = 2e5; geometryHeight = 1e5; instance = new import__480.GeometryInstance({ geometry: import__480.PolygonGeometry.fromPositions({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, ellipsoid, positions: import__480.Cartesian3.fromDegreesArray([ -1, -1, 1, -1, 1, 1, -1, 1 ]), height: geometryHeight, extrudedHeight }), id: "extrudedPolygon", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.PolygonGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); it("async", function() { return renderAsync(instance); }); it("renders bottom", function() { function afterView() { const height = (extrudedHeight - geometryHeight) * 0.5; const transform = import__480.Matrix4.multiplyByTranslation( import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphere.center ), new import__480.Cartesian3(0, 0, height), new import__480.Matrix4() ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphere.radius) ); scene2.camera.rotateDown(import__481.Math.PI); } render3D(instance, afterView); }); it("renders wall 1", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphere.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphere.radius) ); scene2.camera.rotateUp(import__481.Math.PI_OVER_TWO); } render3D(instance, afterView); }); it("renders wall 2", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphere.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphere.radius) ); scene2.camera.rotateDown(-import__481.Math.PI_OVER_TWO); } render3D(instance, afterView); }); it("renders wall 3", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphere.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphere.radius) ); scene2.camera.rotateRight(-import__481.Math.PI_OVER_TWO); } render3D(instance, afterView); }); it("renders wall 4", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphere.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphere.radius) ); scene2.camera.rotateRight(import__481.Math.PI_OVER_TWO); } render3D(instance, afterView); }); it("renders with correct winding order in southern hemisphere", function() { const instance2 = new import__480.GeometryInstance({ geometry: import__480.PolygonGeometry.fromPositions({ vertexFormat: import__480.PerInstanceColorAppearance.VERTEX_FORMAT, ellipsoid, positions: import__480.Cartesian3.fromDegreesArrayHeights([ -108, -25, 5e5, -100, -25, 5e5, -100, -30, 5e5, -108, -30, 5e5 ]), perPositionHeight: true, extrudedHeight: 0 }), id: "extrudedPolygon", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.PolygonGeometry.createGeometry(instance2.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance2.modelMatrix ); function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphereWC.radius) ); scene2.camera.rotateDown(-import__481.Math.PI_OVER_TWO); scene2.camera.moveForward(geometry.boundingSphereWC.radius * 0.75); } render3D(instance2, afterView); }); }, "WebGL" ); describe( "WallGeometry", function() { let instance; let afterViewCV; let afterView3D; beforeAll(function() { const height = 1e5; instance = new import__480.GeometryInstance({ geometry: new import__480.WallGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, ellipsoid, positions: import__480.Cartesian3.fromDegreesArrayHeights([ 0, 0, height, 0.01, 0, height ]) }), id: "wall", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.WallGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); afterView3D = function() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphereWC.radius) ); scene2.camera.rotateDown(-import__481.Math.PI_OVER_TWO); }; afterViewCV = function() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ); import__480.Matrix4.clone(transform, scene2.camera._transform); scene2.camera.rotateDown(-import__481.Math.PI_OVER_TWO); scene2.camera.zoomIn(geometry.boundingSphereWC.radius); import__480.Matrix4.clone(import__480.Matrix4.IDENTITY, scene2.camera._transform); }; }); it("3D", function() { render3D(instance, afterView3D); }); it("Columbus view", function() { renderCV(instance, afterViewCV); }); it("pick", function() { pickGeometry(instance, afterView3D); }); it("async", function() { return renderAsync(instance, afterView3D); }); }, "WebGL" ); describe( "CorridorGeometry", function() { let instance; let positions; let width; beforeAll(function() { positions = import__480.Cartesian3.fromDegreesArray([0, -1, 0, 1]); width = 1e5; instance = new import__480.GeometryInstance({ geometry: new import__480.CorridorGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, ellipsoid, positions, width, cornerType: import__480.CornerType.MITERED }), id: "corridor", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.CorridorGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); it("async", function() { return renderAsync(instance); }); it("at height", function() { const atHeight = new import__480.GeometryInstance({ geometry: new import__480.CorridorGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, ellipsoid, positions, width, cornerType: import__480.CornerType.MITERED, height: 1e5 }), attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.CorridorGeometry.createGeometry(atHeight.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, atHeight.modelMatrix ); render3D(atHeight); }); }, "WebGL" ); describe( "Extruded CorridorGeometry", function() { let instance; let extrudedHeight; let geometryHeight; const width = 1e5; let positions; beforeAll(function() { positions = import__480.Cartesian3.fromDegreesArray([0, -1, 0, 1]); extrudedHeight = 2e5; geometryHeight = 1e5; instance = new import__480.GeometryInstance({ geometry: new import__480.CorridorGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, ellipsoid, positions, width, cornerType: import__480.CornerType.MITERED, height: geometryHeight, extrudedHeight }), id: "extrudedCorridor", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.CorridorGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); it("async", function() { return renderAsync(instance); }); it("renders bottom", function() { function afterView() { const height = (extrudedHeight - geometryHeight) * 0.5; const transform = import__480.Matrix4.multiplyByTranslation( import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ), new import__480.Cartesian3(0, 0, height), new import__480.Matrix4() ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphereWC.radius) ); scene2.camera.rotateDown(import__481.Math.PI); } render3D(instance, afterView); }); it("renders north wall", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphereWC.radius) ); scene2.camera.rotateDown(-import__481.Math.PI_OVER_TWO); } render3D(instance, afterView); }); it("renders south wall", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphereWC.radius) ); scene2.camera.rotateDown(import__481.Math.PI_OVER_TWO); } render3D(instance, afterView); }); it("renders west wall", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphereWC.radius) ); scene2.camera.rotateRight(-import__481.Math.PI_OVER_TWO); } render3D(instance, afterView); }); it("renders east wall", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphereWC.radius) ); scene2.camera.rotateRight(import__481.Math.PI_OVER_TWO); } render3D(instance, afterView); }); }, "WebGL" ); describe( "PolylineVolumeGeometry", function() { let instance; let geometryHeight; let positions; let shape; beforeAll(function() { positions = import__480.Cartesian3.fromDegreesArray([0, -1, 0, 1]); shape = [ new import__480.Cartesian2(-1e5, -1e5), new import__480.Cartesian2(1e5, -1e5), new import__480.Cartesian2(1e5, 1e5), new import__480.Cartesian2(-1e5, 1e5) ]; geometryHeight = 15e4; instance = new import__480.GeometryInstance({ geometry: new import__480.PolylineVolumeGeometry({ vertexFormat: import__480.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT, ellipsoid, polylinePositions: positions, shapePositions: shape, cornerType: import__480.CornerType.MITERED, height: geometryHeight }), id: "polylineVolume", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); geometry = import__480.PolylineVolumeGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); it("async", function() { return renderAsync(instance); }); it("renders bottom", function() { function afterView() { const height = geometryHeight * 0.5; const transform = import__480.Matrix4.multiplyByTranslation( import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ), new import__480.Cartesian3(0, 0, height), new import__480.Matrix4() ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphereWC.radius) ); scene2.camera.rotateDown(import__481.Math.PI); } render3D(instance, afterView); }); it("renders north wall", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphereWC.radius) ); scene2.camera.rotateDown(-import__481.Math.PI_OVER_TWO); } render3D(instance, afterView); }); it("renders south wall", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphereWC.radius) ); scene2.camera.rotateDown(import__481.Math.PI_OVER_TWO); } render3D(instance, afterView); }); it("renders west wall", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphereWC.radius) ); scene2.camera.rotateRight(-import__481.Math.PI_OVER_TWO); } render3D(instance, afterView); }); it("renders east wall", function() { function afterView() { const transform = import__480.Transforms.eastNorthUpToFixedFrame( geometry.boundingSphereWC.center ); scene2.camera.lookAtTransform( transform, new import__480.Cartesian3(0, 0, geometry.boundingSphereWC.radius) ); scene2.camera.rotateRight(import__481.Math.PI_OVER_TWO); } render3D(instance, afterView); }); }, "WebGL" ); describe( "SimplePolylineGeometry", function() { let instance; beforeAll(function() { instance = new import__480.GeometryInstance({ geometry: new import__480.SimplePolylineGeometry({ positions: import__480.Cartesian3.fromDegreesArray([0, 0, 5, 0]) }), attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 1, 1) }, id: "simple polyline" }); geometry = import__480.SimplePolylineGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); it("async", function() { return renderAsync(instance); }); it("per segment colors", function() { instance = new import__480.GeometryInstance({ geometry: new import__480.SimplePolylineGeometry({ positions: import__480.Cartesian3.fromDegreesArray([0, 0, 5, 0]), colors: [ new import__480.Color(1, 0, 0, 1), new import__480.Color(0, 1, 0, 1) ] }), id: "polyline" }); geometry = import__480.SimplePolylineGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); render3D(instance); }); it("per vertex colors", function() { instance = new import__480.GeometryInstance({ geometry: new import__480.SimplePolylineGeometry({ positions: import__480.Cartesian3.fromDegreesArray([0, 0, 5, 0]), colors: [ new import__480.Color(1, 0, 0, 1), new import__480.Color(0, 1, 0, 1) ], colorsPerVertex: true }), id: "polyline" }); geometry = import__480.SimplePolylineGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); render3D(instance); }); }, "WebGL" ); describe( "PolylineGeometry", function() { let instance; let appearance; beforeAll(function() { instance = new import__480.GeometryInstance({ geometry: new import__480.PolylineGeometry({ positions: import__480.Cartesian3.fromDegreesArray([0, 0, 5, 0]), width: 20 }), attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 1, 1) }, id: "polyline" }); appearance = new import__480.PolylineColorAppearance({ translucent: false }); geometry = import__480.PolylineGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance, void 0, appearance); }); it("Columbus view", function() { renderCV(instance, void 0, appearance); }); it("2D", function() { render2D(instance, appearance); }); it("pick", function() { pickGeometry(instance, void 0, appearance); }); it("async", function() { return renderAsync(instance, void 0, appearance); }); it("per segment colors", function() { instance = new import__480.GeometryInstance({ geometry: new import__480.PolylineGeometry({ positions: import__480.Cartesian3.fromDegreesArray([0, 0, 5, 0]), width: 20, colors: [ new import__480.Color(1, 0, 0, 1), new import__480.Color(0, 1, 0, 1) ], arcType: import__480.ArcType.NONE }), id: "polyline" }); geometry = import__480.PolylineGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); render3D(instance, void 0, appearance); }); it("per vertex colors", function() { instance = new import__480.GeometryInstance({ geometry: new import__480.PolylineGeometry({ positions: import__480.Cartesian3.fromDegreesArray([0, 0, 5, 0]), width: 20, colors: [ new import__480.Color(1, 0, 0, 1), new import__480.Color(0, 1, 0, 1) ], colorsPerVertex: true, arcType: import__480.ArcType.NONE }), id: "polyline" }); geometry = import__480.PolylineGeometry.createGeometry(instance.geometry); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); render3D(instance, void 0, appearance); }); }, "WebGL" ); describe("Custom geometry", function() { describe( "with indices", function() { let instance; beforeAll(function() { instance = new import__480.GeometryInstance({ geometry: new import__480.Geometry({ attributes: { position: new import__480.GeometryAttribute({ componentDatatype: import__480.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ 1e6, 0, 0, 1e6, 1e6, 0, 1e6, 0, 1e6, 1e6, 1e6, 1e6 ]) }) }, indices: new Uint16Array([0, 1, 2, 2, 1, 3]), primitiveType: import__480.PrimitiveType.TRIANGLES }), modelMatrix: import__480.Matrix4.multiplyByTranslation( import__480.Transforms.eastNorthUpToFixedFrame( import__480.Cartesian3.fromDegrees(0, 0) ), new import__480.Cartesian3(0, 0, 1e4), new import__480.Matrix4() ), id: "customWithIndices", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 1, 1) } }); geometry = instance.geometry; geometry.boundingSphere = import__480.BoundingSphere.fromVertices( instance.geometry.attributes.position.values ); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); }, "WebGL" ); describe( "without indices", function() { let instance; beforeAll(function() { instance = new import__480.GeometryInstance({ geometry: new import__480.Geometry({ attributes: { position: new import__480.GeometryAttribute({ componentDatatype: import__480.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: new Float64Array([ 1e6, 0, 0, 1e6, 1e6, 0, 1e6, 0, 1e6, 1e6, 0, 1e6, 1e6, 1e6, 0, 1e6, 1e6, 1e6 ]) }) }, primitiveType: import__480.PrimitiveType.TRIANGLES }), modelMatrix: import__480.Matrix4.multiplyByTranslation( import__480.Transforms.eastNorthUpToFixedFrame( import__480.Cartesian3.fromDegrees(0, 0) ), new import__480.Cartesian3(0, 0, 1e4), new import__480.Matrix4() ), id: "customWithoutIndices", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 1, 1) } }); geometry = instance.geometry; geometry.boundingSphere = import__480.BoundingSphere.fromVertices( instance.geometry.attributes.position.values ); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); }, "WebGL" ); describe( "with native arrays as attributes and indices", function() { let instance; beforeAll(function() { instance = new import__480.GeometryInstance({ geometry: new import__480.Geometry({ attributes: { position: new import__480.GeometryAttribute({ componentDatatype: import__480.ComponentDatatype.DOUBLE, componentsPerAttribute: 3, values: [ 1e6, 0, 0, 1e6, 1e6, 0, 1e6, 0, 1e6, 1e6, 1e6, 1e6 ] }) }, indices: [0, 1, 2, 2, 1, 3], primitiveType: import__480.PrimitiveType.TRIANGLES }), modelMatrix: import__480.Matrix4.multiplyByTranslation( import__480.Transforms.eastNorthUpToFixedFrame( import__480.Cartesian3.fromDegrees(0, 0) ), new import__480.Cartesian3(0, 0, 1e4), new import__480.Matrix4() ), id: "customWithIndices", attributes: { color: new import__480.ColorGeometryInstanceAttribute(1, 1, 1, 1) } }); geometry = instance.geometry; geometry.boundingSphere = import__480.BoundingSphere.fromVertices( instance.geometry.attributes.position.values ); geometry.boundingSphereWC = import__480.BoundingSphere.transform( geometry.boundingSphere, instance.modelMatrix ); }); it("3D", function() { render3D(instance); }); it("Columbus view", function() { renderCV(instance); }); it("2D", function() { render2D(instance); }); it("pick", function() { pickGeometry(instance); }); }, "WebGL" ); }); }, "WebGL" ); // packages/engine/Specs/Scene/GlobeSpec.js var import__482 = __toESM(require_Cesium(), 1); describe( "Scene/Globe", function() { let scene2; let globe2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { globe2 = new import__482.Globe(); scene2.globe = globe2; }); afterEach(function() { scene2.globe = void 0; import__482.Resource._Implementations.loadWithXhr = import__482.Resource._DefaultImplementations.loadWithXhr; }); function returnTileJson(path) { const oldLoad = import__482.Resource._Implementations.loadWithXhr; import__482.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { if (url.indexOf("layer.json") >= 0) { import__482.Resource._DefaultImplementations.loadWithXhr( path, responseType, method, data, headers, deferred ); } else { return oldLoad( url, responseType, method, data, headers, deferred, overrideMimeType ); } }; } function returnVertexNormalTileJson() { return returnTileJson( "Data/CesiumTerrainTileJson/VertexNormals.tile.json" ); } function updateUntilDone(globe3) { return pollToPromise_default(function() { globe3._surface._debug.enableDebugOutput = true; scene2.render(); return globe3.tilesLoaded; }); } it("renders with enableLighting", async function() { globe2.enableLighting = true; const layerCollection = globe2.imageryLayers; layerCollection.removeAll(); const provider = await import__482.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); layerCollection.addImageryProvider(provider); scene2.camera.setView({ destination: new import__482.Rectangle(1e-4, 1e-4, 25e-4, 25e-4) }); return updateUntilDone(globe2).then(function() { scene2.globe.show = false; expect(scene2).toRender([0, 0, 0, 255]); scene2.globe.show = true; expect(scene2).notToRender([0, 0, 0, 255]); }); }); it("renders with dynamicAtmosphereLighting", async function() { globe2.enableLighting = true; globe2.dynamicAtmosphereLighting = true; const layerCollection = globe2.imageryLayers; layerCollection.removeAll(); const provider = await import__482.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); layerCollection.addImageryProvider(provider); scene2.camera.setView({ destination: new import__482.Rectangle(1e-4, 1e-4, 25e-4, 25e-4) }); return updateUntilDone(globe2).then(function() { scene2.globe.show = false; expect(scene2).toRender([0, 0, 0, 255]); scene2.globe.show = true; expect(scene2).notToRender([0, 0, 0, 255]); }); }); it("renders with dynamicAtmosphereLightingFromSun", async function() { globe2.enableLighting = true; globe2.dynamicAtmosphereLighting = true; globe2.dynamicAtmosphereLightingFromSun = true; const layerCollection = globe2.imageryLayers; layerCollection.removeAll(); const provider = await import__482.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); layerCollection.addImageryProvider(provider); scene2.camera.setView({ destination: new import__482.Rectangle(1e-4, 1e-4, 25e-4, 25e-4) }); return updateUntilDone(globe2).then(function() { scene2.globe.show = false; expect(scene2).toRender([0, 0, 0, 255]); scene2.globe.show = true; expect(scene2).notToRender([0, 0, 0, 255]); }); }); it("renders with showWaterEffect set to false", async function() { globe2.showWaterEffect = false; const layerCollection = globe2.imageryLayers; layerCollection.removeAll(); const provider = await import__482.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); layerCollection.addImageryProvider(provider); scene2.camera.setView({ destination: new import__482.Rectangle(1e-4, 1e-4, 25e-4, 25e-4) }); return updateUntilDone(globe2).then(function() { scene2.globe.show = false; expect(scene2).toRender([0, 0, 0, 255]); scene2.globe.show = true; expect(scene2).notToRender([0, 0, 0, 255]); }); }); it("ImageryLayersUpdated event fires when layer is added, hidden, shown, moved, or removed", async function() { let timesEventRaised = 0; globe2.imageryLayersUpdatedEvent.addEventListener(function() { ++timesEventRaised; }); const layerCollection = globe2.imageryLayers; layerCollection.removeAll(); const provider = await import__482.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); const layer = layerCollection.addImageryProvider(provider); layerCollection.addImageryProvider(provider); return updateUntilDone(globe2).then(function() { expect(timesEventRaised).toEqual(2); layer.show = false; return updateUntilDone(globe2); }).then(function() { expect(timesEventRaised).toEqual(3); layer.show = true; return updateUntilDone(globe2); }).then(function() { expect(timesEventRaised).toEqual(4); layerCollection.raise(layer); return updateUntilDone(globe2); }).then(function() { expect(timesEventRaised).toEqual(5); layerCollection.remove(layer); return updateUntilDone(globe2); }).then(function() { expect(timesEventRaised).toEqual(6); }); }); it("terrainProviderChanged event fires", async function() { const terrainProvider = await import__482.CesiumTerrainProvider.fromUrl( "made/up/url", { requestVertexNormals: true } ); const spyListener = jasmine.createSpy("listener"); globe2.terrainProviderChanged.addEventListener(spyListener); globe2.terrainProvider = terrainProvider; expect(spyListener).toHaveBeenCalledWith(terrainProvider); }); it("tilesLoaded return true when tile load queue is empty", async function() { expect(globe2.tilesLoaded).toBe(true); globe2._surface._tileLoadQueueHigh.length = 2; expect(globe2.tilesLoaded).toBe(false); globe2._surface._tileLoadQueueHigh.length = 0; expect(globe2.tilesLoaded).toBe(true); globe2._surface._tileLoadQueueMedium.length = 2; expect(globe2.tilesLoaded).toBe(false); globe2._surface._tileLoadQueueMedium.length = 0; expect(globe2.tilesLoaded).toBe(true); globe2._surface._tileLoadQueueLow.length = 2; expect(globe2.tilesLoaded).toBe(false); globe2._surface._tileLoadQueueLow.length = 0; expect(globe2.tilesLoaded).toBe(true); const terrainProvider = await import__482.CesiumTerrainProvider.fromUrl( "made/up/url", { requestVertexNormals: true } ); globe2.terrainProvider = terrainProvider; scene2.render(); expect(globe2.tilesLoaded).toBe(false); }); it("renders terrain with enableLighting", async function() { const renderOptions = { scene: scene2, time: new import__482.JulianDate(2557522) }; globe2.enableLighting = true; const layerCollection = globe2.imageryLayers; layerCollection.removeAll(); const imageryProvider = await import__482.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); layerCollection.addImageryProvider(imageryProvider); import__482.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__482.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.vertexnormals.terrain", responseType, method, data, headers, deferred ); }; returnVertexNormalTileJson(); const terrainProvider = await import__482.CesiumTerrainProvider.fromUrl( "made/up/url", { requestVertexNormals: true } ); globe2.terrainProvider = terrainProvider; scene2.camera.setView({ destination: new import__482.Rectangle(1e-4, 1e-4, 25e-4, 25e-4) }); await updateUntilDone(globe2); expect(renderOptions).notToRender([0, 0, 0, 255]); scene2.globe.show = false; expect(renderOptions).toRender([0, 0, 0, 255]); }); it("renders terrain with lambertDiffuseMultiplier", async function() { const renderOptions = { scene: scene2, time: new import__482.JulianDate(2557522) }; globe2.enableLighting = true; const layerCollection = globe2.imageryLayers; layerCollection.removeAll(); const imageryProvider = await import__482.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); layerCollection.addImageryProvider(imageryProvider); import__482.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__482.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.vertexnormals.terrain", responseType, method, data, headers, deferred ); }; returnVertexNormalTileJson(); const terrainProvider = await import__482.CesiumTerrainProvider.fromUrl( "made/up/url", { requestVertexNormals: true } ); globe2.terrainProvider = terrainProvider; scene2.camera.setView({ destination: new import__482.Rectangle(1e-4, 1e-4, 25e-4, 25e-4) }); await updateUntilDone(globe2); let initialRgba; expect(renderOptions).toRenderAndCall(function(rgba) { initialRgba = rgba; expect(renderOptions).notToRender([0, 0, 0, 255]); }); globe2.lambertDiffuseMultiplier = 10; expect(renderOptions).notToRender(initialRgba); }); it("renders terrain with vertexShadowDarkness", async function() { const renderOptions = { scene: scene2, time: new import__482.JulianDate(2557522) }; globe2.enableLighting = true; const layerCollection = globe2.imageryLayers; layerCollection.removeAll(); const imageryProvider = await import__482.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); layerCollection.addImageryProvider(imageryProvider); import__482.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__482.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.vertexnormals.terrain", responseType, method, data, headers, deferred ); }; returnVertexNormalTileJson(); const terrainProvider = await import__482.CesiumTerrainProvider.fromUrl( "made/up/url", { requestVertexNormals: true } ); globe2.terrainProvider = terrainProvider; scene2.camera.setView({ destination: new import__482.Rectangle(1e-4, 1e-4, 25e-4, 25e-4) }); await updateUntilDone(globe2); let initialRgba; expect(renderOptions).toRenderAndCall(function(rgba) { initialRgba = rgba; expect(renderOptions).notToRender([0, 0, 0, 255]); globe2.vertexShadowDarkness = 0.1; expect(renderOptions).notToRender(initialRgba); }); }); it("renders with hue shift", async function() { const layerCollection = globe2.imageryLayers; layerCollection.removeAll(); const provider = await import__482.SingleTileImageryProvider.fromUrl( "Data/Images/Blue.png" ); layerCollection.addImageryProvider(provider); scene2.camera.flyHome(0); await updateUntilDone(globe2); scene2.globe.show = false; expect(scene2).toRender([0, 0, 0, 255]); scene2.globe.show = true; expect(scene2).notToRender([0, 0, 0, 255]); expect(scene2).toRenderAndCall(function(rgba) { scene2.globe.atmosphereHueShift = 0.1; expect(scene2).notToRender([0, 0, 0, 255]); expect(scene2).notToRender(rgba); }); }); it("renders with saturation shift", async function() { const layerCollection = globe2.imageryLayers; layerCollection.removeAll(); const provider = await import__482.SingleTileImageryProvider.fromUrl( "Data/Images/Blue.png" ); layerCollection.addImageryProvider(provider); scene2.camera.flyHome(0); await updateUntilDone(globe2); scene2.globe.show = false; expect(scene2).toRender([0, 0, 0, 255]); scene2.globe.show = true; expect(scene2).notToRender([0, 0, 0, 255]); expect(scene2).toRenderAndCall(function(rgba) { scene2.globe.atmosphereSaturationShift = 0.1; expect(scene2).notToRender([0, 0, 0, 255]); expect(scene2).notToRender(rgba); }); }); it("renders with brightness shift", async function() { const layerCollection = globe2.imageryLayers; layerCollection.removeAll(); const provider = await import__482.SingleTileImageryProvider.fromUrl( "Data/Images/Blue.png" ); layerCollection.addImageryProvider(provider); scene2.camera.flyHome(0); await updateUntilDone(globe2); scene2.globe.show = false; expect(scene2).toRender([0, 0, 0, 255]); scene2.globe.show = true; expect(scene2).notToRender([0, 0, 0, 255]); expect(scene2).toRenderAndCall(function(rgba) { scene2.globe.atmosphereBrightnessShift = 0.1; expect(scene2).notToRender([0, 0, 0, 255]); expect(scene2).notToRender(rgba); }); }); it("applies back face culling", function() { scene2.camera.setView({ destination: new import__482.Rectangle(1e-4, 1e-4, 25e-4, 25e-4) }); return updateUntilDone(globe2).then(function() { globe2.backFaceCulling = true; scene2.render(); let command = scene2.frameState.commandList[0]; expect(command.renderState.cull.enabled).toBe(true); globe2.backFaceCulling = false; scene2.render(); command = scene2.frameState.commandList[0]; expect(command.renderState.cull.enabled).toBe(false); }); }); it("shows terrain skirts", function() { scene2.camera.setView({ destination: new import__482.Rectangle(1e-4, 1e-4, 25e-4, 25e-4) }); return updateUntilDone(globe2).then(function() { globe2.showSkirts = true; scene2.render(); let command = scene2.frameState.commandList[0]; const indexCount = command.count; expect(indexCount).toBe(command.owner.data.renderedMesh.indices.length); globe2.showSkirts = false; scene2.render(); command = scene2.frameState.commandList[0]; expect(command.count).toBeLessThan(indexCount); expect(command.count).toBe( command.owner.data.renderedMesh.indexCountWithoutSkirts ); }); }); it("gets underground color", function() { expect(globe2.undergroundColor).toEqual(import__482.Color.BLACK); }); it("sets underground color", function() { globe2.undergroundColor = import__482.Color.RED; scene2.camera.setView({ destination: new import__482.Cartesian3( -524251.65918537375, -5.3163555357514685e6, 3400179253223899e-9 ), orientation: new import__482.HeadingPitchRoll( 0.22779127099032603, -0.7030060668670961, 0.0024147223687949193 ) }); return updateUntilDone(globe2).then(function() { expect(scene2).toRender([255, 0, 0, 255]); }); }); it("gets underground color by distance", function() { expect(globe2.undergroundColorAlphaByDistance).toBeDefined(); }); it("sets underground color by distance", function() { globe2.baseColor = import__482.Color.BLACK; globe2.undergroundColor = import__482.Color.RED; const radius = globe2.ellipsoid.maximumRadius; globe2.undergroundColorAlphaByDistance = new import__482.NearFarScalar( radius * 0.25, 0, radius * 2, 1 ); scene2.camera.setView({ destination: new import__482.Cartesian3( -524251.65918537375, -5.3163555357514685e6, 3400179253223899e-9 ), orientation: new import__482.HeadingPitchRoll( 0.24245689061958142, -0.445653254172905, 0.0024147223687949193 ) }); return updateUntilDone(globe2).then(function() { expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[0]).toBeLessThan(255); }); }); }); it("throws if underground color by distance far is less than near", function() { expect(function() { globe2.undergroundColorAlphaByDistance = new import__482.NearFarScalar( 1, 0, 0, 1 ); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Scene/GlobeSurfaceTileProviderSpec.js var import__483 = __toESM(require_Cesium(), 1); describe( "Scene/GlobeSurfaceTileProvider", function() { let scene2; function forEachRenderedTile(quadtreePrimitive, minimumTiles, maximumTiles, callback) { let tileCount = 0; quadtreePrimitive.forEachRenderedTile(function(tile) { ++tileCount; callback(tile); }); if ((0, import__483.defined)(minimumTiles)) { expect(tileCount).not.toBeLessThan(minimumTiles); } if ((0, import__483.defined)(maximumTiles)) { expect(tileCount).not.toBeGreaterThan(maximumTiles); } } function updateUntilDone(globe2) { return pollToPromise_default(function() { scene2.renderForSpecs(); return globe2._surface._tileLoadQueueHigh.length === 0 && globe2._surface._tileLoadQueueMedium.length === 0 && globe2._surface._tileLoadQueueLow.length === 0 && globe2._surface._debug.tilesWaitingForChildren === 0; }); } const cameraDestination = new import__483.Rectangle(1e-4, 1e-4, 3e-3, 3e-3); function switchViewMode(mode, projection) { scene2.mode = mode; scene2.frameState.mapProjection = projection; scene2.camera.update(scene2.mode); scene2.camera.setView({ destination: cameraDestination }); } beforeAll(function() { scene2 = createScene_default(); scene2.frameState.scene3DOnly = false; }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { scene2.globe = new import__483.Globe(); }); afterEach(function() { scene2.imageryLayers.removeAll(); scene2.primitives.removeAll(); import__483.Resource._Implementations.loadWithXhr = import__483.Resource._DefaultImplementations.loadWithXhr; }); it("conforms to QuadtreeTileProvider interface", function() { expect(import__483.GlobeSurfaceTileProvider).toConformToInterface( import__483.QuadtreeTileProvider ); }); describe( "construction", function() { it("throws if a terrainProvider is not provided", function() { function constructWithoutTerrainProvider() { return new import__483.GlobeSurfaceTileProvider({ imageryLayers: new import__483.ImageryLayerCollection(), surfaceShaderSet: new import__483.GlobeSurfaceShaderSet() }); } expect(constructWithoutTerrainProvider).toThrowDeveloperError(); }); it("throws if a imageryLayers is not provided", function() { function constructWithoutImageryLayerCollection() { return new import__483.GlobeSurfaceTileProvider({ terrainProvider: new import__483.EllipsoidTerrainProvider(), surfaceShaderSet: new import__483.GlobeSurfaceShaderSet() }); } expect( constructWithoutImageryLayerCollection ).toThrowDeveloperError(); }); it("throws if a surfaceShaderSet is not provided", function() { function constructWithoutImageryLayerCollection() { return new import__483.GlobeSurfaceTileProvider({ terrainProvider: new import__483.EllipsoidTerrainProvider(), imageryLayers: new import__483.ImageryLayerCollection() }); } expect( constructWithoutImageryLayerCollection ).toThrowDeveloperError(); }); }, "WebGL" ); describe( "layer updating", function() { it("removing a layer removes it from all tiles", async function() { const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); const layer = scene2.imageryLayers.addImageryProvider(provider); await updateUntilDone(scene2.globe); forEachRenderedTile(scene2.globe._surface, 1, void 0, function(tile) { expect(tile.data.imagery.length).toBeGreaterThan(0); for (let i = 0; i < tile.data.imagery.length; ++i) { const imagery = (0, import__483.defaultValue)( tile.data.imagery[i].readyImagery, tile.data.imagery[i].loadingImagery ); expect(imagery.imageryLayer).toEqual(layer); } }); scene2.imageryLayers.remove(layer); forEachRenderedTile(scene2.globe._surface, 1, void 0, function(tile) { expect(tile.data.imagery.length).toEqual(0); }); }); it("adding a layer adds it to all tiles after update", async function() { const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); scene2.imageryLayers.addImageryProvider(provider); await updateUntilDone(scene2.globe); const provider2 = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Green4x4.png" ); const layer2 = scene2.imageryLayers.addImageryProvider(provider2); await updateUntilDone(scene2.globe); forEachRenderedTile(scene2.globe._surface, 1, void 0, function(tile) { expect(tile.data.imagery.length).toBeGreaterThan(0); let hasImageFromLayer2 = false; for (let i = 0; i < tile.data.imagery.length; ++i) { let imageryTile = tile.data.imagery[i].readyImagery; if (!(0, import__483.defined)(imageryTile)) { imageryTile = tile.data.imagery[i].loadingImagery; } if (imageryTile.imageryLayer === layer2) { hasImageFromLayer2 = true; } } expect(hasImageFromLayer2).toEqual(true); }); }); it("moving a layer moves the corresponding TileImagery instances on every tile", async function() { const provider1 = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); const layer1 = scene2.imageryLayers.addImageryProvider(provider1); const provider2 = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Green4x4.png" ); const layer2 = scene2.imageryLayers.addImageryProvider(provider2); await updateUntilDone(scene2.globe); forEachRenderedTile(scene2.globe._surface, 1, void 0, function(tile) { expect(tile.data.imagery.length).toBeGreaterThan(0); let indexOfFirstLayer1 = tile.data.imagery.length; let indexOfLastLayer1 = -1; let indexOfFirstLayer2 = tile.data.imagery.length; for (let i = 0; i < tile.data.imagery.length; ++i) { const imagery = (0, import__483.defaultValue)( tile.data.imagery[i].readyImagery, tile.data.imagery[i].loadingImagery ); if (imagery.imageryLayer === layer1) { indexOfFirstLayer1 = Math.min(indexOfFirstLayer1, i); indexOfLastLayer1 = i; } else { expect(imagery.imageryLayer).toEqual(layer2); indexOfFirstLayer2 = Math.min(indexOfFirstLayer2, i); } } expect(indexOfFirstLayer1).toBeLessThan(indexOfFirstLayer2); expect(indexOfLastLayer1).toBeLessThan(indexOfFirstLayer2); }); scene2.imageryLayers.raiseToTop(layer1); await updateUntilDone(scene2.globe); forEachRenderedTile(scene2.globe._surface, 1, void 0, function(tile) { expect(tile.data.imagery.length).toBeGreaterThan(0); let indexOfFirstLayer2 = tile.data.imagery.length; let indexOfLastLayer2 = -1; let indexOfFirstLayer1 = tile.data.imagery.length; for (let i = 0; i < tile.data.imagery.length; ++i) { if (tile.data.imagery[i].readyImagery.imageryLayer === layer2) { indexOfFirstLayer2 = Math.min(indexOfFirstLayer2, i); indexOfLastLayer2 = i; } else { expect(tile.data.imagery[i].readyImagery.imageryLayer).toEqual( layer1 ); indexOfFirstLayer1 = Math.min(indexOfFirstLayer1, i); } } expect(indexOfFirstLayer2).toBeLessThan(indexOfFirstLayer1); expect(indexOfLastLayer2).toBeLessThan(indexOfFirstLayer1); }); }); it("adding a layer creates its skeletons only once", async function() { const provider1 = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); scene2.imageryLayers.addImageryProvider(provider1); await updateUntilDone(scene2.globe); const provider2 = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Green4x4.png" ); const layer2 = scene2.imageryLayers.addImageryProvider(provider2); await updateUntilDone(scene2.globe); forEachRenderedTile(scene2.globe._surface, 1, void 0, function(tile) { expect(tile.data.imagery.length).toBeGreaterThan(0); let tilesFromLayer2 = 0; for (let i = 0; i < tile.data.imagery.length; ++i) { let imageryTile = tile.data.imagery[i].readyImagery; if (!(0, import__483.defined)(imageryTile)) { imageryTile = tile.data.imagery[i].loadingImagery; } if (imageryTile.imageryLayer === layer2) { ++tilesFromLayer2; } } expect(tilesFromLayer2).toBe(1); }); }); it("calling _reload adds a callback per layer per tile", async function() { const provider1 = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); const layer1 = scene2.imageryLayers.addImageryProvider(provider1); const provider2 = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Green4x4.png" ); const layer2 = scene2.imageryLayers.addImageryProvider(provider2); await updateUntilDone(scene2.globe); forEachRenderedTile(scene2.globe._surface, 1, void 0, function(tile) { expect(tile.data.imagery.length).toBe(2); expect(Object.keys(tile._loadedCallbacks).length).toBe(0); }); layer1._imageryProvider._reload(); layer2._imageryProvider._reload(); layer1._imageryProvider._reload(); layer2._imageryProvider._reload(); forEachRenderedTile(scene2.globe._surface, 1, void 0, function(tile) { expect(tile.data.imagery.length).toBe(4); expect(Object.keys(tile._loadedCallbacks).length).toBe(2); }); await updateUntilDone(scene2.globe); forEachRenderedTile(scene2.globe._surface, 1, void 0, function(tile) { expect(tile.data.imagery.length).toBe(2); expect(Object.keys(tile._loadedCallbacks).length).toBe(0); }); }); }, "WebGL" ); it("renders in 2D geographic", async function() { expect(scene2).toRender([0, 0, 0, 255]); const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); scene2.imageryLayers.addImageryProvider(provider); switchViewMode( import__483.SceneMode.SCENE2D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); await updateUntilDone(scene2.globe); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders in 2D web mercator", async function() { expect(scene2).toRender([0, 0, 0, 255]); const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); scene2.imageryLayers.addImageryProvider(provider); switchViewMode( import__483.SceneMode.SCENE2D, new import__483.WebMercatorProjection(import__483.Ellipsoid.WGS84) ); await updateUntilDone(scene2.globe); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders in Columbus View geographic", async function() { expect(scene2).toRender([0, 0, 0, 255]); const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); scene2.imageryLayers.addImageryProvider(provider); switchViewMode( import__483.SceneMode.COLUMBUS_VIEW, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); await updateUntilDone(scene2.globe); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders in Columbus View web mercator", async function() { expect(scene2).toRender([0, 0, 0, 255]); const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); scene2.imageryLayers.addImageryProvider(provider); switchViewMode( import__483.SceneMode.COLUMBUS_VIEW, new import__483.WebMercatorProjection(import__483.Ellipsoid.WGS84) ); await updateUntilDone(scene2.globe); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders in 3D", async function() { expect(scene2).toRender([0, 0, 0, 255]); const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); scene2.imageryLayers.addImageryProvider(provider); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); await updateUntilDone(scene2.globe); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders in 3D (2)", async function() { expect(scene2).toRender([0, 0, 0, 255]); const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); scene2.imageryLayers.addImageryProvider(provider); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); await updateUntilDone(scene2.globe); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders imagery layers according to show property", async function() { await updateUntilDone(scene2.globe); let renderedRed; expect(scene2).toRenderAndCall((rgba) => renderedRed = rgba[0]); const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); const layer = scene2.imageryLayers.addImageryProvider(provider); await updateUntilDone(scene2.globe); expect(scene2).toRenderAndCall( (rgba) => expect(rgba[0]).toBeGreaterThan(renderedRed) ); layer.show = false; await updateUntilDone(scene2.globe); expect(scene2).toRenderAndCall( (rgba) => expect(rgba[0]).toEqual(renderedRed) ); }); it("adds imagery credits to the CreditDisplay based on show property", async function() { const CreditDisplayElement = import__483.CreditDisplay.CreditDisplayElement; const imageryCredit = new import__483.Credit("imagery credit"); const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png", { credit: imageryCredit } ); const layer = scene2.imageryLayers.addImageryProvider(provider); await updateUntilDone(scene2.globe); const creditDisplay = scene2.frameState.creditDisplay; creditDisplay.showLightbox(); expect( creditDisplay._currentFrameCredits.lightboxCredits.values ).toContain(new CreditDisplayElement(imageryCredit)); layer.show = false; await updateUntilDone(scene2.globe); expect( creditDisplay._currentFrameCredits.lightboxCredits.values ).not.toContain(new CreditDisplayElement(imageryCredit)); creditDisplay.hideLightbox(); }); describe("fog", function() { it("culls tiles in full fog", async function() { expect(scene2).toRender([0, 0, 0, 255]); const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); scene2.imageryLayers.addImageryProvider(provider); const oldFog = scene2.fog; scene2.fog = new import__483.Fog(); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); scene2.camera.lookUp(1.2); await updateUntilDone(scene2.globe); expect(scene2).notToRender([0, 0, 0, 255]); scene2.fog.enabled = true; scene2.fog.density = 1; scene2.fog.screenSpaceErrorFactor = 0; expect(scene2).toRender([0, 0, 0, 255]); scene2.fog = oldFog; }); it("culls tiles but does not render fog visuals when renderable is false", async function() { expect(scene2).toRender([0, 0, 0, 255]); const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); scene2.imageryLayers.addImageryProvider(provider); const oldFog = scene2.fog; scene2.fog = new import__483.Fog(); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); scene2.camera.lookUp(1.2); await updateUntilDone(scene2.globe); expect(scene2).notToRender([0, 0, 0, 255]); scene2.fog.enabled = true; scene2.fog.density = 1e-3; scene2.fog.screenSpaceErrorFactor = 0; let result; expect(scene2).toRenderAndCall(function(rgba) { result = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); }); scene2.fog.renderable = false; expect(scene2).notToRender(result); expect(scene2).notToRender([0, 0, 0, 255]); scene2.fog = oldFog; }); it("culls tiles because of increased SSE", async function() { expect(scene2).toRender([0, 0, 0, 255]); const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); scene2.imageryLayers.addImageryProvider(provider); const oldFog = scene2.fog; scene2.fog = new import__483.Fog(); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); scene2.camera.lookUp(1.2); await updateUntilDone(scene2.globe); expect(scene2).notToRender([0, 0, 0, 255]); scene2.fog.enabled = true; scene2.fog.density = 1e-3; scene2.fog.screenSpaceErrorFactor = 0; let result; expect(scene2).toRenderAndCall(function(rgba) { result = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); }); scene2.fog.screenSpaceErrorFactor = 1e4; expect(scene2).notToRender(result); scene2.fog = oldFog; }); }); it("can change baseColor", function() { expect(scene2).toRender([0, 0, 0, 255]); scene2.globe.baseColor = import__483.Color.RED; scene2.fog.enabled = false; switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); return updateUntilDone(scene2.globe).then(function() { expect(scene2).toRender([255, 0, 0, 255]); }); }); it("renders in 3D and then Columbus View", async function() { const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); scene2.imageryLayers.addImageryProvider(provider); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); await updateUntilDone(scene2.globe); expect(scene2).notToRender([0, 0, 0, 255]); switchViewMode( import__483.SceneMode.COLUMBUS_VIEW, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); await updateUntilDone(scene2.globe); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders even if imagery root tiles fail to load", function() { expect(scene2).toRender([0, 0, 0, 255]); const providerWithInvalidRootTiles = new import__483.WebMapServiceImageryProvider({ url: "/invalid", layers: "invalid" }); scene2.imageryLayers.addImageryProvider(providerWithInvalidRootTiles); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); return updateUntilDone(scene2.globe).then(function() { expect(scene2).notToRender([0, 0, 0, 255]); }); }); it("passes layer adjustment values as uniforms", async function() { expect(scene2).toRender([0, 0, 0, 255]); const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); const layer = scene2.imageryLayers.addImageryProvider(provider); layer.alpha = 0.123; layer.nightAlpha = 0.658; layer.dayAlpha = 0.356; layer.brightness = 0.456; layer.contrast = 0.654; layer.gamma = 0.321; layer.saturation = 0.123; layer.hue = 0.456; layer.splitDirection = import__483.SplitDirection.LEFT; switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); await updateUntilDone(scene2.globe); expect(scene2).notToRender([0, 0, 0, 255]); let tileCommandCount = 0; const commandList = scene2.frameState.commandList; for (let i = 0; i < commandList.length; ++i) { const command = commandList[i]; const uniforms = command.uniformMap; if (!(0, import__483.defined)(uniforms) || !(0, import__483.defined)(uniforms.u_dayTextureAlpha)) { continue; } ++tileCommandCount; expect(uniforms.u_dayTextureAlpha()).toEqual([0.123]); expect(uniforms.u_dayTextureNightAlpha()).toEqual([0.658]); expect(uniforms.u_dayTextureDayAlpha()).toEqual([0.356]); expect(uniforms.u_dayTextureBrightness()).toEqual([0.456]); expect(uniforms.u_dayTextureContrast()).toEqual([0.654]); expect(uniforms.u_dayTextureOneOverGamma()).toEqual([1 / 0.321]); expect(uniforms.u_dayTextureSaturation()).toEqual([0.123]); expect(uniforms.u_dayTextureHue()).toEqual([0.456]); expect(uniforms.u_dayTextureSplit()).toEqual([import__483.SplitDirection.LEFT]); } expect(tileCommandCount).toBeGreaterThan(0); }); it("renders imagery cutout", async function() { expect(scene2).toRender([0, 0, 0, 255]); const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); const layer = scene2.imageryLayers.addImageryProvider(provider); layer.cutoutRectangle = cameraDestination; switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); let baseColor; await updateUntilDone(scene2.globe); expect(scene2).toRenderAndCall(function(rgba) { baseColor = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); }); layer.cutoutRectangle = void 0; await updateUntilDone(scene2.globe); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual(baseColor); expect(rgba).not.toEqual([0, 0, 0, 255]); }); }); it("renders imagery with color-to-alpha", async function() { expect(scene2).toRender([0, 0, 0, 255]); const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); const layer = scene2.imageryLayers.addImageryProvider(provider); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); let layerColor; await updateUntilDone(scene2.globe); expect(scene2).toRenderAndCall(function(rgba) { layerColor = rgba; expect(layerColor[0]).toBeGreaterThan(layerColor[1]); expect(layerColor[0]).toBeGreaterThan(layerColor[2]); }); layer.colorToAlpha = new import__483.Color(1, 0, 0); layer.colorToAlphaThreshold = 0.1; await updateUntilDone(scene2.globe); const commandList = scene2.frameState.commandList; for (let i = 0; i < commandList.length; ++i) { const command = commandList[i]; const uniforms = command.uniformMap; if (!(0, import__483.defined)(uniforms) || !(0, import__483.defined)(uniforms.u_dayTextureAlpha)) { continue; } expect(uniforms.u_colorsToAlpha()).toEqual([ new import__483.Cartesian4(1, 0, 0, 0.1) ]); } expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual(layerColor); }); }); it("skips layer with uniform alpha value of zero", async function() { const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); const layer = scene2.imageryLayers.addImageryProvider(provider); layer.alpha = 0; switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); await updateUntilDone(scene2.globe); expect(scene2).notToRender([0, 0, 0, 255]); let tileCommandCount = 0; const commandList = scene2.frameState.commandList; for (let i = 0; i < commandList.length; ++i) { const command = commandList[i]; const uniforms = command.uniformMap; if (!(0, import__483.defined)(uniforms) || !(0, import__483.defined)(uniforms.u_dayTextureAlpha)) { continue; } ++tileCommandCount; expect(uniforms.u_dayTextureAlpha()).toEqual([]); } expect(tileCommandCount).toBeGreaterThan(0); }); it("can render more imagery layers than the available texture units", async function() { const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); for (let i = 0; i < import__483.ContextLimits.maximumTextureImageUnits + 1; ++i) { scene2.imageryLayers.addImageryProvider(provider); } switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); await updateUntilDone(scene2.globe); expect(scene2).notToRender([0, 0, 0, 255]); const renderStateWithAlphaBlending = import__483.RenderState.fromCache({ blending: import__483.BlendingState.ALPHA_BLEND }); const drawCommandsPerTile = {}; const commandList = scene2.frameState.commandList; for (let i = 0; i < commandList.length; ++i) { const command = commandList[i]; if (command.owner instanceof import__483.QuadtreeTile) { const tile = command.owner; const key = `L${tile.level}X${tile.x}Y${tile.y}`; if (!(0, import__483.defined)(drawCommandsPerTile[key])) { drawCommandsPerTile[key] = 0; expect(command.renderState.blending).not.toEqual( renderStateWithAlphaBlending.blending ); } else { expect(command.renderState.blending).toEqual( renderStateWithAlphaBlending.blending ); expect(command.uniformMap.u_initialColor().w).toEqual(0); } ++drawCommandsPerTile[key]; } } let tileCount = 0; for (const tileID in drawCommandsPerTile) { if (drawCommandsPerTile.hasOwnProperty(tileID)) { ++tileCount; expect(drawCommandsPerTile[tileID]).toBeGreaterThanOrEqual(2); } } expect(tileCount).toBeGreaterThanOrEqual(1); }); it("adds terrain and imagery credits to the CreditDisplay", async function() { const CreditDisplayElement = import__483.CreditDisplay.CreditDisplayElement; const imageryCredit = new import__483.Credit("imagery credit"); const provider = await import__483.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png", { credit: imageryCredit } ); scene2.imageryLayers.addImageryProvider(provider); const terrainCredit = new import__483.Credit("terrain credit"); import__483.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { if ((0, import__483.defined)(url.match(/\/\d+\/\d+\/\d+\.terrain/))) { import__483.Resource._DefaultImplementations.loadWithXhr( "Data/CesiumTerrainTileJson/tile.32bitIndices.terrain", responseType, method, data, headers, deferred ); return; } import__483.Resource._DefaultImplementations.loadWithXhr( url, responseType, method, data, headers, deferred, overrideMimeType ); }; scene2.terrainProvider = await import__483.CesiumTerrainProvider.fromUrl( "Data/CesiumTerrainTileJson/QuantizedMesh.tile.json", { credit: terrainCredit } ); await updateUntilDone(scene2.globe); const creditDisplay = scene2.frameState.creditDisplay; creditDisplay.showLightbox(); expect( creditDisplay._currentFrameCredits.lightboxCredits.values ).toContain(new CreditDisplayElement(imageryCredit)); expect( creditDisplay._currentFrameCredits.lightboxCredits.values ).toContain(new CreditDisplayElement(terrainCredit)); creditDisplay.hideLightbox(); }); describe( "switching terrain providers", function() { it("clears the replacement queue", function() { return updateUntilDone(scene2.globe).then(function() { const surface = scene2.globe._surface; const replacementQueue = surface._tileReplacementQueue; expect(replacementQueue.count).toBeGreaterThan(0); const oldTile = replacementQueue.head; surface.tileProvider.terrainProvider = new import__483.EllipsoidTerrainProvider(); scene2.renderForSpecs(); expect(replacementQueue.count).toBeGreaterThan(0); expect(replacementQueue.head).not.toBe(oldTile); }); }); it("recreates the level zero tiles", function() { const surface = scene2.globe._surface; scene2.renderForSpecs(); let levelZeroTiles = surface._levelZeroTiles; expect(levelZeroTiles.length).toBe(2); const levelZero0 = levelZeroTiles[0]; const levelZero1 = levelZeroTiles[1]; surface.tileProvider.terrainProvider = new import__483.EllipsoidTerrainProvider(); scene2.renderForSpecs(); scene2.renderForSpecs(); levelZeroTiles = surface._levelZeroTiles; expect(levelZeroTiles[0]).not.toBe(levelZero0); expect(levelZeroTiles[1]).not.toBe(levelZero1); }); it("does nothing if the new provider is the same as the old", function() { const surface = scene2.globe._surface; const provider = surface.tileProvider.terrainProvider; scene2.renderForSpecs(); let levelZeroTiles = surface._levelZeroTiles; expect(levelZeroTiles.length).toBe(2); const levelZero0 = levelZeroTiles[0]; const levelZero1 = levelZeroTiles[1]; surface.tileProvider.terrainProvider = provider; scene2.renderForSpecs(); levelZeroTiles = surface._levelZeroTiles; expect(levelZeroTiles[0]).toBe(levelZero0); expect(levelZeroTiles[1]).toBe(levelZero1); }); }, "WebGL" ); it("renders back side of globe when camera is near the poles", function() { const camera = scene2.camera; camera.position = new import__483.Cartesian3( 2.9090781077849553e6, -3893505340234136e-8, -6325240094628872e-8 ); camera.direction = new import__483.Cartesian3( -0.03928753135806185, 0.44884096070717633, 0.8927476025569903 ); camera.up = new import__483.Cartesian3( 2847975895320034e-20, -0.8934368803055558, 0.4491887577613425 ); camera.right = new import__483.Cartesian3( 0.99922794650124, 0.017672942642764363, 0.03508814656908402 ); scene2.cullingVolume = camera.frustum.computeCullingVolume( camera.position, camera.direction, camera.up ); return updateUntilDone(scene2.globe).then(function() { forEachRenderedTile(scene2.globe._surface, 2, 2, function(tile) { }); }); }); it("throws if baseColor is assigned undefined", function() { expect(function() { scene2.globe._surface.tileProvider.baseColor = void 0; }).toThrowDeveloperError(); }); it("clipping planes selectively disable rendering globe surface", function() { expect(scene2).toRender([0, 0, 0, 255]); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); return updateUntilDone(scene2.globe).then(function() { expect(scene2).notToRender([0, 0, 0, 255]); let result; expect(scene2).toRenderAndCall(function(rgba) { result = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); }); const clipPlane = new import__483.ClippingPlane(import__483.Cartesian3.UNIT_Z, -1e4); scene2.globe.clippingPlanes = new import__483.ClippingPlaneCollection({ planes: [clipPlane] }); expect(scene2).notToRender(result); clipPlane.distance = 0; expect(scene2).toRender(result); scene2.globe.clippingPlanes = void 0; }); }); it("renders with clipping planes edge styling on globe surface", function() { expect(scene2).toRender([0, 0, 0, 255]); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); return updateUntilDone(scene2.globe).then(function() { expect(scene2).notToRender([0, 0, 0, 255]); let result; expect(scene2).toRenderAndCall(function(rgba) { result = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); }); const clipPlane = new import__483.ClippingPlane(import__483.Cartesian3.UNIT_Z, -1e3); scene2.globe.clippingPlanes = new import__483.ClippingPlaneCollection({ planes: [clipPlane], edgeWidth: 20, edgeColor: import__483.Color.RED }); expect(scene2).notToRender(result); clipPlane.distance = 0; expect(scene2).toRender([255, 0, 0, 255]); scene2.globe.clippingPlanes = void 0; }); }); it("renders with multiple clipping planes clipping regions according to the value of unionClippingPlane", function() { expect(scene2).toRender([0, 0, 0, 255]); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); return updateUntilDone(scene2.globe).then(function() { expect(scene2).notToRender([0, 0, 0, 255]); let result; expect(scene2).toRenderAndCall(function(rgba) { result = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); }); scene2.globe.clippingPlanes = new import__483.ClippingPlaneCollection({ planes: [ new import__483.ClippingPlane(import__483.Cartesian3.UNIT_Z, -1e4), new import__483.ClippingPlane(import__483.Cartesian3.UNIT_X, -1e3) ], unionClippingRegions: true }); expect(scene2).notToRender(result); scene2.globe.clippingPlanes.unionClippingRegions = false; expect(scene2).toRender(result); scene2.globe.clippingPlanes = void 0; }); }); it("No extra tiles culled with no clipping planes", function() { const globe2 = scene2.globe; switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); return updateUntilDone(globe2).then(function() { expect(scene2.frameState.commandList.length).toBe(4); }); }); it("Culls tiles when completely inside clipping region", function() { const globe2 = scene2.globe; globe2.clippingPlanes = new import__483.ClippingPlaneCollection({ planes: [new import__483.ClippingPlane(import__483.Cartesian3.UNIT_Z, -1e6)] }); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); return updateUntilDone(globe2).then(function() { const surface = globe2._surface; const tile = surface._levelZeroTiles[0]; expect(tile.isClipped).toBe(true); expect(scene2.frameState.commandList.length).toBe(2); }); }); it("Doesn't cull, but clips tiles when intersecting clipping plane", function() { const globe2 = scene2.globe; globe2.clippingPlanes = new import__483.ClippingPlaneCollection({ planes: [new import__483.ClippingPlane(import__483.Cartesian3.UNIT_Z, 0)] }); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); return updateUntilDone(globe2).then(function() { const surface = globe2._surface; const tile = surface._levelZeroTiles[0]; expect(tile.isClipped).toBe(true); expect(scene2.frameState.commandList.length).toBe(4); }); }); it("Doesn't cull or clip tiles when completely outside clipping region", function() { const globe2 = scene2.globe; globe2.clippingPlanes = new import__483.ClippingPlaneCollection({ planes: [new import__483.ClippingPlane(import__483.Cartesian3.UNIT_Z, 1e7)] }); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); return updateUntilDone(globe2).then(function() { const surface = globe2._surface; const tile = surface._levelZeroTiles[0]; expect(tile.isClipped).toBe(false); expect(scene2.frameState.commandList.length).toBe(4); }); }); it("destroys attached ClippingPlaneCollections that have been detached", function() { const clippingPlanes = new import__483.ClippingPlaneCollection({ planes: [new import__483.ClippingPlane(import__483.Cartesian3.UNIT_Z, 1e7)] }); const globe2 = scene2.globe; globe2.clippingPlanes = clippingPlanes; expect(clippingPlanes.isDestroyed()).toBe(false); globe2.clippingPlanes = void 0; expect(clippingPlanes.isDestroyed()).toBe(true); }); it("throws a DeveloperError when given a ClippingPlaneCollection attached to a Model", async function() { const clippingPlanes = new import__483.ClippingPlaneCollection({ planes: [new import__483.ClippingPlane(import__483.Cartesian3.UNIT_Z, 1e7)] }); const model = scene2.primitives.add( await import__483.Model.fromGltfAsync({ url: "./Data/Models/glTF-2.0/BoxTextured/glTF/BoxTextured.gltf" }) ); model.clippingPlanes = clippingPlanes; const globe2 = scene2.globe; expect(function() { globe2.clippingPlanes = clippingPlanes; }).toThrowDeveloperError(); }); describe("clippingPolygons", () => { const positions = import__483.Cartesian3.fromRadiansArray([ -1.3194369277314022, 0.6988062530900625, -1.31941, 0.69879, -1.3193955980204217, 0.6988091578771254, -1.3193931220959367, 0.698743632490865, -1.3194358224045408, 0.6987471965556998 ]); let polygon; beforeEach(() => { polygon = new import__483.ClippingPolygon({ positions }); }); it("selectively disable rendering globe surface", async function() { if (!scene2.context.webgl2) { return; } expect(scene2).toRender([0, 0, 0, 255]); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); await updateUntilDone(scene2.globe); expect(scene2).notToRender([0, 0, 0, 255]); let result; expect(scene2).toRenderAndCall(function(rgba) { result = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); }); scene2.globe.clippingPolygons = new import__483.ClippingPolygonCollection({ polygons: [polygon] }); expect(scene2).toRender(result); scene2.globe.clippingPolygons.inverse = true; expect(scene2).not.toRender(result); scene2.globe.clippingPolygons = void 0; }); it("renders with multiple clipping regions", async function() { if (!scene2.context.webgl2) { return; } expect(scene2).toRender([0, 0, 0, 255]); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); await updateUntilDone(scene2.globe); expect(scene2).notToRender([0, 0, 0, 255]); let result; expect(scene2).toRenderAndCall(function(rgba) { result = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); }); const positionsB = import__483.Cartesian3.fromDegreesArray([ 153.03383443542293, -27.569622925766826, 153.03383608252798, -27.56961689989725, 153.03390570198877, -27.569628939963906, 153.0339997791706, -27.569639093357882 ]); scene2.globe.clippingPolygons = new import__483.ClippingPolygonCollection({ polygons: [polygon, new import__483.ClippingPolygon({ positions: positionsB })] }); expect(scene2).toRender(result); scene2.globe.clippingPolygons.inverse = true; expect(scene2).not.toRender(result); scene2.globe.clippingPolygons = void 0; }); it("Clips tiles when completely inside clipping region", async function() { if (!scene2.context.webgl2) { return; } const globe2 = scene2.globe; scene2.globe.clippingPolygons = new import__483.ClippingPolygonCollection({ polygons: [polygon], inverse: true }); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); await updateUntilDone(globe2); const surface = globe2._surface; const tile = surface._levelZeroTiles[0]; expect(tile.isClipped).toBe(true); }); it("Clips tiles that intersect a clipping region", async function() { if (!scene2.context.webgl2) { return; } const globe2 = scene2.globe; scene2.globe.clippingPolygons = new import__483.ClippingPolygonCollection({ polygons: [polygon] }); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); await updateUntilDone(globe2); const surface = globe2._surface; const tile = surface._levelZeroTiles[1]; expect(tile.isClipped).toBe(true); }); it("Doesn't clip tiles when completely outside clipping region", async function() { if (!scene2.context.webgl2) { return; } const globe2 = scene2.globe; scene2.globe.clippingPolygons = new import__483.ClippingPolygonCollection({ polygons: [polygon] }); switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); await updateUntilDone(globe2); const surface = globe2._surface; const tile = surface._levelZeroTiles[0]; expect(tile.isClipped).toBe(false); }); it("destroys attached ClippingPolygonCollections that have been detached", function() { const globe2 = scene2.globe; const collection = new import__483.ClippingPolygonCollection({ polygons: [polygon] }); globe2.clippingPolygons = collection; expect(collection.isDestroyed()).toBe(false); globe2.clippingPolygons = void 0; expect(collection.isDestroyed()).toBe(true); }); it("throws a DeveloperError when given a ClippingPolygonCollection attached to a Model", async function() { const collection = new import__483.ClippingPolygonCollection({ polygons: [polygon] }); const model = scene2.primitives.add( await import__483.Model.fromGltfAsync({ url: "./Data/Models/glTF-2.0/BoxTextured/glTF/BoxTextured.gltf" }) ); model.clippingPolygons = collection; const globe2 = scene2.globe; expect(function() { globe2.clippingPolygons = collection; }).toThrowDeveloperError(); }); }); it("cartographicLimitRectangle selectively enables rendering globe surface", function() { expect(scene2).toRender([0, 0, 0, 255]); switchViewMode( import__483.SceneMode.COLUMBUS_VIEW, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); let result; return updateUntilDone(scene2.globe).then(function() { expect(scene2).notToRender([0, 0, 0, 255]); expect(scene2).toRenderAndCall(function(rgba) { result = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); }); scene2.globe.cartographicLimitRectangle = import__483.Rectangle.fromDegrees( -2, -2, -1, -1 ); expect(scene2).notToRender(result); scene2.camera.setView({ destination: scene2.globe.cartographicLimitRectangle }); return updateUntilDone(scene2.globe); }).then(function() { expect(scene2).toRender(result); }); }); it("cartographicLimitRectangle defaults to Rectangle.MAX_VALUE", function() { scene2.globe.cartographicLimitRectangle = void 0; expect( scene2.globe.cartographicLimitRectangle.equals(import__483.Rectangle.MAX_VALUE) ).toBe(true); }); it("cartographicLimitRectangle culls tiles outside the region", function() { switchViewMode( import__483.SceneMode.COLUMBUS_VIEW, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); let unculledCommandCount; return updateUntilDone(scene2.globe).then(function() { unculledCommandCount = scene2.frameState.commandList.length; scene2.globe.cartographicLimitRectangle = import__483.Rectangle.fromDegrees( -2, -2, -1, -1 ); return updateUntilDone(scene2.globe); }).then(function() { expect(unculledCommandCount).toBeGreaterThan( scene2.frameState.commandList.length ); }); }); it("cartographicLimitRectangle may cross the antimeridian", function() { switchViewMode( import__483.SceneMode.SCENE2D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); let unculledCommandCount; return updateUntilDone(scene2.globe).then(function() { unculledCommandCount = scene2.frameState.commandList.length; scene2.globe.cartographicLimitRectangle = import__483.Rectangle.fromDegrees( 179, -2, -179, -1 ); return updateUntilDone(scene2.globe); }).then(function() { expect(unculledCommandCount).toBeGreaterThan( scene2.frameState.commandList.length ); }); }); it("disables skirts and enables back face culling when camera is underground", function() { switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); return updateUntilDone(scene2.globe).then(function() { const command = scene2.frameState.commandList[0]; expect(command.count).toBe( command.owner.data.renderedMesh.indices.length ); expect(command.renderState.cull.enabled).toBe(true); scene2.camera.setView({ destination: new import__483.Cartesian3( -746658.0557573901, -5.6441910002196245e6, 2863585099969967e-9 ), orientation: new import__483.HeadingPitchRoll( 0.3019699121236403, 0.07316306869231592, 7089903642230055e-19 ) }); return updateUntilDone(scene2.globe); }).then(function() { const command = scene2.frameState.commandList[0]; expect(command.count).toBe( command.owner.data.renderedMesh.indexCountWithoutSkirts ); expect(command.renderState.cull.enabled).toBe(false); }); }); it("Detects change in vertical exaggeration", function() { switchViewMode( import__483.SceneMode.SCENE3D, new import__483.GeographicProjection(import__483.Ellipsoid.WGS84) ); scene2.camera.flyHome(0); scene2.verticalExaggeration = 1; scene2.verticalExaggerationRelativeHeight = 0; return updateUntilDone(scene2.globe).then(function() { forEachRenderedTile(scene2.globe._surface, 1, void 0, function(tile) { const surfaceTile = tile.data; const encoding = surfaceTile.mesh.encoding; const boundingSphere = surfaceTile.tileBoundingRegion.boundingSphere; expect(encoding.exaggeration).toEqual(1); expect(encoding.hasGeodeticSurfaceNormals).toEqual(false); expect(boundingSphere.radius).toBeLessThan(7e6); }); scene2.verticalExaggeration = 2; scene2.verticalExaggerationRelativeHeight = -1e6; return updateUntilDone(scene2.globe).then(function() { forEachRenderedTile(scene2.globe._surface, 1, void 0, function(tile) { const surfaceTile = tile.data; const encoding = surfaceTile.mesh.encoding; const boundingSphere = surfaceTile.tileBoundingRegion.boundingSphere; expect(encoding.exaggeration).toEqual(2); expect(encoding.hasGeodeticSurfaceNormals).toEqual(true); expect(boundingSphere.radius).toBeGreaterThan(7e6); }); scene2.verticalExaggeration = 1; scene2.verticalExaggerationRelativeHeight = 0; return updateUntilDone(scene2.globe).then(function() { forEachRenderedTile(scene2.globe._surface, 1, void 0, function(tile) { const surfaceTile = tile.data; const encoding = surfaceTile.mesh.encoding; const boundingSphere = surfaceTile.tileBoundingRegion.boundingSphere; expect(encoding.exaggeration).toEqual(1); expect(encoding.hasGeodeticSurfaceNormals).toEqual(false); expect(boundingSphere.radius).toBeLessThan(7e6); }); }); }); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/GlobeSurfaceTileSpec.js var import__484 = __toESM(require_Cesium(), 1); // Specs/createTileKey.js var import_engine21 = __toESM(require_Cesium(), 1); function createTileKey(xOrTile, y, level) { if (!(0, import_engine21.defined)(xOrTile)) { throw new import_engine21.DeveloperError("xOrTile is required"); } if (typeof xOrTile === "object") { const tile = xOrTile; xOrTile = tile.x; y = tile.y; level = tile.level; } return `L${level}X${xOrTile}Y${y}`; } var createTileKey_default = createTileKey; // Specs/runLater.js var import_engine22 = __toESM(require_Cesium(), 1); function runLater(functionToRunLater, milliseconds) { milliseconds = (0, import_engine22.defaultValue)(milliseconds, 0); return new Promise((resolve, reject) => { setTimeout(function() { try { resolve(functionToRunLater()); } catch (e) { reject(e); } }, milliseconds); }); } var runLater_default = runLater; // Specs/MockImageryProvider.js var import_engine23 = __toESM(require_Cesium(), 1); function MockImageryProvider() { this.tilingScheme = new import_engine23.GeographicTilingScheme(); this.rectangle = this.tilingScheme.rectangle; this.tileWidth = 256; this.tileHeight = 256; this.errorEvent = new import_engine23.Event(); this._requestImageWillSucceed = {}; } MockImageryProvider.prototype.requestImage = function(x, y, level, request) { const willSucceed = this._requestImageWillSucceed[createTileKey_default(x, y, level)]; if (willSucceed === void 0) { return void 0; } return runLater_default(function() { if (willSucceed === true) { return import_engine23.Resource.fetchImage("./Data/Images/Green.png"); } else if (willSucceed === false) { throw new import_engine23.RuntimeError("requestImage failed as request."); } return Promise.resolve(willSucceed).then(function() { return import_engine23.Resource.fetchImage("./Data/Images/Green.png"); }); }); }; MockImageryProvider.prototype.requestImageWillSucceed = function(xOrTile, y, level) { this._requestImageWillSucceed[createTileKey_default(xOrTile, y, level)] = true; return this; }; MockImageryProvider.prototype.requestImageWillFail = function(xOrTile, y, level) { this._requestImageWillSucceed[createTileKey_default(xOrTile, y, level)] = false; return this; }; MockImageryProvider.prototype.requestImageWillDefer = function(xOrTile, y, level) { this._requestImageWillSucceed[createTileKey_default(xOrTile, y, level)] = void 0; return this; }; MockImageryProvider.prototype.requestImageWillWaitOn = function(promise, xOrTile, y, level) { this._requestImageWillSucceed[createTileKey_default(xOrTile, y, level)] = promise; return this; }; var MockImageryProvider_default = MockImageryProvider; // Specs/MockTerrainProvider.js var import_engine24 = __toESM(require_Cesium(), 1); function MockTerrainProvider() { this.tilingScheme = new import_engine24.GeographicTilingScheme(); this.heightmapWidth = 65; this.levelZeroMaximumGeometricError = import_engine24.TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap( this.tilingScheme.ellipsoid, this.heightmapWidth, this.tilingScheme.getNumberOfXTilesAtLevel(0) ); this.hasWaterMask = true; this.errorEvent = new import_engine24.Event(); this._tileDataAvailable = {}; this._requestTileGeometryWillSucceed = {}; this._requestTileGeometryWillSucceedWith = {}; this._willHaveWaterMask = {}; this._createMeshWillSucceed = {}; this._upsampleWillSucceed = {}; } MockTerrainProvider.prototype.requestTileGeometry = function(x, y, level, request) { const willSucceed = this._requestTileGeometryWillSucceed[createTileKey_default(x, y, level)]; if (willSucceed === void 0) { return void 0; } const that = this; return runLater_default(function() { if (willSucceed === true) { return createTerrainData(that, x, y, level, false); } else if (willSucceed === false) { throw new import_engine24.RuntimeError("requestTileGeometry failed as requested."); } return Promise.resolve(willSucceed).then(function() { return createTerrainData(that, x, y, level, false); }); }); }; MockTerrainProvider.prototype.getTileDataAvailable = function(xOrTile, y, level) { return this._tileDataAvailable[createTileKey_default(xOrTile, y, level)]; }; MockTerrainProvider.prototype.getLevelMaximumGeometricError = function(level) { return this.levelZeroMaximumGeometricError / (1 << level); }; MockTerrainProvider.prototype.requestTileGeometryWillSucceed = function(xOrTile, y, level) { this._requestTileGeometryWillSucceed[createTileKey_default(xOrTile, y, level)] = true; return this; }; MockTerrainProvider.prototype.requestTileGeometryWillSucceedWith = function(terrainData, xOrTile, y, level) { this._requestTileGeometryWillSucceed[createTileKey_default(xOrTile, y, level)] = true; this._requestTileGeometryWillSucceedWith[createTileKey_default(xOrTile, y, level)] = terrainData; return this; }; MockTerrainProvider.prototype.requestTileGeometryWillFail = function(xOrTile, y, level) { this._requestTileGeometryWillSucceed[createTileKey_default(xOrTile, y, level)] = false; return this; }; MockTerrainProvider.prototype.requestTileGeometryWillDefer = function(xOrTile, y, level) { this._requestTileGeometryWillSucceed[createTileKey_default(xOrTile, y, level)] = void 0; return this; }; MockTerrainProvider.prototype.requestTileGeometryWillWaitOn = function(promise, xOrTile, y, level) { this._requestTileGeometryWillSucceed[createTileKey_default(xOrTile, y, level)] = promise; return this; }; MockTerrainProvider.prototype.willHaveWaterMask = function(includeLand, includeWater, xOrTile, y, level) { this._willHaveWaterMask[createTileKey_default(xOrTile, y, level)] = includeLand || includeWater ? { includeLand, includeWater } : void 0; return this; }; MockTerrainProvider.prototype.createMeshWillSucceed = function(xOrTile, y, level) { this._createMeshWillSucceed[createTileKey_default(xOrTile, y, level)] = true; return this; }; MockTerrainProvider.prototype.createMeshWillFail = function(xOrTile, y, level) { this._createMeshWillSucceed[createTileKey_default(xOrTile, y, level)] = false; return this; }; MockTerrainProvider.prototype.createMeshWillDefer = function(xOrTile, y, level) { this._createMeshWillSucceed[createTileKey_default(xOrTile, y, level)] = void 0; return this; }; MockTerrainProvider.prototype.createMeshWillWaitOn = function(promise, xOrTile, y, level) { this._createMeshWillSucceed[createTileKey_default(xOrTile, y, level)] = promise; return this; }; MockTerrainProvider.prototype.upsampleWillSucceed = function(xOrTile, y, level) { this._upsampleWillSucceed[createTileKey_default(xOrTile, y, level)] = true; return this; }; MockTerrainProvider.prototype.upsampleWillFail = function(xOrTile, y, level) { this._upsampleWillSucceed[createTileKey_default(xOrTile, y, level)] = false; return this; }; MockTerrainProvider.prototype.upsampleWillDefer = function(xOrTile, y, level) { this._upsampleWillSucceed[createTileKey_default(xOrTile, y, level)] = void 0; return this; }; MockTerrainProvider.prototype.willBeAvailable = function(xOrTile, y, level) { this._tileDataAvailable[createTileKey_default(xOrTile, y, level)] = true; return this; }; MockTerrainProvider.prototype.willBeUnavailable = function(xOrTile, y, level) { this._tileDataAvailable[createTileKey_default(xOrTile, y, level)] = false; return this; }; MockTerrainProvider.prototype.willBeUnknownAvailability = function(xOrTile, y, level) { this._tileDataAvailable[createTileKey_default(xOrTile, y, level)] = void 0; return this; }; function createTerrainData(terrainProvider, x, y, level, upsampled) { let terrainData = terrainProvider._requestTileGeometryWillSucceedWith[createTileKey_default(x, y, level)]; if (!(0, import_engine24.defined)(terrainData)) { const options = { width: 5, height: 5, buffer: new Float32Array(25), createdByUpsampling: upsampled }; const willHaveWaterMask = terrainProvider._willHaveWaterMask[createTileKey_default(x, y, level)]; if ((0, import_engine24.defined)(willHaveWaterMask)) { if (willHaveWaterMask.includeLand && willHaveWaterMask.includeWater) { options.waterMask = new Uint8Array(4); options.waterMask[0] = 1; options.waterMask[1] = 1; options.waterMask[2] = 0; options.waterMask[3] = 0; } else if (willHaveWaterMask.includeLand) { options.waterMask = new Uint8Array(1); options.waterMask[0] = 0; } else if (willHaveWaterMask.includeWater) { options.waterMask = new Uint8Array(1); options.waterMask[0] = 1; } } terrainData = new import_engine24.HeightmapTerrainData(options); } const originalUpsample = terrainData.upsample; terrainData.upsample = function(tilingScheme, thisX, thisY, thisLevel, descendantX, descendantY) { const willSucceed = terrainProvider._upsampleWillSucceed[createTileKey_default(descendantX, descendantY, thisLevel + 1)]; if (willSucceed === void 0) { return void 0; } if (willSucceed) { return originalUpsample.apply(terrainData, arguments); } return runLater_default(function() { throw new import_engine24.RuntimeError("upsample failed as requested."); }); }; const originalCreateMesh = terrainData.createMesh; terrainData.createMesh = function(options) { const x2 = options.x; const y2 = options.y; const level2 = options.level; const willSucceed = terrainProvider._createMeshWillSucceed[createTileKey_default(x2, y2, level2)]; if (willSucceed === void 0) { return void 0; } if (willSucceed === true) { return originalCreateMesh.apply(terrainData, arguments); } else if (willSucceed === false) { return runLater_default(function() { throw new import_engine24.RuntimeError("createMesh failed as requested."); }); } const args = arguments; return runLater_default(function() { return Promise.resolve(willSucceed).then(function() { return originalCreateMesh.apply(terrainData, args); }); }); }; return terrainData; } var MockTerrainProvider_default = MockTerrainProvider; // Specs/TerrainTileProcessor.js var import_engine25 = __toESM(require_Cesium(), 1); function TerrainTileProcessor(frameState2, terrainProvider, imageryLayerCollection) { this.frameState = frameState2; this.terrainProvider = terrainProvider; this.imageryLayerCollection = imageryLayerCollection; } TerrainTileProcessor.prototype.process = function(tiles, maxIterations) { const that = this; function getState(tile) { return [ tile.state, tile.data ? tile.data.terrainState : void 0, tile.data && tile.data.imagery ? tile.data.imagery.map(function(imagery) { return [ imagery.readyImagery ? imagery.readyImagery.state : void 0, imagery.loadingImagery ? imagery.loadingImagery.state : void 0 ]; }) : [] ]; } function statesAreSame(a, b) { if (a.length !== b.length) { return false; } let same = true; for (let i = 0; i < a.length; ++i) { if (Array.isArray(a[i]) && Array.isArray(b[i])) { same = same && statesAreSame(a[i], b[i]); } else if (Array.isArray(a[i]) || Array.isArray(b[i])) { same = false; } else { same = same && a[i] === b[i]; } } return same; } return new Promise((resolve) => { let iterations = 0; function next() { ++iterations; ++that.frameState.frameNumber; let changed = false; tiles.forEach(function(tile) { const beforeState = getState(tile); import_engine25.GlobeSurfaceTile.processStateMachine( tile, that.frameState, that.terrainProvider, that.imageryLayerCollection ); const afterState = getState(tile); changed = changed || tile.data.terrainState === import_engine25.TerrainState.RECEIVING || tile.data.terrainState === import_engine25.TerrainState.TRANSFORMING || !statesAreSame(beforeState, afterState); }); if (!changed || iterations >= maxIterations) { resolve(iterations); } else { setTimeout(next, 0); } } next(); }); }; TerrainTileProcessor.prototype.mockWebGL = function() { spyOn(import_engine25.GlobeSurfaceTile, "_createVertexArrayForMesh").and.callFake( function() { const vertexArray = jasmine.createSpyObj("VertexArray", [ "destroy", "isDestroyed" ]); return vertexArray; } ); spyOn(import_engine25.ImageryLayer.prototype, "_createTextureWebGL").and.callFake(function(context, imagery) { const texture = jasmine.createSpyObj("Texture", ["destroy"]); texture.width = imagery.image.width; texture.height = imagery.image.height; return texture; }); spyOn(import_engine25.ImageryLayer.prototype, "_finalizeReprojectTexture"); spyOn(import_engine25.Texture, "create").and.callFake(function(options) { const result = (0, import_engine25.clone)(options); result.destroy = function() { }; return result; }); }; var TerrainTileProcessor_default = TerrainTileProcessor; // packages/engine/Specs/Scene/GlobeSurfaceTileSpec.js describe("Scene/GlobeSurfaceTile", function() { let frameState2; let tilingScheme; let rootTiles; let rootTile; let imageryLayerCollection; let mockTerrain; let processor; beforeEach(function() { frameState2 = { context: { cache: {} } }; tilingScheme = new import__484.GeographicTilingScheme(); rootTiles = import__484.QuadtreeTile.createLevelZeroTiles(tilingScheme); rootTile = rootTiles[0]; imageryLayerCollection = new import__484.ImageryLayerCollection(); mockTerrain = new MockTerrainProvider_default(); processor = new TerrainTileProcessor_default( frameState2, mockTerrain, imageryLayerCollection ); }); afterEach(function() { for (let i = 0; i < rootTiles.length; ++i) { rootTiles[i].freeResources(); } }); describe("processStateMachine", function() { beforeEach(function() { processor.mockWebGL(); }); it("starts in the START state", function() { for (let i = 0; i < rootTiles.length; ++i) { const tile = rootTiles[i]; expect(tile.state).toBe(import__484.QuadtreeTileLoadState.START); } }); it("transitions to the LOADING state immediately if this tile is available", function() { mockTerrain.willBeAvailable(rootTile.southwestChild); return processor.process([rootTile.southwestChild]).then(function() { expect(rootTile.southwestChild.state).toBe( import__484.QuadtreeTileLoadState.LOADING ); expect(rootTile.southwestChild.data.terrainState).toBe( import__484.TerrainState.UNLOADED ); }); }); it("transitions to the LOADING tile state and FAILED terrain state immediately if this tile is NOT available", function() { mockTerrain.willBeUnavailable(rootTile.southwestChild); return processor.process([rootTile.southwestChild]).then(function() { expect(rootTile.southwestChild.state).toBe( import__484.QuadtreeTileLoadState.LOADING ); expect(rootTile.southwestChild.data.terrainState).toBe( import__484.TerrainState.FAILED ); }); }); it("pushes parent along if waiting on it to be able to upsample", function() { mockTerrain.willBeAvailable(rootTile).requestTileGeometryWillSucceed(rootTile).willBeUnavailable(rootTile.southwestChild); spyOn(mockTerrain, "requestTileGeometry").and.callThrough(); return processor.process([rootTile.southwestChild]).then(function() { expect(mockTerrain.requestTileGeometry.calls.count()).toBe(1); expect(mockTerrain.requestTileGeometry.calls.argsFor(0)[0]).toBe(0); expect(mockTerrain.requestTileGeometry.calls.argsFor(0)[1]).toBe(0); expect(mockTerrain.requestTileGeometry.calls.argsFor(0)[2]).toBe(0); }); }); it("does nothing when a root tile is unavailable", function() { mockTerrain.willBeUnavailable(rootTile); return processor.process([rootTile]).then(function() { expect(rootTile.state).toBe(import__484.QuadtreeTileLoadState.FAILED); expect(rootTile.data.terrainState).toBe(import__484.TerrainState.FAILED); }); }); it("does nothing when a root tile fails to load", function() { mockTerrain.requestTileGeometryWillFail(rootTile); return processor.process([rootTile]).then(function() { expect(rootTile.state).toBe(import__484.QuadtreeTileLoadState.FAILED); expect(rootTile.data.terrainState).toBe(import__484.TerrainState.FAILED); }); }); it("prints error message when a root tile fails to load", function() { spyOn(import__484.TileProviderError, "reportError").and.callThrough(); mockTerrain.requestTileGeometryWillFail(rootTile); return processor.process([rootTile]).then(function() { expect(import__484.TileProviderError.reportError.calls.count()).toBe(1); expect(import__484.TileProviderError.reportError.calls.argsFor(0)[3]).toContain( "RuntimeError: requestTileGeometry failed as requested." ); }); }); it("upsamples failed tiles from parent TerrainData", function() { mockTerrain.requestTileGeometryWillSucceed(rootTile).createMeshWillSucceed(rootTile).willBeUnavailable(rootTile.southwestChild).upsampleWillSucceed(rootTile.southwestChild); return processor.process([rootTile, rootTile.southwestChild]).then(function() { expect(rootTile.data.terrainData.wasCreatedByUpsampling()).toBe( false ); expect( rootTile.southwestChild.data.terrainData.wasCreatedByUpsampling() ).toBe(true); }); }); it("loads available tiles", function() { mockTerrain.willBeAvailable(rootTile.southwestChild).requestTileGeometryWillSucceed(rootTile.southwestChild); spyOn(mockTerrain, "requestTileGeometry").and.callThrough(); return processor.process([rootTile.southwestChild]).then(function() { expect(mockTerrain.requestTileGeometry.calls.count()).toBe(1); expect(mockTerrain.requestTileGeometry.calls.argsFor(0)[0]).toBe(0); expect(mockTerrain.requestTileGeometry.calls.argsFor(0)[1]).toBe(1); expect(mockTerrain.requestTileGeometry.calls.argsFor(0)[2]).toBe(1); }); }); it("marks an upsampled tile as such", function() { mockTerrain.willBeAvailable(rootTile).requestTileGeometryWillSucceed(rootTile).createMeshWillSucceed(rootTile).willBeUnavailable(rootTile.southwestChild).upsampleWillSucceed(rootTile.southwestChild).createMeshWillSucceed(rootTile.southwestChild); const mockImagery = new MockImageryProvider_default(); imageryLayerCollection.addImageryProvider(mockImagery); mockImagery.requestImageWillSucceed(rootTile).requestImageWillFail(rootTile.southwestChild); return processor.process([rootTile, rootTile.southwestChild]).then(function() { expect(rootTile.state).toBe(import__484.QuadtreeTileLoadState.DONE); expect(rootTile.upsampledFromParent).toBe(false); expect(rootTile.southwestChild.state).toBe( import__484.QuadtreeTileLoadState.DONE ); expect(rootTile.southwestChild.upsampledFromParent).toBe(true); }); }); it("does not mark a tile as upsampled if it has fresh imagery", function() { mockTerrain.willBeAvailable(rootTile).requestTileGeometryWillSucceed(rootTile).createMeshWillSucceed(rootTile).willBeUnavailable(rootTile.southwestChild).upsampleWillSucceed(rootTile.southwestChild).createMeshWillSucceed(rootTile.southwestChild); const mockImagery = new MockImageryProvider_default(); imageryLayerCollection.addImageryProvider(mockImagery); mockImagery.requestImageWillSucceed(rootTile).requestImageWillSucceed(rootTile.southwestChild); return processor.process([rootTile, rootTile.southwestChild]).then(function() { expect(rootTile.state).toBe(import__484.QuadtreeTileLoadState.DONE); expect(rootTile.upsampledFromParent).toBe(false); expect(rootTile.southwestChild.state).toBe( import__484.QuadtreeTileLoadState.DONE ); expect(rootTile.southwestChild.upsampledFromParent).toBe(false); }); }); it("does not mark a tile as upsampled if it has fresh terrain", function() { mockTerrain.willBeAvailable(rootTile).requestTileGeometryWillSucceed(rootTile).createMeshWillSucceed(rootTile).willBeAvailable(rootTile.southwestChild).requestTileGeometryWillSucceed(rootTile.southwestChild).createMeshWillSucceed(rootTile.southwestChild); const mockImagery = new MockImageryProvider_default(); imageryLayerCollection.addImageryProvider(mockImagery); mockImagery.requestImageWillSucceed(rootTile).requestImageWillFail(rootTile.southwestChild); return processor.process([rootTile, rootTile.southwestChild]).then(function() { expect(rootTile.state).toBe(import__484.QuadtreeTileLoadState.DONE); expect(rootTile.upsampledFromParent).toBe(false); expect(rootTile.southwestChild.state).toBe( import__484.QuadtreeTileLoadState.DONE ); expect(rootTile.southwestChild.upsampledFromParent).toBe(false); }); }); it("creates water mask texture from one-byte water mask data, if it exists", function() { mockTerrain.willBeAvailable(rootTile).requestTileGeometryWillSucceed(rootTile).willHaveWaterMask(false, true, rootTile); return processor.process([rootTile]).then(function() { expect(rootTile.data.waterMaskTexture).toBeDefined(); }); }); it("uses undefined water mask texture for tiles that are entirely land", function() { mockTerrain.requestTileGeometryWillSucceed(rootTile).willHaveWaterMask(true, false, rootTile); return processor.process([rootTile]).then(function() { expect(rootTile.data.waterMaskTexture).toBeUndefined(); }); }); it("uses shared water mask texture for tiles that are entirely water", function() { mockTerrain.requestTileGeometryWillSucceed(rootTile).willHaveWaterMask(false, true, rootTile).requestTileGeometryWillSucceed(rootTile.southwestChild).willHaveWaterMask(false, true, rootTile.southwestChild); return processor.process([rootTile, rootTile.southwestChild]).then(function() { expect(rootTile.data.waterMaskTexture).toBe( rootTile.southwestChild.data.waterMaskTexture ); }); }); it("creates water mask texture from multi-byte water mask data, if it exists", function() { mockTerrain.requestTileGeometryWillSucceed(rootTile).willHaveWaterMask(true, true, rootTile); return processor.process([rootTile]).then(function() { expect(rootTile.data.waterMaskTexture).toBeDefined(); }); }); it("upsamples water mask if data is not available", function() { mockTerrain.requestTileGeometryWillSucceed(rootTile).willHaveWaterMask(false, true, rootTile).requestTileGeometryWillSucceed(rootTile.southwestChild); return processor.process([rootTile, rootTile.southwestChild]).then(function() { expect(rootTile.southwestChild.data.waterMaskTexture).toBeDefined(); expect( rootTile.southwestChild.data.waterMaskTranslationAndScale ).toEqual(new import__484.Cartesian4(0, 0, 0.5, 0.5)); }); }); }); describe( "pick", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); it("gets correct results even when the mesh includes normals", async function() { const terrainProvider = await (0, import__484.createWorldTerrainAsync)({ requestVertexNormals: true, requestWaterMask: false }); const tile = new import__484.QuadtreeTile({ tilingScheme: new import__484.GeographicTilingScheme(), level: 11, x: 3788, y: 1336 }); processor.frameState = scene2.frameState; processor.terrainProvider = terrainProvider; await processor.process([tile]); const ray = new import__484.Ray( new import__484.Cartesian3( -5052039459789615e-9, 2561172040315167e-9, -2936276999965875e-9 ), new import__484.Cartesian3( 0.5036332963145244, 0.6648033332898124, 0.5517155343926082 ) ); const pickResult = tile.data.pick(ray, void 0, void 0, true); const cartographic = import__484.Ellipsoid.WGS84.cartesianToCartographic( pickResult ); expect(cartographic.height).toBeGreaterThan(-500); }); it("gets correct result when a closer triangle is processed after a farther triangle", function() { const terrainProvider = new import__484.EllipsoidTerrainProvider(); const tile = new import__484.QuadtreeTile({ tilingScheme: new import__484.GeographicTilingScheme(), level: 0, x: 0, y: 0 }); processor.frameState = scene2.frameState; processor.terrainProvider = terrainProvider; return processor.process([tile]).then(function() { const origin = new import__484.Cartesian3(5e7, -1, 0); const direction = new import__484.Cartesian3(-1, 0, 0); const ray = new import__484.Ray(origin, direction); const cullBackFaces = false; const pickResult = tile.data.pick( ray, void 0, void 0, cullBackFaces ); expect(pickResult.x).toBeGreaterThan(0); }); }); it("ignores triangles that are behind the ray", function() { const terrainProvider = new import__484.EllipsoidTerrainProvider(); const tile = new import__484.QuadtreeTile({ tilingScheme: new import__484.GeographicTilingScheme(), level: 0, x: 0, y: 0 }); processor.frameState = scene2.frameState; processor.terrainProvider = terrainProvider; return processor.process([tile]).then(function() { const origin = new import__484.Cartesian3(0, -1, 0); const direction = new import__484.Cartesian3(1, 0, 0); const ray = new import__484.Ray(origin, direction); const cullBackFaces = false; const pickResult = tile.data.pick( ray, void 0, void 0, cullBackFaces ); expect(pickResult.x).toBeGreaterThan(0); }); }); }, "WebGL" ); describe("eligibleForUnloading", function() { beforeEach(function() { processor.mockWebGL(); }); it("returns true when no loading has been done", function() { rootTile.data = new import__484.GlobeSurfaceTile(); expect(rootTile.data.eligibleForUnloading).toBe(true); }); it("returns true when some loading has been done", function() { mockTerrain.requestTileGeometryWillSucceed(rootTile); return processor.process([rootTile]).then(function() { expect(rootTile.data.eligibleForUnloading).toBe(true); mockTerrain.createMeshWillSucceed(rootTile); return processor.process([rootTile]); }).then(function() { expect(rootTile.data.eligibleForUnloading).toBe(true); }); }); it("returns false when RECEIVING", function() { const promise = new Promise((resolve) => { processor.process([rootTile], 5).then(function() { expect(rootTile.data.eligibleForUnloading).toBe(false); resolve(); }); }); mockTerrain.requestTileGeometryWillSucceed(rootTile).requestTileGeometryWillWaitOn(promise, rootTile); return promise; }); it("returns false when TRANSFORMING", function() { const promise = new Promise((resolve) => { processor.process([rootTile], 5).then(function() { expect(rootTile.data.eligibleForUnloading).toBe(false); resolve(); }); }); mockTerrain.requestTileGeometryWillSucceed(rootTile).createMeshWillSucceed(rootTile).createMeshWillWaitOn(promise, rootTile); return promise; }); it("returns false when imagery is TRANSITIONING", function() { let resolveFunc; const promise = new Promise((resolve) => { resolveFunc = resolve; }); const mockImagery = new MockImageryProvider_default(); imageryLayerCollection.addImageryProvider(mockImagery); mockImagery.requestImageWillWaitOn(promise, rootTile); mockTerrain.requestTileGeometryWillSucceed(rootTile); return processor.process([rootTile], 5).then(function() { expect(rootTile.data.eligibleForUnloading).toBe(false); resolveFunc(); }); }); }); }); // packages/engine/Specs/Scene/GlobeTranslucencyFramebufferSpec.js var import__485 = __toESM(require_Cesium(), 1); describe("Scene/GlobeTranslucencyFramebuffer", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); it("creates resources", function() { const globeTranslucency = new import__485.GlobeTranslucencyFramebuffer(); const context = scene2.context; const viewport = new import__485.BoundingRectangle(0, 0, 100, 100); const passState = new import__485.PassState(context); globeTranslucency.updateAndClear(false, viewport, context, passState); expect(globeTranslucency.classificationTexture).toBeDefined(); expect(globeTranslucency.classificationFramebuffer).toBeDefined(); expect(globeTranslucency.packedDepthTexture).toBeDefined(); expect(globeTranslucency.packedDepthFramebuffer).toBeDefined(); if (context.depthTexture) { expect(globeTranslucency.depthStencilTexture).toBeDefined(); } else { expect(globeTranslucency.depthStencilRenderbuffer).toBeDefined(); } expect(globeTranslucency._packedDepthCommand).toBeDefined(); expect(globeTranslucency._clearCommand).toBeDefined(); }); it("recreates resources when viewport changes", function() { const globeTranslucency = new import__485.GlobeTranslucencyFramebuffer(); const frameState2 = scene2.frameState; const context = frameState2.context; const viewport = new import__485.BoundingRectangle(0, 0, 100, 100); const passState = new import__485.PassState(context); globeTranslucency.updateAndClear(false, viewport, context, passState); const firstColorTexture = globeTranslucency.classificationTexture; const firstFramebuffer = globeTranslucency.classificationFramebuffer; const firstPackedDepthFramebuffer = globeTranslucency.packedDepthFramebuffer; expect(globeTranslucency._clearCommand.framebuffer).toBe(firstFramebuffer); expect(globeTranslucency._packedDepthCommand.framebuffer).toBe( firstPackedDepthFramebuffer ); viewport.width = 50; globeTranslucency.updateAndClear(false, viewport, context, passState); expect(firstColorTexture.isDestroyed()).toBe(true); expect(globeTranslucency._colorTexture).not.toBe(firstColorTexture); expect(globeTranslucency._clearCommand.framebuffer).not.toBe( firstFramebuffer ); expect(globeTranslucency._packedDepthCommand.framebuffer).not.toBe( firstPackedDepthFramebuffer ); }); it("recreates resources when HDR changes", function() { if (!scene2.highDynamicRangeSupported) { return; } const frameState2 = scene2.frameState; const context = frameState2.context; const globeTranslucency = new import__485.GlobeTranslucencyFramebuffer(); const viewport = new import__485.BoundingRectangle(0, 0, 100, 100); const passState = new import__485.PassState(context); globeTranslucency.updateAndClear(false, viewport, context, passState); const firstColorTexture = globeTranslucency.classificationTexture; const expectedPixelDatatype = context.halfFloatingPointTexture ? import__485.PixelDatatype.HALF_FLOAT : import__485.PixelDatatype.FLOAT; globeTranslucency.updateAndClear(true, viewport, context, passState); expect(firstColorTexture.isDestroyed()).toBe(true); expect(globeTranslucency.classificationTexture).not.toBe(firstColorTexture); expect(globeTranslucency.classificationTexture.pixelDatatype).toBe( expectedPixelDatatype ); }); it("destroys", function() { const globeTranslucency = new import__485.GlobeTranslucencyFramebuffer(); const frameState2 = scene2.frameState; const context = frameState2.context; const viewport = new import__485.BoundingRectangle(0, 0, 100, 100); const passState = new import__485.PassState(context); globeTranslucency.updateAndClear(false, viewport, context, passState); spyOn(import__485.Texture.prototype, "destroy").and.callThrough(); spyOn(import__485.Framebuffer.prototype, "destroy").and.callThrough(); globeTranslucency.destroy(); expect(globeTranslucency.isDestroyed()).toBe(true); expect(import__485.Texture.prototype.destroy).toHaveBeenCalled(); expect(import__485.Framebuffer.prototype.destroy).toHaveBeenCalled(); }); }); // packages/engine/Specs/Scene/GlobeTranslucencyStateSpec.js var import__486 = __toESM(require_Cesium(), 1); var scene; var globe; var frameState; var state; var framebuffer; function reset() { scene._globe = globe; globe.show = true; globe.translucency.enabled = false; globe.translucency.frontFaceAlpha = 1; globe.translucency.frontFaceAlphaByDistance = void 0; globe.translucency.backFaceAlpha = 1; globe.translucency.backFaceAlphaByDistance = void 0; globe.baseColor = import__486.Color.WHITE; globe.depthTestAgainstTerrain = false; frameState.commandList.length = 0; frameState.passes.pick = false; frameState.frameNumber = 0; scene._cameraUnderground = false; scene._mode = import__486.SceneMode.SCENE3D; } function createShaderProgram(colorString) { const vs = "void main() { gl_Position = vec4(0.0, 0.0, 0.0, 1.0); }"; const fs = `void main() { out_FragColor = vec4(${colorString}); }`; const vertexShaderSource = new import__486.ShaderSource({ sources: [vs] }); const fragmentShaderSource = new import__486.ShaderSource({ sources: [fs] }); return import__486.ShaderProgram.fromCache({ context: scene.context, vertexShaderSource, fragmentShaderSource }); } function createDrawCommand() { const uniformMap = {}; const shaderProgram = createShaderProgram("0.0"); const renderState = import__486.RenderState.fromCache({ depthMask: true, cull: { enabled: true } }); const drawCommand = new import__486.DrawCommand({ shaderProgram, uniformMap, renderState }); return drawCommand; } describe("Scene/GlobeTranslucencyState", function() { beforeAll(function() { scene = createScene_default(); scene.globe = new import__486.Globe(); globe = scene.globe; frameState = scene.frameState; state = new import__486.GlobeTranslucencyState(); framebuffer = new import__486.GlobeTranslucencyFramebuffer(); }); afterAll(function() { scene.destroyForSpecs(); }); beforeEach(function() { reset(); }); it("gets front face alpha by distance", function() { reset(); state.update(scene); const frontFaceAlphaByDistance = state.frontFaceAlphaByDistance; const backFaceAlphaByDistance = state.backFaceAlphaByDistance; expect(frontFaceAlphaByDistance.nearValue).toBe(1); expect(frontFaceAlphaByDistance.farValue).toBe(1); expect(backFaceAlphaByDistance.nearValue).toBe(1); expect(backFaceAlphaByDistance.farValue).toBe(1); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; globe.translucency.backFaceAlpha = 0.25; state.update(scene); expect(frontFaceAlphaByDistance.nearValue).toBe(0.5); expect(frontFaceAlphaByDistance.farValue).toBe(0.5); expect(backFaceAlphaByDistance.nearValue).toBe(0.25); expect(backFaceAlphaByDistance.farValue).toBe(0.25); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; globe.translucency.backFaceAlpha = 0.25; globe.translucency.frontFaceAlphaByDistance = new import__486.NearFarScalar( 0, 0.5, 1, 0.75 ); state.update(scene); expect(frontFaceAlphaByDistance.nearValue).toBe(0.25); expect(frontFaceAlphaByDistance.farValue).toBe(0.375); expect(backFaceAlphaByDistance.nearValue).toBe(0.25); expect(backFaceAlphaByDistance.farValue).toBe(0.25); }); it("detects if globe is translucent", function() { reset(); scene._globe = void 0; state.update(scene); expect(state.translucent).toBe(false); reset(); globe.show = false; state.update(scene); expect(state.translucent).toBe(false); reset(); state.update(scene); expect(state.translucent).toBe(false); reset(); globe.translucency.enabled = true; globe.baseColor = import__486.Color.TRANSPARENT; state.update(scene); expect(state.translucent).toBe(true); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; state.update(scene); expect(state.translucent).toBe(true); }); it("detects if sun is visible through globe", function() { reset(); scene._globe = void 0; state.update(scene); expect(state.sunVisibleThroughGlobe).toBe(true); reset(); globe.show = false; state.update(scene); expect(state.sunVisibleThroughGlobe).toBe(true); reset(); state.update(scene); expect(state.sunVisibleThroughGlobe).toBe(false); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; globe.translucency.backFaceAlpha = 0.5; state.update(scene); expect(state.sunVisibleThroughGlobe).toBe(true); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; state.update(scene); expect(state.sunVisibleThroughGlobe).toBe(false); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; scene._cameraUnderground = true; state.update(scene); expect(state.sunVisibleThroughGlobe).toBe(true); }); it("detects if environment is visible", function() { reset(); scene._globe = void 0; state.update(scene); expect(state.environmentVisible).toBe(true); reset(); globe.show = false; state.update(scene); expect(state.environmentVisible).toBe(true); reset(); state.update(scene); expect(state.environmentVisible).toBe(true); reset(); scene._cameraUnderground = true; state.update(scene); expect(state.environmentVisible).toBe(false); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; scene._cameraUnderground = true; state.update(scene); expect(state.environmentVisible).toBe(true); }); it("detects whether to use depth plane", function() { reset(); scene._globe = void 0; state.update(scene); expect(state.useDepthPlane).toBe(false); reset(); globe.show = false; state.update(scene); expect(state.useDepthPlane).toBe(false); reset(); scene._cameraUnderground = true; state.update(scene); expect(state.useDepthPlane).toBe(false); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; state.update(scene); expect(state.useDepthPlane).toBe(false); }); it("gets number of texture uniforms required", function() { reset(); state.update(scene); expect(state.numberOfTextureUniforms).toBe(0); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; state.update(scene); expect(state.numberOfTextureUniforms).toBe(1 + scene.context.depthTexture); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; globe.depthTestAgainstTerrain = true; state.update(scene); expect(state.numberOfTextureUniforms).toBe(1); }); function checkTypes(state2, typeArrays) { const derivedCommandTypes = state2._derivedCommandTypes; const derivedBlendCommandTypes = state2._derivedBlendCommandTypes; const derivedPickCommandTypes = state2._derivedPickCommandTypes; const derivedCommandTypesToUpdate = state2._derivedCommandTypesToUpdate; const length2 = state2._derivedCommandsLength; const blendLength = state2._derivedBlendCommandsLength; const pickLength = state2._derivedPickCommandsLength; const updateLength = state2._derivedCommandsToUpdateLength; const types = derivedCommandTypes.slice(0, length2); const blendTypes = derivedBlendCommandTypes.slice(0, blendLength); const pickTypes = derivedPickCommandTypes.slice(0, pickLength); const updateTypes = derivedCommandTypesToUpdate.slice(0, updateLength); expect(types).toEqual(typeArrays[0]); expect(blendTypes).toEqual(typeArrays[1]); expect(pickTypes).toEqual(typeArrays[2]); expect(updateTypes).toEqual(typeArrays[3]); } it("gets derived commands to update", function() { reset(); state.update(scene); checkTypes(state, [[], [], [], []]); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; globe.depthTestAgainstTerrain = true; state.update(scene); checkTypes(state, [ [2, 1, 5], [1, 5], [2, 1, 9], [1, 2, 5, 9] ]); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; state.update(scene); if (frameState.context.depthTexture) { checkTypes(state, [ [2, 1, 7], [1, 7], [2, 1, 9], [1, 2, 7, 9] ]); } else { checkTypes(state, [ [2, 1, 5], [1, 5], [2, 1, 9], [1, 2, 5, 9] ]); } reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; scene._cameraUnderground = true; state.update(scene); if (frameState.context.depthTexture) { checkTypes(state, [ [3, 0, 8], [0, 8], [3, 0, 10], [0, 3, 8, 10] ]); } else { checkTypes(state, [ [3, 0, 6], [0, 6], [3, 0, 10], [0, 3, 6, 10] ]); } reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; globe.translucency.backFaceAlpha = 0.5; state.update(scene); checkTypes(state, [ [4, 6, 5], [6, 5], [4, 10, 9], [4, 5, 6, 9, 10] ]); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; globe.translucency.backFaceAlpha = 0.5; scene._cameraUnderground = true; state.update(scene); checkTypes(state, [ [4, 5, 6], [5, 6], [4, 9, 10], [4, 5, 6, 9, 10] ]); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; scene._mode = import__486.SceneMode.SCENE2D; state.update(scene); checkTypes(state, [ [2, 5], [2, 5], [2, 9], [2, 5, 9] ]); }); it("detects when derived command requirements have changed", function() { reset(); state.update(scene); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; globe.depthTestAgainstTerrain = true; state.update(scene); expect(state._derivedCommandsDirty).toBe(true); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; globe.depthTestAgainstTerrain = true; state.update(scene); expect(state._derivedCommandsDirty).toBe(false); }); it("does not update derived commands when globe is opaque", function() { const command = createDrawCommand(); reset(); state.update(scene); state.updateDerivedCommands(command, frameState); const derivedCommands = command.derivedCommands.globeTranslucency; expect(derivedCommands).toBeUndefined(); }); it("updates derived commands", function() { const command = createDrawCommand(); const uniformMap = command.uniformMap; const shaderProgram = command.shaderProgram; const renderState = command.renderState; reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; globe.depthTestAgainstTerrain = true; state.update(scene); state.updateDerivedCommands(command, frameState); let derivedCommands = command.derivedCommands.globeTranslucency; expect(derivedCommands).toBeDefined(); expect(derivedCommands.opaqueBackFaceCommand).toBeDefined(); expect(derivedCommands.depthOnlyFrontFaceCommand).toBeDefined(); expect(derivedCommands.translucentFrontFaceCommand).toBeDefined(); expect(derivedCommands.pickFrontFaceCommand).toBeDefined(); expect(derivedCommands.pickBackFaceCommand).toBeUndefined(); let derivedCommand = derivedCommands.translucentFrontFaceCommand; const derivedUniformMap = derivedCommand.uniformMap; const derivedShaderProgram = derivedCommand.shaderProgram; const derivedRenderState = derivedCommand.renderState; expect(derivedUniformMap).not.toBe(uniformMap); expect(derivedShaderProgram).not.toBe(shaderProgram); expect(derivedRenderState).not.toBe(renderState); command.uniformMap = {}; command.shaderProgram = createShaderProgram("1.0"); command.renderState = import__486.RenderState.fromCache({ colorMask: { red: false } }); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; globe.depthTestAgainstTerrain = true; state.update(scene); state.updateDerivedCommands(command, frameState); derivedCommands = command.derivedCommands.globeTranslucency; derivedCommand = derivedCommands.translucentFrontFaceCommand; expect(derivedCommand.uniformMap).not.toBe(derivedUniformMap); expect(derivedCommand.shaderProgram).not.toBe(derivedShaderProgram); expect(derivedCommand.renderState).not.toBe(derivedRenderState); expect(derivedCommand.uniformMap).not.toBe(uniformMap); expect(derivedCommand.shaderProgram).not.toBe(shaderProgram); expect(derivedCommand.renderState).not.toBe(renderState); command.uniformMap = uniformMap; command.shaderProgram = shaderProgram; command.renderState = renderState; reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; globe.depthTestAgainstTerrain = true; state.update(scene); state.updateDerivedCommands(command, frameState); derivedCommands = command.derivedCommands.globeTranslucency; derivedCommand = derivedCommands.translucentFrontFaceCommand; expect(derivedCommand.uniformMap).not.toBe(derivedUniformMap); expect(derivedCommand.shaderProgram).toBe(derivedShaderProgram); expect(derivedCommand.renderState).toBe(derivedRenderState); }); it("does not push derived commands when blend command is in the pick pass", function() { const command = createDrawCommand(); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; frameState.passes.pick = true; state.update(scene); state.updateDerivedCommands(command, frameState); state.pushDerivedCommands(command, true, frameState); expect(frameState.commandList.length).toBe(0); }); it("pushes globe command when globe is opaque", function() { const command = createDrawCommand(); reset(); state.update(scene); state.updateDerivedCommands(command, frameState); state.pushDerivedCommands(command, false, frameState); expect(frameState.commandList.length).toBe(1); expect(frameState.commandList[0]).toBe(command); }); it("pushes derived commands when globe is translucent", function() { const command = createDrawCommand(); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; globe.depthTestAgainstTerrain = true; state.update(scene); state.updateDerivedCommands(command, frameState); state.pushDerivedCommands(command, false, frameState); const derivedCommands = command.derivedCommands.globeTranslucency; expect(frameState.commandList).toEqual([ derivedCommands.depthOnlyFrontFaceCommand, derivedCommands.opaqueBackFaceCommand, derivedCommands.translucentFrontFaceCommand ]); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; globe.depthTestAgainstTerrain = true; state.update(scene); state.updateDerivedCommands(command, frameState); state.pushDerivedCommands(command, true, frameState); expect(frameState.commandList).toEqual([ derivedCommands.opaqueBackFaceCommand, derivedCommands.translucentFrontFaceCommand ]); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; globe.depthTestAgainstTerrain = true; frameState.passes.pick = true; state.update(scene); state.updateDerivedCommands(command, frameState); state.pushDerivedCommands(command, false, frameState); expect(frameState.commandList).toEqual([ derivedCommands.depthOnlyFrontFaceCommand, derivedCommands.opaqueBackFaceCommand, derivedCommands.pickFrontFaceCommand ]); }); it("executes globe commands", function() { const context = frameState.context; const passState = new import__486.PassState(context); const command = createDrawCommand(); const executeCommand = jasmine.createSpy("executeCommand"); spyOn(import__486.GlobeTranslucencyFramebuffer.prototype, "clearClassification"); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; globe.depthTestAgainstTerrain = true; state.update(scene); state.updateDerivedCommands(command, frameState); state.pushDerivedCommands(command, false, frameState); const globeCommands = frameState.commandList; const frustumCommands = new import__486.FrustumCommands(); frustumCommands.commands[import__486.Pass.GLOBE] = globeCommands; frustumCommands.indices[import__486.Pass.GLOBE] = globeCommands.length; state.executeGlobeCommands( frustumCommands, executeCommand, framebuffer, scene, passState ); expect(executeCommand).toHaveBeenCalledWith( command.derivedCommands.globeTranslucency.opaqueBackFaceCommand, scene, context, passState ); expect( import__486.GlobeTranslucencyFramebuffer.prototype.clearClassification ).toHaveBeenCalled(); }); it("does not execute globe commands if there are no commands", function() { const frameState2 = scene.frameState; const context = frameState2.context; const passState = new import__486.PassState(context); const frustumCommands = new import__486.FrustumCommands(); const executeCommand = jasmine.createSpy("executeCommand"); state.executeGlobeCommands( frustumCommands, executeCommand, framebuffer, scene, passState ); expect(executeCommand).not.toHaveBeenCalled(); }); it("executes classification commands", function() { const context = frameState.context; const passState = new import__486.PassState(context); const command = createDrawCommand(); const executeCommand = jasmine.createSpy("executeCommand"); spyOn(import__486.GlobeTranslucencyFramebuffer.prototype, "packDepth"); spyOn(import__486.GlobeTranslucencyFramebuffer.prototype, "clearClassification"); reset(); globe.translucency.enabled = true; globe.translucency.frontFaceAlpha = 0.5; globe.depthTestAgainstTerrain = true; state.update(scene); state.updateDerivedCommands(command, frameState); state.pushDerivedCommands(command, false, frameState); const classificationCommand = createDrawCommand(); const globeCommands = frameState.commandList; const classificationCommands = [classificationCommand]; const frustumCommands = new import__486.FrustumCommands(); frustumCommands.commands[import__486.Pass.GLOBE] = globeCommands; frustumCommands.indices[import__486.Pass.GLOBE] = globeCommands.length; frustumCommands.commands[import__486.Pass.TERRAIN_CLASSIFICATION] = classificationCommands; frustumCommands.indices[import__486.Pass.TERRAIN_CLASSIFICATION] = classificationCommands.length; state.executeGlobeClassificationCommands( frustumCommands, executeCommand, framebuffer, scene, passState ); expect(executeCommand).toHaveBeenCalledWith( classificationCommand, scene, context, passState ); expect(executeCommand).toHaveBeenCalledWith( command.derivedCommands.globeTranslucency.depthOnlyFrontFaceCommand, scene, context, passState ); if (context.depthTexture) { expect( import__486.GlobeTranslucencyFramebuffer.prototype.packDepth ).toHaveBeenCalled(); } }); }); // packages/engine/Specs/Scene/GltfBufferViewLoaderSpec.js var import__487 = __toESM(require_Cesium(), 1); describe("Scene/GltfBufferViewLoader", function() { const gltfEmbedded = { buffers: [ { byteLength: 8 } ], bufferViews: [ { buffer: 0, byteOffset: 2, byteLength: 3 } ] }; const gltfExternal = { buffers: [ { uri: "external.bin", byteLength: 8 } ], bufferViews: [ { buffer: 0, byteOffset: 2, byteLength: 3 } ] }; const meshoptGltfEmbedded = { buffers: [{ byteLength: 29 }, { byteLength: 360 }], bufferViews: [ { buffer: 1, byteOffset: 96, byteLength: 192, byteStride: 8, target: 34962, extensions: { EXT_meshopt_compression: { buffer: 0, byteOffset: 0, byteLength: 124, byteStride: 8, mode: "ATTRIBUTES", count: 24 } } }, { buffer: 1, byteOffset: 288, byteLength: 72, target: 34963, extensions: { EXT_meshopt_compression: { buffer: 0, byteOffset: 0, byteLength: 29, byteStride: 2, mode: "TRIANGLES", count: 36 } } } ] }; function getBase64FromTypedArray(typedArray) { return btoa(String.fromCharCode.apply(null, typedArray)); } function getTypedArrayFromBase64(base64) { return Uint8Array.from(atob(base64), function(c) { return c.charCodeAt(0); }); } const fallbackPositionBufferBase64 = "AAD/P/8/AAD/P/8//z8AAAAA/z8AAAAA/z//PwAAAAD/P/8//z8AAAAA/z//PwAA/z8AAP8/AAAAAAAA/z8AAP8//z8AAAAA/z//P/8/AAD/PwAAAAAAAP8/AAD/PwAAAAD/PwAAAAD/P/8/AAAAAAAAAAAAAAAA/z8AAAAAAAAAAP8//z8AAAAA/z8AAAAAAAAAAP8/AAAAAAAAAAAAAAAAAAD/PwAAAAAAAAAAAAD/PwAA/z8AAP8/AAAAAAAA"; const meshoptPositionBufferBase64 = "oAUZJkCZgAQAAAU/P8D/fn1+fX59fn1+fX7ADAAAfX4FAAhISEgAAAAFAAzMzH1+fX59zAAAAH59BQhAmYBmZgAABQzA/8B9fn1+fX59//8AAH59fn1+fX59AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP8//z8AAA=="; const meshoptPositionTypedArray = getTypedArrayFromBase64( meshoptPositionBufferBase64 ); const bufferTypedArray = new Uint8Array([1, 3, 7, 15, 31, 63, 127, 255]); const bufferArrayBuffer = bufferTypedArray.buffer; const gltfUri = "https://example.com/model.glb"; const gltfResource = new import__487.Resource({ url: gltfUri }); afterEach(function() { import__487.ResourceCache.clearForSpecs(); }); it("throws if resourceCache is undefined", function() { expect(function() { return new import__487.GltfBufferViewLoader({ resourceCache: void 0, gltf: gltfExternal, bufferViewId: 0, gltfResource, baseResource: gltfResource }); }).toThrowDeveloperError(); }); it("throws if gltf is undefined", function() { expect(function() { return new import__487.GltfBufferViewLoader({ resourceCache: import__487.ResourceCache, gltf: void 0, bufferViewId: 0, gltfResource, baseResource: gltfResource }); }).toThrowDeveloperError(); }); it("throws if bufferViewId is undefined", function() { expect(function() { return new import__487.GltfBufferViewLoader({ resourceCache: import__487.ResourceCache, gltf: gltfExternal, bufferViewId: void 0, gltfResource, baseResource: gltfResource }); }).toThrowDeveloperError(); }); it("throws if gltfResource is undefined", function() { expect(function() { return new import__487.GltfBufferViewLoader({ resourceCache: import__487.ResourceCache, gltf: gltfExternal, bufferViewId: 0, gltfResource: void 0, baseResource: gltfResource }); }).toThrowDeveloperError(); }); it("throws if baseResource is undefined", function() { expect(function() { return new import__487.GltfBufferViewLoader({ resourceCache: import__487.ResourceCache, gltf: gltfExternal, bufferViewId: 0, gltfResource, baseResource: void 0 }); }).toThrowDeveloperError(); }); it("load throws if buffer fails to load", async function() { spyOn(import__487.Resource.prototype, "fetchArrayBuffer").and.callFake( () => Promise.reject(new Error("404 Not Found")) ); const bufferViewLoader = new import__487.GltfBufferViewLoader({ resourceCache: import__487.ResourceCache, gltf: gltfExternal, bufferViewId: 0, gltfResource, baseResource: gltfResource }); await expectAsync(bufferViewLoader.load()).toBeRejectedWithError( import__487.RuntimeError, "Failed to load buffer view\nFailed to load external buffer: https://example.com/external.bin\n404 Not Found" ); }); it("loads buffer view for embedded buffer", async function() { const bufferLoader = import__487.ResourceCache.getEmbeddedBufferLoader({ parentResource: gltfResource, bufferId: 0, typedArray: bufferTypedArray }); await bufferLoader.load(); const bufferViewLoader = new import__487.GltfBufferViewLoader({ resourceCache: import__487.ResourceCache, gltf: gltfEmbedded, bufferViewId: 0, gltfResource, baseResource: gltfResource }); await bufferViewLoader.load(); expect(bufferViewLoader.typedArray).toEqual(new Uint8Array([7, 15, 31])); }); it("loads buffer view for external buffer", async function() { spyOn(import__487.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(bufferArrayBuffer) ); const bufferViewLoader = new import__487.GltfBufferViewLoader({ resourceCache: import__487.ResourceCache, gltf: gltfExternal, bufferViewId: 0, gltfResource, baseResource: gltfResource }); await bufferViewLoader.load(); expect(bufferViewLoader.typedArray).toEqual(new Uint8Array([7, 15, 31])); }); it("destroys buffer view", async function() { spyOn(import__487.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(bufferArrayBuffer) ); const unloadBuffer = spyOn( import__487.BufferLoader.prototype, "unload" ).and.callThrough(); const bufferViewLoader = new import__487.GltfBufferViewLoader({ resourceCache: import__487.ResourceCache, gltf: gltfExternal, bufferViewId: 0, gltfResource, baseResource: gltfResource }); expect(bufferViewLoader.typedArray).not.toBeDefined(); await bufferViewLoader.load(); expect(bufferViewLoader.typedArray).toEqual(new Uint8Array([7, 15, 31])); expect(bufferViewLoader.isDestroyed()).toBe(false); bufferViewLoader.destroy(); expect(bufferViewLoader.typedArray).not.toBeDefined(); expect(bufferViewLoader.isDestroyed()).toBe(true); expect(unloadBuffer).toHaveBeenCalled(); }); it("decodes positions with EXT_meshopt_compression", async function() { const bufferLoader = import__487.ResourceCache.getEmbeddedBufferLoader({ parentResource: gltfResource, bufferId: 0, typedArray: meshoptPositionTypedArray }); await bufferLoader.load(); const bufferViewLoader = new import__487.GltfBufferViewLoader({ resourceCache: import__487.ResourceCache, gltf: meshoptGltfEmbedded, bufferViewId: 0, gltfResource, baseResource: gltfResource }); await bufferViewLoader.load(); const decodedPositionBase64 = getBase64FromTypedArray( bufferViewLoader.typedArray ); expect(decodedPositionBase64).toEqual(fallbackPositionBufferBase64); }); it("handles asynchronous load after destroy", async function() { spyOn(import__487.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(bufferArrayBuffer) ); const bufferViewLoader = new import__487.GltfBufferViewLoader({ resourceCache: import__487.ResourceCache, gltf: gltfExternal, bufferViewId: 0, gltfResource, baseResource: gltfResource }); expect(bufferViewLoader.typedArray).not.toBeDefined(); const loadPromise = bufferViewLoader.load(); bufferViewLoader.destroy(); await expectAsync(loadPromise).toBeResolved(); expect(bufferViewLoader.typedArray).not.toBeDefined(); expect(bufferViewLoader.isDestroyed()).toBe(true); }); it("handles asynchronous error after destroy", async function() { spyOn(import__487.Resource.prototype, "fetchArrayBuffer").and.callFake( () => Promise.reject(new Error()) ); const bufferViewLoader = new import__487.GltfBufferViewLoader({ resourceCache: import__487.ResourceCache, gltf: gltfExternal, bufferViewId: 0, gltfResource, baseResource: gltfResource }); expect(bufferViewLoader.typedArray).not.toBeDefined(); const loadPromise = bufferViewLoader.load(); bufferViewLoader.destroy(); await expectAsync(loadPromise).toBeResolved(); expect(bufferViewLoader.typedArray).not.toBeDefined(); expect(bufferViewLoader.isDestroyed()).toBe(true); }); }); // packages/engine/Specs/Scene/GltfDracoLoaderSpec.js var import__488 = __toESM(require_Cesium(), 1); // Specs/loaderProcess.js function loaderProcess(loader, scene2) { scene2.jobScheduler.resetBudgets(); const ready = loader.process(scene2.frameState); scene2.jobScheduler.resetBudgets(); return ready; } var loaderProcess_default = loaderProcess; // Specs/waitForLoaderProcess.js function waitForLoaderProcess(loader, scene2) { return pollToPromise_default(function() { if (loader.isDestroyed()) { return true; } return loaderProcess_default(loader, scene2); }); } var waitForLoaderProcess_default = waitForLoaderProcess; // packages/engine/Specs/Scene/GltfDracoLoaderSpec.js describe( "Scene/GltfDracoLoader", function() { const bufferTypedArray = new Uint8Array([1, 3, 7, 15, 31, 63, 127, 255]); const bufferArrayBuffer = bufferTypedArray.buffer; const decodedPositions = new Uint16Array([0, 0, 0, 65535, 65535, 65535, 0, 65535, 0]); const decodedNormals = new Uint8Array([0, 255, 128, 128, 255, 0]); const decodedIndices = new Uint16Array([0, 1, 2]); const gltfUri = "https://example.com/model.glb"; const gltfResource = new import__488.Resource({ url: gltfUri }); const decodeDracoResults = { indexArray: { typedArray: decodedIndices, numberOfIndices: decodedIndices.length }, attributeData: { POSITION: { array: decodedPositions, data: { byteOffset: 0, byteStride: 6, componentDatatype: import__488.ComponentDatatype.UNSIGNED_SHORT, componentsPerAttribute: 3, normalized: false, quantization: { octEncoded: false, quantizationBits: 14, minValues: [-1, -1, -1], range: 2 } } }, NORMAL: { array: decodedNormals, data: { byteOffset: 0, byteStride: 2, componentDatatype: import__488.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 2, normalized: false, quantization: { octEncoded: true, quantizationBits: 10 } } } } }; const gltfDraco = { buffers: [ { uri: "external.bin", byteLength: 8 } ], bufferViews: [ { buffer: 0, byteOffset: 4, byteLength: 4 } ], accessors: [ { componentType: 5126, count: 3, max: [-1, -1, -1], min: [1, 1, 1], type: "VEC3" }, { componentType: 5126, count: 3, type: "VEC3" }, { componentType: 5123, count: 3, type: "SCALAR" } ], meshes: [ { primitives: [ { attributes: { POSITION: 0, NORMAL: 1 }, indices: 2, extensions: { KHR_draco_mesh_compression: { bufferView: 0, attributes: { POSITION: 0, NORMAL: 1 } } } } ] } ] }; const dracoExtension = gltfDraco.meshes[0].primitives[0].extensions.KHR_draco_mesh_compression; let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { import__488.ResourceCache.clearForSpecs(); }); it("throws if resourceCache is undefined", function() { expect(function() { return new import__488.GltfDracoLoader({ resourceCache: void 0, gltf: gltfDraco, draco: dracoExtension, gltfResource, baseResource: gltfResource }); }).toThrowDeveloperError(); }); it("throws if gltf is undefined", function() { expect(function() { return new import__488.GltfDracoLoader({ resourceCache: import__488.ResourceCache, gltf: void 0, draco: dracoExtension, gltfResource, baseResource: gltfResource }); }).toThrowDeveloperError(); }); it("throws if draco is undefined", function() { expect(function() { return new import__488.GltfDracoLoader({ resourceCache: import__488.ResourceCache, gltf: gltfDraco, draco: void 0, gltfResource, baseResource: gltfResource }); }).toThrowDeveloperError(); }); it("throws if gltfResource is undefined", function() { expect(function() { return new import__488.GltfDracoLoader({ resourceCache: import__488.ResourceCache, gltf: gltfDraco, draco: dracoExtension, gltfResource: void 0, baseResource: gltfResource }); }).toThrowDeveloperError(); }); it("throws if baseResource is undefined", function() { expect(function() { return new import__488.GltfDracoLoader({ resourceCache: import__488.ResourceCache, gltf: gltfDraco, draco: dracoExtension, gltfResource, baseResource: void 0 }); }).toThrowDeveloperError(); }); it("load throws if buffer view fails to load", async function() { spyOn(import__488.Resource.prototype, "fetchArrayBuffer").and.callFake(function() { const error = new Error("404 Not Found"); return Promise.reject(error); }); const dracoLoader = new import__488.GltfDracoLoader({ resourceCache: import__488.ResourceCache, gltf: gltfDraco, draco: dracoExtension, gltfResource, baseResource: gltfResource }); await expectAsync(dracoLoader.load()).toBeRejectedWithError( import__488.RuntimeError, "Failed to load Draco\nFailed to load buffer view\nFailed to load external buffer: https://example.com/external.bin\n404 Not Found" ); }); it("process throws if draco decoding fails", async function() { spyOn(import__488.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(bufferArrayBuffer) ); spyOn(import__488.DracoLoader, "decodeBufferView").and.callFake(function() { const error = new Error("Draco decode failed"); return Promise.reject(error); }); const dracoLoader = new import__488.GltfDracoLoader({ resourceCache: import__488.ResourceCache, gltf: gltfDraco, draco: dracoExtension, gltfResource, baseResource: gltfResource }); await dracoLoader.load(); await expectAsync( waitForLoaderProcess_default(dracoLoader, scene2) ).toBeRejectedWithError( import__488.RuntimeError, "Failed to load Draco\nDraco decode failed" ); expect(() => loaderProcess_default(dracoLoader, scene2)).not.toThrowError(); }); it("loads draco", async function() { spyOn(import__488.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(bufferArrayBuffer) ); const decodeBufferViewCallsTotal = 3; let decodeBufferViewCallsCount = 0; spyOn(import__488.DracoLoader, "decodeBufferView").and.callFake(function() { if (decodeBufferViewCallsCount++ === decodeBufferViewCallsTotal) { return Promise.resolve(decodeDracoResults); } return void 0; }); const dracoLoader = new import__488.GltfDracoLoader({ resourceCache: import__488.ResourceCache, gltf: gltfDraco, draco: dracoExtension, gltfResource, baseResource: gltfResource }); await dracoLoader.load(); await waitForLoaderProcess_default(dracoLoader, scene2); expect(() => loaderProcess_default(dracoLoader, scene2)).not.toThrowError(); expect(dracoLoader.decodedData.indices).toBe( decodeDracoResults.indexArray ); expect(dracoLoader.decodedData.vertexAttributes).toBe( decodeDracoResults.attributeData ); }); it("destroys draco loader", async function() { spyOn(import__488.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(bufferArrayBuffer) ); spyOn(import__488.DracoLoader, "decodeBufferView").and.returnValue( Promise.resolve(decodeDracoResults) ); const unloadBufferView = spyOn( import__488.GltfBufferViewLoader.prototype, "unload" ).and.callThrough(); const dracoLoader = new import__488.GltfDracoLoader({ resourceCache: import__488.ResourceCache, gltf: gltfDraco, draco: dracoExtension, gltfResource, baseResource: gltfResource }); await dracoLoader.load(); await waitForLoaderProcess_default(dracoLoader, scene2); expect(dracoLoader.decodedData).toBeDefined(); expect(dracoLoader.isDestroyed()).toBe(false); dracoLoader.destroy(); expect(dracoLoader.decodedData).not.toBeDefined(); expect(dracoLoader.isDestroyed()).toBe(true); expect(unloadBufferView).toHaveBeenCalled(); }); async function resolveBufferViewAfterDestroy(reject) { spyOn(import__488.Resource.prototype, "fetchArrayBuffer").and.callFake(function() { if (reject) { return Promise.reject(new Error()); } return Promise.resolve(bufferArrayBuffer); }); spyOn(import__488.DracoLoader, "decodeBufferView").and.returnValue( Promise.resolve(decodeDracoResults) ); const dracoLoader = new import__488.GltfDracoLoader({ resourceCache: import__488.ResourceCache, gltf: gltfDraco, draco: dracoExtension, gltfResource, baseResource: gltfResource }); expect(dracoLoader.decodedData).not.toBeDefined(); const promise = dracoLoader.load(); dracoLoader.destroy(); await expectAsync(promise).toBeResolved(); expect(dracoLoader.decodedData).not.toBeDefined(); expect(dracoLoader.isDestroyed()).toBe(true); } it("handles resolving buffer view after destroy", function() { return resolveBufferViewAfterDestroy(false); }); it("handles rejecting buffer view after destroy", function() { return resolveBufferViewAfterDestroy(true); }); async function resolveDracoAfterDestroy(rejectPromise) { const dracoLoader = new import__488.GltfDracoLoader({ resourceCache: import__488.ResourceCache, gltf: gltfDraco, draco: dracoExtension, gltfResource, baseResource: gltfResource }); spyOn(import__488.Resource.prototype, "fetchArrayBuffer").and.callFake(function() { setTimeout(function() { dracoLoader.destroy(); }, 1); return Promise.resolve(bufferArrayBuffer); }); const decodeBufferView = spyOn( import__488.DracoLoader, "decodeBufferView" ).and.callFake(function() { return new Promise(function(resolve, reject) { if (rejectPromise) { reject(new Error("Draco decode failed")); } else { resolve(decodeDracoResults); } }); }); expect(dracoLoader.decodedData).not.toBeDefined(); await dracoLoader.load(); await waitForLoaderProcess_default(dracoLoader, scene2); expect(decodeBufferView).toHaveBeenCalled(); expect(dracoLoader.decodedData).not.toBeDefined(); expect(dracoLoader.isDestroyed()).toBe(true); } it("handles resolving draco after destroy", function() { return resolveDracoAfterDestroy(false); }); it("handles rejecting draco after destroy", function() { return resolveDracoAfterDestroy(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/GltfImageLoaderSpec.js var import__489 = __toESM(require_Cesium(), 1); describe( "Scene/GltfImageLoader", function() { const image = new Image(); image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII="; const pngBuffer = dataUriToBuffer_default( "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=" ); const jpgBuffer = dataUriToBuffer_default( "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wAALCAABAAEBAREA/8QAJgABAAAAAAAAAAAAAAAAAAAAAxABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQAAPwBH/9k" ); const webpBuffer = dataUriToBuffer_default( "data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA" ); const gifBuffer = dataUriToBuffer_default( "data:image/gif;base64,R0lGODdhBAAEAIAAAP///////ywAAAAABAAEAAACBISPCQUAOw==" ); let ktx2BasisBuffer; let ktx2BasisMipmapBuffer; const gltfUri = "https://example.com/model.glb"; const gltfResource = new import__489.Resource({ url: gltfUri }); const gltf = { buffers: [ { uri: "external.bin", byteLength: 0 // updated in getGltf } ], bufferViews: [ { buffer: 0, byteOffset: 0, byteLength: 0 // updated in getGltf } ], images: [ { mimeType: "image/png", bufferView: 0 }, { uri: "image.png" }, { mimeType: "image/ktx2", bufferView: 0 }, { uri: "image.ktx2" } ] }; let context; function getGltf(imageBuffer) { const clonedGltf = (0, import__489.clone)(gltf, true); clonedGltf.buffers[0].byteLength = imageBuffer.byteLength; clonedGltf.bufferViews[0].byteLength = imageBuffer.byteLength; return clonedGltf; } beforeAll(function() { context = createContext_default(); const ktx2BasisBufferPromise = import__489.Resource.fetchArrayBuffer({ url: "./Data/Images/Green4x4_ETC1S.ktx2" }).then(function(arrayBuffer) { ktx2BasisBuffer = new Uint8Array(arrayBuffer); }); const ktx2BasisMipmapBufferPromise = import__489.Resource.fetchArrayBuffer({ url: "./Data/Images/Green4x4Mipmap_ETC1S.ktx2" }).then(function(arrayBuffer) { ktx2BasisMipmapBuffer = new Uint8Array(arrayBuffer); }); return Promise.all([ ktx2BasisBufferPromise, ktx2BasisMipmapBufferPromise ]); }); afterAll(function() { context.destroyForSpecs(); }); afterEach(function() { import__489.ResourceCache.clearForSpecs(); }); it("throws if resourceCache is undefined", function() { expect(function() { return new import__489.GltfImageLoader({ resourceCache: void 0, gltf, imageId: 0, gltfResource, baseResource: gltfResource }); }).toThrowDeveloperError(); }); it("throws if gltf is undefined", function() { expect(function() { return new import__489.GltfImageLoader({ resourceCache: import__489.ResourceCache, gltf: void 0, imageId: 0, gltfResource, baseResource: gltfResource }); }).toThrowDeveloperError(); }); it("throws if imageId is undefined", function() { expect(function() { return new import__489.GltfImageLoader({ resourceCache: import__489.ResourceCache, gltf, imageId: void 0, gltfResource, baseResource: gltfResource }); }).toThrowDeveloperError(); }); it("throws if gltfResource is undefined", function() { expect(function() { return new import__489.GltfImageLoader({ resourceCache: import__489.ResourceCache, gltf, imageId: 0, gltfResource: void 0, baseResource: gltfResource }); }).toThrowDeveloperError(); }); it("throws if baseResource is undefined", function() { expect(function() { return new import__489.GltfImageLoader({ resourceCache: import__489.ResourceCache, gltf, imageId: 0, gltfResource, baseResource: void 0 }); }).toThrowDeveloperError(); }); it("load throws if buffer view fails to load", async function() { spyOn(import__489.Resource.prototype, "fetchArrayBuffer").and.callFake(function() { const error = new Error("404 Not Found"); return Promise.reject(error); }); const imageLoader = new import__489.GltfImageLoader({ resourceCache: import__489.ResourceCache, gltf: getGltf(pngBuffer), imageId: 0, gltfResource, baseResource: gltfResource }); await expectAsync(imageLoader.load()).toBeRejectedWithError( import__489.RuntimeError, "Failed to load embedded image\nFailed to load buffer view\nFailed to load external buffer: https://example.com/external.bin\n404 Not Found" ); }); it("load throws if image format is not recognized", async function() { spyOn(import__489.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(gifBuffer) ); const imageLoader = new import__489.GltfImageLoader({ resourceCache: import__489.ResourceCache, gltf: getGltf(gifBuffer), imageId: 0, gltfResource, baseResource: gltfResource }); await expectAsync(imageLoader.load()).toBeRejectedWithError( import__489.RuntimeError, "Failed to load embedded image\nImage format is not recognized" ); }); it("load throws if uri fails to load", async function() { spyOn(import__489.Resource.prototype, "fetchImage").and.callFake(function() { const error = new Error("404 Not Found"); return Promise.reject(error); }); const imageLoader = new import__489.GltfImageLoader({ resourceCache: import__489.ResourceCache, gltf: getGltf(pngBuffer), imageId: 1, gltfResource, baseResource: gltfResource }); await expectAsync(imageLoader.load()).toBeRejectedWithError( import__489.RuntimeError, "Failed to load image: image.png\n404 Not Found" ); }); async function loadsFromBufferView(imageBuffer) { spyOn(import__489.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(imageBuffer) ); const imageLoader = new import__489.GltfImageLoader({ resourceCache: import__489.ResourceCache, gltf: getGltf(imageBuffer), imageId: 0, gltfResource, baseResource: gltfResource }); await imageLoader.load(); expect(imageLoader.image.width).toBe(1); expect(imageLoader.image.height).toBe(1); } it("loads PNG from buffer view", function() { return loadsFromBufferView(pngBuffer); }); it("loads JPEG from buffer view", function() { return loadsFromBufferView(jpgBuffer); }); it("loads WebP from buffer view", async function() { await import__489.FeatureDetection.supportsWebP.initialize(); if (!import__489.FeatureDetection.supportsWebP()) { return; } return loadsFromBufferView(webpBuffer); }); it("loads KTX2/Basis from buffer view", async function() { if (!context.supportsBasis) { return; } spyOn(import__489.BufferLoader, "_fetchArrayBuffer").and.returnValue( Promise.resolve(ktx2BasisBuffer) ); const imageLoader = new import__489.GltfImageLoader({ resourceCache: import__489.ResourceCache, gltf: getGltf(ktx2BasisBuffer), imageId: 2, gltfResource, baseResource: gltfResource }); await imageLoader.load(); expect(imageLoader.image instanceof import__489.CompressedTextureBuffer).toBe(true); expect(imageLoader.image.width).toBe(4); expect(imageLoader.image.height).toBe(4); expect(imageLoader.mipLevels).toBeUndefined(); }); it("loads KTX2/Basis with mipmap from buffer view", async function() { if (!context.supportsBasis) { return; } spyOn(import__489.BufferLoader, "_fetchArrayBuffer").and.returnValue( Promise.resolve(ktx2BasisMipmapBuffer) ); const imageLoader = new import__489.GltfImageLoader({ resourceCache: import__489.ResourceCache, gltf: getGltf(ktx2BasisMipmapBuffer), imageId: 2, gltfResource, baseResource: gltfResource }); await imageLoader.load(); expect(imageLoader.image).toBeInstanceOf(import__489.CompressedTextureBuffer); expect(imageLoader.image.width).toBe(4); expect(imageLoader.image.height).toBe(4); expect(imageLoader.mipLevels.length).toBe(2); }); it("loads from uri", async function() { spyOn(import__489.Resource.prototype, "fetchImage").and.returnValue( Promise.resolve(image) ); const imageLoader = new import__489.GltfImageLoader({ resourceCache: import__489.ResourceCache, gltf: (0, import__489.clone)(gltf, true), imageId: 1, gltfResource, baseResource: gltfResource }); await imageLoader.load(); expect(imageLoader.image.width).toBe(1); expect(imageLoader.image.height).toBe(1); }); it("loads KTX2/Basis from uri ", async function() { if (!context.supportsBasis) { return; } const baseResource = new import__489.Resource({ url: "./Data/Images/" }); const clonedGltf = (0, import__489.clone)(gltf, true); clonedGltf.images[3].uri = "Green4x4_ETC1S.ktx2"; const imageLoader = new import__489.GltfImageLoader({ resourceCache: import__489.ResourceCache, gltf: clonedGltf, imageId: 3, gltfResource, baseResource }); await imageLoader.load(); expect(imageLoader.image).toBeInstanceOf(import__489.CompressedTextureBuffer); expect(imageLoader.image.width).toBe(4); expect(imageLoader.image.height).toBe(4); expect(imageLoader.mipLevels).toBeUndefined(); }); it("match the ktx2 url with the ktx2Regex", function() { const ktx2Regex = /(^data:image\/ktx2)|(\.ktx2$)/i; const r = new import__489.Resource({ url: "../../textures/test.ktx2", queryParameters: { v: "123-435-456-000" } }); const uri = r.getUrlComponent(false, true); expect(ktx2Regex.test(uri)).toBe(true); }); it("destroys image loader", async function() { spyOn(import__489.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(pngBuffer) ); const unloadBufferView = spyOn( import__489.GltfBufferViewLoader.prototype, "unload" ).and.callThrough(); const imageLoader = new import__489.GltfImageLoader({ resourceCache: import__489.ResourceCache, gltf: getGltf(pngBuffer), imageId: 0, gltfResource, baseResource: gltfResource }); expect(imageLoader.image).not.toBeDefined(); await imageLoader.load(); expect(imageLoader.image).toBeDefined(); expect(imageLoader.isDestroyed()).toBe(false); imageLoader.destroy(); expect(imageLoader.image).not.toBeDefined(); expect(imageLoader.isDestroyed()).toBe(true); expect(unloadBufferView).toHaveBeenCalled(); }); async function resolveBufferViewAfterDestroy(rejectPromise) { spyOn(import__489.Resource.prototype, "fetchArrayBuffer").and.callFake( () => new Promise(function(resolve, reject) { if (rejectPromise) { reject(new Error()); } else { resolve(pngBuffer); } }) ); const imageLoader = new import__489.GltfImageLoader({ resourceCache: import__489.ResourceCache, gltf: getGltf(pngBuffer), imageId: 0, gltfResource, baseResource: gltfResource }); expect(imageLoader.image).not.toBeDefined(); const loadPromise = imageLoader.load(); imageLoader.destroy(); await expectAsync(loadPromise).toBeResolved(); expect(imageLoader.image).not.toBeDefined(); expect(imageLoader.isDestroyed()).toBe(true); } it("handles resolving buffer view after destroy", function() { return resolveBufferViewAfterDestroy(false); }); it("handles rejecting buffer view after destroy", function() { return resolveBufferViewAfterDestroy(true); }); async function resolveImageFromTypedArrayAfterDestroy(rejectPromise) { spyOn(import__489.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(pngBuffer) ); spyOn(import__489.GltfImageLoader, "_loadImageFromTypedArray").and.callFake( () => new Promise(function(resolve, reject) { if (rejectPromise) { reject(new Error()); } else { resolve(image); } }) ); const imageLoader = new import__489.GltfImageLoader({ resourceCache: import__489.ResourceCache, gltf: getGltf(pngBuffer), imageId: 0, gltfResource, baseResource: gltfResource }); expect(imageLoader.image).not.toBeDefined(); const loadPromise = imageLoader.load(); imageLoader.destroy(); await expectAsync(loadPromise).toBeResolved(); expect(imageLoader.image).not.toBeDefined(); expect(imageLoader.isDestroyed()).toBe(true); } it("handles resolving image from typed array after destroy", function() { return resolveImageFromTypedArrayAfterDestroy(false); }); it("handles rejecting image from typed array after destroy", function() { return resolveImageFromTypedArrayAfterDestroy(true); }); async function resolveUriAfterDestroy(rejectPromise) { spyOn(import__489.Resource.prototype, "fetchImage").and.callFake( () => new Promise(function(resolve, reject) { if (rejectPromise) { reject(new Error()); } else { resolve(image); } }) ); const imageLoader = new import__489.GltfImageLoader({ resourceCache: import__489.ResourceCache, gltf: getGltf(pngBuffer), imageId: 1, gltfResource, baseResource: gltfResource }); expect(imageLoader.image).not.toBeDefined(); const loadPromise = imageLoader.load(); imageLoader.destroy(); await expectAsync(loadPromise).toBeResolved(); expect(imageLoader.image).not.toBeDefined(); expect(imageLoader.isDestroyed()).toBe(true); } it("handles resolving uri after destroy", function() { return resolveUriAfterDestroy(false); }); it("handles rejecting uri after destroy", function() { return resolveUriAfterDestroy(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/GltfIndexBufferLoaderSpec.js var import__490 = __toESM(require_Cesium(), 1); describe( "Scene/GltfIndexBufferLoader", function() { const dracoBufferTypedArray = new Uint8Array([ 1, 3, 7, 15, 31, 63, 127, 255 ]); const dracoArrayBuffer = dracoBufferTypedArray.buffer; const decodedPositions = new Uint16Array([0, 0, 0, 65535, 65535, 65535, 0, 65535, 0]); const decodedNormals = new Uint8Array([0, 255, 128, 128, 255, 0]); const decodedIndices = new Uint16Array([0, 1, 2]); const positions = new Float32Array([-1, -1, -1, 1, 1, 1, 0, 1, 0]); const normals = new Float32Array([-1, 0, 0, 1, 0, 0, 0, 1, 0]); const indicesUint32 = new Uint32Array([0, 1, 2]); const indicesUint16 = new Uint16Array([0, 1, 2]); const indicesUint8 = new Uint8Array([0, 1, 2]); const bufferViewTypedArray = concatTypedArrays_default([ positions, normals, indicesUint32, indicesUint16, indicesUint8 ]); const arrayBuffer = bufferViewTypedArray.buffer; const gltfUri = "https://example.com/model.glb"; const gltfResource = new import__490.Resource({ url: gltfUri }); const decodeDracoResults = { indexArray: { typedArray: decodedIndices, numberOfIndices: decodedIndices.length }, attributeData: { POSITION: { array: decodedPositions, data: { byteOffset: 0, byteStride: 6, componentDatatype: import__490.ComponentDatatype.UNSIGNED_SHORT, componentsPerAttribute: 3, normalized: false, quantization: { octEncoded: false, quantizationBits: 14, minValues: [-1, -1, -1], range: 2 } } }, NORMAL: { array: decodedNormals, data: { byteOffset: 0, byteStride: 2, componentDatatype: import__490.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 2, normalized: false, quantization: { octEncoded: true, quantizationBits: 10 } } } } }; const gltfDraco = { buffers: [ { uri: "external.bin", byteLength: 8 } ], bufferViews: [ { buffer: 0, byteOffset: 4, byteLength: 4 } ], accessors: [ { componentType: 5126, count: 3, max: [-1, -1, -1], min: [1, 1, 1], type: "VEC3" }, { componentType: 5126, count: 3, type: "VEC3" }, { componentType: 5123, count: 3, type: "SCALAR" } ], meshes: [ { primitives: [ { attributes: { POSITION: 0, NORMAL: 1 }, indices: 2, extensions: { KHR_draco_mesh_compression: { bufferView: 0, attributes: { POSITION: 0, NORMAL: 1 } } } } ] } ] }; const dracoExtension = gltfDraco.meshes[0].primitives[0].extensions.KHR_draco_mesh_compression; const gltfUncompressed = { buffers: [ { uri: "external.bin", byteLength: 78 } ], bufferViews: [ { buffer: 0, byteOffset: 0, byteLength: 36 }, { buffer: 0, byteOffset: 36, byteLength: 36 }, { buffer: 0, byteOffset: 72, byteLength: 12 }, { buffer: 0, byteOffset: 84, byteLength: 6 }, { buffer: 0, byteOffset: 90, byteLength: 3 } ], accessors: [ { componentType: 5126, count: 3, max: [-1, -1, -1], min: [1, 1, 1], type: "VEC3", bufferView: 0, byteOffset: 0 }, { componentType: 5126, count: 3, type: "VEC3", bufferView: 1, byteOffset: 0 }, { componentType: 5125, // UNSIGNED_INT count: 3, type: "SCALAR", bufferView: 2, byteOffset: 0 }, { componentType: 5123, // UNSIGNED_SHORT count: 3, type: "SCALAR", bufferView: 3, byteOffset: 0 }, { componentType: 5121, // UNSIGNED_BYTE count: 3, type: "SCALAR", bufferView: 4, byteOffset: 0 } ], meshes: [ { primitives: [ { attributes: { POSITION: 0, NORMAL: 1 }, indices: 2 }, { attributes: { POSITION: 0, NORMAL: 1 }, indices: 3 }, { attributes: { POSITION: 0, NORMAL: 1 }, indices: 4 } ] } ] }; let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { import__490.ResourceCache.clearForSpecs(); }); it("throws if resourceCache is undefined", function() { expect(function() { return new import__490.GltfIndexBufferLoader({ resourceCache: void 0, gltf: gltfUncompressed, accessorId: 3, gltfResource, baseResource: gltfResource, loadBuffer: true }); }).toThrowDeveloperError(); }); it("throws if gltf is undefined", function() { expect(function() { return new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: void 0, accessorId: 3, gltfResource, baseResource: gltfResource, loadBuffer: true }); }).toThrowDeveloperError(); }); it("throws if accessorId is undefined", function() { expect(function() { return new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: gltfUncompressed, accessorId: void 0, gltfResource, baseResource: gltfResource, loadBuffer: true }); }).toThrowDeveloperError(); }); it("throws if gltfResource is undefined", function() { expect(function() { return new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: gltfUncompressed, accessorId: 3, gltfResource: void 0, baseResource: gltfResource, loadBuffer: true }); }).toThrowDeveloperError(); }); it("throws if baseResource is undefined", function() { expect(function() { return new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: gltfUncompressed, accessorId: 3, gltfResource, baseResource: void 0, loadBuffer: true }); }).toThrowDeveloperError(); }); it("throws if both loadBuffer and loadTypedArray are false", function() { expect(function() { return new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: gltfUncompressed, accessorId: 3, gltfResource, baseResource: gltfResource, loadBuffer: false, loadTypedArray: false }); }).toThrowDeveloperError(); }); it("load throws if buffer view fails to load", async function() { spyOn(import__490.Resource.prototype, "fetchArrayBuffer").and.callFake( () => Promise.reject(new Error("404 Not Found")) ); const indexBufferLoader = new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: gltfUncompressed, accessorId: 3, gltfResource, baseResource: gltfResource, loadBuffer: true }); await expectAsync(indexBufferLoader.load()).toBeRejectedWithError( import__490.RuntimeError, "Failed to load index buffer\nFailed to load buffer view\nFailed to load external buffer: https://example.com/external.bin\n404 Not Found" ); }); it("process throws if draco fails to load", async function() { spyOn(import__490.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(dracoArrayBuffer) ); spyOn(import__490.DracoLoader, "decodeBufferView").and.callFake(function() { const error = new Error("Draco decode failed"); return Promise.reject(error); }); const indexBufferLoader = new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: gltfDraco, accessorId: 2, gltfResource, baseResource: gltfResource, draco: dracoExtension, loadBuffer: true }); await indexBufferLoader.load(); await expectAsync( waitForLoaderProcess_default(indexBufferLoader, scene2) ).toBeRejectedWithError( import__490.RuntimeError, "Failed to load index buffer\nFailed to load Draco\nDraco decode failed" ); }); it("loads from accessor into buffer", async function() { spyOn(import__490.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); const processCallsTotal = 3; let processCallsCount = 0; const jobScheduler = scene2.frameState.jobScheduler; const originalJobSchedulerExecute = jobScheduler.execute; spyOn(import__490.JobScheduler.prototype, "execute").and.callFake(function(job, jobType) { if (processCallsCount++ >= processCallsTotal) { return originalJobSchedulerExecute.call(jobScheduler, job, jobType); } return false; }); const indexBufferLoader = new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: gltfUncompressed, accessorId: 3, gltfResource, baseResource: gltfResource, loadBuffer: true }); await indexBufferLoader.load(); await waitForLoaderProcess_default(indexBufferLoader, scene2); expect(() => loaderProcess_default(indexBufferLoader, scene2)).not.toThrow(); expect(indexBufferLoader.buffer.sizeInBytes).toBe( indicesUint16.byteLength ); expect(indexBufferLoader.typedArray).toBeUndefined(); expect(import__490.ResourceCache.statistics.geometryByteLength).toBe( indexBufferLoader.buffer.sizeInBytes ); }); it("loads from accessor as typed array", async function() { spyOn(import__490.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); spyOn(import__490.Buffer, "createIndexBuffer").and.callThrough(); const indexBufferLoader = new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: gltfUncompressed, accessorId: 3, gltfResource, baseResource: gltfResource, loadTypedArray: true }); await indexBufferLoader.load(); await waitForLoaderProcess_default(indexBufferLoader, scene2); expect(indexBufferLoader.typedArray.byteLength).toBe( indicesUint16.byteLength ); expect(indexBufferLoader.buffer).toBeUndefined(); expect(import__490.Buffer.createIndexBuffer.calls.count()).toBe(0); expect(import__490.ResourceCache.statistics.geometryByteLength).toBe( indexBufferLoader.typedArray.byteLength ); }); it("loads from accessor as buffer and typed array", async function() { spyOn(import__490.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); const indexBufferLoader = new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: gltfUncompressed, accessorId: 3, gltfResource, baseResource: gltfResource, loadBuffer: true, loadTypedArray: true }); await indexBufferLoader.load(); await waitForLoaderProcess_default(indexBufferLoader, scene2); expect(indexBufferLoader.buffer.sizeInBytes).toBe( indicesUint16.byteLength ); expect(indexBufferLoader.typedArray.byteLength).toBe( indicesUint16.byteLength ); expect(import__490.ResourceCache.statistics.geometryByteLength).toBe( 2 * indexBufferLoader.typedArray.byteLength ); }); it("creates index buffer synchronously", async function() { spyOn(import__490.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); const indexBufferLoader = new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: gltfUncompressed, accessorId: 3, gltfResource, baseResource: gltfResource, asynchronous: false, loadBuffer: true }); await indexBufferLoader.load(); await waitForLoaderProcess_default(indexBufferLoader, scene2); expect(indexBufferLoader.buffer.sizeInBytes).toBe( indicesUint16.byteLength ); }); async function loadIndices(accessorId, expectedByteLength) { spyOn(import__490.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); const indexBufferLoader = new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: gltfUncompressed, accessorId, gltfResource, baseResource: gltfResource, loadBuffer: true }); await indexBufferLoader.load(); await waitForLoaderProcess_default(indexBufferLoader, scene2); expect(indexBufferLoader.buffer.sizeInBytes).toBe(expectedByteLength); } it("loads uint32 indices", function() { if (!scene2.frameState.context.elementIndexUint) { return; } return loadIndices(2, indicesUint32.byteLength); }); it("loads uint16 indices", function() { return loadIndices(3, indicesUint16.byteLength); }); it("loads uint8 indices", function() { return loadIndices(4, indicesUint8.byteLength); }); it("loads from draco", async function() { spyOn(import__490.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); const processCallsTotal = 3; let processCallsCount = 0; spyOn(import__490.DracoLoader, "decodeBufferView").and.callFake(function() { if (processCallsCount++ === processCallsTotal) { return Promise.resolve(decodeDracoResults); } return void 0; }); const indexBufferLoader = new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: gltfDraco, accessorId: 2, gltfResource, baseResource: gltfResource, draco: dracoExtension, loadBuffer: true }); await indexBufferLoader.load(); await waitForLoaderProcess_default(indexBufferLoader, scene2); expect(() => loaderProcess_default(indexBufferLoader, scene2)).not.toThrow(); expect(indexBufferLoader.buffer.sizeInBytes).toBe( decodedIndices.byteLength ); expect(import__490.ResourceCache.statistics.geometryByteLength).toBe( indexBufferLoader.buffer.sizeInBytes ); }); it("uses the decoded data's type instead of the accessor component type", async function() { spyOn(import__490.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); spyOn(import__490.DracoLoader, "decodeBufferView").and.returnValue( Promise.resolve(decodeDracoResults) ); const clonedGltf = (0, import__490.clone)(gltfDraco, true); clonedGltf.accessors[2].componentType = 5125; const indexBufferLoader = new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: clonedGltf, accessorId: 2, gltfResource, baseResource: gltfResource, draco: dracoExtension, loadBuffer: true }); await indexBufferLoader.load(); await waitForLoaderProcess_default(indexBufferLoader, scene2); expect(indexBufferLoader.indexDatatype).toBe(5123); expect(indexBufferLoader.buffer.indexDatatype).toBe(5123); }); it("destroys index buffer loaded from buffer view", async function() { spyOn(import__490.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); const unloadBufferView = spyOn( import__490.GltfBufferViewLoader.prototype, "unload" ).and.callThrough(); const destroyIndexBuffer = spyOn( import__490.Buffer.prototype, "destroy" ).and.callThrough(); const indexBufferLoader = new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: gltfUncompressed, accessorId: 3, gltfResource, baseResource: gltfResource, loadBuffer: true }); await indexBufferLoader.load(); await waitForLoaderProcess_default(indexBufferLoader, scene2); expect(indexBufferLoader.buffer).toBeDefined(); expect(indexBufferLoader.isDestroyed()).toBe(false); indexBufferLoader.destroy(); expect(indexBufferLoader.buffer).not.toBeDefined(); expect(indexBufferLoader.isDestroyed()).toBe(true); expect(unloadBufferView).toHaveBeenCalled(); expect(destroyIndexBuffer).toHaveBeenCalled(); }); it("destroys index buffer loaded from draco", async function() { spyOn(import__490.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); spyOn(import__490.DracoLoader, "decodeBufferView").and.returnValue( Promise.resolve(decodeDracoResults) ); const unloadDraco = spyOn( import__490.GltfDracoLoader.prototype, "unload" ).and.callThrough(); const destroyIndexBuffer = spyOn( import__490.Buffer.prototype, "destroy" ).and.callThrough(); const indexBufferLoader = new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: gltfDraco, accessorId: 2, gltfResource, baseResource: gltfResource, draco: dracoExtension, loadBuffer: true }); await indexBufferLoader.load(); await waitForLoaderProcess_default(indexBufferLoader, scene2); expect(indexBufferLoader.buffer).toBeDefined(); expect(indexBufferLoader.isDestroyed()).toBe(false); indexBufferLoader.destroy(); expect(indexBufferLoader.buffer).not.toBeDefined(); expect(indexBufferLoader.isDestroyed()).toBe(true); expect(unloadDraco).toHaveBeenCalled(); expect(destroyIndexBuffer).toHaveBeenCalled(); }); async function resolveBufferViewAfterDestroy(rejectPromise) { const indexBufferLoader = new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: gltfUncompressed, accessorId: 3, gltfResource, baseResource: gltfResource, loadBuffer: true }); spyOn(import__490.Resource.prototype, "fetchArrayBuffer").and.callFake( () => rejectPromise ? Promise.reject(new Error()) : Promise.resolve(arrayBuffer) ); expect(indexBufferLoader.buffer).not.toBeDefined(); const promise = indexBufferLoader.load(); indexBufferLoader.destroy(); await expectAsync(promise).toBeResolved(); expect(indexBufferLoader.buffer).not.toBeDefined(); expect(indexBufferLoader.isDestroyed()).toBe(true); } it("handles resolving buffer view after destroy", function() { return resolveBufferViewAfterDestroy(false); }); it("handles rejecting buffer view after destroy", function() { return resolveBufferViewAfterDestroy(true); }); async function resolveDracoAfterDestroy(rejectPromise) { const indexBufferLoader = new import__490.GltfIndexBufferLoader({ resourceCache: import__490.ResourceCache, gltf: gltfDraco, accessorId: 2, gltfResource, baseResource: gltfResource, draco: dracoExtension, loadBuffer: true }); spyOn(import__490.Resource.prototype, "fetchArrayBuffer").and.callFake(function() { setTimeout(function() { indexBufferLoader.destroy(); }, 1); return Promise.resolve(arrayBuffer); }); const decodeBufferView = spyOn( import__490.DracoLoader, "decodeBufferView" ).and.callFake(function() { return new Promise(function(resolve, reject) { if (rejectPromise) { reject(new Error("Draco decode failed")); } else { resolve(decodeDracoResults); } }); }); expect(indexBufferLoader.buffer).not.toBeDefined(); await indexBufferLoader.load(); await expectAsync( waitForLoaderProcess_default(indexBufferLoader, scene2) ).toBeResolved(); expect(decodeBufferView).toHaveBeenCalled(); expect(indexBufferLoader.buffer).not.toBeDefined(); expect(indexBufferLoader.isDestroyed()).toBe(true); } it("handles resolving draco after destroy", function() { return resolveDracoAfterDestroy(false); }); it("handles rejecting draco after destroy", function() { return resolveDracoAfterDestroy(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/GltfJsonLoaderSpec.js var import__491 = __toESM(require_Cesium(), 1); describe("Scene/GltfJsonLoader", function() { const gltfUri = "https://example.com/model.glb"; const gltfResource = new import__491.Resource({ url: gltfUri }); const gltf1 = { asset: { version: "1.0" }, buffers: { buffer: { uri: "external.bin" } }, bufferViews: { bufferView: { buffer: "buffer", byteOffset: 0 } }, accessors: { accessor: { bufferView: "bufferView", byteOffset: 0, componentType: 5126, type: "VEC3", count: 1 } }, meshes: { mesh: { primitives: [ { attributes: { POSITION: "accessor" }, material: "red" } ] } }, nodes: { node: { meshes: ["mesh"] } }, scene: "scene", scenes: { scene: { nodes: ["node"] } }, shaders: { Box0FS: { type: 35632, uri: "data:text/plain;base64," }, Box0VS: { type: 35633, uri: "data:text/plain;base64," } }, programs: { program_0: { attributes: ["a_position"], fragmentShader: "Box0FS", vertexShader: "Box0VS" } }, materials: { red: { technique: "technique0", values: { diffuse: [0.8, 0, 0, 1], shininess: 256, specular: [0.2, 0.2, 0.2, 1] } } }, techniques: { technique0: { attributes: { a_position: "position" }, parameters: { diffuse: { type: 35666 }, modelViewMatrix: { semantic: "MODELVIEW", type: 35676 }, position: { semantic: "POSITION", type: 35665 }, projectionMatrix: { semantic: "PROJECTION", type: 35676 }, shininess: { type: 5126 }, specular: { type: 35666 } }, program: "program_0", states: { enable: [2929, 2884] }, uniforms: { u_diffuse: "diffuse", u_modelViewMatrix: "modelViewMatrix", u_projectionMatrix: "projectionMatrix", u_shininess: "shininess", u_specular: "specular" } } } }; const gltf1MaterialsCommon = { asset: { version: "1.0" }, buffers: { buffer: { uri: "external.bin" } }, bufferViews: { bufferView: { buffer: "buffer", byteOffset: 0 } }, accessors: { accessor: { bufferView: "bufferView", byteOffset: 0, componentType: 5126, type: "VEC3", count: 1 } }, materials: { red: { extensions: { KHR_materials_common: { doubleSided: false, jointCount: 0, technique: "PHONG", transparent: false, values: { diffuse: [0.8, 0, 0, 1], shininess: 256, specular: [0.2, 0.2, 0.2, 1] } } } } }, meshes: { mesh: { primitives: [ { attributes: { POSITION: "accessor" }, material: "red" } ] } }, nodes: { node: { meshes: ["mesh"] } }, scene: "scene", scenes: { scene: { nodes: ["node"] } }, extensionsUsed: ["KHR_materials_common"] }; const gltf2 = { asset: { version: "2.0" }, buffers: [ { name: "buffer", uri: "external.bin", byteLength: 12 } ], bufferViews: [ { name: "bufferView", buffer: 0, byteOffset: 0, byteLength: 12 } ], accessors: [ { name: "accessor", bufferView: 0, byteOffset: 0, componentType: 5126, type: "VEC3", count: 1, min: [0, 0, 0], max: [0, 0, 0] } ], materials: [ { name: "red", pbrMetallicRoughness: { roughnessFactor: 1, metallicFactor: 0, baseColorFactor: [0.6038273388553378, 0, 0, 1] } } ], meshes: [ { name: "mesh", primitives: [ { attributes: { POSITION: 0 }, material: 0 } ] } ], nodes: [ { name: "node", mesh: 0, matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] } ], scene: 0, scenes: [ { name: "scene", nodes: [0] } ] }; const gltf2TechniquesWebgl = { asset: { version: "2.0" }, buffers: [ { name: "buffer", uri: "external.bin", byteLength: 12 } ], bufferViews: [ { name: "bufferView", buffer: 0, byteOffset: 0, byteLength: 12 } ], accessors: [ { name: "accessor", bufferView: 0, byteOffset: 0, componentType: 5126, type: "VEC3", count: 1, min: [0, 0, 0], max: [0, 0, 0] } ], meshes: [ { name: "mesh", primitives: [ { attributes: { POSITION: 0 }, material: 0 } ] } ], nodes: [ { name: "node", mesh: 0, matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] } ], scene: 0, scenes: [ { name: "scene", nodes: [0] } ], materials: [ { name: "red", extensions: { KHR_techniques_webgl: { technique: 0, values: { u_diffuse: [0.8, 0, 0, 1], u_shininess: 256, u_specular: [0.2, 0.2, 0.2, 1] } } } } ], extensionsUsed: ["KHR_techniques_webgl"], extensionsRequired: ["KHR_techniques_webgl"], extensions: { KHR_techniques_webgl: { programs: [ { name: "program_0", fragmentShader: 0, vertexShader: 1 } ], shaders: [ { type: 35632, name: "Box0FS", bufferView: 2 }, { type: 35633, name: "Box0VS", bufferView: 3 } ], techniques: [ { name: "technique0", program: 0, attributes: { a_position: { semantic: "POSITION" } }, uniforms: { u_diffuse: { type: 35666 }, u_modelViewMatrix: { type: 35676, semantic: "MODELVIEW" }, u_projectionMatrix: { type: 35676, semantic: "PROJECTION" }, u_shininess: { type: 5126 }, u_specular: { type: 35666 } } } ] } } }; const gltf2Updated = { asset: { version: "2.0" }, buffers: [ { uri: "external.bin", name: "buffer", byteLength: 12 } ], bufferViews: [ { buffer: 0, byteOffset: 0, name: "bufferView", byteLength: 12, byteStride: 12, target: 34962 } ], accessors: [ { bufferView: 0, byteOffset: 0, componentType: 5126, type: "VEC3", count: 1, name: "accessor", min: [0, 0, 0], max: [0, 0, 0], normalized: false } ], meshes: [ { primitives: [ { attributes: { POSITION: 0 }, mode: 4, material: 0 } ], name: "mesh" } ], nodes: [ { name: "node", mesh: 0, matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] } ], scene: 0, scenes: [ { nodes: [0], name: "scene" } ], materials: [ { name: "red", pbrMetallicRoughness: { roughnessFactor: 1, metallicFactor: 0, baseColorFactor: [0.6038273388553378, 0, 0, 1] }, emissiveFactor: [0, 0, 0], alphaMode: "OPAQUE", doubleSided: false } ] }; function createGlb1(json) { const jsonBuffer = generateJsonBuffer_default(json, 12, 4); const positionBuffer = new Float32Array([0, 0, 0]); const binaryBuffer = new Uint8Array(positionBuffer.buffer); const glbLength = 20 + jsonBuffer.byteLength + binaryBuffer.byteLength; const glb = new Uint8Array(glbLength); const dataView = new DataView(glb.buffer, glb.byteOffset, glb.byteLength); let byteOffset = 0; dataView.setUint32(byteOffset, 1179937895, true); byteOffset += 4; dataView.setUint32(byteOffset, 1, true); byteOffset += 4; dataView.setUint32(byteOffset, glbLength, true); byteOffset += 4; dataView.setUint32(byteOffset, jsonBuffer.byteLength, true); byteOffset += 4; dataView.setUint32(byteOffset, 0, true); byteOffset += 4; glb.set(jsonBuffer, byteOffset); byteOffset += jsonBuffer.byteLength; glb.set(binaryBuffer, byteOffset); return glb; } function createGlb2(json) { const jsonBuffer = generateJsonBuffer_default(json, 12, 4); const positionBuffer = new Float32Array([0, 0, 0]); const binaryBuffer = new Uint8Array(positionBuffer.buffer); const glbLength = 12 + 8 + jsonBuffer.byteLength + 8 + binaryBuffer.byteLength; const glb = new Uint8Array(glbLength); const dataView = new DataView(glb.buffer, glb.byteOffset, glb.byteLength); let byteOffset = 0; dataView.setUint32(byteOffset, 1179937895, true); byteOffset += 4; dataView.setUint32(byteOffset, 2, true); byteOffset += 4; dataView.setUint32(byteOffset, glbLength, true); byteOffset += 4; dataView.setUint32(byteOffset, jsonBuffer.byteLength, true); byteOffset += 4; dataView.setUint32(byteOffset, 1313821514, true); byteOffset += 4; glb.set(jsonBuffer, byteOffset); byteOffset += jsonBuffer.byteLength; dataView.setUint32(byteOffset, binaryBuffer.byteLength); byteOffset += 4; dataView.setUint32(byteOffset, 5130562, true); byteOffset += 4; glb.set(binaryBuffer, byteOffset); return glb; } afterEach(function() { import__491.ResourceCache.clearForSpecs(); }); it("throws if resourceCache is undefined", function() { expect(function() { return new import__491.GltfJsonLoader({ resourceCache: void 0, gltfResource, baseResource: gltfResource }); }).toThrowDeveloperError(); }); it("throws if gltfResource is undefined", function() { expect(function() { return new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource: void 0, baseResource: gltfResource }); }).toThrowDeveloperError(); }); it("throws if baseResource is undefined", function() { expect(function() { return new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: void 0 }); }).toThrowDeveloperError(); }); it("load throws if resource fails to load", async function() { spyOn(import__491.GltfJsonLoader.prototype, "_fetchGltf").and.callFake(function() { const error = new Error("404 Not Found"); return Promise.reject(error); }); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource }); await expectAsync(gltfJsonLoader.load()).toBeRejectedWithError( import__491.RuntimeError, "Failed to load glTF: https://example.com/model.glb\n404 Not Found" ); }); it("load throws if an unsupported extension is required", async function() { const arrayBuffer = generateJsonBuffer_default({ ...gltf1, extensionsRequired: ["NOT_supported_extension"] }).buffer; spyOn(import__491.GltfJsonLoader.prototype, "_fetchGltf").and.returnValue( Promise.resolve(arrayBuffer) ); spyOn(import__491.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(new Float32Array([0, 0, 0]).buffer) ); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource }); await expectAsync(gltfJsonLoader.load()).toBeRejectedWithError( import__491.RuntimeError, "Failed to load glTF: https://example.com/model.glb\nUnsupported glTF Extension: NOT_supported_extension" ); }); it("load throws if glTF fails to process", async function() { const arrayBuffer = generateJsonBuffer_default(gltf1).buffer; spyOn(import__491.GltfJsonLoader.prototype, "_fetchGltf").and.returnValue( Promise.resolve(arrayBuffer) ); spyOn(import__491.Resource.prototype, "fetchArrayBuffer").and.callFake(function() { const error = new Error("404 Not Found"); return Promise.reject(error); }); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource }); await expectAsync(gltfJsonLoader.load()).toBeRejectedWithError( import__491.RuntimeError, "Failed to load glTF: https://example.com/model.glb\nFailed to load external buffer: https://example.com/external.bin\n404 Not Found" ); }); it("load throws if glTF fails to process from typed array", async function() { const typedArray = createGlb1(gltf1); spyOn(import__491.Resource.prototype, "fetchArrayBuffer").and.callFake(function() { const error = new Error("404 Not Found"); return Promise.reject(error); }); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource, typedArray }); await expectAsync(gltfJsonLoader.load()).toBeRejectedWithError( import__491.RuntimeError, "Failed to load glTF: https://example.com/model.glb\nFailed to load external buffer: https://example.com/external.bin\n404 Not Found" ); }); it("loads glTF 1.0", async function() { const arrayBuffer = generateJsonBuffer_default(gltf1).buffer; spyOn(import__491.GltfJsonLoader.prototype, "_fetchGltf").and.returnValue( Promise.resolve(arrayBuffer) ); spyOn(import__491.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(new Float32Array([0, 0, 0]).buffer) ); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource }); await gltfJsonLoader.load(); const gltf = gltfJsonLoader.gltf; expect(gltf).toEqual(gltf2Updated); }); it("loads glTF 1.0 with KHR_materials_common", async function() { const arrayBuffer = generateJsonBuffer_default(gltf1MaterialsCommon).buffer; spyOn(import__491.GltfJsonLoader.prototype, "_fetchGltf").and.returnValue( Promise.resolve(arrayBuffer) ); spyOn(import__491.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(new Float32Array([0, 0, 0]).buffer) ); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource }); await gltfJsonLoader.load(); const gltf = gltfJsonLoader.gltf; expect(gltf).toEqual(gltf2Updated); }); it("loads glTF 1.0 binary", async function() { const gltf1Binary = (0, import__491.clone)(gltf1, true); gltf1Binary.buffers = { binary_glTF: { type: "arraybuffer", byteLength: 12, uri: "data:," } }; gltf1Binary.extensionsUsed = ["KHR_binary_glTF"]; gltf1Binary.bufferViews.bufferView.buffer = "binary_glTF"; const gltf1BinaryUpdated = (0, import__491.clone)(gltf2Updated, true); gltf1BinaryUpdated.buffers[0].name = "binary_glTF"; delete gltf1BinaryUpdated.buffers[0].uri; const arrayBuffer = createGlb1(gltf1Binary).buffer; spyOn(import__491.GltfJsonLoader.prototype, "_fetchGltf").and.returnValue( Promise.resolve(arrayBuffer) ); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource }); await gltfJsonLoader.load(); const gltf = gltfJsonLoader.gltf; expect(gltf).toEqual(gltf1BinaryUpdated); }); it("loads glTF 1.0 with data uri", async function() { const gltf1DataUri = (0, import__491.clone)(gltf1, true); gltf1DataUri.buffers.buffer = { uri: "data:application/octet-stream;base64,AAAAAAAAAAAAAAAA" }; const gltf1DataUriUpdated = (0, import__491.clone)(gltf2Updated, true); delete gltf1DataUriUpdated.buffers[0].uri; const arrayBuffer = generateJsonBuffer_default(gltf1DataUri).buffer; spyOn(import__491.GltfJsonLoader.prototype, "_fetchGltf").and.returnValue( Promise.resolve(arrayBuffer) ); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource }); await gltfJsonLoader.load(); const gltf = gltfJsonLoader.gltf; expect(gltf).toEqual(gltf1DataUriUpdated); }); it("loads glTF 2.0", async function() { const arrayBuffer = generateJsonBuffer_default(gltf2).buffer; spyOn(import__491.GltfJsonLoader.prototype, "_fetchGltf").and.returnValue( Promise.resolve(arrayBuffer) ); spyOn(import__491.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(new Float32Array([0, 0, 0]).buffer) ); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource }); await gltfJsonLoader.load(); const gltf = gltfJsonLoader.gltf; expect(gltf).toEqual(gltf2Updated); }); it("loads glTF 2.0 with KHR_techniques_webgl", async function() { const arrayBuffer = generateJsonBuffer_default(gltf2TechniquesWebgl).buffer; spyOn(import__491.GltfJsonLoader.prototype, "_fetchGltf").and.returnValue( Promise.resolve(arrayBuffer) ); spyOn(import__491.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(new Float32Array([0, 0, 0]).buffer) ); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource }); await gltfJsonLoader.load(); const gltf = gltfJsonLoader.gltf; expect(gltf).toEqual(gltf2Updated); }); it("loads glTF 2.0 binary", async function() { const gltf2Binary = (0, import__491.clone)(gltf2, true); delete gltf2Binary.buffers[0].uri; const gltf2BinaryUpdated = (0, import__491.clone)(gltf2Updated, true); delete gltf2BinaryUpdated.buffers[0].uri; const arrayBuffer = createGlb2(gltf2Binary).buffer; spyOn(import__491.GltfJsonLoader.prototype, "_fetchGltf").and.returnValue( Promise.resolve(arrayBuffer) ); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource }); await gltfJsonLoader.load(); const gltf = gltfJsonLoader.gltf; expect(gltf).toEqual(gltf2BinaryUpdated); }); it("loads glTF 2.0 with data uri", async function() { const gltf2DataUri = (0, import__491.clone)(gltf2, true); gltf2DataUri.buffers[0].uri = "data:application/octet-stream;base64,AAAAAAAAAAAAAAAA"; const gltf2DataUriUpdated = (0, import__491.clone)(gltf2Updated, true); delete gltf2DataUriUpdated.buffers[0].uri; const arrayBuffer = generateJsonBuffer_default(gltf2DataUri).buffer; spyOn(import__491.GltfJsonLoader.prototype, "_fetchGltf").and.returnValue( Promise.resolve(arrayBuffer) ); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource }); await gltfJsonLoader.load(); const gltf = gltfJsonLoader.gltf; expect(gltf).toEqual(gltf2DataUriUpdated); }); it("loads typed array", async function() { const gltf2Binary = (0, import__491.clone)(gltf2, true); delete gltf2Binary.buffers[0].uri; const gltf2BinaryUpdated = (0, import__491.clone)(gltf2Updated, true); delete gltf2BinaryUpdated.buffers[0].uri; const typedArray = createGlb2(gltf2Binary); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource, typedArray }); await gltfJsonLoader.load(); const gltf = gltfJsonLoader.gltf; expect(gltf).toEqual(gltf2BinaryUpdated); }); it("loads JSON directly", async function() { const gltf = (0, import__491.clone)(gltf2, true); spyOn(import__491.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(new Float32Array([0, 0, 0]).buffer) ); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource, gltfJson: gltf }); await gltfJsonLoader.load(); const loadedGltf = gltfJsonLoader.gltf; expect(loadedGltf).toEqual(gltf2Updated); }); it("destroys", async function() { const gltf2Binary = (0, import__491.clone)(gltf2, true); delete gltf2Binary.buffers[0].uri; const arrayBuffer = createGlb2(gltf2Binary).buffer; spyOn(import__491.GltfJsonLoader.prototype, "_fetchGltf").and.returnValue( Promise.resolve(arrayBuffer) ); const unloadBuffer = spyOn( import__491.BufferLoader.prototype, "unload" ).and.callThrough(); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource }); await gltfJsonLoader.load(); expect(gltfJsonLoader.gltf).toBeDefined(); expect(gltfJsonLoader.isDestroyed()).toBe(false); gltfJsonLoader.destroy(); expect(gltfJsonLoader.gltf).not.toBeDefined(); expect(gltfJsonLoader.isDestroyed()).toBe(true); expect(unloadBuffer).toHaveBeenCalled(); }); async function resolvesGltfAfterDestroy(rejectPromise) { const arrayBuffer = generateJsonBuffer_default(gltf2).buffer; spyOn(import__491.GltfJsonLoader.prototype, "_fetchGltf").and.callFake( () => rejectPromise ? Promise.reject(new Error()) : Promise.resolve(arrayBuffer) ); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource }); expect(gltfJsonLoader.gltf).not.toBeDefined(); const promise = gltfJsonLoader.load(); gltfJsonLoader.destroy(); await expectAsync(promise).toBeResolved(); expect(gltfJsonLoader.gltf).not.toBeDefined(); expect(gltfJsonLoader.isDestroyed()).toBe(true); } it("handles resolving glTF after destroy", function() { return resolvesGltfAfterDestroy(false); }); it("handles rejecting glTF after destroy", function() { return resolvesGltfAfterDestroy(true); }); async function resolvesProcessedGltfAfterDestroy(rejectPromise) { spyOn(import__491.GltfJsonLoader.prototype, "_fetchGltf").and.returnValue( Promise.resolve(generateJsonBuffer_default(gltf2).buffer) ); const buffer = new Float32Array([0, 0, 0]).buffer; spyOn(import__491.Resource.prototype, "fetchArrayBuffer").and.callFake(function() { return new Promise(function(resolve, reject) { if (rejectPromise) { reject(new Error()); } else { resolve(buffer); } }); }); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource }); expect(gltfJsonLoader.gltf).not.toBeDefined(); const promise = gltfJsonLoader.load(); gltfJsonLoader.destroy(); await expectAsync(promise).toBeResolved(); expect(gltfJsonLoader.gltf).not.toBeDefined(); expect(gltfJsonLoader.isDestroyed()).toBe(true); } it("handles resolving processed glTF after destroy", function() { return resolvesProcessedGltfAfterDestroy(false); }); it("handles rejecting processed glTF after destroy", function() { return resolvesProcessedGltfAfterDestroy(true); }); async function resolvesTypedArrayAfterDestroy(rejectPromise) { const typedArray = generateJsonBuffer_default(gltf1); const gltfJsonLoader = new import__491.GltfJsonLoader({ resourceCache: import__491.ResourceCache, gltfResource, baseResource: gltfResource, typedArray }); const buffer = new Float32Array([0, 0, 0]).buffer; spyOn(import__491.Resource.prototype, "fetchArrayBuffer").and.callFake(function() { return new Promise(function(resolve, reject) { if (rejectPromise) { reject(new Error()); return; } resolve(buffer); }); }); expect(gltfJsonLoader.gltf).not.toBeDefined(); const promise = gltfJsonLoader.load(); gltfJsonLoader.destroy(); await expectAsync(promise).toBeResolved(); expect(gltfJsonLoader.gltf).not.toBeDefined(); expect(gltfJsonLoader.isDestroyed()).toBe(true); } it("handles resolving typed array after destroy", function() { return resolvesTypedArrayAfterDestroy(false); }); it("handles rejecting typed array after destroy", function() { return resolvesTypedArrayAfterDestroy(true); }); }); // packages/engine/Specs/Scene/GltfLoaderSpec.js var import__492 = __toESM(require_Cesium(), 1); describe( "Scene/GltfLoader", function() { const boxWithCredits = "./Data/Models/glTF-2.0/BoxWithCopyright/glTF/Box.gltf"; const boxInterleaved = "./Data/Models/glTF-2.0/BoxInterleaved/glTF/BoxInterleaved.gltf"; const boxTextured = "./Data/Models/glTF-2.0/BoxTextured/glTF/BoxTextured.gltf"; const boxTexturedBinary = "./Data/Models/glTF-2.0/BoxTextured/glTF-Binary/BoxTextured.glb"; const boxTexturedEmbedded = "./Data/Models/glTF-2.0/BoxTextured/glTF-Embedded/BoxTextured.gltf"; const boxTexturedKtx2Basis = "./Data/Models/glTF-2.0/BoxTexturedKtx2Basis/glTF/BoxTexturedKtx2Basis.gltf"; const boxTexturedKtx2BasisBinary = "./Data/Models/glTF-2.0/BoxTexturedKtx2Basis/glTF-Binary/BoxTexturedKtx2Basis.glb"; const boxVertexColors = "./Data/Models/glTF-2.0/BoxVertexColors/glTF/BoxVertexColors.gltf"; const simpleMorph = "./Data/Models/glTF-2.0/SimpleMorph/glTF/SimpleMorph.gltf"; const simpleSkin = "./Data/Models/glTF-2.0/SimpleSkin/glTF/SimpleSkin.gltf"; const animatedTriangle = "./Data/Models/glTF-2.0/AnimatedTriangle/glTF/AnimatedTriangle.gltf"; const animatedMorphCube = "./Data/Models/glTF-2.0/AnimatedMorphCube/glTF/AnimatedMorphCube.gltf"; const interpolationTest = "./Data/Models/glTF-2.0/InterpolationTest/glTF-Binary/InterpolationTest.glb"; const triangle = "./Data/Models/glTF-2.0/Triangle/glTF/Triangle.gltf"; const triangleWithoutIndices = "./Data/Models/glTF-2.0/TriangleWithoutIndices/glTF/TriangleWithoutIndices.gltf"; const twoSidedPlane = "./Data/Models/glTF-2.0/TwoSidedPlane/glTF/TwoSidedPlane.gltf"; const unlitTest = "./Data/Models/glTF-2.0/UnlitTest/glTF/UnlitTest.gltf"; const microcosm = "./Data/Models/glTF-2.0/Microcosm/glTF/microcosm.gltf"; const microcosmLegacy = "./Data/Models/glTF-2.0/Microcosm/glTF/microcosm_EXT_feature_metadata.gltf"; const buildingsMetadata = "./Data/Models/glTF-2.0/BuildingsMetadata/glTF/buildings-metadata.gltf"; const buildingsMetadataLegacy = "./Data/Models/glTF-2.0/BuildingsMetadata/glTF/buildings-metadata_EXT_feature_metadata.gltf"; const weather = "./Data/Models/glTF-2.0/Weather/glTF/weather.gltf"; const weatherLegacy = "./Data/Models/glTF-2.0/Weather/glTF/weather_EXT_feature_metadata.gltf"; const pointCloudWithPropertyAttributes = "./Data/Models/glTF-2.0/PointCloudWithPropertyAttributes/glTF/PointCloudWithPropertyAttributes.gltf"; const boxWithPropertyAttributes = "./Data/Models/glTF-2.0/BoxTexturedWithPropertyAttributes/glTF/BoxTexturedWithPropertyAttributes.gltf"; const boxInstanced = "./Data/Models/glTF-2.0/BoxInstanced/glTF/box-instanced.gltf"; const boxInstancedLegacy = "./Data/Models/glTF-2.0/BoxInstanced/glTF/box-instanced_EXT_feature_metadata.gltf"; const boxInstancedInterleaved = "./Data/Models/glTF-2.0/BoxInstancedInterleaved/glTF/box-instanced-interleaved.gltf"; const boxInstancedTranslation = "./Data/Models/glTF-2.0/BoxInstancedTranslation/glTF/box-instanced-translation.gltf"; const boxInstancedTranslationMinMax = "./Data/Models/glTF-2.0/BoxInstancedTranslationWithMinMax/glTF/box-instanced-translation-min-max.gltf"; const duckDraco = "./Data/Models/glTF-2.0/Duck/glTF-Draco/Duck.gltf"; const boxMixedCompression = "./Data/Models/glTF-2.0/BoxMixedCompression/glTF/BoxMixedCompression.gltf"; const boomBoxSpecularGlossiness = "./Data/Models/glTF-2.0/BoomBox/glTF-pbrSpecularGlossiness/BoomBox.gltf"; const largeFeatureIdTexture = "./Data/Models/glTF-2.0/LargeFeatureIdTexture/glTF/LargeFeatureIdTexture.gltf"; const boxArticulations = "./Data/Models/glTF-2.0/BoxArticulations/glTF/BoxArticulations.gltf"; const boxWithPrimitiveOutline = "./Data/Models/glTF-2.0/BoxWithPrimitiveOutline/glTF/BoxWithPrimitiveOutline.gltf"; const boxWithPrimitiveOutlineSharedVertices = "./Data/Models/glTF-2.0/BoxWithPrimitiveOutlineSharedVertices/glTF/BoxWithPrimitiveOutlineSharedVertices.gltf"; const multiUvTest = "./Data/Models/glTF-2.0/MultiUVTest/glTF-Binary/MultiUVTest.glb"; const boxCesiumRtc = "./Data/Models/glTF-2.0/BoxCesiumRtc/glTF/BoxCesiumRtc.gltf"; const torusQuantized = "./Data/Models/glTF-2.0/TorusQuantized/glTF/TorusQuantized.gltf"; const boxWeb3dQuantizedAttributes = "./Data/Models/glTF-2.0/BoxWeb3dQuantizedAttributes/glTF/BoxWeb3dQuantizedAttributes.gltf"; let scene2; const gltfLoaders = []; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { const gltfLoadersLength = gltfLoaders.length; for (let i = 0; i < gltfLoadersLength; ++i) { const gltfLoader = gltfLoaders[i]; if (!gltfLoader.isDestroyed()) { gltfLoader.destroy(); } } gltfLoaders.length = 0; import__492.ResourceCache.clearForSpecs(); }); it("throws if gltfResource is undefined", function() { expect(function() { return new import__492.GltfVertexBufferLoader({ gltfResource: void 0 }); }).toThrowDeveloperError(); }); it("load throws if glTF JSON fails to load", async function() { const error = new Error("404 Not Found"); spyOn(import__492.GltfJsonLoader.prototype, "_fetchGltf").and.returnValue( Promise.reject(error) ); const gltfResource = new import__492.Resource({ url: "https://example.com/model.glb" }); const gltfLoader = new import__492.GltfLoader({ gltfResource, releaseGltfJson: true }); gltfLoaders.push(gltfLoader); await expectAsync(gltfLoader.load()).toBeRejectedWithError( import__492.RuntimeError, "Failed to load glTF\nFailed to load glTF: https://example.com/model.glb\n404 Not Found" ); }); function getOptions(gltfPath, options) { const resource = new import__492.Resource({ url: gltfPath }); return (0, import__492.combine)(options, { gltfResource: resource, incrementallyLoadTextures: false // Default to false if not supplied }); } async function loadGltf(gltfPath, options) { options = (0, import__492.defaultValue)(options, import__492.defaultValue.EMPTY_OBJECT); const gltfLoader = new import__492.GltfLoader(getOptions(gltfPath, options)); const targetScene = (0, import__492.defaultValue)(options.scene, scene2); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, targetScene); return gltfLoader; } async function loadGltfFromJson(gltfPath, options) { const gltf = await import__492.Resource.fetchJson({ url: gltfPath }); const loaderOptions = (0, import__492.combine)(options, { gltf, gltfResource: new import__492.Resource({ url: gltfPath }), incrementallyLoadTextures: false }); const gltfLoader = new import__492.GltfLoader(loaderOptions); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, scene2); return gltfLoader; } async function loadModifiedGltfAndTest(gltfPath, options, modifyFunction) { let gltf = await import__492.Resource.fetchJson({ url: gltfPath }); gltf = modifyFunction(gltf); spyOn(import__492.GltfJsonLoader.prototype, "_fetchGltf").and.returnValue( Promise.resolve(generateJsonBuffer_default(gltf).buffer) ); const gltfLoader = new import__492.GltfLoader(getOptions(gltfPath, options)); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, scene2); return gltfLoader; } function getAttribute(attributes, semantic, setIndex) { const attributesLength = attributes.length; for (let i = 0; i < attributesLength; ++i) { const attribute = attributes[i]; if (attribute.semantic === semantic && attribute.setIndex === setIndex) { return attribute; } } return void 0; } function getAttributeByName(attributes, name) { const attributesLength = attributes.length; for (let i = 0; i < attributesLength; ++i) { const attribute = attributes[i]; if (attribute.name === name) { return attribute; } } return void 0; } it("preserves query string in url", async function() { const params = "?param1=1¶m2=2"; const url = boxTextured + params; const gltfLoader = new import__492.GltfLoader(getOptions(url)); gltfLoaders.push(gltfLoader); await gltfLoader.load(); const loaderResource = gltfLoader._gltfResource; expect(loaderResource.url).toEndWith(params); }); it("releases GLB typed array when finished loading", function() { return loadGltf(boxTexturedBinary).then(function(gltfLoader) { expect(gltfLoader.components).toBeDefined(); expect(gltfLoader._typedArray).not.toBeDefined(); }); }); it("loads BoxInterleaved", function() { return loadGltf(boxInterleaved).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const childNode = rootNode.children[0]; const primitive = childNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); expect(positionAttribute.buffer).toBeDefined(); expect(positionAttribute.byteOffset).toBe(12); expect(positionAttribute.byteStride).toBe(24); expect(normalAttribute.buffer).toBeDefined(); expect(normalAttribute.byteOffset).toBe(0); expect(normalAttribute.byteStride).toBe(24); expect(positionAttribute.buffer).toBe(normalAttribute.buffer); expect(positionAttribute.buffer.sizeInBytes).toBe(576); }); }); function loadsBoxTextured(gltfPath) { return loadGltf(gltfPath).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const nodes = components.nodes; const rootNode = scene3.nodes[0]; const childNode = rootNode.children[0]; const primitive = childNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const texcoordAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.TEXCOORD, 0 ); const indices = primitive.indices; const material = primitive.material; const metallicRoughness = material.metallicRoughness; const rootMatrix = new import__492.Matrix4( 1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1 ); const childMatrix = import__492.Matrix4.IDENTITY; expect(rootNode.children.length).toBe(1); expect(rootNode.primitives.length).toBe(0); expect(rootNode.matrix).toEqual(rootMatrix); expect(rootNode.translation).toBeUndefined(); expect(rootNode.rotation).toBeUndefined(); expect(rootNode.scale).toBeUndefined(); expect(childNode.children.length).toBe(0); expect(childNode.primitives.length).toBe(1); expect(childNode.matrix).toEqual(childMatrix); expect(childNode.translation).toBeUndefined(); expect(childNode.rotation).toBeUndefined(); expect(childNode.scale).toBeUndefined(); expect(primitive.attributes.length).toBe(3); expect(primitive.primitiveType).toBe(import__492.PrimitiveType.TRIANGLES); expect(positionAttribute.name).toBe("POSITION"); expect(positionAttribute.semantic).toBe( import__492.VertexAttributeSemantic.POSITION ); expect(positionAttribute.setIndex).toBeUndefined(); expect(positionAttribute.componentDatatype).toBe( import__492.ComponentDatatype.FLOAT ); expect(positionAttribute.type).toBe(import__492.AttributeType.VEC3); expect(positionAttribute.normalized).toBe(false); expect(positionAttribute.count).toBe(24); expect(positionAttribute.min).toEqual(new import__492.Cartesian3(-0.5, -0.5, -0.5)); expect(positionAttribute.max).toEqual(new import__492.Cartesian3(0.5, 0.5, 0.5)); expect(positionAttribute.constant).toEqual(import__492.Cartesian3.ZERO); expect(positionAttribute.quantization).toBeUndefined(); expect(positionAttribute.typedArray).toBeUndefined(); expect(positionAttribute.buffer).toBeDefined(); expect(positionAttribute.byteOffset).toBe(288); expect(positionAttribute.byteStride).toBe(12); expect(normalAttribute.name).toBe("NORMAL"); expect(normalAttribute.semantic).toBe(import__492.VertexAttributeSemantic.NORMAL); expect(normalAttribute.setIndex).toBeUndefined(); expect(normalAttribute.componentDatatype).toBe(import__492.ComponentDatatype.FLOAT); expect(normalAttribute.type).toBe(import__492.AttributeType.VEC3); expect(normalAttribute.normalized).toBe(false); expect(normalAttribute.count).toBe(24); expect(normalAttribute.min).toEqual(new import__492.Cartesian3(-1, -1, -1)); expect(normalAttribute.max).toEqual(new import__492.Cartesian3(1, 1, 1)); expect(normalAttribute.constant).toEqual(import__492.Cartesian3.ZERO); expect(normalAttribute.quantization).toBeUndefined(); expect(normalAttribute.typedArray).toBeUndefined(); expect(normalAttribute.buffer).toBeDefined(); expect(normalAttribute.byteOffset).toBe(0); expect(normalAttribute.byteStride).toBe(12); expect(texcoordAttribute.name).toBe("TEXCOORD_0"); expect(texcoordAttribute.semantic).toBe( import__492.VertexAttributeSemantic.TEXCOORD ); expect(texcoordAttribute.setIndex).toBe(0); expect(texcoordAttribute.componentDatatype).toBe( import__492.ComponentDatatype.FLOAT ); expect(texcoordAttribute.type).toBe(import__492.AttributeType.VEC2); expect(texcoordAttribute.normalized).toBe(false); expect(texcoordAttribute.count).toBe(24); expect(texcoordAttribute.min).toEqual(new import__492.Cartesian2(0, 0)); expect(texcoordAttribute.max).toEqual(new import__492.Cartesian2(6, 1)); expect(texcoordAttribute.constant).toEqual(import__492.Cartesian2.ZERO); expect(texcoordAttribute.quantization).toBeUndefined(); expect(texcoordAttribute.typedArray).toBeUndefined(); expect(texcoordAttribute.buffer).toBeDefined(); expect(texcoordAttribute.byteOffset).toBe(0); expect(texcoordAttribute.byteStride).toBe(8); expect(indices.indexDatatype).toBe(import__492.IndexDatatype.UNSIGNED_SHORT); expect(indices.count).toBe(36); expect(indices.buffer).toBeDefined(); expect(indices.buffer.sizeInBytes).toBe(72); expect(positionAttribute.buffer).toBe(normalAttribute.buffer); expect(positionAttribute.buffer).not.toBe(texcoordAttribute.buffer); expect(positionAttribute.buffer.sizeInBytes).toBe(576); expect(texcoordAttribute.buffer.sizeInBytes).toBe(192); expect(metallicRoughness.baseColorFactor).toEqual( new import__492.Cartesian4(1, 1, 1, 1) ); expect(metallicRoughness.metallicFactor).toBe(0); expect(metallicRoughness.roughnessFactor).toBe(1); expect(metallicRoughness.baseColorTexture.texture.width).toBe(256); expect(metallicRoughness.baseColorTexture.texture.height).toBe(256); expect(metallicRoughness.baseColorTexture.texCoord).toBe(0); const sampler = metallicRoughness.baseColorTexture.texture.sampler; expect(sampler.wrapS).toBe(import__492.TextureWrap.REPEAT); expect(sampler.wrapT).toBe(import__492.TextureWrap.REPEAT); expect(sampler.magnificationFilter).toBe( import__492.TextureMagnificationFilter.LINEAR ); expect(sampler.minificationFilter).toBe( import__492.TextureMinificationFilter.NEAREST_MIPMAP_LINEAR ); expect(nodes.length).toBe(2); expect(scene3.nodes.length).toBe(1); }); } it("loads BoxTextured", function() { return loadsBoxTextured(boxTextured); }); it("loads BoxTexturedBinary", function() { return loadsBoxTextured(boxTexturedBinary); }); it("loads BoxTexturedEmbedded", function() { return loadsBoxTextured(boxTexturedEmbedded); }); it("loads BoxTextured with texture source removed", function() { function modifyGltf(gltf) { delete gltf.textures[0].source; return gltf; } return loadModifiedGltfAndTest(boxTextured, void 0, modifyGltf).then( function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const childNode = rootNode.children[0]; const primitive = childNode.primitives[0]; const material = primitive.material; const metallicRoughness = material.metallicRoughness; expect(metallicRoughness.baseColorTexture).toBeUndefined(); } ); }); function loadsBoxTexturedKtx2Basis(gltfPath) { return loadGltf(gltfPath).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const childNode = rootNode.children[0]; const primitive = childNode.primitives[0]; const material = primitive.material; const metallicRoughness = material.metallicRoughness; const texture = metallicRoughness.baseColorTexture.texture; const sampler = texture.sampler; expect(texture.width).toBe(256); expect(texture.height).toBe(256); expect(sampler.wrapS).toBe(import__492.TextureWrap.REPEAT); expect(sampler.wrapT).toBe(import__492.TextureWrap.REPEAT); expect(sampler.magnificationFilter).toBe( import__492.TextureMagnificationFilter.LINEAR ); expect(sampler.minificationFilter).toBe( import__492.TextureMinificationFilter.LINEAR ); }); } it("loads BoxTexturedKtx2Basis", function() { if (!scene2.context.supportsBasis) { return; } return loadsBoxTexturedKtx2Basis(boxTexturedKtx2Basis); }); it("loads BoxTexturedKtx2BasisBinary", function() { if (!scene2.context.supportsBasis) { return; } return loadsBoxTexturedKtx2Basis(boxTexturedKtx2BasisBinary); }); it("loads BoxVertexColors", function() { return loadGltf(boxVertexColors).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const childNode = rootNode.children[1]; const primitive = childNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const texcoordAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.TEXCOORD, 0 ); const colorAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.COLOR, 0 ); expect(positionAttribute.buffer).toBeDefined(); expect(positionAttribute.byteOffset).toBe(0); expect(positionAttribute.byteStride).toBe(12); expect(normalAttribute.buffer).toBeDefined(); expect(normalAttribute.byteOffset).toBe(0); expect(normalAttribute.byteStride).toBe(12); expect(texcoordAttribute.buffer).toBeDefined(); expect(texcoordAttribute.byteOffset).toBe(0); expect(texcoordAttribute.byteStride).toBe(8); expect(colorAttribute.name).toBe("COLOR_0"); expect(colorAttribute.semantic).toBe(import__492.VertexAttributeSemantic.COLOR); expect(colorAttribute.setIndex).toBe(0); expect(colorAttribute.componentDatatype).toBe(import__492.ComponentDatatype.FLOAT); expect(colorAttribute.type).toBe(import__492.AttributeType.VEC4); expect(colorAttribute.normalized).toBe(false); expect(colorAttribute.count).toBe(24); expect(colorAttribute.min).toBeUndefined(); expect(colorAttribute.max).toBeUndefined(); expect(colorAttribute.constant).toEqual(import__492.Cartesian4.ZERO); expect(colorAttribute.quantization).toBeUndefined(); expect(colorAttribute.typedArray).toBeUndefined(); expect(colorAttribute.buffer).toBeDefined(); expect(colorAttribute.byteOffset).toBe(0); expect(colorAttribute.byteStride).toBe(16); expect(colorAttribute.buffer.sizeInBytes).toBe(384); }); }); it("loads BoxVertexColors with default vertex colors", function() { function modifyGltf(gltf) { delete gltf.accessors[3].bufferView; return gltf; } return loadModifiedGltfAndTest( boxVertexColors, void 0, modifyGltf ).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const childNode = rootNode.children[1]; const primitive = childNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const texcoordAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.TEXCOORD, 0 ); const colorAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.COLOR, 0 ); expect(positionAttribute.buffer).toBeDefined(); expect(normalAttribute.buffer).toBeDefined(); expect(texcoordAttribute.buffer).toBeDefined(); expect(colorAttribute.buffer).toBeUndefined(); expect(colorAttribute.typedArray).toBeUndefined(); expect(colorAttribute.constant).toEqual(import__492.Cartesian4.ZERO); }); }); it("loads SimpleMorph", function() { return loadGltf(simpleMorph).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const morphTargets = primitive.morphTargets; const morphTarget0 = morphTargets[0]; const morphTarget1 = morphTargets[1]; const morphPositions0 = getAttribute( morphTarget0.attributes, import__492.VertexAttributeSemantic.POSITION ); const morphPositions1 = getAttribute( morphTarget1.attributes, import__492.VertexAttributeSemantic.POSITION ); expect(morphPositions0.name).toBe("POSITION"); expect(morphPositions0.semantic).toBe(import__492.VertexAttributeSemantic.POSITION); expect(morphPositions0.setIndex).toBeUndefined(); expect(morphPositions0.componentDatatype).toBe(import__492.ComponentDatatype.FLOAT); expect(morphPositions0.type).toBe(import__492.AttributeType.VEC3); expect(morphPositions0.normalized).toBe(false); expect(morphPositions0.count).toBe(3); expect(morphPositions0.min).toEqual(new import__492.Cartesian3(-1, 0, 0)); expect(morphPositions0.max).toEqual(new import__492.Cartesian3(0, 1, 0)); expect(morphPositions0.constant).toEqual(import__492.Cartesian3.ZERO); expect(morphPositions0.quantization).toBeUndefined(); expect(morphPositions0.typedArray).toBeUndefined(); expect(morphPositions0.buffer).toBeDefined(); expect(morphPositions0.byteOffset).toBe(36); expect(morphPositions0.byteStride).toBe(12); expect(morphPositions1.name).toBe("POSITION"); expect(morphPositions1.semantic).toBe(import__492.VertexAttributeSemantic.POSITION); expect(morphPositions1.setIndex).toBeUndefined(); expect(morphPositions1.componentDatatype).toBe(import__492.ComponentDatatype.FLOAT); expect(morphPositions1.type).toBe(import__492.AttributeType.VEC3); expect(morphPositions1.normalized).toBe(false); expect(morphPositions1.count).toBe(3); expect(morphPositions1.min).toEqual(new import__492.Cartesian3(0, 0, 0)); expect(morphPositions1.max).toEqual(new import__492.Cartesian3(1, 1, 0)); expect(morphPositions1.constant).toEqual(import__492.Cartesian3.ZERO); expect(morphPositions1.quantization).toBeUndefined(); expect(morphPositions1.typedArray).toBeUndefined(); expect(morphPositions1.buffer).toBeDefined(); expect(morphPositions1.byteOffset).toBe(72); expect(morphPositions1.byteStride).toBe(12); expect(positionAttribute.buffer).toBe(morphPositions0.buffer); expect(positionAttribute.buffer).toBe(morphPositions1.buffer); expect(positionAttribute.buffer.sizeInBytes).toBe(108); expect(rootNode.morphWeights).toEqual([0.5, 0.5]); }); }); it("loads SimpleMorph with default morph weights", function() { function modifyGltf(gltf) { delete gltf.meshes[0].weights; return gltf; } return loadModifiedGltfAndTest(simpleMorph, void 0, modifyGltf).then( function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; expect(rootNode.morphWeights).toEqual([0, 0]); } ); }); it("loads SimpleSkin", function() { return loadGltf(simpleSkin).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const nodes = components.nodes; const skin = rootNode.skin; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const jointsAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.JOINTS, 0 ); const weightsAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.WEIGHTS, 0 ); expect(positionAttribute.buffer).toBeDefined(); expect(positionAttribute.byteOffset).toBe(0); expect(positionAttribute.byteStride).toBe(12); expect(jointsAttribute.name).toBe("JOINTS_0"); expect(jointsAttribute.semantic).toBe(import__492.VertexAttributeSemantic.JOINTS); expect(jointsAttribute.setIndex).toBe(0); expect(jointsAttribute.componentDatatype).toBe( import__492.ComponentDatatype.UNSIGNED_SHORT ); expect(jointsAttribute.type).toBe(import__492.AttributeType.VEC4); expect(jointsAttribute.normalized).toBe(false); expect(jointsAttribute.count).toBe(10); expect(jointsAttribute.min).toBeUndefined(); expect(jointsAttribute.max).toBeUndefined(); expect(jointsAttribute.constant).toEqual(import__492.Cartesian4.ZERO); expect(jointsAttribute.quantization).toBeUndefined(); expect(jointsAttribute.typedArray).toBeUndefined(); expect(jointsAttribute.buffer).toBeDefined(); expect(jointsAttribute.byteOffset).toBe(0); expect(jointsAttribute.byteStride).toBe(16); expect(weightsAttribute.name).toBe("WEIGHTS_0"); expect(weightsAttribute.semantic).toBe(import__492.VertexAttributeSemantic.WEIGHTS); expect(weightsAttribute.setIndex).toBe(0); expect(weightsAttribute.componentDatatype).toBe( import__492.ComponentDatatype.FLOAT ); expect(weightsAttribute.type).toBe(import__492.AttributeType.VEC4); expect(weightsAttribute.normalized).toBe(false); expect(weightsAttribute.count).toBe(10); expect(weightsAttribute.min).toBeUndefined(); expect(weightsAttribute.max).toBeUndefined(); expect(weightsAttribute.constant).toEqual(import__492.Cartesian4.ZERO); expect(weightsAttribute.quantization).toBeUndefined(); expect(weightsAttribute.typedArray).toBeUndefined(); expect(weightsAttribute.buffer).toBeDefined(); expect(weightsAttribute.byteOffset).toBe(160); expect(weightsAttribute.byteStride).toBe(16); expect(components.skins).toEqual([skin]); expect(skin.joints.length).toBe(2); expect(skin.joints[0]).toBe(nodes[1]); expect(skin.joints[1]).toBe(nodes[2]); expect(skin.inverseBindMatrices).toEqual([ // prettier-ignore import__492.Matrix4.fromColumnMajorArray([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, -1, 0, 1 ]), // prettier-ignore import__492.Matrix4.fromColumnMajorArray([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, -1, 0, 1 ]) ]); }); }); it("loads SimpleSkin with default inverse bind matrices", function() { function modifyGltf(gltf) { delete gltf.skins[0].inverseBindMatrices; return gltf; } return loadModifiedGltfAndTest(simpleSkin, void 0, modifyGltf).then( function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const skin = rootNode.skin; expect(skin.inverseBindMatrices).toEqual([ import__492.Matrix4.IDENTITY, import__492.Matrix4.IDENTITY ]); } ); }); it("loads AnimatedTriangle", function() { return loadGltf(animatedTriangle).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const animations = components.animations; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); expect(positionAttribute.buffer).toBeDefined(); expect(positionAttribute.byteOffset).toBe(0); expect(positionAttribute.byteStride).toBe(12); const animation = animations[0]; expect(animation.samplers.length).toEqual(1); const sampler = animation.samplers[0]; const expectedInput = [0, 0.25, 0.5, 0.75, 1]; const expectedOutput = [ new import__492.Quaternion(0, 0, 0, 1), new import__492.Quaternion(0, 0, 0.707, 0.707), new import__492.Quaternion(0, 0, 1, 0), new import__492.Quaternion(0, 0, 0.707, -0.707), new import__492.Quaternion(0, 0, 0, 1) ]; expect(sampler.input).toEqual(expectedInput); expect(sampler.interpolation).toEqual(import__492.InterpolationType.LINEAR); const length2 = expectedOutput.length; for (let i = 0; i < length2; i++) { expect( import__492.Quaternion.equalsEpsilon( sampler.output[i], expectedOutput[i], import__492.Math.EPSILON3 ) ).toBe(true); } expect(animation.channels.length).toEqual(1); const channel = animation.channels[0]; expect(channel.sampler).toBe(sampler); expect(channel.target.node).toBe(rootNode); expect(channel.target.path).toEqual( import__492.ModelComponents.AnimatedPropertyType.ROTATION ); }); }); it("loads AnimatedMorphCube", function() { return loadGltf(animatedMorphCube).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const animations = components.animations; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); expect(positionAttribute.buffer).toBeDefined(); expect(positionAttribute.byteOffset).toBe(0); expect(positionAttribute.byteStride).toBe(12); const animation = animations[0]; expect(animation.samplers.length).toEqual(1); const sampler = animation.samplers[0]; expect(sampler.input.length).toEqual(127); expect(sampler.interpolation).toEqual(import__492.InterpolationType.LINEAR); expect(sampler.output.length).toEqual(254); expect(animation.channels.length).toEqual(1); const channel = animation.channels[0]; expect(channel.sampler).toBe(sampler); expect(channel.target.node).toBe(rootNode); expect(channel.target.path).toEqual( import__492.ModelComponents.AnimatedPropertyType.WEIGHTS ); }); }); it("loads InterpolationTest", function() { return loadGltf(interpolationTest).then(function(gltfLoader) { const components = gltfLoader.components; const nodes = components.nodes; const animations = components.animations; const stepScaleAnimation = animations[0]; expect(stepScaleAnimation.samplers.length).toEqual(1); let sampler = stepScaleAnimation.samplers[0]; expect(sampler.input.length).toEqual(sampler.output.length); expect(sampler.interpolation).toEqual(import__492.InterpolationType.STEP); expect(sampler.output[0] instanceof import__492.Cartesian3).toBe(true); expect(stepScaleAnimation.channels.length).toEqual(1); let channel = stepScaleAnimation.channels[0]; expect(channel.sampler).toBe(sampler); expect(channel.target.node).toBe(nodes[0]); expect(channel.target.path).toEqual( import__492.ModelComponents.AnimatedPropertyType.SCALE ); const cubicSplineRotation = animations[4]; expect(cubicSplineRotation.samplers.length).toEqual(1); sampler = cubicSplineRotation.samplers[0]; expect(sampler.output.length).toEqual(sampler.input.length * 3); expect(sampler.interpolation).toEqual(import__492.InterpolationType.CUBICSPLINE); expect(sampler.output[0] instanceof import__492.Quaternion).toBe(true); expect(cubicSplineRotation.channels.length).toEqual(1); channel = cubicSplineRotation.channels[0]; expect(channel.sampler).toBe(sampler); expect(channel.target.node).toBe(nodes[6]); expect(channel.target.path).toEqual( import__492.ModelComponents.AnimatedPropertyType.ROTATION ); const linearTranslation = animations[8]; expect(linearTranslation.samplers.length).toEqual(1); sampler = linearTranslation.samplers[0]; expect(sampler.input.length).toEqual(sampler.output.length); expect(sampler.interpolation).toEqual(import__492.InterpolationType.LINEAR); expect(sampler.output[0] instanceof import__492.Cartesian3).toBe(true); expect(linearTranslation.channels.length).toEqual(1); channel = linearTranslation.channels[0]; expect(channel.sampler).toBe(sampler); expect(channel.target.node).toBe(nodes[10]); expect(channel.target.path).toEqual( import__492.ModelComponents.AnimatedPropertyType.TRANSLATION ); }); }); it("loads Triangle", function() { return loadGltf(triangle).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); expect(positionAttribute).toBeDefined(); expect(primitive.indices).toBeDefined(); expect(primitive.indices.indexDatatype).toBe( import__492.IndexDatatype.UNSIGNED_SHORT ); expect(primitive.indices.count).toBe(3); expect(primitive.indices.buffer).toBeDefined(); }); }); it("loads Triangle with indices buffer view removed", function() { function modifyGltf(gltf) { delete gltf.accessors[0].bufferView; return gltf; } return loadModifiedGltfAndTest(triangle, void 0, modifyGltf).then( function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); expect(positionAttribute).toBeDefined(); expect(primitive.indices).toBeUndefined(); } ); }); it("loads TriangleWithoutIndices", function() { return loadGltf(triangleWithoutIndices).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); expect(positionAttribute).toBeDefined(); expect(primitive.indices).toBeUndefined(); }); }); it("loads TwoSidedPlane", function() { return loadGltf(twoSidedPlane).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const material = primitive.material; const metallicRoughness = material.metallicRoughness; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const tangentAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.TANGENT ); const texcoordAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.TEXCOORD, 0 ); expect(positionAttribute).toBeDefined(); expect(normalAttribute).toBeDefined(); expect(tangentAttribute).toBeDefined(); expect(texcoordAttribute).toBeDefined(); expect(metallicRoughness.baseColorTexture.texture).toBeDefined(); expect( metallicRoughness.metallicRoughnessTexture.texture ).toBeDefined(); expect(material.normalTexture.texture).toBeDefined(); expect(material.doubleSided).toBe(true); }); }); it("loads UnlitTest", function() { return loadGltf(unlitTest).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const node0 = scene3.nodes[0]; const node1 = scene3.nodes[1]; const primitive0 = node0.primitives[0]; const primitive1 = node1.primitives[0]; const material0 = primitive0.material; const material1 = primitive1.material; expect(material0.unlit).toBe(true); expect(material1.unlit).toBe(true); }); }); it("loads MultiUVTest", function() { return loadGltf(multiUvTest).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const material = primitive.material; const baseColorTexture = material.metallicRoughness.baseColorTexture; const emissiveTexture = material.emissiveTexture; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const tangentAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.TANGENT ); const texcoordAttribute0 = getAttribute( attributes, import__492.VertexAttributeSemantic.TEXCOORD, 0 ); const texcoordAttribute1 = getAttribute( attributes, import__492.VertexAttributeSemantic.TEXCOORD, 1 ); expect(positionAttribute).toBeDefined(); expect(normalAttribute).toBeDefined(); expect(tangentAttribute).toBeDefined(); expect(texcoordAttribute0).toBeDefined(); expect(texcoordAttribute1).toBeDefined(); expect(baseColorTexture.texCoord).toBe(0); expect(emissiveTexture.texCoord).toBe(1); }); }); it("loads Microcosm", function() { return loadGltf(microcosm).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const material = primitive.material; const baseColorTexture = material.metallicRoughness.baseColorTexture; const structuralMetadata = components.structuralMetadata; expect(baseColorTexture.texCoord).toBe(1); expect(primitive.featureIds.length).toBe(1); expect(primitive.propertyTextureIds).toEqual([0]); const featureIdTexture = primitive.featureIds[0]; expect(featureIdTexture).toBeInstanceOf( import__492.ModelComponents.FeatureIdTexture ); expect(featureIdTexture.featureCount).toEqual(256); expect(featureIdTexture.nullFeatureId).not.toBeDefined(); expect(featureIdTexture.propertyTableId).toBe(0); expect(featureIdTexture.label).toBe("landCover"); expect(featureIdTexture.positionalLabel).toBe("featureId_0"); expect(featureIdTexture.textureReader.channels).toBe("r"); expect(featureIdTexture.textureReader.texCoord).toBe(0); expect(featureIdTexture.textureReader.texture.width).toBe(256); expect(featureIdTexture.textureReader.texture.height).toBe(256); expect(featureIdTexture.textureReader.texture.sampler).toBe( import__492.Sampler.NEAREST ); const classDefinition = structuralMetadata.schema.classes.landCover; const properties = classDefinition.properties; expect(properties.name.type).toBe(import__492.MetadataType.STRING); expect(properties.name.componentType).not.toBeDefined(); expect(properties.color.type).toBe(import__492.MetadataType.VEC3); expect(properties.color.componentType).toBe( import__492.MetadataComponentType.UINT8 ); const propertyTable = structuralMetadata.getPropertyTable(0); expect(propertyTable.id).toEqual(0); expect(propertyTable.name).toEqual("Land Cover"); expect(propertyTable.count).toBe(256); expect(propertyTable.class).toBe(classDefinition); expect(propertyTable.getProperty(0, "name")).toBe("Grassland"); expect(propertyTable.getProperty(0, "color")).toEqual( new import__492.Cartesian3(118, 163, 11) ); expect(propertyTable.getProperty(255, "name")).toBe("Building"); expect(propertyTable.getProperty(255, "color")).toEqual( new import__492.Cartesian3(194, 194, 194) ); const propertyTexture = structuralMetadata.getPropertyTexture(0); expect(propertyTexture.id).toEqual(0); expect(propertyTexture.name).toEqual("Vegetation"); const vegetationProperty = propertyTexture.getProperty( "vegetationDensity" ); expect(vegetationProperty.textureReader.texture.width).toBe(256); expect(vegetationProperty.textureReader.texture.height).toBe(256); }); }); it("loads Microcosm with EXT_feature_metadata", function() { return loadGltf(microcosmLegacy).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const material = primitive.material; const baseColorTexture = material.metallicRoughness.baseColorTexture; const structuralMetadata = components.structuralMetadata; expect(baseColorTexture.texCoord).toBe(1); expect(primitive.featureIds.length).toBe(1); expect(primitive.propertyTextureIds).toEqual([0]); const featureIdTexture = primitive.featureIds[0]; expect(featureIdTexture).toBeInstanceOf( import__492.ModelComponents.FeatureIdTexture ); expect(featureIdTexture.featureCount).toEqual(256); expect(featureIdTexture.nullFeatureId).not.toBeDefined(); expect(featureIdTexture.propertyTableId).toBe(0); expect(featureIdTexture.label).not.toBeDefined(); expect(featureIdTexture.positionalLabel).toBe("featureId_0"); expect(featureIdTexture.textureReader.channels).toBe("r"); expect(featureIdTexture.textureReader.texCoord).toBe(0); expect(featureIdTexture.textureReader.texture.width).toBe(256); expect(featureIdTexture.textureReader.texture.height).toBe(256); expect(featureIdTexture.textureReader.texture.sampler).toBe( import__492.Sampler.NEAREST ); const classDefinition = structuralMetadata.schema.classes.landCover; const properties = classDefinition.properties; expect(properties.name.type).toBe(import__492.MetadataType.STRING); expect(properties.name.componentType).not.toBeDefined(); expect(properties.color.type).toBe(import__492.MetadataType.SCALAR); expect(properties.color.componentType).toBe( import__492.MetadataComponentType.UINT8 ); expect(properties.color.arrayLength).toBe(3); const propertyTable = structuralMetadata.getPropertyTable(0); expect(propertyTable.id).toEqual("landCoverTable"); expect(propertyTable.count).toBe(256); expect(propertyTable.class).toBe(classDefinition); expect(propertyTable.getProperty(0, "name")).toBe("Grassland"); expect(propertyTable.getProperty(0, "color")).toEqual([118, 163, 11]); expect(propertyTable.getProperty(255, "name")).toBe("Building"); expect(propertyTable.getProperty(255, "color")).toEqual([ 194, 194, 194 ]); const propertyTexture = structuralMetadata.getPropertyTexture(0); expect(propertyTexture.id).toEqual("vegetationTexture"); const vegetationProperty = propertyTexture.getProperty( "vegetationDensity" ); expect(vegetationProperty.textureReader.texture.width).toBe(256); expect(vegetationProperty.textureReader.texture.height).toBe(256); }); }); it("Loads model with multi-channel feature ID textures", function() { return loadGltf(largeFeatureIdTexture).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const material = primitive.material; const baseColorTexture = material.metallicRoughness.baseColorTexture; const structuralMetadata = components.structuralMetadata; expect(structuralMetadata).not.toBeDefined(); expect(baseColorTexture.texCoord).toBe(0); expect(primitive.featureIds.length).toBe(7); expect(primitive.propertyTextureIds).toEqual([]); let featureIdTexture = primitive.featureIds[0]; expect(featureIdTexture).toBeInstanceOf( import__492.ModelComponents.FeatureIdTexture ); expect(featureIdTexture.featureCount).toEqual(1048576); expect(featureIdTexture.nullFeatureId).not.toBeDefined(); expect(featureIdTexture.propertyTableId).not.toBeDefined(); expect(featureIdTexture.label).toBe("idsRGBA"); expect(featureIdTexture.positionalLabel).toBe("featureId_0"); expect(featureIdTexture.textureReader.channels).toBe("rgba"); expect(featureIdTexture.textureReader.texCoord).toBe(0); const texture = featureIdTexture.textureReader.texture; expect(texture.width).toBe(1024); expect(texture.height).toBe(1024); expect(texture.sampler).toBe(import__492.Sampler.NEAREST); featureIdTexture = primitive.featureIds[1]; expect(featureIdTexture).toBeInstanceOf( import__492.ModelComponents.FeatureIdTexture ); expect(featureIdTexture.featureCount).toEqual(1048576); expect(featureIdTexture.nullFeatureId).not.toBeDefined(); expect(featureIdTexture.propertyTableId).not.toBeDefined(); expect(featureIdTexture.label).toBe("idsRGB"); expect(featureIdTexture.positionalLabel).toBe("featureId_1"); expect(featureIdTexture.textureReader.channels).toBe("rgb"); expect(featureIdTexture.textureReader.texCoord).toBe(0); expect(featureIdTexture.textureReader.texture).toBe(texture); featureIdTexture = primitive.featureIds[2]; expect(featureIdTexture).toBeInstanceOf( import__492.ModelComponents.FeatureIdTexture ); expect(featureIdTexture.featureCount).toEqual(256); expect(featureIdTexture.nullFeatureId).not.toBeDefined(); expect(featureIdTexture.propertyTableId).not.toBeDefined(); expect(featureIdTexture.label).toBe("idsG"); expect(featureIdTexture.positionalLabel).toBe("featureId_2"); expect(featureIdTexture.textureReader.channels).toBe("g"); expect(featureIdTexture.textureReader.texCoord).toBe(0); expect(featureIdTexture.textureReader.texture).toBe(texture); featureIdTexture = primitive.featureIds[3]; expect(featureIdTexture).toBeInstanceOf( import__492.ModelComponents.FeatureIdTexture ); expect(featureIdTexture.featureCount).toEqual(65536); expect(featureIdTexture.nullFeatureId).not.toBeDefined(); expect(featureIdTexture.propertyTableId).not.toBeDefined(); expect(featureIdTexture.label).toBe("idsBA"); expect(featureIdTexture.positionalLabel).toBe("featureId_3"); expect(featureIdTexture.textureReader.channels).toBe("ba"); expect(featureIdTexture.textureReader.texCoord).toBe(0); expect(featureIdTexture.textureReader.texture).toBe(texture); featureIdTexture = primitive.featureIds[4]; expect(featureIdTexture).toBeInstanceOf( import__492.ModelComponents.FeatureIdTexture ); expect(featureIdTexture.featureCount).toEqual(65536); expect(featureIdTexture.nullFeatureId).not.toBeDefined(); expect(featureIdTexture.propertyTableId).not.toBeDefined(); expect(featureIdTexture.label).toBe("idsGR"); expect(featureIdTexture.positionalLabel).toBe("featureId_4"); expect(featureIdTexture.textureReader.channels).toBe("gr"); expect(featureIdTexture.textureReader.texCoord).toBe(0); expect(featureIdTexture.textureReader.texture).toBe(texture); featureIdTexture = primitive.featureIds[5]; expect(featureIdTexture).toBeInstanceOf( import__492.ModelComponents.FeatureIdTexture ); expect(featureIdTexture.featureCount).toEqual(1048576); expect(featureIdTexture.nullFeatureId).not.toBeDefined(); expect(featureIdTexture.propertyTableId).not.toBeDefined(); expect(featureIdTexture.label).toBe("idsAGBB"); expect(featureIdTexture.positionalLabel).toBe("featureId_5"); expect(featureIdTexture.textureReader.channels).toBe("agbb"); expect(featureIdTexture.textureReader.texCoord).toBe(0); expect(featureIdTexture.textureReader.texture).toBe(texture); featureIdTexture = primitive.featureIds[6]; expect(featureIdTexture).toBeInstanceOf( import__492.ModelComponents.FeatureIdTexture ); expect(featureIdTexture.featureCount).toEqual(255); expect(featureIdTexture.nullFeatureId).toBe(10); expect(featureIdTexture.propertyTableId).not.toBeDefined(); expect(featureIdTexture.label).toBe("idsGWithNull"); expect(featureIdTexture.positionalLabel).toBe("featureId_6"); expect(featureIdTexture.textureReader.channels).toBe("g"); expect(featureIdTexture.textureReader.texCoord).toBe(0); expect(featureIdTexture.textureReader.texture).toBe(texture); }); }); it("loads BuildingsMetadata", function() { return loadGltf(buildingsMetadata).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const childNode = rootNode.children[0]; const primitive = childNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const featureIdAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.FEATURE_ID, 0 ); const structuralMetadata = components.structuralMetadata; expect(positionAttribute).toBeDefined(); expect(normalAttribute).toBeDefined(); expect(featureIdAttribute.name).toBe("_FEATURE_ID_0"); expect(featureIdAttribute.semantic).toBe( import__492.VertexAttributeSemantic.FEATURE_ID ); expect(featureIdAttribute.setIndex).toBe(0); expect(featureIdAttribute.componentDatatype).toBe( import__492.ComponentDatatype.FLOAT ); expect(featureIdAttribute.type).toBe(import__492.AttributeType.SCALAR); expect(featureIdAttribute.normalized).toBe(false); expect(featureIdAttribute.count).toBe(240); expect(featureIdAttribute.min).toBe(0); expect(featureIdAttribute.max).toBe(9); expect(featureIdAttribute.constant).toBe(0); expect(featureIdAttribute.quantization).toBeUndefined(); expect(featureIdAttribute.typedArray).toBeUndefined(); expect(featureIdAttribute.buffer).toBeDefined(); expect(featureIdAttribute.byteOffset).toBe(0); expect(featureIdAttribute.byteStride).toBe(4); expect(primitive.featureIds.length).toBe(2); expect(primitive.propertyTextureIds.length).toBe(0); const featureIdAccessor = primitive.featureIds[0]; expect(featureIdAccessor).toBeInstanceOf( import__492.ModelComponents.FeatureIdAttribute ); expect(featureIdAccessor.featureCount).toEqual(10); expect(featureIdAccessor.nullFeatureId).not.toBeDefined(); expect(featureIdAccessor.propertyTableId).toBe(0); expect(featureIdAccessor.setIndex).toBe(0); expect(featureIdAccessor.label).toBe("buildings"); expect(featureIdAccessor.positionalLabel).toBe("featureId_0"); const featureIdDefault = primitive.featureIds[1]; expect(featureIdDefault).toBeInstanceOf( import__492.ModelComponents.FeatureIdImplicitRange ); expect(featureIdDefault.featureCount).toEqual(5); expect(featureIdDefault.nullFeatureId).not.toBeDefined(); expect(featureIdDefault.propertyTableId).toBe(0); expect(featureIdDefault.setIndex).not.toBeDefined(); expect(featureIdDefault.offset).toBe(0); expect(featureIdDefault.repeat).toBe(1); expect(featureIdDefault.label).toBe("defaultIdsTest"); expect(featureIdDefault.positionalLabel).toBe("featureId_1"); const classDefinition = structuralMetadata.schema.classes.building; const properties = classDefinition.properties; expect(properties.height.componentType).toBe( import__492.MetadataComponentType.FLOAT32 ); expect(properties.id.componentType).toBe(import__492.MetadataComponentType.INT32); const propertyTable = structuralMetadata.getPropertyTable(0); expect(propertyTable.id).toBe(0); expect(propertyTable.count).toBe(10); expect(propertyTable.class).toBe(classDefinition); expect(propertyTable.getProperty(0, "height")).toBe(78.15579986572266); expect(propertyTable.getProperty(0, "id")).toBe(0); expect(propertyTable.getProperty(9, "height")).toBe(79.63207244873047); expect(propertyTable.getProperty(9, "id")).toBe(9); expect(propertyTable.getProperty(3, "year")).toBe("2022"); expect(propertyTable.getProperty(5, "year")).toBe("2022"); expect(propertyTable.getProperty(7, "year")).toBe("2022"); const expectedEmployeeCounts = [ 10, 33, 40, void 0, 100, 45, 0, 1, void 0, void 0 ]; for (let i = 0; i < expectedEmployeeCounts.length; i++) { const expected = expectedEmployeeCounts[i]; expect(propertyTable.getProperty(i, "employeeCount")).toBe(expected); } for (let i = 0; i < 10; i++) { const temperature = propertyTable.getProperty( i, "temperatureCelsius" ); expect(temperature).toBeGreaterThanOrEqual(18); expect(temperature).toBeLessThanOrEqual(24); } }); }); it("loads BuildingsMetadata with EXT_feature_metadata", function() { return loadGltf(buildingsMetadataLegacy).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const childNode = rootNode.children[0]; const primitive = childNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const featureIdAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.FEATURE_ID, 0 ); const structuralMetadata = components.structuralMetadata; expect(positionAttribute).toBeDefined(); expect(normalAttribute).toBeDefined(); expect(featureIdAttribute.name).toBe("_FEATURE_ID_0"); expect(featureIdAttribute.semantic).toBe( import__492.VertexAttributeSemantic.FEATURE_ID ); expect(featureIdAttribute.setIndex).toBe(0); expect(featureIdAttribute.componentDatatype).toBe( import__492.ComponentDatatype.FLOAT ); expect(featureIdAttribute.type).toBe(import__492.AttributeType.SCALAR); expect(featureIdAttribute.normalized).toBe(false); expect(featureIdAttribute.count).toBe(240); expect(featureIdAttribute.min).toBe(0); expect(featureIdAttribute.max).toBe(9); expect(featureIdAttribute.constant).toBe(0); expect(featureIdAttribute.quantization).toBeUndefined(); expect(featureIdAttribute.typedArray).toBeUndefined(); expect(featureIdAttribute.buffer).toBeDefined(); expect(featureIdAttribute.byteOffset).toBe(0); expect(featureIdAttribute.byteStride).toBe(4); expect(primitive.featureIds.length).toBe(2); expect(primitive.propertyTextureIds.length).toBe(0); const featureIdAccessor = primitive.featureIds[0]; expect(featureIdAccessor).toBeInstanceOf( import__492.ModelComponents.FeatureIdAttribute ); expect(featureIdAccessor.featureCount).toEqual(10); expect(featureIdAccessor.nullFeatureId).not.toBeDefined(); expect(featureIdAccessor.propertyTableId).toBe(0); expect(featureIdAccessor.setIndex).toBe(0); expect(featureIdAccessor.label).not.toBeDefined(); expect(featureIdAccessor.positionalLabel).toBe("featureId_0"); const featureIdDefault = primitive.featureIds[1]; expect(featureIdDefault).toBeInstanceOf( import__492.ModelComponents.FeatureIdImplicitRange ); expect(featureIdDefault.featureCount).toEqual(10); expect(featureIdDefault.nullFeatureId).not.toBeDefined(); expect(featureIdDefault.propertyTableId).toBe(0); expect(featureIdDefault.setIndex).not.toBeDefined(); expect(featureIdDefault.offset).toBe(0); expect(featureIdDefault.repeat).toBe(2); expect(featureIdDefault.label).not.toBeDefined(); expect(featureIdDefault.positionalLabel).toBe("featureId_1"); const classDefinition = structuralMetadata.schema.classes.building; const properties = classDefinition.properties; expect(properties.height.componentType).toBe( import__492.MetadataComponentType.FLOAT32 ); expect(properties.id.componentType).toBe(import__492.MetadataComponentType.INT32); const propertyTable = structuralMetadata.getPropertyTable(0); expect(propertyTable.id).toBe("buildings"); expect(propertyTable.count).toBe(10); expect(propertyTable.class).toBe(classDefinition); expect(propertyTable.getProperty(0, "height")).toBe(78.15579986572266); expect(propertyTable.getProperty(0, "id")).toBe(0); expect(propertyTable.getProperty(9, "height")).toBe(79.63207244873047); expect(propertyTable.getProperty(9, "id")).toBe(9); expect(propertyTable.getProperty(3, "year")).toBe("2022"); expect(propertyTable.getProperty(5, "year")).toBe("2022"); expect(propertyTable.getProperty(7, "year")).toBe("2022"); expect(propertyTable.hasProperty(3, "employeeCount")).toBe(false); }); }); it("loads Weather", function() { return loadGltf(weather).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const featureIdAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.FEATURE_ID, 0 ); const structuralMetadata = components.structuralMetadata; expect(primitive.primitiveType).toBe(import__492.PrimitiveType.POINTS); expect(positionAttribute).toBeDefined(); expect(featureIdAttribute).toBeDefined(); expect(primitive.featureIds.length).toBe(2); expect(primitive.propertyTextureIds.length).toBe(0); const featureIdAttributeMapping0 = primitive.featureIds[0]; expect(featureIdAttributeMapping0).toBeInstanceOf( import__492.ModelComponents.FeatureIdImplicitRange ); expect(featureIdAttributeMapping0.featureCount).toEqual(1e3); expect(featureIdAttributeMapping0.nullFeatureId).not.toBeDefined(); expect(featureIdAttributeMapping0.propertyTableId).toBe(1); expect(featureIdAttributeMapping0.offset).toBe(0); expect(featureIdAttributeMapping0.repeat).toBe(1); expect(featureIdAttributeMapping0.label).toBe("perPoint"); expect(featureIdAttributeMapping0.positionalLabel).toBe("featureId_0"); const featureIdAttributeMapping1 = primitive.featureIds[1]; expect(featureIdAttributeMapping1).toBeInstanceOf( import__492.ModelComponents.FeatureIdAttribute ); expect(featureIdAttributeMapping1.featureCount).toEqual(3); expect(featureIdAttributeMapping1.nullFeatureId).not.toBeDefined(); expect(featureIdAttributeMapping1.propertyTableId).toBe(0); expect(featureIdAttributeMapping1.setIndex).toBe(0); expect(featureIdAttributeMapping1.label).toBe("town"); expect(featureIdAttributeMapping1.positionalLabel).toBe("featureId_1"); const weatherClass = structuralMetadata.schema.classes.weather; const weatherProperties = weatherClass.properties; expect(weatherProperties.airTemperature.componentType).toBe( import__492.MetadataComponentType.FLOAT32 ); expect(weatherProperties.airPressure.componentType).toBe( import__492.MetadataComponentType.FLOAT32 ); expect(weatherProperties.windVelocity.type).toBe(import__492.MetadataType.VEC3); expect(weatherProperties.windVelocity.componentType).toBe( import__492.MetadataComponentType.FLOAT32 ); const townClass = structuralMetadata.schema.classes.town; const townProperties = townClass.properties; expect(townProperties.name.type).toBe(import__492.MetadataType.STRING); expect(townProperties.name.componentCount).not.toBeDefined(); expect(townProperties.population.type).toBe(import__492.MetadataType.SCALAR); expect(townProperties.population.componentType).toBe( import__492.MetadataComponentType.UINT16 ); const weatherTable = structuralMetadata.getPropertyTable(1); expect(weatherTable.id).toBe(1); expect(weatherTable.name).toBe("Weather"); expect(weatherTable.count).toBe(1e3); expect(weatherTable.class).toBe(weatherClass); expect(weatherTable.getProperty(0, "airTemperature")).toBe( 22.120203018188477 ); expect(weatherTable.getProperty(0, "airPressure")).toBe( 1.170711874961853 ); expect(weatherTable.getProperty(0, "windVelocity")).toEqual( new import__492.Cartesian3(1, 0.2964223027229309, 0.23619766533374786) ); expect(weatherTable.getProperty(999, "airTemperature")).toBe( 24.308320999145508 ); expect(weatherTable.getProperty(999, "airPressure")).toBe( 1.1136815547943115 ); expect(weatherTable.getProperty(999, "windVelocity")).toEqual( new import__492.Cartesian3(1, 0.07490774989128113, 0.0022833053953945637) ); const townTable = structuralMetadata.getPropertyTable(0); expect(townTable.id).toBe(0); expect(townTable.name).toBe("Town"); expect(townTable.count).toBe(3); expect(townTable.class).toBe(townClass); expect(townTable.getProperty(0, "name")).toBe("Old Town"); expect(townTable.getProperty(0, "population")).toBe(452); expect(townTable.getProperty(1, "name")).toBe("New Town"); expect(townTable.getProperty(1, "population")).toBe(5234); expect(townTable.getProperty(2, "name")).toBe("Newer Town"); expect(townTable.getProperty(2, "population")).toBe(34245); }); }); it("loads Weather with EXT_feature_metadata", function() { return loadGltf(weatherLegacy).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const featureIdAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.FEATURE_ID, 0 ); const structuralMetadata = components.structuralMetadata; expect(primitive.primitiveType).toBe(import__492.PrimitiveType.POINTS); expect(positionAttribute).toBeDefined(); expect(featureIdAttribute).toBeDefined(); expect(primitive.featureIds.length).toBe(2); expect(primitive.propertyTextureIds.length).toBe(0); const featureIdAttributeMapping0 = primitive.featureIds[0]; expect(featureIdAttributeMapping0).toBeInstanceOf( import__492.ModelComponents.FeatureIdImplicitRange ); expect(featureIdAttributeMapping0.featureCount).toEqual(1e3); expect(featureIdAttributeMapping0.nullFeatureId).not.toBeDefined(); expect(featureIdAttributeMapping0.propertyTableId).toBe(1); expect(featureIdAttributeMapping0.offset).toBe(0); expect(featureIdAttributeMapping0.repeat).toBe(1); expect(featureIdAttributeMapping0.label).not.toBeDefined(); expect(featureIdAttributeMapping0.positionalLabel).toBe("featureId_0"); const featureIdAttributeMapping1 = primitive.featureIds[1]; expect(featureIdAttributeMapping1).toBeInstanceOf( import__492.ModelComponents.FeatureIdAttribute ); expect(featureIdAttributeMapping1.featureCount).toEqual(3); expect(featureIdAttributeMapping1.nullFeatureId).not.toBeDefined(); expect(featureIdAttributeMapping1.propertyTableId).toBe(0); expect(featureIdAttributeMapping1.setIndex).toBe(0); expect(featureIdAttributeMapping1.label).not.toBeDefined(); expect(featureIdAttributeMapping1.positionalLabel).toBe("featureId_1"); const weatherClass = structuralMetadata.schema.classes.weather; const weatherProperties = weatherClass.properties; expect(weatherProperties.airTemperature.componentType).toBe( import__492.MetadataComponentType.FLOAT32 ); expect(weatherProperties.airPressure.componentType).toBe( import__492.MetadataComponentType.FLOAT32 ); expect(weatherProperties.windVelocity.type).toBe(import__492.MetadataType.SCALAR); expect(weatherProperties.windVelocity.componentType).toBe( import__492.MetadataComponentType.FLOAT32 ); expect(weatherProperties.windVelocity.arrayLength).toBe(3); const townClass = structuralMetadata.schema.classes.town; const townProperties = townClass.properties; expect(townProperties.name.type).toBe(import__492.MetadataType.STRING); expect(townProperties.name.componentType).not.toBeDefined(); expect(townProperties.population.type).toBe(import__492.MetadataType.SCALAR); expect(townProperties.population.componentType).toBe( import__492.MetadataComponentType.UINT16 ); const weatherTable = structuralMetadata.getPropertyTable(1); expect(weatherTable.id).toBe("weatherTable"); expect(weatherTable.count).toBe(1e3); expect(weatherTable.class).toBe(weatherClass); expect(weatherTable.getProperty(0, "airTemperature")).toBe( 22.120203018188477 ); expect(weatherTable.getProperty(0, "airPressure")).toBe( 1.170711874961853 ); expect(weatherTable.getProperty(0, "windVelocity")).toEqual([ 1, 0.2964223027229309, 0.23619766533374786 ]); expect(weatherTable.getProperty(999, "airTemperature")).toBe( 24.308320999145508 ); expect(weatherTable.getProperty(999, "airPressure")).toBe( 1.1136815547943115 ); expect(weatherTable.getProperty(999, "windVelocity")).toEqual([ 1, 0.07490774989128113, 0.0022833053953945637 ]); const townTable = structuralMetadata.getPropertyTable(0); expect(townTable.id).toBe("townTable"); expect(townTable.count).toBe(3); expect(townTable.class).toBe(townClass); expect(townTable.getProperty(0, "name")).toBe("Old Town"); expect(townTable.getProperty(0, "population")).toBe(452); expect(townTable.getProperty(1, "name")).toBe("New Town"); expect(townTable.getProperty(1, "population")).toBe(5234); expect(townTable.getProperty(2, "name")).toBe("Newer Town"); expect(townTable.getProperty(2, "population")).toBe(34245); }); }); it("loads PointCloudWithPropertyAttributes", function() { return loadGltf(pointCloudWithPropertyAttributes).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const color0Attribute = getAttribute( attributes, import__492.VertexAttributeSemantic.COLOR, 0 ); const circleTAttribute = getAttributeByName(attributes, "_CIRCLE_T"); const featureId0Attribute = getAttribute( attributes, import__492.VertexAttributeSemantic.FEATURE_ID, 0 ); const featureId1Attribute = getAttribute( attributes, import__492.VertexAttributeSemantic.FEATURE_ID, 1 ); const structuralMetadata = components.structuralMetadata; expect(primitive.primitiveType).toBe(import__492.PrimitiveType.POINTS); expect(positionAttribute).toBeDefined(); expect(color0Attribute).toBeDefined(); expect(circleTAttribute).toBeDefined(); expect(featureId0Attribute).toBeDefined(); expect(featureId1Attribute).toBeDefined(); expect(primitive.featureIds.length).toBe(2); expect(primitive.propertyTextureIds.length).toBe(0); expect(primitive.propertyAttributeIds).toEqual([0]); const featureIdAttribute0 = primitive.featureIds[0]; expect(featureIdAttribute0).toBeInstanceOf( import__492.ModelComponents.FeatureIdAttribute ); expect(featureIdAttribute0.featureCount).toEqual(30); expect(featureIdAttribute0.nullFeatureId).not.toBeDefined(); expect(featureIdAttribute0.propertyTableId).not.toBeDefined(); expect(featureIdAttribute0.setIndex).toBe(0); expect(featureIdAttribute0.label).toBe("iteration"); expect(featureIdAttribute0.positionalLabel).toBe("featureId_0"); const featureIdAttribute1 = primitive.featureIds[1]; expect(featureIdAttribute1).toBeInstanceOf( import__492.ModelComponents.FeatureIdAttribute ); expect(featureIdAttribute1.featureCount).toEqual(20); expect(featureIdAttribute1.nullFeatureId).not.toBeDefined(); expect(featureIdAttribute1.propertyTableId).not.toBeDefined(); expect(featureIdAttribute1.setIndex).toBe(1); expect(featureIdAttribute1.label).toBe("pointId"); expect(featureIdAttribute1.positionalLabel).toBe("featureId_1"); const torusClass = structuralMetadata.schema.classes.torus; const torusProperties = torusClass.properties; const circleT = torusProperties.circleT; expect(circleT.type).toBe(import__492.MetadataType.SCALAR); expect(circleT.componentType).toBe(import__492.MetadataComponentType.FLOAT32); const iteration = torusProperties.iteration; expect(iteration.type).toBe(import__492.MetadataType.SCALAR); expect(iteration.componentType).toBe(import__492.MetadataComponentType.FLOAT32); const pointId = torusProperties.pointId; expect(pointId.type).toBe(import__492.MetadataType.SCALAR); expect(pointId.componentType).toBe(import__492.MetadataComponentType.FLOAT32); const propertyAttribute = structuralMetadata.getPropertyAttribute(0); expect(propertyAttribute.id).toBe(0); expect(propertyAttribute.name).not.toBeDefined(); expect(propertyAttribute.class).toBe(torusClass); expect(propertyAttribute.getProperty("circleT").attribute).toBe( "_CIRCLE_T" ); expect(propertyAttribute.getProperty("iteration").attribute).toBe( "_FEATURE_ID_0" ); expect(propertyAttribute.getProperty("pointId").attribute).toBe( "_FEATURE_ID_1" ); const toroidalNormalized = propertyAttribute.getProperty( "toroidalNormalized" ); expect(toroidalNormalized.attribute).toBe("_FEATURE_ID_0"); expect(toroidalNormalized.hasValueTransform).toBe(true); expect(toroidalNormalized.offset).toBe(0); expect(toroidalNormalized.scale).toBe(0.034482758620689655); const poloidalNormalized = propertyAttribute.getProperty( "poloidalNormalized" ); expect(poloidalNormalized.attribute).toBe("_FEATURE_ID_1"); expect(poloidalNormalized.hasValueTransform).toBe(true); expect(poloidalNormalized.offset).toBe(0); expect(poloidalNormalized.scale).toBe(0.05263157894736842); const toroidalAngle = propertyAttribute.getProperty("toroidalAngle"); expect(toroidalAngle.attribute).toBe("_FEATURE_ID_0"); expect(toroidalAngle.hasValueTransform).toBe(true); expect(toroidalAngle.offset).toBe(0); expect(toroidalAngle.scale).toBe(0.21666156231653746); const poloidalAngle = propertyAttribute.getProperty("poloidalAngle"); expect(poloidalAngle.attribute).toBe("_FEATURE_ID_1"); expect(poloidalAngle.hasValueTransform).toBe(true); expect(poloidalAngle.offset).toBe(-3.141592653589793); expect(poloidalAngle.scale).toBe(0.3306939635357677); }); }); it("loads BoxTexturedWithPropertyAttributes", function() { return loadGltf(boxWithPropertyAttributes).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const nodes = components.nodes; const rootNode = scene3.nodes[0]; const childNode = rootNode.children[0]; const primitive = childNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const texcoordAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.TEXCOORD, 0 ); const warpMatrixAttribute = getAttributeByName( attributes, "_WARP_MATRIX" ); const temperaturesAttribute = getAttributeByName( attributes, "_TEMPERATURES" ); const indices = primitive.indices; const material = primitive.material; const metallicRoughness = material.metallicRoughness; expect(primitive.attributes.length).toBe(5); expect(primitive.primitiveType).toBe(import__492.PrimitiveType.TRIANGLES); expect(positionAttribute.name).toBe("POSITION"); expect(positionAttribute.semantic).toBe( import__492.VertexAttributeSemantic.POSITION ); expect(positionAttribute.setIndex).toBeUndefined(); expect(positionAttribute.componentDatatype).toBe( import__492.ComponentDatatype.FLOAT ); expect(positionAttribute.type).toBe(import__492.AttributeType.VEC3); expect(positionAttribute.normalized).toBe(false); expect(positionAttribute.count).toBe(24); expect(positionAttribute.min).toEqual(new import__492.Cartesian3(-0.5, -0.5, -0.5)); expect(positionAttribute.max).toEqual(new import__492.Cartesian3(0.5, 0.5, 0.5)); expect(positionAttribute.constant).toEqual(import__492.Cartesian3.ZERO); expect(positionAttribute.quantization).toBeUndefined(); expect(positionAttribute.typedArray).toBeUndefined(); expect(positionAttribute.buffer).toBeDefined(); expect(positionAttribute.byteOffset).toBe(288); expect(positionAttribute.byteStride).toBe(12); expect(normalAttribute.name).toBe("NORMAL"); expect(normalAttribute.semantic).toBe(import__492.VertexAttributeSemantic.NORMAL); expect(normalAttribute.setIndex).toBeUndefined(); expect(normalAttribute.componentDatatype).toBe(import__492.ComponentDatatype.FLOAT); expect(normalAttribute.type).toBe(import__492.AttributeType.VEC3); expect(normalAttribute.normalized).toBe(false); expect(normalAttribute.count).toBe(24); expect(normalAttribute.min).toEqual(new import__492.Cartesian3(-1, -1, -1)); expect(normalAttribute.max).toEqual(new import__492.Cartesian3(1, 1, 1)); expect(normalAttribute.constant).toEqual(import__492.Cartesian3.ZERO); expect(normalAttribute.quantization).toBeUndefined(); expect(normalAttribute.typedArray).toBeUndefined(); expect(normalAttribute.buffer).toBeDefined(); expect(normalAttribute.byteOffset).toBe(0); expect(normalAttribute.byteStride).toBe(12); expect(texcoordAttribute.name).toBe("TEXCOORD_0"); expect(texcoordAttribute.semantic).toBe( import__492.VertexAttributeSemantic.TEXCOORD ); expect(texcoordAttribute.setIndex).toBe(0); expect(texcoordAttribute.componentDatatype).toBe( import__492.ComponentDatatype.FLOAT ); expect(texcoordAttribute.type).toBe(import__492.AttributeType.VEC2); expect(texcoordAttribute.normalized).toBe(false); expect(texcoordAttribute.count).toBe(24); expect(texcoordAttribute.min).toEqual(new import__492.Cartesian2(0, 0)); expect(texcoordAttribute.max).toEqual(new import__492.Cartesian2(6, 1)); expect(texcoordAttribute.constant).toEqual(import__492.Cartesian2.ZERO); expect(texcoordAttribute.quantization).toBeUndefined(); expect(texcoordAttribute.typedArray).toBeUndefined(); expect(texcoordAttribute.buffer).toBeDefined(); expect(texcoordAttribute.byteOffset).toBe(0); expect(texcoordAttribute.byteStride).toBe(8); expect(warpMatrixAttribute.name).toBe("_WARP_MATRIX"); expect(warpMatrixAttribute.semantic).toBeUndefined(); expect(warpMatrixAttribute.setIndex).toBeUndefined(); expect(warpMatrixAttribute.componentDatatype).toBe( import__492.ComponentDatatype.FLOAT ); expect(warpMatrixAttribute.type).toBe(import__492.AttributeType.MAT2); expect(warpMatrixAttribute.normalized).toBe(false); expect(warpMatrixAttribute.count).toBe(24); expect(warpMatrixAttribute.min).toBeUndefined(); expect(warpMatrixAttribute.max).toBeUndefined(); expect(warpMatrixAttribute.constant).toEqual(import__492.Matrix2.ZERO); expect(warpMatrixAttribute.quantization).toBeUndefined(); expect(warpMatrixAttribute.typedArray).toBeUndefined(); expect(warpMatrixAttribute.buffer).toBeDefined(); expect(warpMatrixAttribute.byteOffset).toBe(0); expect(warpMatrixAttribute.byteStride).toBe(16); expect(temperaturesAttribute.name).toBe("_TEMPERATURES"); expect(temperaturesAttribute.semantic).toBeUndefined(); expect(temperaturesAttribute.setIndex).toBeUndefined(); expect(temperaturesAttribute.componentDatatype).toBe( import__492.ComponentDatatype.UNSIGNED_SHORT ); expect(temperaturesAttribute.type).toBe(import__492.AttributeType.VEC2); expect(temperaturesAttribute.normalized).toBe(true); expect(temperaturesAttribute.count).toBe(24); expect(temperaturesAttribute.min).toBeUndefined(); expect(temperaturesAttribute.max).toBeUndefined(); expect(temperaturesAttribute.constant).toEqual(import__492.Cartesian2.ZERO); expect(temperaturesAttribute.quantization).toBeUndefined(); expect(temperaturesAttribute.typedArray).toBeUndefined(); expect(temperaturesAttribute.buffer).toBeDefined(); expect(temperaturesAttribute.byteOffset).toBe(0); expect(temperaturesAttribute.byteStride).toBe(4); expect(indices.indexDatatype).toBe(import__492.IndexDatatype.UNSIGNED_SHORT); expect(indices.count).toBe(36); expect(indices.buffer).toBeDefined(); expect(indices.buffer.sizeInBytes).toBe(72); expect(positionAttribute.buffer).toBe(normalAttribute.buffer); expect(positionAttribute.buffer).not.toBe(texcoordAttribute.buffer); expect(positionAttribute.buffer.sizeInBytes).toBe(576); expect(texcoordAttribute.buffer.sizeInBytes).toBe(192); expect(metallicRoughness.baseColorFactor).toEqual( new import__492.Cartesian4(1, 1, 1, 1) ); expect(metallicRoughness.metallicFactor).toBe(0); expect(metallicRoughness.roughnessFactor).toBe(1); expect(metallicRoughness.baseColorTexture.texture.width).toBe(256); expect(metallicRoughness.baseColorTexture.texture.height).toBe(256); expect(metallicRoughness.baseColorTexture.texCoord).toBe(0); const sampler = metallicRoughness.baseColorTexture.texture.sampler; expect(sampler.wrapS).toBe(import__492.TextureWrap.REPEAT); expect(sampler.wrapT).toBe(import__492.TextureWrap.REPEAT); expect(sampler.magnificationFilter).toBe( import__492.TextureMagnificationFilter.LINEAR ); expect(sampler.minificationFilter).toBe( import__492.TextureMinificationFilter.NEAREST_MIPMAP_LINEAR ); expect(nodes.length).toBe(2); expect(scene3.nodes.length).toBe(1); const structuralMetadata = components.structuralMetadata; const boxClass = structuralMetadata.schema.classes.warpedBox; const boxProperties = boxClass.properties; const warpMatrixProperty = boxProperties.warpMatrix; expect(warpMatrixProperty.type).toBe(import__492.MetadataType.MAT2); expect(warpMatrixProperty.componentType).toBe( import__492.MetadataComponentType.FLOAT32 ); expect(warpMatrixProperty.hasValueTransform).toBe(false); const transformedWarpMatrixProperty = boxProperties.transformedWarpMatrix; expect(transformedWarpMatrixProperty.type).toBe(import__492.MetadataType.MAT2); expect(transformedWarpMatrixProperty.componentType).toBe( import__492.MetadataComponentType.FLOAT32 ); expect(transformedWarpMatrixProperty.hasValueTransform).toBe(true); expect(transformedWarpMatrixProperty.offset).toEqual([ 0.5, 0.5, 0.5, 0.5 ]); expect(transformedWarpMatrixProperty.scale).toEqual([2, 2, 2, 2]); const temperaturesProperty = boxProperties.temperatures; expect(temperaturesProperty.type).toBe(import__492.MetadataType.VEC2); expect(temperaturesProperty.componentType).toBe( import__492.MetadataComponentType.UINT16 ); expect(temperaturesProperty.normalized).toBe(true); expect(temperaturesProperty.hasValueTransform).toBe(true); expect(temperaturesProperty.offset).toEqual([20, 10]); expect(temperaturesProperty.scale).toEqual([5, 20]); const propertyAttribute = structuralMetadata.getPropertyAttribute(0); expect(propertyAttribute.id).toBe(0); expect(propertyAttribute.name).toBeUndefined(); expect(propertyAttribute.class).toBe(boxClass); const warpMatrix = propertyAttribute.getProperty("warpMatrix"); expect(warpMatrix.attribute).toBe("_WARP_MATRIX"); expect(warpMatrix.hasValueTransform).toBe(false); const transformedWarpMatrix = propertyAttribute.getProperty( "transformedWarpMatrix" ); expect(transformedWarpMatrix.attribute).toBe("_WARP_MATRIX"); expect(transformedWarpMatrix.hasValueTransform).toBe(true); expect(transformedWarpMatrix.offset).toEqual( new import__492.Matrix2(0.5, 0.5, 0.5, 0.5) ); expect(transformedWarpMatrix.scale).toEqual(new import__492.Matrix2(2, 2, 2, 2)); const temperatures = propertyAttribute.getProperty("temperatures"); expect(temperatures.attribute).toBe("_TEMPERATURES"); expect(temperatures.hasValueTransform).toBe(true); expect(temperatures.offset).toEqual(new import__492.Cartesian2(20, 10)); expect(temperatures.scale).toEqual(new import__492.Cartesian2(5, 20)); }); }); describe("loads instanced models", function() { let sceneWithNoInstancing; beforeAll(function() { sceneWithNoInstancing = createScene_default({ contextOptions: { requestWebgl1: true } }); sceneWithNoInstancing.context._instancedArrays = void 0; }); function verifyBoxInstancedAttributes(loader, options) { options = (0, import__492.defaultValue)(options, import__492.defaultValue.EMPTY_OBJECT); const interleaved = (0, import__492.defaultValue)(options.interleaved, false); const instancingDisabled = (0, import__492.defaultValue)( options.instancingDisabled, false ); const components = loader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const instances = rootNode.instances; const instancedAttributes = instances.attributes; const translationAttribute = getAttribute( instancedAttributes, import__492.InstanceAttributeSemantic.TRANSLATION ); const rotationAttribute = getAttribute( instancedAttributes, import__492.InstanceAttributeSemantic.ROTATION ); const scaleAttribute = getAttribute( instancedAttributes, import__492.InstanceAttributeSemantic.SCALE ); const featureIdAttribute = getAttribute( instancedAttributes, import__492.InstanceAttributeSemantic.FEATURE_ID, 0 ); expect(positionAttribute).toBeDefined(); expect(normalAttribute).toBeDefined(); expect(translationAttribute.semantic).toBe( import__492.InstanceAttributeSemantic.TRANSLATION ); expect(translationAttribute.componentDatatype).toBe( import__492.ComponentDatatype.FLOAT ); expect(translationAttribute.type).toBe(import__492.AttributeType.VEC3); expect(translationAttribute.normalized).toBe(false); expect(translationAttribute.count).toBe(4); expect(translationAttribute.min).toBeUndefined(); expect(translationAttribute.max).toBeUndefined(); expect(translationAttribute.constant).toEqual(import__492.Cartesian3.ZERO); expect(translationAttribute.quantization).toBeUndefined(); expect(translationAttribute.typedArray).toEqual( new Float32Array([-2, 2, 0, -2, -2, 0, 2, -2, 0, 2, 2, 0]) ); expect(translationAttribute.buffer).toBeUndefined(); expect(translationAttribute.byteOffset).toBe(0); expect(translationAttribute.byteStride).toBeUndefined(); expect(rotationAttribute.semantic).toBe( import__492.InstanceAttributeSemantic.ROTATION ); expect(rotationAttribute.componentDatatype).toBe( import__492.ComponentDatatype.FLOAT ); expect(rotationAttribute.type).toBe(import__492.AttributeType.VEC4); expect(rotationAttribute.normalized).toBe(false); expect(rotationAttribute.count).toBe(4); expect(rotationAttribute.min).toBeUndefined(); expect(rotationAttribute.max).toBeUndefined(); expect(rotationAttribute.constant).toEqual(import__492.Cartesian4.ZERO); expect(rotationAttribute.quantization).toBeUndefined(); expect(rotationAttribute.typedArray).toEqual( // prettier-ignore new Float32Array([ 0.3826833963394165, 0, 0, 0.9238795042037964, 0.3535534143447876, 0.3535534143447876, 0.1464466005563736, 0.8535534143447876, 0.46193981170654297, 0.19134169816970825, 0.46193981170654297, 0.7325378060340881, 0.5319756865501404, 0.022260000929236412, 0.43967971205711365, 0.7233173847198486 ]) ); expect(rotationAttribute.buffer).toBeUndefined(); expect(rotationAttribute.byteOffset).toBe(0); expect(rotationAttribute.byteStride).toBeUndefined(); expect(scaleAttribute.semantic).toBe(import__492.InstanceAttributeSemantic.SCALE); expect(scaleAttribute.componentDatatype).toBe(import__492.ComponentDatatype.FLOAT); expect(scaleAttribute.type).toBe(import__492.AttributeType.VEC3); expect(scaleAttribute.normalized).toBe(false); expect(scaleAttribute.count).toBe(4); expect(scaleAttribute.min).toBeUndefined(); expect(scaleAttribute.max).toBeUndefined(); expect(scaleAttribute.constant).toEqual(import__492.Cartesian3.ZERO); expect(scaleAttribute.quantization).toBeUndefined(); expect(scaleAttribute.typedArray).toEqual( // prettier-ignore new Float32Array([ 0.6000000238418579, 0.699999988079071, 1, 1, 1, 0.5, 0.75, 0.20000000298023224, 0.5, 0.800000011920929, 0.6000000238418579, 0.8999999761581421 ]) ); expect(scaleAttribute.buffer).toBeUndefined(); expect(scaleAttribute.byteOffset).toBe(0); expect(scaleAttribute.byteStride).toBeUndefined(); expect(featureIdAttribute.setIndex).toBe(0); expect(featureIdAttribute.componentDatatype).toBe( import__492.ComponentDatatype.FLOAT ); expect(featureIdAttribute.type).toBe(import__492.AttributeType.SCALAR); expect(featureIdAttribute.normalized).toBe(false); expect(featureIdAttribute.count).toBe(4); expect(featureIdAttribute.min).toBeUndefined(); expect(featureIdAttribute.max).toBeUndefined(); expect(featureIdAttribute.constant).toBe(0); expect(featureIdAttribute.quantization).toBeUndefined(); if (instancingDisabled) { expect(featureIdAttribute.typedArray).toEqual( new Float32Array([0, 0, 1, 1]) ); expect(featureIdAttribute.buffer).toBeUndefined(); } else { expect(featureIdAttribute.typedArray).toBeUndefined(); expect(featureIdAttribute.buffer).toBeDefined(); } if (interleaved && !instancingDisabled) { expect(featureIdAttribute.byteOffset).toBe(40); expect(featureIdAttribute.byteStride).toBe(44); } else if (instancingDisabled) { expect(featureIdAttribute.byteOffset).toBe(0); expect(featureIdAttribute.byteStride).toBeUndefined(); } else { expect(featureIdAttribute.byteOffset).toBe(0); expect(featureIdAttribute.byteStride).toBe(4); } } function verifyBoxInstancedStructuralMetadata(loader) { const components = loader.components; const structuralMetadata = components.structuralMetadata; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const instances = rootNode.instances; expect(instances.featureIds.length).toBe(2); const featureIdAttributeMapping0 = instances.featureIds[0]; expect(featureIdAttributeMapping0).toBeInstanceOf( import__492.ModelComponents.FeatureIdImplicitRange ); expect(featureIdAttributeMapping0.featureCount).toEqual(4); expect(featureIdAttributeMapping0.nullFeatureId).not.toBeDefined(); expect(featureIdAttributeMapping0.propertyTableId).toBe(0); expect(featureIdAttributeMapping0.offset).toBe(0); expect(featureIdAttributeMapping0.repeat).toBe(1); expect(featureIdAttributeMapping0.label).toBe("perInstance"); expect(featureIdAttributeMapping0.positionalLabel).toBe( "instanceFeatureId_0" ); const featureIdAttributeMapping1 = instances.featureIds[1]; expect(featureIdAttributeMapping1).toBeInstanceOf( import__492.ModelComponents.FeatureIdAttribute ); expect(featureIdAttributeMapping1.featureCount).toEqual(2); expect(featureIdAttributeMapping1.nullFeatureId).not.toBeDefined(); expect(featureIdAttributeMapping1.propertyTableId).toBe(1); expect(featureIdAttributeMapping1.setIndex).toBe(0); expect(featureIdAttributeMapping1.label).toBe("section"); expect(featureIdAttributeMapping1.positionalLabel).toBe( "instanceFeatureId_1" ); const boxClass = structuralMetadata.schema.classes.box; const boxProperties = boxClass.properties; expect(boxProperties.name.type).toBe(import__492.MetadataType.STRING); expect(boxProperties.name.componentType).not.toBeDefined(); expect(boxProperties.volume.componentType).toBe( import__492.MetadataComponentType.FLOAT32 ); const sectionClass = structuralMetadata.schema.classes.section; const sectionProperties = sectionClass.properties; expect(sectionProperties.name.type).toBe(import__492.MetadataType.STRING); expect(sectionProperties.name.componentType).not.toBeDefined(); expect(sectionProperties.id.type).toBe(import__492.MetadataType.SCALAR); expect(sectionProperties.id.componentType).toBe( import__492.MetadataComponentType.UINT16 ); const boxTable = structuralMetadata.getPropertyTable(0); expect(boxTable.id).toBe(0); expect(boxTable.name).toBe("Box"); expect(boxTable.count).toBe(4); expect(boxTable.class).toBe(boxClass); expect(boxTable.getProperty(0, "name")).toBe("top left"); expect(boxTable.getProperty(0, "volume")).toBe(0.41999998688697815); expect(boxTable.getProperty(1, "name")).toBe("bottom left"); expect(boxTable.getProperty(1, "volume")).toBe(0.5); expect(boxTable.getProperty(2, "name")).toBe("bottom right"); expect(boxTable.getProperty(2, "volume")).toBe(0.07500000298023224); expect(boxTable.getProperty(3, "name")).toBe("top right"); expect(boxTable.getProperty(3, "volume")).toBe(0.4320000112056732); const sectionTable = structuralMetadata.getPropertyTable(1); expect(sectionTable.id).toBe(1); expect(sectionTable.name).toBe("Section"); expect(sectionTable.count).toBe(2); expect(sectionTable.class).toBe(sectionClass); expect(sectionTable.getProperty(0, "name")).toBe("left"); expect(sectionTable.getProperty(0, "id")).toBe(10293); expect(sectionTable.getProperty(1, "name")).toBe("right"); expect(sectionTable.getProperty(1, "id")).toBe(54923); } function verifyBoxInstancedStructuralMetadataLegacy(loader) { const components = loader.components; const structuralMetadata = components.structuralMetadata; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const instances = rootNode.instances; expect(instances.featureIds.length).toBe(2); const featureIdAttributeMapping0 = instances.featureIds[0]; expect(featureIdAttributeMapping0).toBeInstanceOf( import__492.ModelComponents.FeatureIdImplicitRange ); expect(featureIdAttributeMapping0.featureCount).toEqual(4); expect(featureIdAttributeMapping0.nullFeatureId).not.toBeDefined(); expect(featureIdAttributeMapping0.propertyTableId).toBe(0); expect(featureIdAttributeMapping0.offset).toBe(0); expect(featureIdAttributeMapping0.repeat).toBe(1); expect(featureIdAttributeMapping0.label).not.toBeDefined(); expect(featureIdAttributeMapping0.positionalLabel).toBe( "instanceFeatureId_0" ); const featureIdAttributeMapping1 = instances.featureIds[1]; expect(featureIdAttributeMapping1).toBeInstanceOf( import__492.ModelComponents.FeatureIdAttribute ); expect(featureIdAttributeMapping1.featureCount).toEqual(2); expect(featureIdAttributeMapping1.nullFeatureId).not.toBeDefined(); expect(featureIdAttributeMapping1.propertyTableId).toBe(1); expect(featureIdAttributeMapping1.setIndex).toBe(0); expect(featureIdAttributeMapping1.label).not.toBeDefined(); expect(featureIdAttributeMapping1.positionalLabel).toBe( "instanceFeatureId_1" ); const boxClass = structuralMetadata.schema.classes.box; const boxProperties = boxClass.properties; expect(boxProperties.name.type).toBe(import__492.MetadataType.STRING); expect(boxProperties.name.componentType).not.toBeDefined(); expect(boxProperties.volume.componentType).toBe( import__492.MetadataComponentType.FLOAT32 ); const sectionClass = structuralMetadata.schema.classes.section; const sectionProperties = sectionClass.properties; expect(sectionProperties.name.type).toBe(import__492.MetadataType.STRING); expect(sectionProperties.name.componentType).not.toBeDefined(); expect(sectionProperties.id.type).toBe(import__492.MetadataType.SCALAR); expect(sectionProperties.id.componentType).toBe( import__492.MetadataComponentType.UINT16 ); const boxTable = structuralMetadata.getPropertyTable(0); expect(boxTable.id).toBe("boxTable"); expect(boxTable.count).toBe(4); expect(boxTable.class).toBe(boxClass); expect(boxTable.getProperty(0, "name")).toBe("top left"); expect(boxTable.getProperty(0, "volume")).toBe(0.41999998688697815); expect(boxTable.getProperty(1, "name")).toBe("bottom left"); expect(boxTable.getProperty(1, "volume")).toBe(0.5); expect(boxTable.getProperty(2, "name")).toBe("bottom right"); expect(boxTable.getProperty(2, "volume")).toBe(0.07500000298023224); expect(boxTable.getProperty(3, "name")).toBe("top right"); expect(boxTable.getProperty(3, "volume")).toBe(0.4320000112056732); const sectionTable = structuralMetadata.getPropertyTable(1); expect(sectionTable.id).toBe("sectionTable"); expect(sectionTable.count).toBe(2); expect(sectionTable.class).toBe(sectionClass); expect(sectionTable.getProperty(0, "name")).toBe("left"); expect(sectionTable.getProperty(0, "id")).toBe(10293); expect(sectionTable.getProperty(1, "name")).toBe("right"); expect(sectionTable.getProperty(1, "id")).toBe(54923); } it("loads BoxInstanced", function() { return loadGltf(boxInstanced).then(function(gltfLoader) { verifyBoxInstancedAttributes(gltfLoader); verifyBoxInstancedStructuralMetadata(gltfLoader); }); }); it("loads BoxInstanced with EXT_feature_metadata", function() { return loadGltf(boxInstancedLegacy).then(function(gltfLoader) { verifyBoxInstancedAttributes(gltfLoader); verifyBoxInstancedStructuralMetadataLegacy(gltfLoader); }); }); it("loads BoxInstanced when WebGL instancing is disabled on WebGL 1", function() { const options = { scene: sceneWithNoInstancing }; return loadGltf(boxInstanced, options).then(function(gltfLoader) { verifyBoxInstancedAttributes(gltfLoader, { instancingDisabled: true }); verifyBoxInstancedStructuralMetadata(gltfLoader); }); }); it("loads BoxInstanced with default feature ids", function() { function modifyGltf(gltf) { delete gltf.accessors[6].bufferView; return gltf; } return loadModifiedGltfAndTest( boxInstanced, void 0, modifyGltf ).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const instances = rootNode.instances; const instancedAttributes = instances.attributes; const featureIdAttribute = getAttribute( instancedAttributes, import__492.InstanceAttributeSemantic.FEATURE_ID, 0 ); expect(featureIdAttribute.buffer).toBeUndefined(); expect(featureIdAttribute.typedArray).toBeUndefined(); expect(featureIdAttribute.constant).toEqual(0); }); }); it("loads BoxInstancedInterleaved", function() { return loadGltf(boxInstancedInterleaved).then(function(gltfLoader) { verifyBoxInstancedAttributes(gltfLoader, { interleaved: true }); }); }); it("loads BoxInstancedInterleaved with instancing disabled", function() { const options = { scene: sceneWithNoInstancing }; return loadGltf(boxInstancedInterleaved, options).then(function(gltfLoader) { verifyBoxInstancedAttributes(gltfLoader, { interleaved: true, instancingDisabled: true }); }); }); function verifyBoxInstancedTranslation(loader, expectMinMax, expectBufferDefined, expectTypedArrayDefined) { const components = loader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const instances = rootNode.instances; const instancedAttributes = instances.attributes; const translationAttribute = getAttribute( instancedAttributes, import__492.InstanceAttributeSemantic.TRANSLATION ); expect(positionAttribute).toBeDefined(); expect(normalAttribute).toBeDefined(); expect(translationAttribute.semantic).toBe( import__492.InstanceAttributeSemantic.TRANSLATION ); expect(translationAttribute.componentDatatype).toBe( import__492.ComponentDatatype.FLOAT ); expect(translationAttribute.type).toBe(import__492.AttributeType.VEC3); expect(translationAttribute.normalized).toBe(false); expect(translationAttribute.count).toBe(4); if (expectMinMax) { expect(translationAttribute.min).toEqual(new import__492.Cartesian3(-2, -2, 0)); expect(translationAttribute.max).toEqual(new import__492.Cartesian3(2, 2, 0)); } else { expect(translationAttribute.min).toBeUndefined(); expect(translationAttribute.max).toBeUndefined(); } expect(translationAttribute.constant).toEqual(import__492.Cartesian3.ZERO); expect(translationAttribute.quantization).toBeUndefined(); if (expectTypedArrayDefined) { expect(translationAttribute.typedArray).toEqual( new Float32Array([-2, 2, 0, -2, -2, 0, 2, -2, 0, 2, 2, 0]) ); } else { expect(translationAttribute.typedArray).toBeUndefined(); expect(translationAttribute.byteOffset).toBe(0); } if (expectBufferDefined) { expect(translationAttribute.buffer).toBeDefined(); expect(translationAttribute.byteOffset).toBe(0); expect(translationAttribute.byteStride).toBe(12); } else { expect(translationAttribute.buffer).toBeUndefined(); expect(translationAttribute.byteOffset).toBe(0); expect(translationAttribute.byteStride).toBeUndefined(); } } it("loads BoxInstancedTranslation", function() { return loadGltf(boxInstancedTranslation).then(function(gltfLoader) { const expectMinMax = false; const expectBufferDefined = true; const expectTypedArrayDefined = true; verifyBoxInstancedTranslation( gltfLoader, expectMinMax, expectBufferDefined, expectTypedArrayDefined ); }); }); it("loads BoxInstancedTranslation when WebGL instancing is disabled", function() { const options = { scene: sceneWithNoInstancing }; return loadGltf(boxInstancedTranslation, options).then(function(gltfLoader) { const expectMinMax = false; const expectBufferDefined = false; const expectTypedArrayDefined = true; verifyBoxInstancedTranslation( gltfLoader, expectMinMax, expectBufferDefined, expectTypedArrayDefined ); }); }); it("loads BoxInstancedTranslationWithMinMax", function() { return loadGltf(boxInstancedTranslationMinMax).then(function(gltfLoader) { const expectMinMax = true; const expectBufferDefined = true; const expectTypedArrayDefined = false; verifyBoxInstancedTranslation( gltfLoader, expectMinMax, expectBufferDefined, expectTypedArrayDefined ); }); }); }); it("loads Duck", function() { return loadGltf(duckDraco).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const childNode = rootNode.children[0]; const primitive = childNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const texcoordAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.TEXCOORD, 0 ); const positionQuantization = positionAttribute.quantization; const normalQuantization = normalAttribute.quantization; const texcoordQuantization = texcoordAttribute.quantization; const indices = primitive.indices; expect(positionAttribute.name).toBe("POSITION"); expect(positionAttribute.semantic).toBe( import__492.VertexAttributeSemantic.POSITION ); expect(positionAttribute.setIndex).toBeUndefined(); expect(positionAttribute.componentDatatype).toBe( import__492.ComponentDatatype.FLOAT ); expect(positionAttribute.type).toBe(import__492.AttributeType.VEC3); expect(positionAttribute.normalized).toBe(false); expect(positionAttribute.count).toBe(2399); expect(positionAttribute.min).toEqual( new import__492.Cartesian3( -69.37933953401223, 9.848530453475558, -61.40903695222513 ) ); expect(positionAttribute.max).toEqual( new import__492.Cartesian3( 96.26074059602396, 164.09024489374352, 54.029730459044615 ) ); expect(positionAttribute.constant).toEqual(import__492.Cartesian3.ZERO); expect(positionAttribute.typedArray).toBeUndefined(); expect(positionAttribute.buffer).toBeDefined(); expect(positionAttribute.byteOffset).toBe(0); expect(positionAttribute.byteStride).toBeUndefined(); expect(positionQuantization.octEncoded).toBe(false); expect(positionQuantization.normalizationRange).toEqual( new import__492.Cartesian3(2047, 2047, 2047) ); expect(positionQuantization.quantizedVolumeOffset).toEqual( new import__492.Cartesian3( -69.29850006103516, 9.929369926452637, -61.32819747924805 ) ); expect(positionQuantization.quantizedVolumeDimensions).toEqual( new import__492.Cartesian3( 165.4783935546875, 165.4783935546875, 165.4783935546875 ) ); expect(positionQuantization.componentDatatype).toBe( import__492.ComponentDatatype.UNSIGNED_SHORT ); expect(positionQuantization.type).toBe(import__492.AttributeType.VEC3); expect(normalAttribute.name).toBe("NORMAL"); expect(normalAttribute.semantic).toBe(import__492.VertexAttributeSemantic.NORMAL); expect(normalAttribute.setIndex).toBeUndefined(); expect(normalAttribute.componentDatatype).toBe(import__492.ComponentDatatype.FLOAT); expect(normalAttribute.type).toBe(import__492.AttributeType.VEC3); expect(normalAttribute.normalized).toBe(false); expect(normalAttribute.count).toBe(2399); expect(normalAttribute.min).toEqual( new import__492.Cartesian3( -1.0069254898557476, -1.0078414940366558, -1.007673468543034 ) ); expect(normalAttribute.max).toEqual( new import__492.Cartesian3( 1.0083384775647932, 1.007422473383885, 1.0075904988775068 ) ); expect(normalAttribute.constant).toEqual(import__492.Cartesian3.ZERO); expect(normalAttribute.typedArray).toBeUndefined(); expect(normalAttribute.buffer).toBeDefined(); expect(normalAttribute.byteOffset).toBe(0); expect(normalAttribute.byteStride).toBeUndefined(); expect(normalQuantization.octEncoded).toBe(true); expect(normalQuantization.normalizationRange).toBe(255); expect(normalQuantization.quantizedVolumeOffset).toBeUndefined(); expect(normalQuantization.quantizedVolumeDimensions).toBeUndefined(); expect(normalQuantization.componentDatatype).toBe( import__492.ComponentDatatype.UNSIGNED_BYTE ); expect(normalQuantization.type).toBe(import__492.AttributeType.VEC2); expect(texcoordAttribute.name).toBe("TEXCOORD_0"); expect(texcoordAttribute.semantic).toBe( import__492.VertexAttributeSemantic.TEXCOORD ); expect(texcoordAttribute.setIndex).toBe(0); expect(texcoordAttribute.componentDatatype).toBe( import__492.ComponentDatatype.FLOAT ); expect(texcoordAttribute.type).toBe(import__492.AttributeType.VEC2); expect(texcoordAttribute.normalized).toBe(false); expect(texcoordAttribute.count).toBe(2399); expect(texcoordAttribute.min).toEqual( new import__492.Cartesian2(0.025470511450678954, 0.019024537339121947) ); expect(texcoordAttribute.max).toEqual( new import__492.Cartesian2(0.9846059706495423, 0.9809754626608782) ); expect(texcoordAttribute.constant).toEqual(import__492.Cartesian2.ZERO); expect(texcoordAttribute.typedArray).toBeUndefined(); expect(texcoordAttribute.buffer).toBeDefined(); expect(texcoordAttribute.byteOffset).toBe(0); expect(texcoordAttribute.byteStride).toBeUndefined(); expect(texcoordQuantization.octEncoded).toBe(false); expect(texcoordQuantization.normalizationRange).toEqual( new import__492.Cartesian2(1023, 1023) ); expect(texcoordQuantization.quantizedVolumeOffset).toEqual( new import__492.Cartesian2(0.026409000158309937, 0.01996302604675293) ); expect(texcoordQuantization.quantizedVolumeDimensions).toEqual( new import__492.Cartesian2(0.9600739479064941, 0.9600739479064941) ); expect(texcoordQuantization.componentDatatype).toBe( import__492.ComponentDatatype.UNSIGNED_SHORT ); expect(texcoordQuantization.type).toBe(import__492.AttributeType.VEC2); expect(indices.indexDatatype).toBe(import__492.IndexDatatype.UNSIGNED_SHORT); expect(indices.count).toBe(12636); expect(indices.buffer).toBeDefined(); expect(indices.buffer.sizeInBytes).toBe(25272); expect(positionAttribute.buffer).not.toBe(normalAttribute.buffer); expect(positionAttribute.buffer).not.toBe(texcoordAttribute.buffer); expect(positionAttribute.buffer.sizeInBytes).toBe(14394); expect(normalAttribute.buffer.sizeInBytes).toBe(4798); expect(texcoordAttribute.buffer.sizeInBytes).toBe(9596); }); }); it("loads BoxMixedCompression", function() { return loadGltf(boxMixedCompression).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const texcoordAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.TEXCOORD, 0 ); expect(positionAttribute.quantization).toBeDefined(); expect(normalAttribute.quantization).toBeUndefined(); expect(texcoordAttribute.quantization).toBeDefined(); }); }); it("loads Boom Box", function() { const textureCreate = spyOn(import__492.Texture, "create").and.callThrough(); return loadGltf(boomBoxSpecularGlossiness).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const material = primitive.material; const specularGlossiness = material.specularGlossiness; expect(components.upAxis).toBe(import__492.Axis.Y); expect(components.forwardAxis).toBe(import__492.Axis.Z); expect(material.occlusionTexture.texture.width).toBe(256); expect(material.normalTexture.texture.width).toBe(256); expect(material.emissiveTexture.texture.width).toBe(256); expect(specularGlossiness.diffuseTexture.texture.width).toBe(256); expect(specularGlossiness.specularGlossinessTexture.texture.width).toBe( 256 ); expect(specularGlossiness.diffuseFactor).toEqual( new import__492.Cartesian4(1, 1, 1, 1) ); expect(specularGlossiness.specularFactor).toEqual( new import__492.Cartesian3(1, 1, 1) ); expect(specularGlossiness.glossinessFactor).toBe(0.5); expect(textureCreate.calls.count()).toBe(5); }); }); it("loads BoxArticulations", function() { return loadGltf(boxArticulations).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; expect(rootNode.articulationName).toEqual("SampleArticulation"); const articulations = components.articulations; expect(articulations.length).toEqual(1); const articulation = articulations[0]; expect(articulation.name).toEqual("SampleArticulation"); const stages = articulation.stages; expect(stages.length).toEqual(10); const xTranslateStage = stages[0]; expect(xTranslateStage.name).toEqual("MoveX"); expect(xTranslateStage.type).toEqual(import__492.ArticulationStageType.XTRANSLATE); expect(xTranslateStage.minimumValue).toEqual(-1e3); expect(xTranslateStage.maximumValue).toEqual(1e3); expect(xTranslateStage.initialValue).toEqual(0); const yTranslateStage = stages[1]; expect(yTranslateStage.name).toEqual("MoveY"); expect(yTranslateStage.type).toEqual(import__492.ArticulationStageType.YTRANSLATE); expect(yTranslateStage.minimumValue).toEqual(-1e3); expect(yTranslateStage.maximumValue).toEqual(1e3); expect(yTranslateStage.initialValue).toEqual(0); const zTranslateStage = stages[2]; expect(zTranslateStage.name).toEqual("MoveZ"); expect(zTranslateStage.type).toEqual(import__492.ArticulationStageType.ZTRANSLATE); expect(zTranslateStage.minimumValue).toEqual(-1e3); expect(zTranslateStage.maximumValue).toEqual(1e3); expect(zTranslateStage.initialValue).toEqual(0); const yRotateStage = stages[3]; expect(yRotateStage.name).toEqual("Yaw"); expect(yRotateStage.type).toEqual(import__492.ArticulationStageType.YROTATE); expect(yRotateStage.minimumValue).toEqual(-360); expect(yRotateStage.maximumValue).toEqual(360); expect(yRotateStage.initialValue).toEqual(0); const xRotateStage = stages[4]; expect(xRotateStage.name).toEqual("Pitch"); expect(xRotateStage.type).toEqual(import__492.ArticulationStageType.XROTATE); expect(xRotateStage.minimumValue).toEqual(-360); expect(xRotateStage.maximumValue).toEqual(360); expect(xRotateStage.initialValue).toEqual(0); const zRotateStage = stages[5]; expect(zRotateStage.name).toEqual("Roll"); expect(zRotateStage.type).toEqual(import__492.ArticulationStageType.ZROTATE); expect(zRotateStage.minimumValue).toEqual(-360); expect(zRotateStage.maximumValue).toEqual(360); expect(zRotateStage.initialValue).toEqual(0); const uniformScaleStage = stages[6]; expect(uniformScaleStage.name).toEqual("Size"); expect(uniformScaleStage.type).toEqual( import__492.ArticulationStageType.UNIFORMSCALE ); expect(uniformScaleStage.minimumValue).toEqual(0); expect(uniformScaleStage.maximumValue).toEqual(1); expect(uniformScaleStage.initialValue).toEqual(1); const xScaleStage = stages[7]; expect(xScaleStage.name).toEqual("SizeX"); expect(xScaleStage.type).toEqual(import__492.ArticulationStageType.XSCALE); expect(xScaleStage.minimumValue).toEqual(0); expect(xScaleStage.maximumValue).toEqual(1); expect(xScaleStage.initialValue).toEqual(1); const yScaleStage = stages[8]; expect(yScaleStage.name).toEqual("SizeY"); expect(yScaleStage.type).toEqual(import__492.ArticulationStageType.YSCALE); expect(yScaleStage.minimumValue).toEqual(0); expect(yScaleStage.maximumValue).toEqual(1); expect(yScaleStage.initialValue).toEqual(1); const zScaleStage = stages[9]; expect(zScaleStage.name).toEqual("SizeZ"); expect(zScaleStage.type).toEqual(import__492.ArticulationStageType.ZSCALE); expect(zScaleStage.minimumValue).toEqual(0); expect(zScaleStage.maximumValue).toEqual(1); expect(zScaleStage.initialValue).toEqual(1); }); }); it("loads model with CESIUM_RTC", function() { return loadGltf(boxCesiumRtc).then(function(gltfLoader) { const components = gltfLoader.components; const expectedTransform = import__492.Matrix4.fromTranslation( new import__492.Cartesian3(6378137, 0, 0) ); expect(components.transform).toEqual(expectedTransform); }); }); it("loads TorusQuantized", function() { return loadGltf(torusQuantized).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const primitive = scene3.nodes[0].primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); expect(positionAttribute.buffer).toBeDefined(); expect(positionAttribute.byteOffset).toBe(0); expect(positionAttribute.byteStride).toBe(4); expect(positionAttribute.normalized).toBe(true); const dequantizedValue = 127 / 255; expect(positionAttribute.min).toEqual(new import__492.Cartesian3(0, 0, 0)); expect(positionAttribute.max).toEqual( new import__492.Cartesian3(dequantizedValue, dequantizedValue, dequantizedValue) ); expect(normalAttribute.buffer).toBeDefined(); expect(normalAttribute.byteOffset).toBe(0); expect(normalAttribute.byteStride).toBe(4); expect(normalAttribute.min).not.toBeDefined(); expect(normalAttribute.max).not.toBeDefined(); }); }); it("loads WEB3D_quantized_attributes extension", function() { return loadGltf(boxWeb3dQuantizedAttributes).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const primitive = scene3.nodes[0].primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const scalarAttribute = getAttributeByName(attributes, "_SCALAR_TEST"); const positionQuantization = positionAttribute.quantization; expect(positionQuantization).toBeDefined(); expect(positionQuantization.quantizedVolumeOffset).toEqual( new import__492.Cartesian3(-0.5, -0.5, -0.5) ); expect(positionQuantization.quantizedVolumeStepSize).toEqual( new import__492.Cartesian3( 15259021896696422e-21, 15259021896696422e-21, 15259021896696422e-21 ) ); expect(positionAttribute.min).toEqual(new import__492.Cartesian3(-0.5, -0.5, -0.5)); expect(positionAttribute.max).toEqual(new import__492.Cartesian3(0.5, 0.5, 0.5)); const normalQuantization = normalAttribute.quantization; expect(normalQuantization).toBeDefined(); expect(normalQuantization.quantizedVolumeOffset).toEqual( new import__492.Cartesian3(-1, -1, -1) ); expect(normalQuantization.quantizedVolumeStepSize).toEqual( new import__492.Cartesian3( 30518043793392844e-21, 30518043793392844e-21, 30518043793392844e-21 ) ); const scalarQuantization = scalarAttribute.quantization; expect(scalarQuantization).toBeDefined(); expect(scalarQuantization.quantizedVolumeOffset).toBe(1); expect(scalarQuantization.quantizedVolumeStepSize).toBe(0); expect(scalarAttribute.min).toEqual(1); expect(scalarAttribute.max).toEqual(1); }); }); it("loads model from parsed JSON object", function() { return loadGltfFromJson(triangle).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); expect(positionAttribute).toBeDefined(); expect(primitive.indices).toBeDefined(); expect(primitive.indices.indexDatatype).toBe( import__492.IndexDatatype.UNSIGNED_SHORT ); expect(primitive.indices.count).toBe(3); expect(primitive.indices.buffer).toBeDefined(); }); }); it("models share the same resources", function() { const textureCreate = spyOn(import__492.Texture, "create").and.callThrough(); return Promise.all([loadGltf(duckDraco), loadGltf(duckDraco)]).then( function(gltfLoaders2) { const cacheEntries = import__492.ResourceCache.cacheEntries; for (const cacheKey in cacheEntries) { if (cacheEntries.hasOwnProperty(cacheKey)) { const cacheEntry = cacheEntries[cacheKey]; expect(cacheEntry.referenceCount).toBe(2); } } expect(textureCreate.calls.count()).toBe(1); gltfLoaders2[0].destroy(); gltfLoaders2[1].destroy(); } ); }); it("releases glTF JSON after parse", function() { const destroyGltfJsonLoader = spyOn( import__492.GltfJsonLoader.prototype, "destroy" ).and.callThrough(); const options = { releaseGltfJson: true }; return loadGltf(triangle, options).then(function(gltfLoader) { expect(destroyGltfJsonLoader).toHaveBeenCalled(); }); }); it("releases glTF JSON after unload", function() { const destroyGltfJsonLoader = spyOn( import__492.GltfJsonLoader.prototype, "destroy" ).and.callThrough(); const options = { releaseGltfJson: false }; return loadGltf(triangle, options).then(function(gltfLoader) { expect(destroyGltfJsonLoader).not.toHaveBeenCalled(); gltfLoader.destroy(); expect(destroyGltfJsonLoader).toHaveBeenCalled(); }); }); it("creates GPU resources asynchronously", function() { const jobSchedulerExecute = spyOn( import__492.JobScheduler.prototype, "execute" ).and.callThrough(); const options = { asynchronous: true }; return loadGltf(triangle, options).then(function(gltfLoader) { expect(jobSchedulerExecute).toHaveBeenCalled(); }); }); it("creates GPU resources synchronously", function() { const jobSchedulerExecute = spyOn( import__492.JobScheduler.prototype, "execute" ).and.callThrough(); const options = { asynchronous: false }; return loadGltf(triangle, options).then(function(gltfLoader) { expect(jobSchedulerExecute).not.toHaveBeenCalled(); }); }); it("becomes ready before textures are loaded when incrementallyLoadTextures is true", async function() { const textureCreate = spyOn(import__492.Texture, "create").and.callThrough(); const options = { incrementallyLoadTextures: true }; let resolver; const promise = new Promise((resolve) => { resolver = resolve; }); spyOn(import__492.Resource.prototype, "fetchImage").and.returnValue(promise); const gltfLoader = await loadGltf(boxTextured, options); expect(textureCreate).not.toHaveBeenCalled(); const image = new Image(); image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII="; resolver(image); await pollToPromise_default(function() { loaderProcess_default(gltfLoader, scene2); return gltfLoader._textureLoaders.every(function(loader) { return loader._state === import__492.ResourceLoaderState.READY || loader._state === import__492.ResourceLoaderState.FAILED; }); }); expect(textureCreate).toHaveBeenCalled(); }); it("sets default transform", function() { return loadGltf(microcosm).then(function(gltfLoader) { expect(gltfLoader.components.transform).toEqual(import__492.Matrix4.IDENTITY); }); }); it("destroys glTF loader", function() { const destroyStructuralMetadataLoader = spyOn( import__492.GltfStructuralMetadataLoader.prototype, "destroy" ).and.callThrough(); const destroyVertexBufferLoader = spyOn( import__492.GltfVertexBufferLoader.prototype, "destroy" ).and.callThrough(); const destroyIndexBufferLoader = spyOn( import__492.GltfIndexBufferLoader.prototype, "destroy" ).and.callThrough(); const destroyTextureLoader = spyOn( import__492.GltfTextureLoader.prototype, "destroy" ).and.callThrough(); return loadGltf(microcosm).then(function(gltfLoader) { expect(gltfLoader.components).toBeDefined(); expect(gltfLoader.isDestroyed()).toBe(false); gltfLoader.destroy(); expect(gltfLoader.components).not.toBeDefined(); expect(destroyStructuralMetadataLoader.calls.count()).toBe(1); expect(destroyVertexBufferLoader.calls.count()).toBe(3); expect(destroyIndexBufferLoader.calls.count()).toBe(1); expect(destroyTextureLoader.calls.count()).toBe(3); }); }); it("process throws if image resource fails to load", async function() { spyOn(import__492.Resource.prototype, "fetchImage").and.callFake(function() { const error = new Error("404 Not Found"); return Promise.reject(error); }); const destroyVertexBufferLoader = spyOn( import__492.GltfVertexBufferLoader.prototype, "destroy" ).and.callThrough(); const destroyIndexBufferLoader = spyOn( import__492.GltfIndexBufferLoader.prototype, "destroy" ).and.callThrough(); const destroyTextureLoader = spyOn( import__492.GltfTextureLoader.prototype, "destroy" ).and.callThrough(); const options = { releaseGltfJson: true }; const gltfLoader = new import__492.GltfLoader(getOptions(boxTextured, options)); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await expectAsync( waitForLoaderProcess_default(gltfLoader, scene2) ).toBeRejectedWithError( import__492.RuntimeError, "Failed to load glTF\nFailed to load texture\nFailed to load image: CesiumLogoFlat.png\n404 Not Found" ); expect(destroyVertexBufferLoader.calls.count()).toBe(2); expect(destroyIndexBufferLoader.calls.count()).toBe(1); expect(destroyTextureLoader.calls.count()).toBe(1); }); function resolveGltfJsonAfterDestroy(rejectPromise) { const gltf = { asset: { version: "2.0" } }; const arrayBuffer = generateJsonBuffer_default(gltf).buffer; const fetchPromise = new Promise(function(resolve, reject) { if (rejectPromise) { reject(new Error()); } else { resolve(arrayBuffer); } }); spyOn(import__492.GltfJsonLoader.prototype, "_fetchGltf").and.returnValue( fetchPromise ); const gltfUri = "https://example.com/model.glb"; const gltfResource = new import__492.Resource({ url: gltfUri }); const gltfLoader = new import__492.GltfLoader({ gltfResource }); expect(gltfLoader.components).not.toBeDefined(); const promise = gltfLoader.load(); gltfLoader.destroy(); return promise.then(function() { expect(gltfLoader.components).not.toBeDefined(); expect(gltfLoader.isDestroyed()).toBe(true); }); } it("handles resolving glTF JSON after destroy", function() { return resolveGltfJsonAfterDestroy(false); }); it("handles rejecting glTF JSON after destroy", function() { return resolveGltfJsonAfterDestroy(true); }); describe("loadIndicesForWireframe", function() { let sceneWithWebgl1; beforeAll(function() { sceneWithWebgl1 = createScene_default({ contextOptions: { requestWebgl1: true } }); }); afterAll(function() { sceneWithWebgl1.destroyForSpecs(); }); it("loads indices in buffer and typed array for wireframes in WebGL1", function() { return loadGltf(triangle, { loadIndicesForWireframe: true, scene: sceneWithWebgl1 }).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); expect(positionAttribute).toBeDefined(); expect(primitive.indices).toBeDefined(); expect(primitive.indices.indexDatatype).toBe( import__492.IndexDatatype.UNSIGNED_SHORT ); expect(primitive.indices.count).toBe(3); expect(primitive.indices.typedArray).toBeDefined(); expect(primitive.indices.buffer).toBeDefined(); }); }); it("loads indices in buffer only for wireframes in WebGL2", function() { const customScene = createScene_default(); customScene.context._webgl2 = true; return loadGltf(triangle, { loadIndicesForWireframe: true, scene: customScene }).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); expect(positionAttribute).toBeDefined(); expect(primitive.indices).toBeDefined(); expect(primitive.indices.indexDatatype).toBe( import__492.IndexDatatype.UNSIGNED_SHORT ); expect(primitive.indices.count).toBe(3); expect(primitive.indices.typedArray).not.toBeDefined(); expect(primitive.indices.buffer).toBeDefined(); customScene.destroyForSpecs(); }); }); }); describe("loadAttributesAsTypedArray", function() { it("loads vertex attributes and indices as typed arrays", function() { const options = { loadAttributesAsTypedArray: true }; return loadGltf(boxInterleaved, options).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const childNode = rootNode.children[0]; const primitive = childNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); expect(positionAttribute.buffer).toBeUndefined(); expect(positionAttribute.typedArray).toBeDefined(); expect(positionAttribute.byteOffset).toBe(0); expect(positionAttribute.byteStride).toBeUndefined(); expect(positionAttribute.typedArray.byteLength).toBe(288); expect(normalAttribute.buffer).toBeUndefined(); expect(normalAttribute.typedArray).toBeDefined(); expect(normalAttribute.byteOffset).toBe(0); expect(normalAttribute.byteStride).toBeUndefined(); expect(normalAttribute.typedArray.byteLength).toBe(288); expect(primitive.indices).toBeDefined(); expect(primitive.indices.typedArray).toBeDefined(); }); }); it("loads instanced attributes as typed arrays only", function() { const options = { loadAttributesAsTypedArray: true }; return loadGltf(boxInstancedTranslationMinMax, options).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const instances = rootNode.instances; const instancedAttributes = instances.attributes; const translationAttribute = getAttribute( instancedAttributes, import__492.InstanceAttributeSemantic.TRANSLATION ); expect(positionAttribute).toBeDefined(); expect(normalAttribute).toBeDefined(); expect(translationAttribute.semantic).toBe( import__492.InstanceAttributeSemantic.TRANSLATION ); expect(translationAttribute.componentDatatype).toBe( import__492.ComponentDatatype.FLOAT ); expect(translationAttribute.type).toBe(import__492.AttributeType.VEC3); expect(translationAttribute.normalized).toBe(false); expect(translationAttribute.count).toBe(4); expect(translationAttribute.min).toEqual(new import__492.Cartesian3(-2, -2, 0)); expect(translationAttribute.max).toEqual(new import__492.Cartesian3(2, 2, 0)); expect(translationAttribute.constant).toEqual(import__492.Cartesian3.ZERO); expect(translationAttribute.quantization).toBeUndefined(); expect(translationAttribute.typedArray).toBeDefined(); expect(translationAttribute.buffer).toBeUndefined(); expect(translationAttribute.byteOffset).toBe(0); expect(translationAttribute.byteStride).toBeUndefined(); }); }); }); describe("loadAttributesFor2D", function() { it("loads position attribute as buffer and typed array for 2D projection", function() { const options = { loadAttributesFor2D: true }; return loadGltf(boxInterleaved, options).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const childNode = rootNode.children[0]; const primitive = childNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); expect(positionAttribute.buffer).toBeDefined(); expect(positionAttribute.typedArray).toBeDefined(); expect(positionAttribute.byteOffset).toBe(12); expect(positionAttribute.byteStride).toBe(24); expect(normalAttribute.buffer).toBeDefined(); expect(normalAttribute.typedArray).toBeUndefined(); expect(normalAttribute.byteOffset).toBe(0); expect(normalAttribute.byteStride).toBe(24); expect(positionAttribute.typedArray.byteLength).toBe(288); }); }); it("loads position attribute as buffer only if model is instanced", function() { const options = { loadAttributesFor2D: true }; return loadGltf(boxInstanced, options).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); expect(positionAttribute.buffer).toBeDefined(); expect(positionAttribute.typedArray).toBeUndefined(); }); }); it("loads instanced attributes as typed arrays for 2D", function() { const options = { loadAttributesFor2D: true }; return loadGltf(boxInstanced, options).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const instances = rootNode.instances; const instancedAttributes = instances.attributes; const translationAttribute = getAttribute( instancedAttributes, import__492.InstanceAttributeSemantic.TRANSLATION ); expect(translationAttribute.typedArray).toBeDefined(); expect(translationAttribute.buffer).toBeUndefined(); const rotationAttribute = getAttribute( instancedAttributes, import__492.InstanceAttributeSemantic.ROTATION ); expect(rotationAttribute.typedArray).toBeDefined(); expect(rotationAttribute.buffer).toBeUndefined(); const scaleAttribute = getAttribute( instancedAttributes, import__492.InstanceAttributeSemantic.SCALE ); expect(scaleAttribute.typedArray).toBeDefined(); expect(scaleAttribute.buffer).toBeUndefined(); const featureIdAttribute = getAttribute( instancedAttributes, import__492.InstanceAttributeSemantic.FEATURE_ID, 0 ); expect(featureIdAttribute.typedArray).toBeUndefined(); expect(featureIdAttribute.buffer).toBeDefined(); }); }); it("loads instanced translation without min/max as typed array for 2D", function() { const options = { loadAttributesFor2D: true }; return loadGltf(boxInstancedTranslation, options).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const instances = rootNode.instances; const instancedAttributes = instances.attributes; const translationAttribute = getAttribute( instancedAttributes, import__492.InstanceAttributeSemantic.TRANSLATION ); expect(positionAttribute).toBeDefined(); expect(normalAttribute).toBeDefined(); expect(translationAttribute.semantic).toBe( import__492.InstanceAttributeSemantic.TRANSLATION ); expect(translationAttribute.componentDatatype).toBe( import__492.ComponentDatatype.FLOAT ); expect(translationAttribute.type).toBe(import__492.AttributeType.VEC3); expect(translationAttribute.normalized).toBe(false); expect(translationAttribute.count).toBe(4); expect(translationAttribute.constant).toEqual(import__492.Cartesian3.ZERO); expect(translationAttribute.quantization).toBeUndefined(); expect(translationAttribute.typedArray).toBeDefined(); expect(translationAttribute.buffer).toBeDefined(); expect(translationAttribute.byteOffset).toBe(0); expect(translationAttribute.byteStride).toBe(12); }); }); it("loads instanced translation with min/max as buffer and typed array for 2D", function() { const options = { loadAttributesFor2D: true }; return loadGltf(boxInstancedTranslationMinMax, options).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const instances = rootNode.instances; const instancedAttributes = instances.attributes; const translationAttribute = getAttribute( instancedAttributes, import__492.InstanceAttributeSemantic.TRANSLATION ); expect(positionAttribute).toBeDefined(); expect(normalAttribute).toBeDefined(); expect(translationAttribute.semantic).toBe( import__492.InstanceAttributeSemantic.TRANSLATION ); expect(translationAttribute.componentDatatype).toBe( import__492.ComponentDatatype.FLOAT ); expect(translationAttribute.type).toBe(import__492.AttributeType.VEC3); expect(translationAttribute.normalized).toBe(false); expect(translationAttribute.count).toBe(4); expect(translationAttribute.min).toEqual(new import__492.Cartesian3(-2, -2, 0)); expect(translationAttribute.max).toEqual(new import__492.Cartesian3(2, 2, 0)); expect(translationAttribute.constant).toEqual(import__492.Cartesian3.ZERO); expect(translationAttribute.quantization).toBeUndefined(); expect(translationAttribute.typedArray).toBeDefined(); expect(translationAttribute.buffer).toBeDefined(); expect(translationAttribute.byteOffset).toBe(0); expect(translationAttribute.byteStride).toBe(12); }); }); }); describe("loadForClassification", function() { it("loads model without feature IDs for classification", function() { const options = { loadForClassification: true }; return loadGltf(boxVertexColors, options).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const childNode = rootNode.children[1]; const primitive = childNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const texcoordAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.TEXCOORD, 0 ); const colorAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.COLOR, 0 ); expect(positionAttribute).toBeDefined(); expect(normalAttribute).toBeUndefined(); expect(texcoordAttribute).toBeDefined(); expect(colorAttribute).toBeUndefined(); expect(positionAttribute.buffer).toBeDefined(); expect(texcoordAttribute.buffer).toBeDefined(); }); }); it("loads model with feature IDs for classification", function() { const options = { loadForClassification: true }; return loadGltf(buildingsMetadata, options).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const childNode = rootNode.children[0]; const primitive = childNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const featureIdAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.FEATURE_ID, 0 ); expect(positionAttribute).toBeDefined(); expect(positionAttribute.buffer).toBeDefined(); expect(positionAttribute.typedArray).toBeUndefined(); expect(normalAttribute).toBeUndefined(); expect(featureIdAttribute.name).toBe("_FEATURE_ID_0"); expect(featureIdAttribute.semantic).toBe( import__492.VertexAttributeSemantic.FEATURE_ID ); expect(featureIdAttribute.setIndex).toBe(0); expect(featureIdAttribute.buffer).toBeDefined(); expect(featureIdAttribute.typedArray).toBeDefined(); const indices = primitive.indices; expect(indices.buffer).toBeDefined(); expect(indices.typedArray).toBeDefined(); }); }); it("ignores morph targets for classification", function() { const options = { loadForClassification: true }; return loadGltf(simpleMorph, options).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); expect(positionAttribute).toBeDefined(); expect(positionAttribute.buffer).toBeDefined(); const morphTargets = primitive.morphTargets; expect(morphTargets.length).toBe(0); }); }); it("ignores skins for classification", function() { const options = { loadForClassification: true }; return loadGltf(simpleSkin, options).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const skin = rootNode.skin; expect(skin).toBeUndefined(); const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const jointsAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.JOINTS, 0 ); const weightsAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.WEIGHTS, 0 ); expect(positionAttribute).toBeDefined(); expect(positionAttribute.buffer).toBeDefined(); expect(jointsAttribute).toBeUndefined(); expect(weightsAttribute).toBeUndefined(); expect(components.skins.length).toBe(0); }); }); it("ignores animations for classification", function() { const options = { loadForClassification: true }; return loadGltf(animatedTriangle, options).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); expect(positionAttribute).toBeDefined(); expect(positionAttribute.buffer).toBeDefined(); const animations = components.animations; expect(animations.length).toBe(0); }); }); it("ignores normal textures for classification", function() { const options = { loadForClassification: true }; return loadGltf(twoSidedPlane, options).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const tangentAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.TANGENT ); const texcoordAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.TEXCOORD, 0 ); expect(positionAttribute).toBeDefined(); expect(texcoordAttribute).toBeDefined(); expect(normalAttribute).toBeUndefined(); expect(tangentAttribute).toBeUndefined(); const material = primitive.material; expect(material.normalTexture).toBeUndefined(); }); }); it("throws when loading instanced model for classification", async function() { const options = { loadForClassification: true }; await expectAsync( loadGltf(boxInstanced, options) ).toBeRejectedWithError( import__492.RuntimeError, "Failed to load glTF\nModels with the EXT_mesh_gpu_instancing extension cannot be used for classification." ); }); it("throws when loading non-triangle mesh for classification", async function() { const options = { loadForClassification: true }; await expectAsync( loadGltf(pointCloudWithPropertyAttributes, options) ).toBeRejectedWithError( import__492.RuntimeError, "Failed to load glTF\nOnly triangle meshes can be used for classification." ); }); }); it("loads model with CESIUM_primitive_outline", function() { return loadGltf(boxWithPrimitiveOutline).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const [rootNode] = scene3.nodes; const [primitive] = rootNode.primitives; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const texCoordAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.TEXCOORD, 0 ); expect(positionAttribute).toBeDefined(); expect(normalAttribute).toBeDefined(); expect(texCoordAttribute).toBeDefined(); const indices = primitive.indices; expect(indices).toBeDefined(); expect(indices.buffer).toBeDefined(); expect(indices.typedArray).toBeUndefined(); expect(indices.count).toBe(36); const outlineCoordinates = primitive.outlineCoordinates; expect(outlineCoordinates).toBeDefined(); expect(outlineCoordinates.name).toBe("_OUTLINE_COORDINATES"); expect(outlineCoordinates.count).toBe(24); expect(outlineCoordinates.semantic).not.toBeDefined(); expect(outlineCoordinates.type).toBe(import__492.AttributeType.VEC3); expect(outlineCoordinates.buffer).toBeDefined(); expect(outlineCoordinates.typedArray).not.toBeDefined(); }); }); it("loads model with CESIUM_primitive_outline with shared vertices", function() { return loadGltf(boxWithPrimitiveOutlineSharedVertices).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const [rootNode] = scene3.nodes; const [primitive] = rootNode.primitives; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const texCoordAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.TEXCOORD, 0 ); expect(positionAttribute).toBeDefined(); expect(normalAttribute).not.toBeDefined(); expect(texCoordAttribute).not.toBeDefined(); const indices = primitive.indices; expect(indices).toBeDefined(); expect(indices.buffer).toBeDefined(); expect(indices.typedArray).not.toBeDefined(); expect(indices.count).toBe(36); const outlineCoordinates = primitive.outlineCoordinates; expect(outlineCoordinates).toBeDefined(); expect(outlineCoordinates.name).toBe("_OUTLINE_COORDINATES"); expect(outlineCoordinates.count).toBe(16); expect(outlineCoordinates.semantic).not.toBeDefined(); expect(outlineCoordinates.type).toBe(import__492.AttributeType.VEC3); expect(outlineCoordinates.buffer).toBeDefined(); expect(outlineCoordinates.typedArray).not.toBeDefined(); }); }); it("does not load CESIUM_primitive_outline if loadPrimitiveOutline is false", function() { const options = { loadPrimitiveOutline: false }; return loadGltf(boxWithPrimitiveOutline, options).then(function(gltfLoader) { const components = gltfLoader.components; const scene3 = components.scene; const [rootNode] = scene3.nodes; const [primitive] = rootNode.primitives; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.POSITION ); const normalAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.NORMAL ); const texCoordAttribute = getAttribute( attributes, import__492.VertexAttributeSemantic.TEXCOORD, 0 ); expect(positionAttribute).toBeDefined(); expect(normalAttribute).toBeDefined(); expect(texCoordAttribute).toBeDefined(); const indices = primitive.indices; expect(indices).toBeDefined(); expect(indices.buffer).toBeDefined(); expect(indices.typedArray).not.toBeDefined(); expect(indices.count).toBe(36); const outlineCoordinates = primitive.outlineCoordinates; expect(outlineCoordinates).not.toBeDefined(); }); }); it("parses copyright field", function() { return loadGltf(boxWithCredits).then(function(gltfLoader) { const components = gltfLoader.components; const asset = components.asset; expect(asset).toBeDefined(); const expectedCredits = [ "First Source", "Second Source", "Third Source" ]; const credits = asset.credits; const length2 = credits.length; expect(length2).toBe(expectedCredits.length); for (let i = 0; i < length2; i++) { expect(credits[i].html).toEqual(expectedCredits[i]); } }); }); }, "WebGL" ); // packages/engine/Specs/Scene/GltfLoaderUtilSpec.js var import__493 = __toESM(require_Cesium(), 1); describe( "Scene/GltfLoaderUtil", function() { const gltfWithTextures = { images: [ { uri: "image.png" }, { mimeType: "image/jpeg", bufferView: 0 }, { uri: "image.webp" }, { uri: "image.ktx2" } ], textures: [ { source: 0 }, { source: 0, extensions: { EXT_texture_webp: { source: 2 } } }, { source: 0, extensions: { KHR_texture_basisu: { source: 3 } } } ] }; it("getImageIdFromTexture throws if gltf is undefined", function() { expect(function() { import__493.GltfLoaderUtil.getImageIdFromTexture({ gltf: void 0, textureId: 0, supportedImageFormats: new import__493.SupportedImageFormats() }); }).toThrowDeveloperError(); }); it("getImageIdFromTexture throws if textureId is undefined", function() { expect(function() { import__493.GltfLoaderUtil.getImageIdFromTexture({ gltf: gltfWithTextures, textureId: void 0, supportedImageFormats: new import__493.SupportedImageFormats() }); }).toThrowDeveloperError(); }); it("getImageIdFromTexture throws if supportedImageFormats is undefined", function() { expect(function() { import__493.GltfLoaderUtil.getImageIdFromTexture({ gltf: gltfWithTextures, textureId: 0, supportedImageFormats: void 0 }); }).toThrowDeveloperError(); }); it("getImageIdFromTexture gets image id", function() { const imageId = import__493.GltfLoaderUtil.getImageIdFromTexture({ gltf: gltfWithTextures, textureId: 0, supportedImageFormats: new import__493.SupportedImageFormats() }); expect(imageId).toBe(0); }); it("getImageIdFromTexture gets WebP image when EXT_texture_webp extension is supported", function() { const imageId = import__493.GltfLoaderUtil.getImageIdFromTexture({ gltf: gltfWithTextures, textureId: 1, supportedImageFormats: new import__493.SupportedImageFormats({ webp: true }) }); expect(imageId).toBe(2); }); it("getImageIdFromTexture gets default image when EXT_texture_webp extension is not supported", function() { const imageId = import__493.GltfLoaderUtil.getImageIdFromTexture({ gltf: gltfWithTextures, textureId: 1, supportedImageFormats: new import__493.SupportedImageFormats({ webp: false }) }); expect(imageId).toBe(0); }); it("getImageIdFromTexture gets KTX2 image when KHR_texture_basisu extension is supported", function() { const imageId = import__493.GltfLoaderUtil.getImageIdFromTexture({ gltf: gltfWithTextures, textureId: 2, supportedImageFormats: new import__493.SupportedImageFormats({ basis: true }) }); expect(imageId).toBe(3); }); it("getImageIdFromTexture gets default image when KHR_texture_basisu extension is not supported", function() { const imageId = import__493.GltfLoaderUtil.getImageIdFromTexture({ gltf: gltfWithTextures, textureId: 2, supportedImageFormats: new import__493.SupportedImageFormats({ basis: false }) }); expect(imageId).toBe(0); }); it("createSampler throws if gltf is undefined", function() { expect(function() { import__493.GltfLoaderUtil.getImageIdFromTexture({ gltf: void 0, textureInfo: { index: 0 } }); }).toThrowDeveloperError(); }); it("createSampler throws if textureInfo is undefined", function() { expect(function() { import__493.GltfLoaderUtil.getImageIdFromTexture({ gltf: gltfWithTextures, textureInfo: void 0 }); }).toThrowDeveloperError(); }); it("createSampler gets default sampler when texture does not have a sampler", function() { const sampler = import__493.GltfLoaderUtil.createSampler({ gltf: { textures: [ { source: 0 } ] }, textureInfo: { index: 0 } }); expect(sampler.wrapS).toBe(import__493.TextureWrap.REPEAT); expect(sampler.wrapT).toBe(import__493.TextureWrap.REPEAT); expect(sampler.minificationFilter).toBe(import__493.TextureMinificationFilter.LINEAR); expect(sampler.magnificationFilter).toBe( import__493.TextureMagnificationFilter.LINEAR ); }); it("createSampler uses NEAREST when compressedTextureNoMipmap is true and the minFilter uses nearest mipmap filtering", function() { const sampler = import__493.GltfLoaderUtil.createSampler({ gltf: { textures: [ { source: 0, sampler: 0 } ], samplers: [ { magFilter: 9729, minFilter: 9986, wrapS: 10497, wrapT: 10497 } ] }, textureInfo: { index: 0 }, compressedTextureNoMipmap: true }); expect(sampler.wrapS).toBe(import__493.TextureWrap.REPEAT); expect(sampler.wrapT).toBe(import__493.TextureWrap.REPEAT); expect(sampler.minificationFilter).toBe( import__493.TextureMinificationFilter.NEAREST ); expect(sampler.magnificationFilter).toBe( import__493.TextureMagnificationFilter.LINEAR ); }); it("createSampler uses LINEAR when compressedTextureNoMipmap is true and the minFilter uses linear mipmap filtering", function() { const sampler = import__493.GltfLoaderUtil.createSampler({ gltf: { textures: [ { source: 0, sampler: 0 } ], samplers: [ { magFilter: 9729, minFilter: 9987, wrapS: 10497, wrapT: 10497 } ] }, textureInfo: { index: 0 }, compressedTextureNoMipmap: true }); expect(sampler.wrapS).toBe(import__493.TextureWrap.REPEAT); expect(sampler.wrapT).toBe(import__493.TextureWrap.REPEAT); expect(sampler.minificationFilter).toBe(import__493.TextureMinificationFilter.LINEAR); expect(sampler.magnificationFilter).toBe( import__493.TextureMagnificationFilter.LINEAR ); }); function createSampler(options) { const gltf = { textures: [ { source: 0, sampler: 0 } ], samplers: [ { minFilter: options.minFilter, magFilter: options.magFilter, wrapS: options.wrapS, wrapT: options.wrapT } ] }; const textureInfo = { index: 0 }; if (options.useTextureTransform) { textureInfo.extensions = { KHR_texture_transform: {} }; } return import__493.GltfLoaderUtil.createSampler({ gltf, textureInfo }); } it("createSampler fills in undefined sampler properties", function() { const sampler = createSampler({ wrapS: import__493.TextureWrap.CLAMP_TO_EDGE }); expect(sampler.wrapS).toBe(import__493.TextureWrap.CLAMP_TO_EDGE); expect(sampler.wrapT).toBe(import__493.TextureWrap.REPEAT); expect(sampler.minificationFilter).toBe(import__493.TextureMinificationFilter.LINEAR); expect(sampler.magnificationFilter).toBe( import__493.TextureMagnificationFilter.LINEAR ); }); it("createModelTextureReader creates texture with default values", function() { const textureInfo = { index: 0 }; const modelTexture = import__493.GltfLoaderUtil.createModelTextureReader({ textureInfo }); expect(modelTexture.texture).toBeUndefined(); expect(modelTexture.texCoord).toBe(0); expect(modelTexture.transform).toBeUndefined(); expect(modelTexture.channels).toBeUndefined(); }); it("createModelTextureReader creates texture with KHR_texture_transform extension", function() { const textureInfo = { index: 0, texCoord: 0, extensions: { KHR_texture_transform: { offset: [0.5, 0.5], scale: [0.1, 0.2], texCoord: 1 } } }; const expectedTransform = new import__493.Matrix3( 0.1, 0, 0.5, 0, 0.2, 0.5, 0, 0, 1 ); const modelTexture = import__493.GltfLoaderUtil.createModelTextureReader({ textureInfo }); expect(modelTexture.texCoord).toBe(1); expect(modelTexture.transform).toEqual(expectedTransform); }); it("createModelTextureReader handles KHR_texture_transform rotation correctly", function() { const angle = Math.PI / 2; const textureInfo = { index: 0, texCoord: 0, extensions: { KHR_texture_transform: { rotation: angle, texCoord: 1 } } }; const expectedTransform = new import__493.Matrix3( Math.cos(-angle), -Math.sin(-angle), 0, Math.sin(-angle), Math.cos(-angle), 0, 0, 0, 1 ); const modelTexture = import__493.GltfLoaderUtil.createModelTextureReader({ textureInfo }); expect(modelTexture.texCoord).toBe(1); expect(modelTexture.transform).toEqual(expectedTransform); }); it("createModelTextureReader creates texture", function() { const context = createContext_default(); const texture = new import__493.Texture({ context, pixelFormat: import__493.PixelFormat.RGBA, pixelDatatype: import__493.PixelDatatype.UNSIGNED_BYTE, source: { arrayBufferView: new Uint8Array([1, 2, 3, 4]), width: 1, height: 1 } }); const textureInfo = { index: 0, texCoord: 1 }; const modelTexture = import__493.GltfLoaderUtil.createModelTextureReader({ textureInfo, channels: "r", texture }); expect(modelTexture.texture).toBe(texture); expect(modelTexture.texCoord).toBe(1); expect(modelTexture.transform).toBeUndefined(); expect(modelTexture.channels).toBe("r"); texture.destroy(); context.destroyForSpecs(); }); it("createModelTextureReader throws if textureInfo is undefined", function() { expect(function() { import__493.GltfLoaderUtil.createModelTextureReader(); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Scene/GltfStructuralMetadataLoaderSpec.js var import__494 = __toESM(require_Cesium(), 1); // Specs/MetadataTester.js var import_engine26 = __toESM(require_Cesium(), 1); function MetadataTester() { } MetadataTester.isSupported = function() { return import_engine26.FeatureDetection.supportsBigInt64Array() && import_engine26.FeatureDetection.supportsBigUint64Array() && import_engine26.FeatureDetection.supportsBigInt() && typeof TextEncoder !== "undefined"; }; MetadataTester.createProperty = function(options) { const properties = { propertyId: options.property }; const propertyValues = { propertyId: options.values }; const table = MetadataTester.createMetadataTable({ properties, propertyValues, // offsetType is for legacy EXT_feature_metadata, arrayOffsetType and // stringOffsetType are for EXT_structural_metadata offsetType: options.offsetType, arrayOffsetType: options.arrayOffsetType, stringOffsetType: options.stringOffsetType, enums: options.enums, disableBigIntSupport: options.disableBigIntSupport, disableBigInt64ArraySupport: options.disableBigInt64ArraySupport, disableBigUint64ArraySupport: options.disableBigUint64ArraySupport }); return table._properties.propertyId; }; function createProperties(options) { const schema = options.schema; const classId = options.classId; const propertyValues = options.propertyValues; const offsetType = options.offsetType; const stringOffsetType = options.stringOffsetType; const arrayOffsetType = options.arrayOffsetType; const bufferViews = (0, import_engine26.defined)(options.bufferViews) ? options.bufferViews : {}; const enums = (0, import_engine26.defined)(schema.enums) ? schema.enums : {}; const enumDefinitions = {}; for (const enumId in enums) { if (enums.hasOwnProperty(enumId)) { enumDefinitions[enumId] = import_engine26.MetadataEnum.fromJson({ id: enumId, enum: enums[enumId] }); } } const classDefinition = import_engine26.MetadataClass.fromJson({ id: classId, class: schema.classes[classId], enums: enumDefinitions }); const properties = {}; let bufferViewIndex = Object.keys(bufferViews).length; let count = 0; for (const propertyId in propertyValues) { if (propertyValues.hasOwnProperty(propertyId)) { const classProperty = classDefinition.properties[propertyId]; const values = propertyValues[propertyId]; count = values.length; const valuesBuffer = addPadding( createValuesBuffer(values, classProperty) ); const valuesBufferView = bufferViewIndex++; bufferViews[valuesBufferView] = valuesBuffer; const property = { values: valuesBufferView }; properties[propertyId] = property; if ((0, import_engine26.defined)(offsetType)) { property.offsetType = offsetType; } if ((0, import_engine26.defined)(stringOffsetType)) { property.stringOffsetType = stringOffsetType; } if ((0, import_engine26.defined)(arrayOffsetType)) { property.arrayOffsetType = arrayOffsetType; } if (classProperty.isVariableLengthArray) { const arrayOffsetBufferType = (0, import_engine26.defaultValue)(arrayOffsetType, offsetType); const arrayOffsetBuffer = addPadding( createArrayOffsetBuffer( values, classProperty.type, arrayOffsetBufferType ) ); const arrayOffsetBufferView = bufferViewIndex++; bufferViews[arrayOffsetBufferView] = arrayOffsetBuffer; property.arrayOffsets = arrayOffsetBufferView; } if (classProperty.type === import_engine26.MetadataType.STRING) { const stringOffsetBufferType = (0, import_engine26.defaultValue)( stringOffsetType, offsetType ); const stringOffsetBuffer = addPadding( createStringOffsetBuffer(values, stringOffsetBufferType) ); const stringOffsetBufferView = bufferViewIndex++; bufferViews[stringOffsetBufferView] = stringOffsetBuffer; property.stringOffsets = stringOffsetBufferView; } } } return { count, properties, class: classDefinition, bufferViews }; } MetadataTester.createMetadataTable = function(options) { options = (0, import_engine26.defaultValue)(options, import_engine26.defaultValue.EMPTY_OBJECT); const disableBigIntSupport = options.disableBigIntSupport; const disableBigInt64ArraySupport = options.disableBigInt64ArraySupport; const disableBigUint64ArraySupport = options.disableBigUint64ArraySupport; const schema = { enums: options.enums, classes: { classId: { properties: options.properties } } }; const propertyResults = createProperties({ schema, classId: "classId", propertyValues: options.propertyValues, offsetType: options.offsetType }); const count = propertyResults.count; const properties = propertyResults.properties; const classDefinition = propertyResults.class; const bufferViews = propertyResults.bufferViews; if (disableBigIntSupport) { spyOn(import_engine26.FeatureDetection, "supportsBigInt").and.returnValue(false); } if (disableBigInt64ArraySupport) { spyOn(import_engine26.FeatureDetection, "supportsBigInt64Array").and.returnValue(false); } if (disableBigUint64ArraySupport) { spyOn(import_engine26.FeatureDetection, "supportsBigUint64Array").and.returnValue(false); } return new import_engine26.MetadataTable({ count, properties, class: classDefinition, bufferViews }); }; MetadataTester.createPropertyTable = function(options) { options = (0, import_engine26.defaultValue)(options, import_engine26.defaultValue.EMPTY_OBJECT); const disableBigIntSupport = options.disableBigIntSupport; const disableBigInt64ArraySupport = options.disableBigInt64ArraySupport; const disableBigUint64ArraySupport = options.disableBigUint64ArraySupport; const schema = { enums: options.enums, classes: { classId: { properties: options.properties } } }; const propertyResults = createProperties({ schema, classId: "classId", propertyValues: options.propertyValues, offsetType: options.offsetType }); const count = propertyResults.count; const properties = propertyResults.properties; const classDefinition = propertyResults.class; const bufferViews = propertyResults.bufferViews; if (disableBigIntSupport) { spyOn(import_engine26.FeatureDetection, "supportsBigInt").and.returnValue(false); } if (disableBigInt64ArraySupport) { spyOn(import_engine26.FeatureDetection, "supportsBigInt64Array").and.returnValue(false); } if (disableBigUint64ArraySupport) { spyOn(import_engine26.FeatureDetection, "supportsBigUint64Array").and.returnValue(false); } const metadataTable = new import_engine26.MetadataTable({ count, class: classDefinition, bufferViews, properties }); return new import_engine26.PropertyTable({ metadataTable, count, extras: options.extras, extensions: options.extensions }); }; MetadataTester.createPropertyTables = function(options) { options = (0, import_engine26.defaultValue)(options, import_engine26.defaultValue.EMPTY_OBJECT); const propertyTables = []; const bufferViews = {}; for (let i = 0; i < options.propertyTables.length; i++) { const propertyTable = options.propertyTables[i]; const tablePropertyResults = createProperties({ schema: options.schema, classId: propertyTable.class, propertyValues: propertyTable.properties, bufferViews }); const count = tablePropertyResults.count; const properties = tablePropertyResults.properties; propertyTables.push({ name: propertyTable.name, class: propertyTable.class, count, properties }); } return { propertyTables, bufferViews }; }; MetadataTester.createFeatureTables = function(options) { options = (0, import_engine26.defaultValue)(options, import_engine26.defaultValue.EMPTY_OBJECT); const featureTables = {}; const bufferViews = {}; for (const featureTableId in options.featureTables) { if (options.featureTables.hasOwnProperty(featureTableId)) { const featureTable = options.featureTables[featureTableId]; const propertyResults = createProperties({ schema: options.schema, classId: featureTable.class, propertyValues: featureTable.properties, bufferViews }); const count = propertyResults.count; const properties = propertyResults.properties; featureTables[featureTableId] = { class: featureTable.class, count, properties }; } } return { featureTables, bufferViews }; }; MetadataTester.createGltf = function(options) { options = (0, import_engine26.defaultValue)(options, import_engine26.defaultValue.EMPTY_OBJECT); const propertyTableResults = MetadataTester.createPropertyTables(options); let bufferByteLength = 0; const bufferViewsMap = propertyTableResults.bufferViews; const bufferViewsLength = Object.keys(bufferViewsMap).length; const byteLengths = new Array(bufferViewsLength); let bufferViewId; let uint8Array; for (bufferViewId in bufferViewsMap) { if (bufferViewsMap.hasOwnProperty(bufferViewId)) { uint8Array = bufferViewsMap[bufferViewId]; const remainder = uint8Array.byteLength % 8; const padding = remainder === 0 ? 0 : 8 - remainder; const byteLength = uint8Array.byteLength + padding; bufferByteLength += byteLength; byteLengths[bufferViewId] = byteLength; } } const buffer = new Uint8Array(bufferByteLength); const bufferViews = new Array(bufferViewsLength); let byteOffset = 0; for (bufferViewId in bufferViewsMap) { if (bufferViewsMap.hasOwnProperty(bufferViewId)) { uint8Array = bufferViewsMap[bufferViewId]; bufferViews[bufferViewId] = { buffer: 0, byteOffset, byteLength: uint8Array.byteLength }; buffer.set(uint8Array, byteOffset); byteOffset += byteLengths[bufferViewId]; } } const gltf = { buffers: [ { uri: "external.bin", byteLength: buffer.byteLength } ], images: options.images, textures: options.textures, bufferViews, extensionsUsed: ["EXT_structural_metadata"], extensions: { EXT_structural_metadata: { schema: options.schema, propertyTables: propertyTableResults.propertyTables, propertyTextures: options.propertyTextures } } }; return { gltf, buffer }; }; function createBuffer(values, componentType) { let typedArray; switch (componentType) { case import_engine26.MetadataComponentType.INT8: typedArray = new Int8Array(values); break; case import_engine26.MetadataComponentType.UINT8: typedArray = new Uint8Array(values); break; case import_engine26.MetadataComponentType.INT16: typedArray = new Int16Array(values); break; case import_engine26.MetadataComponentType.UINT16: typedArray = new Uint16Array(values); break; case import_engine26.MetadataComponentType.INT32: typedArray = new Int32Array(values); break; case import_engine26.MetadataComponentType.UINT32: typedArray = new Uint32Array(values); break; case import_engine26.MetadataComponentType.INT64: typedArray = new BigInt64Array(values); break; case import_engine26.MetadataComponentType.UINT64: typedArray = new BigUint64Array(values); break; case import_engine26.MetadataComponentType.FLOAT32: typedArray = new Float32Array(values); break; case import_engine26.MetadataComponentType.FLOAT64: typedArray = new Float64Array(values); break; default: throw new import_engine26.DeveloperError( `${componentType} is not a valid component type` ); } return new Uint8Array(typedArray.buffer); } function createStringBuffer(values) { const encoder = new TextEncoder(); return encoder.encode(values.join("")); } function createBooleanBuffer(values) { const length2 = Math.ceil(values.length / 8); const typedArray = new Uint8Array(length2); for (let i = 0; i < values.length; ++i) { const byteIndex = i >> 3; const bitIndex = i % 8; if (values[i]) { typedArray[byteIndex] |= 1 << bitIndex; } } return typedArray; } function flatten(values) { return [].concat.apply([], values); } function createValuesBuffer(values, classProperty) { const type = classProperty.type; const valueType = classProperty.valueType; const enumType = classProperty.enumType; const flattenedValues = flatten(values); if (type === import_engine26.MetadataType.STRING) { return createStringBuffer(flattenedValues); } if (type === import_engine26.MetadataType.BOOLEAN) { return createBooleanBuffer(flattenedValues); } if ((0, import_engine26.defined)(enumType)) { const length2 = flattenedValues.length; for (let i = 0; i < length2; ++i) { flattenedValues[i] = enumType.valuesByName[flattenedValues[i]]; } } return createBuffer(flattenedValues, valueType); } function createStringOffsetBuffer(values, offsetType) { const encoder = new TextEncoder(); const strings = flatten(values); const length2 = strings.length; const offsets = new Array(length2 + 1); let offset = 0; for (let i = 0; i < length2; ++i) { offsets[i] = offset; offset += encoder.encode(strings[i]).length; } offsets[length2] = offset; offsetType = (0, import_engine26.defaultValue)(offsetType, import_engine26.MetadataComponentType.UINT32); return createBuffer(offsets, offsetType); } function createArrayOffsetBuffer(values, type, offsetType) { const componentCount = import_engine26.MetadataType.getComponentCount(type); const length2 = values.length; const offsets = new Array(length2 + 1); let offset = 0; for (let i = 0; i < length2; ++i) { offsets[i] = offset; offset += values[i].length / componentCount; } offsets[length2] = offset; offsetType = (0, import_engine26.defaultValue)(offsetType, import_engine26.MetadataComponentType.UINT32); return createBuffer(offsets, offsetType); } function addPadding(uint8Array) { const paddingBytes = 8; const padded = new Uint8Array(paddingBytes + uint8Array.length); padded.set(uint8Array, paddingBytes); return new Uint8Array(padded.buffer, paddingBytes, uint8Array.length); } var MetadataTester_default = MetadataTester; // packages/engine/Specs/Scene/GltfStructuralMetadataLoaderSpec.js describe( "Scene/GltfStructuralMetadataLoader", function() { if (!MetadataTester_default.isSupported()) { return; } const image = new Image(); image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII="; const gltfUri = "https://example.com/model.glb"; const gltfResource = new import__494.Resource({ url: gltfUri }); const schemaJson = { classes: { building: { properties: { name: { type: "STRING" }, height: { type: "SCALAR", componentType: "FLOAT64" } } }, tree: { properties: { species: { type: "STRING", array: true } } }, map: { properties: { color: { type: "SCALAR", componentType: "UINT8", array: true, count: 3 }, intensity: { type: "SCALAR", componentType: "UINT8" } } }, ortho: { properties: { vegetation: { type: "SCALAR", componentType: "UINT8", normalized: true } } } } }; const results = MetadataTester_default.createGltf({ schema: schemaJson, propertyTables: [ { name: "Buildings", class: "building", properties: { name: ["House", "Hospital"], height: [10, 20] } }, { name: "Trees", class: "tree", properties: { species: [["Sparrow", "Squirrel"], ["Crow"]] } } ], images: [ { uri: "map.png" }, { uri: "ortho.png" } ], textures: [ { source: 0 }, { source: 1 } ], propertyTextures: [ { name: "Map", class: "map", properties: { color: { channels: [0, 1, 2], index: 0, texCoord: 0 }, intensity: { channels: [3], index: 0, texCoord: 0 } } }, { name: "Ortho", class: "ortho", properties: { vegetation: { channels: [0], index: 1, texCoord: 1 } } } ] }); const gltf = results.gltf; const extension = gltf.extensions.EXT_structural_metadata; const buffer = results.buffer.buffer; const gltfSchemaUri = (0, import__494.clone)(gltf, true); const extensionSchemaUri = gltfSchemaUri.extensions.EXT_structural_metadata; extensionSchemaUri.schemaUri = "schema.json"; delete extensionSchemaUri.schema; const mockFrameState = { context: { id: "01234" } }; let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { import__494.ResourceCache.clearForSpecs(); }); it("throws if gltf is undefined", function() { expect(function() { return new import__494.GltfStructuralMetadataLoader({ gltf: void 0, extension, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__494.SupportedImageFormats(), frameState: mockFrameState }); }).toThrowDeveloperError(); }); it("throws if neither extension nor extensionLegacy is defined", function() { expect(function() { return new import__494.GltfStructuralMetadataLoader({ gltf, extension: void 0, extensionLegacy: void 0, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__494.SupportedImageFormats(), frameState: mockFrameState }); }).toThrowDeveloperError(); }); it("throws if gltfResource is undefined", function() { expect(function() { return new import__494.GltfStructuralMetadataLoader({ gltf, extension, gltfResource: void 0, baseResource: gltfResource, supportedImageFormats: new import__494.SupportedImageFormats(), frameState: mockFrameState }); }).toThrowDeveloperError(); }); it("throws if baseResource is undefined", function() { expect(function() { return new import__494.GltfStructuralMetadataLoader({ gltf, extension, gltfResource, baseResource: void 0, supportedImageFormats: new import__494.SupportedImageFormats(), frameState: mockFrameState }); }).toThrowDeveloperError(); }); it("throws if supportedImageFormats is undefined", function() { expect(function() { return new import__494.GltfStructuralMetadataLoader({ gltf, extension, gltfResource, baseResource: gltfResource, supportedImageFormats: void 0, frameState: mockFrameState }); }).toThrowDeveloperError(); }); it("throws if frameState is undefined", function() { expect(function() { return new import__494.GltfStructuralMetadataLoader({ gltf, extension, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__494.SupportedImageFormats(), frameState: void 0 }); }).toThrowDeveloperError(); }); it("load throws if buffer view fails to load", async function() { spyOn(import__494.Resource.prototype, "fetchArrayBuffer").and.callFake(function() { const error = new Error("404 Not Found"); return Promise.reject(error); }); spyOn(import__494.Resource.prototype, "fetchImage").and.returnValue( Promise.resolve(image) ); const structuralMetadataLoader = new import__494.GltfStructuralMetadataLoader({ gltf, extension, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__494.SupportedImageFormats(), frameState: mockFrameState }); await expectAsync(structuralMetadataLoader.load()).toBeRejectedWithError( import__494.RuntimeError, "Failed to load structural metadata\nFailed to load buffer view\nFailed to load external buffer: https://example.com/external.bin\n404 Not Found" ); }); it("load throws if texture fails to load", async function() { spyOn(import__494.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(buffer) ); spyOn(import__494.Resource.prototype, "fetchImage").and.callFake(function() { const error = new Error("404 Not Found"); return Promise.reject(error); }); const structuralMetadataLoader = new import__494.GltfStructuralMetadataLoader({ gltf, extension, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__494.SupportedImageFormats(), frameState: mockFrameState }); await expectAsync(structuralMetadataLoader.load()).toBeRejectedWithError( import__494.RuntimeError, "Failed to load structural metadata\nFailed to load texture\nFailed to load image: map.png\n404 Not Found" ); }); it("load throws if external schema fails to load", async function() { spyOn(import__494.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(buffer) ); spyOn(import__494.Resource.prototype, "fetchImage").and.returnValue( Promise.resolve(image) ); spyOn(import__494.Resource.prototype, "fetchJson").and.callFake(function() { const error = new Error("404 Not Found"); return Promise.reject(error); }); const structuralMetadataLoader = new import__494.GltfStructuralMetadataLoader({ gltf: gltfSchemaUri, extension: extensionSchemaUri, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__494.SupportedImageFormats(), frameState: mockFrameState }); await expectAsync(structuralMetadataLoader.load()).toBeRejectedWithError( import__494.RuntimeError, "Failed to load structural metadata\nFailed to load schema: https://example.com/schema.json\n404 Not Found" ); }); it("loads structural metadata", async function() { spyOn(import__494.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(buffer) ); spyOn(import__494.Resource.prototype, "fetchImage").and.returnValue( Promise.resolve(image) ); const structuralMetadataLoader = new import__494.GltfStructuralMetadataLoader({ gltf, extension, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__494.SupportedImageFormats(), frameState: mockFrameState }); await structuralMetadataLoader.load(); await waitForLoaderProcess_default(structuralMetadataLoader, scene2); expect( () => loaderProcess_default(structuralMetadataLoader, scene2) ).not.toThrow(); const structuralMetadata = structuralMetadataLoader.structuralMetadata; const buildingsTable = structuralMetadata.getPropertyTable(0); expect(buildingsTable.id).toBe(0); const treesTable = structuralMetadata.getPropertyTable(1); expect(treesTable.id).toBe(1); const mapTexture = structuralMetadata.getPropertyTexture(0); expect(mapTexture.id).toBe(0); const orthoTexture = structuralMetadata.getPropertyTexture(1); expect(orthoTexture.id).toBe(1); expect(buildingsTable.getProperty(0, "name")).toBe("House"); expect(buildingsTable.getProperty(1, "name")).toBe("Hospital"); expect(treesTable.getProperty(0, "species")).toEqual([ "Sparrow", "Squirrel" ]); expect(treesTable.getProperty(1, "species")).toEqual(["Crow"]); const colorProperty = mapTexture.getProperty("color"); const intensityProperty = mapTexture.getProperty("intensity"); const vegetationProperty = orthoTexture.getProperty("vegetation"); expect(colorProperty.textureReader.texture.width).toBe(1); expect(colorProperty.textureReader.texture.height).toBe(1); expect(colorProperty.textureReader.texture).toBe( intensityProperty.textureReader.texture ); expect(vegetationProperty.textureReader.texture.width).toBe(1); expect(vegetationProperty.textureReader.texture.height).toBe(1); expect(vegetationProperty.textureReader.texture).not.toBe( colorProperty.textureReader.texture ); expect(Object.keys(structuralMetadata.schema.classes).sort()).toEqual([ "building", "map", "ortho", "tree" ]); }); it("loads structural metadata with external schema", async function() { spyOn(import__494.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(buffer) ); spyOn(import__494.Resource.prototype, "fetchImage").and.returnValue( Promise.resolve(image) ); spyOn(import__494.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(schemaJson) ); const structuralMetadataLoader = new import__494.GltfStructuralMetadataLoader({ gltf: gltfSchemaUri, extension: extensionSchemaUri, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__494.SupportedImageFormats(), frameState: mockFrameState }); await structuralMetadataLoader.load(); await waitForLoaderProcess_default(structuralMetadataLoader, scene2); const structuralMetadata = structuralMetadataLoader.structuralMetadata; expect(Object.keys(structuralMetadata.schema.classes).sort()).toEqual([ "building", "map", "ortho", "tree" ]); }); it("destroys structural metadata", async function() { spyOn(import__494.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(buffer) ); spyOn(import__494.Resource.prototype, "fetchImage").and.returnValue( Promise.resolve(image) ); spyOn(import__494.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(schemaJson) ); const destroyBufferView = spyOn( import__494.GltfBufferViewLoader.prototype, "destroy" ).and.callThrough(); const destroyTexture = spyOn( import__494.GltfTextureLoader.prototype, "destroy" ).and.callThrough(); const destroySchema = spyOn( import__494.MetadataSchemaLoader.prototype, "destroy" ).and.callThrough(); const structuralMetadataLoader = new import__494.GltfStructuralMetadataLoader({ gltf, extension, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__494.SupportedImageFormats(), frameState: mockFrameState }); await structuralMetadataLoader.load(); await waitForLoaderProcess_default(structuralMetadataLoader, scene2); expect(structuralMetadataLoader.structuralMetadata).toBeDefined(); expect(structuralMetadataLoader.isDestroyed()).toBe(false); structuralMetadataLoader.destroy(); expect(structuralMetadataLoader.structuralMetadata).not.toBeDefined(); expect(structuralMetadataLoader.isDestroyed()).toBe(true); expect(destroyBufferView.calls.count()).toBe(6); expect(destroyTexture.calls.count()).toBe(2); expect(destroySchema.calls.count()).toBe(1); }); async function resolveAfterDestroy(rejectPromise) { spyOn(import__494.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(buffer) ); spyOn(import__494.Resource.prototype, "fetchImage").and.returnValue( Promise.resolve(image) ); spyOn(import__494.Resource.prototype, "fetchJson").and.callFake( () => rejectPromise ? Promise.reject(new Error("")) : Promise.resolve(schemaJson) ); const destroyBufferView = spyOn( import__494.GltfBufferViewLoader.prototype, "destroy" ).and.callThrough(); const destroyTexture = spyOn( import__494.GltfTextureLoader.prototype, "destroy" ).and.callThrough(); const destroySchema = spyOn( import__494.MetadataSchemaLoader.prototype, "destroy" ).and.callThrough(); const structuralMetadataLoader = new import__494.GltfStructuralMetadataLoader({ gltf: gltfSchemaUri, extension: extensionSchemaUri, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__494.SupportedImageFormats(), frameState: mockFrameState }); expect(structuralMetadataLoader.structuralMetadata).not.toBeDefined(); const promise = structuralMetadataLoader.load(); structuralMetadataLoader.destroy(); expect(structuralMetadataLoader.structuralMetadata).not.toBeDefined(); expect(structuralMetadataLoader.isDestroyed()).toBe(true); expect(destroyBufferView.calls.count()).toBe(6); expect(destroyTexture.calls.count()).toBe(2); expect(destroySchema.calls.count()).toBe(1); await expectAsync(promise).toBeResolved(); } it("handles resolving resources after destroy", function() { return resolveAfterDestroy(false); }); it("handles rejecting resources after destroy", function() { return resolveAfterDestroy(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/GltfTextureLoaderSpec.js var import__495 = __toESM(require_Cesium(), 1); describe( "Scene/GltfTextureLoader", function() { const image = new Image(); image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII="; const imageNpot = new Image(); imageNpot.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACAQMAAACnuvRZAAAAA3NCSVQICAjb4U/gAAAABlBMVEUAAAD///+l2Z/dAAAAAnRSTlP/AOW3MEoAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAAcdEVYdFNvZnR3YXJlAEFkb2JlIEZpcmV3b3JrcyBDUzQGstOgAAAAFnRFWHRDcmVhdGlvbiBUaW1lADAxLzA0LzE0Kb6O2wAAAAxJREFUCJljeMDwAAADhAHBgGgjpQAAAABJRU5ErkJggg=="; const gltfUri = "https://example.com/model.glb"; const gltfResource = new import__495.Resource({ url: gltfUri }); const gltf = { images: [ { uri: "image.png" } ], textures: [ { source: 0 }, { source: 0, sampler: 0 }, { source: 0, sampler: 1 } ], materials: [ { emissiveTexture: { index: 0 }, occlusionTexture: { index: 1 }, normalTexture: { index: 2 } } ], samplers: [ { magFilter: 9728, // NEAREST minFilter: 9984, // NEAREST_MIPMAP_NEAREST wrapS: 10497, // REPEAT wrapT: 10497 // REPEAT }, { magFilter: 9728, // NEAREST minFilter: 9728, // NEAREST wrapS: 33071, // CLAMP_TO_EDGE wrapT: 33071 // CLAMP_TO_EDGE } ] }; const gltfKtx2BaseResource = new import__495.Resource({ url: "./Data/Images/" }); const gltfKtx2 = { images: [ { uri: "image.png" }, { uri: "Green4x4_ETC1S.ktx2" }, { uri: "Green4x4Mipmap_ETC1S.ktx2" } ], textures: [ { source: 0, sampler: 0, extensions: { KHR_texture_basisu: { source: 1 } } }, { source: 0, sampler: 1, extensions: { KHR_texture_basisu: { source: 2 } } } ], materials: [ { emissiveTexture: { index: 0 }, occlusionTexture: { index: 1 } } ], samplers: [ { magFilter: 9728, // NEAREST minFilter: 9728, // NEAREST wrapS: 10497, // REPEAT wrapT: 10497 // REPEAT }, { magFilter: 9728, // NEAREST minFilter: 9984, // NEAREST_MIPMAP_NEAREST wrapS: 33071, // CLAMP_TO_EDGE wrapT: 33071 // CLAMP_TO_EDGE } ] }; let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { import__495.ResourceCache.clearForSpecs(); }); it("throws if resourceCache is undefined", function() { expect(function() { return new import__495.GltfTextureLoader({ resourceCache: void 0, gltf, imageId: 0, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__495.SupportedImageFormats() }); }).toThrowDeveloperError(); }); it("throws if gltf is undefined", function() { expect(function() { return new import__495.GltfTextureLoader({ resourceCache: import__495.ResourceCache, gltf: void 0, textureInfo: gltf.materials[0].emissiveTexture, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__495.SupportedImageFormats() }); }).toThrowDeveloperError(); }); it("throws if textureInfo is undefined", function() { expect(function() { return new import__495.GltfTextureLoader({ resourceCache: import__495.ResourceCache, gltf, textureInfo: void 0, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__495.SupportedImageFormats() }); }).toThrowDeveloperError(); }); it("throws if gltfResource is undefined", function() { expect(function() { return new import__495.GltfTextureLoader({ resourceCache: import__495.ResourceCache, gltf, textureInfo: gltf.materials[0].emissiveTexture, gltfResource: void 0, baseResource: gltfResource, supportedImageFormats: new import__495.SupportedImageFormats() }); }).toThrowDeveloperError(); }); it("throws if baseResource is undefined", function() { expect(function() { return new import__495.GltfTextureLoader({ resourceCache: import__495.ResourceCache, gltf, textureInfo: gltf.materials[0].emissiveTexture, gltfResource, baseResource: void 0, supportedImageFormats: new import__495.SupportedImageFormats() }); }).toThrowDeveloperError(); }); it("throws if supportedImageFormats is undefined", function() { expect(function() { return new import__495.GltfTextureLoader({ resourceCache: import__495.ResourceCache, gltf, textureInfo: gltf.materials[0].emissiveTexture, gltfResource, baseResource: gltfResource, supportedImageFormats: void 0 }); }).toThrowDeveloperError(); }); it("load throws if image fails to load", async function() { spyOn(import__495.Resource.prototype, "fetchImage").and.callFake( () => Promise.reject(new Error("404 Not Found")) ); const textureLoader = new import__495.GltfTextureLoader({ resourceCache: import__495.ResourceCache, gltf, textureInfo: gltf.materials[0].emissiveTexture, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__495.SupportedImageFormats() }); await expectAsync(textureLoader.load()).toBeRejectedWithError( import__495.RuntimeError, "Failed to load texture\nFailed to load image: image.png\n404 Not Found" ); }); it("loads texture", async function() { spyOn(import__495.Resource.prototype, "fetchImage").and.returnValue( Promise.resolve(image) ); const processCallsTotal = 3; let processCallsCount = 0; const jobScheduler = scene2.frameState.jobScheduler; const originalJobSchedulerExecute = jobScheduler.execute; spyOn(import__495.JobScheduler.prototype, "execute").and.callFake(function(job, jobType) { if (processCallsCount++ >= processCallsTotal) { return originalJobSchedulerExecute.call(jobScheduler, job, jobType); } return false; }); const textureLoader = new import__495.GltfTextureLoader({ resourceCache: import__495.ResourceCache, gltf, textureInfo: gltf.materials[0].emissiveTexture, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__495.SupportedImageFormats() }); expect(() => loaderProcess_default(textureLoader, scene2)).not.toThrowError(); await textureLoader.load(); await waitForLoaderProcess_default(textureLoader, scene2); expect(() => loaderProcess_default(textureLoader, scene2)).not.toThrowError(); expect(textureLoader.texture.width).toBe(1); expect(textureLoader.texture.height).toBe(1); expect(import__495.ResourceCache.statistics.texturesByteLength).toBe( textureLoader.texture.sizeInBytes ); }); it("creates texture synchronously", async function() { spyOn(import__495.Resource.prototype, "fetchImage").and.returnValue( Promise.resolve(image) ); const textureLoader = new import__495.GltfTextureLoader({ resourceCache: import__495.ResourceCache, gltf, textureInfo: gltf.materials[0].emissiveTexture, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__495.SupportedImageFormats(), asynchronous: false }); await textureLoader.load(); await waitForLoaderProcess_default(textureLoader, scene2); expect(() => loaderProcess_default(textureLoader, scene2)).not.toThrowError(); expect(textureLoader.texture.width).toBe(1); expect(textureLoader.texture.height).toBe(1); }); it("loads KTX2/Basis texture", async function() { if (!scene2.context.supportsBasis) { return; } const gl = scene2.context._gl; spyOn(gl, "compressedTexImage2D").and.callThrough(); const textureLoader = new import__495.GltfTextureLoader({ resourceCache: import__495.ResourceCache, gltf: gltfKtx2, textureInfo: gltf.materials[0].emissiveTexture, gltfResource, baseResource: gltfKtx2BaseResource, supportedImageFormats: new import__495.SupportedImageFormats({ basis: true }) }); await textureLoader.load(); await waitForLoaderProcess_default(textureLoader, scene2); expect(textureLoader.texture.width).toBe(4); expect(textureLoader.texture.height).toBe(4); expect(gl.compressedTexImage2D.calls.count()).toEqual(1); }); it("loads KTX2/Basis texture with mipmap", async function() { if (!scene2.context.supportsBasis) { return; } const gl = scene2.context._gl; spyOn(gl, "compressedTexImage2D").and.callThrough(); const textureLoader = new import__495.GltfTextureLoader({ resourceCache: import__495.ResourceCache, gltf: gltfKtx2, textureInfo: gltf.materials[0].occlusionTexture, gltfResource, baseResource: gltfKtx2BaseResource, supportedImageFormats: new import__495.SupportedImageFormats({ basis: true }) }); await textureLoader.load(); await waitForLoaderProcess_default(textureLoader, scene2); expect(textureLoader.texture.width).toBe(4); expect(textureLoader.texture.height).toBe(4); expect(gl.compressedTexImage2D.calls.count()).toEqual(3); }); it("loads KTX2/Basis texture with incompatible mipmap sampler", async function() { if (!scene2.context.supportsBasis) { return; } spyOn(import__495.GltfLoaderUtil, "createSampler").and.callThrough(); const gltfKtx2MissingMipmap = (0, import__495.clone)(gltfKtx2, true); gltfKtx2MissingMipmap.samplers[0].minFilter = import__495.TextureMinificationFilter.NEAREST_MIPMAP_NEAREST; const textureLoader = new import__495.GltfTextureLoader({ resourceCache: import__495.ResourceCache, gltf: gltfKtx2MissingMipmap, textureInfo: gltfKtx2MissingMipmap.materials[0].emissiveTexture, gltfResource, baseResource: gltfKtx2BaseResource, supportedImageFormats: new import__495.SupportedImageFormats({ basis: true }), asynchronous: false }); await textureLoader.load(); await waitForLoaderProcess_default(textureLoader, scene2); expect(import__495.GltfLoaderUtil.createSampler).toHaveBeenCalledWith({ gltf: gltfKtx2MissingMipmap, textureInfo: gltf.materials[0].emissiveTexture, compressedTextureNoMipmap: true }); expect(textureLoader.texture.sampler.minificationFilter).toBe( import__495.TextureMinificationFilter.NEAREST ); }); it("generates mipmap if sampler requires it", async function() { spyOn(import__495.Resource.prototype, "fetchImage").and.returnValue( Promise.resolve(image) ); const generateMipmap = spyOn( import__495.Texture.prototype, "generateMipmap" ).and.callThrough(); const textureLoader = new import__495.GltfTextureLoader({ resourceCache: import__495.ResourceCache, gltf, textureInfo: gltf.materials[0].occlusionTexture, // This texture has a sampler that require a mipmap gltfResource, baseResource: gltfResource, supportedImageFormats: new import__495.SupportedImageFormats() }); await textureLoader.load(); await waitForLoaderProcess_default(textureLoader, scene2); expect(textureLoader.texture.width).toBe(1); expect(textureLoader.texture.height).toBe(1); expect(generateMipmap).toHaveBeenCalled(); }); it("generates power-of-two texture if sampler requires it", async function() { spyOn(import__495.Resource.prototype, "fetchImage").and.returnValue( Promise.resolve(imageNpot) ); const textureLoader = new import__495.GltfTextureLoader({ resourceCache: import__495.ResourceCache, gltf, textureInfo: gltf.materials[0].occlusionTexture, // This texture has a sampler that require power-of-two texture gltfResource, baseResource: gltfResource, supportedImageFormats: new import__495.SupportedImageFormats() }); await textureLoader.load(); await waitForLoaderProcess_default(textureLoader, scene2); expect(textureLoader.texture.width).toBe(4); expect(textureLoader.texture.height).toBe(2); }); it("does not generate power-of-two texture if sampler does not require it", async function() { spyOn(import__495.Resource.prototype, "fetchImage").and.returnValue( Promise.resolve(imageNpot) ); const textureLoader = new import__495.GltfTextureLoader({ resourceCache: import__495.ResourceCache, gltf, textureInfo: gltf.materials[0].normalTexture, // This texture has a sampler that does not require power-of-two texture gltfResource, baseResource: gltfResource, supportedImageFormats: new import__495.SupportedImageFormats() }); await textureLoader.load(); await waitForLoaderProcess_default(textureLoader, scene2); expect(textureLoader.texture.width).toBe(3); expect(textureLoader.texture.height).toBe(2); }); it("destroys texture loader", async function() { spyOn(import__495.Resource.prototype, "fetchImage").and.returnValue( Promise.resolve(image) ); const unloadImage = spyOn( import__495.GltfImageLoader.prototype, "unload" ).and.callThrough(); const destroyTexture = spyOn( import__495.Texture.prototype, "destroy" ).and.callThrough(); const textureLoader = new import__495.GltfTextureLoader({ resourceCache: import__495.ResourceCache, gltf, textureInfo: gltf.materials[0].emissiveTexture, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__495.SupportedImageFormats() }); expect(textureLoader.texture).not.toBeDefined(); await textureLoader.load(); await waitForLoaderProcess_default(textureLoader, scene2); expect(textureLoader.texture).toBeDefined(); expect(textureLoader.isDestroyed()).toBe(false); textureLoader.destroy(); expect(textureLoader.texture).not.toBeDefined(); expect(textureLoader.isDestroyed()).toBe(true); expect(unloadImage).toHaveBeenCalled(); expect(destroyTexture).toHaveBeenCalled(); }); async function resolveImageAfterDestroy(rejectPromise) { spyOn(import__495.Resource.prototype, "fetchImage").and.callFake( () => new Promise(function(resolve, reject) { if (rejectPromise) { reject(new Error()); } else { resolve(image); } }) ); const textureLoader = new import__495.GltfTextureLoader({ resourceCache: import__495.ResourceCache, gltf, textureInfo: gltf.materials[0].emissiveTexture, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__495.SupportedImageFormats() }); expect(textureLoader.texture).not.toBeDefined(); const promise = textureLoader.load(); textureLoader.destroy(); await expectAsync(promise).toBeResolved(); expect(textureLoader.texture).not.toBeDefined(); expect(textureLoader.isDestroyed()).toBe(true); } it("handles resolving image after destroy", function() { return resolveImageAfterDestroy(false); }); it("handles rejecting image after destroy", function() { return resolveImageAfterDestroy(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/GltfVertexBufferLoaderSpec.js var import__496 = __toESM(require_Cesium(), 1); describe( "Scene/GltfVertexBufferLoader", function() { const dracoBufferTypedArray = new Uint8Array([ 1, 3, 7, 15, 31, 63, 127, 255 ]); const dracoArrayBuffer = dracoBufferTypedArray.buffer; const decodedPositions = new Uint16Array([0, 0, 0, 65535, 65535, 65535, 0, 65535, 0]); const decodedNormals = new Uint8Array([0, 255, 128, 128, 255, 0]); const decodedIndices = new Uint16Array([0, 1, 2]); const positions = new Float32Array([-1, -1, -1, 1, 1, 1, 0, 1, 0]); const normals = new Float32Array([-1, 0, 0, 1, 0, 0, 0, 1, 0]); const indices = new Uint16Array([0, 1, 2]); const bufferViewTypedArray = concatTypedArrays_default([ positions, normals, indices ]); const arrayBuffer = bufferViewTypedArray.buffer; const gltfUri = "https://example.com/model.glb"; const gltfResource = new import__496.Resource({ url: gltfUri }); const decodeDracoResults = { indexArray: { typedArray: decodedIndices, numberOfIndices: decodedIndices.length }, attributeData: { POSITION: { array: decodedPositions, data: { byteOffset: 0, byteStride: 6, componentDatatype: import__496.ComponentDatatype.UNSIGNED_SHORT, componentsPerAttribute: 3, normalized: false, quantization: { octEncoded: false, quantizationBits: 14, minValues: [-1, -1, -1], range: 2 } } }, NORMAL: { array: decodedNormals, data: { byteOffset: 0, byteStride: 2, componentDatatype: import__496.ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute: 2, normalized: false, quantization: { octEncoded: true, quantizationBits: 10 } } } } }; const gltfDraco = { buffers: [ { uri: "external.bin", byteLength: 8 } ], bufferViews: [ { buffer: 0, byteOffset: 4, byteLength: 4 } ], accessors: [ { componentType: 5126, count: 3, max: [-1, -1, -1], min: [1, 1, 1], type: "VEC3" }, { componentType: 5126, count: 3, type: "VEC3" }, { componentType: 5123, count: 3, type: "SCALAR" } ], meshes: [ { primitives: [ { attributes: { POSITION: 0, NORMAL: 1 }, indices: 2, extensions: { KHR_draco_mesh_compression: { bufferView: 0, attributes: { POSITION: 0, NORMAL: 1 } } } } ] } ] }; const dracoExtension = gltfDraco.meshes[0].primitives[0].extensions.KHR_draco_mesh_compression; const gltfUncompressed = { buffers: [ { uri: "external.bin", byteLength: 78 } ], bufferViews: [ { buffer: 0, byteOffset: 0, byteLength: 36 }, { buffer: 0, byteOffset: 36, byteLength: 36 }, { buffer: 0, byteOffset: 72, byteLength: 6 } ], accessors: [ { componentType: 5126, count: 3, max: [-1, -1, -1], min: [1, 1, 1], type: "VEC3", bufferView: 0, byteOffset: 0 }, { componentType: 5126, count: 3, type: "VEC3", bufferView: 1, byteOffset: 0 }, { componentType: 5123, count: 3, type: "SCALAR", bufferView: 2, byteOffset: 0 } ], meshes: [ { primitives: [ { attributes: { POSITION: 0, NORMAL: 1 }, indices: 2 } ] } ] }; let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { import__496.ResourceCache.clearForSpecs(); }); it("throws if resourceCache is undefined", function() { expect(function() { return new import__496.GltfVertexBufferLoader({ resourceCache: void 0, gltf: gltfUncompressed, gltfResource, baseResource: gltfResource, bufferViewId: 0, loadBuffer: true }); }).toThrowDeveloperError(); }); it("throws if gltf is undefined", function() { expect(function() { return new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: void 0, gltfResource, baseResource: gltfResource, bufferViewId: 0, loadBuffer: true }); }).toThrowDeveloperError(); }); it("throws if gltfResource is undefined", function() { expect(function() { return new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfUncompressed, gltfResource: void 0, baseResource: gltfResource, bufferViewId: 0, loadBuffer: true }); }).toThrowDeveloperError(); }); it("throws if baseResource is undefined", function() { expect(function() { return new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfUncompressed, gltfResource, baseResource: void 0, bufferViewId: 0, loadBuffer: true }); }).toThrowDeveloperError(); }); it("throws if bufferViewId and draco are both defined", function() { expect(function() { return new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfDraco, gltfResource, baseResource: gltfResource, bufferViewId: 0, draco: dracoExtension, attributeSemantic: "POSITION", accessorId: 0, loadBuffer: true }); }).toThrowDeveloperError(); }); it("throws if bufferViewId and draco are both undefined", function() { expect(function() { return new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfDraco, gltfResource, baseResource: gltfResource, loadBuffer: true }); }).toThrowDeveloperError(); }); it("throws if draco is defined and attributeSemantic is not defined", function() { expect(function() { return new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfDraco, gltfResource, baseResource: gltfResource, draco: dracoExtension, attributeSemantic: void 0, accessorId: 0, loadBuffer: true }); }).toThrowDeveloperError(); }); it("throws if draco is defined and accessorId is not defined", function() { expect(function() { return new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfDraco, gltfResource, baseResource: gltfResource, draco: dracoExtension, attributeSemantic: "POSITION", accessorId: void 0, loadBuffer: true }); }).toThrowDeveloperError(); }); it("throws if both loadBuffer and loadTypedArray are false", function() { expect(function() { return new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfUncompressed, gltfResource, baseResource: void 0, bufferViewId: 0, loadBuffer: false, loadTypedArray: false }); }).toThrowDeveloperError(); }); it("load throws if buffer view fails to load", async function() { spyOn(import__496.Resource.prototype, "fetchArrayBuffer").and.callFake( () => Promise.reject(new Error("404 Not Found")) ); const vertexBufferLoader = new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfUncompressed, gltfResource, baseResource: gltfResource, bufferViewId: 0, loadBuffer: true }); await expectAsync(vertexBufferLoader.load()).toBeRejectedWithError( import__496.RuntimeError, "Failed to load vertex buffer\nFailed to load buffer view\nFailed to load external buffer: https://example.com/external.bin\n404 Not Found" ); }); it("process throws if draco fails to load", async function() { spyOn(import__496.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(dracoArrayBuffer) ); spyOn(import__496.DracoLoader, "decodeBufferView").and.callFake(function() { const error = new Error("Draco decode failed"); return Promise.reject(error); }); const vertexBufferLoader = new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfDraco, gltfResource, baseResource: gltfResource, draco: dracoExtension, attributeSemantic: "POSITION", accessorId: 0, loadBuffer: true }); await vertexBufferLoader.load(); await expectAsync( waitForLoaderProcess_default(vertexBufferLoader, scene2) ).toBeRejectedWithError( import__496.RuntimeError, "Failed to load vertex buffer\nFailed to load Draco\nDraco decode failed" ); }); it("loads as buffer", async function() { spyOn(import__496.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); const processCallsTotal = 3; let processCallsCount = 0; const jobScheduler = scene2.frameState.jobScheduler; const originalJobSchedulerExecute = jobScheduler.execute; spyOn(import__496.JobScheduler.prototype, "execute").and.callFake(function(job, jobType) { if (processCallsCount++ >= processCallsTotal) { return originalJobSchedulerExecute.call(jobScheduler, job, jobType); } return false; }); const vertexBufferLoader = new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfUncompressed, gltfResource, baseResource: gltfResource, bufferViewId: 0, accessorId: 0, loadBuffer: true }); await vertexBufferLoader.load(); await waitForLoaderProcess_default(vertexBufferLoader, scene2); expect(() => loaderProcess_default(vertexBufferLoader, scene2)).not.toThrowError(); expect(vertexBufferLoader.buffer.sizeInBytes).toBe(positions.byteLength); expect(vertexBufferLoader.typedArray).toBeUndefined(); expect(import__496.ResourceCache.statistics.geometryByteLength).toBe( vertexBufferLoader.buffer.sizeInBytes ); }); it("loads as typed array", async function() { spyOn(import__496.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); spyOn(import__496.Buffer, "createVertexBuffer").and.callThrough(); const vertexBufferLoader = new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfUncompressed, gltfResource, baseResource: gltfResource, bufferViewId: 0, accessorId: 0, loadTypedArray: true }); await vertexBufferLoader.load(); await waitForLoaderProcess_default(vertexBufferLoader, scene2); expect(() => loaderProcess_default(vertexBufferLoader, scene2)).not.toThrowError(); expect(vertexBufferLoader.typedArray.byteLength).toBe( positions.byteLength ); expect(vertexBufferLoader.buffer).toBeUndefined(); expect(import__496.Buffer.createVertexBuffer.calls.count()).toBe(0); expect(import__496.ResourceCache.statistics.geometryByteLength).toBe( vertexBufferLoader.typedArray.byteLength ); }); it("loads as both buffer and typed array", async function() { spyOn(import__496.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); const processCallsTotal = 3; let processCallsCount = 0; const jobScheduler = scene2.frameState.jobScheduler; const originalJobSchedulerExecute = jobScheduler.execute; spyOn(import__496.JobScheduler.prototype, "execute").and.callFake(function(job, jobType) { if (processCallsCount++ >= processCallsTotal) { return originalJobSchedulerExecute.call(jobScheduler, job, jobType); } return false; }); const vertexBufferLoader = new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfUncompressed, gltfResource, baseResource: gltfResource, bufferViewId: 0, accessorId: 0, loadBuffer: true, loadTypedArray: true }); await vertexBufferLoader.load(); await waitForLoaderProcess_default(vertexBufferLoader, scene2); expect(() => loaderProcess_default(vertexBufferLoader, scene2)).not.toThrowError(); expect(vertexBufferLoader.buffer.sizeInBytes).toBe(positions.byteLength); expect(vertexBufferLoader.typedArray.byteLength).toBe( positions.byteLength ); const totalSize = vertexBufferLoader.typedArray.byteLength + vertexBufferLoader.buffer.sizeInBytes; expect(import__496.ResourceCache.statistics.geometryByteLength).toBe(totalSize); }); it("creates vertex buffer synchronously", async function() { spyOn(import__496.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); const vertexBufferLoader = new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfUncompressed, gltfResource, baseResource: gltfResource, bufferViewId: 0, asynchronous: false, accessorId: 0, loadBuffer: true }); await vertexBufferLoader.load(); await waitForLoaderProcess_default(vertexBufferLoader, scene2); expect(vertexBufferLoader.buffer.sizeInBytes).toBe(positions.byteLength); expect(vertexBufferLoader.typedArray).toBeUndefined(); }); it("loads positions from draco", async function() { spyOn(import__496.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); const processCallsTotal = 3; let processCallsCount = 0; spyOn(import__496.DracoLoader, "decodeBufferView").and.callFake(function() { if (processCallsCount++ === processCallsTotal) { return Promise.resolve(decodeDracoResults); } return void 0; }); const vertexBufferLoader = new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfDraco, gltfResource, baseResource: gltfResource, draco: dracoExtension, attributeSemantic: "POSITION", accessorId: 0, loadBuffer: true }); await vertexBufferLoader.load(); await waitForLoaderProcess_default(vertexBufferLoader, scene2); expect(() => loaderProcess_default(vertexBufferLoader, scene2)).not.toThrowError(); expect(vertexBufferLoader.buffer.sizeInBytes).toBe( decodedPositions.byteLength ); expect(vertexBufferLoader.typedArray).toBeUndefined(); const quantization = vertexBufferLoader.quantization; expect(quantization.octEncoded).toBe(false); expect(quantization.quantizedVolumeOffset).toEqual( new import__496.Cartesian3(-1, -1, -1) ); expect(quantization.quantizedVolumeDimensions).toEqual( new import__496.Cartesian3(2, 2, 2) ); expect(quantization.normalizationRange).toEqual( new import__496.Cartesian3(16383, 16383, 16383) ); expect(quantization.componentDatatype).toBe( import__496.ComponentDatatype.UNSIGNED_SHORT ); expect(import__496.ResourceCache.statistics.geometryByteLength).toBe( vertexBufferLoader.buffer.sizeInBytes ); }); it("loads normals from draco", async function() { spyOn(import__496.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); spyOn(import__496.DracoLoader, "decodeBufferView").and.callFake(function() { return Promise.resolve(decodeDracoResults); }); const vertexBufferLoader = new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfDraco, gltfResource, baseResource: gltfResource, draco: dracoExtension, attributeSemantic: "NORMAL", accessorId: 1, loadBuffer: true }); await vertexBufferLoader.load(); await waitForLoaderProcess_default(vertexBufferLoader, scene2); expect(vertexBufferLoader.buffer.sizeInBytes).toBe( decodedNormals.byteLength ); const quantization = vertexBufferLoader.quantization; expect(quantization.octEncoded).toBe(true); expect(quantization.octEncodedZXY).toBe(true); expect(quantization.quantizedVolumeOffset).toBeUndefined(); expect(quantization.quantizedVolumeDimensions).toBeUndefined(); expect(quantization.normalizationRange).toBe(1023); expect(quantization.componentDatatype).toBe( import__496.ComponentDatatype.UNSIGNED_BYTE ); }); it("destroys vertex buffer loaded from buffer view", async function() { spyOn(import__496.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); const unloadBufferView = spyOn( import__496.GltfBufferViewLoader.prototype, "unload" ).and.callThrough(); const destroyVertexBuffer = spyOn( import__496.Buffer.prototype, "destroy" ).and.callThrough(); const vertexBufferLoader = new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfUncompressed, gltfResource, baseResource: gltfResource, bufferViewId: 0, accessorId: 0, loadBuffer: true }); await vertexBufferLoader.load(); await waitForLoaderProcess_default(vertexBufferLoader, scene2); expect(vertexBufferLoader.buffer).toBeDefined(); expect(vertexBufferLoader.isDestroyed()).toBe(false); vertexBufferLoader.destroy(); expect(vertexBufferLoader.buffer).not.toBeDefined(); expect(vertexBufferLoader.isDestroyed()).toBe(true); expect(unloadBufferView).toHaveBeenCalled(); expect(destroyVertexBuffer).toHaveBeenCalled(); }); it("destroys vertex buffer loaded from draco", async function() { spyOn(import__496.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(arrayBuffer) ); spyOn(import__496.DracoLoader, "decodeBufferView").and.returnValue( Promise.resolve(decodeDracoResults) ); const unloadDraco = spyOn( import__496.GltfDracoLoader.prototype, "unload" ).and.callThrough(); const destroyVertexBuffer = spyOn( import__496.Buffer.prototype, "destroy" ).and.callThrough(); const vertexBufferLoader = new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfDraco, gltfResource, baseResource: gltfResource, draco: dracoExtension, attributeSemantic: "POSITION", accessorId: 0, loadBuffer: true }); await vertexBufferLoader.load(); await waitForLoaderProcess_default(vertexBufferLoader, scene2); expect(vertexBufferLoader.buffer).toBeDefined(); expect(vertexBufferLoader.isDestroyed()).toBe(false); vertexBufferLoader.destroy(); expect(vertexBufferLoader.buffer).not.toBeDefined(); expect(vertexBufferLoader.isDestroyed()).toBe(true); expect(unloadDraco).toHaveBeenCalled(); expect(destroyVertexBuffer).toHaveBeenCalled(); }); async function resolveBufferViewAfterDestroy(rejectPromise) { spyOn(import__496.Resource.prototype, "fetchArrayBuffer").and.callFake( () => rejectPromise ? Promise.reject(new Error()) : Promise.resolve(arrayBuffer) ); const vertexBufferLoader = new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfUncompressed, gltfResource, baseResource: gltfResource, bufferViewId: 0, loadBuffer: true }); expect(vertexBufferLoader.buffer).not.toBeDefined(); const promise = vertexBufferLoader.load(); vertexBufferLoader.destroy(); await expectAsync(promise).toBeResolved(); expect(vertexBufferLoader.buffer).not.toBeDefined(); expect(vertexBufferLoader.isDestroyed()).toBe(true); } it("handles resolving buffer view after destroy", function() { return resolveBufferViewAfterDestroy(false); }); it("handles rejecting buffer view after destroy", function() { return resolveBufferViewAfterDestroy(true); }); async function resolveDracoAfterDestroy(rejectPromise) { const vertexBufferLoader = new import__496.GltfVertexBufferLoader({ resourceCache: import__496.ResourceCache, gltf: gltfDraco, gltfResource, baseResource: gltfResource, draco: dracoExtension, attributeSemantic: "POSITION", accessorId: 0, loadBuffer: true }); spyOn(import__496.Resource.prototype, "fetchArrayBuffer").and.callFake(function() { setTimeout(function() { loaderProcess_default(vertexBufferLoader, scene2); vertexBufferLoader.destroy(); }, 1); return Promise.resolve(arrayBuffer); }); const decodeBufferView = spyOn( import__496.DracoLoader, "decodeBufferView" ).and.callFake(function() { return new Promise(function(resolve, reject) { setTimeout(function() { if (rejectPromise) { reject(new Error()); } else { resolve(decodeDracoResults); } }, 1); }); }); expect(vertexBufferLoader.buffer).not.toBeDefined(); await vertexBufferLoader.load(); await expectAsync( waitForLoaderProcess_default(vertexBufferLoader, scene2) ).toBeResolved(); expect(decodeBufferView).toHaveBeenCalled(); expect(vertexBufferLoader.buffer).not.toBeDefined(); expect(vertexBufferLoader.isDestroyed()).toBe(true); } it("handles resolving draco after destroy", function() { return resolveDracoAfterDestroy(false); }); it("handles rejecting draco after destroy", function() { return resolveDracoAfterDestroy(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/GoogleEarthEnterpriseImageryProviderSpec.js var import_urijs6 = __toESM(require_URI(), 1); var import__497 = __toESM(require_Cesium(), 1); describe("Scene/GoogleEarthEnterpriseImageryProvider", function() { beforeEach(function() { import__497.RequestScheduler.clearForSpecs(); }); let supportsImageBitmapOptions; beforeAll(async function() { import__497.decodeGoogleEarthEnterpriseData.passThroughDataForTesting = true; const result = import__497.Resource.supportsImageBitmapOptions(); supportsImageBitmapOptions = result; }); afterAll(function() { import__497.decodeGoogleEarthEnterpriseData.passThroughDataForTesting = false; }); let imageryProvider; afterEach(function() { import__497.Resource._Implementations.createImage = import__497.Resource._DefaultImplementations.createImage; import__497.Resource._Implementations.loadWithXhr = import__497.Resource._DefaultImplementations.loadWithXhr; }); it("conforms to ImageryProvider interface", function() { expect(import__497.GoogleEarthEnterpriseImageryProvider).toConformToInterface( import__497.ImageryProvider ); }); function installMockGetQuadTreePacket() { spyOn( import__497.GoogleEarthEnterpriseMetadata.prototype, "getQuadTreePacket" ).and.callFake(function(quadKey, version) { quadKey = (0, import__497.defaultValue)(quadKey, ""); this._tileInfo[`${quadKey}0`] = new import__497.GoogleEarthEnterpriseTileInformation( 255, 1, 1, 1 ); this._tileInfo[`${quadKey}1`] = new import__497.GoogleEarthEnterpriseTileInformation( 255, 1, 1, 1 ); this._tileInfo[`${quadKey}2`] = new import__497.GoogleEarthEnterpriseTileInformation( 255, 1, 1, 1 ); this._tileInfo[`${quadKey}3`] = new import__497.GoogleEarthEnterpriseTileInformation( 255, 1, 1, 1 ); return Promise.resolve(); }); } function installFakeImageRequest(expectedUrl, proxy) { import__497.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { let url = request.url; if (/^blob:/.test(url) || supportsImageBitmapOptions) { import__497.Resource._DefaultImplementations.createImage( request, crossOrigin, deferred, true, false, true ); } else { if (proxy) { const uri = new import_urijs6.default(url); url = decodeURIComponent(uri.query()); } if ((0, import__497.defined)(expectedUrl)) { expect(url).toEqual(expectedUrl); } import__497.Resource._DefaultImplementations.createImage( new import__497.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); } }; import__497.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { if ((0, import__497.defined)(expectedUrl) && !/^blob:/.test(url)) { if (proxy) { const uri = new import_urijs6.default(url); url = decodeURIComponent(uri.query()); } expect(url).toEqual(expectedUrl); } import__497.Resource._DefaultImplementations.loadWithXhr( "Data/Images/Red16x16.png", responseType, method, data, headers, deferred ); }; } it("fromMetadata throws without metadata", function() { expect( () => import__497.GoogleEarthEnterpriseImageryProvider.fromMetadata() ).toThrowDeveloperError(""); }); it("fromMetadata throws if there isn't imagery", async function() { installMockGetQuadTreePacket(); const metadata = await import__497.GoogleEarthEnterpriseMetadata.fromUrl({ url: "made/up/url" }); metadata.imageryPresent = false; expect( () => import__497.GoogleEarthEnterpriseImageryProvider.fromMetadata(metadata) ).toThrowError( import__497.RuntimeError, "The server made/up/url/ doesn't have imagery" ); }); it("fromMetadata resolves to created provider", async function() { installMockGetQuadTreePacket(); const url = "http://fake.fake.invalid"; const metadata = await import__497.GoogleEarthEnterpriseMetadata.fromUrl(url); imageryProvider = import__497.GoogleEarthEnterpriseImageryProvider.fromMetadata( metadata ); expect(imageryProvider).toBeInstanceOf( import__497.GoogleEarthEnterpriseImageryProvider ); }); it("returns false for hasAlphaChannel", async function() { installMockGetQuadTreePacket(); const url = "http://fake.fake.invalid"; const metadata = await import__497.GoogleEarthEnterpriseMetadata.fromUrl(url); imageryProvider = import__497.GoogleEarthEnterpriseImageryProvider.fromMetadata( metadata ); expect(typeof imageryProvider.hasAlphaChannel).toBe("boolean"); expect(imageryProvider.hasAlphaChannel).toBe(false); }); it("can provide a root tile", async function() { installMockGetQuadTreePacket(); const url = "http://fake.fake.invalid/"; const metadata = await import__497.GoogleEarthEnterpriseMetadata.fromUrl(url); imageryProvider = import__497.GoogleEarthEnterpriseImageryProvider.fromMetadata( metadata ); expect(imageryProvider.url).toEqual(url); expect(imageryProvider.tileWidth).toEqual(256); expect(imageryProvider.tileHeight).toEqual(256); expect(imageryProvider.maximumLevel).toEqual(23); expect(imageryProvider.tilingScheme).toBeInstanceOf(import__497.GeographicTilingScheme); expect(imageryProvider.tileDiscardPolicy).not.toBeInstanceOf( import__497.DiscardMissingTileImagePolicy ); expect(imageryProvider.rectangle).toEqual( new import__497.Rectangle(-Math.PI, -Math.PI, Math.PI, Math.PI) ); expect(imageryProvider.credit).toBeUndefined(); installFakeImageRequest("http://fake.fake.invalid/flatfile?f1-03-i.1"); const image = await imageryProvider.requestImage(0, 0, 0); expect(image).toBeImageOrImageBitmap(); }); it("raises error event when image cannot be loaded", async function() { installMockGetQuadTreePacket(); const url = "http://foo.bar.invalid"; const metadata = await import__497.GoogleEarthEnterpriseMetadata.fromUrl(url); imageryProvider = import__497.GoogleEarthEnterpriseImageryProvider.fromMetadata( metadata ); const layer = new import__497.ImageryLayer(imageryProvider); let tries = 0; imageryProvider.errorEvent.addEventListener(function(error) { expect(error.timesRetried).toEqual(tries); ++tries; if (tries < 3) { error.retry = true; } setTimeout(function() { import__497.RequestScheduler.update(); }, 1); }); import__497.Resource._Implementations.loadWithXhr = function(url2, responseType, method, data, headers, deferred, overrideMimeType) { if (tries === 2) { import__497.Resource._DefaultImplementations.loadWithXhr( "Data/Images/Red16x16.png", responseType, method, data, headers, deferred ); } else { setTimeout(function() { deferred.reject(); }, 1); } }; const imagery = new import__497.Imagery(layer, 0, 0, 0); imagery.addReference(); layer._requestImagery(imagery); import__497.RequestScheduler.update(); return pollToPromise_default(function() { return imagery.state === import__497.ImageryState.RECEIVED; }).then(function() { expect(imagery.image).toBeImageOrImageBitmap(); expect(tries).toEqual(2); imagery.releaseReference(); }); }); }); // packages/engine/Specs/Scene/GoogleEarthEnterpriseMapsProviderSpec.js var import__498 = __toESM(require_Cesium(), 1); describe("Scene/GoogleEarthEnterpriseMapsProvider", function() { let supportsImageBitmapOptions; beforeAll(function() { return import__498.Resource.supportsImageBitmapOptions().then(function(result) { supportsImageBitmapOptions = result; }); }); afterEach(function() { import__498.Resource._Implementations.createImage = import__498.Resource._DefaultImplementations.createImage; import__498.Resource._Implementations.loadWithXhr = import__498.Resource._DefaultImplementations.loadWithXhr; }); it("conforms to ImageryProvider interface", function() { expect(import__498.GoogleEarthEnterpriseMapsProvider).toConformToInterface( import__498.ImageryProvider ); }); it("fromUrl throws without url", async function() { await expectAsync( import__498.GoogleEarthEnterpriseMapsProvider.fromUrl(void 0, 1234) ).toBeRejectedWithDeveloperError(); }); it("fromUrl throws without channel", async function() { await expectAsync( import__498.GoogleEarthEnterpriseMapsProvider.fromUrl("url", void 0) ).toBeRejectedWithDeveloperError(); }); it("fromUrl resolves to imagery provider", async function() { const path = ""; const url = "http://example.invalid"; const channel = 1234; import__498.Resource._Implementations.loadWithXhr = function(url2, responseType, method, data, headers, deferred, overrideMimeType) { import__498.Resource._DefaultImplementations.loadWithXhr( "Data/GoogleEarthEnterpriseMapsProvider/good.json", responseType, method, data, headers, deferred ); }; const provider = await import__498.GoogleEarthEnterpriseMapsProvider.fromUrl( url, channel, { path } ); expect(provider).toBeInstanceOf(import__498.GoogleEarthEnterpriseMapsProvider); }); it("fromUrl with Resource resolves to imagery provider", async function() { const path = ""; const url = "http://example.invalid"; const channel = 1234; import__498.Resource._Implementations.loadWithXhr = function(url2, responseType, method, data, headers, deferred, overrideMimeType) { import__498.Resource._DefaultImplementations.loadWithXhr( "Data/GoogleEarthEnterpriseMapsProvider/good.json", responseType, method, data, headers, deferred ); }; const resource = new import__498.Resource({ url }); const provider = await import__498.GoogleEarthEnterpriseMapsProvider.fromUrl( resource, channel, { path } ); expect(provider).toBeInstanceOf(import__498.GoogleEarthEnterpriseMapsProvider); }); it("fromUrl throws with invalid url", async function() { const url = "http://invalid.localhost"; await expectAsync( import__498.GoogleEarthEnterpriseMapsProvider.fromUrl(url, 1234) ).toBeRejectedWithError( import__498.RuntimeError, new RegExp("An error occurred while accessing") ); }); it("fromUrl throws when channel cannot be found", async function() { import__498.Resource._Implementations.loadWithXhr = function(url2, responseType, method, data, headers, deferred, overrideMimeType) { import__498.Resource._DefaultImplementations.loadWithXhr( "Data/GoogleEarthEnterpriseMapsProvider/bad_channel.json", responseType, method, data, headers, deferred ); }; const url = "http://invalid.localhost"; await expectAsync( import__498.GoogleEarthEnterpriseMapsProvider.fromUrl(url, 1235) ).toBeRejectedWithError( import__498.RuntimeError, new RegExp("Could not find layer with channel \\(id\\) of 1235") ); }); it("fromUrl throws when channel version cannot be found", async function() { import__498.Resource._Implementations.loadWithXhr = function(url2, responseType, method, data, headers, deferred, overrideMimeType) { import__498.Resource._DefaultImplementations.loadWithXhr( "Data/GoogleEarthEnterpriseMapsProvider/bad_version.json", responseType, method, data, headers, deferred ); }; const url = "http://invalid.localhost"; await expectAsync( import__498.GoogleEarthEnterpriseMapsProvider.fromUrl(url, 1234) ).toBeRejectedWithError( import__498.RuntimeError, new RegExp("Could not find a version in channel \\(id\\) 1234") ); }); it("fromUrl throws when unsupported projection is specified", async function() { import__498.Resource._Implementations.loadWithXhr = function(url2, responseType, method, data, headers, deferred, overrideMimeType) { import__498.Resource._DefaultImplementations.loadWithXhr( "Data/GoogleEarthEnterpriseMapsProvider/bad_projection.json", responseType, method, data, headers, deferred ); }; const url = "http://invalid.localhost"; await expectAsync( import__498.GoogleEarthEnterpriseMapsProvider.fromUrl(url, 1234) ).toBeRejectedWithError( import__498.RuntimeError, new RegExp("Unsupported projection asdf") ); }); it("returns valid value for hasAlphaChannel", async function() { const path = ""; const url = "http://example.invalid"; const channel = 1234; import__498.Resource._Implementations.loadWithXhr = function(url2, responseType, method, data, headers, deferred, overrideMimeType) { import__498.Resource._DefaultImplementations.loadWithXhr( "Data/GoogleEarthEnterpriseMapsProvider/good.json", responseType, method, data, headers, deferred ); }; const provider = await import__498.GoogleEarthEnterpriseMapsProvider.fromUrl( url, channel, { path } ); expect(typeof provider.hasAlphaChannel).toBe("boolean"); }); it("can provide a root tile", async function() { const path = ""; const url = "http://example.invalid"; const channel = 1234; const version = 1; import__498.Resource._Implementations.loadWithXhr = function(url2, responseType, method, data, headers, deferred, overrideMimeType) { import__498.Resource._DefaultImplementations.loadWithXhr( "Data/GoogleEarthEnterpriseMapsProvider/good.json", responseType, method, data, headers, deferred ); }; const provider = await import__498.GoogleEarthEnterpriseMapsProvider.fromUrl( url, channel, { path } ); expect(provider.url).toEqual(url); expect(provider.path).toEqual(path); expect(provider.channel).toEqual(channel); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.minimumLevel).toEqual(0); expect(provider.version).toEqual(version); expect(provider.tilingScheme).toBeInstanceOf(import__498.WebMercatorTilingScheme); expect(provider.tileDiscardPolicy).toBeUndefined(); expect(provider.rectangle).toEqual(new import__498.WebMercatorTilingScheme().rectangle); expect(provider.credit).toBeInstanceOf(Object); import__498.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { const url2 = request.url; if (/^blob:/.test(url2) || supportsImageBitmapOptions) { import__498.Resource._DefaultImplementations.createImage( request, crossOrigin, deferred, true, false, true ); } else { expect(url2).toEqual( "http://example.invalid/query?request=ImageryMaps&channel=1234&version=1&x=0&y=0&z=1" ); import__498.Resource._DefaultImplementations.createImage( new import__498.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); } }; import__498.Resource._Implementations.loadWithXhr = function(url2, responseType, method, data, headers, deferred, overrideMimeType) { expect(url2).toEqual( "http://example.invalid/query?request=ImageryMaps&channel=1234&version=1&x=0&y=0&z=1" ); import__498.Resource._DefaultImplementations.loadWithXhr( "Data/Images/Red16x16.png", responseType, method, data, headers, deferred ); }; return provider.requestImage(0, 0, 0).then(function(image) { expect(image).toBeImageOrImageBitmap(); }); }); it("handles malformed JSON data returned by the server", async function() { const path = "/default_map"; const url = "http://example.invalid"; const version = 1; const channel = 1234; import__498.Resource._Implementations.loadWithXhr = function(url2, responseType, method, data, headers, deferred, overrideMimeType) { return deferred.resolve( '{\nisAuthenticated: true,\nlayers: [\n {\n icon: "icons/773_l.png",\n id: 1234,\n initialState: true,\n label: "Imagery",\n lookAt: "none",\n requestType: "ImageryMaps",\n version: 1\n },{\n icon: "icons/773_l.png",\n id: 1007,\n initialState: true,\n label: "Labels",\n lookAt: "none",\n requestType: "VectorMapsRaster",\n version: 8\n }\n],\nserverUrl: "https://example.invalid",\nuseGoogleLayers: false\n}' ); }; const provider = await import__498.GoogleEarthEnterpriseMapsProvider.fromUrl( url, channel ); expect(provider.url).toEqual(url); expect(provider.path).toEqual(path); expect(provider.version).toEqual(version); expect(provider.channel).toEqual(channel); }); it("defaults to WebMercatorTilingScheme when no projection specified", async function() { import__498.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { return deferred.resolve( JSON.stringify({ isAuthenticated: true, layers: [ { icon: "icons/773_l.png", id: 1234, initialState: true, label: "Imagery", requestType: "ImageryMaps", version: 1 } ], serverUrl: "https://example.invalid", useGoogleLayers: false }) ); }; const provider = await import__498.GoogleEarthEnterpriseMapsProvider.fromUrl( "http://example.invalid", 1234 ); expect(provider.tilingScheme).toBeInstanceOf(import__498.WebMercatorTilingScheme); expect(provider.rectangle).toEqual(new import__498.WebMercatorTilingScheme().rectangle); }); it("Projection is WebMercatorTilingScheme when server projection is mercator", async function() { import__498.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { return deferred.resolve( JSON.stringify({ isAuthenticated: true, layers: [ { icon: "icons/773_l.png", id: 1234, initialState: true, label: "Imagery", requestType: "ImageryMaps", version: 1 } ], projection: "mercator", serverUrl: "https://example.invalid", useGoogleLayers: false }) ); }; const provider = await import__498.GoogleEarthEnterpriseMapsProvider.fromUrl( "http://example.invalid", 1234 ); expect(provider.tilingScheme).toBeInstanceOf(import__498.WebMercatorTilingScheme); expect(provider.rectangle).toEqual(new import__498.WebMercatorTilingScheme().rectangle); }); it("Projection is GeographicTilingScheme when server projection is flat", async function() { import__498.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { return deferred.resolve( JSON.stringify({ isAuthenticated: true, layers: [ { icon: "icons/773_l.png", id: 1234, initialState: true, label: "Imagery", requestType: "ImageryMaps", version: 1 } ], projection: "flat", serverUrl: "https://example.invalid", useGoogleLayers: false }) ); }; const provider = await import__498.GoogleEarthEnterpriseMapsProvider.fromUrl( "http://example.invalid", 1234 ); expect(provider.tilingScheme).toBeInstanceOf(import__498.GeographicTilingScheme); expect(provider.rectangle).toEqual( new import__498.Rectangle(-Math.PI, -Math.PI, Math.PI, Math.PI) ); }); }); // packages/engine/Specs/Scene/GridImageryProviderSpec.js var import__499 = __toESM(require_Cesium(), 1); describe("Scene/GridImageryProvider", function() { it("conforms to ImageryProvider interface", function() { expect(import__499.GridImageryProvider).toConformToInterface(import__499.ImageryProvider); }); it("returns valid value for hasAlphaChannel", function() { const provider = new import__499.GridImageryProvider(); expect(typeof provider.hasAlphaChannel).toBe("boolean"); }); it("can use a custom ellipsoid", function() { const ellipsoid = new import__499.Ellipsoid(1, 2, 3); const provider = new import__499.GridImageryProvider({ ellipsoid }); expect(provider.tilingScheme.ellipsoid).toEqual(ellipsoid); }); it("can provide a root tile", function() { const provider = new import__499.GridImageryProvider(); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__499.GeographicTilingScheme); expect(provider.tileDiscardPolicy).toBeUndefined(); expect(provider.rectangle).toEqual(new import__499.GeographicTilingScheme().rectangle); return Promise.resolve(provider.requestImage(0, 0, 0)).then(function(image) { expect(image).toBeDefined(); }); }); it("uses alternate tiling scheme if provided", function() { const tilingScheme = new import__499.WebMercatorTilingScheme(); const provider = new import__499.GridImageryProvider({ tilingScheme }); expect(provider.tilingScheme).toBe(tilingScheme); }); it("uses tile width and height if provided", function() { const provider = new import__499.GridImageryProvider({ tileWidth: 123, tileHeight: 456 }); expect(provider.tileWidth).toEqual(123); expect(provider.tileHeight).toEqual(456); }); }); // packages/engine/Specs/Scene/GroundPolylinePrimitiveSpec.js var import__500 = __toESM(require_Cesium(), 1); var import__501 = __toESM(require_Cesium(), 1); describe( "Scene/GroundPolylinePrimitive", function() { let scene2; let context; let ellipsoid; let depthColor; let polylineColor; let polylineColorAttribute; let groundPolylineInstance; let groundPolylinePrimitive; let depthRectanglePrimitive; const positions = import__500.Cartesian3.fromDegreesArray([0.01, 0, 0.03, 0]); const lookPosition = import__500.Cartesian3.fromDegrees(0.02, 0); const lookPositionOffset = import__500.Cartesian3.fromDegrees(0.02, 1e-4); const canvasWidth = 4; const canvasHeight = 4; beforeAll(function() { const canvas = createCanvas_default(canvasWidth, canvasHeight); scene2 = createScene_default({ canvas }); scene2.postProcessStages.fxaa.enabled = false; context = scene2.context; ellipsoid = import__500.Ellipsoid.WGS84; return import__500.GroundPolylinePrimitive.initializeTerrainHeights(); }); afterAll(function() { scene2.destroyForSpecs(); import__500.ApproximateTerrainHeights._initPromise = void 0; import__500.ApproximateTerrainHeights._terrainHeights = void 0; }); function MockGlobePrimitive(primitive) { this._primitive = primitive; this.pass = import__500.Pass.GLOBE; } MockGlobePrimitive.prototype.update = function(frameState2) { const commandList = frameState2.commandList; const startLength = commandList.length; this._primitive.update(frameState2); for (let i = startLength; i < commandList.length; ++i) { const command = commandList[i]; command.pass = this.pass; } }; MockGlobePrimitive.prototype.isDestroyed = function() { return false; }; MockGlobePrimitive.prototype.destroy = function() { this._primitive.destroy(); return (0, import__500.destroyObject)(this); }; beforeEach(function() { scene2.morphTo3D(0); scene2.camera.frustum.near = 0.1; scene2.camera.frustum.far = 1e10; const depthpolylineColorAttribute = import__500.ColorGeometryInstanceAttribute.fromColor( new import__500.Color(0, 0, 1, 1) ); depthColor = depthpolylineColorAttribute.value; const primitive = new import__500.Primitive({ geometryInstances: new import__500.GeometryInstance({ geometry: new import__500.RectangleGeometry({ ellipsoid, rectangle: import__500.Rectangle.fromDegrees(-1, -1, 1, 1) }), id: "depth rectangle", attributes: { color: depthpolylineColorAttribute } }), appearance: new import__500.PerInstanceColorAppearance({ translucent: false, flat: true }), asynchronous: false }); depthRectanglePrimitive = new MockGlobePrimitive(primitive); polylineColorAttribute = import__500.ColorGeometryInstanceAttribute.fromColor( new import__500.Color(0, 1, 1, 1) ); polylineColor = polylineColorAttribute.value; groundPolylineInstance = new import__500.GeometryInstance({ geometry: new import__500.GroundPolylineGeometry({ positions, granularity: 0, width: 1, loop: false, ellipsoid }), id: "polyline on terrain", attributes: { color: polylineColorAttribute } }); }); afterEach(function() { scene2.groundPrimitives.removeAll(); groundPolylinePrimitive = groundPolylinePrimitive && !groundPolylinePrimitive.isDestroyed() && groundPolylinePrimitive.destroy(); depthRectanglePrimitive = depthRectanglePrimitive && !depthRectanglePrimitive.isDestroyed() && depthRectanglePrimitive.destroy(); }); it("default constructs", function() { groundPolylinePrimitive = new import__500.GroundPolylinePrimitive(); expect(groundPolylinePrimitive.geometryInstances).not.toBeDefined(); expect(groundPolylinePrimitive.appearance).toBeInstanceOf( import__500.PolylineMaterialAppearance ); expect(groundPolylinePrimitive.show).toEqual(true); expect(groundPolylinePrimitive.interleave).toEqual(false); expect(groundPolylinePrimitive.releaseGeometryInstances).toEqual(true); expect(groundPolylinePrimitive.allowPicking).toEqual(true); expect(groundPolylinePrimitive.asynchronous).toEqual(true); expect(groundPolylinePrimitive.debugShowBoundingVolume).toEqual(false); expect(groundPolylinePrimitive.debugShowShadowVolume).toEqual(false); }); it("constructs with options", function() { const geometryInstances = []; groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances, show: false, interleave: true, releaseGeometryInstances: false, allowPicking: false, asynchronous: false, debugShowBoundingVolume: true, debugShowShadowVolume: true }); expect(groundPolylinePrimitive.geometryInstances).toEqual( geometryInstances ); expect(groundPolylinePrimitive.show).toEqual(false); expect(groundPolylinePrimitive.interleave).toEqual(true); expect(groundPolylinePrimitive.releaseGeometryInstances).toEqual(false); expect(groundPolylinePrimitive.allowPicking).toEqual(false); expect(groundPolylinePrimitive.asynchronous).toEqual(false); expect(groundPolylinePrimitive.debugShowBoundingVolume).toEqual(true); expect(groundPolylinePrimitive.debugShowShadowVolume).toEqual(true); }); it("releases geometry instances when releaseGeometryInstances is true", async function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, releaseGeometryInstances: true, asynchronous: false }); expect(groundPolylinePrimitive.geometryInstances).toBeDefined(); scene2.groundPrimitives.add(groundPolylinePrimitive); await pollToPromise_default(() => { scene2.renderForSpecs(); return groundPolylinePrimitive.ready; }); expect(groundPolylinePrimitive.geometryInstances).not.toBeDefined(); }); it("does not release geometry instances when releaseGeometryInstances is false", async function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, releaseGeometryInstances: false, asynchronous: false }); expect(groundPolylinePrimitive.geometryInstances).toBeDefined(); scene2.groundPrimitives.add(groundPolylinePrimitive); await pollToPromise_default(() => { scene2.renderForSpecs(); return groundPolylinePrimitive.ready; }); expect(groundPolylinePrimitive.geometryInstances).toBeDefined(); }); it("becomes ready", async function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, releaseGeometryInstances: false, asynchronous: false }); scene2.groundPrimitives.add(groundPolylinePrimitive); await pollToPromise_default(() => { scene2.renderForSpecs(); return groundPolylinePrimitive.ready; }); expect(groundPolylinePrimitive.ready).toBe(true); }); it("does not render when geometryInstances is undefined", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: void 0, asynchronous: false }); scene2.groundPrimitives.add(groundPolylinePrimitive); scene2.renderForSpecs(); expect(scene2.frameState.commandList.length).toEqual(0); }); it("does not render when show is false", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false }); scene2.groundPrimitives.add(groundPolylinePrimitive); scene2.renderForSpecs(); expect(scene2.frameState.commandList.length).toBeGreaterThan(0); groundPolylinePrimitive.show = false; scene2.renderForSpecs(); expect(scene2.frameState.commandList.length).toEqual(0); }); it("becomes ready when show is false", async function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = scene2.groundPrimitives.add( new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance }) ); groundPolylinePrimitive.show = false; await pollToPromise_default(() => { scene2.renderForSpecs(); return groundPolylinePrimitive.ready; }); expect(groundPolylinePrimitive.ready).toBeTrue(); }); it("does not render other than for the color or pick pass", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false }); const frameState2 = scene2.frameState; frameState2.passes.render = false; frameState2.passes.pick = false; groundPolylinePrimitive.update(frameState2); expect(frameState2.commandList.length).toEqual(0); }); function coordinateOfPixelColor(rgba, color) { for (let y = 0; y < canvasHeight; y++) { for (let x = 0; x < canvasWidth; x++) { const i = (y * canvasWidth + x) * 4; if (color[0] === rgba[i] && color[1] === rgba[i + 1] && color[2] === rgba[i + 2] && color[3] === rgba[i + 3]) { return new import__500.Cartesian2(x, canvasHeight - y); } } } } function verifyGroundPolylinePrimitiveRender(lookPosition2, primitive, color) { scene2.camera.lookAt(lookPosition2, import__500.Cartesian3.UNIT_Z); scene2.groundPrimitives.add(depthRectanglePrimitive); expect(scene2).toRenderAndCall(function(rgba) { expect(coordinateOfPixelColor(rgba, depthColor)).toBeDefined(); }); scene2.groundPrimitives.add(primitive); let coordinate; expect(scene2).toRenderAndCall(function(rgba) { coordinate = coordinateOfPixelColor(rgba, color); expect(coordinate).toBeDefined(); }); return coordinate; } it("renders in 3D", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false, appearance: new import__500.PolylineColorAppearance() }); verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, polylineColor ); }); it("renders in Columbus view when scene3DOnly is false", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false, appearance: new import__500.PolylineColorAppearance() }); scene2.morphToColumbusView(0); verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, polylineColor ); }); it("renders in 2D when scene3DOnly is false", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false, appearance: new import__500.PolylineColorAppearance() }); scene2.morphTo2D(0); verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, polylineColor ); }); it("renders during morph when scene3DOnly is false", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: new import__500.GeometryInstance({ geometry: new import__500.GroundPolylineGeometry({ positions: import__500.Cartesian3.fromDegreesArray([-30, 0, 30, 0]), granularity: 0, width: 1e3, loop: false, ellipsoid }), attributes: { color: polylineColorAttribute } }), asynchronous: false, appearance: new import__500.PolylineColorAppearance() }); scene2.groundPrimitives.add(depthRectanglePrimitive); scene2.groundPrimitives.add(groundPolylinePrimitive); scene2.morphTo2D(0); scene2.renderForSpecs(); scene2.morphToColumbusView(1); expect(scene2).toRenderAndCall(function(rgba) { expect(coordinateOfPixelColor(rgba, polylineColor)).toBeDefined(); }); scene2.completeMorph(); }); it("renders batched instances", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } const instance1 = new import__500.GeometryInstance({ geometry: new import__500.GroundPolylineGeometry({ positions, granularity: 0, width: 1, loop: false, ellipsoid }), id: "polyline on terrain", attributes: { color: import__500.ColorGeometryInstanceAttribute.fromColor( new import__500.Color(1, 1, 1, 0.5) ) } }); const instance2 = new import__500.GeometryInstance({ geometry: new import__500.GroundPolylineGeometry({ positions, granularity: 0, width: 1, loop: false, ellipsoid }), id: "polyline on terrain", attributes: { color: import__500.ColorGeometryInstanceAttribute.fromColor( new import__500.Color(1, 1, 1, 0.5) ) } }); groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: [instance1, instance2], asynchronous: false, appearance: new import__500.PolylineColorAppearance() }); verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, [192, 192, 255, 255] ); }); it("renders bounding volume with debugShowBoundingVolume", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false, appearance: new import__500.PolylineColorAppearance(), debugShowBoundingVolume: true }); scene2.groundPrimitives.add(groundPolylinePrimitive); scene2.camera.lookAt(lookPosition, import__500.Cartesian3.UNIT_Z); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[1]).toBeGreaterThanOrEqual(0); expect(rgba[1]).toBeGreaterThanOrEqual(0); expect(rgba[2]).toBeGreaterThanOrEqual(0); expect(rgba[3]).toEqual(255); }); }); it("renders shadow volume with debugShowShadowVolume", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false, appearance: new import__500.PolylineColorAppearance(), debugShowShadowVolume: true }); scene2.groundPrimitives.add(groundPolylinePrimitive); scene2.camera.lookAt(lookPosition, import__500.Cartesian3.UNIT_Z); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[1]).toBeGreaterThanOrEqual(0); expect(rgba[1]).toBeGreaterThanOrEqual(0); expect(rgba[2]).toBeGreaterThanOrEqual(0); expect(rgba[3]).toEqual(255); }); }); it("get per instance attributes", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false, appearance: new import__500.PolylineColorAppearance() }); verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, polylineColor ); const attributes = groundPolylinePrimitive.getGeometryInstanceAttributes( "polyline on terrain" ); expect(attributes.color).toBeDefined(); }); it("modify color instance attribute", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false, appearance: new import__500.PolylineColorAppearance() }); verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, polylineColor ); scene2.groundPrimitives.destroyPrimitives = false; scene2.groundPrimitives.removeAll(); scene2.groundPrimitives.destroyPrimitives = true; const newColor = [255, 255, 255, 255]; const attributes = groundPolylinePrimitive.getGeometryInstanceAttributes( "polyline on terrain" ); expect(attributes.color).toBeDefined(); attributes.color = newColor; verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, newColor ); }); it("adds width instance attribute", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false, appearance: new import__500.PolylineColorAppearance() }); verifyGroundPolylinePrimitiveRender( lookPositionOffset, groundPolylinePrimitive, polylineColor ); scene2.groundPrimitives.destroyPrimitives = false; scene2.groundPrimitives.removeAll(); scene2.groundPrimitives.destroyPrimitives = true; const attributes = groundPolylinePrimitive.getGeometryInstanceAttributes( "polyline on terrain" ); expect(attributes.width).toBeDefined(); attributes.width = [0]; verifyGroundPolylinePrimitiveRender( lookPositionOffset, groundPolylinePrimitive, depthColor ); }); it("modify show instance attribute", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylineInstance.attributes.show = new import__500.ShowGeometryInstanceAttribute( true ); groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false, appearance: new import__500.PolylineColorAppearance() }); verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, polylineColor ); scene2.groundPrimitives.destroyPrimitives = false; scene2.groundPrimitives.removeAll(); scene2.groundPrimitives.destroyPrimitives = true; const attributes = groundPolylinePrimitive.getGeometryInstanceAttributes( "polyline on terrain" ); expect(attributes.show).toBeDefined(); attributes.show = [0]; verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, depthColor ); }); xit("renders with distance display condition per instance attribute", function() { if (!context.floatingPointTexture) { return; } if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } const near = 10; const far = 1e3; const geometryInstance = new import__500.GeometryInstance({ geometry: new import__500.GroundPolylineGeometry({ positions, granularity: 0, width: 1e3, loop: false, ellipsoid }), id: "polyline on terrain", attributes: { distanceDisplayCondition: new import__500.DistanceDisplayConditionGeometryInstanceAttribute( near, far ), color: polylineColorAttribute } }); groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: geometryInstance, asynchronous: false }); scene2.groundPrimitives.add(depthRectanglePrimitive); scene2.groundPrimitives.add(groundPolylinePrimitive); scene2.camera.lookAt(lookPosition, import__500.Cartesian3.UNIT_Z); scene2.renderForSpecs(); const boundingSphere = groundPolylinePrimitive.getGeometryInstanceAttributes( "polyline on terrain" ).boundingSphere; const center = boundingSphere.center; const radius = boundingSphere.radius; scene2.camera.lookAt( center, new import__500.HeadingPitchRange(0, -import__501.Math.PI_OVER_TWO, radius) ); expect(scene2).toRenderAndCall(function(rgba) { expect(coordinateOfPixelColor(rgba, depthColor)).toBeDefined(); }); scene2.camera.lookAt( center, new import__500.HeadingPitchRange(0, -import__501.Math.PI_OVER_TWO, radius + near + 1) ); expect(scene2).toRenderAndCall(function(rgba) { expect(coordinateOfPixelColor(rgba, depthColor)).toBeUndefined(); }); scene2.camera.lookAt( center, new import__500.HeadingPitchRange(0, -import__501.Math.PI_OVER_TWO, radius + far + 1) ); expect(scene2).toRenderAndCall(function(rgba) { expect(coordinateOfPixelColor(rgba, depthColor)).toBeDefined(); }); }); it("getGeometryInstanceAttributes returns same object each time", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylineInstance.attributes.show = new import__500.ShowGeometryInstanceAttribute( true ); groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false, appearance: new import__500.PolylineColorAppearance() }); verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, polylineColor ); const attributes = groundPolylinePrimitive.getGeometryInstanceAttributes( "polyline on terrain" ); const attributes2 = groundPolylinePrimitive.getGeometryInstanceAttributes( "polyline on terrain" ); expect(attributes).toBe(attributes2); }); it("picking in 3D", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false, appearance: new import__500.PolylineColorAppearance() }); const polylineColorCoordinate = verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, polylineColor ); expect(scene2).toPickAndCall(function(result) { expect(result.id).toEqual("polyline on terrain"); }, polylineColorCoordinate); }); it("picking in 2D", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false, appearance: new import__500.PolylineColorAppearance() }); scene2.morphTo2D(0); const polylineColorCoordinate = verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, polylineColor ); expect(scene2).toPickAndCall(function(result) { expect(result.id).toEqual("polyline on terrain"); }, polylineColorCoordinate); }); it("picking in Columbus View", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false, appearance: new import__500.PolylineColorAppearance() }); scene2.morphToColumbusView(0); const polylineColorCoordinate = verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, polylineColor ); scene2.camera.lookAt(lookPosition, import__500.Cartesian3.UNIT_Z); expect(scene2).toPickAndCall(function(result) { expect(result.id).toEqual("polyline on terrain"); }, polylineColorCoordinate); }); it("picking in Morph", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: new import__500.GeometryInstance({ geometry: new import__500.GroundPolylineGeometry({ positions: import__500.Cartesian3.fromDegreesArray([-30, 0, 30, 0]), granularity: 0, width: 1e3, loop: false, ellipsoid }), attributes: { color: polylineColorAttribute }, id: "big polyline on terrain" }), asynchronous: false, appearance: new import__500.PolylineColorAppearance() }); scene2.morphTo2D(0); scene2.renderForSpecs(); scene2.morphToColumbusView(1); scene2.groundPrimitives.add(depthRectanglePrimitive); scene2.groundPrimitives.add(groundPolylinePrimitive); let polylineColorCoordinate; expect(scene2).toRenderAndCall(function(rgba) { polylineColorCoordinate = coordinateOfPixelColor(rgba, polylineColor); }); scene2.renderForSpecs(); expect(scene2).toPickAndCall(function(result) { expect(result.id).toEqual("big polyline on terrain"); }, polylineColorCoordinate); scene2.completeMorph(); }); it("does not pick when allowPicking is false", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false, allowPicking: false, appearance: new import__500.PolylineColorAppearance() }); verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, polylineColor ); expect(scene2).toPickAndCall(function(result) { expect(result.id).toEqual("depth rectangle"); }); }); it("update throws when batched instance colors are missing", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: new import__500.GeometryInstance({ geometry: new import__500.GroundPolylineGeometry({ positions }) }), appearance: new import__500.PolylineColorAppearance(), asynchronous: false }); expect(function() { verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, polylineColor ); }).toThrowDeveloperError(); }); it("setting per instance attribute throws when value is undefined", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false, appearance: new import__500.PolylineColorAppearance() }); verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, polylineColor ); const attributes = groundPolylinePrimitive.getGeometryInstanceAttributes( "polyline on terrain" ); expect(function() { attributes.color = void 0; }).toThrowDeveloperError(); }); it("can disable picking when asynchronous", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: true, allowPicking: false, appearance: new import__500.PolylineColorAppearance() }); scene2.groundPrimitives.add(groundPolylinePrimitive); return pollToPromise_default(function() { scene2.renderForSpecs(); return groundPolylinePrimitive.ready; }).then(function() { const attributes = groundPolylinePrimitive.getGeometryInstanceAttributes( "polyline on terrain" ); expect(function() { attributes.color = void 0; }).toThrowDeveloperError(); }); }); it("getGeometryInstanceAttributes throws without id", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false, appearance: new import__500.PolylineColorAppearance() }); verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, polylineColor ); expect(function() { groundPolylinePrimitive.getGeometryInstanceAttributes(); }).toThrowDeveloperError(); }); it("getGeometryInstanceAttributes returns undefined if id does not exist", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false, appearance: new import__500.PolylineColorAppearance() }); expect(function() { groundPolylinePrimitive.getGeometryInstanceAttributes("unknown"); }).toThrowDeveloperError(); }); it("isDestroyed", function() { groundPolylinePrimitive = new import__500.GroundPolylinePrimitive(); expect(groundPolylinePrimitive.isDestroyed()).toEqual(false); groundPolylinePrimitive.destroy(); expect(groundPolylinePrimitive.isDestroyed()).toEqual(true); }); it("renders when using asynchronous pipeline", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: true, appearance: new import__500.PolylineColorAppearance() }); scene2.groundPrimitives.add(groundPolylinePrimitive); return pollToPromise_default(function() { scene2.renderForSpecs(); return groundPolylinePrimitive.ready; }).then(function() { scene2.groundPrimitives.destroyPrimitives = false; scene2.groundPrimitives.removeAll(); scene2.groundPrimitives.destroyPrimitives = true; verifyGroundPolylinePrimitiveRender( lookPosition, groundPolylinePrimitive, polylineColor ); }); }); it("destroy before asynchronous pipeline is complete", function() { if (!import__500.GroundPolylinePrimitive.isSupported(scene2)) { return; } groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: true, appearance: new import__500.PolylineColorAppearance() }); scene2.groundPrimitives.add(groundPolylinePrimitive); scene2.renderForSpecs(); groundPolylinePrimitive.destroy(); expect(groundPolylinePrimitive.isDestroyed()).toEqual(true); scene2.groundPrimitives.destroyPrimitives = false; scene2.groundPrimitives.removeAll(); scene2.groundPrimitives.destroyPrimitives = true; }); it("creating a synchronous primitive throws if initializeTerrainHeights wasn't called", function() { const initPromise = import__500.ApproximateTerrainHeights._initPromise; const terrainHeights = import__500.ApproximateTerrainHeights._terrainHeights; import__500.ApproximateTerrainHeights._initPromise = void 0; import__500.ApproximateTerrainHeights._terrainHeights = void 0; groundPolylinePrimitive = new import__500.GroundPolylinePrimitive({ geometryInstances: groundPolylineInstance, asynchronous: false }); scene2.groundPrimitives.add(groundPolylinePrimitive); if (import__500.GroundPolylinePrimitive.isSupported(scene2)) { expect(function() { scene2.renderForSpecs(); }).toThrowDeveloperError(); } import__500.ApproximateTerrainHeights._initPromise = initPromise; import__500.ApproximateTerrainHeights._terrainHeights = terrainHeights; }); }, "WebGL" ); // packages/engine/Specs/Scene/GroundPrimitiveSpec.js var import__502 = __toESM(require_Cesium(), 1); var import__503 = __toESM(require_Cesium(), 1); describe( "Scene/GroundPrimitive", function() { let scene2; let context; let ellipsoid; let rectangle; let depthColor; let rectColor; let rectangleInstance; let primitive; let globePrimitive; let tilesetPrimitive; let reusableGlobePrimitive; let reusableTilesetPrimitive; function createPrimitive(rectangle2, pass) { let renderState; if (pass === import__502.Pass.CESIUM_3D_TILE) { renderState = import__502.RenderState.fromCache({ stencilTest: import__502.StencilConstants.setCesium3DTileBit(), stencilMask: import__502.StencilConstants.CESIUM_3D_TILE_MASK, depthTest: { enabled: true } }); } const depthColorAttribute = import__502.ColorGeometryInstanceAttribute.fromColor( new import__502.Color(0, 0, 1, 1) ); depthColor = depthColorAttribute.value; return new import__502.Primitive({ geometryInstances: new import__502.GeometryInstance({ geometry: new import__502.RectangleGeometry({ ellipsoid: import__502.Ellipsoid.WGS84, rectangle: rectangle2 }), id: "depth rectangle", attributes: { color: depthColorAttribute } }), appearance: new import__502.PerInstanceColorAppearance({ translucent: false, flat: true, renderState }), asynchronous: false }); } function MockPrimitive(primitive2, pass) { this._primitive = primitive2; this._pass = pass; this.show = true; } MockPrimitive.prototype.update = function(frameState2) { if (!this.show) { return; } const commandList = frameState2.commandList; const startLength = commandList.length; this._primitive.update(frameState2); for (let i = startLength; i < commandList.length; ++i) { const command = commandList[i]; command.pass = this._pass; } }; MockPrimitive.prototype.isDestroyed = function() { return false; }; MockPrimitive.prototype.destroy = function() { return (0, import__502.destroyObject)(this); }; beforeAll(function() { scene2 = createScene_default(); scene2.postProcessStages.fxaa.enabled = false; context = scene2.context; ellipsoid = import__502.Ellipsoid.WGS84; const bigRectangle = import__502.Rectangle.fromDegrees( -180 + import__503.Math.EPSILON4, -90 + import__503.Math.EPSILON4, 180 - import__503.Math.EPSILON4, 90 - import__503.Math.EPSILON4 ); reusableGlobePrimitive = createPrimitive(bigRectangle, import__502.Pass.GLOBE); reusableTilesetPrimitive = createPrimitive( bigRectangle, import__502.Pass.CESIUM_3D_TILE ); return import__502.GroundPrimitive.initializeTerrainHeights(); }); afterAll(function() { reusableGlobePrimitive.destroy(); reusableTilesetPrimitive.destroy(); scene2.destroyForSpecs(); import__502.ApproximateTerrainHeights._initPromise = void 0; import__502.ApproximateTerrainHeights._terrainHeights = void 0; }); beforeEach(function() { scene2.morphTo3D(0); rectangle = import__502.Rectangle.fromDegrees(-80, 20, -70, 30); globePrimitive = new MockPrimitive(reusableGlobePrimitive, import__502.Pass.GLOBE); tilesetPrimitive = new MockPrimitive( reusableTilesetPrimitive, import__502.Pass.CESIUM_3D_TILE ); const rectColorAttribute = import__502.ColorGeometryInstanceAttribute.fromColor( new import__502.Color(1, 1, 0, 1) ); rectColor = rectColorAttribute.value; rectangleInstance = new import__502.GeometryInstance({ geometry: new import__502.RectangleGeometry({ ellipsoid, rectangle }), id: "rectangle", attributes: { color: rectColorAttribute } }); }); afterEach(function() { scene2.primitives.removeAll(); scene2.groundPrimitives.removeAll(); primitive = primitive && !primitive.isDestroyed() && primitive.destroy(); globePrimitive = globePrimitive && !globePrimitive.isDestroyed() && globePrimitive.destroy(); tilesetPrimitive = tilesetPrimitive && !tilesetPrimitive.isDestroyed() && tilesetPrimitive.destroy(); }); it("default constructs", function() { primitive = new import__502.GroundPrimitive(); expect(primitive.geometryInstances).not.toBeDefined(); expect(primitive.show).toEqual(true); expect(primitive.vertexCacheOptimize).toEqual(false); expect(primitive.interleave).toEqual(false); expect(primitive.compressVertices).toEqual(true); expect(primitive.releaseGeometryInstances).toEqual(true); expect(primitive.allowPicking).toEqual(true); expect(primitive.asynchronous).toEqual(true); expect(primitive.debugShowBoundingVolume).toEqual(false); expect(primitive.debugShowShadowVolume).toEqual(false); }); it("constructs with options", function() { const geometryInstances = []; primitive = new import__502.GroundPrimitive({ geometryInstances, show: false, vertexCacheOptimize: true, interleave: true, compressVertices: false, releaseGeometryInstances: false, allowPicking: false, asynchronous: false, debugShowBoundingVolume: true, debugShowShadowVolume: true }); expect(primitive.geometryInstances).toEqual(geometryInstances); expect(primitive.show).toEqual(false); expect(primitive.vertexCacheOptimize).toEqual(true); expect(primitive.interleave).toEqual(true); expect(primitive.compressVertices).toEqual(false); expect(primitive.releaseGeometryInstances).toEqual(false); expect(primitive.allowPicking).toEqual(false); expect(primitive.asynchronous).toEqual(false); expect(primitive.debugShowBoundingVolume).toEqual(true); expect(primitive.debugShowShadowVolume).toEqual(true); }); it("releases geometry instances when releaseGeometryInstances is true", async function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, releaseGeometryInstances: true, asynchronous: false }); expect(primitive.geometryInstances).toBeDefined(); scene2.groundPrimitives.add(primitive); await pollToPromise_default(() => { scene2.renderForSpecs(); return primitive.ready; }); expect(primitive.geometryInstances).not.toBeDefined(); }); it("does not release geometry instances when releaseGeometryInstances is false", async function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, releaseGeometryInstances: false, asynchronous: false }); expect(primitive.geometryInstances).toBeDefined(); scene2.groundPrimitives.add(primitive); await pollToPromise_default(() => { scene2.renderForSpecs(); return primitive.ready; }); expect(primitive.geometryInstances).toBeDefined(); }); it("becomes ready", async function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, releaseGeometryInstances: false, asynchronous: false }); scene2.groundPrimitives.add(primitive); await pollToPromise_default(() => { scene2.renderForSpecs(); return primitive.ready; }); expect(primitive.ready).toBe(true); }); it("does not render when geometryInstances is undefined", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: void 0, appearance: new import__502.PerInstanceColorAppearance(), asynchronous: false }); scene2.groundPrimitives.add(primitive); scene2.renderForSpecs(); expect(scene2.frameState.commandList.length).toEqual(0); }); it("does not render when show is false", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); scene2.groundPrimitives.add(primitive); scene2.renderForSpecs(); expect(scene2.frameState.commandList.length).toBeGreaterThan(0); primitive.show = false; scene2.renderForSpecs(); expect(scene2.frameState.commandList.length).toEqual(0); }); it("becomes ready when show is false", async function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = scene2.groundPrimitives.add( new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false, show: false }) ); await pollToPromise_default(() => { scene2.renderForSpecs(); return primitive.ready; }); expect(primitive.ready).toBe(true); }); it("does not render other than for the color or pick pass", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); const frameState2 = scene2.frameState; frameState2.passes.render = false; frameState2.passes.pick = false; primitive.update(frameState2); expect(frameState2.commandList.length).toEqual(0); }); function expectRender(scene3, color) { expect(scene3).toRenderAndCall(function(rgba) { expect(rgba.slice(0, 4)).toEqual(color); }); } function expectRenderBlank(scene3) { expect(scene3).toRenderAndCall(function(rgba) { expect(rgba.slice()).not.toEqual([0, 0, 0, 255]); expect(rgba[0]).toEqual(0); }); } function verifyGroundPrimitiveRender(primitive2, color) { scene2.camera.setView({ destination: rectangle }); scene2.primitives.add(globePrimitive); scene2.primitives.add(tilesetPrimitive); expectRenderBlank(scene2); scene2.groundPrimitives.add(primitive2); primitive2.classificationType = import__502.ClassificationType.BOTH; globePrimitive.show = false; tilesetPrimitive.show = true; expectRender(scene2, color); globePrimitive.show = true; tilesetPrimitive.show = false; expectRender(scene2, color); primitive2.classificationType = import__502.ClassificationType.CESIUM_3D_TILE; globePrimitive.show = false; tilesetPrimitive.show = true; expectRender(scene2, color); globePrimitive.show = true; tilesetPrimitive.show = false; expectRenderBlank(scene2); primitive2.classificationType = import__502.ClassificationType.TERRAIN; globePrimitive.show = false; tilesetPrimitive.show = true; expectRenderBlank(scene2); globePrimitive.show = true; tilesetPrimitive.show = false; expectRender(scene2, color); globePrimitive.show = true; tilesetPrimitive.show = true; } it("renders in 3D", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); verifyGroundPrimitiveRender(primitive, rectColor); }); it("renders GroundPrimitives with spherical texture coordinates across the IDL in 3D", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } const rectColorAttribute = import__502.ColorGeometryInstanceAttribute.fromColor( new import__502.Color(1, 1, 0, 1) ); const bigIdlRectangle = import__502.Rectangle.fromDegrees(176, 30, -176, 34); const bigIdlRectangleInstance = new import__502.GeometryInstance({ geometry: new import__502.RectangleGeometry({ ellipsoid, rectangle: bigIdlRectangle }), id: "rectangle", attributes: { color: rectColorAttribute } }); primitive = new import__502.GroundPrimitive({ geometryInstances: bigIdlRectangleInstance, asynchronous: false }); scene2.camera.setView({ destination: bigIdlRectangle }); scene2.primitives.add(globePrimitive); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba[0]).toEqual(0); }); scene2.groundPrimitives.add(primitive); expect(scene2).toRender(rectColor); }); it("renders GroundPrimitives with planar texture coordinates across the IDL in 3D", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } const rectColorAttribute = import__502.ColorGeometryInstanceAttribute.fromColor( new import__502.Color(1, 1, 0, 1) ); const smallIdlRectangle = import__502.Rectangle.fromDegrees( 179.6, 30, -179.6, 30.9 ); const smallIdlRectangleInstance = new import__502.GeometryInstance({ geometry: new import__502.RectangleGeometry({ ellipsoid, rectangle: smallIdlRectangle }), id: "rectangle", attributes: { color: rectColorAttribute } }); primitive = new import__502.GroundPrimitive({ geometryInstances: smallIdlRectangleInstance, asynchronous: false }); scene2.camera.setView({ destination: smallIdlRectangle }); scene2.primitives.add(globePrimitive); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba[0]).toEqual(0); }); scene2.groundPrimitives.add(primitive); expect(scene2).toRender(rectColor); }); it("renders in Columbus view when scene3DOnly is false", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); scene2.morphToColumbusView(0); verifyGroundPrimitiveRender(primitive, rectColor); }); it("renders in 2D when scene3DOnly is false", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); scene2.morphTo2D(0); verifyGroundPrimitiveRender(primitive, rectColor); }); describe("larger scene", function() { let largeScene; let largeSceneReusableGlobePrimitive; let largeSceneReusableTilesetPrimitive; beforeAll(function() { largeScene = createScene_default({ canvas: createCanvas_default(2, 2) }); const bigRectangle = import__502.Rectangle.fromDegrees( -180 + import__503.Math.EPSILON4, -90 + import__503.Math.EPSILON4, 180 - import__503.Math.EPSILON4, 90 - import__503.Math.EPSILON4 ); largeSceneReusableGlobePrimitive = createPrimitive( bigRectangle, import__502.Pass.GLOBE ); largeSceneReusableTilesetPrimitive = createPrimitive( bigRectangle, import__502.Pass.CESIUM_3D_TILE ); }); afterAll(function() { largeSceneReusableGlobePrimitive.destroy(); largeSceneReusableTilesetPrimitive.destroy(); largeScene.destroyForSpecs(); }); afterEach(function() { largeScene.primitives.removeAll(); largeScene.groundPrimitives.removeAll(); }); function verifyLargerScene(groundPrimitive, expectedColor, destination) { largeScene.renderForSpecs(); largeScene.postProcessStages.fxaa.enabled = false; largeScene.camera.setView({ destination }); const largeSceneGlobePrimitive = new MockPrimitive( largeSceneReusableGlobePrimitive, import__502.Pass.GLOBE ); const largeSceneTilesetPrimitive = new MockPrimitive( largeSceneReusableTilesetPrimitive, import__502.Pass.CESIUM_3D_TILE ); largeScene.primitives.add(largeSceneGlobePrimitive); largeScene.primitives.add(largeSceneTilesetPrimitive); expectRenderBlank(largeScene); largeScene.groundPrimitives.add(groundPrimitive); groundPrimitive.classificationType = import__502.ClassificationType.BOTH; largeSceneGlobePrimitive.show = false; largeSceneTilesetPrimitive.show = true; expectRender(largeScene, expectedColor); globePrimitive.show = true; tilesetPrimitive.show = false; expectRender(largeScene, expectedColor); groundPrimitive.classificationType = import__502.ClassificationType.CESIUM_3D_TILE; largeSceneGlobePrimitive.show = false; largeSceneTilesetPrimitive.show = true; expectRender(largeScene, expectedColor); globePrimitive.show = true; largeSceneTilesetPrimitive.show = false; expectRenderBlank(largeScene); groundPrimitive.classificationType = import__502.ClassificationType.TERRAIN; largeSceneGlobePrimitive.show = false; largeSceneTilesetPrimitive.show = true; expectRenderBlank(largeScene); largeSceneGlobePrimitive.show = true; largeSceneTilesetPrimitive.show = false; expectRender(largeScene, expectedColor); largeSceneGlobePrimitive.show = true; largeSceneTilesetPrimitive.show = true; } it("renders batched instances", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } const rectColorAttribute = import__502.ColorGeometryInstanceAttribute.fromColor( new import__502.Color(0, 1, 1, 1) ); const rectangleInstance1 = new import__502.GeometryInstance({ geometry: new import__502.RectangleGeometry({ ellipsoid, rectangle: new import__502.Rectangle( rectangle.west, rectangle.south, rectangle.east, (rectangle.north + rectangle.south) * 0.5 ) }), id: "rectangle1", attributes: { color: rectColorAttribute } }); const rectangleInstance2 = new import__502.GeometryInstance({ geometry: new import__502.RectangleGeometry({ ellipsoid, rectangle: new import__502.Rectangle( rectangle.west, (rectangle.north + rectangle.south) * 0.5, rectangle.east, rectangle.north ) }), id: "rectangle2", attributes: { color: rectColorAttribute } }); const batchedPrimitive = new import__502.GroundPrimitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], asynchronous: false }); verifyLargerScene(batchedPrimitive, [0, 255, 255, 255], rectangle); }); it("renders small GeometryInstances with texture", function() { if (!import__502.GroundPrimitive.isSupported(scene2) || !import__502.GroundPrimitive.supportsMaterials(scene2)) { return; } const whiteImageMaterial = import__502.Material.fromType(import__502.Material.DiffuseMapType); whiteImageMaterial.uniforms.image = "./Data/Images/White.png"; const radians = import__503.Math.toRadians(0.1); const west = rectangle.west; const south = rectangle.south; const smallRectangle = new import__502.Rectangle( west, south, west + radians, south + radians ); const smallRectanglePrimitive = new import__502.GroundPrimitive({ geometryInstances: new import__502.GeometryInstance({ geometry: new import__502.RectangleGeometry({ ellipsoid, rectangle: smallRectangle }), id: "smallRectangle" }), appearance: new import__502.EllipsoidSurfaceAppearance({ aboveGround: false, flat: true, material: whiteImageMaterial }), asynchronous: false }); verifyLargerScene( smallRectanglePrimitive, [255, 255, 255, 255], smallRectangle ); }); it("renders large GeometryInstances with texture", function() { if (!import__502.GroundPrimitive.isSupported(scene2) || !import__502.GroundPrimitive.supportsMaterials(scene2)) { return; } const whiteImageMaterial = import__502.Material.fromType(import__502.Material.DiffuseMapType); whiteImageMaterial.uniforms.image = "./Data/Images/White.png"; const radians = import__503.Math.toRadians(1.1); const west = rectangle.west; const south = rectangle.south; const largeRectangle = new import__502.Rectangle( west, south, west + radians, south + radians ); const largeRectanglePrimitive = new import__502.GroundPrimitive({ geometryInstances: new import__502.GeometryInstance({ geometry: new import__502.RectangleGeometry({ ellipsoid, rectangle: largeRectangle }) }), id: "largeRectangle", appearance: new import__502.EllipsoidSurfaceAppearance({ aboveGround: false, flat: true, material: whiteImageMaterial }), asynchronous: false }); verifyLargerScene( largeRectanglePrimitive, [255, 255, 255, 255], largeRectangle ); }); it("renders GeometryInstances with texture across the IDL", function() { if (!import__502.GroundPrimitive.isSupported(scene2) || !import__502.GroundPrimitive.supportsMaterials(scene2)) { return; } const whiteImageMaterial = import__502.Material.fromType(import__502.Material.DiffuseMapType); whiteImageMaterial.uniforms.image = "./Data/Images/White.png"; const largeRectangle = import__502.Rectangle.fromDegrees(179, 30, -179, 31); const largeRectanglePrimitive = new import__502.GroundPrimitive({ geometryInstances: new import__502.GeometryInstance({ geometry: new import__502.RectangleGeometry({ ellipsoid, rectangle: largeRectangle }) }), id: "largeRectangle", appearance: new import__502.EllipsoidSurfaceAppearance({ aboveGround: false, flat: true, material: whiteImageMaterial }), asynchronous: false }); verifyLargerScene( largeRectanglePrimitive, [255, 255, 255, 255], largeRectangle ); }); }); it("renders with invert classification and an opaque color", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } scene2.invertClassification = true; scene2.invertClassificationColor = new import__502.Color(0.25, 0.25, 0.25, 1); rectangleInstance.attributes.show = new import__502.ShowGeometryInstanceAttribute( true ); primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); scene2.camera.setView({ destination: rectangle }); const invertedColor = new Array(4); invertedColor[0] = import__502.Color.floatToByte( import__502.Color.byteToFloat(depthColor[0]) * scene2.invertClassificationColor.red ); invertedColor[1] = import__502.Color.floatToByte( import__502.Color.byteToFloat(depthColor[1]) * scene2.invertClassificationColor.green ); invertedColor[2] = import__502.Color.floatToByte( import__502.Color.byteToFloat(depthColor[2]) * scene2.invertClassificationColor.blue ); invertedColor[3] = 255; scene2.primitives.add(tilesetPrimitive); expect(scene2).toRender(invertedColor); scene2.groundPrimitives.add(primitive); expect(scene2).toRender(rectColor); primitive.getGeometryInstanceAttributes("rectangle").show = [0]; expect(scene2).toRender(depthColor); scene2.invertClassification = false; }); it("renders with invert classification and a translucent color", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } if (!import__502.InvertClassification.isTranslucencySupported(scene2.context)) { return; } scene2.invertClassification = true; scene2.invertClassificationColor = new import__502.Color(0.25, 0.25, 0.25, 0.25); rectangleInstance.attributes.show = new import__502.ShowGeometryInstanceAttribute( true ); primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); scene2.camera.setView({ destination: rectangle }); const invertedColor = new Array(4); invertedColor[0] = import__502.Color.floatToByte( import__502.Color.byteToFloat(depthColor[0]) * scene2.invertClassificationColor.red * scene2.invertClassificationColor.alpha ); invertedColor[1] = import__502.Color.floatToByte( import__502.Color.byteToFloat(depthColor[1]) * scene2.invertClassificationColor.green * scene2.invertClassificationColor.alpha ); invertedColor[2] = import__502.Color.floatToByte( import__502.Color.byteToFloat(depthColor[2]) * scene2.invertClassificationColor.blue * scene2.invertClassificationColor.alpha ); invertedColor[3] = 255; scene2.primitives.add(tilesetPrimitive); expect(scene2).toRender(invertedColor); scene2.groundPrimitives.add(primitive); expect(scene2).toRender(rectColor); primitive.getGeometryInstanceAttributes("rectangle").show = [0]; expect(scene2).toRender(depthColor); scene2.invertClassification = false; }); it("renders bounding volume with debugShowBoundingVolume", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false, debugShowBoundingVolume: true }); scene2.groundPrimitives.add(primitive); scene2.camera.setView({ destination: rectangle }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[1]).toBeGreaterThanOrEqual(0); expect(rgba[1]).toBeGreaterThanOrEqual(0); expect(rgba[2]).toBeGreaterThanOrEqual(0); expect(rgba[3]).toEqual(255); }); }); it("renders shadow volume with debugShowShadowVolume", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false, debugShowShadowVolume: true }); scene2.groundPrimitives.add(primitive); scene2.camera.setView({ destination: rectangle }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[1]).toBeGreaterThanOrEqual(0); expect(rgba[1]).toBeGreaterThanOrEqual(0); expect(rgba[2]).toBeGreaterThanOrEqual(0); expect(rgba[3]).toEqual(255); }); }); it("get per instance attributes", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); verifyGroundPrimitiveRender(primitive, rectColor); const attributes = primitive.getGeometryInstanceAttributes("rectangle"); expect(attributes.color).toBeDefined(); }); it("modify color instance attribute", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); verifyGroundPrimitiveRender(primitive, rectColor); scene2.primitives.destroyPrimitives = false; scene2.primitives.removeAll(); scene2.primitives.destroyPrimitives = true; scene2.groundPrimitives.destroyPrimitives = false; scene2.groundPrimitives.removeAll(); scene2.groundPrimitives.destroyPrimitives = true; const newColor = [255, 255, 255, 255]; const attributes = primitive.getGeometryInstanceAttributes("rectangle"); expect(attributes.color).toBeDefined(); attributes.color = newColor; verifyGroundPrimitiveRender(primitive, newColor); }); it("modify show instance attribute", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } rectangleInstance.attributes.show = new import__502.ShowGeometryInstanceAttribute( true ); primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); verifyGroundPrimitiveRender(primitive, rectColor); scene2.primitives.destroyPrimitives = false; scene2.primitives.removeAll(); scene2.primitives.destroyPrimitives = true; scene2.groundPrimitives.destroyPrimitives = false; scene2.groundPrimitives.removeAll(); scene2.groundPrimitives.destroyPrimitives = true; const attributes = primitive.getGeometryInstanceAttributes("rectangle"); expect(attributes.show).toBeDefined(); attributes.show = [0]; verifyGroundPrimitiveRender(primitive, depthColor); }); it("renders with distance display condition per instance attribute", function() { if (!context.floatingPointTexture) { return; } if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } const near = 1e4; const far = 1e6; const rect = import__502.Rectangle.fromDegrees(-1, -1, 1, 1); const rectColorAttribute = import__502.ColorGeometryInstanceAttribute.fromColor( new import__502.Color(1, 1, 0, 1) ); const rectInstance = new import__502.GeometryInstance({ geometry: new import__502.RectangleGeometry({ ellipsoid, rectangle }), id: "rect", attributes: { color: rectColorAttribute, distanceDisplayCondition: new import__502.DistanceDisplayConditionGeometryInstanceAttribute( near, far ) } }); primitive = new import__502.GroundPrimitive({ geometryInstances: rectInstance, asynchronous: false }); scene2.primitives.add(globePrimitive); scene2.groundPrimitives.add(primitive); scene2.camera.setView({ destination: rect }); scene2.renderForSpecs(); const boundingSphere = primitive.getGeometryInstanceAttributes("rect").boundingSphere; const center = boundingSphere.center; const radius = boundingSphere.radius; scene2.camera.lookAt( center, new import__502.HeadingPitchRange(0, -import__503.Math.PI_OVER_TWO, radius) ); expect(scene2).toRender([0, 0, 255, 255]); scene2.camera.lookAt( center, new import__502.HeadingPitchRange(0, -import__503.Math.PI_OVER_TWO, radius + near + 1) ); expect(scene2).notToRender([0, 0, 255, 255]); scene2.camera.lookAt( center, new import__502.HeadingPitchRange(0, -import__503.Math.PI_OVER_TWO, radius + far + 1) ); expect(scene2).toRender([0, 0, 255, 255]); }); it("get bounding sphere from per instance attribute", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); verifyGroundPrimitiveRender(primitive, rectColor); const attributes = primitive.getGeometryInstanceAttributes("rectangle"); expect(attributes.boundingSphere).toBeDefined(); }); it("getGeometryInstanceAttributes returns same object each time", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); verifyGroundPrimitiveRender(primitive, rectColor); const attributes = primitive.getGeometryInstanceAttributes("rectangle"); const attributes2 = primitive.getGeometryInstanceAttributes("rectangle"); expect(attributes).toBe(attributes2); }); it("picking in 3D", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); verifyGroundPrimitiveRender(primitive, rectColor); expect(scene2).toPickAndCall(function(result) { expect(result.id).toEqual("rectangle"); }); }); it("picking in 2D", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); scene2.morphTo2D(0); verifyGroundPrimitiveRender(primitive, rectColor); expect(scene2).toPickAndCall(function(result) { expect(result.id).toEqual("rectangle"); }); }); it("picking in Columbus View", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); scene2.morphToColumbusView(0); verifyGroundPrimitiveRender(primitive, rectColor); expect(scene2).toPickAndCall(function(result) { expect(result.id).toEqual("rectangle"); }); }); it("picking without depth texture", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } spyOn(import__502.GroundPrimitive, "_supportsMaterials").and.callFake(function() { return false; }); primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); verifyGroundPrimitiveRender(primitive, rectColor); expect(scene2).toPickAndCall(function(result) { expect(result.id).toEqual("rectangle"); }); }); it("does not pick when allowPicking is false", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, allowPicking: false, asynchronous: false }); verifyGroundPrimitiveRender(primitive, rectColor); expect(scene2).notToPick(); }); it("internally invalid asynchronous geometry becomes ready", async function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: new import__502.GeometryInstance({ geometry: import__502.PolygonGeometry.fromPositions({ positions: [] }), attributes: { color: import__502.ColorGeometryInstanceAttribute.fromColor(import__502.Color.RED) } }), compressVertices: false }); scene2.groundPrimitives.add(primitive); await pollToPromise_default(() => { scene2.renderForSpecs(); return primitive.ready; }); expect(primitive.ready).toBe(true); }); it("internally invalid synchronous geometry becomes ready", async function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: new import__502.GeometryInstance({ geometry: import__502.PolygonGeometry.fromPositions({ positions: [] }), attributes: { color: import__502.ColorGeometryInstanceAttribute.fromColor(import__502.Color.RED) } }), asynchronous: false, compressVertices: false }); scene2.groundPrimitives.add(primitive); await pollToPromise_default(() => { scene2.renderForSpecs(); return primitive.ready; }); expect(primitive.ready).toBe(true); }); it("update throws when batched instance colors are different and materials on GroundPrimitives are not supported", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } spyOn(import__502.GroundPrimitive, "_supportsMaterials").and.callFake(function() { return false; }); let rectColorAttribute = import__502.ColorGeometryInstanceAttribute.fromColor( new import__502.Color(0, 1, 1, 1) ); const rectangleInstance1 = new import__502.GeometryInstance({ geometry: new import__502.RectangleGeometry({ ellipsoid, rectangle: new import__502.Rectangle( rectangle.west, rectangle.south, rectangle.east, (rectangle.north + rectangle.south) * 0.5 ) }), id: "rectangle1", attributes: { color: rectColorAttribute } }); rectColorAttribute = import__502.ColorGeometryInstanceAttribute.fromColor( new import__502.Color(1, 1, 0, 1) ); const rectangleInstance2 = new import__502.GeometryInstance({ geometry: new import__502.RectangleGeometry({ ellipsoid, rectangle: new import__502.Rectangle( rectangle.west, (rectangle.north + rectangle.south) * 0.5, rectangle.east, rectangle.north ) }), id: "rectangle2", attributes: { color: rectColorAttribute } }); primitive = new import__502.GroundPrimitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], asynchronous: false }); expect(function() { verifyGroundPrimitiveRender(primitive, rectColorAttribute.value); }).toThrowDeveloperError(); }); it("update throws when one batched instance color is undefined", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } const rectColorAttribute = import__502.ColorGeometryInstanceAttribute.fromColor( new import__502.Color(0, 1, 1, 1) ); const rectangleInstance1 = new import__502.GeometryInstance({ geometry: new import__502.RectangleGeometry({ ellipsoid, rectangle: new import__502.Rectangle( rectangle.west, rectangle.south, rectangle.east, (rectangle.north + rectangle.south) * 0.5 ) }), id: "rectangle1", attributes: { color: rectColorAttribute } }); const rectangleInstance2 = new import__502.GeometryInstance({ geometry: new import__502.RectangleGeometry({ ellipsoid, rectangle: new import__502.Rectangle( rectangle.west, (rectangle.north + rectangle.south) * 0.5, rectangle.east, rectangle.north ) }), id: "rectangle2" }); primitive = new import__502.GroundPrimitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], asynchronous: false }); expect(function() { verifyGroundPrimitiveRender(primitive, rectColorAttribute.value); }).toThrowDeveloperError(); }); it("setting per instance attribute throws when value is undefined", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); verifyGroundPrimitiveRender(primitive, rectColor); const attributes = primitive.getGeometryInstanceAttributes("rectangle"); expect(function() { attributes.color = void 0; }).toThrowDeveloperError(); }); it("can disable picking when asynchronous", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: true, allowPicking: false }); scene2.groundPrimitives.add(primitive); return pollToPromise_default(function() { scene2.renderForSpecs(); return primitive.ready; }).then(function() { const attributes = primitive.getGeometryInstanceAttributes("rectangle"); expect(function() { attributes.color = void 0; }).toThrowDeveloperError(); }); }); it("getGeometryInstanceAttributes throws without id", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); verifyGroundPrimitiveRender(primitive, rectColor); expect(function() { primitive.getGeometryInstanceAttributes(); }).toThrowDeveloperError(); }); it("getGeometryInstanceAttributes throws if update was not called", function() { primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); expect(function() { primitive.getGeometryInstanceAttributes("rectangle"); }).toThrowDeveloperError(); }); it("getGeometryInstanceAttributes returns undefined if id does not exist", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); verifyGroundPrimitiveRender(primitive, rectColor); expect( primitive.getGeometryInstanceAttributes("unknown") ).not.toBeDefined(); }); it("isDestroyed", function() { primitive = new import__502.GroundPrimitive(); expect(primitive.isDestroyed()).toEqual(false); primitive.destroy(); expect(primitive.isDestroyed()).toEqual(true); }); it("renders when using asynchronous pipeline", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance }); scene2.groundPrimitives.add(primitive); return pollToPromise_default(function() { scene2.renderForSpecs(); return primitive.ready; }).then(function() { scene2.groundPrimitives.destroyPrimitives = false; scene2.groundPrimitives.removeAll(); scene2.groundPrimitives.destroyPrimitives = true; verifyGroundPrimitiveRender(primitive, rectColor); }); }); it("destroy before asynchronous pipeline is complete", function() { if (!import__502.GroundPrimitive.isSupported(scene2)) { return; } primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance }); scene2.groundPrimitives.add(primitive); scene2.renderForSpecs(); primitive.destroy(); expect(primitive.isDestroyed()).toEqual(true); scene2.groundPrimitives.destroyPrimitives = false; scene2.groundPrimitives.removeAll(); scene2.groundPrimitives.destroyPrimitives = true; }); it("creating a synchronous primitive throws if initializeTerrainHeights wasn't called", function() { const initPromise = import__502.ApproximateTerrainHeights._initPromise; const terrainHeights = import__502.ApproximateTerrainHeights._terrainHeights; import__502.ApproximateTerrainHeights._initPromise = void 0; import__502.ApproximateTerrainHeights._terrainHeights = void 0; primitive = new import__502.GroundPrimitive({ geometryInstances: rectangleInstance, asynchronous: false }); scene2.groundPrimitives.add(primitive); if (import__502.GroundPrimitive.isSupported(scene2)) { expect(function() { scene2.renderForSpecs(); }).toThrowDeveloperError(); } import__502.ApproximateTerrainHeights._initPromise = initPromise; import__502.ApproximateTerrainHeights._terrainHeights = terrainHeights; }); }, "WebGL" ); // packages/engine/Specs/Scene/GroupMetadataSpec.js var import__504 = __toESM(require_Cesium(), 1); describe("Scene/GroupMetadata", function() { const buildingClassWithNoProperties = import__504.MetadataClass.fromJson({ id: "building", class: {} }); it("creates group metadata with default values", function() { const groupMetadata = new import__504.GroupMetadata({ id: "building", group: {}, class: buildingClassWithNoProperties }); expect(groupMetadata.id).toBe("building"); expect(groupMetadata.extras).toBeUndefined(); expect(groupMetadata.extensions).toBeUndefined(); }); it("creates group metadata", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { position: { type: "VEC3", componentType: "FLOAT32" } } } }); const extras = { other: 0 }; const extensions = { EXT_other_extension: {} }; const properties = { position: [0, 0, 0] }; const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: { extras, extensions, properties } }); expect(groupMetadata.id).toBe("building"); expect(groupMetadata.class).toBe(buildingClass); expect(groupMetadata.extras).toBe(extras); expect(groupMetadata.extensions).toBe(extensions); expect(groupMetadata.getProperty("position")).toEqual( import__504.Cartesian3.unpack(properties.position) ); }); it("constructor throws without group", function() { expect(function() { return new import__504.GroupMetadata({ id: "building", group: void 0, class: buildingClassWithNoProperties }); }).toThrowDeveloperError(); }); it("constructor throws without class", function() { expect(function() { return new import__504.GroupMetadata({ id: "building", group: {}, class: void 0 }); }).toThrowDeveloperError(); }); it("hasProperty returns false when there's no properties", function() { const groupMetadata = new import__504.GroupMetadata({ id: "building", group: {}, class: buildingClassWithNoProperties }); expect(groupMetadata.hasProperty("height")).toBe(false); }); it("hasProperty returns false when there's no property with the given property ID", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" } } } }); const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: { properties: { height: 10 } } }); expect(groupMetadata.hasProperty("color")).toBe(false); }); it("hasProperty returns true when there's a property with the given property ID", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" } } } }); const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: { properties: { height: 10 } } }); expect(groupMetadata.hasProperty("height")).toBe(true); }); it("hasProperty returns true when the class has a default value for a missing property", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32", required: false, default: 10 } } } }); const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: {} }); expect(groupMetadata.hasProperty("height")).toBe(true); }); it("hasProperty throws without propertyId", function() { const groupMetadata = new import__504.GroupMetadata({ id: "building", group: {}, class: buildingClassWithNoProperties }); expect(function() { groupMetadata.hasProperty(); }).toThrowDeveloperError(); }); it("hasPropertyBySemantic returns false when there's no properties", function() { const groupMetadata = new import__504.GroupMetadata({ class: buildingClassWithNoProperties, id: "building", group: {} }); expect(groupMetadata.hasPropertyBySemantic("HEIGHT")).toBe(false); }); it("hasPropertyBySemantic returns false when there's no property with the given semantic", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" } } } }); const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: { properties: { height: 10 } } }); expect(groupMetadata.hasPropertyBySemantic("HEIGHT")).toBe(false); }); it("hasPropertyBySemantic returns true when there's a property with the given semantic", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "HEIGHT" } } } }); const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: { properties: { height: 10 } } }); expect(groupMetadata.hasPropertyBySemantic("HEIGHT")).toBe(true); }); it("hasPropertyBySemantic returns true when the class has a default value for a missing property", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "HEIGHT", required: false, default: 10 } } } }); const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: {} }); expect(groupMetadata.hasPropertyBySemantic("HEIGHT")).toBe(true); }); it("hasPropertyBySemantic throws without semantic", function() { const groupMetadata = new import__504.GroupMetadata({ id: "building", group: {}, class: buildingClassWithNoProperties }); expect(function() { groupMetadata.hasPropertyBySemantic(void 0); }).toThrowDeveloperError(); }); it("getPropertyIds returns empty array when there are no properties", function() { const groupMetadata = new import__504.GroupMetadata({ id: "building", group: {}, class: buildingClassWithNoProperties }); expect(groupMetadata.getPropertyIds().length).toBe(0); }); it("getPropertyIds returns array of property IDs", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" }, color: { type: "STRING" } } } }); const groupMetadata = new import__504.GroupMetadata({ id: "building", class: buildingClass, group: { properties: { height: 10, color: "RED" } } }); expect(groupMetadata.getPropertyIds().sort()).toEqual(["color", "height"]); }); it("getPropertyIds includes properties with default values", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32", required: false, default: 10 }, color: { type: "STRING" } } } }); const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: { properties: { color: "RED" } } }); expect(groupMetadata.getPropertyIds().sort()).toEqual(["color", "height"]); }); it("getPropertyIds uses results argument", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" }, color: { type: "STRING" } } } }); const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: { properties: { height: 10, color: "RED" } } }); const results = []; const returnedResults = groupMetadata.getPropertyIds(results); expect(results).toBe(returnedResults); expect(results.sort()).toEqual(["color", "height"]); }); it("getProperty throws when there's no property with the given property ID", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" } } } }); const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: { properties: { height: 10 } } }); expect(function() { return groupMetadata.getProperty("color"); }).toThrowDeveloperError(); }); it("getProperty returns the property value", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { position: { type: "VEC3", componentType: "FLOAT32" } } } }); const position = [0, 0, 0]; const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: { properties: { position } } }); const value = groupMetadata.getProperty("position"); expect(value).toEqual(import__504.Cartesian3.unpack(position)); }); it("getProperty returns the default value when the property is missing", function() { const position = [0, 0, 0]; const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { position: { type: "VEC3", componentType: "FLOAT32", required: false, default: position } } } }); const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: {} }); const value = groupMetadata.getProperty("position"); expect(value).toEqual(import__504.Cartesian3.unpack(position)); }); it("getProperty throws without propertyId", function() { const groupMetadata = new import__504.GroupMetadata({ id: "building", group: {}, class: buildingClassWithNoProperties }); expect(function() { groupMetadata.getProperty(); }).toThrowDeveloperError(); }); it("setProperty returns false if property doesn't exist", function() { const groupMetadata = new import__504.GroupMetadata({ id: "building", group: {}, class: buildingClassWithNoProperties }); const position = [0, 0, 0]; expect(groupMetadata.setProperty("position", position)).toBe(false); }); it("setProperty sets property value", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { position: { type: "VEC3", componentType: "FLOAT32" } } } }); const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: { properties: { position: [0, 0, 0] } } }); const position = new import__504.Cartesian3(1, 1, 1); expect(groupMetadata.setProperty("position", position)).toBe(true); expect(groupMetadata.getProperty("position")).toEqual(position); expect(groupMetadata.getProperty("position")).not.toBe(position); }); it("setProperty throws without propertyId", function() { const groupMetadata = new import__504.GroupMetadata({ id: "building", group: {}, class: buildingClassWithNoProperties }); expect(function() { groupMetadata.setProperty(); }).toThrowDeveloperError(); }); it("setProperty throws without value", function() { const groupMetadata = new import__504.GroupMetadata({ id: "building", group: {}, class: buildingClassWithNoProperties }); expect(function() { groupMetadata.setProperty("color"); }).toThrowDeveloperError(); }); it("getPropertyBySemantic returns undefined when there's no class", function() { const groupMetadata = new import__504.GroupMetadata({ id: "building", group: {}, class: buildingClassWithNoProperties }); expect(groupMetadata.getPropertyBySemantic("_HEIGHT")).toBeUndefined(); }); it("getPropertyBySemantic returns undefined when there's no property with the given semantic", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" } } } }); const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: { properties: { height: 10 } } }); expect(groupMetadata.getPropertyBySemantic("_HEIGHT")).toBeUndefined(); }); it("getPropertyBySemantic returns the property value", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "_HEIGHT" } } } }); const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: { properties: { height: 10 } } }); expect(groupMetadata.getPropertyBySemantic("_HEIGHT")).toBe(10); }); it("getPropertyBySemantic throws without semantic", function() { const groupMetadata = new import__504.GroupMetadata({ id: "building", group: {}, class: buildingClassWithNoProperties }); expect(function() { groupMetadata.getPropertyBySemantic(); }).toThrowDeveloperError(); }); it("setPropertyBySemantic sets property value", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "_HEIGHT" } } } }); const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: { properties: { height: 10 } } }); expect(groupMetadata.setPropertyBySemantic("_HEIGHT", 20)).toBe(true); expect(groupMetadata.getProperty("height")).toBe(20); }); it("setPropertyBySemantic returns false if the semantic does not exist", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" } } } }); const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: { properties: { height: 10 } } }); expect(groupMetadata.setPropertyBySemantic("_HEIGHT", 20)).toBe(false); }); it("setPropertyBySemantic throws without semantic", function() { const groupMetadata = new import__504.GroupMetadata({ id: "building", group: {}, class: buildingClassWithNoProperties }); expect(function() { groupMetadata.setPropertyBySemantic(); }).toThrowDeveloperError(); }); it("setPropertyBySemantic throws without value", function() { const buildingClass = import__504.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "_HEIGHT" } } } }); const groupMetadata = new import__504.GroupMetadata({ class: buildingClass, id: "building", group: { properties: { height: 10 } } }); expect(function() { groupMetadata.setPropertyBySemantic("_HEIGHT"); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/HeightmapTessellatorSpec.js var import__505 = __toESM(require_Cesium(), 1); var import__506 = __toESM(require_Cesium(), 1); describe("Scene/HeightmapTessellator", function() { it("throws when heightmap is not provided", function() { expect(function() { import__505.HeightmapTessellator.computeVertices(); }).toThrowDeveloperError(); expect(function() { import__505.HeightmapTessellator.computeVertices({ width: 2, height: 2, vertices: [], nativeRectangle: { west: 10, south: 20, east: 20, north: 30 }, skirtHeight: 10 }); }).toThrowDeveloperError(); }); it("throws when width or height is not provided", function() { expect(function() { import__505.HeightmapTessellator.computeVertices({ heightmap: [1, 2, 3, 4], height: 2, vertices: [], nativeRectangle: { west: 10, south: 20, east: 20, north: 30 }, skirtHeight: 10 }); }).toThrowDeveloperError(); expect(function() { import__505.HeightmapTessellator.computeVertices({ heightmap: [1, 2, 3, 4], width: 2, vertices: [], nativeRectangle: { west: 10, south: 20, east: 20, north: 30 }, skirtHeight: 10 }); }).toThrowDeveloperError(); }); it("throws when nativeRectangle is not provided", function() { expect(function() { import__505.HeightmapTessellator.computeVertices({ heightmap: [1, 2, 3, 4], width: 2, height: 2, vertices: [], skirtHeight: 10 }); }).toThrowDeveloperError(); }); it("throws when skirtHeight is not provided", function() { expect(function() { import__505.HeightmapTessellator.computeVertices({ heightmap: [1, 2, 3, 4], width: 2, height: 2, vertices: [], nativeRectangle: { west: 10, south: 20, east: 20, north: 30 } }); }).toThrowDeveloperError(); }); function checkExpectedVertex(nativeRectangle, i, j, width, height, index, isEdge, vertices, heightmap, ellipsoid, skirtHeight) { let latitude = import__506.Math.lerp( nativeRectangle.north, nativeRectangle.south, j / (height - 1) ); latitude = import__506.Math.toRadians(latitude); let longitude = import__506.Math.lerp( nativeRectangle.west, nativeRectangle.east, i / (width - 1) ); longitude = import__506.Math.toRadians(longitude); let heightSample = heightmap[j * width + i]; if (isEdge) { heightSample -= skirtHeight; } const expectedVertexPosition = ellipsoid.cartographicToCartesian({ longitude, latitude, height: heightSample }); index = index * 6; const vertexPosition = new import__505.Cartesian3( vertices[index], vertices[index + 1], vertices[index + 2] ); expect(vertexPosition).toEqualEpsilon(expectedVertexPosition, 1); expect(vertices[index + 3]).toEqual(heightSample); expect(vertices[index + 4]).toEqualEpsilon( i / (width - 1), import__506.Math.EPSILON7 ); expect(vertices[index + 5]).toEqualEpsilon( 1 - j / (height - 1), import__506.Math.EPSILON7 ); } function checkExpectedQuantizedVertex(nativeRectangle, i, j, width, height, index, isEdge, vertices, heightmap, ellipsoid, skirtHeight, encoding) { let latitude = import__506.Math.lerp( nativeRectangle.north, nativeRectangle.south, j / (height - 1) ); latitude = import__506.Math.toRadians(latitude); let longitude = import__506.Math.lerp( nativeRectangle.west, nativeRectangle.east, i / (width - 1) ); longitude = import__506.Math.toRadians(longitude); let heightSample = heightmap[j * width + i]; if (isEdge) { heightSample -= skirtHeight; } const expectedVertexPosition = ellipsoid.cartographicToCartesian({ longitude, latitude, height: heightSample }); expect(encoding.decodePosition(vertices, index)).toEqualEpsilon( expectedVertexPosition, 1 ); } it("creates mesh without skirt", function() { const width = 3; const height = 3; const options = { heightmap: [1, 2, 3, 4, 5, 6, 7, 8, 9], width, height, skirtHeight: 0, nativeRectangle: { west: 10, south: 30, east: 20, north: 40 }, rectangle: new import__505.Rectangle( import__506.Math.toRadians(10), import__506.Math.toRadians(30), import__506.Math.toRadians(20), import__506.Math.toRadians(40) ) }; const results = import__505.HeightmapTessellator.computeVertices(options); const vertices = results.vertices; const ellipsoid = import__505.Ellipsoid.WGS84; const nativeRectangle = options.nativeRectangle; let index = 0; for (let j = 0; j < height; ++j) { for (let i = 0; i < width; ++i) { checkExpectedVertex( nativeRectangle, i, j, width, height, index++, false, vertices, options.heightmap, ellipsoid, options.skirtHeight ); } } }); it("creates mesh with skirt", function() { const width = 3; const height = 3; const options = { heightmap: [1, 2, 3, 4, 5, 6, 7, 8, 9], width, height, skirtHeight: 10, nativeRectangle: { west: 10, east: 20, south: 30, north: 40 } }; const results = import__505.HeightmapTessellator.computeVertices(options); const vertices = results.vertices; const ellipsoid = import__505.Ellipsoid.WGS84; const nativeRectangle = options.nativeRectangle; let i, j; let index = 0; for (j = 0; j < height; ++j) { for (i = 0; i < width; ++i) { checkExpectedVertex( nativeRectangle, i, j, width, height, index++, false, vertices, options.heightmap, ellipsoid, options.skirtHeight ); } } for (j = 0; j < height; ++j) { checkExpectedVertex( nativeRectangle, 0, height - 1 - j, width, height, index++, true, vertices, options.heightmap, ellipsoid, options.skirtHeight ); } for (i = 0; i < height; ++i) { checkExpectedVertex( nativeRectangle, width - 1 - i, height - 1, width, height, index++, true, vertices, options.heightmap, ellipsoid, options.skirtHeight ); } for (j = 0; j < height; ++j) { checkExpectedVertex( nativeRectangle, width - 1, j, width, height, index++, true, vertices, options.heightmap, ellipsoid, options.skirtHeight ); } for (i = 0; i < height; ++i) { checkExpectedVertex( nativeRectangle, i, 0, width, height, index++, true, vertices, options.heightmap, ellipsoid, options.skirtHeight ); } }); it("creates quantized mesh", function() { const width = 3; const height = 3; const options = { heightmap: [1, 2, 3, 4, 5, 6, 7, 8, 9], width, height, skirtHeight: 10, nativeRectangle: { west: 0.01, east: 0.02, south: 0.01, north: 0.02 } }; const results = import__505.HeightmapTessellator.computeVertices(options); const vertices = results.vertices; const ellipsoid = import__505.Ellipsoid.WGS84; const nativeRectangle = options.nativeRectangle; let i, j; let index = 0; for (j = 0; j < height; ++j) { for (i = 0; i < width; ++i) { checkExpectedQuantizedVertex( nativeRectangle, i, j, width, height, index++, false, vertices, options.heightmap, ellipsoid, options.skirtHeight, results.encoding ); } } for (j = 0; j < height; ++j) { checkExpectedQuantizedVertex( nativeRectangle, 0, height - 1 - j, width, height, index++, true, vertices, options.heightmap, ellipsoid, options.skirtHeight, results.encoding ); } for (i = 0; i < height; ++i) { checkExpectedQuantizedVertex( nativeRectangle, width - 1 - i, height - 1, width, height, index++, true, vertices, options.heightmap, ellipsoid, options.skirtHeight, results.encoding ); } for (j = 0; j < height; ++j) { checkExpectedQuantizedVertex( nativeRectangle, width - 1, j, width, height, index++, true, vertices, options.heightmap, ellipsoid, options.skirtHeight, results.encoding ); } for (i = 0; i < height; ++i) { checkExpectedQuantizedVertex( nativeRectangle, i, 0, width, height, index++, true, vertices, options.heightmap, ellipsoid, options.skirtHeight, results.encoding ); } }); it("tessellates web mercator heightmaps", function() { const width = 3; const height = 3; const options = { heightmap: [1, 2, 3, 4, 5, 6, 7, 8, 9], width, height, skirtHeight: 0, nativeRectangle: { west: 1e6, east: 2e6, south: 3e6, north: 4e6 }, isGeographic: false }; const results = import__505.HeightmapTessellator.computeVertices(options); const vertices = results.vertices; const ellipsoid = import__505.Ellipsoid.WGS84; const projection = new import__505.WebMercatorProjection(ellipsoid); const nativeRectangle = options.nativeRectangle; const geographicSouthwest = projection.unproject( new import__505.Cartesian2(nativeRectangle.west, nativeRectangle.south) ); const geographicNortheast = projection.unproject( new import__505.Cartesian2(nativeRectangle.east, nativeRectangle.north) ); for (let j = 0; j < height; ++j) { const y = import__506.Math.lerp( nativeRectangle.north, nativeRectangle.south, j / (height - 1) ); for (let i = 0; i < width; ++i) { const x = import__506.Math.lerp( nativeRectangle.west, nativeRectangle.east, i / (width - 1) ); const latLon = projection.unproject(new import__505.Cartesian2(x, y)); const longitude = latLon.longitude; const latitude = latLon.latitude; const heightSample = options.heightmap[j * width + i]; const expectedVertexPosition = ellipsoid.cartographicToCartesian({ longitude, latitude, height: heightSample }); const index = (j * width + i) * 6; const vertexPosition = new import__505.Cartesian3( vertices[index], vertices[index + 1], vertices[index + 2] ); const expectedU = (longitude - geographicSouthwest.longitude) / (geographicNortheast.longitude - geographicSouthwest.longitude); const expectedV = (latitude - geographicSouthwest.latitude) / (geographicNortheast.latitude - geographicSouthwest.latitude); expect(vertexPosition).toEqualEpsilon(expectedVertexPosition, 1); expect(vertices[index + 3]).toEqual(heightSample); expect(vertices[index + 4]).toEqualEpsilon( expectedU, import__506.Math.EPSILON7 ); expect(vertices[index + 5]).toEqualEpsilon( expectedV, import__506.Math.EPSILON7 ); } } }); it("supports multi-element little endian heights", function() { const width = 3; const height = 3; const options = { heightmap: [ 1, 2, 100, 3, 4, 100, 5, 6, 100, 7, 8, 100, 9, 10, 100, 11, 12, 100, 13, 14, 100, 15, 16, 100, 17, 18, 100 ], width, height, skirtHeight: 0, nativeRectangle: { west: 10, south: 30, east: 20, north: 40 }, rectangle: new import__505.Rectangle( import__506.Math.toRadians(10), import__506.Math.toRadians(30), import__506.Math.toRadians(20), import__506.Math.toRadians(40) ), structure: { stride: 3, elementsPerHeight: 2, elementMultiplier: 10 } }; const results = import__505.HeightmapTessellator.computeVertices(options); const vertices = results.vertices; const ellipsoid = import__505.Ellipsoid.WGS84; const nativeRectangle = options.nativeRectangle; for (let j = 0; j < height; ++j) { let latitude = import__506.Math.lerp( nativeRectangle.north, nativeRectangle.south, j / (height - 1) ); latitude = import__506.Math.toRadians(latitude); for (let i = 0; i < width; ++i) { let longitude = import__506.Math.lerp( nativeRectangle.west, nativeRectangle.east, i / (width - 1) ); longitude = import__506.Math.toRadians(longitude); const heightSampleIndex = (j * width + i) * options.structure.stride; const heightSample = options.heightmap[heightSampleIndex] + options.heightmap[heightSampleIndex + 1] * 10; const expectedVertexPosition = ellipsoid.cartographicToCartesian({ longitude, latitude, height: heightSample }); const index = (j * width + i) * 6; const vertexPosition = new import__505.Cartesian3( vertices[index], vertices[index + 1], vertices[index + 2] ); expect(vertexPosition).toEqualEpsilon(expectedVertexPosition, 1); expect(vertices[index + 3]).toEqual(heightSample); expect(vertices[index + 4]).toEqualEpsilon( i / (width - 1), import__506.Math.EPSILON7 ); expect(vertices[index + 5]).toEqualEpsilon( 1 - j / (height - 1), import__506.Math.EPSILON7 ); } } }); it("supports multi-element big endian heights", function() { const width = 3; const height = 3; const options = { heightmap: [ 1, 2, 100, 3, 4, 100, 5, 6, 100, 7, 8, 100, 9, 10, 100, 11, 12, 100, 13, 14, 100, 15, 16, 100, 17, 18, 100 ], width, height, skirtHeight: 0, nativeRectangle: { west: 10, south: 30, east: 20, north: 40 }, rectangle: new import__505.Rectangle( import__506.Math.toRadians(10), import__506.Math.toRadians(30), import__506.Math.toRadians(20), import__506.Math.toRadians(40) ), structure: { stride: 3, elementsPerHeight: 2, elementMultiplier: 10, isBigEndian: true } }; const results = import__505.HeightmapTessellator.computeVertices(options); const vertices = results.vertices; const ellipsoid = import__505.Ellipsoid.WGS84; const nativeRectangle = options.nativeRectangle; for (let j = 0; j < height; ++j) { let latitude = import__506.Math.lerp( nativeRectangle.north, nativeRectangle.south, j / (height - 1) ); latitude = import__506.Math.toRadians(latitude); for (let i = 0; i < width; ++i) { let longitude = import__506.Math.lerp( nativeRectangle.west, nativeRectangle.east, i / (width - 1) ); longitude = import__506.Math.toRadians(longitude); const heightSampleIndex = (j * width + i) * options.structure.stride; const heightSample = options.heightmap[heightSampleIndex] * 10 + options.heightmap[heightSampleIndex + 1]; const expectedVertexPosition = ellipsoid.cartographicToCartesian({ longitude, latitude, height: heightSample }); const index = (j * width + i) * 6; const vertexPosition = new import__505.Cartesian3( vertices[index], vertices[index + 1], vertices[index + 2] ); expect(vertexPosition).toEqualEpsilon(expectedVertexPosition, 1); expect(vertices[index + 3]).toEqual(heightSample); expect(vertices[index + 4]).toEqualEpsilon( i / (width - 1), import__506.Math.EPSILON7 ); expect(vertices[index + 5]).toEqualEpsilon( 1 - j / (height - 1), import__506.Math.EPSILON7 ); } } }); }); // packages/engine/Specs/Scene/I3SDataProviderSpec.js var import__507 = __toESM(require_Cesium(), 1); describe("Scene/I3SDataProvider", function() { const mockTileset = { destroy: function() { }, isDestroyed: function() { return false; }, update: function(frameState2) { }, prePassesUpdate: function(frameState2) { }, postPassesUpdate: function(frameState2) { }, updateForPass: function(frameState2, passState) { } }; const mockTilesetReady = { destroy: function() { }, isDestroyed: function() { return false; }, update: function(frameState2) { }, prePassesUpdate: function(frameState2) { }, postPassesUpdate: function(frameState2) { }, updateForPass: function(frameState2, passState) { } }; const mockLayers = [ { _tileset: mockTileset }, { _tileset: mockTilesetReady }, { // Need to handle the case of undefined tilesets because update may be called before they're created _tileset: void 0 } ]; const geoidTiles = [ [ { _buffer: new Float32Array([0, 1, 2, 3]), _encoding: 0, _height: 2, _structure: { elementMultiplier: 1, elementsPerHeight: 1, heightOffset: 0, heightScale: 1, isBigEndian: false, stride: 1 }, _width: 2 } ], [ { _buffer: new Float32Array([4, 5, 6, 7]), _encoding: 0, _height: 2, _structure: { elementMultiplier: 1, elementsPerHeight: 1, heightOffset: 0, heightScale: 1, isBigEndian: false, stride: 1 }, _width: 2 } ] ]; const mockGeoidProvider = { _lodCount: 0, tilingScheme: new import__507.GeographicTilingScheme(), requestTileGeometry: function(x, y, level) { if (level === 0) { return Promise.resolve(geoidTiles[x][y]); } return void 0; } }; const mockRootNodeData = { id: "root", level: 0, mbs: [-90, 45, 0, 28288.6903196], obb: { center: [-90, 45, 0], halfSize: [2e4, 2e4, 500], quaternion: [1, 0, 0, 0] }, lodSelection: [ { metricType: "maxScreenThresholdSQ", maxError: 4 }, { metricType: "maxScreenThreshold", maxError: 2 } ], children: [] }; const mockLayerData = { href: "layers/0/", layerType: "3DObject", attributeStorageInfo: [], store: { rootNode: "mockRootNodeUrl", version: "1.6" }, fullExtent: { xmin: 0, ymin: 1, xmax: 2, ymax: 3 }, spatialReference: { wkid: 4326 }, id: 0 }; const mockLayerData2 = { href: "layers/1/", layerType: "IntegratedMesh", attributeStorageInfo: [], store: { rootNode: "mockRootNodeUrl", version: "1.6" }, fullExtent: { xmin: 0, ymin: 1, xmax: 2, ymax: 3 }, spatialReference: { wkid: 4326 }, id: 1 }; const mockLayerData3 = { href: "layers/2/", layerType: "Point", attributeStorageInfo: [], store: { rootNode: "mockRootNodeUrl", version: "1.6" }, fullExtent: { xmin: 0, ymin: 1, xmax: 2, ymax: 3 }, spatialReference: { wkid: 4326 }, id: 2 }; const mockLayerDataTextured = { href: "layers/0/", layerType: "IntegratedMesh", attributeStorageInfo: [], store: { rootNode: "mockRootNodeUrl", version: "1.6" }, fullExtent: { xmin: 0, ymin: 1, xmax: 2, ymax: 3 }, spatialReference: { wkid: 4326 }, id: 0, textureSetDefinitions: [ { formats: [ { name: "0", format: "jpg" } ] } ] }; const mockBuildingLayerData = { layerType: "Building", name: "Test-Building", version: "1.6", store: { rootNode: "mockRootNodeUrl", version: "1.6" }, fullExtent: { xmin: 0, ymin: 1, xmax: 2, ymax: 3 }, spatialReference: { wkid: 4326 }, id: 0, statisticsHRef: "./statistics/summary", sublayers: [ { id: 200, layerType: "group", visibility: false, name: "Full Model", modelName: "FullModel", sublayers: [ { id: 210, layerType: "group", name: "Cat1", visibility: false, sublayers: [ { id: 1, layerType: "3DObject", visibility: false, name: "SubCat1" }, { id: 2, layerType: "3DObject", visibility: true, name: "SubCat2" }, { id: 3, layerType: "Point", visibility: true, name: "SubCat3" } ] }, { id: 220, layerType: "group", name: "Cat2", visibility: false } ] }, { id: 0, layerType: "3DObject", visibility: true, name: "Overview", modelName: "Overview" } ] }; const mockBuildingLayerDataNoSublayers = { layerType: "Building", name: "Test-Building", version: "1.6", store: { rootNode: "mockRootNodeUrl", version: "1.6" }, spatialReference: { wkid: 4326 }, id: 0 }; const mockLayerDataWithLargeExtent = { href: "layers/0/", layerType: "3DObject", attributeStorageInfo: [], store: { rootNode: "mockRootNodeUrl", version: "1.6" }, fullExtent: { xmin: -1, ymin: -1, xmax: 2, ymax: 3 }, spatialReference: { wkid: 4326 }, id: 0 }; const mockProviderData = { name: "mockProviderName", serviceVersion: "1.6", layers: [mockLayerData, mockLayerData2, mockLayerData3] }; const mockBSLProviderData = { name: "mockProviderName", serviceVersion: "1.6", layers: [mockBuildingLayerData] }; const mockBSLProviderData2 = { name: "mockProviderName", serviceVersion: "1.6", layers: [mockBuildingLayerDataNoSublayers] }; const mockProviderDataWithLargeExtent = { name: "mockProviderName", serviceVersion: "1.6", layers: [mockLayerDataWithLargeExtent] }; const mockStatisticsData = { summary: [ { fieldName: "BldgLevel", label: "BldgLevel", min: 0, max: 9, modelName: "bldgLevel", mostFrequentValues: [1, 3] }, { fieldName: "NoValues", label: "NoValues", modelName: "noValues" } ] }; const geoidService = {}; const cesium3dTilesetOptions = { skipLevelOfDetail: true, debugShowBoundingVolume: false, maximumScreenSpaceError: 16 }; const i3sOptions = { name: "testProvider", geoidTiledTerrainProvider: geoidService, // pass the geoid service cesium3dTilesetOptions }; it("constructs I3SDataProvider with options", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockProviderData) ); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl( "mockProviderUrl", i3sOptions ); expect(testProvider.name).toEqual("testProvider"); expect(testProvider.geoidTiledTerrainProvider).toEqual(geoidService); }); it("constructs I3SDataProvider with BSL", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.callFake(function fetch2() { let mockedData; if (this.url.includes("/sublayers/")) { const id = this.url.match(/\/sublayers\/\d+\//)[0].split("/")[2]; mockedData = { ...mockLayerData, href: `layers/${id}/`, id: parseInt(id) }; } else { mockedData = mockBSLProviderData; } return Promise.resolve(mockedData); }); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl( "mockProviderUrl", i3sOptions ); expect(testProvider.name).toEqual("testProvider"); expect(testProvider.geoidTiledTerrainProvider).toEqual(geoidService); expect(testProvider.sublayers[0].name).toEqual("Full Model"); expect(testProvider.sublayers[0].modelName).toEqual("FullModel"); expect(testProvider.sublayers[0].visibility).toEqual(false); expect(testProvider.sublayers[1].name).toEqual("Overview"); expect(testProvider.sublayers[1].modelName).toEqual("Overview"); expect(testProvider.sublayers[1].visibility).toEqual(true); expect(testProvider.sublayers[0].sublayers.length).toEqual(2); expect(testProvider.sublayers[0].sublayers[0].name).toEqual("Cat1"); expect(testProvider.sublayers[0].sublayers[0]._parent.name).toEqual( "Full Model" ); expect(testProvider.sublayers[0].sublayers[0]._parent.modelName).toEqual( "FullModel" ); expect(testProvider.sublayers[0].sublayers[1].name).toEqual("Cat2"); expect(testProvider.sublayers[0].sublayers[1]._parent.name).toEqual( "Full Model" ); expect(testProvider.sublayers[0].sublayers[1]._parent.modelName).toEqual( "FullModel" ); expect(testProvider.sublayers[0].sublayers[0].sublayers.length).toEqual(3); expect(testProvider.sublayers[0].sublayers[0].sublayers[0].name).toEqual( "SubCat1" ); expect( testProvider.sublayers[0].sublayers[0].sublayers[0].visibility ).toEqual(false); expect( testProvider.sublayers[0].sublayers[0].sublayers[0]._parent.name ).toEqual("Cat1"); expect(testProvider.sublayers[0].sublayers[0].sublayers[1].name).toEqual( "SubCat2" ); expect( testProvider.sublayers[0].sublayers[0].sublayers[1].visibility ).toEqual(true); expect( testProvider.sublayers[0].sublayers[0].sublayers[1]._parent.name ).toEqual("Cat1"); expect(testProvider.sublayers[0].sublayers[0].sublayers[2].name).toEqual( "SubCat3" ); expect( testProvider.sublayers[0].sublayers[0].sublayers[2].visibility ).toEqual(true); expect( testProvider.sublayers[0].sublayers[0].sublayers[2]._parent.name ).toEqual("Cat1"); expect(testProvider.sublayers[0].sublayers[1].sublayers.length).toEqual(0); }); it("default options for I3SDataProvider with textured layers", async function() { const providerData = { name: "mockProviderName", serviceVersion: "1.6", layers: [mockLayerDataTextured] }; spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(providerData) ); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl"); expect(testProvider.name).toBeUndefined(); expect(testProvider.geoidTiledTerrainProvider).toBeUndefined(); expect(testProvider.showFeatures).toEqual(false); expect(testProvider.adjustMaterialAlphaMode).toEqual(false); expect(testProvider.applySymbology).toEqual(false); expect(testProvider.calculateNormals).toEqual(false); }); it("default options for I3SDataProvider without textured layers", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockProviderData) ); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl"); expect(testProvider.name).toBeUndefined(); expect(testProvider.geoidTiledTerrainProvider).toBeUndefined(); expect(testProvider.showFeatures).toEqual(false); expect(testProvider.adjustMaterialAlphaMode).toEqual(false); expect(testProvider.applySymbology).toEqual(false); expect(testProvider.calculateNormals).toEqual(true); }); it("manual options for I3SDataProvider without textured layers", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockProviderData) ); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl", { ...i3sOptions, showFeatures: true, adjustMaterialAlphaMode: true, applySymbology: true, calculateNormals: false }); expect(testProvider.name).toEqual("testProvider"); expect(testProvider.geoidTiledTerrainProvider).toEqual(geoidService); expect(testProvider.showFeatures).toEqual(true); expect(testProvider.adjustMaterialAlphaMode).toEqual(true); expect(testProvider.applySymbology).toEqual(true); expect(testProvider.calculateNormals).toEqual(false); }); it("default options for I3SDataProvider with BSL", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.callFake(function fetch2() { let mockedData; if (this.url.includes("/sublayers/")) { const id = this.url.match(/\/sublayers\/\d+\//)[0].split("/")[2]; mockedData = { ...mockLayerData, href: `layers/${id}/`, id: parseInt(id) }; } else { mockedData = mockBSLProviderData; } return Promise.resolve(mockedData); }); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl"); expect(testProvider.name).toBeUndefined(); expect(testProvider.geoidTiledTerrainProvider).toBeUndefined(); expect(testProvider.showFeatures).toEqual(true); expect(testProvider.adjustMaterialAlphaMode).toEqual(true); expect(testProvider.applySymbology).toEqual(true); expect(testProvider.calculateNormals).toEqual(true); }); it("manual options for I3SDataProvider with BSL", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.callFake(function fetch2() { let mockedData; if (this.url.includes("/sublayers/")) { const id = this.url.match(/\/sublayers\/\d+\//)[0].split("/")[2]; mockedData = { ...mockLayerData, href: `layers/${id}/`, id: parseInt(id) }; } else { mockedData = mockBSLProviderData; } return Promise.resolve(mockedData); }); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl", { ...i3sOptions, showFeatures: false, adjustMaterialAlphaMode: false, applySymbology: false, calculateNormals: false }); expect(testProvider.name).toEqual("testProvider"); expect(testProvider.geoidTiledTerrainProvider).toEqual(geoidService); expect(testProvider.showFeatures).toEqual(false); expect(testProvider.adjustMaterialAlphaMode).toEqual(false); expect(testProvider.applySymbology).toEqual(false); expect(testProvider.calculateNormals).toEqual(false); }); it("constructs I3SDataProvider with BSL without sublayers and statistics", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockBSLProviderData2) ); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl( "mockProviderUrl", i3sOptions ); expect(testProvider.sublayers.length).toEqual(0); expect(testProvider._attributeStatistics.length).toEqual(0); }); it("wraps update", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockProviderData) ); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl", { name: "testProvider" }); testProvider._layers = mockLayers; spyOn(testProvider._layers[0]._tileset, "update"); spyOn(testProvider._layers[1]._tileset, "update"); const frameState2 = {}; testProvider.update(frameState2); expect(testProvider._layers[0]._tileset.update).toHaveBeenCalledWith( frameState2 ); expect(testProvider._layers[1]._tileset.update).toHaveBeenCalledWith( frameState2 ); }); it("wraps prePassesUpdate", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockProviderData) ); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl", { name: "testProvider" }); testProvider._layers = mockLayers; spyOn(testProvider._layers[0]._tileset, "prePassesUpdate"); spyOn(testProvider._layers[1]._tileset, "prePassesUpdate"); const frameState2 = {}; testProvider.prePassesUpdate(frameState2); expect( testProvider._layers[0]._tileset.prePassesUpdate ).toHaveBeenCalledWith(frameState2); expect( testProvider._layers[1]._tileset.prePassesUpdate ).toHaveBeenCalledWith(frameState2); }); it("wraps postPassesUpdate", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockProviderData) ); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl", { name: "testProvider" }); testProvider._layers = mockLayers; spyOn(testProvider._layers[0]._tileset, "postPassesUpdate"); spyOn(testProvider._layers[1]._tileset, "postPassesUpdate"); const frameState2 = {}; testProvider.postPassesUpdate(frameState2); expect( testProvider._layers[0]._tileset.postPassesUpdate ).toHaveBeenCalledWith(frameState2); expect( testProvider._layers[1]._tileset.postPassesUpdate ).toHaveBeenCalledWith(frameState2); }); it("wraps updateForPass", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockProviderData) ); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl", { name: "testProvider" }); testProvider._layers = mockLayers; spyOn(testProvider._layers[0]._tileset, "updateForPass"); spyOn(testProvider._layers[1]._tileset, "updateForPass"); const frameState2 = {}; const passState = { test: "test" }; testProvider.updateForPass(frameState2, passState); expect(testProvider._layers[0]._tileset.updateForPass).toHaveBeenCalledWith( frameState2, passState ); expect(testProvider._layers[1]._tileset.updateForPass).toHaveBeenCalledWith( frameState2, passState ); }); it("wraps show property", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.callFake(function fetch2() { return Promise.resolve(mockProviderData); }); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl( "mockProviderUrl", i3sOptions ); testProvider.show = true; expect(testProvider._layers[0]._tileset.show).toEqual(true); expect(testProvider._layers[1]._tileset.show).toEqual(true); testProvider.show = false; expect(testProvider._layers[0]._tileset.show).toEqual(false); expect(testProvider._layers[1]._tileset.show).toEqual(false); }); it("isDestroyed returns false for new provider", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockProviderData) ); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl", { name: "testProvider" }); testProvider._layers = mockLayers; expect(testProvider.isDestroyed()).toEqual(false); }); it("destroys provider", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockProviderData) ); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl", { name: "testProvider" }); testProvider._layers = mockLayers; spyOn(mockTileset, "destroy"); spyOn(mockTilesetReady, "destroy"); testProvider.destroy(); expect(mockTileset.destroy).toHaveBeenCalled(); expect(mockTilesetReady.destroy).toHaveBeenCalled(); expect(testProvider.isDestroyed()).toEqual(true); }); it("loads binary", async function() { const mockBinaryResponse = new ArrayBuffer(1); spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockProviderData) ); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl", { name: "testProvider" }); spyOn(import__507.Resource.prototype, "fetchArrayBuffer").and.returnValue( Promise.resolve(mockBinaryResponse) ); const resource = import__507.Resource.createIfNeeded("mockBinaryUri"); return testProvider._loadBinary(resource).then(function(result) { expect(import__507.Resource.prototype.fetchArrayBuffer).toHaveBeenCalled(); expect(result).toBe(mockBinaryResponse); }); }); it("loads binary with invalid uri", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockProviderData) ); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl", { name: "testProvider" }); const resource = import__507.Resource.createIfNeeded("mockBinaryUri"); return testProvider._loadBinary(resource).then(function() { fail("Promise should not be resolved for invalid uri"); }).catch(function(error) { expect(error.statusCode).toEqual(404); }); }); it("fromUrl throws without url ", async function() { await expectAsync( import__507.I3SDataProvider.fromUrl() ).toBeRejectedWithDeveloperError(); }); it("loads json", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockProviderData) ); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl", { name: "testProvider" }); expect(import__507.Resource.prototype.fetchJson).toHaveBeenCalled(); expect(testProvider).toBeInstanceOf(import__507.I3SDataProvider); expect(testProvider.data).toEqual(mockProviderData); expect(import__507.Cesium3DTileset.fromUrl).toHaveBeenCalled(); }); it("loadJson rejects invalid uri", async function() { const resource = import__507.Resource.createIfNeeded("mockJsonUri"); await expectAsync(import__507.I3SDataProvider.loadJson(resource)).toBeRejected(); }); it("loadJson rejects error response", async function() { const mockErrorResponse = { error: { code: 498, details: [ "Token would have expired, regenerate token and send the request again.", "If the token is generated based on the referrer ma\u2026mation is available with every request in header." ], message: "Invalid Token." } }; spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockErrorResponse) ); const resource = import__507.Resource.createIfNeeded("mockJsonUri"); await expectAsync(import__507.I3SDataProvider.loadJson(resource)).toBeRejectedWithError( import__507.RuntimeError, mockErrorResponse.error ); }); it("loadJson rejects error response with no details", async function() { const mockErrorResponse = { error: "Error with no details" }; spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockErrorResponse) ); const resource = import__507.Resource.createIfNeeded("mockJsonUri"); await expectAsync(import__507.I3SDataProvider.loadJson(resource)).toBeRejectedWithError( import__507.RuntimeError, mockErrorResponse.error ); }); it("loads geoid data", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockProviderDataWithLargeExtent) ); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl", { name: "testProvider", geoidTiledTerrainProvider: mockGeoidProvider }); return testProvider.loadGeoidData().then(function() { expect(testProvider._geoidDataList.length).toEqual(2); expect(testProvider._geoidDataList[0].height).toEqual(2); expect(testProvider._geoidDataList[0].width).toEqual(2); expect(testProvider._geoidDataList[0].buffer).toEqual( new Float32Array([0, 1, 2, 3]) ); expect(testProvider._geoidDataList[1].height).toEqual(2); expect(testProvider._geoidDataList[1].width).toEqual(2); expect(testProvider._geoidDataList[1].buffer).toEqual( new Float32Array([4, 5, 6, 7]) ); }); }); it("loadGeoidData resolves when no geoid provider is given", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockProviderData) ); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl", { name: "testProvider" }); return testProvider.loadGeoidData().then(function() { expect(testProvider._geoidDataList).toBeUndefined(); }); }); it("computes extent from layers", async function() { const mockExtent1 = import__507.Rectangle.fromDegrees(-1, 0, 1, 2); const mockExtent2 = import__507.Rectangle.fromDegrees(3, 1, 4, 3); spyOn(import__507.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(mockProviderData) ); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl", { name: "testProvider" }); testProvider._layersExtent = [mockExtent1, mockExtent2]; testProvider._computeExtent(); expect(testProvider.extent.west).toEqual(import__507.Math.toRadians(-1)); expect(testProvider.extent.south).toEqual(import__507.Math.toRadians(0)); expect(testProvider.extent.east).toEqual(import__507.Math.toRadians(4)); expect(testProvider.extent.north).toEqual(import__507.Math.toRadians(3)); }); it("loads i3s provider", async function() { spyOn(import__507.I3SDataProvider, "_fetchJson").and.callFake(function(resource) { if (resource.url.includes("mockProviderUrl/layers/0/mockRootNodeUrl/?") || resource.url.includes("mockProviderUrl/layers/1/mockRootNodeUrl/?")) { return Promise.resolve(mockRootNodeData); } else if (resource.url.includes("mockProviderUrl?")) { return Promise.resolve(mockProviderData); } return Promise.reject("invalid i3s request"); }); const testProvider = await import__507.I3SDataProvider.fromUrl("mockProviderUrl", { name: "testProvider", geoidTiledTerrainProvider: mockGeoidProvider }); expect(testProvider.layers.length).toEqual(2); expect(testProvider.layers[0].rootNode.tile).toBeDefined(); expect(testProvider.layers[0].rootNode.tile.i3sNode).toEqual( testProvider.layers[0].rootNode ); expect(testProvider._geoidDataList.length).toEqual(1); expect(testProvider._geoidDataList[0].height).toEqual(2); expect(testProvider._geoidDataList[0].width).toEqual(2); expect(testProvider._geoidDataList[0].buffer).toEqual( new Float32Array([4, 5, 6, 7]) ); }); it("loads i3s provider from single layer url", async function() { spyOn(import__507.I3SDataProvider, "_fetchJson").and.callFake(function(resource) { if (resource.url.includes("mockProviderUrl/layers/0/mockRootNodeUrl/?")) { return Promise.resolve(mockRootNodeData); } else if (resource.url.includes("mockProviderUrl/layers/0/?")) { return Promise.resolve(mockLayerData); } return Promise.reject("invalid i3s request"); }); const testProvider = await import__507.I3SDataProvider.fromUrl( "mockProviderUrl/layers/0/", { name: "testProvider", geoidTiledTerrainProvider: mockGeoidProvider } ); expect(testProvider.layers.length).toEqual(1); expect(testProvider.layers[0].rootNode.tile).toBeDefined(); expect(testProvider.layers[0].rootNode.tile.i3sNode).toEqual( testProvider.layers[0].rootNode ); expect(testProvider._geoidDataList.length).toEqual(1); expect(testProvider._geoidDataList[0].height).toEqual(2); expect(testProvider._geoidDataList[0].width).toEqual(2); expect(testProvider._geoidDataList[0].buffer).toEqual( new Float32Array([4, 5, 6, 7]) ); }); it("BSL change visibility", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.callFake(function fetch2() { let mockedData; if (this.url.includes("/sublayers/")) { const id = this.url.match(/\/sublayers\/\d+\//)[0].split("/")[2]; mockedData = { ...mockLayerData, href: `layers/${id}/`, id: parseInt(id) }; } else { mockedData = mockBSLProviderData; } return Promise.resolve(mockedData); }); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl( "mockProviderUrl", i3sOptions ); expect(testProvider.sublayers[0].sublayers[0].sublayers[0].name).toEqual( "SubCat1" ); expect( testProvider.sublayers[0].sublayers[0].sublayers[0].visibility ).toEqual(false); const spy = spyOn( testProvider.sublayers[0].sublayers[0].sublayers[0]._i3sLayers[0], "_updateVisibility" ); testProvider.sublayers[0].sublayers[0].sublayers[0].visibility = false; expect( testProvider.sublayers[0].sublayers[0].sublayers[0].visibility ).toEqual(false); expect(spy).not.toHaveBeenCalled(); testProvider.sublayers[0].sublayers[0].sublayers[0].visibility = true; expect( testProvider.sublayers[0].sublayers[0].sublayers[0].visibility ).toEqual(true); expect(spy).toHaveBeenCalled(); }); it("BSL get sublayers", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.callFake(function fetch2() { let mockedData; if (this.url.includes("/sublayers/")) { const id = this.url.match(/\/sublayers\/\d+\//)[0].split("/")[2]; mockedData = { ...mockLayerData, href: `layers/${id}/`, id: parseInt(id) }; } else { mockedData = mockBSLProviderData; } return Promise.resolve(mockedData); }); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl( "mockProviderUrl/layers/0/", i3sOptions ); const sublayers = testProvider.sublayers; expect(sublayers.length).toEqual(2); expect(sublayers[0]).toBeInstanceOf(import__507.I3SSublayer); expect(sublayers[0].data.name).toEqual("Full Model"); expect(sublayers[0].data.modelName).toEqual("FullModel"); expect(sublayers[1]).toBeInstanceOf(import__507.I3SSublayer); expect(sublayers[1].data.name).toEqual("Overview"); expect(sublayers[1].data.modelName).toEqual("Overview"); expect(sublayers[0].name).toEqual("Full Model"); expect(sublayers[0].modelName).toEqual("FullModel"); expect(sublayers[0].visibility).toEqual(false); expect(sublayers[0].sublayers.length).toEqual(2); expect(sublayers[0].sublayers[0].name).toEqual("Cat1"); expect(sublayers[0].sublayers[1].name).toEqual("Cat2"); expect(sublayers[0].sublayers[0].sublayers.length).toEqual(3); expect(sublayers[0].sublayers[0].sublayers[0].name).toEqual("SubCat1"); expect(sublayers[0].sublayers[0].sublayers[1].name).toEqual("SubCat2"); expect(sublayers[0].sublayers[0].sublayers[2].name).toEqual("SubCat3"); expect(sublayers[1].name).toEqual("Overview"); expect(sublayers[1].modelName).toEqual("Overview"); expect(sublayers[1].visibility).toEqual(true); expect(sublayers[1].sublayers.length).toEqual(0); }); it("BSL get attributes and values", async function() { spyOn(import__507.Resource.prototype, "fetchJson").and.callFake(function fetch2() { let mockedData = {}; if (this.url.includes("/sublayers/")) { const id = this.url.match(/\/sublayers\/\d+\//)[0].split("/")[2]; mockedData = { ...mockLayerData, href: `layers/${id}/`, id: parseInt(id) }; } else if (this.url.includes("/statistics/")) { mockedData = mockStatisticsData; } else { mockedData = mockBSLProviderData; } return Promise.resolve(mockedData); }); spyOn(import__507.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__507.Cesium3DTileset(); tileset._root = {}; return tileset; }); const testProvider = await import__507.I3SDataProvider.fromUrl( "mockProviderUrl", i3sOptions ); expect( testProvider._attributeStatistics[0].resource.url.includes( `${mockBuildingLayerData.statisticsHRef}/?` ) ).toEqual(true); expect(testProvider._attributeStatistics[0].data).toEqual( mockStatisticsData ); const attributes = testProvider.getAttributeNames(); expect(attributes.length).toEqual(2); expect(attributes[0]).toEqual("BldgLevel"); expect(attributes[1]).toEqual("NoValues"); const values = testProvider.getAttributeValues(attributes[0]); expect(values).toEqual([1, 3]); const noValues = testProvider.getAttributeValues(attributes[1]); expect(noValues).toEqual([]); const notExistingValues = testProvider.getAttributeValues( "notExistingAttribute" ); expect(notExistingValues).toEqual([]); }); it("empty statistics", async function() { spyOn(import__507.I3SDataProvider, "loadJson").and.returnValue(Promise.resolve({})); const mockProvider = { resource: new import__507.Resource({ url: "mockUrl" }) }; const statistics = new import__507.I3SStatistics(mockProvider, "mockStatUrl"); await statistics.load(); expect(statistics.names).toEqual([]); expect(statistics._getValues("anyName")).toBeUndefined(); }); }); // packages/engine/Specs/Scene/I3SDecoderSpec.js var import__508 = __toESM(require_Cesium(), 1); describe("Scene/I3SDecoder", function() { const defaultGeometrySchema = { ordering: [], featureAttributeOrder: [] }; const binaryData = new ArrayBuffer(8); const geometryDataObb = { _dataProvider: {}, _data: binaryData, _parent: { _data: { obb: { center: [0, 0, 0] } }, _inverseRotationMatrix: [1, 0, 0, 0, 1, 0, 0, 0, 1] } }; const geometryDataMbs = { _dataProvider: {}, _data: binaryData, _parent: { _data: { mbs: [0, 0, 0] }, _inverseRotationMatrix: [1, 0, 0, 0, 1, 0, 0, 0, 1] } }; const featureData = [ { data: {} } ]; beforeEach(function() { import__508.I3SDecoder._promise = void 0; }); it("constructor", function() { expect(new import__508.I3SDecoder()).toBeDefined(); }); it("throws with no url", async function() { await expectAsync(import__508.I3SDecoder.decode()).toBeRejectedWithDeveloperError(); }); it("throws with no default geometry schema", async function() { await expectAsync( import__508.I3SDecoder.decode("mockUrl") ).toBeRejectedWithDeveloperError(); }); it("throws with no geometry data", async function() { await expectAsync( import__508.I3SDecoder.decode("mockUrl", defaultGeometrySchema) ).toBeRejectedWithDeveloperError(); }); it("throws if not initialized", async function() { spyOn(import__508.TaskProcessor.prototype, "initWebAssemblyModule").and.returnValue( Promise.resolve(false) ); await expectAsync( import__508.I3SDecoder.decode("mockUrl", defaultGeometrySchema, geometryDataObb) ).toBeRejectedWithError(import__508.RuntimeError); }); it("empty geometry with obb", async function() { const result = await import__508.I3SDecoder.decode( "mockUrl", defaultGeometrySchema, geometryDataObb ); expect(result).toBeDefined(); expect(result.meshData).toBeDefined(); expect(result.meshData.buffers).toBeDefined(); expect(result.meshData.buffers.length).toEqual(0); expect(result.meshData.bufferViews).toBeDefined(); expect(result.meshData.bufferViews.length).toEqual(0); expect(result.meshData.accessors).toBeDefined(); expect(result.meshData.accessors.length).toEqual(0); expect(result.meshData.meshes).toBeDefined(); expect(result.meshData.meshes.length).toEqual(0); expect(result.meshData.nodes).toBeDefined(); expect(result.meshData.nodes.length).toEqual(0); expect(result.meshData.nodesInScene).toBeDefined(); expect(result.meshData.nodesInScene.length).toEqual(0); }); it("empty geometry with mbs", async function() { const result = await import__508.I3SDecoder.decode( "mockUrl", defaultGeometrySchema, geometryDataMbs ); expect(result).toBeDefined(); expect(result.meshData).toBeDefined(); expect(result.meshData.buffers).toBeDefined(); expect(result.meshData.buffers.length).toEqual(0); expect(result.meshData.bufferViews).toBeDefined(); expect(result.meshData.bufferViews.length).toEqual(0); expect(result.meshData.accessors).toBeDefined(); expect(result.meshData.accessors.length).toEqual(0); expect(result.meshData.meshes).toBeDefined(); expect(result.meshData.meshes.length).toEqual(0); expect(result.meshData.nodes).toBeDefined(); expect(result.meshData.nodes.length).toEqual(0); expect(result.meshData.nodesInScene).toBeDefined(); expect(result.meshData.nodesInScene.length).toEqual(0); }); it("empty geometry with empty feature data", async function() { const result = await import__508.I3SDecoder.decode( "mockUrl", defaultGeometrySchema, geometryDataMbs, featureData ); expect(result).toBeDefined(); expect(result.meshData).toBeDefined(); expect(result.meshData.buffers).toBeDefined(); expect(result.meshData.buffers.length).toEqual(0); expect(result.meshData.bufferViews).toBeDefined(); expect(result.meshData.bufferViews.length).toEqual(0); expect(result.meshData.accessors).toBeDefined(); expect(result.meshData.accessors.length).toEqual(0); expect(result.meshData.meshes).toBeDefined(); expect(result.meshData.meshes.length).toEqual(0); expect(result.meshData.nodes).toBeDefined(); expect(result.meshData.nodes.length).toEqual(0); expect(result.meshData.nodesInScene).toBeDefined(); expect(result.meshData.nodesInScene.length).toEqual(0); }); }); // packages/engine/Specs/Scene/I3SFieldSpec.js var import__509 = __toESM(require_Cesium(), 1); describe("Scene/I3SField", function() { async function createMockProvider(url, layerData, geoidDataList) { spyOn(import__509.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(layerData) ); spyOn(import__509.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__509.Cesium3DTileset(); tileset._root = {}; tileset._isI3STileSet = true; return tileset; }); const mockI3SProvider = await import__509.I3SDataProvider.fromUrl(url); mockI3SProvider._taskProcessorReadyPromise = Promise.resolve(); mockI3SProvider._geoidDataList = geoidDataList; return mockI3SProvider; } async function createMockLayer(providerUrl, layerData, geoidDataList) { const provider = await createMockProvider( providerUrl, layerData, geoidDataList ); const mockI3SLayer = provider.layers[0]; mockI3SLayer._geometryDefinitions = [ [ { index: 0, compressed: false, attributes: ["position"] }, { index: 1, compressed: false, attributes: [ "position", "normal", "uv0", "color", "featureId", "faceRange" ] } ] ]; return mockI3SLayer; } const attrStorageInfo = [ { attributeValues: { valueType: "UInt8", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_0", name: "testUInt8", ordering: ["attributeValues"] }, { attributeValues: { valueType: "Int8", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_1", name: "testInt8", ordering: ["attributeValues"] }, { attributeValues: { valueType: "UInt16", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_2", name: "testUInt16", ordering: ["attributeValues"] }, { attributeValues: { valueType: "Int16", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_3", name: "testInt16", ordering: ["attributeValues"] }, { attributeValues: { valueType: "Oid32", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_4", name: "testOid32", ordering: ["attributeValues"] }, { attributeValues: { valueType: "UInt32", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_5", name: "testUInt32", ordering: ["attributeValues"] }, { attributeValues: { valueType: "Int32", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_6", name: "testInt32", ordering: ["attributeValues"] }, { attributeValues: { valueType: "UInt64", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_7", name: "testUInt64", ordering: ["attributeValues"] }, { attributeValues: { valueType: "Int64", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_8", name: "testInt64", ordering: ["attributeValues"] }, { attributeValues: { valueType: "Float32", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_9", name: "testFloat32", ordering: ["attributeValues"] }, { attributeValues: { valueType: "Float64", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_10", name: "testFloat64", ordering: ["attributeValues"] }, { attributeByteCounts: { valueType: "UInt32", valuesPerElement: 1 }, attributeValues: { valueType: "String", valuesPerElement: 1, encoding: "UTF-8" }, header: [ { property: "count", valueType: "UInt32" }, { property: "attributeValuesByteCount", valueType: "UInt32" } ], key: "f_11", name: "testString", ordering: ["attributeByteCounts", "attributeValues"] } ]; const layerDataWithoutNodePages = { href: "mockLayerUrl", layerType: "3DObject", attributeStorageInfo: attrStorageInfo, store: { defaultGeometrySchema: {}, version: "1.6" }, materialDefinitions: [ { doubleSided: true, pbrMetallicRoughness: { metallicFactor: 0 } }, { doubleSided: true, pbrMetallicRoughness: { baseColorTexture: { textureSetDefinitionId: 0 }, metallicFactor: 0 } } ], textureSetDefinitions: [ { formats: [ { name: "0", format: "dds" }, { name: "1", format: "jpg" } ] } ], spatialReference: { wkid: 4326 } }; it("create field for root node loaded from uri", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const rootNode = new import__509.I3SNode(mockI3SLayerWithoutNodePages, "mockUrl", true); const field = new import__509.I3SField(rootNode, { key: "test_key" }); expect( field.resource.url.includes("mockUrl/attributes/test_key/0?") ).toEqual(true); }); it("get field values", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const rootNode = new import__509.I3SNode(mockI3SLayerWithoutNodePages, "mockUrl", true); const field = new import__509.I3SField(rootNode, {}); field._values = [1, 2]; expect(field.values).toEqual([]); field._values["objectIds"] = [3, 4]; expect(field.values).toEqual([3, 4]); field._values["attributeValues"] = [5, 6]; expect(field.values).toEqual([5, 6]); }); it("get body offset for objectIds", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const rootNode = new import__509.I3SNode(mockI3SLayerWithoutNodePages, "mockUrl", true); const field = new import__509.I3SField(rootNode, { objectIds: { valueType: "UInt16" } }); expect(field._getBodyOffset(7)).toEqual(8); }); it("get body offset for unsupported property", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const rootNode = new import__509.I3SNode(mockI3SLayerWithoutNodePages, "mockUrl", true); const field = new import__509.I3SField(rootNode, { property: { valueType: "UInt16" } }); expect(field._getBodyOffset(7)).toEqual(7); }); it("validate field header with invalid attribute buffer size", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const rootNode = new import__509.I3SNode(mockI3SLayerWithoutNodePages, "mockUrl", true); const field = new import__509.I3SField(rootNode, { header: [{ valueType: "String" }] }); field["_header"] = { count: 1 }; expect(function() { field._validateHeader({ byteLength: 0 }); }).toThrowError(import__509.RuntimeError); }); it("validate field body with empty header", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const rootNode = new import__509.I3SNode(mockI3SLayerWithoutNodePages, "mockUrl", true); const field = new import__509.I3SField(rootNode, {}); field["_header"] = {}; expect(function() { field._validateBody(void 0, void 0); }).toThrowError(import__509.RuntimeError); }); it("validate field body with invalid attribute buffer", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const rootNode = new import__509.I3SNode(mockI3SLayerWithoutNodePages, "mockUrl", true); const field = new import__509.I3SField(rootNode, { ordering: ["testAttr"], testAttr: { valueType: "String" } }); field["_header"] = { count: 1 }; expect(function() { field._validateBody({ byteLength: 5 }, 4); }).toThrowError(import__509.RuntimeError); }); it("validate field body with invalid offset", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const rootNode = new import__509.I3SNode(mockI3SLayerWithoutNodePages, "mockUrl", true); const field = new import__509.I3SField(rootNode, { ordering: [] }); field["_header"] = { count: 1 }; expect(function() { field._validateBody({ byteLength: 3 }, 4); }).toThrowError(import__509.RuntimeError); }); it("validate field body with missing property", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const rootNode = new import__509.I3SNode(mockI3SLayerWithoutNodePages, "mockUrl", true); const field = new import__509.I3SField(rootNode, { ordering: ["ObjectIds"] }); field["_header"] = { count: 0 }; expect(function() { field._validateBody({ byteLength: 5 }, 4); }).toThrowError(import__509.RuntimeError); }); it("load field with unavailable resource", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const spy = spyOn(import__509.Resource.prototype, "fetchArrayBuffer"); spy.and.callFake(function() { const text = "{404}"; const buffer = new ArrayBuffer(text.length); const view = new Uint8Array(buffer); for (let i = 0; i < text.length; i++) { view[i] = text.charCodeAt(i); } return Promise.resolve(buffer); }); const rootNode = new import__509.I3SNode(mockI3SLayerWithoutNodePages, "mockUrl", true); const field = new import__509.I3SField(rootNode, { ordering: [] }); await field.load(); expect(spy).toHaveBeenCalledTimes(1); await field.load(); expect(spy).toHaveBeenCalledTimes(1); expect(field._data).toBeUndefined(); }); it("load field with invalid header", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); spyOn( mockI3SLayerWithoutNodePages._dataProvider, "_loadBinary" ).and.callFake(function() { return Promise.resolve(new ArrayBuffer(1)); }); const rootNode = new import__509.I3SNode(mockI3SLayerWithoutNodePages, "mockUrl", true); const field = new import__509.I3SField(rootNode, { header: [{ valueType: "UInt16" }] }); const spy = spyOn(field, "_parseBody"); await field.load(); expect(spy).not.toHaveBeenCalled(); expect(field.header).toBeUndefined(); }); it("load field with invalid body", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); spyOn( mockI3SLayerWithoutNodePages._dataProvider, "_loadBinary" ).and.callFake(function() { return Promise.resolve(new ArrayBuffer(1)); }); const rootNode = new import__509.I3SNode(mockI3SLayerWithoutNodePages, "mockUrl", true); const field = new import__509.I3SField(rootNode, { header: [] }); const spy = spyOn(field, "_parseBody"); await field.load(); expect(spy).not.toHaveBeenCalled(); expect(field.header).toBeDefined(); expect(field._values).toBeUndefined(); }); it("load field with valid buffer", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const text = "Pass"; spyOn( mockI3SLayerWithoutNodePages._dataProvider, "_loadBinary" ).and.callFake(function() { const buffer = new ArrayBuffer(text.length + 3); const view = new Uint8Array(buffer); view[0] = 1; view[1] = text.length + 1; for (let i = 0; i < text.length; i++) { view[i + 2] = text.charCodeAt(i); } return Promise.resolve(buffer); }); const rootNode = new import__509.I3SNode(mockI3SLayerWithoutNodePages, "mockUrl", true); const attributeStorageInfo = { objectIds: { valueType: "String" }, attributeByteCounts: { valueType: "UInt8" }, header: [{ property: "count", valueType: "UInt8" }], ordering: ["attributeByteCounts", "ObjectIds", "custom"] }; const field = new import__509.I3SField(rootNode, attributeStorageInfo); await field.load(); expect(field.values).toEqual([text]); }); }); // packages/engine/Specs/Scene/I3SLayerSpec.js var import__510 = __toESM(require_Cesium(), 1); describe("Scene/I3SLayer", function() { const rootNodePageEntry = { index: 0, children: [1, 2], obb: { center: [-90, 45, 0], halfSize: [2e4, 2e4, 500], quaternion: [1, 0, 0, 0] } }; const childNodePageEntry = { index: 1, children: [], obb: { center: [-90, 45, 0], halfSize: [1e4, 1e4, 250], quaternion: [1, 0, 0, 0] }, lodThreshold: 500, parentIndex: 0 }; const nodePageResult = { nodes: [rootNodePageEntry, childNodePageEntry] }; const geometryDefinitions = [ { geometryBuffers: [ { color: { type: "UInt8", component: 4 }, faceRange: { type: "UInt32", component: 2, binding: "per-feature" }, featureId: { type: "UInt64", component: 1, binding: "per-feature" }, normal: { type: "Float32", component: 3 }, offset: 8, position: { type: "Float32", component: 3 }, uv0: { type: "Float32", component: 2 } }, { compressedAttributes: { attributes: ["position", "normal", "uv0", "color", "feature-index"], encoding: "draco" } }, { compressedAttributes: { attributes: ["position", "color", "feature-index"], encoding: "draco" } }, { offset: 8, color: { type: "UInt8", component: 4 }, faceRange: { type: "UInt32", component: 2, binding: "per-feature" }, featureId: { type: "UInt64", component: 1, binding: "per-feature" }, normal: { type: "Float32", component: 3 }, position: { type: "Float32", component: 3 }, uv0: { type: "Float32", component: 2 }, uv1: { type: "Float32", component: 2 } } ] } ]; const layerData = { href: "mockLayerUrl", layerType: "3DObject", nodePages: { lodSelectionMetricType: "maxScreenThresholdSQ", nodesPerPage: 2, rootIndex: 0 }, attributeStorageInfo: [], store: { defaultGeometrySchema: {}, version: "1.7" }, geometryDefinitions, fullExtent: { xmin: 0, ymin: 1, xmax: 2, ymax: 3 }, spatialReference: { wkid: 4326 } }; const layerData2 = { id: 0, layerType: "3DObject", nodePages: { lodSelectionMetricType: "maxScreenThresholdSQ", nodesPerPage: 2, rootIndex: 0 }, attributeStorageInfo: [], store: { defaultGeometrySchema: {}, extent: [0, 1, 2, 3], version: "1.7" }, spatialReference: { wkid: 4326 }, drawingInfo: { renderer: { type: "simple", symbol: { symbolLayers: [ { type: "Fill", edges: { color: [255, 255, 255], tranparency: 0 } } ] } } } }; async function createMockI3SProvider(layerData3, options) { spyOn(import__510.I3SDataProvider, "loadJson").and.returnValue( Promise.resolve(layerData3) ); spyOn(import__510.Cesium3DTileset, "fromUrl").and.callFake(async (url, options2) => { const tileset = new import__510.Cesium3DTileset(options2); tileset._root = {}; tileset._isI3STileSet = true; return tileset; }); const mockI3SProvider = await import__510.I3SDataProvider.fromUrl( "mockProviderUrl?testQuery=test", options ); spyOn(import__510.I3SDataProvider.prototype, "loadGeoidData").and.returnValue( Promise.resolve() ); return mockI3SProvider; } it("constructs I3SLayer from url", async function() { spyOn(import__510.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodePageResult) ); const mockI3SProvider = await createMockI3SProvider(layerData); const testLayer = mockI3SProvider.layers[0]; expect(testLayer).toBeInstanceOf(import__510.I3SLayer); expect(testLayer.resource.url).toContain("mockProviderUrl/mockLayerUrl/"); expect(testLayer.resource.queryParameters.testQuery).toEqual("test"); expect(testLayer.version).toEqual("1.7"); expect(testLayer.majorVersion).toEqual(1); expect(testLayer.minorVersion).toEqual(7); expect(testLayer.legacyVersion16).toEqual(false); expect(testLayer.data).toEqual(layerData); expect(testLayer._extent.west).toEqual(import__510.Math.toRadians(0)); expect(testLayer._extent.south).toEqual(import__510.Math.toRadians(1)); expect(testLayer._extent.east).toEqual(import__510.Math.toRadians(2)); expect(testLayer._extent.north).toEqual(import__510.Math.toRadians(3)); expect(testLayer._geometryDefinitions.length).toEqual(1); expect(testLayer._geometryDefinitions[0].length).toEqual(4); expect(testLayer._geometryDefinitions[0][0].compressed).toEqual(true); expect(testLayer._geometryDefinitions[0][0].attributes).toEqual([ "position", "color", "feature-index" ]); expect(testLayer._geometryDefinitions[0][1].compressed).toEqual(true); expect(testLayer._geometryDefinitions[0][1].attributes).toEqual([ "position", "normal", "uv0", "color", "feature-index" ]); expect(testLayer._geometryDefinitions[0][2].compressed).toEqual(false); expect(testLayer._geometryDefinitions[0][2].attributes).toEqual([ "color", "faceRange", "featureId", "normal", "position", "uv0" ]); expect(testLayer._geometryDefinitions[0][3].compressed).toEqual(false); expect(testLayer._geometryDefinitions[0][3].attributes).toEqual([ "color", "faceRange", "featureId", "normal", "position", "uv0", "uv1" ]); }); it("constructs I3SLayer from id", async function() { spyOn(import__510.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodePageResult) ); const mockI3SProvider = await createMockI3SProvider(layerData2); const testLayer = new import__510.I3SLayer( mockI3SProvider, layerData2, mockI3SProvider ); expect(testLayer.data).toEqual(layerData2); expect(testLayer.resource.url).toContain("mockProviderUrl/layers/0/"); expect(testLayer.resource.queryParameters.testQuery).toEqual("test"); expect(testLayer._extent.west).toEqual(import__510.Math.toRadians(0)); expect(testLayer._extent.south).toEqual(import__510.Math.toRadians(1)); expect(testLayer._extent.east).toEqual(import__510.Math.toRadians(2)); expect(testLayer._extent.north).toEqual(import__510.Math.toRadians(3)); const spy = spyOn(import__510.I3SNode.prototype, "_filterFeatures"); await testLayer.filterByAttributes(); expect(spy).not.toHaveBeenCalled(); mockI3SProvider.show = false; testLayer._updateVisibility(); expect(testLayer._tileset).toBeUndefined(); await testLayer.load(); expect(testLayer._tileset.show).toBeFalse(); await testLayer.filterByAttributes(); expect(spy).toHaveBeenCalled(); }); it("constructs I3SLayer from single layer url", async function() { spyOn(import__510.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodePageResult) ); const mockI3SProvider = await createMockI3SProvider(layerData2); const testLayer = mockI3SProvider.layers[0]; expect(testLayer.resource.url).toContain("mockProviderUrl/layers/0/"); expect(testLayer._extent.west).toEqual(import__510.Math.toRadians(0)); expect(testLayer._extent.south).toEqual(import__510.Math.toRadians(1)); expect(testLayer._extent.east).toEqual(import__510.Math.toRadians(2)); expect(testLayer._extent.north).toEqual(import__510.Math.toRadians(3)); }); it("loads root node", async function() { spyOn(import__510.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(nodePageResult) ); const mockI3SProvider = await createMockI3SProvider(layerData); const testLayer = mockI3SProvider.layers[0]; expect(testLayer.rootNode).toBeDefined(); expect(testLayer.rootNode.data.index).toEqual(rootNodePageEntry.index); expect(testLayer.rootNode.data.children).toEqual( rootNodePageEntry.children ); expect(testLayer.rootNode.data.obb).toEqual(rootNodePageEntry.obb); }); it("creates 3d tileset", async function() { spyOn(import__510.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodePageResult) ); const mockI3SProvider = await createMockI3SProvider(layerData); const testLayer = mockI3SProvider.layers[0]; expect(testLayer.tileset).toBeDefined(); expect(testLayer.tileset.tileUnload._listeners.length).toEqual(1); expect(testLayer.tileset.tileVisible._listeners.length).toEqual(1); expect(testLayer._rootNode).toBeDefined(); expect(testLayer._rootNode._tile).toBe(testLayer.tileset._root); }); it("creates 3d tileset with options", async function() { const cesium3dTilesetOptions = { debugShowBoundingVolume: true, maximumScreenSpaceError: 8 }; spyOn(import__510.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodePageResult) ); await createMockI3SProvider(layerData, { cesium3dTilesetOptions }); expect(import__510.Cesium3DTileset.fromUrl).toHaveBeenCalledWith( jasmine.any(String), cesium3dTilesetOptions ); }); it("load i3s layer rejects unsupported spatial reference", async function() { spyOn(import__510.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodePageResult) ); const invalidLayerData = { layerType: "3DObject", nodePages: { lodSelectionMetricType: "maxScreenThresholdSQ", nodesPerPage: 2, rootIndex: 0 }, store: { defaultGeometrySchema: {}, extent: [0, 1, 2, 3], version: "1.7" }, spatialReference: { wkid: 3857 } }; await expectAsync( createMockI3SProvider(invalidLayerData) ).toBeRejectedWithError( import__510.RuntimeError, `Unsupported spatial reference: ${invalidLayerData.spatialReference.wkid}` ); }); it("creates 3d tileset with outline color from symbology", async function() { spyOn(import__510.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodePageResult) ); const mockI3SProvider = await createMockI3SProvider(layerData2, { applySymbology: true, cesium3dTilesetOptions: {} }); const testLayer = mockI3SProvider.layers[0]; expect(testLayer.tileset).toBeDefined(); expect(testLayer.tileset.outlineColor.red).toEqual(1); expect(testLayer.tileset.outlineColor.green).toEqual(1); expect(testLayer.tileset.outlineColor.blue).toEqual(1); expect(testLayer.tileset.outlineColor.alpha).toEqual(1); }); it("creates 3d tileset with outline color from options", async function() { const cesium3dTilesetOptions = { outlineColor: new import__510.Color(0.5, 0.5, 0.5, 0.5) }; spyOn(import__510.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodePageResult) ); const mockI3SProvider = await createMockI3SProvider(layerData2, { applySymbology: true, cesium3dTilesetOptions }); const testLayer = mockI3SProvider.layers[0]; expect(testLayer.tileset).toBeDefined(); expect(testLayer.tileset.outlineColor.red).toEqual(0.5); expect(testLayer.tileset.outlineColor.green).toEqual(0.5); expect(testLayer.tileset.outlineColor.blue).toEqual(0.5); expect(testLayer.tileset.outlineColor.alpha).toEqual(0.5); }); }); // packages/engine/Specs/Scene/I3SNodeSpec.js var import__511 = __toESM(require_Cesium(), 1); describe("Scene/I3SNode", function() { const geoidDataList = [ { buffer: new Float32Array([0, 10, 10, 20]), height: 2, nativeExtent: new import__511.Rectangle( -200375083427870, -200375083427870, 200375083427870, 200375083427870 ), offset: 0, projection: new import__511.WebMercatorProjection( new import__511.Ellipsoid(6378137, 6378137, 6356752314245179e-9) ), projectionType: "WebMercator", scale: 1, width: 2 } ]; const rootNodeWithChildren = { id: "root", level: 0, mbs: [-90, 45, 0, 28288.6903196], obb: { center: [-90, 45, 0], halfSize: [2e4, 2e4, 500], quaternion: [1, 0, 0, 0] }, lodSelection: [ { metricType: "maxScreenThresholdSQ", maxError: 4 }, { metricType: "maxScreenThreshold", maxError: 2 } ], children: [ { id: 1, href: "../1" }, { id: 2, href: "../2" } ] }; const nodeWithContent = { id: 1, level: 1, mbs: [-90, 45, 0, 14144.3451598], lodSelection: [ { metricType: "maxScreenThreshold", maxError: 2 }, { metricType: "maxScreenThresholdSQ", maxError: 4 } ], children: [], featureData: [ { href: "mockFeatureDataUrl" } ], geometryData: [ { href: "mockGeometryDataUrl" } ] }; const nodeWithTexturedContent = { id: 1, level: 1, mbs: [-90, 45, 0, 14144.3451598], lodSelection: [ { metricType: "maxScreenThreshold", maxError: 2 }, { metricType: "maxScreenThresholdSQ", maxError: 4 } ], children: [], featureData: [ { href: "mockFeatureDataUrl" } ], geometryData: [ { href: "mockGeometryDataUrl" } ], textureData: [ { href: "mockTextureDataUrl" } ] }; const mockMesh = { attribute: { resource: 1 }, geometry: { definition: 0, featureCount: 2, resource: 1, vertexCount: 6 }, material: { definition: 0, resource: 1 } }; const mockMeshWithMaterial = { attribute: { resource: 2 }, geometry: { definition: 0, featureCount: 2, resource: 2, vertexCount: 6 }, material: { definition: 1, resource: 2 } }; const rootNodePageEntry = { index: 0, children: [1, 2], obb: { center: [-90, 45, 0], halfSize: [2e4, 2e4, 500], quaternion: [1, 0, 0, 0] } }; const childNodePageEntry = { index: 1, children: [], obb: { center: [-90, 45, 0], halfSize: [1e4, 1e4, 250], quaternion: [1, 0, 0, 0] }, lodThreshold: 500, parentIndex: 0, mesh: mockMesh }; const texturedChildNodePageEntry = { index: 2, children: [], obb: { center: [-90, 45, 0], halfSize: [1e4, 1e4, 250], quaternion: [1, 0, 0, 0] }, lodThreshold: 500, parentIndex: 0, mesh: mockMeshWithMaterial }; const nodeData = { nodes: [rootNodePageEntry, childNodePageEntry, texturedChildNodePageEntry] }; const base64ToArrayBuffer = function(base64String) { const byteString = atob(base64String); const buffer = new ArrayBuffer(byteString.length); const view = new Uint8Array(buffer); for (let i = 0; i < byteString.length; i++) { view[i] = byteString.charCodeAt(i); } return buffer; }; const int8AttrBufferBase64 = "AgAAAAEC"; const int16AttrBufferBase64 = "AgAAAAEAAgA="; const int32AttrBufferBase64 = "AgAAAAEAAAD/////"; const int64AttrBufferBase64 = "AgAAAAAAAAABAAAAAAAAAP//////////"; const float32AttrBufferBase64 = "AgAAAAAAgD8AAABA"; const float64AttrBufferBase64 = "AgAAAAAAAAAAAAAAAADwPwAAAAAAAABA"; const stringAttrBufferBase64 = "AgAAABAAAAAEAAAABAAAAGFiYwBkZWYA"; const attrStorageInfo = [ { attributeValues: { valueType: "UInt8", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_0", name: "testUInt8", ordering: ["attributeValues"] }, { attributeValues: { valueType: "Int8", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_1", name: "testInt8", ordering: ["attributeValues"] }, { attributeValues: { valueType: "UInt16", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_2", name: "testUInt16", ordering: ["attributeValues"] }, { attributeValues: { valueType: "Int16", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_3", name: "testInt16", ordering: ["attributeValues"] }, { attributeValues: { valueType: "Oid32", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_4", name: "testOid32", ordering: ["attributeValues"] }, { attributeValues: { valueType: "UInt32", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_5", name: "testUInt32", ordering: ["attributeValues"] }, { attributeValues: { valueType: "Int32", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_6", name: "testInt32", ordering: ["attributeValues"] }, { attributeValues: { valueType: "UInt64", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_7", name: "testUInt64", ordering: ["attributeValues"] }, { attributeValues: { valueType: "Int64", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_8", name: "testInt64", ordering: ["attributeValues"] }, { attributeValues: { valueType: "Float32", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_9", name: "testFloat32", ordering: ["attributeValues"] }, { attributeValues: { valueType: "Float64", valuesPerElement: 1 }, header: [{ property: "count", valueType: "UInt32" }], key: "f_10", name: "testFloat64", ordering: ["attributeValues"] }, { attributeByteCounts: { valueType: "UInt32", valuesPerElement: 1 }, attributeValues: { valueType: "String", valuesPerElement: 1, encoding: "UTF-8" }, header: [ { property: "count", valueType: "UInt32" }, { property: "attributeValuesByteCount", valueType: "UInt32" } ], key: "f_11", name: "testString", ordering: ["attributeByteCounts", "attributeValues"] } ]; const layerData = { href: "mockLayerUrl", layerType: "3DObject", nodePages: { lodSelectionMetricType: "maxScreenThresholdSQ", nodesPerPage: 64 }, attributeStorageInfo: attrStorageInfo, store: { defaultGeometrySchema: {}, version: "1.7" }, materialDefinitions: [ { doubleSided: true, pbrMetallicRoughness: { metallicFactor: 0, baseColorFactor: [1, 1, 1, 1] }, emissiveFactor: [0, 0, 0] }, { doubleSided: true, pbrMetallicRoughness: { baseColorTexture: { textureSetDefinitionId: 0 }, metallicFactor: 0 } } ], textureSetDefinitions: [ { formats: [ { name: "0", format: "dds" }, { name: "1", format: "jpg" } ] } ], spatialReference: { wkid: 4326 }, drawingInfo: { renderer: { type: "simple", symbol: { symbolLayers: [ { type: "Fill", edges: { color: [255, 255, 255], tranparency: 0 } } ] } } } }; const layerDataWithoutNodePages = { href: "mockLayerUrl", layerType: "3DObject", attributeStorageInfo: attrStorageInfo, store: { defaultGeometrySchema: {}, version: "1.6" }, materialDefinitions: [ { doubleSided: true, pbrMetallicRoughness: { metallicFactor: 0 } }, { doubleSided: true, pbrMetallicRoughness: { baseColorTexture: { textureSetDefinitionId: 0 }, metallicFactor: 0 } } ], textureSetDefinitions: [ { formats: [ { name: "0", format: "dds" }, { name: "1", format: "jpg" } ] } ], spatialReference: { wkid: 4326 } }; async function createMockProvider(url, layerData2, geoidDataList2, options) { spyOn(import__511.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(layerData2) ); spyOn(import__511.Cesium3DTileset, "fromUrl").and.callFake(async () => { const tileset = new import__511.Cesium3DTileset(); tileset._root = {}; tileset._isI3STileSet = true; return tileset; }); const mockI3SProvider = await import__511.I3SDataProvider.fromUrl(url, options); mockI3SProvider._geoidDataList = geoidDataList2; return mockI3SProvider; } async function createMockLayer(providerUrl, layerData2, geoidDataList2, options) { const provider = await createMockProvider( providerUrl, layerData2, geoidDataList2, options ); const mockI3SLayer = provider.layers[0]; mockI3SLayer._geometryDefinitions = [ [ { index: 0, compressed: false, attributes: ["position"] }, { index: 1, compressed: false, attributes: [ "position", "normal", "uv0", "color", "featureId", "faceRange" ] } ] ]; return mockI3SLayer; } it("constructs nodes", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const rootNode = new import__511.I3SNode( mockI3SLayerWithoutNodePages, "mockRootUrl", true ); expect(rootNode.resource.url).toContain( "mockProviderUrl/mockLayerUrl/mockRootUrl/" ); expect(rootNode.parent).toEqual(mockI3SLayerWithoutNodePages); expect(rootNode.layer).toEqual(mockI3SLayerWithoutNodePages); expect(rootNode._level).toEqual(0); const childNode = new import__511.I3SNode(rootNode, 3, false); expect(childNode.resource).toBeUndefined(); expect(childNode.parent).toEqual(rootNode); expect(childNode.layer).toEqual(mockI3SLayerWithoutNodePages); expect(childNode._nodeIndex).toEqual(3); expect(childNode._level).toEqual(1); }); const customAttributes = { cartesianCenter: import__511.Ellipsoid.WGS84.cartographicToCartesian( new import__511.Cartographic(-90, 45, 0) ), featureIndex: new Uint32Array([0, 0, 1, 1]), positions: new Float32Array([ -20, -20, 0, 20, 0, 0, -20, 0, 0, -20, -20, 0, 20, -20, 0, 20, 0, 0, -20, 0, 0, 20, 20, 0, -20, 20, 0, -20, 0, 0, 20, 0, 0, 20, 20, 0 ]), parentRotation: [1, 0, 0, 0, 1, 0, 0, 0, 1] }; const customAttributesIndexed = { cartesianCenter: import__511.Ellipsoid.WGS84.cartographicToCartesian( new import__511.Cartographic(-90, 45, 0) ), featureIndex: new Uint32Array([0, 0, 1, 1]), indices: new Uint32Array([0, 1, 2, 0, 3, 1, 2, 4, 5, 2, 1, 4]), positions: new Float32Array([ -20, -20, 0, 20, 0, 0, -20, 0, 0, 20, -20, 0, 20, 20, 0, -20, 20, 0 ]), parentRotation: [1, 0, 0, 0, 1, 0, 0, 0, 1] }; const intersectPoint = new import__511.Cartesian3( -19 + customAttributes.cartesianCenter.x, -19 + customAttributes.cartesianCenter.y, 0 + customAttributes.cartesianCenter.z ); const borderPoint = new import__511.Cartesian3( 20 + customAttributes.cartesianCenter.x, 15 + customAttributes.cartesianCenter.y, 0 + customAttributes.cartesianCenter.z ); const floatingIntersectPoint = new import__511.Cartesian3( -19 + customAttributes.cartesianCenter.x, 19 + customAttributes.cartesianCenter.y, 2 + customAttributes.cartesianCenter.z ); const noIntersectPoint = new import__511.Cartesian3( -21 + customAttributes.cartesianCenter.x, -21 + customAttributes.cartesianCenter.y, 0 + customAttributes.cartesianCenter.z ); const i3sGeometryData = { meshData: { nodesInScene: [0], nodes: [{ mesh: 0 }], meshes: [ { primitives: [ { attributes: { POSITION: 0, NORMAL: 1, TEXCOORD_0: 2 }, indices: 4, material: 0 } ] } ], buffers: [ { byteLength: 336, uri: "i3sMockBufferUrl" } ], bufferViews: [ { buffer: 0, byteLength: 108, byteOffset: 48, target: 34962 }, { buffer: 0, byteLength: 108, byteOffset: 156, target: 34962 }, { buffer: 0, byteLength: 72, byteOffset: 264, target: 34962 }, { buffer: 0, byteLength: 48, byteOffset: 0, target: 34963 } ], accessors: [ { bufferView: 0, byteOffset: 0, componentType: 5126, count: 9, max: [20, 20, 0], min: [-20, -20, 0], type: "VEC3" }, { bufferView: 1, byteOffset: 0, componentType: 5126, count: 9, max: [0, 0, 1], min: [0, 0, 1], type: "VEC3" }, { bufferView: 2, byteOffset: 0, componentType: 5126, count: 9, max: [0, 1], min: [0, 1], type: "VEC2" }, { bufferView: 3, byteOffset: 0, componentType: 5125, count: 12, max: [8], min: [0], type: "SCALAR" } ], customAttributes } }; it("loads root node from uri", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const rootNode = new import__511.I3SNode(mockI3SLayerWithoutNodePages, "mockUrl", true); const spy = spyOn(import__511.I3SDataProvider, "loadJson").and.returnValue( Promise.resolve(rootNodeWithChildren) ); return rootNode.load().then(function() { expect(spy).toHaveBeenCalledWith(rootNode.resource); expect(rootNode.data.children.length).toEqual(2); }); }); it("loads child node from uri", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const rootNode = new import__511.I3SNode(mockI3SLayerWithoutNodePages, "mockUrl", true); const childNode = new import__511.I3SNode(rootNode, "mockUrlChild", false); const spy = spyOn(import__511.I3SDataProvider, "loadJson").and.returnValue( Promise.resolve(nodeWithContent) ); return rootNode.load().then(function() { return childNode.load(); }).then(function() { expect(spy).toHaveBeenCalledWith(childNode.resource); expect(childNode.data.children.length).toEqual(0); expect(childNode.tile).toBeDefined(); expect(childNode.tile.i3sNode).toBe(childNode); }); }); it("loads root from node pages", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 0, true); return rootNode.load().then(function() { expect(rootNode.data.children.length).toEqual(2); expect(rootNode.data.mesh).toBeUndefined(); }); }); it("loads node from node pages", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 0, true); const childNode = new import__511.I3SNode(rootNode, 1, false); return rootNode.load().then(function() { return childNode.load(); }).then(function() { expect(childNode.data.children.length).toEqual(0); expect(childNode.data.mesh).toBeDefined(); }); }); it("loads node with geoid conversion", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerGeoid = await createMockLayer( "mockProviderUrl?testQuery=test", layerData, geoidDataList ); const rootNode = new import__511.I3SNode(mockI3SLayerGeoid, 0, true); const childNode = new import__511.I3SNode(rootNode, 1, false); return rootNode.load().then(function() { return childNode.load(); }).then(function() { expect(childNode.data.children.length).toEqual(0); expect(childNode.data.mesh).toBeDefined(); const nodeOrigin = new import__511.Cartesian3( childNode._globalTransform[3], childNode._globalTransform[7], childNode._globalTransform[11] ); const cartographicOrigin = import__511.Ellipsoid.WGS84.cartesianToCartographic( nodeOrigin ); const expectedHeight = 10; const expectedPosition = new import__511.Cartographic( import__511.Math.toRadians(-90), import__511.Math.toRadians(45), expectedHeight ); expect(cartographicOrigin.longitude).toBeCloseTo( expectedPosition.longitude, -3 ); expect(cartographicOrigin.latitude).toBeCloseTo( expectedPosition.latitude, -3 ); expect(cartographicOrigin.height).toBeCloseTo( expectedPosition.height, -3 ); }); }); it("loads children", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 0, true); const mockCesiumTilesetRootTile = { children: [], computedTransform: new import__511.Matrix4(), _initialTransform: new import__511.Matrix4(), geometricError: 1, refine: import__511.Cesium3DTileRefine.REPLACE }; rootNode._tile = mockCesiumTilesetRootTile; return rootNode.load().then(function() { return rootNode._loadChildren(); }).then(function() { expect(rootNode.children.length).toEqual(2); expect(rootNode.children[0].data.index).toEqual(1); expect(rootNode.children[1].data.index).toEqual(2); }); }); it("loads children for leaf node", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const nodeWithoutChildren = new import__511.I3SNode(mockI3SLayerWithNodePages, 1, true); return nodeWithoutChildren.load().then(function() { return nodeWithoutChildren._loadChildren(); }).then(function() { expect(nodeWithoutChildren.children.length).toEqual(0); }); }); it("loads not existing fields", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 1, true); spyOn(rootNode._dataProvider, "_loadBinary").and.callFake(function(resource) { return new Promise(function(resolve, reject) { let resultBuffer = ""; if (resource.url.includes("f_0/") || resource.url.includes("f_1/")) { resultBuffer = int8AttrBufferBase64; } else if (resource.url.includes("f_2/") || resource.url.includes("f_3/")) { resultBuffer = int16AttrBufferBase64; } else if (resource.url.includes("f_4/") || resource.url.includes("f_5/") || resource.url.includes("f_6/")) { resultBuffer = int32AttrBufferBase64; } else if (resource.url.includes("f_7/") || resource.url.includes("f_8/")) { resultBuffer = int64AttrBufferBase64; } else if (resource.url.includes("f_9/")) { resultBuffer = float32AttrBufferBase64; } else if (resource.url.includes("f_10/")) { resultBuffer = float64AttrBufferBase64; } else if (resource.url.includes("f_11/")) { resultBuffer = stringAttrBufferBase64; } resolve(base64ToArrayBuffer(resultBuffer)); }); }); return rootNode.load().then(function() { return rootNode.loadFields(); }).then(function() { expect(rootNode.fields.testInt8.name).toEqual("testInt8"); expect(rootNode.fields.testInt8.resource.url).toContain( "mockProviderUrl/mockLayerUrl/nodes/1/attributes/f_1/0" ); expect( rootNode.fields.testInt8.resource.queryParameters.testQuery ).toEqual("test"); expect(rootNode.fields.testInt8.header.count).toEqual(2); expect(rootNode.fields.testUInt8.header.count).toEqual(2); expect(rootNode.fields.testInt16.header.count).toEqual(2); expect(rootNode.fields.testUInt16.header.count).toEqual(2); expect(rootNode.fields.testInt32.header.count).toEqual(2); expect(rootNode.fields.testUInt32.header.count).toEqual(2); expect(rootNode.fields.testInt64.header.count).toEqual(2); expect(rootNode.fields.testUInt64.header.count).toEqual(2); expect(rootNode.fields.testFloat32.header.count).toEqual(2); expect(rootNode.fields.testFloat32.values[0]).toEqual(1); expect(rootNode.fields.testFloat32.values[1]).toEqual(2); expect(rootNode.fields.testFloat64.header.count).toEqual(2); expect(rootNode.fields.testFloat64.values[0]).toEqual(1); expect(rootNode.fields.testFloat64.values[1]).toEqual(2); expect(rootNode.fields.testString.header.count).toEqual(2); expect( rootNode.fields.testString.header.attributeValuesByteCount ).toEqual(16); const featureFields0 = rootNode.getFieldsForFeature(0); const featureFields1 = rootNode.getFieldsForFeature(1); expect(featureFields0.testInt8).toEqual(1); expect(featureFields1.testInt8).toEqual(2); expect(featureFields0.testUInt8).toEqual(1); expect(featureFields1.testUInt8).toEqual(2); expect(featureFields0.testInt16).toEqual(1); expect(featureFields1.testInt16).toEqual(2); expect(featureFields0.testUInt16).toEqual(1); expect(featureFields1.testUInt16).toEqual(2); expect(featureFields0.testInt32).toEqual(1); expect(featureFields1.testInt32).toEqual(-1); expect(featureFields0.testUInt32).toEqual(1); expect(featureFields1.testUInt32).toEqual(Math.pow(2, 32) - 1); expect(featureFields0.testInt64).toEqual(1); expect(featureFields1.testInt64).toEqual(-1); expect(featureFields0.testUInt64).toEqual(1); expect(featureFields1.testUInt64).toEqual(Math.pow(2, 64)); expect(featureFields0.testString).toEqual("abc"); expect(featureFields1.testString).toEqual("def"); }); }); it("loads existing fields", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); spyOn(import__511.I3SField.prototype, "load").and.returnValue( Promise.resolve({ mockResult: "success" }) ); const mockLayerData = (0, import__511.clone)(layerData, true); mockLayerData.attributeStorageInfo = [{ name: "testField" }]; const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", mockLayerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 1, true); rootNode._data = { mesh: { attribute: { resource: new import__511.Resource({ url: "mockUrl" }) } } }; rootNode._fields = { testField: new import__511.I3SField(rootNode, { key: "mockKey" }) }; return rootNode.loadFields().then(function(result) { expect(result).toEqual([{ mockResult: "success" }]); }); }); it("loads existing fields without storageInfo", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockLayerData = (0, import__511.clone)(layerData, true); delete mockLayerData.attributeStorageInfo; const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", mockLayerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 1, true); return rootNode.loadFields().then(function(result) { expect(result).toEqual([]); }); }); it("loads existing field", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); spyOn(import__511.I3SField.prototype, "load").and.returnValue( Promise.resolve({ mockResult: "success" }) ); const mockLayerData = (0, import__511.clone)(layerData, true); mockLayerData.attributeStorageInfo = [{ name: "testField" }]; const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", mockLayerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 1, true); rootNode._data = { mesh: { attribute: { resource: new import__511.Resource({ url: "mockUrl" }) } } }; rootNode._fields = { testField: new import__511.I3SField(rootNode, { key: "mockKey" }) }; return rootNode.loadField("testField").then(function(result) { expect(result).toEqual({ mockResult: "success" }); }); }); it("loads not existing field without storageInfo for the layer", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockLayerData = (0, import__511.clone)(layerData, true); delete mockLayerData.attributeStorageInfo; const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", mockLayerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 1, true); return rootNode.loadField("test").then(function(result) { expect(result).toBeUndefined(); }); }); it("loads not existing field without storageInfo for the field", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockLayerData = (0, import__511.clone)(layerData, true); mockLayerData.attributeStorageInfo = [{ name: "testField" }]; const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", mockLayerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 1, true); return rootNode.loadField("test").then(function(result) { expect(result).toBeUndefined(); }); }); it("loads geometry from node pages", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const nodeWithMesh = new import__511.I3SNode(mockI3SLayerWithNodePages, 1, true); spyOn(nodeWithMesh._dataProvider, "_loadBinary").and.returnValue( Promise.resolve(new ArrayBuffer()) ); return nodeWithMesh.load().then(function() { return nodeWithMesh._loadGeometryData(); }).then(function(result) { expect(nodeWithMesh.geometryData.length).toEqual(1); expect(nodeWithMesh.geometryData[0].resource.url).toContain( "mockProviderUrl/mockLayerUrl/nodes/1/geometries/1" ); expect( nodeWithMesh.geometryData[0].resource.queryParameters.testQuery ).toEqual("test"); expect(nodeWithMesh._dataProvider._loadBinary).toHaveBeenCalledWith( nodeWithMesh.geometryData[0].resource ); expect(nodeWithMesh.geometryData[0]._geometryBufferInfo.index).toEqual( 1 ); expect(nodeWithMesh.geometryData[0]._geometryDefinitions).toBeDefined(); expect(nodeWithMesh.geometryData[0].data).toEqual(new ArrayBuffer()); }); }); it("loads geometry from url", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const nodeWithMesh = new import__511.I3SNode( mockI3SLayerWithoutNodePages, "mockNodeUrl", true ); spyOn(import__511.I3SDataProvider, "loadJson").and.returnValue( Promise.resolve(nodeWithContent) ); spyOn(nodeWithMesh._dataProvider, "_loadBinary").and.returnValue( Promise.resolve(new ArrayBuffer()) ); return nodeWithMesh.load().then(function() { return nodeWithMesh._loadGeometryData(); }).then(function(result) { expect(nodeWithMesh.geometryData.length).toEqual(1); expect(nodeWithMesh.geometryData[0].resource.url).toContain( "mockProviderUrl/mockLayerUrl/mockNodeUrl/mockGeometryDataUrl" ); expect(nodeWithMesh._dataProvider._loadBinary).toHaveBeenCalledWith( nodeWithMesh.geometryData[0].resource ); expect(nodeWithMesh.geometryData[0].data).toEqual(new ArrayBuffer()); }); }); it("loads not existing geometry", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 1, true); rootNode._data = {}; return rootNode._loadGeometryData().then(function(result) { expect(result).toEqual([]); }); }); it("generate geometry from node pages", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const nodeWithTexturedMesh = new import__511.I3SNode( mockI3SLayerWithNodePages, 1, true ); spyOn(nodeWithTexturedMesh._dataProvider, "_loadBinary").and.returnValue( Promise.resolve(new ArrayBuffer()) ); return nodeWithTexturedMesh.load().then(function() { return nodeWithTexturedMesh._loadGeometryData(); }).then(function(result) { const rawGltf = nodeWithTexturedMesh.geometryData[0]._generateGltf( i3sGeometryData.meshData.nodesInScene, i3sGeometryData.meshData.nodes, i3sGeometryData.meshData.meshes, i3sGeometryData.meshData.buffers, i3sGeometryData.meshData.bufferViews, i3sGeometryData.meshData.accessors ); expect(rawGltf.scene).toEqual(0); expect(rawGltf.scenes.length).toEqual(1); expect(rawGltf.nodes).toEqual(i3sGeometryData.meshData.nodes); expect(rawGltf.meshes).toEqual(i3sGeometryData.meshData.meshes); expect(rawGltf.buffers).toEqual(i3sGeometryData.meshData.buffers); expect(rawGltf.bufferViews).toEqual( i3sGeometryData.meshData.bufferViews ); expect(rawGltf.accessors).toEqual(i3sGeometryData.meshData.accessors); expect(rawGltf.textures).toEqual([]); expect(rawGltf.samplers).toEqual([]); expect(rawGltf.images).toEqual([]); expect(rawGltf.materials[0].alphaMode).toBeUndefined(); }); }); it("generate geometry from node pages with transparent material", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const nodeWithTexturedMesh = new import__511.I3SNode( mockI3SLayerWithNodePages, 1, true ); spyOn(nodeWithTexturedMesh._dataProvider, "_loadBinary").and.returnValue( Promise.resolve(new ArrayBuffer()) ); return nodeWithTexturedMesh.load().then(function() { return nodeWithTexturedMesh._loadGeometryData(); }).then(function(result) { const transparentI3sGeometryData = (0, import__511.clone)(i3sGeometryData, true); transparentI3sGeometryData.meshData.meshes[0].primitives[0].extra = { isTransparent: true }; transparentI3sGeometryData.meshData.meshes[0].primitives.push({ attributes: { POSITION: 0, NORMAL: 1, TEXCOORD_0: 2 }, indices: 4, material: 1, extra: { isTransparent: false } }); const rawGltf = nodeWithTexturedMesh.geometryData[0]._generateGltf( transparentI3sGeometryData.meshData.nodesInScene, transparentI3sGeometryData.meshData.nodes, transparentI3sGeometryData.meshData.meshes, transparentI3sGeometryData.meshData.buffers, transparentI3sGeometryData.meshData.bufferViews, transparentI3sGeometryData.meshData.accessors ); expect(rawGltf.scene).toEqual(0); expect(rawGltf.scenes.length).toEqual(1); expect(rawGltf.nodes).toEqual( transparentI3sGeometryData.meshData.nodes ); expect(rawGltf.meshes).toEqual( transparentI3sGeometryData.meshData.meshes ); expect(rawGltf.buffers).toEqual( transparentI3sGeometryData.meshData.buffers ); expect(rawGltf.bufferViews).toEqual( transparentI3sGeometryData.meshData.bufferViews ); expect(rawGltf.accessors).toEqual( transparentI3sGeometryData.meshData.accessors ); expect(rawGltf.textures).toEqual([]); expect(rawGltf.samplers).toEqual([]); expect(rawGltf.images).toEqual([]); expect(rawGltf.materials[0].alphaMode).toEqual("BLEND"); expect(rawGltf.materials[0].emissiveFactor).toEqual([0, 0, 0]); expect( rawGltf.materials[0].pbrMetallicRoughness.baseColorFactor ).toEqual([1, 1, 1, 1]); expect(rawGltf.materials[1].alphaMode).toBeUndefined(); }); }); it("generate geometry from node pages with transparent material when alpha mode is defined", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); mockI3SLayerWithNodePages._data.materialDefinitions[0].alphaMode = "blend"; mockI3SLayerWithNodePages._data.materialDefinitions[1].alphaMode = "blend"; const nodeWithTexturedMesh = new import__511.I3SNode( mockI3SLayerWithNodePages, 1, true ); spyOn(nodeWithTexturedMesh._dataProvider, "_loadBinary").and.returnValue( Promise.resolve(new ArrayBuffer()) ); return nodeWithTexturedMesh.load().then(function() { return nodeWithTexturedMesh._loadGeometryData(); }).then(function(result) { const transparentI3sGeometryData = (0, import__511.clone)(i3sGeometryData, true); transparentI3sGeometryData.meshData.meshes[0].primitives[0].extra = { isTransparent: true }; transparentI3sGeometryData.meshData.meshes[0].primitives.push({ attributes: { POSITION: 0, NORMAL: 1, TEXCOORD_0: 2 }, indices: 4, material: 1, extra: { isTransparent: false } }); const rawGltf = nodeWithTexturedMesh.geometryData[0]._generateGltf( transparentI3sGeometryData.meshData.nodesInScene, transparentI3sGeometryData.meshData.nodes, transparentI3sGeometryData.meshData.meshes, transparentI3sGeometryData.meshData.buffers, transparentI3sGeometryData.meshData.bufferViews, transparentI3sGeometryData.meshData.accessors ); expect(rawGltf.scene).toEqual(0); expect(rawGltf.scenes.length).toEqual(1); expect(rawGltf.nodes).toEqual( transparentI3sGeometryData.meshData.nodes ); expect(rawGltf.meshes).toEqual( transparentI3sGeometryData.meshData.meshes ); expect(rawGltf.buffers).toEqual( transparentI3sGeometryData.meshData.buffers ); expect(rawGltf.bufferViews).toEqual( transparentI3sGeometryData.meshData.bufferViews ); expect(rawGltf.accessors).toEqual( transparentI3sGeometryData.meshData.accessors ); expect(rawGltf.textures).toEqual([]); expect(rawGltf.samplers).toEqual([]); expect(rawGltf.images).toEqual([]); expect(rawGltf.materials[0].alphaMode).toEqual("BLEND"); expect(rawGltf.materials[1].alphaMode).toEqual("OPAQUE"); }); }); it("generate geometry from node pages without material", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const nodeWithTexturedMesh = new import__511.I3SNode( mockI3SLayerWithNodePages, 1, true ); spyOn(nodeWithTexturedMesh._dataProvider, "_loadBinary").and.returnValue( Promise.resolve(new ArrayBuffer()) ); return nodeWithTexturedMesh.load().then(function() { return nodeWithTexturedMesh._loadGeometryData(); }).then(function(result) { const copyI3sGeometryData = (0, import__511.clone)(i3sGeometryData, true); delete copyI3sGeometryData.meshData.meshes[0].primitives[0].material; const rawGltf = nodeWithTexturedMesh.geometryData[0]._generateGltf( copyI3sGeometryData.meshData.nodesInScene, copyI3sGeometryData.meshData.nodes, copyI3sGeometryData.meshData.meshes, copyI3sGeometryData.meshData.buffers, copyI3sGeometryData.meshData.bufferViews, copyI3sGeometryData.meshData.accessors ); expect(rawGltf.scene).toEqual(0); expect(rawGltf.scenes.length).toEqual(1); expect(rawGltf.nodes).toEqual(copyI3sGeometryData.meshData.nodes); expect(rawGltf.meshes).toEqual(copyI3sGeometryData.meshData.meshes); expect(rawGltf.buffers).toEqual(copyI3sGeometryData.meshData.buffers); expect(rawGltf.bufferViews).toEqual( copyI3sGeometryData.meshData.bufferViews ); expect(rawGltf.accessors).toEqual( copyI3sGeometryData.meshData.accessors ); expect(rawGltf.textures).toEqual([]); expect(rawGltf.samplers).toEqual([]); expect(rawGltf.images).toEqual([]); expect(rawGltf.materials).toEqual([]); }); }); it("generate textured geometry from node pages", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const nodeWithTexturedMesh = new import__511.I3SNode( mockI3SLayerWithNodePages, 2, true ); spyOn(nodeWithTexturedMesh._dataProvider, "_loadBinary").and.returnValue( Promise.resolve(new ArrayBuffer()) ); return nodeWithTexturedMesh.load().then(function() { return nodeWithTexturedMesh._loadGeometryData(); }).then(function(result) { const rawGltf = nodeWithTexturedMesh.geometryData[0]._generateGltf( i3sGeometryData.meshData.nodesInScene, i3sGeometryData.meshData.nodes, i3sGeometryData.meshData.meshes, i3sGeometryData.meshData.buffers, i3sGeometryData.meshData.bufferViews, i3sGeometryData.meshData.accessors ); expect(rawGltf.textures).toBeDefined(); expect(rawGltf.textures.length).toEqual(1); expect(rawGltf.textures[0].sampler).toEqual(0); expect(rawGltf.textures[0].source).toEqual(0); expect(rawGltf.samplers).toBeDefined(); expect(rawGltf.samplers.length).toEqual(1); expect(rawGltf.images).toBeDefined(); expect(rawGltf.images.length).toEqual(1); expect(rawGltf.images[0].uri).toContain( "mockProviderUrl/mockLayerUrl/nodes/2/textures/1?testQuery=test" ); }); }); it("generate textured geometry from url", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const nodeWithTexturedMesh = new import__511.I3SNode( mockI3SLayerWithoutNodePages, "mockNodeUrl", true ); spyOn(import__511.I3SDataProvider, "loadJson").and.returnValue( Promise.resolve(nodeWithTexturedContent) ); spyOn(nodeWithTexturedMesh._dataProvider, "_loadBinary").and.returnValue( Promise.resolve(new ArrayBuffer()) ); return nodeWithTexturedMesh.load().then(function() { return nodeWithTexturedMesh._loadGeometryData(); }).then(function(result) { const rawGltf = nodeWithTexturedMesh.geometryData[0]._generateGltf( i3sGeometryData.meshData.nodesInScene, i3sGeometryData.meshData.nodes, i3sGeometryData.meshData.meshes, i3sGeometryData.meshData.buffers, i3sGeometryData.meshData.bufferViews, i3sGeometryData.meshData.accessors ); expect(rawGltf.textures).toBeDefined(); expect(rawGltf.textures.length).toEqual(1); expect(rawGltf.textures[0].sampler).toEqual(0); expect(rawGltf.textures[0].source).toEqual(0); expect(rawGltf.samplers).toBeDefined(); expect(rawGltf.samplers.length).toEqual(1); expect(rawGltf.images).toBeDefined(); expect(rawGltf.images.length).toEqual(1); expect(rawGltf.images[0].uri).toContain( "mockProviderUrl/mockLayerUrl/mockNodeUrl/mockTextureDataUrl" ); }); }); it("load geometry rejects invalid url", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const nodeWithMesh = new import__511.I3SNode(mockI3SLayerWithNodePages, 1, true); return nodeWithMesh.load().then(function() { return nodeWithMesh._loadGeometryData(); }).then(function() { fail("Promise should not be resolved for invalid uri"); }).catch(function(error) { expect(error.statusCode).toEqual(404); }); }); it("loads feature data from uri", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const nodeWithMesh = new import__511.I3SNode( mockI3SLayerWithoutNodePages, "mockNodeUrl", true ); const spy = spyOn(import__511.I3SDataProvider, "loadJson").and.callFake(function(resource) { if (resource.getUrlComponent().endsWith( "mockProviderUrl/mockLayerUrl/mockNodeUrl/mockFeatureDataUrl" )) { return Promise.resolve({ featureData: [], geometryData: [] }); } if (resource.getUrlComponent().endsWith("mockProviderUrl/mockLayerUrl/mockNodeUrl/")) { return Promise.resolve(nodeWithContent); } return Promise.reject("invalid i3s node"); }); return nodeWithMesh.load().then(function() { return nodeWithMesh._loadFeatureData(); }).then(function(result) { expect(nodeWithMesh.featureData.length).toEqual(1); expect(nodeWithMesh.featureData[0].resource.url).toContain( "mockProviderUrl/mockLayerUrl/mockNodeUrl/mockFeatureDataUrl" ); expect(nodeWithMesh.featureData[0].data.featureData).toEqual([]); expect(nodeWithMesh.featureData[0].data.geometryData).toEqual([]); expect(spy).toHaveBeenCalledWith(nodeWithMesh.featureData[0].resource); }); }); it("loads feature data from node pages", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const nodeWithMesh = new import__511.I3SNode(mockI3SLayerWithNodePages, 1, true); return nodeWithMesh.load().then(function() { return nodeWithMesh._loadFeatureData(); }).then(function(result) { expect(nodeWithMesh.featureData.length).toEqual(0); }); }); it("load feature data rejects invalid url", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl", layerDataWithoutNodePages ); const nodeWithMesh = new import__511.I3SNode( mockI3SLayerWithoutNodePages, "mockNodeUrl", true ); spyOn(import__511.I3SDataProvider, "loadJson").and.callFake(function(resource) { if (resource.getUrlComponent().endsWith( "mockProviderUrl/mockLayerUrl/mockNodeUrl/mockFeatureDataUrl" )) { return Promise.reject({ statusCode: 404 }); } if (resource.getUrlComponent().endsWith("mockProviderUrl/mockLayerUrl/mockNodeUrl/")) { return Promise.resolve(nodeWithContent); } return Promise.reject("invalid i3s node"); }); await nodeWithMesh.load(); await expectAsync(nodeWithMesh._loadFeatureData()).toBeRejected(); }); it("creates 3d tile content", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 0, true); const nodeWithMesh = new import__511.I3SNode(rootNode, 1, false); spyOn(nodeWithMesh._dataProvider, "_loadBinary").and.returnValue( Promise.resolve(new ArrayBuffer()) ); spyOn(nodeWithMesh, "_loadFeatureData").and.returnValue(Promise.all([])); spyOn(import__511.I3SDecoder, "decode").and.returnValue( Promise.resolve(i3sGeometryData) ); await rootNode.load(); await nodeWithMesh.load(); const result = await nodeWithMesh._createContentURL(); expect(result).toBeDefined(); expect(nodeWithMesh.tile).toBeDefined(); expect(import__511.I3SDecoder.decode).toHaveBeenCalledWith( jasmine.stringContaining( "mockProviderUrl/mockLayerUrl/nodes/1/geometries/1/?testQuery=test" ), jasmine.any(Object), jasmine.any(import__511.I3SGeometry), void 0, void 0 ); const data = await import__511.Resource.fetchArrayBuffer(result); expect(data.error).toBeUndefined(); const magic = new Uint8Array(data, 0, 4); const version = new Uint32Array(data, 4, 1); const length2 = new Uint32Array(data, 8, 1); const chunkType = new Uint8Array(data, 16, 4); expect(magic[0]).toEqual("g".charCodeAt()); expect(magic[1]).toEqual("l".charCodeAt()); expect(magic[2]).toEqual("T".charCodeAt()); expect(magic[3]).toEqual("F".charCodeAt()); expect(version[0]).toEqual(2); expect(length2[0]).toEqual(data.byteLength); expect(chunkType[0]).toEqual("J".charCodeAt()); expect(chunkType[1]).toEqual("S".charCodeAt()); expect(chunkType[2]).toEqual("O".charCodeAt()); expect(chunkType[3]).toEqual("N".charCodeAt()); }); it("picks closest point in geometry", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const nodeWithMesh = new import__511.I3SNode(mockI3SLayerWithNodePages, 1, true); spyOn(nodeWithMesh._dataProvider, "_loadBinary").and.returnValue( Promise.resolve(new ArrayBuffer()) ); return nodeWithMesh.load().then(function() { return nodeWithMesh._loadGeometryData(); }).then(function(result) { const geometryData = nodeWithMesh.geometryData[0]; geometryData._customAttributes = customAttributes; expect( geometryData.getClosestPointIndexOnTriangle( intersectPoint.x, intersectPoint.y, intersectPoint.z ).index ).toEqual(0); expect( geometryData.getClosestPointIndexOnTriangle( borderPoint.x, borderPoint.y, borderPoint.z ).index ).toEqual(11); expect( geometryData.getClosestPointIndexOnTriangle( floatingIntersectPoint.x, floatingIntersectPoint.y, floatingIntersectPoint.z ).index ).toEqual(8); expect( geometryData.getClosestPointIndexOnTriangle( noIntersectPoint.x, noIntersectPoint.y, noIntersectPoint.z ).index ).toEqual(-1); }); }); it("picks closest point in indexed geometry", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const nodeWithMesh = new import__511.I3SNode(mockI3SLayerWithNodePages, 1, true); spyOn(nodeWithMesh._dataProvider, "_loadBinary").and.returnValue( Promise.resolve(new ArrayBuffer()) ); return nodeWithMesh.load().then(function() { return nodeWithMesh._loadGeometryData(); }).then(function(result) { const geometryData = nodeWithMesh.geometryData[0]; geometryData._customAttributes = customAttributesIndexed; expect( geometryData.getClosestPointIndexOnTriangle( intersectPoint.x, intersectPoint.y, intersectPoint.z ).index ).toEqual(0); expect( geometryData.getClosestPointIndexOnTriangle( borderPoint.x, borderPoint.y, borderPoint.z ).index ).toEqual(4); expect( geometryData.getClosestPointIndexOnTriangle( floatingIntersectPoint.x, floatingIntersectPoint.y, floatingIntersectPoint.z ).index ).toEqual(5); expect( geometryData.getClosestPointIndexOnTriangle( noIntersectPoint.x, noIntersectPoint.y, noIntersectPoint.z ).index ).toEqual(-1); }); }); it("requests content", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 0, true); const childNode = new import__511.I3SNode(rootNode, 1, false); return rootNode.load().then(function() { return childNode.load(); }).then(function(result) { spyOn(childNode, "_createContentURL").and.callFake(function() { return Promise.resolve("mockGlbUrl"); }); spyOn(childNode.tile, "_hookedRequestContent"); return childNode.tile.requestContent(); }).then(function() { expect(childNode.tile._contentResource._url).toEqual("mockGlbUrl"); }); }); it("requests content without url", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 0, true); const childNode = new import__511.I3SNode(rootNode, 1, false); return rootNode.load().then(function() { return childNode.load(); }).then(function(result) { spyOn(childNode, "_createContentURL").and.callFake(function() { expect(childNode.tile._isLoading).toEqual(true); return Promise.resolve(void 0); }); return childNode.tile.requestContent(); }).then(function() { expect(childNode.tile._isLoading).toEqual(false); }); }); it("can filter by attributes", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); spyOn(import__511.I3SField.prototype, "load").and.callFake(function() { this["_values"] = { attributeValues: [1, 1, 2] }; return Promise.resolve(); }); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 0, true); const childNode = new import__511.I3SNode(rootNode, 1, false); const model = { ready: false, readyEvent: new import__511.Event() }; model.readyEvent.addEventListener(() => { model.ready = true; }); const content = { _model: model, batchTable: { features: [true, true, true], setAllShow: function(a) { }, setShow: function(a, b) { this.features[a] = b; }, featuresLength: 3 } }; const spy = spyOn(content.batchTable, "setAllShow"); return rootNode.load().then(function() { return childNode.load(); }).then(function(result) { childNode._geometryData = ["mocked geometry"]; childNode._layer._data.attributeStorageInfo = [{ name: "BldgLevel" }]; rootNode._children = [childNode]; mockI3SLayerWithNodePages._rootNode = rootNode; return mockI3SLayerWithNodePages._parent.filterByAttributes(); }).then(function() { spyOn(childNode, "_createContentURL").and.callFake(function() { return Promise.resolve("mockGlbUrl"); }); spyOn(childNode.tile, "_hookedRequestContent").and.callFake( function() { childNode._tile._content = content; return Promise.resolve(content); } ); return childNode.tile.requestContent(); }).then(function() { expect(spy).not.toHaveBeenCalled(); content._model.readyEvent.raiseEvent(content._model); expect(spy).toHaveBeenCalled(); return mockI3SLayerWithNodePages._parent.filterByAttributes([ { name: "BldgLevel", values: [2] } ]); }).then(function() { expect(content.batchTable.features).toEqual([false, false, true]); }); }); it("can filter by not existing attributes", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); spyOn(import__511.I3SField.prototype, "load").and.callFake(function() { this["_values"] = { attributeValues: [1, 1, 2] }; return Promise.resolve(); }); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 0, true); const childNode = new import__511.I3SNode(rootNode, 1, false); return rootNode.load().then(function() { return childNode.load(); }).then(function(result) { childNode._geometryData = ["mocked geometry"]; childNode._tile._content = { _model: { ready: true } }; childNode._tile._content["batchTable"] = { features: [true, true, true], setAllShow: function(a) { }, setShow: function(a, b) { this.features[a] = b; }, featuresLength: 3 }; childNode._layer._data.attributeStorageInfo = [{ name: "BldgLevel" }]; rootNode._children = [childNode]; mockI3SLayerWithNodePages._rootNode = rootNode; return mockI3SLayerWithNodePages._parent.filterByAttributes([ { name: "NotExistingAttr", values: [2] } ]); }).then(function() { spyOn(childNode, "_createContentURL").and.callFake(function() { return Promise.resolve("mockGlbUrl"); }); spyOn(childNode.tile, "_hookedRequestContent"); return childNode.tile.requestContent(); }).then(function() { expect(childNode._tile.content.batchTable.features).toEqual([ false, false, false ]); }); }); it("filtering by attributes can handle filters without values", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); spyOn(import__511.I3SField.prototype, "load").and.callFake(function() { this["_values"] = { attributeValues: [1, 1, 2] }; return Promise.resolve(); }); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 0, true); const childNode = new import__511.I3SNode(rootNode, 1, false); return rootNode.load().then(function() { return childNode.load(); }).then(function(result) { childNode._geometryData = ["mocked geometry"]; childNode._tile._content = { _model: { ready: true } }; childNode._tile._content["batchTable"] = { features: [true, true, true], setAllShow: function(a) { }, setShow: function(a, b) { this.features[a] = b; }, featuresLength: 3 }; childNode._layer._data.attributeStorageInfo = [{ name: "BldgLevel" }]; rootNode._children = [childNode]; mockI3SLayerWithNodePages._rootNode = rootNode; return mockI3SLayerWithNodePages._parent.filterByAttributes([ { name: "BldgLevel" } ]); }).then(function() { spyOn(childNode, "_createContentURL").and.callFake(function() { return Promise.resolve("mockGlbUrl"); }); spyOn(childNode.tile, "_hookedRequestContent"); return childNode.tile.requestContent(); }).then(function() { expect(childNode._tile.content.batchTable.features).toEqual([ false, false, false ]); }); }); it("filtering by attributes can handle content with zero features length", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 0, true); const childNode = new import__511.I3SNode(rootNode, 1, false); return rootNode.load().then(function() { return childNode.load(); }).then(function(result) { childNode._geometryData = ["mocked geometry"]; childNode._tile._content = { _model: { ready: true } }; childNode._tile._content["batchTable"] = { features: [true, true, true], setShow: function(a, b) { this.features[a] = b; }, featuresLength: 0 }; childNode._layer._data.attributeStorageInfo = [{ name: "BldgLevel" }]; rootNode._children = [childNode]; mockI3SLayerWithNodePages._rootNode = rootNode; return mockI3SLayerWithNodePages._parent.filterByAttributes([ { name: "BldgLevel", values: [2] } ]); }).then(function() { spyOn(childNode, "_createContentURL").and.callFake(function() { return Promise.resolve("mockGlbUrl"); }); spyOn(childNode.tile, "_hookedRequestContent"); return childNode.tile.requestContent(); }).then(function() { expect(childNode._tile.content.batchTable.features).toEqual([ true, true, true ]); }); }); it("filtering by attributes without filters", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); spyOn(import__511.I3SField.prototype, "load").and.returnValue(Promise.resolve()); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 0, true); const childNode = new import__511.I3SNode(rootNode, 1, false); return rootNode.load().then(function() { return childNode.load(); }).then(function(result) { childNode._geometryData = ["mocked geometry"]; childNode._tile._content = { _model: { ready: true } }; childNode._tile._content["batchTable"] = { features: [true, true, true], setAllShow: function(a) { }, setShow: function(a, b) { this.features[a] = b; }, featuresLength: 3 }; childNode._layer._data.attributeStorageInfo = [{ name: "BldgLevel" }]; rootNode._children = [childNode]; mockI3SLayerWithNodePages._rootNode = rootNode; return mockI3SLayerWithNodePages._parent.filterByAttributes(); }).then(function() { spyOn(childNode, "_createContentURL").and.callFake(function() { return Promise.resolve("mockGlbUrl"); }); spyOn(childNode.tile, "_hookedRequestContent"); return childNode.tile.requestContent(); }).then(function() { expect(childNode._tile.content.batchTable.features).toEqual([ true, true, true ]); }); }); it("filtering by attributes can handle fields without values", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); spyOn(import__511.I3SField.prototype, "load").and.returnValue(Promise.resolve()); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 0, true); const childNode = new import__511.I3SNode(rootNode, 1, false); return rootNode.load().then(function() { return childNode.load(); }).then(function(result) { childNode._geometryData = ["mocked geometry"]; childNode._tile._content = { _model: { ready: true } }; childNode._tile._content["batchTable"] = { features: [true, true, true], setAllShow: function(a) { }, setShow: function(a, b) { this.features[a] = b; }, featuresLength: 3 }; childNode._layer._data.attributeStorageInfo = [{ name: "BldgLevel" }]; rootNode._children = [childNode]; mockI3SLayerWithNodePages._rootNode = rootNode; return mockI3SLayerWithNodePages._parent.filterByAttributes([ { name: "BldgLevel", values: [2] } ]); }).then(function() { spyOn(childNode, "_createContentURL").and.callFake(function() { return Promise.resolve("mockGlbUrl"); }); spyOn(childNode.tile, "_hookedRequestContent"); return childNode.tile.requestContent(); }).then(function() { expect(childNode._tile.content.batchTable.features).toEqual([ false, false, false ]); }); }); it("generate feature url for indexed nodes", async function() { const layerResource = new import__511.Resource({ url: "testLayerUrl" }); const attributeResource = new import__511.Resource({ url: "testAttributeUrl" }); const i3sNode = { _nodeIndex: 0, _layer: { resource: layerResource }, _data: { mesh: { attribute: { resource: attributeResource } } } }; const i3sFeature = new import__511.I3SFeature(i3sNode, "testNode"); expect( i3sFeature._resource.url.endsWith( `nodes/${attributeResource.url}/testNode` ) ).toEqual(true); }); it("can clear node geometry data", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); spyOn(import__511.I3SField.prototype, "load").and.callFake(function() { this["_values"] = { attributeValues: [1, 1, 2] }; return Promise.resolve(); }); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 0, true); return rootNode.load().then(function() { rootNode._geometryData = ["mocked geometry"]; rootNode._clearGeometryData(); expect(rootNode.geometryData).toEqual([]); }); }); it("creates 3d tile content with symbology", async function() { spyOn(import__511.I3SLayer.prototype, "_loadNodePage").and.returnValue( Promise.resolve(nodeData) ); const mockI3SLayerWithNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerData, void 0, { applySymbology: true } ); const rootNode = new import__511.I3SNode(mockI3SLayerWithNodePages, 0, true); const nodeWithMesh = new import__511.I3SNode(rootNode, 1, false); spyOn(nodeWithMesh._dataProvider, "_loadBinary").and.returnValue( Promise.resolve(new ArrayBuffer()) ); spyOn(nodeWithMesh, "_loadFeatureData").and.returnValue(Promise.all([])); spyOn(import__511.I3SDecoder, "decode").and.returnValue( Promise.resolve(i3sGeometryData) ); await rootNode.load(); await nodeWithMesh.load(); await nodeWithMesh._createContentURL(); await nodeWithMesh._createContentURL(); expect(import__511.I3SDecoder.decode).toHaveBeenCalledTimes(2); expect(import__511.I3SDecoder.decode).toHaveBeenCalledWith( jasmine.stringContaining( "mockProviderUrl/mockLayerUrl/nodes/1/geometries/1/?testQuery=test" ), jasmine.any(Object), jasmine.any(import__511.I3SGeometry), void 0, jasmine.any(Object) ); }); it("creates 3d tile content without symbology", async function() { const mockI3SLayerWithoutNodePages = await createMockLayer( "mockProviderUrl?testQuery=test", layerDataWithoutNodePages, void 0, { applySymbology: true } ); const nodeWithMesh = new import__511.I3SNode( mockI3SLayerWithoutNodePages, "mockNodeUrl", true ); spyOn(import__511.I3SDataProvider, "loadJson").and.returnValue( Promise.resolve(nodeWithContent) ); spyOn(nodeWithMesh._dataProvider, "_loadBinary").and.returnValue( Promise.resolve(new ArrayBuffer()) ); spyOn(nodeWithMesh, "_loadFeatureData").and.returnValue(Promise.all([])); spyOn(import__511.I3SDecoder, "decode").and.returnValue( Promise.resolve(i3sGeometryData) ); await nodeWithMesh.load(); await nodeWithMesh._createContentURL(); expect(import__511.I3SDecoder.decode).toHaveBeenCalledWith( jasmine.stringContaining( "mockProviderUrl/mockLayerUrl/mockNodeUrl/mockGeometryDataUrl?testQuery=test" ), jasmine.any(Object), jasmine.any(import__511.I3SGeometry), void 0, jasmine.any(Object) ); }); }); // packages/engine/Specs/Scene/I3SSymbologySpec.js var import__512 = __toESM(require_Cesium(), 1); describe("Scene/I3SSymbology", function() { const defaultSymbol = { symbolLayers: [ { type: "Fill", edges: { color: [255, 255, 255], transparency: 0 }, material: { colorMixMode: "replace", color: [0, 0, 0], transparency: 10 } } ] }; const simpleSymbologyData = { data: { drawingInfo: { renderer: { type: "simple", symbol: defaultSymbol } } } }; const uniqueValueInfosSymbologyData = { data: { drawingInfo: { renderer: { type: "uniqueValue", defaultSymbol, field1: "c", uniqueValueInfos: [ { value: "c1", symbol: { symbolLayers: [ { type: "Fill", edges: { color: [255, 255, 255, 255] } } ] } }, { value: "c3", symbol: { symbolLayers: [ { type: "Fill", edges: {}, material: { colorMixMode: "replace" } } ] } } ] } } } }; const uniqueValueGroupsSymbologyData = { data: { drawingInfo: { renderer: { type: "uniqueValue", defaultSymbol, field1: "a", field2: "c", field3: "b", uniqueValueGroups: [ { classes: [ { values: [ [10, "c1", "b2"], [15, "c2", "b2"] ], symbol: { symbolLayers: [ { type: "Fill", edges: { color: [0, 0, 0] } } ] } }, { values: [[30, "c3", "b3"]], symbol: { symbolLayers: [ { type: "Fill", edges: { color: [0, 0, 0, 0] } } ] } } ] }, { classes: [ { values: [[10, "c1", "b1"]], symbol: { symbolLayers: [ { type: "Fill", material: { color: [0, 0, 0, 102] } } ] } } ] } ] } } } }; const classBreaksSymbologyData = { data: { drawingInfo: { renderer: { type: "classBreaks", defaultSymbol, field: "a", minValue: 12, classBreakInfos: [ { classMaxValue: 15, symbol: { symbolLayers: [ { type: "Fill", outline: { color: [0, 0, 0, 255] } } ] } }, { classMinValue: 20, classMaxValue: 25, symbol: { symbolLayers: [ { type: "Fill", outline: {} } ] } }, { classMinValue: 25, classMaxValue: 26, symbol: { symbolLayers: [ { type: "Fill", outline: { color: [0, 255, 0, 255] } } ] } }, { classMaxValue: 12, symbol: { symbolLayers: [ { type: "Fill", outline: { color: [0, 0, 255, 255] } } ] } }, { classMinValue: 17, symbol: { symbolLayers: [ { type: "Fill", outline: { color: [255, 0, 0, 255] } } ] } } ] } } } }; const nodeData = { loadField: function(n) { return Promise.resolve(); }, fields: { a: { values: [10, 15, 30] }, b: { values: ["b1", "b2", "b3", "b4"] }, c: { values: ["c1", "c2"] } } }; it("get simple symbology", async function() { const symbology = new import__512.I3SSymbology(simpleSymbologyData); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeDefined(); expect(symbology.defaultSymbology.edges).toBeDefined(); expect(symbology.defaultSymbology.edges.color).toEqual([1, 1, 1, 1]); expect(symbology.defaultSymbology.material).toBeDefined(); expect(symbology.defaultSymbology.material.colorMixMode).toEqual("replace"); expect(symbology.defaultSymbology.material.color).toEqual([0, 0, 0, 0.9]); expect(data).toBeDefined(); expect(data.default).toBeDefined(); expect(data.default.edges).toBeDefined(); expect(data.default.edges.color).toEqual([1, 1, 1, 1]); expect(data.default.material).toBeDefined(); expect(data.default.material.colorMixMode).toEqual("replace"); expect(data.default.material.color).toEqual([0, 0, 0, 0.9]); }); it("symbology without drawing info", async function() { const symbology = new import__512.I3SSymbology({ data: {} }); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeUndefined(); expect(data).toBeDefined(); expect(data.default).toBeUndefined(); }); it("symbology without renderer", async function() { const symbologyData = (0, import__512.clone)(simpleSymbologyData, true); symbologyData.data.drawingInfo = {}; const symbology = new import__512.I3SSymbology(symbologyData); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeUndefined(); expect(data).toBeDefined(); expect(data.default).toBeUndefined(); }); it("symbology with unsupported renderer", async function() { const symbologyData = (0, import__512.clone)(simpleSymbologyData, true); symbologyData.data.drawingInfo.renderer.type = "unsupported"; const symbology = new import__512.I3SSymbology(symbologyData); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeUndefined(); expect(data).toBeDefined(); expect(data.default).toBeUndefined(); }); it("symbology without symbol", async function() { const symbologyData = (0, import__512.clone)(simpleSymbologyData, true); symbologyData.data.drawingInfo.renderer.symbol = void 0; const symbology = new import__512.I3SSymbology(symbologyData); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeDefined(); expect(symbology.defaultSymbology.edges).toBeUndefined(); expect(symbology.defaultSymbology.material).toBeUndefined(); expect(data).toBeDefined(); expect(data.default).toBeDefined(); expect(data.default.edges).toBeUndefined(); expect(data.default.material).toBeUndefined(); }); it("symbology without symbol layers", async function() { const symbologyData = (0, import__512.clone)(simpleSymbologyData, true); symbologyData.data.drawingInfo.renderer.symbol = {}; const symbology = new import__512.I3SSymbology(symbologyData); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeDefined(); expect(symbology.defaultSymbology.edges).toBeUndefined(); expect(symbology.defaultSymbology.material).toBeUndefined(); expect(data).toBeDefined(); expect(data.default).toBeDefined(); expect(data.default.edges).toBeUndefined(); expect(data.default.material).toBeUndefined(); }); it("symbology with emtpy symbol layers", async function() { const symbologyData = (0, import__512.clone)(simpleSymbologyData, true); symbologyData.data.drawingInfo.renderer.symbol.symbolLayers = []; const symbology = new import__512.I3SSymbology(symbologyData); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeDefined(); expect(symbology.defaultSymbology.edges).toBeUndefined(); expect(symbology.defaultSymbology.material).toBeUndefined(); expect(data).toBeDefined(); expect(data.default).toBeDefined(); expect(data.default.edges).toBeUndefined(); expect(data.default.material).toBeUndefined(); }); it("symbology with unsupported symbol layer", async function() { const symbologyData = (0, import__512.clone)(simpleSymbologyData, true); symbologyData.data.drawingInfo.renderer.symbol.symbolLayers[0].type = "unsupported"; const symbology = new import__512.I3SSymbology(symbologyData); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeDefined(); expect(symbology.defaultSymbology.edges).toBeUndefined(); expect(symbology.defaultSymbology.material).toBeUndefined(); expect(data).toBeDefined(); expect(data.default).toBeDefined(); expect(data.default.edges).toBeUndefined(); expect(data.default.material).toBeUndefined(); }); it("symbology with empty cached drawing info", async function() { const symbologyData = (0, import__512.clone)(simpleSymbologyData, true); symbologyData.data.cachedDrawingInfo = {}; const symbology = new import__512.I3SSymbology(symbologyData); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeDefined(); expect(symbology.defaultSymbology.edges).toBeDefined(); expect(symbology.defaultSymbology.edges.color).toEqual([1, 1, 1, 1]); expect(symbology.defaultSymbology.material).toBeDefined(); expect(symbology.defaultSymbology.material.colorMixMode).toEqual("replace"); expect(symbology.defaultSymbology.material.color).toEqual([0, 0, 0, 0.9]); expect(data).toBeDefined(); expect(data.default).toBeDefined(); expect(data.default.edges).toBeDefined(); expect(data.default.edges.color).toEqual([1, 1, 1, 1]); expect(data.default.material).toBeDefined(); expect(data.default.material.colorMixMode).toEqual("replace"); expect(data.default.material.color).toEqual([0, 0, 0, 0.9]); }); it("symbology with cached drawing info for color", async function() { const symbologyData = (0, import__512.clone)(simpleSymbologyData, true); symbologyData.data.cachedDrawingInfo = { color: true }; const symbology = new import__512.I3SSymbology(symbologyData); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeDefined(); expect(symbology.defaultSymbology.edges).toBeDefined(); expect(symbology.defaultSymbology.edges.color).toEqual([1, 1, 1, 1]); expect(symbology.defaultSymbology.material).toBeUndefined(); expect(data).toBeDefined(); expect(data.default).toBeDefined(); expect(data.default.edges).toBeDefined(); expect(data.default.edges.color).toEqual([1, 1, 1, 1]); expect(data.default.material).toBeUndefined(); }); it("get unique values symbology by info", async function() { const symbology = new import__512.I3SSymbology(uniqueValueInfosSymbologyData); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeDefined(); expect(symbology.defaultSymbology.edges).toBeDefined(); expect(symbology.defaultSymbology.edges.color).toEqual([1, 1, 1, 1]); expect(symbology.defaultSymbology.material).toBeDefined(); expect(symbology.defaultSymbology.material.colorMixMode).toEqual("replace"); expect(symbology.defaultSymbology.material.color).toEqual([0, 0, 0, 0.9]); expect(data).toBeDefined(); expect(data.default).toBeDefined(); expect(data.default.edges).toBeDefined(); expect(data.default.edges.color).toEqual([1, 1, 1, 1]); expect(data.default.material).toBeDefined(); expect(data.default.material.colorMixMode).toEqual("replace"); expect(data.default.material.color).toEqual([0, 0, 0, 0.9]); expect(data[0]).toBeDefined(); expect(data[0].edges).toBeDefined(); expect(data[0].edges.color).toEqual([1, 1, 1, 1]); expect(data[0].material).toBeUndefined(); expect(data[1]).toBeUndefined(); expect(data[2]).toBeUndefined(); }); it("get unique values symbology without values", async function() { const symbologyData = (0, import__512.clone)(uniqueValueInfosSymbologyData, true); symbologyData.data.drawingInfo.renderer.uniqueValueInfos = void 0; const symbology = new import__512.I3SSymbology(symbologyData); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeDefined(); expect(symbology.defaultSymbology.edges).toBeDefined(); expect(symbology.defaultSymbology.edges.color).toEqual([1, 1, 1, 1]); expect(symbology.defaultSymbology.material).toBeDefined(); expect(symbology.defaultSymbology.material.colorMixMode).toEqual("replace"); expect(symbology.defaultSymbology.material.color).toEqual([0, 0, 0, 0.9]); expect(data).toBeDefined(); expect(data.default).toBeDefined(); expect(data.default.edges).toBeDefined(); expect(data.default.edges.color).toEqual([1, 1, 1, 1]); expect(data.default.material).toBeDefined(); expect(data.default.material.colorMixMode).toEqual("replace"); expect(data.default.material.color).toEqual([0, 0, 0, 0.9]); expect(data[0]).toBeUndefined(); expect(data[1]).toBeUndefined(); expect(data[2]).toBeUndefined(); }); it("get unique values symbology by group", async function() { const symbology = new import__512.I3SSymbology(uniqueValueGroupsSymbologyData); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeDefined(); expect(symbology.defaultSymbology.edges).toBeDefined(); expect(symbology.defaultSymbology.edges.color).toEqual([1, 1, 1, 1]); expect(symbology.defaultSymbology.material).toBeDefined(); expect(symbology.defaultSymbology.material.colorMixMode).toEqual("replace"); expect(symbology.defaultSymbology.material.color).toEqual([0, 0, 0, 0.9]); expect(data).toBeDefined(); expect(data.default).toBeDefined(); expect(data.default.edges).toBeDefined(); expect(data.default.edges.color).toEqual([1, 1, 1, 1]); expect(data.default.material).toBeDefined(); expect(data.default.material.colorMixMode).toEqual("replace"); expect(data.default.material.color).toEqual([0, 0, 0, 0.9]); expect(data[0]).toBeDefined(); expect(data[0].material).toBeDefined(); expect(data[0].material.colorMixMode).toBeUndefined(); expect(data[0].material.color).toEqual([0, 0, 0, 0.4]); expect(data[1]).toBeDefined(); expect(data[1].edges).toBeDefined(); expect(data[1].edges.color).toEqual([0, 0, 0, 1]); expect(data[1].material).toBeUndefined(); expect(data[2]).toBeUndefined(); }); it("get unique values symbology without classes", async function() { const symbologyData = (0, import__512.clone)(uniqueValueGroupsSymbologyData, true); symbologyData.data.drawingInfo.renderer.uniqueValueGroups = [{}]; const symbology = new import__512.I3SSymbology(symbologyData); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeDefined(); expect(symbology.defaultSymbology.edges).toBeDefined(); expect(symbology.defaultSymbology.edges.color).toEqual([1, 1, 1, 1]); expect(symbology.defaultSymbology.material).toBeDefined(); expect(symbology.defaultSymbology.material.colorMixMode).toEqual("replace"); expect(symbology.defaultSymbology.material.color).toEqual([0, 0, 0, 0.9]); expect(data).toBeDefined(); expect(data.default).toBeDefined(); expect(data.default.edges).toBeDefined(); expect(data.default.edges.color).toEqual([1, 1, 1, 1]); expect(data.default.material).toBeDefined(); expect(data.default.material.colorMixMode).toEqual("replace"); expect(data.default.material.color).toEqual([0, 0, 0, 0.9]); expect(data[0]).toBeUndefined(); expect(data[1]).toBeUndefined(); expect(data[2]).toBeUndefined(); }); it("get class breaks symbology", async function() { const symbology = new import__512.I3SSymbology(classBreaksSymbologyData); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeDefined(); expect(symbology.defaultSymbology.edges).toBeDefined(); expect(symbology.defaultSymbology.edges.color).toEqual([1, 1, 1, 1]); expect(symbology.defaultSymbology.material).toBeDefined(); expect(symbology.defaultSymbology.material.colorMixMode).toEqual("replace"); expect(symbology.defaultSymbology.material.color).toEqual([0, 0, 0, 0.9]); expect(data).toBeDefined(); expect(data.default).toBeDefined(); expect(data.default.edges).toBeDefined(); expect(data.default.edges.color).toEqual([1, 1, 1, 1]); expect(data.default.material).toBeDefined(); expect(data.default.material.colorMixMode).toEqual("replace"); expect(data.default.material.color).toEqual([0, 0, 0, 0.9]); expect(data[0]).toBeUndefined(); expect(data[1]).toBeDefined(); expect(data[1].edges).toBeDefined(); expect(data[1].edges.color).toEqual([0, 0, 0, 1]); expect(data[1].material).toBeUndefined(); expect(data[2]).toBeUndefined(); }); it("get class breaks symbology without min value", async function() { const symbologyData = (0, import__512.clone)(classBreaksSymbologyData, true); symbologyData.data.drawingInfo.renderer.minValue = void 0; const symbology = new import__512.I3SSymbology(symbologyData); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeDefined(); expect(symbology.defaultSymbology.edges).toBeDefined(); expect(symbology.defaultSymbology.edges.color).toEqual([1, 1, 1, 1]); expect(symbology.defaultSymbology.material).toBeDefined(); expect(symbology.defaultSymbology.material.colorMixMode).toEqual("replace"); expect(symbology.defaultSymbology.material.color).toEqual([0, 0, 0, 0.9]); expect(data).toBeDefined(); expect(data.default).toBeDefined(); expect(data.default.edges).toBeDefined(); expect(data.default.edges.color).toEqual([1, 1, 1, 1]); expect(data.default.material).toBeDefined(); expect(data.default.material.colorMixMode).toEqual("replace"); expect(data.default.material.color).toEqual([0, 0, 0, 0.9]); expect(data[0]).toBeDefined(); expect(data[0].edges).toBeDefined(); expect(data[0].edges.color).toEqual([0, 0, 1, 1]); expect(data[1].material).toBeUndefined(); expect(data[1]).toBeDefined(); expect(data[1].edges).toBeDefined(); expect(data[1].edges.color).toEqual([0, 0, 0, 1]); expect(data[1].material).toBeUndefined(); expect(data[2]).toBeUndefined(); }); it("get class breaks symbology without infos", async function() { const symbologyData = (0, import__512.clone)(classBreaksSymbologyData, true); symbologyData.data.drawingInfo.renderer.classBreakInfos = void 0; const symbology = new import__512.I3SSymbology(symbologyData); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeDefined(); expect(symbology.defaultSymbology.edges).toBeDefined(); expect(symbology.defaultSymbology.edges.color).toEqual([1, 1, 1, 1]); expect(symbology.defaultSymbology.material).toBeDefined(); expect(symbology.defaultSymbology.material.colorMixMode).toEqual("replace"); expect(symbology.defaultSymbology.material.color).toEqual([0, 0, 0, 0.9]); expect(data).toBeDefined(); expect(data.default).toBeDefined(); expect(data.default.edges).toBeDefined(); expect(data.default.edges.color).toEqual([1, 1, 1, 1]); expect(data.default.material).toBeDefined(); expect(data.default.material.colorMixMode).toEqual("replace"); expect(data.default.material.color).toEqual([0, 0, 0, 0.9]); expect(data[0]).toBeUndefined(); expect(data[1]).toBeUndefined(); expect(data[2]).toBeUndefined(); }); it("get class breaks symbology with empty infos", async function() { const symbologyData = (0, import__512.clone)(classBreaksSymbologyData, true); symbologyData.data.drawingInfo.renderer.classBreakInfos = []; symbologyData.data.drawingInfo.renderer.minValue = void 0; const symbology = new import__512.I3SSymbology(symbologyData); const data = await symbology._getSymbology(nodeData); expect(symbology.defaultSymbology).toBeDefined(); expect(symbology.defaultSymbology.edges).toBeDefined(); expect(symbology.defaultSymbology.edges.color).toEqual([1, 1, 1, 1]); expect(symbology.defaultSymbology.material).toBeDefined(); expect(symbology.defaultSymbology.material.colorMixMode).toEqual("replace"); expect(symbology.defaultSymbology.material.color).toEqual([0, 0, 0, 0.9]); expect(data).toBeDefined(); expect(data.default).toBeDefined(); expect(data.default.edges).toBeDefined(); expect(data.default.edges.color).toEqual([1, 1, 1, 1]); expect(data.default.material).toBeDefined(); expect(data.default.material.colorMixMode).toEqual("replace"); expect(data.default.material.color).toEqual([0, 0, 0, 0.9]); expect(data[0]).toBeUndefined(); expect(data[1]).toBeUndefined(); expect(data[2]).toBeUndefined(); }); }); // packages/engine/Specs/Scene/I3dmParserSpec.js var import__513 = __toESM(require_Cesium(), 1); describe( "Scene/I3dmParser", function() { it("throws with undefined arrayBuffer", function() { expect(function() { import__513.I3dmParser.parse(void 0); }).toThrowDeveloperError(); }); it("throws with invalid version", function() { const arrayBuffer = Cesium3DTilesTester_default.generateInstancedTileBuffer({ version: 2 }); expect(function() { import__513.I3dmParser.parse(arrayBuffer); }).toThrowError(import__513.RuntimeError); }); it("throws if there is no feature table json", function() { const arrayBuffer = Cesium3DTilesTester_default.generateInstancedTileBuffer({ featureTableJson: {} }); expect(function() { import__513.I3dmParser.parse(arrayBuffer); }).toThrowError(import__513.RuntimeError); }); it("throws with invalid glTF format", function() { const arrayBuffer = Cesium3DTilesTester_default.generateInstancedTileBuffer({ gltfFormat: 2 }); expect(function() { import__513.I3dmParser.parse(arrayBuffer); }).toThrowError(import__513.RuntimeError); }); it("throws if there is no glTF", function() { const arrayBuffer = Cesium3DTilesTester_default.generateInstancedTileBuffer({ gltfUri: "" }); expect(function() { import__513.I3dmParser.parse(arrayBuffer); }).toThrowError(import__513.RuntimeError); }); it("prints deprecation warning if glTF is not 4-byte aligned", function() { spyOn(import__513.I3dmParser, "_deprecationWarning"); const arrayBuffer = Cesium3DTilesTester_default.generateInstancedTileBuffer({ featureTableBinary: new Uint8Array(1) }); import__513.I3dmParser.parse(arrayBuffer); expect(import__513.I3dmParser._deprecationWarning).toHaveBeenCalled(); }); it("parses i3dm", function() { const instancesLength = 10; const positions = new Float32Array(instancesLength * 3); const heights = new Float32Array(instancesLength); for (let i = 0; i < instancesLength; ++i) { positions[i * 3] = i; positions[i * 3 + 1] = i; positions[i * 3 + 2] = i; heights[i] = i; } const featureTableJson = { INSTANCES_LENGTH: instancesLength, POSITION: { byteOffset: 0 } }; const featureTableBinary = positions; const batchTableJson = { height: { byteOffset: 0, componentType: "FLOAT", type: "SCALAR" } }; const batchTableBinary = heights; const gltfUri = "model.gltf"; const arrayBuffer = Cesium3DTilesTester_default.generateInstancedTileBuffer({ featureTableJson, featureTableBinary, batchTableJson, batchTableBinary, gltfUri }); const results = import__513.I3dmParser.parse(arrayBuffer); expect(results.gltfFormat).toBe(1); expect(results.featureTableJson).toEqual(featureTableJson); expect(results.featureTableBinary).toEqual(featureTableBinary); expect(results.batchTableJson).toEqual(batchTableJson); expect(results.batchTableBinary).toEqual(batchTableBinary); expect((0, import__513.getStringFromTypedArray)(results.gltf)).toEqual(gltfUri); }); }, "WebGL" ); // packages/engine/Specs/Scene/ImageBasedLightingSpec.js var import__514 = __toESM(require_Cesium(), 1); describe("Scene/ImageBasedLighting", function() { const testCoefficients = [ new import__514.Cartesian3(1, 1, 1), new import__514.Cartesian3(2, 2, 2), new import__514.Cartesian3(3, 3, 3), new import__514.Cartesian3(4, 4, 4), new import__514.Cartesian3(5, 5, 5), new import__514.Cartesian3(6, 6, 6), new import__514.Cartesian3(7, 7, 7), new import__514.Cartesian3(8, 8, 8), new import__514.Cartesian3(9, 9, 9) ]; it("constructs with default values", function() { const imageBasedLighting = new import__514.ImageBasedLighting(); expect( import__514.Cartesian2.equals( imageBasedLighting.imageBasedLightingFactor, new import__514.Cartesian2(1, 1) ) ).toBe(true); expect(imageBasedLighting.luminanceAtZenith).toEqual(0.2); expect(imageBasedLighting.sphericalHarmonicCoefficients).toBeUndefined(); expect(imageBasedLighting.specularEnvironmentMaps).toBeUndefined(); }); it("throws when constructing with an invalid value for imageBasedLightingFactor", function() { expect(function() { return new import__514.ImageBasedLighting({ imageBasedLightingFactor: new import__514.Cartesian2(-1, 0) }); }).toThrowDeveloperError(); }); it("throws when constructing with an invalid value for imageBasedLightingFactor", function() { expect(function() { return new import__514.ImageBasedLighting({ imageBasedLightingFactor: new import__514.Cartesian2(-1, 0) }); }).toThrowDeveloperError(); }); it("throws when constructing with an invalid value for sphericalHarmonicCoefficients", function() { expect(function() { return new import__514.ImageBasedLighting({ sphericalHarmonicCoefficients: [] }); }).toThrowDeveloperError(); }); it("throws when setting an invalid value for imageBasedLightingFactor", function() { expect(function() { const imageBasedLighting = new import__514.ImageBasedLighting(); imageBasedLighting.imageBasedLightingFactor = new import__514.Cartesian2(-1, 0); }).toThrowDeveloperError(); }); it("throws when setting an invalid value for imageBasedLightingFactor", function() { expect(function() { const imageBasedLighting = new import__514.ImageBasedLighting(); imageBasedLighting.sphericalHarmonicCoefficients = []; }).toThrowDeveloperError(); }); it("imageBasedLightingFactor saves previous value", function() { const imageBasedLighting = new import__514.ImageBasedLighting({ imageBasedLightingFactor: import__514.Cartesian2.ZERO }); imageBasedLighting.imageBasedLightingFactor = new import__514.Cartesian2(1, 1); expect( import__514.Cartesian2.equals( imageBasedLighting.imageBasedLightingFactor, new import__514.Cartesian2(1, 1) ) ).toBe(true); expect( import__514.Cartesian2.equals( imageBasedLighting._previousImageBasedLightingFactor, import__514.Cartesian2.ZERO ) ).toBe(true); }); it("luminanceAtZenith saves previous value", function() { const imageBasedLighting = new import__514.ImageBasedLighting({ luminanceAtZenith: 0 }); imageBasedLighting.luminanceAtZenith = 0.5; expect(imageBasedLighting.luminanceAtZenith).toBe(0.5); expect(imageBasedLighting._previousLuminanceAtZenith).toBe(0); }); it("sphericalHarmonicCoefficients saves previous value", function() { const imageBasedLighting = new import__514.ImageBasedLighting({ sphericalHarmonicCoefficients: testCoefficients }); imageBasedLighting.sphericalHarmonicCoefficients = void 0; expect(imageBasedLighting.sphericalHarmonicCoefficients).toBeUndefined(); expect(imageBasedLighting._previousSphericalHarmonicCoefficients).toBe( testCoefficients ); }); it("enabled returns correct values", function() { const imageBasedLighting = new import__514.ImageBasedLighting(); expect(imageBasedLighting.enabled).toBe(true); imageBasedLighting.imageBasedLightingFactor = import__514.Cartesian2.ZERO; expect(imageBasedLighting.enabled).toBe(false); imageBasedLighting.imageBasedLightingFactor = new import__514.Cartesian2(0.5, 0); expect(imageBasedLighting.enabled).toBe(true); }); it("useSphericalHarmonicCoefficients returns correct values", function() { const imageBasedLighting = new import__514.ImageBasedLighting(); expect(imageBasedLighting.useSphericalHarmonicCoefficients).toBe(false); imageBasedLighting.sphericalHarmonicCoefficients = testCoefficients; expect(imageBasedLighting.useSphericalHarmonicCoefficients).toBe(true); imageBasedLighting.sphericalHarmonicCoefficients = void 0; expect(imageBasedLighting.useSphericalHarmonicCoefficients).toBe(false); }); }); // packages/engine/Specs/Scene/ImageryLayerCollectionSpec.js var import__515 = __toESM(require_Cesium(), 1); describe( "Scene/ImageryLayerCollection", function() { const fakeProvider = { tilingScheme: new import__515.GeographicTilingScheme() }; it("tracks the base layer on add", function() { const layer1 = new import__515.ImageryLayer(fakeProvider); const layer2 = new import__515.ImageryLayer(fakeProvider); const layer3 = new import__515.ImageryLayer(fakeProvider); const collection = new import__515.ImageryLayerCollection(); expect(layer1.isBaseLayer()).toEqual(false); collection.add(layer1); expect(layer1.isBaseLayer()).toEqual(true); collection.add(layer2); expect(layer1.isBaseLayer()).toEqual(true); expect(layer2.isBaseLayer()).toEqual(false); collection.add(layer3, 0); expect(layer1.isBaseLayer()).toEqual(false); expect(layer2.isBaseLayer()).toEqual(false); expect(layer3.isBaseLayer()).toEqual(true); }); it("tracks the base layer on remove", function() { const layer1 = new import__515.ImageryLayer(fakeProvider); const layer2 = new import__515.ImageryLayer(fakeProvider); const layer3 = new import__515.ImageryLayer(fakeProvider); const collection = new import__515.ImageryLayerCollection(); collection.add(layer1); collection.add(layer2); collection.add(layer3); expect(layer1.isBaseLayer()).toEqual(true); expect(layer2.isBaseLayer()).toEqual(false); expect(layer3.isBaseLayer()).toEqual(false); collection.remove(layer1); expect(layer2.isBaseLayer()).toEqual(true); expect(layer3.isBaseLayer()).toEqual(false); collection.remove(layer3); expect(layer2.isBaseLayer()).toEqual(true); }); it("updates isBaseLayer on re-add", function() { const layer1 = new import__515.ImageryLayer(fakeProvider); const layer2 = new import__515.ImageryLayer(fakeProvider); const collection = new import__515.ImageryLayerCollection(); layer1._isBaseLayer = true; layer2._isBaseLayer = true; collection.add(layer1); collection.add(layer2); expect(layer1.isBaseLayer()).toEqual(true); expect(layer2.isBaseLayer()).toEqual(false); }); it("does not crash when raising and lowering a single layer.", function() { const layer1 = new import__515.ImageryLayer(fakeProvider); const collection = new import__515.ImageryLayerCollection(); collection.add(layer1); collection.raise(layer1); collection.lower(layer1); collection.raiseToTop(layer1); collection.lowerToBottom(layer1); }); it("tracks the base layer on raise and lower", function() { const layer1 = new import__515.ImageryLayer(fakeProvider); const layer2 = new import__515.ImageryLayer(fakeProvider); const layer3 = new import__515.ImageryLayer(fakeProvider); const collection = new import__515.ImageryLayerCollection(); collection.add(layer1); collection.add(layer2); collection.add(layer3); expect(layer1.isBaseLayer()).toEqual(true); expect(layer2.isBaseLayer()).toEqual(false); expect(layer3.isBaseLayer()).toEqual(false); collection.lower(layer1); expect(layer1.isBaseLayer()).toEqual(true); expect(layer2.isBaseLayer()).toEqual(false); expect(layer3.isBaseLayer()).toEqual(false); collection.raise(layer1); expect(layer1.isBaseLayer()).toEqual(false); expect(layer2.isBaseLayer()).toEqual(true); expect(layer3.isBaseLayer()).toEqual(false); collection.lower(layer1); expect(layer1.isBaseLayer()).toEqual(true); expect(layer2.isBaseLayer()).toEqual(false); expect(layer3.isBaseLayer()).toEqual(false); }); it("tracks the base layer on raiseToTop to lowerToBottom", function() { const layer1 = new import__515.ImageryLayer(fakeProvider); const layer2 = new import__515.ImageryLayer(fakeProvider); const layer3 = new import__515.ImageryLayer(fakeProvider); const collection = new import__515.ImageryLayerCollection(); collection.add(layer1); collection.add(layer2); collection.add(layer3); expect(layer1.isBaseLayer()).toEqual(true); expect(layer2.isBaseLayer()).toEqual(false); expect(layer3.isBaseLayer()).toEqual(false); collection.raiseToTop(layer1); expect(layer1.isBaseLayer()).toEqual(false); expect(layer2.isBaseLayer()).toEqual(true); expect(layer3.isBaseLayer()).toEqual(false); collection.lowerToBottom(layer1); expect(layer1.isBaseLayer()).toEqual(true); expect(layer2.isBaseLayer()).toEqual(false); expect(layer3.isBaseLayer()).toEqual(false); }); it("add throws when layer is undefined", function() { const collection = new import__515.ImageryLayerCollection(); expect(function() { collection.add(void 0); }).toThrowDeveloperError(); }); it("addImageryProvider throws when imageryProvider is undefined", function() { const collection = new import__515.ImageryLayerCollection(); expect(function() { collection.addImageryProvider(void 0); }).toThrowDeveloperError(); }); it("add throws when index is outside valid range", function() { const collection = new import__515.ImageryLayerCollection(); const layer1 = new import__515.ImageryLayer(fakeProvider); const layer2 = new import__515.ImageryLayer(fakeProvider); expect(function() { collection.add(layer1, 1); }).toThrowDeveloperError(); expect(function() { collection.add(layer1, -1); }).toThrowDeveloperError(); collection.add(layer1, 0); expect(function() { collection.add(layer2, -1); }).toThrowDeveloperError(); expect(function() { collection.add(layer2, 2); }).toThrowDeveloperError(); collection.add(layer2, 0); }); it("remove ignores request to remove a layer that does not exist in the collection", function() { const collection = new import__515.ImageryLayerCollection(); const layer1 = new import__515.ImageryLayer(fakeProvider); expect(collection.remove(layer1)).toBe(false); }); it("contains works as expected", function() { const collection = new import__515.ImageryLayerCollection(); const layer1 = new import__515.ImageryLayer(fakeProvider); const layer2 = new import__515.ImageryLayer(fakeProvider); expect(collection.contains(layer1)).toEqual(false); expect(collection.contains(layer2)).toEqual(false); collection.add(layer1); expect(collection.contains(layer1)).toEqual(true); expect(collection.contains(layer2)).toEqual(false); collection.add(layer2); expect(collection.contains(layer1)).toEqual(true); expect(collection.contains(layer2)).toEqual(true); collection.remove(layer1); expect(collection.contains(layer1)).toEqual(false); expect(collection.contains(layer2)).toEqual(true); collection.remove(layer2); expect(collection.contains(layer1)).toEqual(false); expect(collection.contains(layer2)).toEqual(false); }); it("get throws if index is not provided", function() { const collection = new import__515.ImageryLayerCollection(); expect(function() { collection.get(); }).toThrowDeveloperError(); }); it("throws when raising an undefined layer", function() { const collection = new import__515.ImageryLayerCollection(); expect(function() { collection.raise(void 0); }).toThrowDeveloperError(); }); it("throws when raising a layer not in the collection", function() { const collection = new import__515.ImageryLayerCollection(); const layer1 = new import__515.ImageryLayer(fakeProvider); expect(function() { collection.raise(layer1); }).toThrowDeveloperError(); }); it("reports whether or not it is destroyed", function() { const collection = new import__515.ImageryLayerCollection(); expect(collection.isDestroyed()).toEqual(false); collection.destroy(); expect(collection.isDestroyed()).toEqual(true); }); function updateUntilDone(globe2, scene2) { return pollToPromise_default(function() { globe2._surface._debug.enableDebugOutput = true; scene2.render(); return globe2._surface._tileLoadQueueHigh.length === 0 && globe2._surface._tileLoadQueueMedium.length === 0 && globe2._surface._tileLoadQueueLow.length === 0 && globe2._surface._debug.tilesWaitingForChildren === 0; }); } describe("pickImageryLayers", function() { let scene2; let globe2; let camera; beforeAll(function() { scene2 = createScene_default(); globe2 = scene2.globe = new import__515.Globe(); camera = scene2.camera; scene2.frameState.passes.render = true; }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { globe2.imageryLayers.removeAll(); }); it("returns undefined when pick ray does not intersect surface", function() { const ellipsoid = import__515.Ellipsoid.WGS84; camera.lookAt( new import__515.Cartesian3(ellipsoid.maximumRadius, 0, 0), new import__515.Cartesian3(0, 0, 100) ); const ray = new import__515.Ray( camera.position, import__515.Cartesian3.negate(camera.direction, new import__515.Cartesian3()) ); const imagery = scene2.imageryLayers.pickImageryLayers(ray, scene2); expect(imagery).toBeUndefined(); }); it("returns undefined when globe has no pickable layers", function() { const ellipsoid = import__515.Ellipsoid.WGS84; camera.lookAt( new import__515.Cartesian3(ellipsoid.maximumRadius, 0, 0), new import__515.Cartesian3(0, 0, 100) ); const ray = new import__515.Ray(camera.position, camera.direction); const imagery = scene2.imageryLayers.pickImageryLayers(ray, scene2); expect(imagery).toBeUndefined(); }); it("returns undefined if there are zero imagery layers", function() { const ellipsoid = import__515.Ellipsoid.WGS84; camera.lookAt( new import__515.Cartesian3(ellipsoid.maximumRadius, 0, 0), new import__515.Cartesian3(0, 0, 100) ); camera.lookAtTransform(import__515.Matrix4.IDENTITY); return updateUntilDone(globe2, scene2).then(function() { const ray = new import__515.Ray(camera.position, camera.direction); const imagery = scene2.imageryLayers.pickImageryLayers(ray, scene2); expect(imagery).toBeUndefined(); }); }); it("returns imagery from one layer", function() { const provider = { rectangle: import__515.Rectangle.MAX_VALUE, tileWidth: 256, tileHeight: 256, maximumLevel: 0, minimumLevel: 0, tilingScheme: new import__515.GeographicTilingScheme(), errorEvent: new import__515.Event(), hasAlphaChannel: true, requestImage: function(x, y, level) { return import__515.ImageryProvider.loadImage(this, "Data/Images/Blue.png"); } }; const currentLayer = globe2.imageryLayers.addImageryProvider(provider); const ellipsoid = import__515.Ellipsoid.WGS84; camera.lookAt( new import__515.Cartesian3(ellipsoid.maximumRadius, 0, 0), new import__515.Cartesian3(0, 0, 100) ); camera.lookAtTransform(import__515.Matrix4.IDENTITY); return updateUntilDone(globe2, scene2).then(function() { const ray = new import__515.Ray(camera.position, camera.direction); const imagery = scene2.imageryLayers.pickImageryLayers(ray, scene2); expect(imagery).toBeDefined(); expect(imagery.length).toBe(1); expect(imagery[0]).toBe(currentLayer); }); }); it("returns imagery from two layers", function() { const provider1 = { rectangle: import__515.Rectangle.MAX_VALUE, tileWidth: 256, tileHeight: 256, maximumLevel: 0, minimumLevel: 0, tilingScheme: new import__515.GeographicTilingScheme(), errorEvent: new import__515.Event(), hasAlphaChannel: true, requestImage: function(x, y, level) { return import__515.ImageryProvider.loadImage(this, "Data/Images/Blue.png"); } }; const currentLayer1 = globe2.imageryLayers.addImageryProvider(provider1); const provider2 = { rectangle: import__515.Rectangle.MAX_VALUE, tileWidth: 256, tileHeight: 256, maximumLevel: 0, minimumLevel: 0, tilingScheme: new import__515.GeographicTilingScheme(), errorEvent: new import__515.Event(), hasAlphaChannel: true, requestImage: function(x, y, level) { return import__515.ImageryProvider.loadImage(this, "Data/Images/Green.png"); } }; const currentLayer2 = globe2.imageryLayers.addImageryProvider(provider2); const ellipsoid = import__515.Ellipsoid.WGS84; camera.lookAt( new import__515.Cartesian3(ellipsoid.maximumRadius, 0, 0), new import__515.Cartesian3(0, 0, 100) ); camera.lookAtTransform(import__515.Matrix4.IDENTITY); return updateUntilDone(globe2, scene2).then(function() { const ray = new import__515.Ray(camera.position, camera.direction); const imagery = scene2.imageryLayers.pickImageryLayers(ray, scene2); expect(imagery).toBeDefined(); expect(imagery.length).toBe(2); expect(imagery[0]).toBe(currentLayer2); expect(imagery[1]).toBe(currentLayer1); }); }); }); describe("pickImageryLayerFeatures", function() { let scene2; let globe2; let camera; beforeAll(function() { scene2 = createScene_default(); globe2 = scene2.globe = new import__515.Globe(); camera = scene2.camera; scene2.frameState.passes.render = true; }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { globe2.imageryLayers.removeAll(); }); it("returns undefined when pick ray does not intersect surface", function() { const ellipsoid = import__515.Ellipsoid.WGS84; camera.lookAt( new import__515.Cartesian3(ellipsoid.maximumRadius, 0, 0), new import__515.Cartesian3(0, 0, 100) ); const ray = new import__515.Ray( camera.position, import__515.Cartesian3.negate(camera.direction, new import__515.Cartesian3()) ); const featuresPromise = scene2.imageryLayers.pickImageryLayerFeatures( ray, scene2 ); expect(featuresPromise).toBeUndefined(); }); it("returns undefined when globe has no pickable layers", function() { const ellipsoid = import__515.Ellipsoid.WGS84; camera.lookAt( new import__515.Cartesian3(ellipsoid.maximumRadius, 0, 0), new import__515.Cartesian3(0, 0, 100) ); const ray = new import__515.Ray(camera.position, camera.direction); const featuresPromise = scene2.imageryLayers.pickImageryLayerFeatures( ray, scene2 ); expect(featuresPromise).toBeUndefined(); }); it("returns undefined when ImageryProvider does not implement pickFeatures", function() { const provider = { rectangle: import__515.Rectangle.MAX_VALUE, tileWidth: 256, tileHeight: 256, maximumLevel: 0, minimumLevel: 0, tilingScheme: new import__515.GeographicTilingScheme(), errorEvent: new import__515.Event(), hasAlphaChannel: true, requestImage: function(x, y, level) { return import__515.ImageryProvider.loadImage(this, "Data/Images/Blue.png"); } }; globe2.imageryLayers.addImageryProvider(provider); return updateUntilDone(globe2, scene2).then(function() { const ellipsoid = import__515.Ellipsoid.WGS84; camera.lookAt( new import__515.Cartesian3(ellipsoid.maximumRadius, 0, 0), new import__515.Cartesian3(0, 0, 100) ); const ray = new import__515.Ray(camera.position, camera.direction); const featuresPromise = scene2.imageryLayers.pickImageryLayerFeatures( ray, scene2 ); expect(featuresPromise).toBeUndefined(); }); }); it("returns undefined when ImageryProvider.pickFeatures returns undefined", function() { const provider = { rectangle: import__515.Rectangle.MAX_VALUE, tileWidth: 256, tileHeight: 256, maximumLevel: 0, minimumLevel: 0, tilingScheme: new import__515.GeographicTilingScheme(), errorEvent: new import__515.Event(), hasAlphaChannel: true, pickFeatures: function(x, y, level, longitude, latitude) { return void 0; }, requestImage: function(x, y, level) { return import__515.ImageryProvider.loadImage(this, "Data/Images/Blue.png"); } }; globe2.imageryLayers.addImageryProvider(provider); return updateUntilDone(globe2, scene2).then(function() { const ellipsoid = import__515.Ellipsoid.WGS84; camera.lookAt( new import__515.Cartesian3(ellipsoid.maximumRadius, 0, 0), new import__515.Cartesian3(0, 0, 100) ); const ray = new import__515.Ray(camera.position, camera.direction); const featuresPromise = scene2.imageryLayers.pickImageryLayerFeatures( ray, scene2 ); expect(featuresPromise).toBeUndefined(); }); }); it("returns features from one layer", function() { const provider = { rectangle: import__515.Rectangle.MAX_VALUE, tileWidth: 256, tileHeight: 256, maximumLevel: 0, minimumLevel: 0, tilingScheme: new import__515.GeographicTilingScheme(), errorEvent: new import__515.Event(), hasAlphaChannel: true, pickFeatures: function(x, y, level, longitude, latitude) { return new Promise((resolve) => { setTimeout(function() { const featureInfo = new import__515.ImageryLayerFeatureInfo(); featureInfo.name = "Foo"; featureInfo.description = "Foo!"; resolve([featureInfo]); }, 1); }); }, requestImage: function(x, y, level) { return import__515.ImageryProvider.loadImage(this, "Data/Images/Blue.png"); } }; const currentLayer = globe2.imageryLayers.addImageryProvider(provider); return updateUntilDone(globe2, scene2).then(function() { const ellipsoid = import__515.Ellipsoid.WGS84; camera.lookAt( new import__515.Cartesian3(ellipsoid.maximumRadius, 0, 0), new import__515.Cartesian3(0, 0, 100) ); camera.lookAtTransform(import__515.Matrix4.IDENTITY); const ray = new import__515.Ray(camera.position, camera.direction); const featuresPromise = scene2.imageryLayers.pickImageryLayerFeatures( ray, scene2 ); expect(featuresPromise).toBeDefined(); return featuresPromise.then(function(features) { expect(features.length).toBe(1); expect(features[0].name).toEqual("Foo"); expect(features[0].description).toContain("Foo!"); expect(features[0].imageryLayer).toBe(currentLayer); }); }); }); it("returns features from two layers", function() { const provider1 = { rectangle: import__515.Rectangle.MAX_VALUE, tileWidth: 256, tileHeight: 256, maximumLevel: 0, minimumLevel: 0, tilingScheme: new import__515.GeographicTilingScheme(), errorEvent: new import__515.Event(), hasAlphaChannel: true, pickFeatures: function(x, y, level, longitude, latitude) { return new Promise((resolve) => { setTimeout(function() { const featureInfo = new import__515.ImageryLayerFeatureInfo(); featureInfo.name = "Foo"; featureInfo.description = "Foo!"; resolve([featureInfo]); }, 1); }); }, requestImage: function(x, y, level) { return import__515.ImageryProvider.loadImage(this, "Data/Images/Blue.png"); } }; const currentLayer1 = globe2.imageryLayers.addImageryProvider(provider1); const provider2 = { rectangle: import__515.Rectangle.MAX_VALUE, tileWidth: 256, tileHeight: 256, maximumLevel: 0, minimumLevel: 0, tilingScheme: new import__515.GeographicTilingScheme(), errorEvent: new import__515.Event(), hasAlphaChannel: true, pickFeatures: function(x, y, level, longitude, latitude) { return new Promise((resolve) => { setTimeout(function() { const featureInfo = new import__515.ImageryLayerFeatureInfo(); featureInfo.name = "Bar"; featureInfo.description = "Bar!"; resolve([featureInfo]); }, 1); }); }, requestImage: function(x, y, level) { return import__515.ImageryProvider.loadImage(this, "Data/Images/Green.png"); } }; const currentLayer2 = globe2.imageryLayers.addImageryProvider(provider2); return updateUntilDone(globe2, scene2).then(function() { const ellipsoid = import__515.Ellipsoid.WGS84; camera.lookAt( new import__515.Cartesian3(ellipsoid.maximumRadius, 0, 0), new import__515.Cartesian3(0, 0, 100) ); camera.lookAtTransform(import__515.Matrix4.IDENTITY); const ray = new import__515.Ray(camera.position, camera.direction); const featuresPromise = scene2.imageryLayers.pickImageryLayerFeatures( ray, scene2 ); expect(featuresPromise).toBeDefined(); return featuresPromise.then(function(features) { expect(features.length).toBe(2); expect(features[0].name).toEqual("Bar"); expect(features[0].description).toContain("Bar!"); expect(features[0].imageryLayer).toBe(currentLayer2); expect(features[1].name).toEqual("Foo"); expect(features[1].description).toContain("Foo!"); expect(features[1].imageryLayer).toBe(currentLayer1); }); }); }); it("correctly picks from a terrain tile that is partially covered by correct-level imagery and partially covered by imagery from an ancestor level", function() { const provider = { rectangle: new import__515.Rectangle( -Math.PI, -import__515.WebMercatorProjection.MaximumLatitude, Math.PI, import__515.WebMercatorProjection.MaximumLatitude ), tileWidth: 256, tileHeight: 256, maximumLevel: 1, minimumLevel: 1, tilingScheme: new import__515.WebMercatorTilingScheme(), errorEvent: new import__515.Event(), hasAlphaChannel: true, pickFeatures: function(x, y, level, longitude, latitude) { return new Promise((resolve) => { setTimeout(function() { const featureInfo = new import__515.ImageryLayerFeatureInfo(); featureInfo.name = `L${level}X${x}Y${y}`; resolve([featureInfo]); }, 1); }); }, requestImage: function(x, y, level) { if (level !== 1 || x === 0 && y === 0) { return import__515.ImageryProvider.loadImage(this, "Data/Images/Blue.png"); } return Promise.reject("invalid tile"); } }; globe2.imageryLayers.addImageryProvider(provider); camera.setView({ destination: import__515.Rectangle.fromDegrees(-180, 0, 0, 90) }); return updateUntilDone(globe2, scene2).then(function() { const ray = new import__515.Ray(camera.position, camera.direction); const featuresPromise = scene2.imageryLayers.pickImageryLayerFeatures( ray, scene2 ); expect(featuresPromise).toBeDefined(); return featuresPromise.then(function(features) { expect(features.length).toBe(1); expect(features[0].name).toEqual("L1X0Y0"); }); }); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/ImageryLayerSpec.js var import__516 = __toESM(require_Cesium(), 1); describe( "Scene/ImageryLayer", function() { let scene2; let computeEngine; beforeAll(function() { scene2 = createScene_default(); computeEngine = new import__516.ComputeEngine(scene2.context); }); afterAll(function() { scene2.destroyForSpecs(); computeEngine.destroy(); }); afterEach(function() { import__516.Resource._Implementations.loadAndExecuteScript = import__516.Resource._DefaultImplementations.loadAndExecuteScript; import__516.Resource._Implementations.createImage = import__516.Resource._DefaultImplementations.createImage; import__516.Resource._Implementations.loadWithXhr = import__516.Resource._DefaultImplementations.loadWithXhr; scene2.frameState.commandList.length = 0; }); function CustomDiscardPolicy() { this.shouldDiscard = false; } CustomDiscardPolicy.prototype.isReady = function() { return true; }; CustomDiscardPolicy.prototype.shouldDiscardImage = function(image) { return this.shouldDiscard; }; it("constructs with default options", function() { const provider = new import__516.TileCoordinatesImageryProvider(); const layer = new import__516.ImageryLayer(provider); expect(layer.imageryProvider).toBe(provider); expect(layer.show).toBeTrue(); expect(layer.errorEvent).toBeDefined(); expect(layer.readyEvent).toBeDefined(); expect(layer.ready).toBeTrue(); }); it("fromProviderAsync throws without provider promise", function() { expect(() => import__516.ImageryLayer.fromProviderAsync()).toThrowDeveloperError( "expected" ); }); it("readyEvent is raised when asynchronous provider become ready", async function() { const providerPromise = import__516.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); const layer = import__516.ImageryLayer.fromProviderAsync(providerPromise); expect(layer.ready).toBe(false); const spyListener = jasmine.createSpy("listener"); layer.readyEvent.addEventListener(spyListener); await providerPromise; expect(spyListener).toHaveBeenCalled(); expect(layer.ready).toBeTrue(); expect(layer.imageryProvider).toBeInstanceOf(import__516.SingleTileImageryProvider); }); it("errorEvent is raised when asynchronous provider cannot be constructed", async function() { const providerPromise = Promise.reject(); const layer = import__516.ImageryLayer.fromProviderAsync(providerPromise); expect(layer.ready).toBe(false); const spyListener = jasmine.createSpy("listener"); layer.errorEvent.addEventListener(spyListener); await expectAsync(providerPromise).toBeRejected(); expect(spyListener).toHaveBeenCalled(); expect(layer.ready).toBeFalse(); expect(layer.imageryProvider).toBeUndefined(); }); it("discards tiles when the ImageryProviders discard policy says to do so", function() { import__516.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { import__516.Resource._DefaultImplementations.createImage( new import__516.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }; import__516.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__516.Resource._DefaultImplementations.loadWithXhr( "Data/Images/Red16x16.png", responseType, method, data, headers, deferred ); }; const discardPolicy = new CustomDiscardPolicy(); const provider = new import__516.WebMapServiceImageryProvider({ url: "made/up/url", layers: "foo", tileDiscardPolicy: discardPolicy }); const layer = new import__516.ImageryLayer(provider); discardPolicy.shouldDiscard = true; const imagery = new import__516.Imagery(layer, 0, 0, 0); imagery.addReference(); layer._requestImagery(imagery); import__516.RequestScheduler.update(); return pollToPromise_default(function() { return imagery.state === import__516.ImageryState.RECEIVED; }).then(function() { layer._createTexture(scene2.context, imagery); expect(imagery.state).toEqual(import__516.ImageryState.INVALID); imagery.releaseReference(); }); }); async function createWebMercatorProvider() { import__516.Resource._Implementations.loadAndExecuteScript = function(url, functionName) { window[functionName]({ authenticationResultCode: "ValidCredentials", brandLogoUri: "http://dev.virtualearth.net/Branding/logo_powered_by.png", copyright: "Copyright \xA9 2012 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.", resourceSets: [ { estimatedTotal: 1, resources: [ { __type: "ImageryMetadata:http://schemas.microsoft.com/search/local/ws/rest/v1", imageHeight: 256, imageUrl: "http://invalid.{subdomain}.invalid/tiles/r{quadkey}?g=1062&lbl=l1&productSet=mmCB", imageUrlSubdomains: ["t0"], imageWidth: 256, imageryProviders: null, vintageEnd: null, vintageStart: null, zoomMax: 21, zoomMin: 1 } ] } ], statusCode: 200, statusDescription: "OK", traceId: "c9cf8c74a8b24644974288c92e448972|EWRM003311|02.00.171.2600|" }); }; import__516.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { import__516.Resource._DefaultImplementations.createImage( new import__516.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }; import__516.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__516.Resource._DefaultImplementations.loadWithXhr( "Data/Images/Red16x16.png", responseType, method, data, headers, deferred ); }; return import__516.BingMapsImageryProvider.fromUrl("http://host.invalid", { key: "", tileDiscardPolicy: new import__516.NeverTileDiscardPolicy() }); } it("reprojects web mercator images when necessary", async function() { const provider = await createWebMercatorProvider(); const layer = new import__516.ImageryLayer(provider); const imagery = new import__516.Imagery(layer, 0, 0, 0); imagery.addReference(); layer._requestImagery(imagery); import__516.RequestScheduler.update(); return pollToPromise_default(function() { return imagery.state === import__516.ImageryState.RECEIVED; }).then(function() { layer._createTexture(scene2.context, imagery); return pollToPromise_default(function() { return imagery.state === import__516.ImageryState.TEXTURE_LOADED; }).then(function() { const textureBeforeReprojection = imagery.textureWebMercator; layer._reprojectTexture(scene2.frameState, imagery, true); layer.queueReprojectionCommands(scene2.frameState); scene2.frameState.commandList[0].execute(computeEngine); return pollToPromise_default(function() { return imagery.state === import__516.ImageryState.READY; }).then(function() { expect(imagery.texture).toBeDefined(); expect(imagery.texture.sampler).toBeDefined(); expect(imagery.texture.sampler.minificationFilter).toEqual( import__516.TextureMinificationFilter.LINEAR_MIPMAP_LINEAR ); expect(imagery.texture.sampler.magnificationFilter).toEqual( import__516.TextureMinificationFilter.LINEAR ); expect(textureBeforeReprojection).not.toEqual(imagery.texture); imagery.releaseReference(); }); }); }); }); it("does not reproject web mercator images when not necessary", async function() { const provider = await createWebMercatorProvider(); const layer = new import__516.ImageryLayer(provider); const imagery = new import__516.Imagery(layer, 0, 1, 3); imagery.addReference(); layer._requestImagery(imagery); import__516.RequestScheduler.update(); return pollToPromise_default(function() { return imagery.state === import__516.ImageryState.RECEIVED; }).then(function() { layer._createTexture(scene2.context, imagery); return pollToPromise_default(function() { return imagery.state === import__516.ImageryState.TEXTURE_LOADED; }).then(function() { expect(imagery.textureWebMercator).toBeDefined(); layer._reprojectTexture(scene2.frameState, imagery, false); layer.queueReprojectionCommands(scene2.frameState); expect(scene2.frameState.commandList.length).toBe(0); return pollToPromise_default(function() { return imagery.state === import__516.ImageryState.READY; }).then(function() { expect(imagery.texture).not.toBeDefined(); imagery.releaseReference(); }); }); }); }); it("reprojects web mercator images later if it becomes necessary later", async function() { const provider = await createWebMercatorProvider(); const layer = new import__516.ImageryLayer(provider); const imagery = new import__516.Imagery(layer, 0, 1, 3); imagery.addReference(); layer._requestImagery(imagery); import__516.RequestScheduler.update(); return pollToPromise_default(function() { return imagery.state === import__516.ImageryState.RECEIVED; }).then(function() { layer._createTexture(scene2.context, imagery); return pollToPromise_default(function() { return imagery.state === import__516.ImageryState.TEXTURE_LOADED; }).then(function() { const textureBeforeReprojection = imagery.textureWebMercator; layer._reprojectTexture(scene2.frameState, imagery, false); layer.queueReprojectionCommands(scene2.frameState); expect(scene2.frameState.commandList.length).toBe(0); return pollToPromise_default(function() { return imagery.state === import__516.ImageryState.READY; }).then(function() { expect(imagery.texture).not.toBeDefined(); layer._reprojectTexture(scene2.frameState, imagery, true); layer.queueReprojectionCommands(scene2.frameState); scene2.frameState.commandList[0].execute(computeEngine); return pollToPromise_default(function() { return imagery.state === import__516.ImageryState.READY; }).then(function() { expect(imagery.texture).toBeDefined(); expect(imagery.texture.sampler).toBeDefined(); expect(imagery.texture.sampler.minificationFilter).toEqual( import__516.TextureMinificationFilter.LINEAR_MIPMAP_LINEAR ); expect(imagery.texture.sampler.magnificationFilter).toEqual( import__516.TextureMinificationFilter.LINEAR ); expect(textureBeforeReprojection).not.toEqual(imagery.texture); imagery.releaseReference(); }); }); }); }); }); it("assigns texture property when reprojection is skipped because the tile is very small", function() { import__516.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { import__516.Resource._DefaultImplementations.createImage( new import__516.Request({ url: "Data/Images/Red256x256.png" }), crossOrigin, deferred ); }; const provider = new import__516.UrlTemplateImageryProvider({ url: "http://example.com/{z}/{x}/{y}.png", minimumLevel: 13, maximumLevel: 19, rectangle: import__516.Rectangle.fromDegrees( 13.39657249732205, 52.49127999816725, 13.42722986993895, 52.50998943590507 ) }); const layer = new import__516.ImageryLayer(provider); const imagery = new import__516.Imagery(layer, 4400, 2686, 13); imagery.addReference(); layer._requestImagery(imagery); import__516.RequestScheduler.update(); return pollToPromise_default(function() { return imagery.state === import__516.ImageryState.RECEIVED; }).then(function() { layer._createTexture(scene2.context, imagery); return pollToPromise_default(function() { return imagery.state === import__516.ImageryState.TEXTURE_LOADED; }).then(function() { layer._reprojectTexture(scene2.frameState, imagery, true); layer.queueReprojectionCommands(scene2.frameState); expect(scene2.frameState.commandList.length).toBe(0); return pollToPromise_default(function() { return imagery.state === import__516.ImageryState.READY; }).then(function() { expect(imagery.texture).toBeDefined(); expect(imagery.texture.sampler).toBeDefined(); expect(imagery.texture.sampler.minificationFilter).toEqual( import__516.TextureMinificationFilter.LINEAR_MIPMAP_LINEAR ); expect(imagery.texture.sampler.magnificationFilter).toEqual( import__516.TextureMinificationFilter.LINEAR ); expect(imagery.texture).toBe(imagery.textureWebMercator); imagery.releaseReference(); }); }); }); }); it("cancels reprojection", async function() { const provider = await createWebMercatorProvider(); const layer = new import__516.ImageryLayer(provider); const imagery = new import__516.Imagery(layer, 0, 0, 0); imagery.addReference(); layer._requestImagery(imagery); import__516.RequestScheduler.update(); return pollToPromise_default(function() { return imagery.state === import__516.ImageryState.RECEIVED; }).then(function() { layer._createTexture(scene2.context, imagery); return pollToPromise_default(function() { return imagery.state === import__516.ImageryState.TEXTURE_LOADED; }).then(function() { layer._reprojectTexture(scene2.frameState, imagery); layer.cancelReprojections(); layer.queueReprojectionCommands(scene2.frameState); expect(scene2.frameState.commandList.length).toEqual(0); }); }); }); it("basic properties work as expected", async function() { const provider = await import__516.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); const rectangle = new import__516.Rectangle(0.1, 0.2, 0.3, 0.4); const layer = new import__516.ImageryLayer(provider, { rectangle }); expect(layer.rectangle).toEqual(rectangle); expect(layer.isDestroyed()).toEqual(false); layer.destroy(); expect(layer.isDestroyed()).toEqual(true); }); it("allows setting texture filter properties", async function() { const provider = await import__516.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); let layer = new import__516.ImageryLayer(provider); expect(layer.minificationFilter).toEqual( import__516.TextureMinificationFilter.LINEAR ); expect(layer.magnificationFilter).toEqual( import__516.TextureMagnificationFilter.LINEAR ); layer.destroy(); layer = new import__516.ImageryLayer(provider, { minificationFilter: import__516.TextureMinificationFilter.NEAREST, magnificationFilter: import__516.TextureMagnificationFilter.NEAREST }); expect(layer.minificationFilter).toEqual( import__516.TextureMinificationFilter.NEAREST ); expect(layer.magnificationFilter).toEqual( import__516.TextureMagnificationFilter.NEAREST ); const imagery = new import__516.Imagery(layer, 0, 0, 0); imagery.addReference(); layer._requestImagery(imagery); import__516.RequestScheduler.update(); return pollToPromise_default(function() { return imagery.state === import__516.ImageryState.RECEIVED; }).then(function() { layer._createTexture(scene2.context, imagery); const sampler = imagery.texture.sampler; expect(sampler.minificationFilter).toEqual( import__516.TextureMinificationFilter.NEAREST ); expect(sampler.magnificationFilter).toEqual( import__516.TextureMinificationFilter.NEAREST ); imagery.releaseReference(); layer.destroy(); }); }); it("returns HTTP status code information in TileProviderError", async function() { const provider = await import__516.ArcGisMapServerImageryProvider.fromUrl( "File/That/Does/Not/Exist", { usePreCachedTilesIfAvailable: false, tileDiscardPolicy: new import__516.NeverTileDiscardPolicy() } ); let errorRaised = false; provider.errorEvent.addEventListener(function(tileProviderError) { expect(tileProviderError).toBeDefined(); expect(tileProviderError.error).toBeDefined(); expect(tileProviderError.error.statusCode).toBe(404); errorRaised = true; }); const imageryLayer = new import__516.ImageryLayer(provider); imageryLayer._requestImagery(new import__516.Imagery(imageryLayer, 0, 0, 0)); import__516.RequestScheduler.update(); return pollToPromise_default(function() { return errorRaised; }); }); it("getImageryRectangle works", async function() { const providerRectangle = import__516.Rectangle.fromDegrees(8.2, 61.09, 8.5, 61.7); const provider = await import__516.SingleTileImageryProvider.fromUrl( "Data/Images/Green4x4.png", { rectangle: providerRectangle } ); const layerRectangle = import__516.Rectangle.fromDegrees(7.2, 60.9, 9, 61.7); const layer = new import__516.ImageryLayer(provider, { rectangle: layerRectangle }); expect(layer.getImageryRectangle()).toEqual( import__516.Rectangle.intersection(providerRectangle, layerRectangle) ); }); describe("createTileImagerySkeletons", function() { it("handles a base layer that does not cover the entire globe", async function() { const provider = await import__516.TileMapServiceImageryProvider.fromUrl( "Data/TMS/SmallArea" ); const layers = new import__516.ImageryLayerCollection(); const layer = layers.addImageryProvider(provider); const terrainProvider = new import__516.EllipsoidTerrainProvider(); const tiles = import__516.QuadtreeTile.createLevelZeroTiles( terrainProvider.tilingScheme ); tiles[0].data = new import__516.GlobeSurfaceTile(); tiles[1].data = new import__516.GlobeSurfaceTile(); layer._createTileImagerySkeletons(tiles[0], terrainProvider); layer._createTileImagerySkeletons(tiles[1], terrainProvider); expect(tiles[0].data.imagery.length).toBe(4); expect(tiles[0].data.imagery[0].textureCoordinateRectangle.x).toBe(0); expect(tiles[0].data.imagery[0].textureCoordinateRectangle.w).toBe(1); expect(tiles[0].data.imagery[1].textureCoordinateRectangle.x).toBe(0); expect(tiles[0].data.imagery[1].textureCoordinateRectangle.y).toBe(0); expect(tiles[0].data.imagery[2].textureCoordinateRectangle.z).toBe(1); expect(tiles[0].data.imagery[2].textureCoordinateRectangle.w).toBe(1); expect(tiles[0].data.imagery[3].textureCoordinateRectangle.y).toBe(0); expect(tiles[0].data.imagery[3].textureCoordinateRectangle.z).toBe(1); expect(tiles[1].data.imagery.length).toBe(2); expect(tiles[1].data.imagery[0].textureCoordinateRectangle.x).toBe(0); expect(tiles[1].data.imagery[0].textureCoordinateRectangle.w).toBe(1); expect(tiles[1].data.imagery[0].textureCoordinateRectangle.z).toBe(1); expect(tiles[1].data.imagery[1].textureCoordinateRectangle.x).toBe(0); expect(tiles[1].data.imagery[1].textureCoordinateRectangle.y).toBe(0); expect(tiles[1].data.imagery[1].textureCoordinateRectangle.z).toBe(1); }); it("does not get confused when base layer imagery overlaps in one direction but not the other", async function() { const wholeWorldProvider = await import__516.SingleTileImageryProvider.fromUrl( "Data/Images/Blue.png" ); const provider = await import__516.TileMapServiceImageryProvider.fromUrl( "Data/TMS/SmallArea" ); const layers = new import__516.ImageryLayerCollection(); const wholeWorldLayer = layers.addImageryProvider(wholeWorldProvider); const terrainProvider = new import__516.EllipsoidTerrainProvider(); let tiles = import__516.QuadtreeTile.createLevelZeroTiles( terrainProvider.tilingScheme ); tiles[0].data = new import__516.GlobeSurfaceTile(); tiles[1].data = new import__516.GlobeSurfaceTile(); wholeWorldLayer._createTileImagerySkeletons(tiles[0], terrainProvider); wholeWorldLayer._createTileImagerySkeletons(tiles[1], terrainProvider); layers.removeAll(); const layer = layers.addImageryProvider(provider); tiles = import__516.QuadtreeTile.createLevelZeroTiles(terrainProvider.tilingScheme); tiles[0].data = new import__516.GlobeSurfaceTile(); tiles[1].data = new import__516.GlobeSurfaceTile(); layer._createTileImagerySkeletons(tiles[1], terrainProvider); expect(tiles[1].data.imagery.length).toBe(2); expect(tiles[1].data.imagery[0].textureCoordinateRectangle.x).toBe(0); expect(tiles[1].data.imagery[0].textureCoordinateRectangle.w).toBe(1); expect(tiles[1].data.imagery[0].textureCoordinateRectangle.z).toBe(1); expect(tiles[1].data.imagery[1].textureCoordinateRectangle.x).toBe(0); expect(tiles[1].data.imagery[1].textureCoordinateRectangle.y).toBe(0); expect(tiles[1].data.imagery[1].textureCoordinateRectangle.z).toBe(1); }); it("handles a non-base layer that does not cover the entire globe", async function() { const baseProvider = await import__516.SingleTileImageryProvider.fromUrl( "Data/Images/Green4x4.png" ); const provider = await import__516.TileMapServiceImageryProvider.fromUrl( "Data/TMS/SmallArea" ); const layers = new import__516.ImageryLayerCollection(); layers.addImageryProvider(baseProvider); const layer = layers.addImageryProvider(provider); const terrainProvider = new import__516.EllipsoidTerrainProvider(); const tiles = import__516.QuadtreeTile.createLevelZeroTiles( terrainProvider.tilingScheme ); tiles[0].data = new import__516.GlobeSurfaceTile(); tiles[1].data = new import__516.GlobeSurfaceTile(); layer._createTileImagerySkeletons(tiles[0], terrainProvider); layer._createTileImagerySkeletons(tiles[1], terrainProvider); expect(tiles[0].data.imagery.length).toBe(4); expect(tiles[0].data.imagery[0].textureCoordinateRectangle.x).not.toBe( 0 ); expect(tiles[0].data.imagery[0].textureCoordinateRectangle.y).not.toBe( 0 ); expect(tiles[0].data.imagery[0].textureCoordinateRectangle.z).not.toBe( 1 ); expect(tiles[0].data.imagery[0].textureCoordinateRectangle.w).not.toBe( 1 ); expect(tiles[0].data.imagery[1].textureCoordinateRectangle.x).not.toBe( 0 ); expect(tiles[0].data.imagery[1].textureCoordinateRectangle.y).not.toBe( 0 ); expect(tiles[0].data.imagery[1].textureCoordinateRectangle.z).not.toBe( 1 ); expect(tiles[0].data.imagery[1].textureCoordinateRectangle.w).not.toBe( 1 ); expect(tiles[0].data.imagery[2].textureCoordinateRectangle.x).not.toBe( 0 ); expect(tiles[0].data.imagery[2].textureCoordinateRectangle.y).not.toBe( 0 ); expect(tiles[0].data.imagery[2].textureCoordinateRectangle.z).not.toBe( 1 ); expect(tiles[0].data.imagery[2].textureCoordinateRectangle.w).not.toBe( 1 ); expect(tiles[0].data.imagery[3].textureCoordinateRectangle.x).not.toBe( 0 ); expect(tiles[0].data.imagery[3].textureCoordinateRectangle.y).not.toBe( 0 ); expect(tiles[0].data.imagery[3].textureCoordinateRectangle.z).not.toBe( 1 ); expect(tiles[0].data.imagery[3].textureCoordinateRectangle.w).not.toBe( 1 ); expect(tiles[1].data.imagery.length).toBe(0); }); it("honors the minimumTerrainLevel and maximumTerrainLevel properties", async function() { const provider = await import__516.SingleTileImageryProvider.fromUrl( "Data/Images/Green4x4.png" ); const layer = new import__516.ImageryLayer(provider, { minimumTerrainLevel: 2, maximumTerrainLevel: 4 }); const layers = new import__516.ImageryLayerCollection(); layers.add(layer); const terrainProvider = new import__516.EllipsoidTerrainProvider(); const level0 = import__516.QuadtreeTile.createLevelZeroTiles( terrainProvider.tilingScheme ); const level1 = level0[0].children; const level2 = level1[0].children; const level3 = level2[0].children; const level4 = level3[0].children; const level5 = level4[0].children; level0[0].data = new import__516.GlobeSurfaceTile(); level1[0].data = new import__516.GlobeSurfaceTile(); level2[0].data = new import__516.GlobeSurfaceTile(); level3[0].data = new import__516.GlobeSurfaceTile(); level4[0].data = new import__516.GlobeSurfaceTile(); level5[0].data = new import__516.GlobeSurfaceTile(); layer._createTileImagerySkeletons(level0[0], terrainProvider); expect(level0[0].data.imagery.length).toBe(0); layer._createTileImagerySkeletons(level1[0], terrainProvider); expect(level1[0].data.imagery.length).toBe(0); layer._createTileImagerySkeletons(level2[0], terrainProvider); expect(level2[0].data.imagery.length).toBe(1); layer._createTileImagerySkeletons(level3[0], terrainProvider); expect(level3[0].data.imagery.length).toBe(1); layer._createTileImagerySkeletons(level4[0], terrainProvider); expect(level4[0].data.imagery.length).toBe(1); layer._createTileImagerySkeletons(level5[0], terrainProvider); expect(level5[0].data.imagery.length).toBe(0); }); it("honors limited extent of non-base ImageryLayer", async function() { const provider = await import__516.SingleTileImageryProvider.fromUrl( "Data/Images/Green4x4.png" ); const layer = new import__516.ImageryLayer(provider, { rectangle: import__516.Rectangle.fromDegrees(7.2, 60.9, 9, 61.7) }); const layers = new import__516.ImageryLayerCollection(); const provider2 = await import__516.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); layers.addImageryProvider(provider2); layers.add(layer); const terrainProvider = new import__516.EllipsoidTerrainProvider(); const tiles = import__516.QuadtreeTile.createLevelZeroTiles( terrainProvider.tilingScheme ); tiles[0].data = new import__516.GlobeSurfaceTile(); tiles[1].data = new import__516.GlobeSurfaceTile(); layer._createTileImagerySkeletons(tiles[0], terrainProvider); layer._createTileImagerySkeletons(tiles[1], terrainProvider); expect(tiles[0].data.imagery.length).toBe(0); expect(tiles[1].data.imagery.length).toBe(1); const textureCoordinates = tiles[1].data.imagery[0].textureCoordinateRectangle; expect(textureCoordinates.x).toBeGreaterThan(0); expect(textureCoordinates.y).toBeGreaterThan(0); expect(textureCoordinates.z).toBeLessThan(1); expect(textureCoordinates.w).toBeLessThan(1); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Implicit3DTileContentSpec.js var import__517 = __toESM(require_Cesium(), 1); // Specs/ImplicitTilingTester.js var import_engine27 = __toESM(require_Cesium(), 1); function ImplicitTilingTester() { } ImplicitTilingTester.generateSubtreeBuffers = function(subtreeDescription, constantOnly) { constantOnly = (0, import_engine27.defaultValue)(constantOnly, false); let subtreeJson = {}; if (!constantOnly) { subtreeJson = { buffers: [], bufferViews: [] }; } const bufferViewsU8 = makeBufferViews(subtreeDescription, subtreeJson); const buffersU8 = makeBuffers(bufferViewsU8, subtreeJson); if (subtreeDescription.json) { return { subtreeJson, externalBuffer: buffersU8.external }; } const jsonChunk = makeJsonChunk(subtreeJson); const binaryChunk = buffersU8.internal; const header = makeSubtreeHeader(jsonChunk.length, binaryChunk.length); const subtreeBuffer = concatTypedArrays_default([header, jsonChunk, binaryChunk]); return { subtreeBuffer, externalBuffer: buffersU8.external }; }; function makeBufferViews(subtreeDescription, subtreeJson) { const hasContent = (0, import_engine27.defined)(subtreeDescription.contentAvailability); const parsedAvailability = { tileAvailability: parseAvailability(subtreeDescription.tileAvailability), childSubtreeAvailability: parseAvailability( subtreeDescription.childSubtreeAvailability ) }; if (hasContent) { parsedAvailability.contentAvailability = subtreeDescription.contentAvailability.map( parseAvailability ); } if ((0, import_engine27.defined)(subtreeDescription.other)) { parsedAvailability.other = parseAvailability(subtreeDescription.other); } const bufferViewsU8 = { internal: [], external: [], count: 0 }; const useLegacySchema = (0, import_engine27.defaultValue)( subtreeDescription.useLegacySchema, false ); const bufferViewJsonArray = []; gatherBufferViews( bufferViewsU8, bufferViewJsonArray, parsedAvailability.tileAvailability, useLegacySchema ); if (hasContent) { parsedAvailability.contentAvailability.forEach(function(contentAvailability) { gatherBufferViews( bufferViewsU8, bufferViewJsonArray, contentAvailability, useLegacySchema ); }); } gatherBufferViews( bufferViewsU8, bufferViewJsonArray, parsedAvailability.childSubtreeAvailability, useLegacySchema ); if ((0, import_engine27.defined)(parsedAvailability.other)) { gatherBufferViews( bufferViewsU8, bufferViewJsonArray, parsedAvailability.other, useLegacySchema ); } if (bufferViewJsonArray.length > 0) { subtreeJson.bufferViews = bufferViewJsonArray; } subtreeJson.tileAvailability = parsedAvailability.tileAvailability.availabilityJson; subtreeJson.childSubtreeAvailability = parsedAvailability.childSubtreeAvailability.availabilityJson; if (hasContent) { const contentAvailabilityArray = parsedAvailability.contentAvailability; if (useLegacySchema) { subtreeJson.extensions = { "3DTILES_multiple_contents": { contentAvailability: contentAvailabilityArray.map(function(x) { return x.availabilityJson; }) } }; } else if (contentAvailabilityArray.length > 1) { subtreeJson.contentAvailability = contentAvailabilityArray.map(function(x) { return x.availabilityJson; }); } else { subtreeJson.contentAvailability = contentAvailabilityArray[0].availabilityJson; } } const metadata = subtreeDescription.metadata; if ((0, import_engine27.defined)(metadata)) { addMetadata(bufferViewsU8, subtreeJson, metadata, useLegacySchema); } return bufferViewsU8; } function gatherBufferViews(bufferViewsU8, bufferViewJsonArray, parsedBitstream, useLegacySchema) { if ((0, import_engine27.defined)(parsedBitstream.constant)) { parsedBitstream.availabilityJson = { constant: parsedBitstream.constant, availableCount: parsedBitstream.availableCount }; } else if ((0, import_engine27.defined)(parsedBitstream.shareBuffer)) { if (useLegacySchema) { parsedBitstream.availabilityJson = { bufferView: 0, availableCount: parsedBitstream.availableCount }; } else { parsedBitstream.availabilityJson = { bitstream: 0, availableCount: parsedBitstream.availableCount }; } } else { const bufferViewId = bufferViewsU8.count; bufferViewsU8.count++; const bufferViewJson = { buffer: void 0, byteOffset: void 0, byteLength: parsedBitstream.byteLength }; bufferViewJsonArray.push(bufferViewJson); if (useLegacySchema) { parsedBitstream.availabilityJson = { bufferView: bufferViewId, availableCount: parsedBitstream.availableCount }; } else { parsedBitstream.availabilityJson = { bitstream: bufferViewId, availableCount: parsedBitstream.availableCount }; } const bufferView = { bufferView: parsedBitstream.bitstream, // save a reference to the object so we can update the offsets and // lengths later. json: bufferViewJson }; if (parsedBitstream.isInternal) { bufferViewsU8.internal.push(bufferView); } else { bufferViewsU8.external.push(bufferView); } } } function makeSubtreeHeader(jsonByteLength, binaryByteLength) { const buffer = new ArrayBuffer(24); const dataView = new DataView(buffer); const MAGIC = 1952609651; const littleEndian = true; const VERSION2 = 1; dataView.setUint32(0, MAGIC, littleEndian); dataView.setUint32(4, VERSION2, littleEndian); dataView.setUint32(8, jsonByteLength, littleEndian); dataView.setUint32(16, binaryByteLength, littleEndian); return new Uint8Array(buffer); } function makeJsonChunk(json) { const jsonString = JSON.stringify(json); const jsonByteLength = jsonString.length; let paddedLength = jsonByteLength; if (paddedLength % 8 !== 0) { paddedLength += 8 - paddedLength % 8; } let i; const buffer = new Uint8Array(paddedLength); for (i = 0; i < jsonByteLength; i++) { buffer[i] = jsonString.charCodeAt(i); } for (i = jsonByteLength; i < paddedLength; i++) { buffer[i] = " ".charCodeAt(0); } return buffer; } function parseAvailability(availability) { const includeAvailableCount = availability.includeAvailableCount; const parsed = parseAvailabilityDescriptor( availability.descriptor, includeAvailableCount ); parsed.isInternal = availability.isInternal; parsed.shareBuffer = availability.shareBuffer; if ((0, import_engine27.defined)(parsed.constant) && includeAvailableCount) { parsed.availableCount = parsed.constant * availability.lengthBits; } parsed.availabilityJson = void 0; return parsed; } function parseAvailabilityDescriptor(descriptor, includeAvailableCount) { if (typeof descriptor === "number") { return { constant: descriptor }; } const bits = descriptor.split("").map(function(x) { return Number(x); }); const byteLength = Math.ceil(bits.length / 8); let byteLengthWithPadding = byteLength; if (byteLengthWithPadding % 8 !== 0) { byteLengthWithPadding += 8 - byteLengthWithPadding % 8; } let availableCount = 0; const bitstream = new Uint8Array(byteLengthWithPadding); for (let i = 0; i < bits.length; i++) { const bit = bits[i]; availableCount += bit; const byte = i >> 3; const bitIndex = i % 8; bitstream[byte] |= bit << bitIndex; } if (!includeAvailableCount) { availableCount = void 0; } return { byteLength, bitstream, availableCount }; } function addMetadata(bufferViewsU8, subtreeJson, metadataOptions, useLegacySchema) { const propertyTableResults = MetadataTester_default.createPropertyTables( metadataOptions.propertyTables ); if (!(0, import_engine27.defined)(subtreeJson.bufferViews)) { subtreeJson.bufferViews = []; } const bufferViewJsonArray = subtreeJson.bufferViews; const bufferViewArray = metadataOptions.isInternal ? bufferViewsU8.internal : bufferViewsU8.external; const metadataBufferViewsU8 = propertyTableResults.bufferViews; const metadataBufferViewCount = Object.keys(metadataBufferViewsU8).length; for (let i = 0; i < metadataBufferViewCount; i++) { const bufferViewU8 = metadataBufferViewsU8[i]; const bufferViewJson = { buffer: void 0, byteOffset: void 0, byteLength: bufferViewU8.byteLength }; bufferViewJsonArray.push(bufferViewJson); const paddedBufferView = padUint8Array(bufferViewU8); const bufferView = { bufferView: paddedBufferView, // save a reference to the object so we can update the offsets and // lengths later. json: bufferViewJson }; bufferViewArray.push(bufferView); } const firstMetadataIndex = bufferViewsU8.count; const tileTable = propertyTableResults.propertyTables[0]; const tileProperties = getPropertiesObjectFromPropertyTable( tileTable, firstMetadataIndex, useLegacySchema ); const propertyTables = []; if (useLegacySchema) { if (!(0, import_engine27.defined)(subtreeJson.extensions)) { subtreeJson.extensions = {}; } subtreeJson.extensions["3DTILES_metadata"] = { class: tileTable.class, properties: tileProperties }; } else { const tilePropertyTable = { class: tileTable.class, properties: tileProperties, count: tileTable.count }; propertyTables.push(tilePropertyTable); subtreeJson.tileMetadata = 0; } const length2 = propertyTableResults.propertyTables.length; if (length2 > 1) { const contentMetadataIndices = []; for (let i = 1; i < length2; i++) { const contentTable = propertyTableResults.propertyTables[i]; const contentProperties = getPropertiesObjectFromPropertyTable( contentTable, firstMetadataIndex, useLegacySchema ); const contentMetadata = { class: contentTable.class, properties: contentProperties, count: contentTable.count }; propertyTables.push(contentMetadata); const contentMetadataIndex = useLegacySchema ? i - 1 : i; contentMetadataIndices.push(contentMetadataIndex); } subtreeJson.contentMetadata = contentMetadataIndices; } subtreeJson.propertyTables = propertyTables; } function getPropertiesObjectFromPropertyTable(propertyTable, firstMetadataIndex, useLegacySchema) { const tableProperties = propertyTable.properties; const properties = {}; const valuesKey = useLegacySchema ? "bufferView" : "values"; const stringOffsetsKey = useLegacySchema ? "stringOffsetBufferView" : "stringOffsets"; const arrayOffsetsKey = useLegacySchema ? "arrayOffsetBufferView" : "arrayOffsets"; for (const key in tableProperties) { if (tableProperties.hasOwnProperty(key)) { const property = tableProperties[key]; const values = property.values; const stringOffsets = property.stringOffsets; const arrayOffsets = property.arrayOffsets; const propertyJson = {}; propertyJson[valuesKey] = firstMetadataIndex + values; if ((0, import_engine27.defined)(stringOffsets)) { propertyJson[stringOffsetsKey] = firstMetadataIndex + stringOffsets; } if ((0, import_engine27.defined)(arrayOffsets)) { propertyJson[arrayOffsetsKey] = firstMetadataIndex + arrayOffsets; } properties[key] = propertyJson; } } return properties; } function padUint8Array(array) { if (array.length % 8 === 0) { return array; } const paddingLength = 8 - array.length % 8; const padding = new Uint8Array(paddingLength); return concatTypedArrays_default([array, padding]); } function makeBuffers(bufferViewsU8, subtreeJson) { let bufferCount = 0; let byteLength = 0; let typedArrays = []; let i; let bufferView; for (i = 0; i < bufferViewsU8.internal.length; i++) { bufferView = bufferViewsU8.internal[i]; typedArrays.push(bufferView.bufferView); bufferView.json.buffer = bufferCount; bufferView.json.byteOffset = byteLength; byteLength += bufferView.bufferView.length; } const internalBufferU8 = concatTypedArrays_default(typedArrays); if (typedArrays.length > 0) { subtreeJson.buffers.push({ byteLength }); bufferCount += 1; } byteLength = 0; typedArrays = []; for (i = 0; i < bufferViewsU8.external.length; i++) { bufferView = bufferViewsU8.external[i]; typedArrays.push(bufferView.bufferView); bufferView.json.buffer = bufferCount; bufferView.json.byteOffset = byteLength; byteLength += bufferView.bufferView.length; } const externalBufferU8 = concatTypedArrays_default(typedArrays); if (typedArrays.length > 0) { subtreeJson.buffers.push({ // dummy URI, unit tests should mock any requests. uri: "external.bin", byteLength }); } return { internal: internalBufferU8, external: externalBufferU8 }; } var ImplicitTilingTester_default = ImplicitTilingTester; // packages/engine/Specs/Scene/Implicit3DTileContentSpec.js describe( "Scene/Implicit3DTileContent", function() { const tilesetResource = new import__517.Resource({ url: "https://example.com/tileset.json" }); const mockTileset = { modelMatrix: import__517.Matrix4.IDENTITY, statistics: new import__517.Cesium3DTilesetStatistics() }; let metadataSchema; const tileJson = { geometricError: 800, refine: "ADD", boundingVolume: { box: [0, 0, 0, 256, 0, 0, 0, 256, 0, 0, 0, 256] }, transform: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 0, 0, 1], content: { uri: "https://example.com/{level}/{x}/{y}.b3dm", extras: { author: "Cesium" } }, implicitTiling: { subdivisionScheme: "QUADTREE", subtreeLevels: 2, availableLevels: 2, subtrees: { uri: "https://example.com/{level}/{x}/{y}.subtree" } }, extras: { year: "2021" } }; let implicitTileset; let rootCoordinates; const quadtreeJson = { tileAvailability: { constant: 1 }, contentAvailability: { constant: 1 }, childSubtreeAvailability: { constant: 0 } }; const quadtreeBuffer = ImplicitTilingTester_default.generateSubtreeBuffers({ tileAvailability: { descriptor: "11010", bitLength: 5, isInternal: true }, contentAvailability: [ { descriptor: "01010", bitLength: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: "1111000011110000", bitLength: 16, isInternal: true } }).subtreeBuffer; function gatherTilesPreorder(tile, minLevel, maxLevel, result) { const level = tile.implicitCoordinates.level; if (minLevel <= level && level <= maxLevel) { result.push(tile); } for (let i = 0; i < tile.children.length; i++) { gatherTilesPreorder(tile.children[i], minLevel, maxLevel, result); } } function getBoundingBoxArray(tile) { const boundingBox = tile.boundingVolume.boundingVolume; const box = new Array(12); import__517.Cartesian3.pack(boundingBox.center, box); import__517.Matrix3.pack(boundingBox.halfAxes, box, 3); return box; } let scene2; const centerLongitude = -1.31968; const centerLatitude = 0.698874; beforeAll(function() { scene2 = createScene_default(); implicitTileset = new import__517.ImplicitTileset( tilesetResource, tileJson, metadataSchema ); rootCoordinates = new import__517.ImplicitTileCoordinates({ subdivisionScheme: implicitTileset.subdivisionScheme, subtreeLevels: implicitTileset.subtreeLevels, level: 0, x: 0, y: 0, z: 0 }); }); afterAll(function() { scene2.destroyForSpecs(); }); let mockPlaceholderTile; beforeEach(function() { import__517.ResourceCache.clearForSpecs(); mockTileset.statistics.numberOfTilesTotal = 0; mockPlaceholderTile = new import__517.Cesium3DTile(mockTileset, tilesetResource, { geometricError: 400, boundingVolume: { box: [0, 0, 0, 256, 0, 0, 0, 256, 0, 0, 0, 256] }, transform: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 0, 0, 1], // For testing that tile metadata is ignored by transcoded children metadata: { class: "tile", properties: { tightBoundingVolume: [0, 0, 0, 64, 0, 0, 0, 64, 0, 0, 0, 64] } } }); mockPlaceholderTile.implicitCoordinates = rootCoordinates; mockPlaceholderTile.implicitTileset = implicitTileset; const center = import__517.Cartesian3.fromRadians(centerLongitude, centerLatitude); scene2.camera.lookAt(center, new import__517.HeadingPitchRange(0, -1.57, 26)); }); afterEach(function() { scene2.primitives.removeAll(); import__517.ResourceCache.clearForSpecs(); }); it("loads subtree using JSON", async function() { await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, quadtreeJson ); const expectedChildrenCounts = [4, 0, 0, 0, 0]; const tiles = []; const subtreeRootTile = mockPlaceholderTile.children[0]; gatherTilesPreorder(subtreeRootTile, 0, 1, tiles); expect(expectedChildrenCounts.length).toEqual(tiles.length); for (let i = 0; i < tiles.length; i++) { expect(tiles[i].children.length).toEqual(expectedChildrenCounts[i]); } expect(mockTileset.statistics.numberOfTilesTotal).toBe(tiles.length); }); it("expands subtree", async function() { await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, void 0, quadtreeBuffer, 0 ); const expectedChildrenCounts = [2, 4, 0, 0, 0, 0, 4, 0, 0, 0, 0]; const tiles = []; const subtreeRootTile = mockPlaceholderTile.children[0]; gatherTilesPreorder(subtreeRootTile, 0, 2, tiles); expect(expectedChildrenCounts.length).toEqual(tiles.length); for (let i = 0; i < tiles.length; i++) { expect(tiles[i].children.length).toEqual(expectedChildrenCounts[i]); } expect(mockTileset.statistics.numberOfTilesTotal).toBe(tiles.length); }); it("sets tile coordinates on each tile", async function() { await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, void 0, quadtreeBuffer, 0 ); const expectedCoordinates = [ [0, 0, 0], [1, 0, 0], [2, 0, 0], [2, 1, 0], [2, 0, 1], [2, 1, 1], [1, 0, 1], [2, 0, 2], [2, 1, 2], [2, 0, 3], [2, 1, 3] ]; const tiles = []; const subtreeRootTile = mockPlaceholderTile.children[0]; gatherTilesPreorder(subtreeRootTile, 0, 2, tiles); for (let i = 0; i < tiles.length; i++) { const expected = expectedCoordinates[i]; const coordinates = new import__517.ImplicitTileCoordinates({ subdivisionScheme: implicitTileset.subdivisionScheme, subtreeLevels: implicitTileset.subtreeLevels, level: expected[0], x: expected[1], y: expected[2] }); expect(tiles[i].implicitCoordinates).toEqual(coordinates); } }); it("handles deeper subtrees correctly", async function() { mockPlaceholderTile.implicitCoordinates = new import__517.ImplicitTileCoordinates({ subdivisionScheme: implicitTileset.subdivisionScheme, subtreeLevels: implicitTileset.subtreeLevels, level: 2, x: 2, y: 1 }); await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, void 0, quadtreeBuffer, 0 ); const refine = implicitTileset.refine === "ADD" ? import__517.Cesium3DTileRefine.ADD : import__517.Cesium3DTileRefine.REPLACE; const parentCoordinates = mockPlaceholderTile.implicitCoordinates; const childCoordinates = parentCoordinates.getChildCoordinates(0); const parentGeometricError = implicitTileset.geometricError / 4; const childGeometricError = implicitTileset.geometricError / 8; const rootBoundingVolume = [10, 0, 0, 256, 0, 0, 0, 256, 0, 0, 0, 256]; const parentBox = import__517.Implicit3DTileContent._deriveBoundingBox( rootBoundingVolume, parentCoordinates.level, parentCoordinates.x, parentCoordinates.y ); const childBox = import__517.Implicit3DTileContent._deriveBoundingBox( rootBoundingVolume, childCoordinates.level, childCoordinates.x, childCoordinates.y ); const subtreeRootTile = mockPlaceholderTile.children[0]; const childTile = subtreeRootTile.children[0]; expect(subtreeRootTile.implicitCoordinates).toEqual(parentCoordinates); expect(childTile.implicitCoordinates).toEqual(childCoordinates); expect(subtreeRootTile.refine).toEqual(refine); expect(childTile.refine).toEqual(refine); expect(subtreeRootTile.geometricError).toEqual(parentGeometricError); expect(childTile.geometricError).toEqual(childGeometricError); expect(getBoundingBoxArray(subtreeRootTile)).toEqual(parentBox); expect(getBoundingBoxArray(childTile)).toEqual(childBox); const tiles = []; gatherTilesPreorder(subtreeRootTile, 2, 4, tiles); expect(mockTileset.statistics.numberOfTilesTotal).toBe(tiles.length); }); it("puts the root tile inside the placeholder tile", async function() { await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, void 0, quadtreeBuffer, 0 ); expect(mockPlaceholderTile.children.length).toEqual(1); }); it("does not propagate explicit tile metadata", async function() { await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, void 0, quadtreeBuffer, 0 ); const tiles = []; const subtreeRootTile = mockPlaceholderTile.children[0]; gatherTilesPreorder(subtreeRootTile, 0, 4, tiles); for (let i = 0; i < tiles.length; i++) { expect(tiles[i].metadata).not.toBeDefined(); } }); it("preserves tile extras", async function() { await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, void 0, quadtreeBuffer, 0 ); expect(mockPlaceholderTile.children[0].extras).toEqual(tileJson.extras); }); it("stores a reference to the subtree in each transcoded tile", async function() { await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, void 0, quadtreeBuffer, 0 ); expect(mockPlaceholderTile.implicitSubtree).not.toBeDefined(); const subtreeRootTile = mockPlaceholderTile.children[0]; const subtree = subtreeRootTile.implicitSubtree; expect(subtree).toBeDefined(); const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 1, tiles); for (let i = 0; i < tiles.length; i++) { expect(tiles[i].implicitSubtree).toBe(subtree); } }); it("does not store references to subtrees in placeholder tiles", async function() { await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, void 0, quadtreeBuffer, 0 ); expect(mockPlaceholderTile.implicitSubtree).not.toBeDefined(); const subtreeRootTile = mockPlaceholderTile.children[0]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 2, 2, tiles); for (let i = 0; i < tiles.length; i++) { expect(tiles[i].implicitSubtree).not.toBeDefined(); } }); it("destroys", async function() { const content = await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, void 0, quadtreeBuffer, 0 ); const subtree = content._implicitSubtree; expect(content.isDestroyed()).toBe(false); expect(subtree.isDestroyed()).toBe(false); content.destroy(); expect(content.isDestroyed()).toBe(true); expect(subtree.isDestroyed()).toBe(true); }); it("returns default values for most Cesium3DTileContent properties", async function() { const content = await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, void 0, quadtreeBuffer, 0 ); expect(content.featurePropertiesDirty).toBe(false); expect(content.featuresLength).toBe(0); expect(content.pointsLength).toBe(0); expect(content.trianglesLength).toBe(0); expect(content.geometryByteLength).toBe(0); expect(content.texturesByteLength).toBe(0); expect(content.batchTableByteLength).toBe(0); expect(content.innerContents).not.toBeDefined(); expect(content.tileset).toBe(mockTileset); expect(content.tile).toBe(mockPlaceholderTile); expect(content.batchTable).not.toBeDefined(); }); it("url returns the subtree url", async function() { const content = await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, void 0, quadtreeBuffer, 0 ); expect(content.url).toBe("https://example.com/0/0/0.subtree"); }); it("templates content URIs for each tile with content", async function() { await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, void 0, quadtreeBuffer, 0 ); const expectedCoordinates = [ [0, 0, 0], [1, 0, 0], [1, 0, 1] ]; const contentAvailability = [false, true, true]; const templateUri = implicitTileset.contentUriTemplates[0]; const subtreeRootTile = mockPlaceholderTile.children[0]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 1, tiles); expect(expectedCoordinates.length).toEqual(tiles.length); for (let i = 0; i < tiles.length; i++) { const expected = expectedCoordinates[i]; const coordinates = new import__517.ImplicitTileCoordinates({ subdivisionScheme: implicitTileset.subdivisionScheme, subtreeLevels: implicitTileset.subtreeLevels, level: expected[0], x: expected[1], y: expected[2] }); const expectedResource = templateUri.getDerivedResource({ templateValues: coordinates.getTemplateValues() }); if (contentAvailability[i]) { expect(tiles[i]._contentResource.url).toEqual(expectedResource.url); } else { expect(tiles[i]._contentResource).not.toBeDefined(); } } }); it("constructs placeholder tiles for child subtrees", async function() { await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, void 0, quadtreeBuffer, 0 ); const expectedCoordinates = [ [2, 0, 0], [2, 1, 0], [2, 0, 1], [2, 1, 1], [2, 0, 2], [2, 1, 2], [2, 0, 3], [2, 1, 3] ]; const templateUri = implicitTileset.subtreeUriTemplate; const subtreeRootTile = mockPlaceholderTile.children[0]; let tiles = []; gatherTilesPreorder(subtreeRootTile, 2, 2, tiles); expect(expectedCoordinates.length).toEqual(tiles.length); for (let i = 0; i < tiles.length; i++) { const expected = expectedCoordinates[i]; const coordinates = new import__517.ImplicitTileCoordinates({ subdivisionScheme: implicitTileset.subdivisionScheme, subtreeLevels: implicitTileset.subtreeLevels, level: expected[0], x: expected[1], y: expected[2] }); const expectedResource = templateUri.getDerivedResource({ templateValues: coordinates.getTemplateValues() }); const placeholderTile = tiles[i]; expect(placeholderTile._contentResource.url).toEqual( expectedResource.url ); expect(placeholderTile.implicitTileset).toBeDefined(); expect(placeholderTile.implicitCoordinates).toBeDefined(); } tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 2, tiles); expect(mockTileset.statistics.numberOfTilesTotal).toBe(tiles.length); }); it("propagates refine down the tree", async function() { await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, void 0, quadtreeBuffer, 0 ); const refine = implicitTileset.refine === "ADD" ? import__517.Cesium3DTileRefine.ADD : import__517.Cesium3DTileRefine.REPLACE; const subtreeRootTile = mockPlaceholderTile.children[0]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 2, tiles); for (let i = 0; i < tiles.length; i++) { expect(tiles[i].refine).toEqual(refine); } }); it("divides the geometricError by 2 for each level of the tree", async function() { await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, void 0, quadtreeBuffer, 0 ); const rootGeometricError = implicitTileset.geometricError; const subtreeRootTile = mockPlaceholderTile.children[0]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 2, tiles); for (let i = 0; i < tiles.length; i++) { const level = tiles[i].implicitCoordinates.level; expect(tiles[i].geometricError).toEqual( rootGeometricError / Math.pow(2, level) ); } }); it("subdivides bounding volumes for each tile", async function() { await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, void 0, quadtreeBuffer, 0 ); const expectedCoordinates = [ [0, 0, 0], [1, 0, 0], [2, 0, 0], [2, 1, 0], [2, 0, 1], [2, 1, 1], [1, 0, 1], [2, 0, 2], [2, 1, 2], [2, 0, 3], [2, 1, 3] ]; const rootBoundingVolume = [10, 0, 0, 256, 0, 0, 0, 256, 0, 0, 0, 256]; const subtreeRootTile = mockPlaceholderTile.children[0]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 2, tiles); expect(expectedCoordinates.length).toEqual(tiles.length); for (let i = 0; i < tiles.length; i++) { const coordinates = expectedCoordinates[i]; const boundingBox = tiles[i].boundingVolume.boundingVolume; const childBox = new Array(12); import__517.Cartesian3.pack(boundingBox.center, childBox); import__517.Matrix3.pack(boundingBox.halfAxes, childBox, 3); const expectedBounds = import__517.Implicit3DTileContent._deriveBoundingBox( rootBoundingVolume, coordinates[0], coordinates[1], coordinates[2] ); expect(childBox).toEqual(expectedBounds); } }); it("propagates transform", async function() { await import__517.Implicit3DTileContent.fromSubtreeJson( mockTileset, mockPlaceholderTile, tilesetResource, void 0, quadtreeBuffer, 0 ); const subtreeRootTile = mockPlaceholderTile.children[0]; expect(subtreeRootTile.computedTransform).toEqual( mockPlaceholderTile.transform ); }); describe("_deriveBoundingVolumeS2", function() { const deriveBoundingVolumeS2 = import__517.Implicit3DTileContent._deriveBoundingVolumeS2; const simpleBoundingVolumeS2 = { token: "1", minimumHeight: 0, maximumHeight: 10 }; const simpleBoundingVolumeS2Cell = new import__517.TileBoundingS2Cell( simpleBoundingVolumeS2 ); const implicitTilesetS2 = { boundingVolume: { extensions: { "3DTILES_bounding_volume_S2": simpleBoundingVolumeS2 } }, subdivisionScheme: import__517.ImplicitSubdivisionScheme.QUADTREE }; it("throws if parentIsPlaceholderTile is undefined", function() { expect(function() { deriveBoundingVolumeS2(void 0, {}, 0, 0, 0, 0, 0); }).toThrowDeveloperError(); }); it("throws if parentTile is undefined", function() { expect(function() { deriveBoundingVolumeS2(false, void 0, 0, 0, 0, 0, 0); }).toThrowDeveloperError(); }); it("throws if childIndex is undefined", function() { expect(function() { deriveBoundingVolumeS2(false, {}, void 0, 0, 0, 0, 0); }).toThrowDeveloperError(); }); it("throws if level is undefined", function() { expect(function() { deriveBoundingVolumeS2(false, {}, 0, void 0, 0, 0, 0); }).toThrowDeveloperError(); }); it("throws if x is undefined", function() { expect(function() { deriveBoundingVolumeS2(false, {}, 0, 0, void 0, 0, 0); }).toThrowDeveloperError(); }); it("throws if y is undefined", function() { expect(function() { deriveBoundingVolumeS2(false, {}, 0, 0, 0, void 0, 0); }).toThrowDeveloperError(); }); it("throws if z is defined but not a number", function() { expect(function() { deriveBoundingVolumeS2(false, {}, 0, 0, 0, 0, ""); }).toThrowDeveloperError(); }); it("returns implicit tileset boundingVolume if parentIsPlaceholderTile is true", function() { const placeholderTile = { _boundingVolume: simpleBoundingVolumeS2Cell }; const result = deriveBoundingVolumeS2( true, placeholderTile, 0, 0, 0, 0, 0 ); expect(result).toEqual(implicitTilesetS2.boundingVolume); expect(result).not.toBe(implicitTilesetS2.boundingVolume); }); it("subdivides correctly using QUADTREE", function() { const parentTile = { _boundingVolume: simpleBoundingVolumeS2Cell }; let expected = { token: "04", minimumHeight: 0, maximumHeight: 10 }; let result = deriveBoundingVolumeS2(false, parentTile, 0, 1, 0, 0); expect(result).toEqual({ extensions: { "3DTILES_bounding_volume_S2": expected } }); parentTile._boundingVolume = new import__517.TileBoundingS2Cell({ token: "3", minimumHeight: 0, maximumHeight: 10 }); expected = { token: "24", minimumHeight: 0, maximumHeight: 10 }; result = deriveBoundingVolumeS2(false, parentTile, 0, 1, 0, 0); expect(result).toEqual({ extensions: { "3DTILES_bounding_volume_S2": expected } }); }); it("subdivides correctly using OCTREE", function() { implicitTilesetS2.subdivisionScheme = import__517.ImplicitSubdivisionScheme.OCTREE; const parentTile = { _boundingVolume: simpleBoundingVolumeS2Cell }; const expected0 = { token: "04", minimumHeight: 0, maximumHeight: 5 }; const expected1 = { token: "04", minimumHeight: 5, maximumHeight: 10 }; const result0 = deriveBoundingVolumeS2( false, parentTile, 0, 1, 0, 0, 0 ); expect(result0).toEqual({ extensions: { "3DTILES_bounding_volume_S2": expected0 } }); const result1 = deriveBoundingVolumeS2( false, parentTile, 4, 1, 0, 0, 0 ); expect(result1).toEqual({ extensions: { "3DTILES_bounding_volume_S2": expected1 } }); }); }); describe("_deriveBoundingBox", function() { const deriveBoundingBox = import__517.Implicit3DTileContent._deriveBoundingBox; const simpleBoundingBox = [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]; it("throws if rootBox is undefined", function() { expect(function() { deriveBoundingBox(void 0, 0, 0, 0); }).toThrowDeveloperError(); }); it("throws if level is undefined", function() { expect(function() { deriveBoundingBox(simpleBoundingBox, void 0, 0, 0); }).toThrowDeveloperError(); }); it("throws if x is undefined", function() { expect(function() { deriveBoundingBox(simpleBoundingBox, 1, void 0, 0); }).toThrowDeveloperError(); }); it("throws if y is undefined", function() { expect(function() { deriveBoundingBox(simpleBoundingBox, 1, 0, void 0); }).toThrowDeveloperError(); }); it("subdivides like a quadtree if z is not given", function() { const tile = [1, 3, 0, 4, 0, 0, 0, 2, 0, 0, 0, 1]; const expected = [0, 1.5, 0, 1, 0, 0, 0, 0.5, 0, 0, 0, 1]; const result = deriveBoundingBox(tile, 2, 1, 0); expect(result).toEqual(expected); }); it("subdivides like an octree if z is given", function() { const tile = [1, 3, 0, 4, 0, 0, 0, 2, 0, 0, 0, 1]; const expected = [0, 1.5, 0.25, 1, 0, 0, 0, 0.5, 0, 0, 0, 0.25]; const result = deriveBoundingBox(tile, 2, 1, 0, 2); expect(result).toEqual(expected); }); it("handles rotation and non-uniform scaling correctly", function() { const tile = [1, 2, 3, 0, 4, 0, 0, 0, 2, 1, 0, 0]; const expected = [1.25, 1, 1.5, 0, 1, 0, 0, 0, 0.5, 0.25, 0, 0]; const result = deriveBoundingBox(tile, 2, 1, 0, 2); expect(result).toEqual(expected); }); }); describe("_deriveBoundingRegion", function() { const deriveBoundingRegion = import__517.Implicit3DTileContent._deriveBoundingRegion; const simpleRegion = [ 0, 0, import__517.Math.PI_OVER_FOUR, import__517.Math.PI_OVER_FOUR, 0, 100 ]; it("throws if rootRegion is undefined", function() { expect(function() { deriveBoundingRegion(void 0, 1, 0, 0); }).toThrowDeveloperError(); }); it("throws if level is undefined", function() { expect(function() { deriveBoundingRegion(simpleRegion, void 0, 0, 0); }).toThrowDeveloperError(); }); it("throws if x is undefined", function() { expect(function() { deriveBoundingRegion(simpleRegion, 1, void 0, 0); }).toThrowDeveloperError(); }); it("throws if y is undefined", function() { expect(function() { deriveBoundingRegion(simpleRegion, 1, 0, void 0); }).toThrowDeveloperError(); }); function makeRectangle(westDegrees, southDegrees, eastDegrees, northDegrees, minimumHeight, maximumHeight) { return [ import__517.Math.toRadians(westDegrees), import__517.Math.toRadians(southDegrees), import__517.Math.toRadians(eastDegrees), import__517.Math.toRadians(northDegrees), minimumHeight, maximumHeight ]; } it("subdivides like a quadtree if z is not given", function() { const tile = makeRectangle(-1, -2, 3, 2, 0, 20); const expected = makeRectangle(0, 1, 1, 2, 0, 20); const result = deriveBoundingRegion(tile, 2, 1, 3); expect(result).toEqualEpsilon(expected, import__517.Math.EPSILON9); }); it("deriveVolume subdivides like an octree if z is given", function() { const tile = makeRectangle(-1, -2, 3, 2, 0, 20); const expected = makeRectangle(0, 1, 1, 2, 10, 15); const result = deriveBoundingRegion(tile, 2, 1, 3, 2); expect(result).toEqualEpsilon(expected, import__517.Math.EPSILON9); }); it("handles the IDL", function() { const tile = makeRectangle(90, -45, -90, 45, 0, 20); const expected = makeRectangle(180, -45, -90, 0, 0, 20); const result = deriveBoundingRegion(tile, 1, 1, 0); expect(result).toEqualEpsilon(expected, import__517.Math.EPSILON9); }); }); describe("multiple contents", function() { const implicitMultipleContentsUrl = "Data/Cesium3DTiles/Implicit/ImplicitMultipleContents/tileset_1.1.json"; it("a single content is transcoded as a regular tile", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitMultipleContentsUrl ).then(function(tileset) { const transcodedRoot = tileset.root.children[0]; const transcodedRootHeader = transcodedRoot._header; expect(transcodedRoot.content).toBeInstanceOf(import__517.Model3DTileContent); expect(transcodedRootHeader.contents[0]).toEqual({ uri: "ground/0/0/0.b3dm" }); expect(transcodedRootHeader.extensions).not.toBeDefined(); }); }); it("multiple contents are transcoded to a tile", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitMultipleContentsUrl ).then(function(tileset) { const childTiles = tileset.root.children[0].children; for (let i = 0; i < childTiles.length; i++) { const childTile = childTiles[i]; const content = childTile.content; expect(content).toBeInstanceOf(import__517.Multiple3DTileContent); const childTileHeader = childTile._header; expect(childTileHeader.content).not.toBeDefined(); } }); }); }); describe("3DTILES_multiple_contents", function() { const implicitMultipleContentsLegacyUrl = "Data/Cesium3DTiles/Implicit/ImplicitMultipleContents/tileset_1.0.json"; const implicitMultipleContentsLegacyWithContentUrl = "Data/Cesium3DTiles/Implicit/ImplicitMultipleContents/tileset_1.0_content.json"; it("a single content is transcoded as a regular tile (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitMultipleContentsLegacyUrl ).then(function(tileset) { const transcodedRoot = tileset.root.children[0]; const transcodedRootHeader = transcodedRoot._header; expect(transcodedRoot.content).toBeInstanceOf(import__517.Model3DTileContent); expect(transcodedRootHeader.contents[0]).toEqual({ uri: "ground/0/0/0.b3dm" }); expect(transcodedRootHeader.extensions).not.toBeDefined(); }); }); it("a single content is transcoded as a regular tile (legacy with 'content')", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitMultipleContentsLegacyWithContentUrl ).then(function(tileset) { const transcodedRoot = tileset.root.children[0]; const transcodedRootHeader = transcodedRoot._header; expect(transcodedRoot.content).toBeInstanceOf(import__517.Model3DTileContent); expect(transcodedRootHeader.contents[0]).toEqual({ uri: "ground/0/0/0.b3dm" }); expect(transcodedRootHeader.extensions).not.toBeDefined(); }); }); it("multiple contents are transcoded to a tile (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitMultipleContentsLegacyUrl ).then(function(tileset) { const childTiles = tileset.root.children[0].children; for (let i = 0; i < childTiles.length; i++) { const childTile = childTiles[i]; const content = childTile.content; expect(content).toBeInstanceOf(import__517.Multiple3DTileContent); const childTileHeader = childTile._header; expect(childTileHeader.content).not.toBeDefined(); } }); }); it("multiple contents are transcoded to a tile (legacy with 'content')", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitMultipleContentsLegacyWithContentUrl ).then(function(tileset) { const childTiles = tileset.root.children[0].children; for (let i = 0; i < childTiles.length; i++) { const childTile = childTiles[i]; const content = childTile.content; expect(content).toBeInstanceOf(import__517.Multiple3DTileContent); const childTileHeader = childTile._header; expect(childTileHeader.content).not.toBeDefined(); } }); }); it("passes extensions through correctly (legacy)", function() { const originalLoadJson = import__517.Cesium3DTileset.loadJson; const metadataExtension = { group: "buildings" }; const otherExtension = { someKey: "someValue" }; spyOn(import__517.Cesium3DTileset, "loadJson").and.callFake(function(tilesetUrl) { return originalLoadJson(tilesetUrl).then(function(tilesetJson) { const multiContent = tilesetJson.root.extensions["3DTILES_multiple_contents"]; multiContent.contents.forEach(function(content) { content.extensions = { "3DTILES_metadata": metadataExtension }; }); tilesetJson.root.extensions["3DTILES_extension"] = otherExtension; tilesetJson.extensionsUsed.push("3DTILES_metadata"); tilesetJson.extensions = {}; tilesetJson.extensions["3DTILES_metadata"] = { schema: {} }; return tilesetJson; }); }); return Cesium3DTilesTester_default.loadTileset( scene2, implicitMultipleContentsLegacyUrl ).then(function(tileset) { const placeholderTile = tileset.root; const placeholderHeader = placeholderTile._header; expect(placeholderHeader.extensions).not.toBeDefined(); expect(placeholderHeader.contents[0].extensions).not.toBeDefined(); const transcodedRoot = placeholderTile.children[0]; const transcodedRootHeader = transcodedRoot._header; expect(transcodedRootHeader.extensions).toEqual({ "3DTILES_extension": otherExtension }); expect(transcodedRootHeader.contents[0].extensions).toEqual({ "3DTILES_metadata": metadataExtension }); const childTiles = transcodedRoot.children; for (let i = 0; i < childTiles.length; i++) { const childTile = childTiles[i]; const childTileHeader = childTile._header; expect(childTileHeader.extensions["3DTILES_extension"]).toEqual( otherExtension ); const innerContentHeaders = childTileHeader.contents; innerContentHeaders.forEach(function(header) { expect(header.extensions).toEqual({ "3DTILES_metadata": metadataExtension }); }); } }); }); }); describe("metadata", function() { const implicitTilesetUrl = "Data/Cesium3DTiles/Implicit/ImplicitTileset/tileset_1.1.json"; const implicitGroupMetadataUrl = "Data/Cesium3DTiles/Metadata/ImplicitGroupMetadata/tileset_1.1.json"; const implicitContentMetadataUrl = "Data/Cesium3DTiles/Metadata/ImplicitContentMetadata/tileset_1.1.json"; const implicitMultipleContentsMetadataUrl = "Data/Cesium3DTiles/Metadata/ImplicitMultipleContentsWithMetadata/tileset_1.1.json"; const implicitHeightSemanticsUrl = "Data/Cesium3DTiles/Metadata/ImplicitHeightSemantics/tileset_1.1.json"; const implicitS2HeightSemanticsUrl = "Data/Cesium3DTiles/Metadata/ImplicitHeightSemantics/s2-tileset_1.1.json"; const implicitTileBoundingVolumeSemanticsUrl = "Data/Cesium3DTiles/Metadata/ImplicitTileBoundingVolumeSemantics/tileset_1.1.json"; const implicitHeightAndSphereSemanticsUrl = "Data/Cesium3DTiles/Metadata/ImplicitHeightAndSphereSemantics/tileset_1.1.json"; const implicitHeightAndRegionSemanticsUrl = "Data/Cesium3DTiles/Metadata/ImplicitHeightAndRegionSemantics/tileset_1.1.json"; const implicitContentBoundingVolumeSemanticsUrl = "Data/Cesium3DTiles/Metadata/ImplicitContentBoundingVolumeSemantics/tileset_1.1.json"; const implicitContentHeightSemanticsUrl = "Data/Cesium3DTiles/Metadata/ImplicitContentHeightSemantics/tileset_1.1.json"; const implicitContentHeightAndRegionSemanticsUrl = "Data/Cesium3DTiles/Metadata/ImplicitContentHeightAndRegionSemantics/tileset_1.1.json"; const implicitGeometricErrorSemanticsUrl = "Data/Cesium3DTiles/Metadata/ImplicitGeometricErrorSemantics/tileset_1.1.json"; let groupMetadataClass; let groupMetadata; beforeAll(function() { groupMetadataClass = import__517.MetadataClass.fromJson({ id: "test", class: { properties: { name: { type: "STRING" }, height: { type: "SCALAR", componentType: "FLOAT32" } } } }); groupMetadata = new import__517.GroupMetadata({ id: "testGroup", group: { properties: { name: "Test Group", height: 35.6 } }, class: groupMetadataClass }); }); it("assigns group metadata", function() { return Cesium3DTilesTester_default.loadTileset(scene2, implicitTilesetUrl).then( function(tileset) { const content = tileset.root.content; content.group = new import__517.Cesium3DContentGroup({ metadata: groupMetadata }); expect(content.group.metadata).toBe(groupMetadata); } ); }); it("group metadata gets transcoded correctly", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitGroupMetadataUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 2, tiles); const groups = tileset.metadataExtension.groups; const ground = groups[0]; expect(ground.getProperty("color")).toEqual( new import__517.Cartesian3(120, 68, 32) ); expect(ground.getProperty("priority")).toBe(0); const sky = groups[1]; expect(sky.getProperty("color")).toEqual( new import__517.Cartesian3(206, 237, 242) ); expect(sky.getProperty("priority")).toBe(1); tiles.forEach(function(tile) { if (tile.hasMultipleContents) { const contents = tile.content.innerContents; expect(contents[0].group.metadata).toBe(ground); expect(contents[1].group.metadata).toBe(sky); } else { expect(tile.content.group.metadata).toBe(ground); } }); }); }); it("assigning content metadata throws", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitContentMetadataUrl ).then(function(tileset) { expect(function() { const placeholderTile = tileset.root; const content = placeholderTile.content; content.metadata = {}; }).toThrowDeveloperError(); }); }); it("content metadata gets transcoded correctly", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitContentMetadataUrl ).then(function(tileset) { const expectedHeights = [10, 20, 0, 30, 40]; const expectedColors = [ new import__517.Cartesian3(255, 255, 255), new import__517.Cartesian3(255, 0, 0), import__517.Cartesian3.ZERO, new import__517.Cartesian3(0, 255, 0), new import__517.Cartesian3(0, 0, 255) ]; const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 2, tiles); for (let i = 0; i < tiles.length; i++) { const tile = tiles[i]; const subtree = tile.implicitSubtree; const coordinates = tile.implicitCoordinates; const index = coordinates.tileIndex; const metadata = tile.content.metadata; if (!subtree.contentIsAvailableAtIndex(index, 0)) { expect(metadata.getProperty("height")).not.toBeDefined(); expect(metadata.getProperty("color")).not.toBeDefined(); } else { expect(metadata.getProperty("height")).toBe( expectedHeights[index] ); expect(metadata.getProperty("color")).toEqual( expectedColors[index] ); } } }); }); it("multiple content metadata views get transcoded correctly", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitMultipleContentsMetadataUrl ).then(function(tileset) { const expectedHeights = [10, 20, 30, 40, 50]; const expectedColors = [ new import__517.Cartesian3(255, 255, 255), new import__517.Cartesian3(255, 0, 0), new import__517.Cartesian3(255, 255, 0), new import__517.Cartesian3(0, 255, 0), new import__517.Cartesian3(0, 0, 255) ]; const expectedAges = [21, 7, 11, 16]; const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 2, tiles); for (let i = 0; i < tiles.length; i++) { const tile = tiles[i]; const coordinates = tile.implicitCoordinates; const index = coordinates.tileIndex; let buildingMetadata; if (i > 0) { expect(tile.hasMultipleContents).toBe(true); const buildingContent = tile.content.innerContents[0]; buildingMetadata = buildingContent.metadata; } else { expect(tile.hasMultipleContents).toBe(false); buildingMetadata = tile.content.metadata; } expect(buildingMetadata.getProperty("height")).toBe( expectedHeights[index] ); expect(buildingMetadata.getProperty("color")).toEqual( expectedColors[index] ); if (i === 0) { continue; } const treeContent = tile.content.innerContents[1]; const treeMetadata = treeContent.metadata; expect(treeMetadata.getProperty("age")).toEqual( expectedAges[index - 1] ); } }); }); function viewCartographicOrigin(height) { const center = import__517.Cartesian3.fromDegrees(0, 0); const offset = new import__517.Cartesian3(0, 0, height); scene2.camera.lookAt(center, offset); } it("uses height semantics to adjust region bounding volumes", function() { viewCartographicOrigin(1e4); return Cesium3DTilesTester_default.loadTileset( scene2, implicitHeightSemanticsUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const implicitRegion = placeholderTile.implicitTileset.boundingVolume.region; const minimumHeight = implicitRegion[4]; const maximumHeight = implicitRegion[5]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); for (let i = 0; i < tiles.length; i++) { const tileRegion = tiles[i].boundingVolume; expect(tileRegion.minimumHeight).toBeGreaterThan(minimumHeight); expect(tileRegion.maximumHeight).toBeLessThan(maximumHeight); } }); }); it("uses height semantics to adjust S2 bounding volumes", function() { viewCartographicOrigin(1e4); return Cesium3DTilesTester_default.loadTileset( scene2, implicitS2HeightSemanticsUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const implicitS2Volume = placeholderTile.implicitTileset.boundingVolume.extensions["3DTILES_bounding_volume_S2"]; const minimumHeight = implicitS2Volume.minimumHeight; const maximumHeight = implicitS2Volume.maximumHeight; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); for (let i = 0; i < tiles.length; i++) { const tileS2Volume = tiles[i].boundingVolume; expect(tileS2Volume.minimumHeight).toBeGreaterThan(minimumHeight); expect(tileS2Volume.maximumHeight).toBeLessThan(maximumHeight); } }); }); function getHalfWidth(boundingBox) { return boundingBox.boundingVolume.halfAxes[0]; } it("ignores height semantics if the implicit volume is a box", function() { const cameraHeight = 100; const rootHalfWidth = 10; const originalLoadJson = import__517.Cesium3DTileset.loadJson; spyOn(import__517.Cesium3DTileset, "loadJson").and.callFake(function(tilesetUrl) { return originalLoadJson(tilesetUrl).then(function(tilesetJson) { tilesetJson.root.boundingVolume = { box: [ import__517.Ellipsoid.WGS84.radii.x + cameraHeight, 0, 0, rootHalfWidth, 0, 0, 0, rootHalfWidth, 0, 0, 0, rootHalfWidth ] }; return tilesetJson; }); }); viewCartographicOrigin(cameraHeight); return Cesium3DTilesTester_default.loadTileset( scene2, implicitHeightSemanticsUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); tiles.forEach(function(tile) { const level = tile.implicitCoordinates.level; const halfWidth = getHalfWidth(tile.boundingVolume); expect(halfWidth).toEqual(rootHalfWidth / Math.pow(2, level)); }); }); }); it("uses tile bounding box from metadata semantics if present", function() { viewCartographicOrigin(124e3); return Cesium3DTilesTester_default.loadTileset( scene2, implicitTileBoundingVolumeSemanticsUrl ).then(function(tileset) { const placeholderTile = tileset.root.children[0]; const subtreeRootTile = placeholderTile.children[0]; const rootHalfWidth = 2048; expect(getHalfWidth(subtreeRootTile.boundingVolume)).toBe( rootHalfWidth ); for (let level = 1; level < 4; level++) { const halfWidthAtLevel = rootHalfWidth / (1 << level); const tiles = []; gatherTilesPreorder(subtreeRootTile, level, level, tiles); for (let i = 0; i < tiles.length; i++) { const tile = tiles[i]; const halfWidth = getHalfWidth(tile.boundingVolume); expect(halfWidth).toBeLessThan(halfWidthAtLevel); } } }); }); it("prioritizes height semantics over bounding volume semantics", function() { viewCartographicOrigin(1e4); return Cesium3DTilesTester_default.loadTileset( scene2, implicitHeightAndSphereSemanticsUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const implicitRegion = placeholderTile.implicitTileset.boundingVolume.region; const minimumHeight = implicitRegion[4]; const maximumHeight = implicitRegion[5]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); for (let i = 0; i < tiles.length; i++) { const tileRegion = tiles[i].boundingVolume; expect(tileRegion.minimumHeight).toBeDefined(); expect(tileRegion.maximumHeight).toBeDefined(); expect(tileRegion.minimumHeight).toBeGreaterThan(minimumHeight); expect(tileRegion.maximumHeight).toBeLessThan(maximumHeight); } }); }); it("uses height semantics to adjust region semantic", function() { viewCartographicOrigin(1e4); return Cesium3DTilesTester_default.loadTileset( scene2, implicitHeightAndRegionSemanticsUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const implicitRegion = placeholderTile.implicitTileset.boundingVolume.region; const west = implicitRegion[0]; const south = implicitRegion[1]; const east = implicitRegion[2]; const north = implicitRegion[3]; const minimumHeight = implicitRegion[4]; const maximumHeight = implicitRegion[5]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); for (let i = 0; i < tiles.length; i++) { const tileRegion = tiles[i].boundingVolume; expect(tileRegion.minimumHeight).toBeGreaterThan(minimumHeight); expect(tileRegion.maximumHeight).toBeLessThan(maximumHeight); expect(tileRegion.rectangle.west).toBeGreaterThan(west); expect(tileRegion.rectangle.south).toBeGreaterThan(south); expect(tileRegion.rectangle.east).toBeLessThan(east); expect(tileRegion.rectangle.north).toBeLessThan(north); } }); }); it("uses content bounding box from metadata semantics if present", function() { viewCartographicOrigin(124e3); return Cesium3DTilesTester_default.loadTileset( scene2, implicitContentBoundingVolumeSemanticsUrl ).then(function(tileset) { const placeholderTile = tileset.root.children[0]; const subtreeRootTile = placeholderTile.children[0]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); tiles.forEach(function(tile) { expect( tile.contentBoundingVolume instanceof import__517.TileBoundingSphere ).toBe(true); expect(tile.contentBoundingVolume).not.toBe(tile.boundingVolume); }); }); }); it("uses content height semantics to adjust implicit region", function() { viewCartographicOrigin(1e4); return Cesium3DTilesTester_default.loadTileset( scene2, implicitContentHeightSemanticsUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const implicitRegion = placeholderTile.implicitTileset.boundingVolume.region; const minimumHeight = implicitRegion[4]; const maximumHeight = implicitRegion[5]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); for (let i = 0; i < tiles.length; i++) { const contentRegion = tiles[i].contentBoundingVolume; expect(contentRegion.minimumHeight).toBeGreaterThan(minimumHeight); expect(contentRegion.maximumHeight).toBeLessThan(maximumHeight); } }); }); it("uses content height semantics to adjust content region semantic", function() { viewCartographicOrigin(1e4); return Cesium3DTilesTester_default.loadTileset( scene2, implicitContentHeightAndRegionSemanticsUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const implicitRegion = placeholderTile.implicitTileset.boundingVolume.region; const west = implicitRegion[0]; const south = implicitRegion[1]; const east = implicitRegion[2]; const north = implicitRegion[3]; const minimumHeight = implicitRegion[4]; const maximumHeight = implicitRegion[5]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); for (let i = 0; i < tiles.length; i++) { const contentRegion = tiles[i].contentBoundingVolume; expect(contentRegion.minimumHeight).toBeGreaterThan(minimumHeight); expect(contentRegion.maximumHeight).toBeLessThan(maximumHeight); expect(contentRegion.rectangle.west).toBeGreaterThan(west); expect(contentRegion.rectangle.south).toBeGreaterThan(south); expect(contentRegion.rectangle.east).toBeLessThan(east); expect(contentRegion.rectangle.north).toBeLessThan(north); } }); }); it("uses geometric error from metadata semantics if present", function() { viewCartographicOrigin(1e4); return Cesium3DTilesTester_default.loadTileset( scene2, implicitGeometricErrorSemanticsUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); const geometricErrors = tiles.map(function(tile) { return tile.geometricError; }); const expectedGeometricErrors = [ 300, 203, 112, 113, 114, 115, 201, 104, 105, 106, 107, 202, 108, 109, 110, 111, 200, 103, 101, 102, 100 ]; expect(geometricErrors).toEqual(expectedGeometricErrors); }); }); }); describe("3DTILES_metadata", function() { const implicitGroupMetadataLegacyUrl = "Data/Cesium3DTiles/Metadata/ImplicitGroupMetadata/tileset_1.0.json"; const implicitContentMetadataLegacyUrl = "Data/Cesium3DTiles/Metadata/ImplicitContentMetadata/tileset_1.0.json"; const implicitMultipleContentsMetadataLegacyUrl = "Data/Cesium3DTiles/Metadata/ImplicitMultipleContentsWithMetadata/tileset_1.0.json"; const implicitHeightSemanticsLegacyUrl = "Data/Cesium3DTiles/Metadata/ImplicitHeightSemantics/tileset_1.0.json"; const implicitS2HeightSemanticsLegacyUrl = "Data/Cesium3DTiles/Metadata/ImplicitHeightSemantics/s2-tileset_1.0.json"; const implicitTileBoundingVolumeSemanticsLegacyUrl = "Data/Cesium3DTiles/Metadata/ImplicitTileBoundingVolumeSemantics/tileset_1.0.json"; const implicitHeightAndSphereSemanticsLegacyUrl = "Data/Cesium3DTiles/Metadata/ImplicitHeightAndSphereSemantics/tileset_1.0.json"; const implicitHeightAndRegionSemanticsLegacyUrl = "Data/Cesium3DTiles/Metadata/ImplicitHeightAndRegionSemantics/tileset_1.0.json"; const implicitContentBoundingVolumeSemanticsLegacyUrl = "Data/Cesium3DTiles/Metadata/ImplicitContentBoundingVolumeSemantics/tileset_1.0.json"; const implicitContentHeightSemanticsLegacyUrl = "Data/Cesium3DTiles/Metadata/ImplicitContentHeightSemantics/tileset_1.0.json"; const implicitContentHeightAndRegionSemanticsLegacyUrl = "Data/Cesium3DTiles/Metadata/ImplicitContentHeightAndRegionSemantics/tileset_1.0.json"; const implicitGeometricErrorSemanticsLegacyUrl = "Data/Cesium3DTiles/Metadata/ImplicitGeometricErrorSemantics/tileset_1.0.json"; it("group metadata gets transcoded correctly (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitGroupMetadataLegacyUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 2, tiles); const groups = tileset.metadataExtension.groups; const ground = groups[0]; expect(ground.getProperty("color")).toEqual( new import__517.Cartesian3(120, 68, 32) ); expect(ground.getProperty("priority")).toBe(0); const sky = groups[1]; expect(sky.getProperty("color")).toEqual( new import__517.Cartesian3(206, 237, 242) ); expect(sky.getProperty("priority")).toBe(1); tiles.forEach(function(tile) { if (tile.hasMultipleContents) { const contents = tile.content.innerContents; expect(contents[0].group.metadata).toBe(ground); expect(contents[1].group.metadata).toBe(sky); } else { expect(tile.content.group.metadata).toBe(ground); } }); }); }); it("content metadata gets transcoded correctly (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitContentMetadataLegacyUrl ).then(function(tileset) { const expectedHeights = [10, 20, 0, 30, 40]; const expectedColors = [ new import__517.Cartesian3(255, 255, 255), new import__517.Cartesian3(255, 0, 0), import__517.Cartesian3.ZERO, new import__517.Cartesian3(0, 255, 0), new import__517.Cartesian3(0, 0, 255) ]; const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 2, tiles); for (let i = 0; i < tiles.length; i++) { const tile = tiles[i]; const subtree = tile.implicitSubtree; const coordinates = tile.implicitCoordinates; const index = coordinates.tileIndex; const metadata = tile.content.metadata; if (!subtree.contentIsAvailableAtIndex(index, 0)) { expect(metadata.getProperty("height")).not.toBeDefined(); expect(metadata.getProperty("color")).not.toBeDefined(); } else { expect(metadata.getProperty("height")).toBe( expectedHeights[index] ); expect(metadata.getProperty("color")).toEqual( expectedColors[index] ); } } }); }); it("multiple content metadata views get transcoded correctly (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, implicitMultipleContentsMetadataLegacyUrl ).then(function(tileset) { const expectedHeights = [10, 20, 30, 40, 50]; const expectedColors = [ new import__517.Cartesian3(255, 255, 255), new import__517.Cartesian3(255, 0, 0), new import__517.Cartesian3(255, 255, 0), new import__517.Cartesian3(0, 255, 0), new import__517.Cartesian3(0, 0, 255) ]; const expectedAges = [21, 7, 11, 16]; const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 2, tiles); for (let i = 0; i < tiles.length; i++) { const tile = tiles[i]; const coordinates = tile.implicitCoordinates; const index = coordinates.tileIndex; let buildingMetadata; if (i > 0) { expect(tile.hasMultipleContents).toBe(true); const buildingContent = tile.content.innerContents[0]; buildingMetadata = buildingContent.metadata; } else { expect(tile.hasMultipleContents).toBe(false); buildingMetadata = tile.content.metadata; } expect(buildingMetadata.getProperty("height")).toBe( expectedHeights[index] ); expect(buildingMetadata.getProperty("color")).toEqual( expectedColors[index] ); if (i === 0) { continue; } const treeContent = tile.content.innerContents[1]; const treeMetadata = treeContent.metadata; expect(treeMetadata.getProperty("age")).toEqual( expectedAges[index - 1] ); } }); }); function viewCartographicOrigin(height) { const center = import__517.Cartesian3.fromDegrees(0, 0); const offset = new import__517.Cartesian3(0, 0, height); scene2.camera.lookAt(center, offset); } it("uses height semantics to adjust region bounding volumes (legacy)", function() { viewCartographicOrigin(1e4); return Cesium3DTilesTester_default.loadTileset( scene2, implicitHeightSemanticsLegacyUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const implicitRegion = placeholderTile.implicitTileset.boundingVolume.region; const minimumHeight = implicitRegion[4]; const maximumHeight = implicitRegion[5]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); for (let i = 0; i < tiles.length; i++) { const tileRegion = tiles[i].boundingVolume; expect(tileRegion.minimumHeight).toBeGreaterThan(minimumHeight); expect(tileRegion.maximumHeight).toBeLessThan(maximumHeight); } }); }); it("uses height semantics to adjust S2 bounding volumes (legacy)", function() { viewCartographicOrigin(1e4); return Cesium3DTilesTester_default.loadTileset( scene2, implicitS2HeightSemanticsLegacyUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const implicitS2Volume = placeholderTile.implicitTileset.boundingVolume.extensions["3DTILES_bounding_volume_S2"]; const minimumHeight = implicitS2Volume.minimumHeight; const maximumHeight = implicitS2Volume.maximumHeight; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); for (let i = 0; i < tiles.length; i++) { const tileS2Volume = tiles[i].boundingVolume; expect(tileS2Volume.minimumHeight).toBeGreaterThan(minimumHeight); expect(tileS2Volume.maximumHeight).toBeLessThan(maximumHeight); } }); }); function getHalfWidth(boundingBox) { return boundingBox.boundingVolume.halfAxes[0]; } it("ignores height semantics if the implicit volume is a box (legacy)", function() { const cameraHeight = 100; const rootHalfWidth = 10; const originalLoadJson = import__517.Cesium3DTileset.loadJson; spyOn(import__517.Cesium3DTileset, "loadJson").and.callFake(function(tilesetUrl) { return originalLoadJson(tilesetUrl).then(function(tilesetJson) { tilesetJson.root.boundingVolume = { box: [ import__517.Ellipsoid.WGS84.radii.x + cameraHeight, 0, 0, rootHalfWidth, 0, 0, 0, rootHalfWidth, 0, 0, 0, rootHalfWidth ] }; return tilesetJson; }); }); viewCartographicOrigin(cameraHeight); return Cesium3DTilesTester_default.loadTileset( scene2, implicitHeightSemanticsLegacyUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); tiles.forEach(function(tile) { const level = tile.implicitCoordinates.level; const halfWidth = getHalfWidth(tile.boundingVolume); expect(halfWidth).toEqual(rootHalfWidth / Math.pow(2, level)); }); }); }); it("uses tile bounding box from metadata semantics if present (legacy)", function() { viewCartographicOrigin(124e3); return Cesium3DTilesTester_default.loadTileset( scene2, implicitTileBoundingVolumeSemanticsLegacyUrl ).then(function(tileset) { const placeholderTile = tileset.root.children[0]; const subtreeRootTile = placeholderTile.children[0]; const rootHalfWidth = 2048; expect(getHalfWidth(subtreeRootTile.boundingVolume)).toBe( rootHalfWidth ); for (let level = 1; level < 4; level++) { const halfWidthAtLevel = rootHalfWidth / (1 << level); const tiles = []; gatherTilesPreorder(subtreeRootTile, level, level, tiles); for (let i = 0; i < tiles.length; i++) { const tile = tiles[i]; const halfWidth = getHalfWidth(tile.boundingVolume); expect(halfWidth).toBeLessThan(halfWidthAtLevel); } } }); }); it("prioritizes height semantics over bounding volume semantics (legacy)", function() { viewCartographicOrigin(1e4); return Cesium3DTilesTester_default.loadTileset( scene2, implicitHeightAndSphereSemanticsLegacyUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const implicitRegion = placeholderTile.implicitTileset.boundingVolume.region; const minimumHeight = implicitRegion[4]; const maximumHeight = implicitRegion[5]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); for (let i = 0; i < tiles.length; i++) { const tileRegion = tiles[i].boundingVolume; expect(tileRegion.minimumHeight).toBeDefined(); expect(tileRegion.maximumHeight).toBeDefined(); expect(tileRegion.minimumHeight).toBeGreaterThan(minimumHeight); expect(tileRegion.maximumHeight).toBeLessThan(maximumHeight); } }); }); it("uses height semantics to adjust region semantic (legacy)", function() { viewCartographicOrigin(1e4); return Cesium3DTilesTester_default.loadTileset( scene2, implicitHeightAndRegionSemanticsLegacyUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const implicitRegion = placeholderTile.implicitTileset.boundingVolume.region; const west = implicitRegion[0]; const south = implicitRegion[1]; const east = implicitRegion[2]; const north = implicitRegion[3]; const minimumHeight = implicitRegion[4]; const maximumHeight = implicitRegion[5]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); for (let i = 0; i < tiles.length; i++) { const tileRegion = tiles[i].boundingVolume; expect(tileRegion.minimumHeight).toBeGreaterThan(minimumHeight); expect(tileRegion.maximumHeight).toBeLessThan(maximumHeight); expect(tileRegion.rectangle.west).toBeGreaterThan(west); expect(tileRegion.rectangle.south).toBeGreaterThan(south); expect(tileRegion.rectangle.east).toBeLessThan(east); expect(tileRegion.rectangle.north).toBeLessThan(north); } }); }); it("uses content bounding box from metadata semantics if present (legacy)", function() { viewCartographicOrigin(124e3); return Cesium3DTilesTester_default.loadTileset( scene2, implicitContentBoundingVolumeSemanticsLegacyUrl ).then(function(tileset) { const placeholderTile = tileset.root.children[0]; const subtreeRootTile = placeholderTile.children[0]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); tiles.forEach(function(tile) { expect( tile.contentBoundingVolume instanceof import__517.TileBoundingSphere ).toBe(true); expect(tile.contentBoundingVolume).not.toBe(tile.boundingVolume); }); }); }); it("uses content height semantics to adjust implicit region (legacy)", function() { viewCartographicOrigin(1e4); return Cesium3DTilesTester_default.loadTileset( scene2, implicitContentHeightSemanticsLegacyUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const implicitRegion = placeholderTile.implicitTileset.boundingVolume.region; const minimumHeight = implicitRegion[4]; const maximumHeight = implicitRegion[5]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); for (let i = 0; i < tiles.length; i++) { const contentRegion = tiles[i].contentBoundingVolume; expect(contentRegion.minimumHeight).toBeGreaterThan(minimumHeight); expect(contentRegion.maximumHeight).toBeLessThan(maximumHeight); } }); }); it("uses content height semantics to adjust content region semantic (legacy)", function() { viewCartographicOrigin(1e4); return Cesium3DTilesTester_default.loadTileset( scene2, implicitContentHeightAndRegionSemanticsLegacyUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const implicitRegion = placeholderTile.implicitTileset.boundingVolume.region; const west = implicitRegion[0]; const south = implicitRegion[1]; const east = implicitRegion[2]; const north = implicitRegion[3]; const minimumHeight = implicitRegion[4]; const maximumHeight = implicitRegion[5]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); for (let i = 0; i < tiles.length; i++) { const contentRegion = tiles[i].contentBoundingVolume; expect(contentRegion.minimumHeight).toBeGreaterThan(minimumHeight); expect(contentRegion.maximumHeight).toBeLessThan(maximumHeight); expect(contentRegion.rectangle.west).toBeGreaterThan(west); expect(contentRegion.rectangle.south).toBeGreaterThan(south); expect(contentRegion.rectangle.east).toBeLessThan(east); expect(contentRegion.rectangle.north).toBeLessThan(north); } }); }); it("uses geometric error from metadata semantics if present (legacy)", function() { viewCartographicOrigin(1e4); return Cesium3DTilesTester_default.loadTileset( scene2, implicitGeometricErrorSemanticsLegacyUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const tiles = []; gatherTilesPreorder(subtreeRootTile, 0, 3, tiles); const geometricErrors = tiles.map(function(tile) { return tile.geometricError; }); const expectedGeometricErrors = [ 300, 203, 112, 113, 114, 115, 201, 104, 105, 106, 107, 202, 108, 109, 110, 111, 200, 103, 101, 102, 100 ]; expect(geometricErrors).toEqual(expectedGeometricErrors); }); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/ImplicitAvailabilityBitstreamSpec.js var import__518 = __toESM(require_Cesium(), 1); describe("Scene/ImplicitAvailabilityBitstream", function() { it("throws on missing lengthBits", function() { expect(function() { return new import__518.ImplicitAvailabilityBitstream({}); }).toThrowDeveloperError(); }); it("throws on mismatched bitLength and bitstream.length", function() { expect(function() { return new import__518.ImplicitAvailabilityBitstream({ lengthBits: 17, bitstream: new Uint8Array([255, 2]) }); }).toThrowError(import__518.RuntimeError); }); it("reads bits from constant", function() { const length2 = 21; const bitstream = new import__518.ImplicitAvailabilityBitstream({ lengthBits: length2, constant: true }); for (let i = 0; i < length2; i++) { expect(bitstream.getBit(i)).toEqual(true); } }); it("reads bits from bitstream", function() { const bitstreamU8 = new Uint8Array([250, 1]); const expected = [false, true, false, true, true, true, true, true, true]; const bitstream = new import__518.ImplicitAvailabilityBitstream({ lengthBits: expected.length, bitstream: bitstreamU8 }); for (let i = 0; i < expected.length; i++) { expect(bitstream.getBit(i)).toEqual(expected[i]); } }); it("throws on out of bounds", function() { const bitstream = new import__518.ImplicitAvailabilityBitstream({ lengthBits: 10, bitstream: new Uint8Array([255, 2]) }); expect(function() { bitstream.getBit(-1); }).toThrowDeveloperError(); expect(function() { bitstream.getBit(10); }).toThrowDeveloperError(); }); it("stores availableCount", function() { const bitstream = new import__518.ImplicitAvailabilityBitstream({ lengthBits: 10, availableCount: 3, bitstream: new Uint8Array([7, 0]) }); expect(bitstream.availableCount).toEqual(3); }); it("computes availableCount if enabled and availableCount is undefined", function() { const bitstream = new import__518.ImplicitAvailabilityBitstream({ lengthBits: 10, bitstream: new Uint8Array([255, 2]), computeAvailableCountEnabled: true }); expect(bitstream.availableCount).toBe(9); }); it("does not compute availableCount if disabled and availableCount is undefined", function() { const bitstream = new import__518.ImplicitAvailabilityBitstream({ lengthBits: 10, bitstream: new Uint8Array([255, 2]) }); expect(bitstream.availableCount).not.toBeDefined(); }); }); // packages/engine/Specs/Scene/ImplicitMetadataViewSpec.js var import__519 = __toESM(require_Cesium(), 1); describe("Scene/ImplicitMetadataView", function() { const highlightColors = [ [255, 0, 0], [255, 255, 0], [255, 0, 255], [255, 255, 255] ]; const buildingCounts = [100, 350, 200, 500]; const tileTableDescription = { name: "Tiles", class: "tile", properties: { highlightColor: highlightColors, buildingCount: buildingCounts } }; const buildingHeights = [20, 30, 10]; const buildingTypes = ["Residential", "Commercial", "Other"]; const buildingTableDescription = { name: "Buildings", class: "building", properties: { height: buildingHeights, buildingType: buildingTypes } }; const treeHeights = [3, 2, 4]; const treeSpecies = ["Oak", "Pine", "Maple"]; const treeTableDescription = { name: "Trees", class: "tree", properties: { height: treeHeights, species: treeSpecies } }; const schema = { classes: { tile: { properties: { highlightColor: { type: "VEC3", componentType: "UINT8", semantic: "_HIGHLIGHT_COLOR" }, buildingCount: { type: "SCALAR", componentType: "UINT16" } } }, building: { properties: { height: { type: "SCALAR", componentType: "UINT16", semantic: "_HEIGHT" }, buildingType: { type: "STRING", semantic: "_BUILDING_TYPE" } } }, tree: { properties: { height: { type: "SCALAR", componentType: "UINT16", semantic: "_HEIGHT" }, species: { type: "STRING", semantic: "_TREE_SPECIES" } } } } }; let tileClass; let buildingClass; let treeClass; const propertyTablesDescription = { schema, propertyTables: [ tileTableDescription, buildingTableDescription, treeTableDescription ] }; const subtreeDescription = { tileAvailability: { descriptor: "11011", lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: "01011", lengthBits: 5, isInternal: true, includeAvailableCount: true }, { descriptor: "11001", lengthBits: 5, isInternal: true, includeAvailableCount: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: true, propertyTables: propertyTablesDescription } }; let tilesetResource; let subtreeResource; let mockTilesetWithMetadata; let metadataSchema; const implicitQuadtreeJson = { geometricError: 500, refine: "ADD", boundingVolume: { region: [0, 0, Math.PI / 24, Math.PI / 24, 0, 1e3] }, content: { uri: "https://example.com/{level}/{x}/{y}.b3dm" }, implicitTiling: { subdivisionScheme: "QUADTREE", subtreeLevels: 2, availableLevels: 2, subtrees: { uri: "https://example.com/{level}/{x}/{y}.subtree" } } }; let metadataQuadtree; let rootCoordinates; beforeAll(function() { tilesetResource = new import__519.Resource({ url: "https://example.com/tileset.json" }); subtreeResource = new import__519.Resource({ url: "https://example.com/test.subtree" }); tileClass = import__519.MetadataClass.fromJson({ id: "tile", class: schema.classes.tile }); buildingClass = import__519.MetadataClass.fromJson({ id: "building", class: schema.classes.building }); treeClass = import__519.MetadataClass.fromJson({ id: "tree", class: schema.classes.tree }); mockTilesetWithMetadata = { metadata: { schema: import__519.MetadataSchema.fromJson(schema) } }; metadataSchema = mockTilesetWithMetadata.metadata.schema; metadataQuadtree = new import__519.ImplicitTileset( tilesetResource, implicitQuadtreeJson, metadataSchema ); rootCoordinates = new import__519.ImplicitTileCoordinates({ subdivisionScheme: metadataQuadtree.subdivisionScheme, subtreeLevels: metadataQuadtree.subtreeLevels, x: 0, y: 0, level: 0 }); }); const emptyJson = {}; let subtree; let tileView; let secondTileView; let buildingView; let secondBuildingView; let treeView; let secondTreeView; beforeEach(async function() { const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); subtree = await import__519.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, metadataQuadtree, rootCoordinates ); tileView = new import__519.ImplicitMetadataView({ metadataTable: subtree.tileMetadataTable, class: tileClass, entityId: 0, propertyTableJson: emptyJson }); secondTileView = new import__519.ImplicitMetadataView({ metadataTable: subtree.tileMetadataTable, class: tileClass, entityId: 1, propertyTableJson: emptyJson }); buildingView = new import__519.ImplicitMetadataView({ metadataTable: subtree.contentMetadataTables[0], class: buildingClass, entityId: 0, contentIndex: 0, propertyTableJson: emptyJson }); secondBuildingView = new import__519.ImplicitMetadataView({ metadataTable: subtree.contentMetadataTables[0], class: buildingClass, entityId: 1, contentIndex: 0, propertyTableJson: emptyJson }); treeView = new import__519.ImplicitMetadataView({ metadataTable: subtree.contentMetadataTables[1], class: treeClass, entityId: 0, contentIndex: 1, propertyTableJson: emptyJson }); secondTreeView = new import__519.ImplicitMetadataView({ metadataTable: subtree.contentMetadataTables[1], class: treeClass, entityId: 1, contentIndex: 1, propertyTableJson: emptyJson }); }); it("throws without metadataTable", function() { expect(function() { tileView = new import__519.ImplicitMetadataView({ metadataTable: void 0, class: tileClass, entityId: 0, propertyTableJson: emptyJson }); }).toThrowDeveloperError(); }); it("throws without class", function() { expect(function() { tileView = new import__519.ImplicitMetadataView({ metadataTable: subtree.tileMetadataTable, class: void 0, entityId: 0, propertyTableJson: emptyJson }); }).toThrowDeveloperError(); }); it("throws without entityId", function() { expect(function() { tileView = new import__519.ImplicitMetadataView({ metadataTable: subtree.tileMetadataTable, class: tileClass, entityId: void 0, propertyTableJson: emptyJson }); }).toThrowDeveloperError(); }); it("throws without propertyTableJson", function() { expect(function() { tileView = new import__519.ImplicitMetadataView({ metadataTable: subtree.tileMetadataTable, class: tileClass, entityId: 0, propertyTableJson: void 0 }); }).toThrowDeveloperError(); }); it("creates tile metadata table view", function() { tileView = new import__519.ImplicitMetadataView({ metadataTable: subtree.tileMetadataTable, class: tileClass, entityId: 0, propertyTableJson: emptyJson }); expect(tileView.class).toBe(tileClass); expect(tileView.extras).toBe(void 0); expect(tileView.extensions).toBe(void 0); }); it("creates content metadata table views", function() { buildingView = new import__519.ImplicitMetadataView({ metadataTable: subtree.contentMetadataTables[0], class: buildingClass, entityId: 0, propertyTableJson: emptyJson }); expect(buildingView.class).toBe(buildingClass); expect(buildingView.extras).toBe(void 0); expect(buildingView.extensions).toBe(void 0); treeView = new import__519.ImplicitMetadataView({ metadataTable: subtree.contentMetadataTables[1], class: treeClass, entityId: 0, propertyTableJson: emptyJson }); expect(treeView.class).toBe(treeClass); expect(treeView.extras).toBe(void 0); expect(treeView.extensions).toBe(void 0); }); it("hasProperty returns true if the metadata table has this property", function() { expect(tileView.hasProperty("highlightColor")).toBe(true); expect(buildingView.hasProperty("height")).toBe(true); expect(treeView.hasProperty("species")).toBe(true); }); it("hasProperty returns false if the metadata table does not have this property", function() { expect(tileView.hasProperty("height")).toBe(false); expect(buildingView.hasProperty("buildingCount")).toBe(false); expect(treeView.hasProperty("buildingType")).toBe(false); }); it("hasPropertyBySemantic returns true if the metadata table has a property with the given semantic", function() { expect(tileView.hasPropertyBySemantic("_HIGHLIGHT_COLOR")).toBe(true); expect(buildingView.hasPropertyBySemantic("_HEIGHT")).toBe(true); expect(treeView.hasPropertyBySemantic("_TREE_SPECIES")).toBe(true); }); it("hasPropertyBySemantic returns false if the metadata table does not have a property with the given semantic", function() { expect(tileView.hasPropertyBySemantic("_AREA")).toBe(false); expect(buildingView.hasPropertyBySemantic("_HIGHLIGHT_COLOR")).toBe(false); expect(treeView.hasPropertyBySemantic("_BUILDING_TYPE")).toBe(false); }); it("getPropertyIds returns array of property IDs for the tile metadata table", function() { const tilePropertyIds = tileView.getPropertyIds([]); tilePropertyIds.sort(); expect(tilePropertyIds).toEqual(["buildingCount", "highlightColor"]); }); it("getPropertyIds returns different property IDs for different content metadata tables", function() { const buildingPropertyIds = buildingView.getPropertyIds([]); buildingPropertyIds.sort(); expect(buildingPropertyIds).toEqual(["buildingType", "height"]); const treePropertyIds = treeView.getPropertyIds([]); treePropertyIds.sort(); expect(treePropertyIds).toEqual(["height", "species"]); }); it("getProperty returns undefined if a property does not exist for the metadata table", function() { expect(tileView.getProperty("height")).not.toBeDefined(); expect(buildingView.getProperty("species")).not.toBeDefined(); expect(treeView.getProperty("buildingType")).not.toBeDefined(); }); it("getProperty returns the property value for the metadata table", function() { expect(tileView.getProperty("highlightColor")).toEqual( new import__519.Cartesian3(255, 0, 0) ); expect(tileView.getProperty("buildingCount")).toBe(100); expect(buildingView.getProperty("height")).toEqual(20); expect(buildingView.getProperty("buildingType")).toBe("Residential"); expect(treeView.getProperty("height")).toEqual(3); expect(treeView.getProperty("species")).toBe("Oak"); }); it("getProperty returns the correct value for metadata table views that point to the same table", function() { expect(tileView.getProperty("highlightColor")).toEqual( new import__519.Cartesian3(255, 0, 0) ); expect(secondTileView.getProperty("highlightColor")).toEqual( new import__519.Cartesian3(255, 255, 0) ); expect(buildingView.getProperty("buildingType")).toEqual("Residential"); expect(secondBuildingView.getProperty("buildingType")).toBe("Commercial"); expect(treeView.getProperty("species")).toEqual("Oak"); expect(secondTreeView.getProperty("species")).toBe("Pine"); }); it("getProperty returns the correct value for different metadata table views with same property", function() { expect(buildingView.getProperty("height")).toEqual(20); expect(treeView.getProperty("height")).toEqual(3); }); it("setProperty does not create property if it doesn't exist", function() { expect(tileView.setProperty("height", 10)).toBe(false); expect(buildingView.setProperty("buildingCount", 10)).toBe(false); expect(treeView.setProperty("buildingType", "Other")).toBe(false); }); it("setProperty sets property value", function() { expect(tileView.getProperty("buildingCount")).toBe(100); expect(tileView.setProperty("buildingCount", 400)).toBe(true); expect(tileView.getProperty("buildingCount")).toBe(400); expect(buildingView.getProperty("buildingType")).toBe("Residential"); expect(buildingView.setProperty("buildingType", "Commercial")).toBe(true); expect(buildingView.getProperty("buildingType")).toBe("Commercial"); expect(treeView.getProperty("species")).toBe("Oak"); expect(treeView.setProperty("species", "Chestnut")).toBe(true); expect(treeView.getProperty("species")).toBe("Chestnut"); }); it("setProperty sets property value for different metadata table views with same property", function() { expect(buildingView.setProperty("height", 100)).toBe(true); expect(buildingView.getProperty("height")).toBe(100); expect(treeView.getProperty("height")).toBe(3); expect(treeView.setProperty("height", 25)).toBe(true); expect(treeView.getProperty("height")).toBe(25); expect(buildingView.getProperty("height")).toBe(100); }); it("setProperty sets the correct values for metadata table views that point to the same table", function() { expect(tileView.getProperty("buildingCount")).toBe(100); expect(tileView.setProperty("buildingCount", 400)).toBe(true); expect(tileView.getProperty("buildingCount")).toBe(400); expect(secondTileView.getProperty("buildingCount")).toBe(350); expect(buildingView.getProperty("buildingType")).toBe("Residential"); expect(buildingView.setProperty("buildingType", "Other")).toBe(true); expect(buildingView.getProperty("buildingType")).toBe("Other"); expect(secondBuildingView.getProperty("buildingType")).toBe("Commercial"); expect(treeView.getProperty("species")).toBe("Oak"); expect(treeView.setProperty("species", "Chestnut")).toBe(true); expect(treeView.getProperty("species")).toBe("Chestnut"); expect(secondTreeView.getProperty("species")).toBe("Pine"); }); it("getPropertyBySemantic returns undefined when there's no property with the given semantic", function() { expect(tileView.getPropertyBySemantic("_AREA")).not.toBeDefined(); expect( buildingView.getPropertyBySemantic("_HIGHLIGHT_COLOR") ).not.toBeDefined(); expect(treeView.getPropertyBySemantic("_BUILDING_TYPE")).not.toBeDefined(); }); it("getPropertyBySemantic returns the property value", function() { expect(tileView.getPropertyBySemantic("_HIGHLIGHT_COLOR")).toEqual( new import__519.Cartesian3(255, 0, 0) ); expect(buildingView.getPropertyBySemantic("_BUILDING_TYPE")).toEqual( "Residential" ); expect(treeView.getPropertyBySemantic("_TREE_SPECIES")).toEqual("Oak"); }); it("getPropertyBySemantic returns correct values for different metadata table views with same semantic", function() { expect(buildingView.getPropertyBySemantic("_HEIGHT")).toEqual(20); expect(treeView.getPropertyBySemantic("_HEIGHT")).toEqual(3); }); it("getPropertyBySemantic returns correct values for metadata table views that point to the same table", function() { expect(tileView.getPropertyBySemantic("_HIGHLIGHT_COLOR")).toEqual( new import__519.Cartesian3(255, 0, 0) ); expect(secondTileView.getPropertyBySemantic("_HIGHLIGHT_COLOR")).toEqual( new import__519.Cartesian3(255, 255, 0) ); expect(buildingView.getPropertyBySemantic("_BUILDING_TYPE")).toEqual( "Residential" ); expect(secondBuildingView.getPropertyBySemantic("_BUILDING_TYPE")).toEqual( "Commercial" ); expect(treeView.getPropertyBySemantic("_TREE_SPECIES")).toEqual("Oak"); expect(secondTreeView.getPropertyBySemantic("_TREE_SPECIES")).toEqual( "Pine" ); }); it("setPropertyBySemantic sets property value", function() { expect(tileView.getPropertyBySemantic("_HIGHLIGHT_COLOR")).toEqual( new import__519.Cartesian3(255, 0, 0) ); expect( tileView.setPropertyBySemantic( "_HIGHLIGHT_COLOR", new import__519.Cartesian3(0, 0, 0) ) ).toBe(true); expect(tileView.getPropertyBySemantic("_HIGHLIGHT_COLOR")).toEqual( new import__519.Cartesian3(0, 0, 0) ); expect(buildingView.getPropertyBySemantic("_BUILDING_TYPE")).toEqual( "Residential" ); expect(buildingView.setPropertyBySemantic("_BUILDING_TYPE", "Other")).toBe( true ); expect(buildingView.getPropertyBySemantic("_BUILDING_TYPE")).toEqual( "Other" ); expect(treeView.getPropertyBySemantic("_TREE_SPECIES")).toEqual("Oak"); expect(treeView.setPropertyBySemantic("_TREE_SPECIES", "Chestnut")).toBe( true ); expect(treeView.getPropertyBySemantic("_TREE_SPECIES")).toEqual("Chestnut"); }); it("setPropertyBySemantic sets the correct value for different metadata table views with the same semantic", function() { expect(buildingView.setPropertyBySemantic("_HEIGHT", 100)).toBe(true); expect(buildingView.getPropertyBySemantic("_HEIGHT")).toEqual(100); expect(treeView.getPropertyBySemantic("_HEIGHT")).toEqual(3); expect(treeView.setPropertyBySemantic("_HEIGHT", 55)).toBe(true); expect(treeView.getPropertyBySemantic("_HEIGHT")).toEqual(55); expect(buildingView.getPropertyBySemantic("_HEIGHT")).toEqual(100); }); it("setPropertyBySemantic sets the correct value for metadata table views that point to the same table", function() { expect(tileView.getPropertyBySemantic("_HIGHLIGHT_COLOR")).toEqual( new import__519.Cartesian3(255, 0, 0) ); expect( tileView.setPropertyBySemantic( "_HIGHLIGHT_COLOR", new import__519.Cartesian3(0, 0, 0) ) ).toBe(true); expect(tileView.getPropertyBySemantic("_HIGHLIGHT_COLOR")).toEqual( new import__519.Cartesian3(0, 0, 0) ); expect(secondTileView.getPropertyBySemantic("_HIGHLIGHT_COLOR")).toEqual( new import__519.Cartesian3(255, 255, 0) ); expect(buildingView.getPropertyBySemantic("_BUILDING_TYPE")).toEqual( "Residential" ); expect(buildingView.setPropertyBySemantic("_BUILDING_TYPE", "Other")).toBe( true ); expect(buildingView.getPropertyBySemantic("_BUILDING_TYPE")).toEqual( "Other" ); expect(secondBuildingView.getPropertyBySemantic("_BUILDING_TYPE")).toEqual( "Commercial" ); expect(treeView.getPropertyBySemantic("_TREE_SPECIES")).toEqual("Oak"); expect(treeView.setPropertyBySemantic("_TREE_SPECIES", "Chestnut")).toBe( true ); expect(treeView.getPropertyBySemantic("_TREE_SPECIES")).toEqual("Chestnut"); expect(secondTreeView.getPropertyBySemantic("_TREE_SPECIES")).toEqual( "Pine" ); }); it("setPropertyBySemantic returns false if the semantic does not exist", function() { expect(tileView.setPropertyBySemantic("_AREA", 100)).toBe(false); expect( buildingView.setPropertyBySemantic( "_HIGHLIGHT_COLOR", new import__519.Cartesian3(255, 0, 0) ) ).toBe(false); expect( treeView.setPropertyBySemantic( "_HIGHLIGHT_COLOR", new import__519.Cartesian3(255, 0, 0) ) ).toBe(false); }); }); // packages/engine/Specs/Scene/ImplicitSubdivisionSchemeSpec.js var import__520 = __toESM(require_Cesium(), 1); describe("Scene/ImplicitSubdivisionScheme", function() { it("getBranchingFactor returns the right branching factor", function() { const treeTypes = [ import__520.ImplicitSubdivisionScheme.OCTREE, import__520.ImplicitSubdivisionScheme.QUADTREE ]; const branchingFactors = [8, 4]; for (let i = 0; i < treeTypes.length; i++) { expect(import__520.ImplicitSubdivisionScheme.getBranchingFactor(treeTypes[i])).toBe( branchingFactors[i] ); } }); it("throws for invalid value", function() { expect(function() { return import__520.ImplicitSubdivisionScheme.getBranchingFactor("BINARY_TREE"); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/ImplicitSubtreeCacheSpec.js var import__521 = __toESM(require_Cesium(), 1); describe("Scene/ImplicitSubtreeCache", function() { const implicitOctreeJson = { geometricError: 500, refine: "REPLACE", boundingVolume: { region: [0, 0, Math.PI / 24, Math.PI / 24, 0, 1e3] }, content: { uri: "https://example.com/{level}/{x}_{y}_{z}.b3dm" }, implicitTiling: { subdivisionScheme: "OCTREE", subtreeLevels: 2, availableLevels: 4, subtrees: { uri: "https://example.com/{level}/{x}_{y}_{z}.subtree" } } }; const subtreeConstantJson = { tileAvailability: { constant: 1 }, contentAvailability: { constant: 1 }, childSubtreeAvailability: { constant: 0 } }; let tilesetResource; let subtreeResource; let implicitOctree; let metadataSchema; beforeEach(function() { tilesetResource = new import__521.Resource({ url: "https://example.com/tileset.json" }); subtreeResource = new import__521.Resource({ url: "https://example.com/test.subtree" }); implicitOctree = new import__521.ImplicitTileset( tilesetResource, implicitOctreeJson, metadataSchema ); }); it("constructs", function() { const cache = new import__521.ImplicitSubtreeCache(); expect(cache._maximumSubtreeCount).toBe(0); expect(cache._subtreeRequestCounter).toBe(0); }); it("can add a subtree", async function() { const cache = new import__521.ImplicitSubtreeCache(); const octreeCoordinates = new import__521.ImplicitTileCoordinates({ subdivisionScheme: implicitOctree.subdivisionScheme, subtreeLevels: implicitOctree.subtreeLevels, level: 0, x: 0, y: 0, z: 0 }); const subtree = await import__521.ImplicitSubtree.fromSubtreeJson( subtreeResource, subtreeConstantJson, void 0, implicitOctree, octreeCoordinates ); cache.addSubtree(subtree); expect(cache._subtreeRequestCounter).toBe(1); }); it("addSubtree throws if parent does not exist", async function() { const cache = new import__521.ImplicitSubtreeCache(); const octreeCoordinates = new import__521.ImplicitTileCoordinates({ subdivisionScheme: implicitOctree.subdivisionScheme, subtreeLevels: implicitOctree.subtreeLevels, level: 2, x: 0, y: 1, z: 0 }); const subtree = await import__521.ImplicitSubtree.fromSubtreeJson( subtreeResource, subtreeConstantJson, void 0, implicitOctree, octreeCoordinates ); expect(() => cache.addSubtree(subtree)).toThrowDeveloperError(); }); it("addSubtree trims cache as needed", async function() { const cache = new import__521.ImplicitSubtreeCache({ maximumSubtreeCount: 3 }); const octreeCoordArray = [ { level: 0, x: 0, y: 0, z: 0 }, { level: 2, x: 1, y: 0, z: 0 }, { level: 2, x: 0, y: 1, z: 0 }, { level: 2, x: 0, y: 0, z: 1 } ]; const octreeCoordParams = { subdivisionScheme: implicitOctree.subdivisionScheme, subtreeLevels: implicitOctree.subtreeLevels }; await Promise.all( octreeCoordArray.map(async (octreeCoord) => { const octreeCoordinates = new import__521.ImplicitTileCoordinates( Object.assign({}, octreeCoordParams, octreeCoord) ); const subtree = await import__521.ImplicitSubtree.fromSubtreeJson( subtreeResource, subtreeConstantJson, void 0, implicitOctree, octreeCoordinates ); cache.addSubtree(subtree); }) ); expect(cache._subtreeRequestCounter).toBe(4); expect(cache._queue.length).toBe(3); }); }); // packages/engine/Specs/Scene/ImplicitSubtreeMetadataSpec.js var import__522 = __toESM(require_Cesium(), 1); describe("Scene/ImplicitSubtreeMetadata", function() { it("creates subtree metadata with default values", function() { const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ subtreeMetadata: {}, class: {} }); expect(subtreeMetadata.extras).toBeUndefined(); expect(subtreeMetadata.extensions).toBeUndefined(); }); it("creates subtree metadata", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { credits: { type: "STRING", array: true } } } }); const extras = { other: 0 }; const extensions = { EXT_other_extension: {} }; const properties = { credits: ["A", "B", "C"] }; const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: { class: "subtree", properties, extensions, extras } }); expect(subtreeMetadata.class).toBe(subtreeClass); expect(subtreeMetadata.extras).toBe(extras); expect(subtreeMetadata.extensions).toBe(extensions); expect(subtreeMetadata.getProperty("credits")).toEqual(properties.credits); }); it("constructor throws without subtree", function() { expect(function() { return new import__522.ImplicitSubtreeMetadata(); }).toThrowDeveloperError(); }); it("constructor throws without class", function() { expect(function() { return new import__522.ImplicitSubtreeMetadata({ subtreeMetadata: {} }); }).toThrowDeveloperError(); }); it("hasProperty throws when there's no property with the given property ID", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { credits: { type: "STRING", array: true } } } }); const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: { properties: { credits: ["A", "B", "C"] } } }); expect(function() { return subtreeMetadata.getProperty("color"); }).toThrowDeveloperError(); }); it("hasProperty returns true when there's a property with the given property ID", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { credits: { type: "STRING", array: true } } } }); const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: { properties: { credits: ["A", "B", "C"] } } }); expect(subtreeMetadata.hasProperty("credits")).toBe(true); }); it("hasProperty returns true when the class has a default value for a missing property", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { credits: { type: "STRING", array: true, required: false, default: [] } } } }); const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: {} }); expect(subtreeMetadata.hasProperty("credits")).toBe(true); }); it("hasProperty throws without propertyId", function() { const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ subtreeMetadata: {}, class: { properties: {} } }); expect(function() { subtreeMetadata.hasProperty(); }).toThrowDeveloperError(); }); it("hasPropertyBySemantic returns false when there's no property with the given semantic", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { credits: { type: "STRING", array: true, semantic: "CREDITS" } } } }); const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: { properties: { credits: ["A", "B", "C"] } } }); expect(subtreeMetadata.hasPropertyBySemantic("AUTHOR")).toBe(false); }); it("hasPropertyBySemantic returns true when there's a property with the given semantic", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { credits: { type: "STRING", array: true, semantic: "CREDITS" } } } }); const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: { properties: { credits: ["A", "B", "C"] } } }); expect(subtreeMetadata.hasPropertyBySemantic("CREDITS")).toBe(true); }); it("hasPropertyBySemantic returns true when the class has a default value for a missing property", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { credits: { type: "STRING", array: true, semantic: "CREDITS", default: [] } } } }); const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: {} }); expect(subtreeMetadata.hasPropertyBySemantic("CREDITS")).toBe(true); }); it("hasPropertyBySemantic throws without semantic", function() { const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ subtreeMetadata: {}, class: { properties: {} } }); expect(function() { subtreeMetadata.hasPropertyBySemantic(void 0); }).toThrowDeveloperError(); }); it("getPropertyIds returns empty array when there are no properties", function() { const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ subtreeMetadata: {}, class: { properties: {} } }); expect(subtreeMetadata.getPropertyIds().length).toBe(0); }); it("getPropertyIds returns array of property IDs", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { author: { type: "STRING" }, date: { type: "STRING" }, credits: { type: "STRING", array: true } } } }); const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: { properties: { author: "Cesium", date: "2022-02-10", credits: ["A", "B", "C"] } } }); expect(subtreeMetadata.getPropertyIds().sort()).toEqual([ "author", "credits", "date" ]); }); it("getPropertyIds includes properties with default values", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { author: { type: "STRING" }, date: { type: "STRING" }, credits: { type: "STRING", array: true, required: false, default: [] } } } }); const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: { properties: { author: "Cesium", date: "2022-02-10" } } }); expect(subtreeMetadata.getPropertyIds().sort()).toEqual([ "author", "credits", "date" ]); }); it("getPropertyIds uses results argument", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { author: { type: "STRING" }, date: { type: "STRING" }, credits: { type: "STRING", array: true } } } }); const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: { properties: { author: "Cesium", date: "2022-02-10", credits: ["A", "B", "C"] } } }); const results = []; const returnedResults = subtreeMetadata.getPropertyIds(results); expect(results).toBe(returnedResults); expect(results.sort()).toEqual(["author", "credits", "date"]); }); it("getProperty throws when there's no property with the given property ID", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { author: { type: "STRING" } } } }); const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: { properties: { author: "Cesium" } } }); expect(function() { return subtreeMetadata.getProperty("credits"); }).toThrowDeveloperError(); }); it("getProperty returns the property value", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { author: { type: "STRING" } } } }); const author = "Cesium"; const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: { properties: { author } } }); const value = subtreeMetadata.getProperty("author"); expect(value).toEqual(author); }); it("getProperty returns the default value when the property is missing", function() { const defaultAuthor = "none"; const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { author: { type: "STRING", required: false, default: defaultAuthor } } } }); const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: {} }); const value = subtreeMetadata.getProperty("author"); expect(value).toEqual(defaultAuthor); }); it("getProperty throws without propertyId", function() { const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ subtreeMetadata: {}, class: { properties: {} } }); expect(function() { subtreeMetadata.getProperty(); }).toThrowDeveloperError(); }); it("setProperty returns false if property doesn't exist", function() { const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ subtreeMetadata: {}, class: { properties: {} } }); const author = "Cesium"; expect(subtreeMetadata.setProperty("author", author)).toBe(false); }); it("setProperty sets property value", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { author: { type: "STRING" } } } }); const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: { properties: { author: "None" } } }); const author = "Cesium"; expect(subtreeMetadata.setProperty("author", author)).toBe(true); expect(subtreeMetadata.getProperty("author")).toEqual(author); }); it("setProperty throws without propertyId", function() { const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ subtreeMetadata: {}, class: { properties: {} } }); expect(function() { subtreeMetadata.setProperty(); }).toThrowDeveloperError(); }); it("setProperty throws without value", function() { const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ subtreeMetadata: {}, class: { properties: {} } }); expect(function() { subtreeMetadata.setProperty("author"); }).toThrowDeveloperError(); }); it("getPropertyBySemantic returns undefined when there's no property with the given semantic", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { author: { type: "STRING", semantic: "AUTHOR" } } } }); const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: { properties: { author: "Cesium" } } }); expect(subtreeMetadata.getPropertyBySemantic("CREDITS")).toBeUndefined(); }); it("getPropertyBySemantic returns the property value", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { author: { type: "STRING", semantic: "AUTHOR" } } } }); const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: { properties: { author: "Cesium" } } }); expect(subtreeMetadata.getPropertyBySemantic("AUTHOR")).toBe("Cesium"); }); it("getPropertyBySemantic throws without semantic", function() { const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ subtreeMetadata: {}, class: { properties: {} } }); expect(function() { subtreeMetadata.getPropertyBySemantic(); }).toThrowDeveloperError(); }); it("setPropertyBySemantic sets property value", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { author: { type: "STRING", semantic: "AUTHOR" } } } }); const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: { properties: { author: "None" } } }); const author = "Cesium"; expect(subtreeMetadata.setPropertyBySemantic("AUTHOR", author)).toBe(true); expect(subtreeMetadata.getProperty("author")).toBe(author); }); it("setPropertyBySemantic returns false if semantic does not exist", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { author: { type: "STRING", semantic: "AUTHOR" } } } }); const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: { properties: { author: "Cesium" } } }); expect(subtreeMetadata.setPropertyBySemantic("CREDITS", ["A"])).toBe(false); }); it("setPropertyBySemantic throws without semantic", function() { const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ subtreeMetadata: {}, class: { properties: {} } }); expect(function() { subtreeMetadata.setPropertyBySemantic(); }).toThrowDeveloperError(); }); it("setPropertyBySemantic throws without value", function() { const subtreeClass = import__522.MetadataClass.fromJson({ id: "subtree", class: { properties: { author: { type: "STRING", semantic: "AUTHOR" } } } }); const subtreeMetadata = new import__522.ImplicitSubtreeMetadata({ class: subtreeClass, subtreeMetadata: { properties: { author: "None" } } }); expect(function() { subtreeMetadata.setPropertyBySemantic("AUTHOR"); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/ImplicitSubtreeSpec.js var import__523 = __toESM(require_Cesium(), 1); describe("Scene/ImplicitSubtree", function() { function availabilityToBooleanArray(availability) { if (typeof availability.descriptor === "number") { const constant = availability.descriptor === 1; const repeated = new Array(availability.lengthBits); for (let i = 0; i < availability.lengthBits; i++) { repeated[i] = constant; } return repeated; } return availability.descriptor.split("").map(function(x) { return x === "1"; }); } function expectTileAvailability(subtree, availability) { const expectedAvailability = availabilityToBooleanArray(availability); for (let i = 0; i < availability.lengthBits; i++) { expect(subtree.tileIsAvailableAtIndex(i)).toEqual( expectedAvailability[i] ); expect( subtree.tileIsAvailableAtCoordinates( import__523.ImplicitTileCoordinates.fromTileIndex( subtree.implicitCoordinates.subdivisionScheme, subtree.implicitCoordinates.subtreeLevels, i ) ) ).toEqual(expectedAvailability[i]); } } function expectContentAvailability(subtree, availabilityArray) { for (let i = 0; i < availabilityArray.length; i++) { const availability = availabilityArray[i]; const expectedAvailability = availabilityToBooleanArray(availability); for (let j = 0; j < availability.lengthBits; j++) { expect(subtree.contentIsAvailableAtIndex(j, i)).toEqual( expectedAvailability[j] ); expect( subtree.contentIsAvailableAtCoordinates( import__523.ImplicitTileCoordinates.fromTileIndex( subtree.implicitCoordinates.subdivisionScheme, subtree.implicitCoordinates.subtreeLevels, j ), i ) ).toEqual(expectedAvailability[j]); } } } function expectChildSubtreeAvailability(subtree, availability) { const expectedAvailability = availabilityToBooleanArray(availability); for (let i = 0; i < availability.lengthBits; i++) { expect(subtree.childSubtreeIsAvailableAtIndex(i)).toEqual( expectedAvailability[i] ); expect( subtree.childSubtreeIsAvailableAtCoordinates( import__523.ImplicitTileCoordinates.fromMortonIndex( subtree.implicitCoordinates.subdivisionScheme, subtree.implicitCoordinates.subtreeLevels, subtree.implicitCoordinates.subtreeLevels, i ) ) ).toEqual(expectedAvailability[i]); } } function fakeResourceLoader(arrayBuffer) { return function(options) { const fakeCacheResource = { typedArray: arrayBuffer, load: async () => { }, process: () => true, isDestroyed: () => false }; return fakeCacheResource; }; } let tilesetResource; let subtreeResource; let metadataSchema; const subtreeConstantJson = { tileAvailability: { constant: 1 }, contentAvailability: { constant: 1 }, childSubtreeAvailability: { constant: 0 } }; const implicitQuadtreeJson = { geometricError: 500, refine: "ADD", boundingVolume: { region: [0, 0, Math.PI / 24, Math.PI / 24, 0, 1e3] }, content: { uri: "https://example.com/{level}/{x}/{y}.b3dm" }, implicitTiling: { subdivisionScheme: "QUADTREE", subtreeLevels: 2, // This is artificially high for ease of testing. This field is // not validated at runtime. availableLevels: 4, subtrees: { uri: "https://example.com/{level}/{x}/{y}.subtree" } } }; let implicitQuadtree; let quadtreeCoordinates; const implicitOctreeJson = { geometricError: 500, refine: "REPLACE", boundingVolume: { region: [0, 0, Math.PI / 24, Math.PI / 24, 0, 1e3] }, content: { uri: "https://example.com/{level}/{x}_{y}_{z}.b3dm" }, implicitTiling: { subdivisionScheme: "OCTREE", subtreeLevels: 2, availableLevels: 4, subtrees: { uri: "https://example.com/{level}/{x}_{y}_{z}.subtree" } } }; let implicitOctree; let octreeCoordinates; const internalQuadtreeDescription = { tileAvailability: { descriptor: "11010", lengthBits: 5, isInternal: true }, contentAvailability: [ { descriptor: "11000", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: "1111000010100000", lengthBits: 16, isInternal: true } }; const constantQuadtreeDescription = { tileAvailability: { descriptor: "11111", lengthBits: 5, isInternal: false }, contentAvailability: [ { descriptor: "11111", lengthBits: 5, isInternal: false } ], childSubtreeAvailability: { descriptor: "0000000000000000", lengthBits: 16, isInternal: false } }; beforeEach(function() { tilesetResource = new import__523.Resource({ url: "https://example.com/tileset.json" }); subtreeResource = new import__523.Resource({ url: "https://example.com/test.subtree" }); implicitQuadtree = new import__523.ImplicitTileset( tilesetResource, implicitQuadtreeJson, metadataSchema ); quadtreeCoordinates = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitQuadtree.subdivisionScheme, subtreeLevels: implicitQuadtree.subtreeLevels, level: 0, x: 0, y: 0 }); implicitOctree = new import__523.ImplicitTileset( tilesetResource, implicitOctreeJson, metadataSchema ); octreeCoordinates = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitOctree.subdivisionScheme, subtreeLevels: implicitOctree.subtreeLevels, level: 0, z: 0, x: 0, y: 0 }); }); it("throws without resource", function() { expect(function() { return new import__523.ImplicitSubtree( void 0, implicitQuadtree, quadtreeCoordinates ); }).toThrowDeveloperError(); }); it("throws without implicitTileset", function() { expect(function() { return new import__523.ImplicitSubtree( subtreeResource, void 0, quadtreeCoordinates ); }).toThrowDeveloperError(); }); it("throws without implicitCoordinates", function() { expect(function() { return new import__523.ImplicitSubtree(subtreeResource, implicitQuadtree, void 0); }).toThrowDeveloperError(); }); it("sets the implicit coordinates of the subtree's root", async function() { const results = ImplicitTilingTester_default.generateSubtreeBuffers( internalQuadtreeDescription ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitQuadtree, quadtreeCoordinates ); expect(subtree.implicitCoordinates.isEqual(quadtreeCoordinates)).toEqual( true ); }); it("ImplicitSubtree.fromSubtreeJson throws without json or subtreeView", async function() { await expectAsync( import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, void 0, implicitQuadtree, quadtreeCoordinates ) ).toBeRejectedWithDeveloperError(); }); it("gets availability from internal buffer", async function() { const results = ImplicitTilingTester_default.generateSubtreeBuffers( internalQuadtreeDescription ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitQuadtree, quadtreeCoordinates ); expectTileAvailability( subtree, internalQuadtreeDescription.tileAvailability ); expectContentAvailability( subtree, internalQuadtreeDescription.contentAvailability ); expectChildSubtreeAvailability( subtree, internalQuadtreeDescription.childSubtreeAvailability ); }); it("gets availability from external buffer", async function() { const subtreeDescription = { tileAvailability: { descriptor: "11010", lengthBits: 5, isInternal: false }, contentAvailability: [ { descriptor: "11000", lengthBits: 5, isInternal: false } ], childSubtreeAvailability: { descriptor: "1111000010100000", lengthBits: 16, isInternal: false } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitQuadtree, quadtreeCoordinates ); expectTileAvailability(subtree, subtreeDescription.tileAvailability); expectContentAvailability(subtree, subtreeDescription.contentAvailability); expectChildSubtreeAvailability( subtree, subtreeDescription.childSubtreeAvailability ); expect(fetchExternal.calls.count()).toEqual(1); }); it("gets availability from JSON constants", async function() { const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, subtreeConstantJson, void 0, implicitQuadtree, quadtreeCoordinates ); expectTileAvailability( subtree, constantQuadtreeDescription.tileAvailability ); expectContentAvailability( subtree, constantQuadtreeDescription.contentAvailability ); expectChildSubtreeAvailability( subtree, constantQuadtreeDescription.childSubtreeAvailability ); }); it("gets availability from JSON and external buffers", async function() { const description = { tileAvailability: { descriptor: "11010", lengthBits: 5, isInternal: false }, contentAvailability: [ { descriptor: "11000", lengthBits: 5, isInternal: false } ], childSubtreeAvailability: { descriptor: "1111000010100000", lengthBits: 16, isInternal: false }, json: true }; const results = ImplicitTilingTester_default.generateSubtreeBuffers(description); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, results.subtreeJson, void 0, implicitQuadtree, quadtreeCoordinates ); expectTileAvailability(subtree, description.tileAvailability); expectContentAvailability(subtree, description.contentAvailability); expectChildSubtreeAvailability( subtree, description.childSubtreeAvailability ); expect(fetchExternal.calls.count()).toEqual(1); }); it("gets availability with bufferViews", async function() { const description = (0, import__523.clone)(internalQuadtreeDescription); description.useLegacySchema = true; const results = ImplicitTilingTester_default.generateSubtreeBuffers(description); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitQuadtree, quadtreeCoordinates ); expectTileAvailability( subtree, internalQuadtreeDescription.tileAvailability ); expectContentAvailability( subtree, internalQuadtreeDescription.contentAvailability ); expectChildSubtreeAvailability( subtree, internalQuadtreeDescription.childSubtreeAvailability ); }); it("handles typed arrays with a byte offset", async function() { const subtreeDescription = { tileAvailability: { descriptor: "11010", lengthBits: 5, isInternal: true }, contentAvailability: [ { descriptor: "11000", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: "1111000010100000", lengthBits: 16, isInternal: true } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const paddingLength = 8; const biggerBuffer = new Uint8Array( results.subtreeBuffer.length + paddingLength ); biggerBuffer.set(results.subtreeBuffer, paddingLength); const subtreeView = new Uint8Array(biggerBuffer.buffer, paddingLength); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, subtreeView, implicitQuadtree, quadtreeCoordinates ); expectTileAvailability(subtree, subtreeDescription.tileAvailability); expectContentAvailability(subtree, subtreeDescription.contentAvailability); expectChildSubtreeAvailability( subtree, subtreeDescription.childSubtreeAvailability ); }); it("tile and content availability can share the same buffer", async function() { const subtreeDescription = { tileAvailability: { descriptor: "11010", lengthBits: 5, isInternal: false }, contentAvailability: [ { shareBuffer: true, descriptor: "11010", lengthBits: 5, isInternal: false } ], childSubtreeAvailability: { descriptor: "1111000010100000", lengthBits: 16, isInternal: false } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitQuadtree, quadtreeCoordinates ); expectTileAvailability(subtree, subtreeDescription.tileAvailability); expectContentAvailability(subtree, subtreeDescription.contentAvailability); expectChildSubtreeAvailability( subtree, subtreeDescription.childSubtreeAvailability ); expect(fetchExternal.calls.count()).toEqual(1); }); it("external buffer is fetched if it is used for availability", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: false }, contentAvailability: [ { descriptor: "11000", lengthBits: 5, isInternal: false } ], childSubtreeAvailability: { descriptor: "1111000010100000", lengthBits: 16, isInternal: false } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitQuadtree, quadtreeCoordinates ); expect(fetchExternal.calls.count()).toEqual(1); }); it("unused external buffers are not fetched", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true }, contentAvailability: [ { descriptor: "11000", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: "1111000010100000", lengthBits: 16, isInternal: true }, other: { descriptor: "101010", lengthBits: 6, isInternal: false } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn( import__523.Resource.prototype, "fetchArrayBuffer" ).and.returnValue(Promise.resolve(results.externalBuffer)); await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitQuadtree, quadtreeCoordinates ); expect(fetchExternal).not.toHaveBeenCalled(); }); it("missing contentAvailability is interpreted as 0s", async function() { const subtreeDescription = { tileAvailability: { descriptor: "11010", lengthBits: 5, isInternal: true }, childSubtreeAvailability: { descriptor: "1111000010100000", lengthBits: 16, isInternal: true } }; const expectedContentAvailability = { descriptor: 0, lengthBits: 5, isInternal: true }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitQuadtree, quadtreeCoordinates ); expectTileAvailability(subtree, subtreeDescription.tileAvailability); expectContentAvailability(subtree, expectedContentAvailability); expectChildSubtreeAvailability( subtree, subtreeDescription.childSubtreeAvailability ); }); it("availability works for quadtrees", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true }, contentAvailability: [ { descriptor: 1, lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitQuadtree, quadtreeCoordinates ); expectTileAvailability(subtree, subtreeDescription.tileAvailability); expectContentAvailability(subtree, subtreeDescription.contentAvailability); expectChildSubtreeAvailability( subtree, subtreeDescription.childSubtreeAvailability ); }); it("computes level offset", async function() { const subtreeDescription = { tileAvailability: { descriptor: "110101111", lengthBits: 9, isInternal: true }, contentAvailability: [ { descriptor: "110101011", lengthBits: 9, isInternal: true } ], childSubtreeAvailability: { descriptor: 1, lengthBits: 64, isInternal: true } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitOctree, octreeCoordinates ); expect(subtree.getLevelOffset(2)).toEqual(9); }); it("getTileIndex throws for a tile not in the subtree", async function() { const subtreeDescription = { tileAvailability: { descriptor: "11000", lengthBits: 5, isInternal: true }, contentAvailability: [ { descriptor: "11000", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: "100000000000000", lengthBits: 16, isInternal: true } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const deeperQuadtreeCoordinates = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitQuadtree.subdivisionScheme, subtreeLevels: implicitQuadtree.subtreeLevels, level: 2, x: 0, y: 0 }); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitQuadtree, deeperQuadtreeCoordinates ); expect(function() { const implicitCoordinates = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitQuadtree.subdivisionScheme, subtreeLevels: implicitQuadtree.subtreeLevels, level: 0, x: 0, y: 0 }); return subtree.getTileIndex(implicitCoordinates); }).toThrowError(import__523.RuntimeError); expect(function() { const implicitCoordinates = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitQuadtree.subdivisionScheme, subtreeLevels: implicitQuadtree.subtreeLevels, level: 5, x: 0, y: 0 }); return subtree.getTileIndex(implicitCoordinates); }).toThrowError(import__523.RuntimeError); }); it("getTileIndex computes bit index for a tile in the subtree", async function() { const subtreeDescription = { tileAvailability: { descriptor: "11000", lengthBits: 5, isInternal: true }, contentAvailability: [ { descriptor: "11000", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: "100000000000000", lengthBits: 16, isInternal: true } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const subtreeCoordinates = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitQuadtree.subdivisionScheme, subtreeLevels: implicitQuadtree.subtreeLevels, level: 0, x: 0, y: 0 }); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitQuadtree, subtreeCoordinates ); const implicitCoordinatesFull = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitQuadtree.subdivisionScheme, subtreeLevels: implicitQuadtree.subtreeLevels, level: 1, x: 0, y: 0 }); const indexFull = subtree.getTileIndex(implicitCoordinatesFull); expect(indexFull).toBe(1); expect(subtree.tileIsAvailableAtIndex(indexFull)).toEqual(true); expect( subtree.tileIsAvailableAtCoordinates(implicitCoordinatesFull) ).toEqual(true); expect(subtree.contentIsAvailableAtIndex(indexFull)).toEqual(true); expect( subtree.contentIsAvailableAtCoordinates(implicitCoordinatesFull) ).toEqual(true); const implicitCoordinatesEmpty = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitQuadtree.subdivisionScheme, subtreeLevels: implicitQuadtree.subtreeLevels, level: 1, x: 1, y: 1 }); const indexEmpty = subtree.getTileIndex(implicitCoordinatesEmpty); expect(indexEmpty).toBe(4); expect(subtree.tileIsAvailableAtIndex(indexEmpty)).toEqual(false); expect( subtree.tileIsAvailableAtCoordinates(implicitCoordinatesEmpty) ).toEqual(false); expect(subtree.contentIsAvailableAtIndex(indexEmpty)).toEqual(false); expect( subtree.contentIsAvailableAtCoordinates(implicitCoordinatesEmpty) ).toEqual(false); }); it("getChildSubtreeIndex throws for a tile not in the child subtrees", async function() { const subtreeDescription = { tileAvailability: { descriptor: "11000", lengthBits: 5, isInternal: true }, contentAvailability: [ { descriptor: "11000", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: "100000000000000", lengthBits: 16, isInternal: true } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const deeperQuadtreeCoordinates = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitQuadtree.subdivisionScheme, subtreeLevels: implicitQuadtree.subtreeLevels, level: 2, x: 0, y: 0 }); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitQuadtree, deeperQuadtreeCoordinates ); expect(function() { const implicitCoordinates = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitQuadtree.subdivisionScheme, subtreeLevels: implicitQuadtree.subtreeLevels, level: 0, x: 0, y: 0 }); return subtree.getChildSubtreeIndex(implicitCoordinates); }).toThrowError(import__523.RuntimeError); expect(function() { const implicitCoordinates = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitQuadtree.subdivisionScheme, subtreeLevels: implicitQuadtree.subtreeLevels, level: 5, x: 0, y: 0 }); return subtree.getChildSubtreeIndex(implicitCoordinates); }).toThrowError(import__523.RuntimeError); }); it("getChildSubtreeIndex computes bit index for a tile in the subtree", async function() { const subtreeDescription = { tileAvailability: { descriptor: "11000", lengthBits: 5, isInternal: true }, contentAvailability: [ { descriptor: "11000", lengthBits: 9, isInternal: true } ], childSubtreeAvailability: { descriptor: "100000000000000", lengthBits: 16, isInternal: true } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const subtreeCoordinates = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitQuadtree.subdivisionScheme, subtreeLevels: implicitQuadtree.subtreeLevels, level: 0, x: 0, y: 0 }); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitQuadtree, subtreeCoordinates ); const implicitCoordinatesFull = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitQuadtree.subdivisionScheme, subtreeLevels: implicitQuadtree.subtreeLevels, level: 2, x: 0, y: 0 }); const indexFull = subtree.getChildSubtreeIndex(implicitCoordinatesFull); expect(indexFull).toBe(0); expect(subtree.childSubtreeIsAvailableAtIndex(indexFull)).toEqual(true); expect( subtree.childSubtreeIsAvailableAtCoordinates(implicitCoordinatesFull) ).toEqual(true); const implicitCoordinatesEmpty = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitQuadtree.subdivisionScheme, subtreeLevels: implicitQuadtree.subtreeLevels, level: 2, x: 1, y: 1 }); const indexEmpty = subtree.getChildSubtreeIndex(implicitCoordinatesEmpty); expect(indexEmpty).toBe(3); expect(subtree.childSubtreeIsAvailableAtIndex(indexEmpty)).toEqual(false); expect( subtree.childSubtreeIsAvailableAtCoordinates(implicitCoordinatesEmpty) ).toEqual(false); }); it("computes parent Morton index", async function() { const subtreeDescription = { tileAvailability: { descriptor: "110101111", lengthBits: 9, isInternal: true }, contentAvailability: [ { descriptor: "110101011", lengthBits: 9, isInternal: true } ], childSubtreeAvailability: { descriptor: 1, lengthBits: 64, isInternal: true } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitOctree, octreeCoordinates ); expect(subtree.getParentMortonIndex(341)).toBe(42); }); it("availability works for octrees", async function() { const subtreeDescription = { tileAvailability: { descriptor: "110101111", lengthBits: 9, isInternal: true }, contentAvailability: [ { descriptor: "110101011", lengthBits: 9, isInternal: true } ], childSubtreeAvailability: { descriptor: 1, lengthBits: 64, isInternal: true } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitOctree, octreeCoordinates ); expectTileAvailability(subtree, subtreeDescription.tileAvailability); expectContentAvailability(subtree, subtreeDescription.contentAvailability); expectChildSubtreeAvailability( subtree, subtreeDescription.childSubtreeAvailability ); }); it("handles subtree with constant-only data", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 9, isInternal: true }, contentAvailability: [ { descriptor: 0, lengthBits: 9, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 64, isInternal: true } }; const constantOnly = true; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription, constantOnly ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitOctree, octreeCoordinates ); expectTileAvailability(subtree, subtreeDescription.tileAvailability); expectContentAvailability(subtree, subtreeDescription.contentAvailability); expectChildSubtreeAvailability( subtree, subtreeDescription.childSubtreeAvailability ); }); it("destroys", async function() { const subtreeDescription = { tileAvailability: { descriptor: "11010", lengthBits: 5, isInternal: false }, contentAvailability: [ { descriptor: "11000", lengthBits: 5, isInternal: false } ], childSubtreeAvailability: { descriptor: "1111000010100000", lengthBits: 16, isInternal: false } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const unload = spyOn(import__523.ResourceCache, "unload"); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, implicitQuadtree, quadtreeCoordinates ); const bufferLoader = subtree._bufferLoader; expect(bufferLoader).toBeDefined(); expect(subtree.isDestroyed()).toBe(false); subtree.destroy(); expect(subtree.isDestroyed()).toBe(true); expect(unload).toHaveBeenCalled(); }); describe("multiple contents", function() { const tileJson = { geometricError: 500, refine: "ADD", boundingVolume: { region: [0, 0, Math.PI / 24, Math.PI / 24, 0, 1e3] }, implicitTiling: { subdivisionScheme: "QUADTREE", subtreeLevels: 2, availableLevels: 2, subtrees: { uri: "https://example.com/{level}/{x}/{y}.subtree" } }, contents: [ { uri: "https://example.com/{level}/{x}/{y}.b3dm" }, { uri: "https://example.com/{level}/{x}/{y}.pnts" } ] }; let multipleContentsQuadtree; let multipleContentsCoordinates; beforeAll(function() { multipleContentsQuadtree = new import__523.ImplicitTileset( tilesetResource, tileJson, metadataSchema ); multipleContentsCoordinates = new import__523.ImplicitTileCoordinates({ subdivisionScheme: multipleContentsQuadtree.subdivisionScheme, subtreeLevels: multipleContentsQuadtree.subtreeLevels, level: 0, x: 0, y: 0 }); }); it("contentIsAvailableAtIndex throws for out-of-bounds contentIndex", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true }, contentAvailability: [ { descriptor: 1, lengthBits: 5, isInternal: true }, { descriptor: "10011", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, multipleContentsQuadtree, multipleContentsCoordinates ); const outOfBounds = 100; expect(function() { subtree.contentIsAvailableAtIndex(0, outOfBounds); }).toThrowDeveloperError(); }); it("contentIsAvailableAtIndex works for multiple contents", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true }, contentAvailability: [ { descriptor: 1, lengthBits: 5, isInternal: false }, { descriptor: "10011", lengthBits: 5, isInternal: false } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, multipleContentsQuadtree, multipleContentsCoordinates ); expect(fetchExternal).toHaveBeenCalled(); expectTileAvailability(subtree, subtreeDescription.tileAvailability); expectContentAvailability( subtree, subtreeDescription.contentAvailability ); }); it("contentIsAvailableAtIndex works for multiple contents (legacy)", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true }, contentAvailability: [ { descriptor: 1, lengthBits: 5, isInternal: false }, { descriptor: "10011", lengthBits: 5, isInternal: false } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, useLegacySchema: true }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, multipleContentsQuadtree, multipleContentsCoordinates ); expect(fetchExternal).toHaveBeenCalled(); expectTileAvailability(subtree, subtreeDescription.tileAvailability); expectContentAvailability( subtree, subtreeDescription.contentAvailability ); }); }); describe("metadata", function() { const tileProperties = { properties: { highlightColor: { type: "VEC3", componentType: "UINT8" }, buildingCount: { type: "SCALAR", componentType: "UINT16" } } }; const tileSchema = { classes: { tile: tileProperties } }; let subtreeJsonResource; const subtreeSchema = { classes: { subtree: { properties: { author: { type: "STRING" }, credits: { type: "STRING", array: true } } } } }; const buildingProperties = { properties: { height: { type: "SCALAR", componentType: "UINT16", semantic: "_HEIGHT" }, buildingType: { type: "STRING", semantic: "_BUILDING_TYPE" } } }; const treeProperties = { properties: { height: { type: "SCALAR", componentType: "UINT16", semantic: "_HEIGHT" }, species: { type: "STRING", semantic: "_TREE_SPECIES" } } }; const buildingSchema = { classes: { tile: tileProperties, building: buildingProperties } }; const multipleContentsSchema = { classes: { tile: tileProperties, building: buildingProperties, tree: treeProperties } }; const highlightColors = [ [255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0], [255, 0, 255] ]; const buildingCounts = [100, 800, 500, 350, 200]; const tileTableDescription = { class: "tile", properties: { highlightColor: highlightColors, buildingCount: buildingCounts } }; const buildingHeights = [20, 30, 10]; const buildingTypes = ["Residential", "Commercial", "Other"]; const buildingTableDescription = { class: "building", properties: { height: buildingHeights, buildingType: buildingTypes } }; const treeHeights = [3, 1, 2, 4]; const treeSpecies = ["Oak", "Chestnut", "Pine", "Maple"]; const treeTableDescription = { class: "tree", properties: { height: treeHeights, species: treeSpecies } }; const tilePropertyTablesDescription = { schema: tileSchema, propertyTables: [tileTableDescription] }; const buildingPropertyTablesDescription = { schema: buildingSchema, propertyTables: [tileTableDescription, buildingTableDescription] }; const multiplePropertyTablesDescription = { schema: multipleContentsSchema, propertyTables: [ tileTableDescription, buildingTableDescription, treeTableDescription ] }; let tileMetadataSchema; let subtreeMetadataSchema; let buildingMetadataSchema; let multipleContentsMetadataSchema; let tileMetadataQuadtree; let subtreeMetadataQuadtree; let buildingMetadataQuadtree; let multipleContentsMetadataQuadtree; beforeAll(function() { subtreeJsonResource = new import__523.Resource({ url: "https://example.com/0.0.0.json" }); tileMetadataSchema = import__523.MetadataSchema.fromJson(tileSchema); subtreeMetadataSchema = import__523.MetadataSchema.fromJson(subtreeSchema); buildingMetadataSchema = import__523.MetadataSchema.fromJson(buildingSchema); multipleContentsMetadataSchema = import__523.MetadataSchema.fromJson( multipleContentsSchema ); tileMetadataQuadtree = new import__523.ImplicitTileset( tilesetResource, implicitQuadtreeJson, tileMetadataSchema ); subtreeMetadataQuadtree = new import__523.ImplicitTileset( tilesetResource, implicitQuadtreeJson, subtreeMetadataSchema ); buildingMetadataQuadtree = new import__523.ImplicitTileset( tilesetResource, implicitQuadtreeJson, buildingMetadataSchema ); multipleContentsMetadataQuadtree = new import__523.ImplicitTileset( tilesetResource, implicitQuadtreeJson, multipleContentsMetadataSchema ); }); it("creates subtree metadata from JSON", async function() { const metadataSubtreeJson = { tileAvailability: { constant: 1 }, contentAvailability: { constant: 1 }, childSubtreeAvailability: { constant: 0 }, subtreeMetadata: { class: "subtree", properties: { author: "Cesium", credits: ["A", "B", "C"] } } }; const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeJsonResource, metadataSubtreeJson, void 0, subtreeMetadataQuadtree, quadtreeCoordinates ); const metadata = subtree.metadata; expect(metadata).toBeDefined(); expect(metadata.hasProperty("author")).toBe(true); expect(metadata.hasProperty("credits")).toBe(true); expect(metadata.getProperty("author")).toEqual("Cesium"); expect(metadata.getProperty("credits")).toEqual(["A", "B", "C"]); }); it("creates a metadata table from internal metadata for tiles", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: 1, lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: true, propertyTables: tilePropertyTablesDescription } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, tileMetadataQuadtree, quadtreeCoordinates ); expect(fetchExternal).not.toHaveBeenCalled(); const metadataTable = subtree.tileMetadataTable; expect(metadataTable).toBeDefined(); expect(metadataTable.count).toBe(5); for (let i = 0; i < buildingCounts.length; i++) { expect(metadataTable.getProperty(i, "highlightColor")).toEqual( import__523.Cartesian3.unpack(highlightColors[i]) ); expect(metadataTable.getProperty(i, "buildingCount")).toBe( buildingCounts[i] ); } }); it("creates a metadata table from external metadata for tiles", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: 1, lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: false, propertyTables: tilePropertyTablesDescription } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, tileMetadataQuadtree, quadtreeCoordinates ); expect(fetchExternal).toHaveBeenCalled(); const metadataTable = subtree.tileMetadataTable; expect(metadataTable).toBeDefined(); expect(metadataTable.count).toBe(5); for (let i = 0; i < buildingCounts.length; i++) { expect(metadataTable.getProperty(i, "highlightColor")).toEqual( import__523.Cartesian3.unpack(highlightColors[i]) ); expect(metadataTable.getProperty(i, "buildingCount")).toBe( buildingCounts[i] ); } }); it("creates a metadata table from internal metadata for single content", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: "10110", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: true, propertyTables: buildingPropertyTablesDescription } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, buildingMetadataQuadtree, quadtreeCoordinates ); expect(fetchExternal).not.toHaveBeenCalled(); const metadataTables = subtree.contentMetadataTables; expect(metadataTables).toBeDefined(); expect(metadataTables.length).toBe(1); const metadataTable = metadataTables[0]; expect(metadataTable).toBeDefined(); expect(metadataTable.count).toBe(3); for (let i = 0; i < buildingHeights.length; i++) { expect(metadataTable.getProperty(i, "height")).toEqual( buildingHeights[i] ); expect(metadataTable.getProperty(i, "buildingType")).toBe( buildingTypes[i] ); } }); it("creates a metadata table from external metadata for single content", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: "10110", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: false, propertyTables: buildingPropertyTablesDescription } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, buildingMetadataQuadtree, quadtreeCoordinates ); expect(fetchExternal).toHaveBeenCalled(); const metadataTables = subtree.contentMetadataTables; expect(metadataTables).toBeDefined(); expect(metadataTables.length).toBe(1); const metadataTable = metadataTables[0]; expect(metadataTable).toBeDefined(); expect(metadataTable.count).toBe(3); for (let i = 0; i < buildingHeights.length; i++) { expect(metadataTable.getProperty(i, "height")).toEqual( buildingHeights[i] ); expect(metadataTable.getProperty(i, "buildingType")).toBe( buildingTypes[i] ); } }); it("creates a metadata table from internal metadata for multiple contents", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: "10110", lengthBits: 5, isInternal: true }, { descriptor: "01111", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: true, propertyTables: multiplePropertyTablesDescription } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, multipleContentsMetadataQuadtree, quadtreeCoordinates ); expect(fetchExternal).not.toHaveBeenCalled(); const metadataTables = subtree.contentMetadataTables; expect(metadataTables).toBeDefined(); expect(metadataTables.length).toBe(2); const buildingMetadataTable = metadataTables[0]; expect(buildingMetadataTable).toBeDefined(); expect(buildingMetadataTable.count).toBe(3); for (let i = 0; i < buildingHeights.length; i++) { expect(buildingMetadataTable.getProperty(i, "height")).toEqual( buildingHeights[i] ); expect(buildingMetadataTable.getProperty(i, "buildingType")).toBe( buildingTypes[i] ); } const treeMetadataTable = metadataTables[1]; expect(treeMetadataTable).toBeDefined(); expect(treeMetadataTable.count).toBe(4); for (let i = 0; i < treeHeights.length; i++) { expect(treeMetadataTable.getProperty(i, "height")).toEqual( treeHeights[i] ); expect(treeMetadataTable.getProperty(i, "species")).toBe( treeSpecies[i] ); } }); it("creates a metadata table from external metadata for multiple contents", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: "10110", lengthBits: 5, isInternal: true }, { descriptor: "01111", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: false, propertyTables: multiplePropertyTablesDescription } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, multipleContentsMetadataQuadtree, quadtreeCoordinates ); expect(fetchExternal).toHaveBeenCalled(); const metadataTables = subtree.contentMetadataTables; expect(metadataTables).toBeDefined(); expect(metadataTables.length).toBe(2); const buildingMetadataTable = metadataTables[0]; expect(buildingMetadataTable).toBeDefined(); expect(buildingMetadataTable.count).toBe(3); for (let i = 0; i < buildingHeights.length; i++) { expect(buildingMetadataTable.getProperty(i, "height")).toEqual( buildingHeights[i] ); expect(buildingMetadataTable.getProperty(i, "buildingType")).toBe( buildingTypes[i] ); } const treeMetadataTable = metadataTables[1]; expect(treeMetadataTable).toBeDefined(); expect(treeMetadataTable.count).toBe(4); for (let i = 0; i < treeHeights.length; i++) { expect(treeMetadataTable.getProperty(i, "height")).toEqual( treeHeights[i] ); expect(treeMetadataTable.getProperty(i, "species")).toBe( treeSpecies[i] ); } }); it("creates tile metadata view", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: 1, lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: true, propertyTables: tilePropertyTablesDescription } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, tileMetadataQuadtree, quadtreeCoordinates ); expect(fetchExternal).not.toHaveBeenCalled(); const metadataView = subtree.getTileMetadataView(quadtreeCoordinates); expect(metadataView).toBeDefined(); expect(metadataView.getProperty("highlightColor")).toEqual( import__523.Cartesian3.unpack(highlightColors[0]) ); expect(metadataView.getProperty("buildingCount")).toEqual( buildingCounts[0] ); }); it("returns undefined tile metadata view for invalid coordinates", async function() { const subtreeDescription = { tileAvailability: { descriptor: "11000", lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: "11000", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: true, propertyTables: tilePropertyTablesDescription } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, tileMetadataQuadtree, quadtreeCoordinates ); expect(fetchExternal).not.toHaveBeenCalled(); const coordinates = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitQuadtree.subdivisionScheme, subtreeLevels: implicitQuadtree.subtreeLevels, level: 1, x: 1, y: 1 }); const metadataView = subtree.getTileMetadataView(coordinates); expect(metadataView).not.toBeDefined(); }); it("creates content metadata view", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: "10110", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: true, propertyTables: buildingPropertyTablesDescription } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, buildingMetadataQuadtree, quadtreeCoordinates ); expect(fetchExternal).not.toHaveBeenCalled(); const metadataView = subtree.getContentMetadataView( quadtreeCoordinates, 0 ); expect(metadataView).toBeDefined(); expect(metadataView.getProperty("height")).toEqual(buildingHeights[0]); expect(metadataView.getProperty("buildingType")).toEqual( buildingTypes[0] ); }); it("returns undefined content metadata view for invalid coordinates", async function() { const subtreeDescription = { tileAvailability: { descriptor: "11000", lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: "10110", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: true, propertyTables: buildingPropertyTablesDescription } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, buildingMetadataQuadtree, quadtreeCoordinates ); expect(fetchExternal).not.toHaveBeenCalled(); const coordinates = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitQuadtree.subdivisionScheme, subtreeLevels: implicitQuadtree.subtreeLevels, level: 1, x: 1, y: 1 }); const metadataView = subtree.getContentMetadataView(coordinates, 0); expect(metadataView).not.toBeDefined(); }); it("creates content metadata view for multiple contents", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: "10110", lengthBits: 5, isInternal: true }, { descriptor: "01111", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: true, propertyTables: multiplePropertyTablesDescription } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, multipleContentsMetadataQuadtree, quadtreeCoordinates ); expect(fetchExternal).not.toHaveBeenCalled(); const coordinates = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitQuadtree.subdivisionScheme, subtreeLevels: implicitQuadtree.subtreeLevels, level: 1, x: 0, y: 1 }); const buildingMetadataView = subtree.getContentMetadataView( coordinates, 0 ); expect(buildingMetadataView).toBeDefined(); expect(buildingMetadataView.getProperty("height")).toEqual( buildingHeights[2] ); expect(buildingMetadataView.getProperty("buildingType")).toEqual( buildingTypes[2] ); const treeMetadataView = subtree.getContentMetadataView(coordinates, 1); expect(treeMetadataView).toBeDefined(); expect(treeMetadataView.getProperty("height")).toEqual(treeHeights[2]); expect(treeMetadataView.getProperty("species")).toEqual(treeSpecies[2]); }); it("returns undefined content metadata view for invalid coordinates and multiple contents", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: "10110", lengthBits: 5, isInternal: true }, { descriptor: "01111", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: true, propertyTables: multiplePropertyTablesDescription } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, multipleContentsMetadataQuadtree, quadtreeCoordinates ); expect(fetchExternal).not.toHaveBeenCalled(); const coordinates = new import__523.ImplicitTileCoordinates({ subdivisionScheme: implicitQuadtree.subdivisionScheme, subtreeLevels: implicitQuadtree.subtreeLevels, level: 1, x: 1, y: 1 }); const buildingMetadataView = subtree.getContentMetadataView( coordinates, 0 ); expect(buildingMetadataView).not.toBeDefined(); const treeMetadataView = subtree.getContentMetadataView( quadtreeCoordinates, 1 ); expect(treeMetadataView).not.toBeDefined(); }); it("handles 3DTILES_metadata extension for backwards compatibility", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: "10110", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: true, propertyTables: buildingPropertyTablesDescription }, useLegacySchema: true }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, buildingMetadataQuadtree, quadtreeCoordinates ); expect(fetchExternal).not.toHaveBeenCalled(); const metadataTables = subtree.contentMetadataTables; expect(metadataTables).toBeDefined(); expect(metadataTables.length).toBe(1); const metadataTable = metadataTables[0]; expect(metadataTable).toBeDefined(); expect(metadataTable.count).toBe(3); for (let i = 0; i < buildingHeights.length; i++) { expect(metadataTable.getProperty(i, "height")).toEqual( buildingHeights[i] ); expect(metadataTable.getProperty(i, "buildingType")).toBe( buildingTypes[i] ); } }); it("works correctly if availableCount is undefined", async function() { const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true, includeAvailableCount: false }, contentAvailability: [ { descriptor: 1, lengthBits: 5, isInternal: true, includeAvailableCount: false } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: true, propertyTables: tilePropertyTablesDescription } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const fetchExternal = spyOn(import__523.ResourceCache, "get").and.callFake( fakeResourceLoader(results.externalBuffer) ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, tileMetadataQuadtree, quadtreeCoordinates ); expect(fetchExternal).not.toHaveBeenCalled(); const metadataTable = subtree.tileMetadataTable; expect(metadataTable).toBeDefined(); expect(metadataTable.count).toBe(5); for (let i = 0; i < buildingCounts.length; i++) { expect(metadataTable.getProperty(i, "highlightColor")).toEqual( import__523.Cartesian3.unpack(highlightColors[i]) ); expect(metadataTable.getProperty(i, "buildingCount")).toBe( buildingCounts[i] ); } }); it("handles unavailable tiles correctly", async function() { const highlightColors2 = [ [255, 0, 0], [255, 255, 0], [255, 0, 255] ]; const buildingCounts2 = [100, 350, 200]; const tileTableDescription2 = { class: "tile", properties: { highlightColor: highlightColors2, buildingCount: buildingCounts2 } }; const propertyTablesDescription = { schema: tileSchema, propertyTables: [tileTableDescription2] }; const subtreeDescription = { tileAvailability: { descriptor: "10011", lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: "10011", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: true, propertyTables: propertyTablesDescription } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, tileMetadataQuadtree, quadtreeCoordinates ); expect(subtree._tileJumpBuffer).toEqual(new Uint8Array([0, 0, 0, 1, 2])); const metadataTable = subtree.tileMetadataTable; expect(metadataTable).toBeDefined(); expect(metadataTable.count).toBe(3); for (let i = 0; i < buildingCounts2.length; i++) { expect(metadataTable.getProperty(i, "highlightColor")).toEqual( import__523.Cartesian3.unpack(highlightColors2[i]) ); expect(metadataTable.getProperty(i, "buildingCount")).toBe( buildingCounts2[i] ); } }); it("handles unavailable content correctly", async function() { const buildingHeightsTruncated = buildingHeights.slice(0, 2); const buildingTypesTruncated = buildingTypes.slice(0, 2); const subtreeDescription = { tileAvailability: { descriptor: "10011", lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: "10010", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: true, propertyTables: buildingPropertyTablesDescription } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, buildingMetadataQuadtree, quadtreeCoordinates ); const jumpBuffer = subtree._contentJumpBuffers[0]; expect(jumpBuffer).toEqual(new Uint8Array([0, 0, 0, 1, 0])); const metadataTables = subtree.contentMetadataTables; expect(metadataTables).toBeDefined(); expect(metadataTables.length).toBe(1); const metadataTable = metadataTables[0]; expect(metadataTable).toBeDefined(); expect(metadataTable.count).toBe(2); for (let i = 0; i < buildingHeightsTruncated.length; i++) { expect(metadataTable.getProperty(i, "height")).toEqual( buildingHeightsTruncated[i] ); expect(metadataTable.getProperty(i, "buildingType")).toBe( buildingTypesTruncated[i] ); } }); it("handles unavailable multiple contents correctly", async function() { const buildingHeightsTruncated = buildingHeights.slice(0, 1); const buildingTypesTruncated = buildingTypes.slice(0, 1); const treeHeightsTruncated = treeHeights.slice(0, 2); const treeSpeciesTruncated = treeSpecies.slice(0, 2); const subtreeDescription = { tileAvailability: { descriptor: "10011", lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: "10000", lengthBits: 5, isInternal: true }, { descriptor: "00011", lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: true, propertyTables: multiplePropertyTablesDescription } }; const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, multipleContentsMetadataQuadtree, quadtreeCoordinates ); const buildingJumpBuffer = subtree._contentJumpBuffers[0]; expect(buildingJumpBuffer).toEqual(new Uint8Array([0, 0, 0, 0, 0])); const treeJumpBuffer = subtree._contentJumpBuffers[1]; expect(treeJumpBuffer).toEqual(new Uint8Array([0, 0, 0, 0, 1])); const metadataTables = subtree.contentMetadataTables; expect(metadataTables).toBeDefined(); expect(metadataTables.length).toBe(2); const buildingMetadataTable = metadataTables[0]; expect(buildingMetadataTable).toBeDefined(); expect(buildingMetadataTable.count).toBe(1); for (let i = 0; i < buildingHeightsTruncated.length; i++) { expect(buildingMetadataTable.getProperty(i, "height")).toEqual( buildingHeightsTruncated[i] ); expect(buildingMetadataTable.getProperty(i, "buildingType")).toBe( buildingTypesTruncated[i] ); } const treeMetadataTable = metadataTables[1]; expect(treeMetadataTable).toBeDefined(); expect(treeMetadataTable.count).toBe(2); for (let i = 0; i < treeHeightsTruncated.length; i++) { expect(treeMetadataTable.getProperty(i, "height")).toEqual( treeHeightsTruncated[i] ); expect(treeMetadataTable.getProperty(i, "species")).toBe( treeSpeciesTruncated[i] ); } }); it("handles metadata with string and array offsets", async function() { if (!MetadataTester_default.isSupported()) { return; } const arraySchema = { classes: { tile: { properties: { stringProperty: { type: "STRING" }, arrayProperty: { type: "SCALAR", componentType: "INT16", array: true }, arrayOfStringProperty: { type: "STRING", array: true } } } } }; const stringValues = ["foo", "bar", "baz", "qux", "quux"]; const arrayValues = [[1, 2], [3], [4, 5, 6], [7], []]; const stringArrayValues = [ ["foo"], ["bar", "bar"], ["qux"], ["quux"], [] ]; const tileTableDescription2 = { class: "tile", properties: { stringProperty: stringValues, arrayProperty: arrayValues, arrayOfStringProperty: stringArrayValues } }; const propertyTablesWithOffsets = { schema: arraySchema, propertyTables: [tileTableDescription2] }; const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: 1, lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: true, propertyTables: propertyTablesWithOffsets } }; const metadataSchema2 = import__523.MetadataSchema.fromJson(arraySchema); const arrayQuadtree = new import__523.ImplicitTileset( tilesetResource, implicitQuadtreeJson, metadataSchema2 ); const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, arrayQuadtree, quadtreeCoordinates ); const metadataTable = subtree.tileMetadataTable; expect(metadataTable).toBeDefined(); expect(metadataTable.count).toBe(5); for (let i = 0; i < buildingCounts.length; i++) { expect(metadataTable.getProperty(i, "stringProperty")).toBe( stringValues[i] ); expect(metadataTable.getProperty(i, "arrayProperty")).toEqual( arrayValues[i] ); expect(metadataTable.getProperty(i, "arrayOfStringProperty")).toEqual( stringArrayValues[i] ); } }); it("handles legacy 3DTILES_metadata schema correctly for arrays and strings", async function() { if (!MetadataTester_default.isSupported()) { return; } const arraySchema = { classes: { tile: { properties: { stringProperty: { type: "STRING" }, arrayProperty: { type: "SCALAR", componentType: "INT16", array: true }, arrayOfStringProperty: { type: "STRING", array: true } } } } }; const stringValues = ["foo", "bar", "baz", "qux", "quux"]; const arrayValues = [[1, 2], [3], [4, 5, 6], [7], []]; const stringArrayValues = [ ["foo"], ["bar", "bar"], ["qux"], ["quux"], [] ]; const tileTableDescription2 = { class: "tile", properties: { stringProperty: stringValues, arrayProperty: arrayValues, arrayOfStringProperty: stringArrayValues }, useLegacySchema: true }; const propertyTablesWithOffsets = { schema: arraySchema, propertyTables: [tileTableDescription2] }; const subtreeDescription = { tileAvailability: { descriptor: 1, lengthBits: 5, isInternal: true, includeAvailableCount: true }, contentAvailability: [ { descriptor: 1, lengthBits: 5, isInternal: true } ], childSubtreeAvailability: { descriptor: 0, lengthBits: 16, isInternal: true }, metadata: { isInternal: true, propertyTables: propertyTablesWithOffsets } }; const metadataSchema2 = import__523.MetadataSchema.fromJson(arraySchema); const arrayQuadtree = new import__523.ImplicitTileset( tilesetResource, implicitQuadtreeJson, metadataSchema2 ); const results = ImplicitTilingTester_default.generateSubtreeBuffers( subtreeDescription ); const subtree = await import__523.ImplicitSubtree.fromSubtreeJson( subtreeResource, void 0, results.subtreeBuffer, arrayQuadtree, quadtreeCoordinates ); const metadataTable = subtree.tileMetadataTable; expect(metadataTable).toBeDefined(); expect(metadataTable.count).toBe(5); for (let i = 0; i < buildingCounts.length; i++) { expect(metadataTable.getProperty(i, "stringProperty")).toBe( stringValues[i] ); expect(metadataTable.getProperty(i, "arrayProperty")).toEqual( arrayValues[i] ); expect(metadataTable.getProperty(i, "arrayOfStringProperty")).toEqual( stringArrayValues[i] ); } }); }); }); // packages/engine/Specs/Scene/ImplicitTileCoordinatesSpec.js var import__524 = __toESM(require_Cesium(), 1); describe("Scene/ImplicitTileCoordinates", function() { function quadtreeCoordinates(level, x, y, subtreeLevels) { return new import__524.ImplicitTileCoordinates({ subdivisionScheme: import__524.ImplicitSubdivisionScheme.QUADTREE, subtreeLevels: (0, import__524.defaultValue)(subtreeLevels, 2), level, x, y }); } function octreeCoordinates(level, x, y, z, subtreeLevels) { return new import__524.ImplicitTileCoordinates({ subdivisionScheme: import__524.ImplicitSubdivisionScheme.OCTREE, subtreeLevels: (0, import__524.defaultValue)(subtreeLevels, 2), level, x, y, z }); } it("constructs quadtree", function() { const coordinates = new import__524.ImplicitTileCoordinates({ subdivisionScheme: import__524.ImplicitSubdivisionScheme.QUADTREE, subtreeLevels: 6, level: 4, x: 3, y: 2 }); expect(coordinates.subdivisionScheme).toEqual( import__524.ImplicitSubdivisionScheme.QUADTREE ); expect(coordinates.level).toEqual(4); expect(coordinates.x).toEqual(3); expect(coordinates.y).toEqual(2); expect(coordinates.z).not.toBeDefined(); }); it("constructs octree", function() { const coordinates = new import__524.ImplicitTileCoordinates({ subdivisionScheme: import__524.ImplicitSubdivisionScheme.OCTREE, subtreeLevels: 6, level: 4, x: 3, y: 2, z: 1 }); expect(coordinates.subdivisionScheme).toEqual( import__524.ImplicitSubdivisionScheme.OCTREE ); expect(coordinates.level).toEqual(4); expect(coordinates.x).toEqual(3); expect(coordinates.y).toEqual(2); expect(coordinates.z).toEqual(1); }); it("constructor throws with invalid inputs for quadree", function() { expect(function() { quadtreeCoordinates(-1, 0, 0); }).toThrowDeveloperError(); expect(function() { quadtreeCoordinates(0, -1, 0); }).toThrowDeveloperError(); expect(function() { quadtreeCoordinates(0, 0, -1); }).toThrowDeveloperError(); expect(function() { quadtreeCoordinates(0, 4, 0); }).toThrowDeveloperError(); expect(function() { quadtreeCoordinates(0, 0, 4); }).toThrowDeveloperError(); }); it("constructor throws with invalid inputs for octree", function() { expect(function() { octreeCoordinates(0, 0, 0, -1); }).toThrowDeveloperError(); expect(function() { octreeCoordinates(0, 0, 0, 4); }).toThrowDeveloperError(); }); it("getDescendantCoordinates throws with invalid inputs", function() { expect(function() { quadtreeCoordinates(0, 0, 0).getDescendantCoordinates(void 0); }).toThrowDeveloperError(); expect(function() { return quadtreeCoordinates(0, 0, 0).getDescendantCoordinates( octreeCoordinates(0, 0, 0, 0) ); }).toThrowDeveloperError(); expect(function() { const subtreeLevelsA = 2; const subtreeLevelsB = 3; return quadtreeCoordinates( 0, 0, 0, subtreeLevelsA ).getDescendantCoordinates(quadtreeCoordinates(0, 0, 0, subtreeLevelsB)); }).toThrowDeveloperError(); }); it("getDescendantCoordinates works as expected for quadtree", function() { expect( quadtreeCoordinates(0, 0, 0).getDescendantCoordinates(quadtreeCoordinates(0, 0, 0)).isEqual(quadtreeCoordinates(0, 0, 0)) ).toEqual(true); expect( quadtreeCoordinates(0, 0, 0).getDescendantCoordinates(quadtreeCoordinates(1, 1, 1)).isEqual(quadtreeCoordinates(1, 1, 1)) ).toEqual(true); expect( quadtreeCoordinates(1, 1, 1).getDescendantCoordinates(quadtreeCoordinates(2, 3, 3)).isEqual(quadtreeCoordinates(3, 7, 7)) ).toEqual(true); }); it("getDescendantCoordinates works as expected for octree", function() { expect( octreeCoordinates(0, 0, 0, 0).getDescendantCoordinates(octreeCoordinates(0, 0, 0, 0)).isEqual(octreeCoordinates(0, 0, 0, 0)) ).toEqual(true); expect( octreeCoordinates(0, 0, 0, 0).getDescendantCoordinates(octreeCoordinates(1, 1, 1, 1)).isEqual(octreeCoordinates(1, 1, 1, 1)) ).toEqual(true); expect( octreeCoordinates(1, 1, 1, 1).getDescendantCoordinates(octreeCoordinates(2, 3, 3, 3)).isEqual(octreeCoordinates(3, 7, 7, 7)) ).toEqual(true); }); it("getAncestorCoordinates throws with invalid inputs", function() { expect(function() { return quadtreeCoordinates(0, 0, 0).getAncestorCoordinates(void 0); }).toThrowDeveloperError(); expect(function() { return quadtreeCoordinates(0, 0, 0).getAncestorCoordinates(-1); }).toThrowDeveloperError(); expect(function() { return quadtreeCoordinates(0, 0, 0).getAncestorCoordinates(1); }).toThrowDeveloperError(); }); it("getAncestorCoordinates works as expected for quadtree", function() { expect( quadtreeCoordinates(0, 0, 0).getAncestorCoordinates(0).isEqual(quadtreeCoordinates(0, 0, 0)) ).toEqual(true); expect( quadtreeCoordinates(1, 0, 0).getAncestorCoordinates(1).isEqual(quadtreeCoordinates(0, 0, 0)) ).toEqual(true); expect( quadtreeCoordinates(1, 1, 1).getAncestorCoordinates(1).isEqual(quadtreeCoordinates(0, 0, 0)) ).toEqual(true); expect( quadtreeCoordinates(2, 3, 3).getAncestorCoordinates(1).isEqual(quadtreeCoordinates(1, 1, 1)) ).toEqual(true); expect( quadtreeCoordinates(2, 3, 3).getAncestorCoordinates(2).isEqual(quadtreeCoordinates(0, 0, 0)) ).toEqual(true); }); it("getAncestorCoordinates works as expected for octree", function() { expect( octreeCoordinates(0, 0, 0, 0).getAncestorCoordinates(0).isEqual(octreeCoordinates(0, 0, 0, 0)) ).toEqual(true); expect( octreeCoordinates(1, 0, 0, 0).getAncestorCoordinates(1).isEqual(octreeCoordinates(0, 0, 0, 0)) ).toEqual(true); expect( octreeCoordinates(1, 1, 1, 1).getAncestorCoordinates(1).isEqual(octreeCoordinates(0, 0, 0, 0)) ).toEqual(true); expect( octreeCoordinates(2, 3, 3, 3).getAncestorCoordinates(1).isEqual(octreeCoordinates(1, 1, 1, 1)) ).toEqual(true); expect( octreeCoordinates(2, 3, 3, 3).getAncestorCoordinates(2).isEqual(octreeCoordinates(0, 0, 0, 0)) ).toEqual(true); }); it("getOffsetCoordinates throws with invalid inputs", function() { expect(function() { return quadtreeCoordinates(0, 0, 0).getOffsetCoordinates(void 0); }).toThrowDeveloperError(); expect(function() { return quadtreeCoordinates(1, 0, 0).getOffsetCoordinates( quadtreeCoordinates(0, 0, 0) ); }).toThrowDeveloperError(); expect(function() { return quadtreeCoordinates(1, 0, 0).getOffsetCoordinates( quadtreeCoordinates(2, 3, 3) ); }).toThrowDeveloperError(); expect(function() { return quadtreeCoordinates(0, 0, 0).getOffsetCoordinates( octreeCoordinates(0, 0, 0, 0) ); }).toThrowDeveloperError(); expect(function() { const subtreeLevelsA = 2; const subtreeLevelsB = 3; return quadtreeCoordinates(0, 0, 0, subtreeLevelsA).getOffsetCoordinates( quadtreeCoordinates(0, 0, 0, subtreeLevelsB) ); }).toThrowDeveloperError(); }); it("getOffsetCoordinates works as expected for quadtree", function() { expect( quadtreeCoordinates(0, 0, 0).getOffsetCoordinates(quadtreeCoordinates(0, 0, 0)).isEqual(quadtreeCoordinates(0, 0, 0)) ).toEqual(true); expect( quadtreeCoordinates(0, 0, 0).getOffsetCoordinates(quadtreeCoordinates(1, 1, 1)).isEqual(quadtreeCoordinates(1, 1, 1)) ).toEqual(true); expect( quadtreeCoordinates(0, 0, 0).getOffsetCoordinates(quadtreeCoordinates(2, 3, 3)).isEqual(quadtreeCoordinates(2, 3, 3)) ).toEqual(true); expect( quadtreeCoordinates(1, 1, 1).getOffsetCoordinates(quadtreeCoordinates(2, 2, 2)).isEqual(quadtreeCoordinates(1, 0, 0)) ).toEqual(true); }); it("getOffsetCoordinates works as expected for octree", function() { expect( octreeCoordinates(0, 0, 0, 0).getOffsetCoordinates(octreeCoordinates(0, 0, 0, 0)).isEqual(octreeCoordinates(0, 0, 0, 0)) ).toEqual(true); expect( octreeCoordinates(0, 0, 0, 0).getOffsetCoordinates(octreeCoordinates(1, 1, 1, 1)).isEqual(octreeCoordinates(1, 1, 1, 1)) ).toEqual(true); expect( octreeCoordinates(0, 0, 0, 0).getOffsetCoordinates(octreeCoordinates(2, 3, 3, 3)).isEqual(octreeCoordinates(2, 3, 3, 3)) ).toEqual(true); expect( octreeCoordinates(1, 1, 1, 1).getOffsetCoordinates(octreeCoordinates(2, 2, 2, 2)).isEqual(octreeCoordinates(1, 0, 0, 0)) ).toEqual(true); }); it("getChildCoordinates throws for invalid inputs", function() { const coordinates = quadtreeCoordinates(1, 0, 0); expect(function() { return coordinates.getChildCoordinates(void 0); }).toThrowDeveloperError(); expect(function() { return coordinates.getChildCoordinates(-1); }).toThrowDeveloperError(); expect(function() { return coordinates.getChildCoordinates(10); }).toThrowDeveloperError(); }); it("getChildCoordinates works as expected for quadree", function() { const coordinates = quadtreeCoordinates(1, 0, 0); expect( coordinates.getChildCoordinates(0).isEqual(quadtreeCoordinates(2, 0, 0)) ).toEqual(true); expect( coordinates.getChildCoordinates(1).isEqual(quadtreeCoordinates(2, 1, 0)) ).toEqual(true); expect( coordinates.getChildCoordinates(2).isEqual(quadtreeCoordinates(2, 0, 1)) ).toEqual(true); expect( coordinates.getChildCoordinates(3).isEqual(quadtreeCoordinates(2, 1, 1)) ).toEqual(true); }); it("getChildCoordinates works as expected for octree", function() { const coordinates = octreeCoordinates(1, 0, 1, 1); expect( coordinates.getChildCoordinates(0).isEqual(octreeCoordinates(2, 0, 2, 2)) ).toEqual(true); expect( coordinates.getChildCoordinates(1).isEqual(octreeCoordinates(2, 1, 2, 2)) ).toEqual(true); expect( coordinates.getChildCoordinates(2).isEqual(octreeCoordinates(2, 0, 3, 2)) ).toEqual(true); expect( coordinates.getChildCoordinates(3).isEqual(octreeCoordinates(2, 1, 3, 2)) ).toEqual(true); expect( coordinates.getChildCoordinates(4).isEqual(octreeCoordinates(2, 0, 2, 3)) ).toEqual(true); expect( coordinates.getChildCoordinates(5).isEqual(octreeCoordinates(2, 1, 2, 3)) ).toEqual(true); expect( coordinates.getChildCoordinates(6).isEqual(octreeCoordinates(2, 0, 3, 3)) ).toEqual(true); expect( coordinates.getChildCoordinates(7).isEqual(octreeCoordinates(2, 1, 3, 3)) ).toEqual(true); }); it("getSubtreeCoordinates works as expected for quadtree", function() { expect( quadtreeCoordinates(0, 0, 0).getSubtreeCoordinates().isEqual(quadtreeCoordinates(0, 0, 0)) ).toEqual(true); expect( quadtreeCoordinates(1, 1, 1).getSubtreeCoordinates().isEqual(quadtreeCoordinates(0, 0, 0)) ).toEqual(true); expect( quadtreeCoordinates(2, 3, 3).getSubtreeCoordinates().isEqual(quadtreeCoordinates(2, 3, 3)) ).toEqual(true); expect( quadtreeCoordinates(3, 7, 7).getSubtreeCoordinates().isEqual(quadtreeCoordinates(2, 3, 3)) ).toEqual(true); }); it("getSubtreeCoordinates works as expected for octree", function() { expect( octreeCoordinates(0, 0, 0, 0).getSubtreeCoordinates().isEqual(octreeCoordinates(0, 0, 0, 0)) ).toEqual(true); expect( octreeCoordinates(1, 1, 1, 1).getSubtreeCoordinates().isEqual(octreeCoordinates(0, 0, 0, 0)) ).toEqual(true); expect( octreeCoordinates(2, 3, 3, 3).getSubtreeCoordinates().isEqual(octreeCoordinates(2, 3, 3, 3)) ).toEqual(true); expect( octreeCoordinates(3, 7, 7, 7).getSubtreeCoordinates().isEqual(octreeCoordinates(2, 3, 3, 3)) ).toEqual(true); }); it("getParentSubtreeCoordinates throws for invalid inputs", function() { expect(function() { return quadtreeCoordinates(0, 0, 0).getParentSubtreeCoordinates(); }).toThrowDeveloperError(); expect(function() { return quadtreeCoordinates(1, 1, 1).getParentSubtreeCoordinates(); }).toThrowDeveloperError(); }); it("getParentSubtreeCoordinates works as expected for quadtree", function() { expect( quadtreeCoordinates(2, 0, 0).getParentSubtreeCoordinates().isEqual(quadtreeCoordinates(0, 0, 0)) ).toEqual(true); expect( quadtreeCoordinates(2, 3, 3).getParentSubtreeCoordinates().isEqual(quadtreeCoordinates(0, 0, 0)) ).toEqual(true); expect( quadtreeCoordinates(3, 7, 7).getParentSubtreeCoordinates().isEqual(quadtreeCoordinates(0, 0, 0)) ).toEqual(true); expect( quadtreeCoordinates(4, 0, 0).getParentSubtreeCoordinates().isEqual(quadtreeCoordinates(2, 0, 0)) ).toEqual(true); expect( quadtreeCoordinates(4, 15, 15).getParentSubtreeCoordinates().isEqual(quadtreeCoordinates(2, 3, 3)) ).toEqual(true); }); it("getParentSubtreeCoordinates works as expected for octree", function() { expect( octreeCoordinates(2, 0, 0, 0).getParentSubtreeCoordinates().isEqual(octreeCoordinates(0, 0, 0, 0)) ).toEqual(true); expect( octreeCoordinates(2, 3, 3, 3).getParentSubtreeCoordinates().isEqual(octreeCoordinates(0, 0, 0, 0)) ).toEqual(true); expect( octreeCoordinates(3, 7, 7, 7).getParentSubtreeCoordinates().isEqual(octreeCoordinates(0, 0, 0, 0)) ).toEqual(true); expect( octreeCoordinates(4, 0, 0, 0).getParentSubtreeCoordinates().isEqual(octreeCoordinates(2, 0, 0, 0)) ).toEqual(true); expect( octreeCoordinates(4, 15, 15, 15).getParentSubtreeCoordinates().isEqual(octreeCoordinates(2, 3, 3, 3)) ).toEqual(true); }); it("isAncestor throws with invalid inputs", function() { expect(function() { quadtreeCoordinates(0, 0, 0).isAncestor(void 0); }).toThrowDeveloperError(); expect(function() { return quadtreeCoordinates(0, 0, 0).isAncestor( octreeCoordinates(0, 0, 0, 0) ); }).toThrowDeveloperError(); expect(function() { const subtreeLevelsA = 2; const subtreeLevelsB = 3; return quadtreeCoordinates(0, 0, 0, subtreeLevelsA).isAncestor( quadtreeCoordinates(0, 0, 0, subtreeLevelsB) ); }).toThrowDeveloperError(); }); it("isAncestor works as expected for quadtree", function() { expect( quadtreeCoordinates(0, 0, 0).isAncestor(quadtreeCoordinates(0, 0, 0)) ).toEqual(false); expect( quadtreeCoordinates(0, 0, 0).isAncestor(quadtreeCoordinates(1, 1, 1)) ).toEqual(true); expect( quadtreeCoordinates(1, 1, 1).isAncestor(quadtreeCoordinates(0, 0, 0)) ).toEqual(false); expect( quadtreeCoordinates(0, 0, 0).isAncestor(quadtreeCoordinates(3, 7, 7)) ).toEqual(true); expect( quadtreeCoordinates(1, 0, 0).isAncestor(quadtreeCoordinates(2, 3, 3)) ).toEqual(false); }); it("isAncestor works as expected for octree", function() { expect( octreeCoordinates(0, 0, 0, 0).isAncestor(octreeCoordinates(0, 0, 0, 0)) ).toEqual(false); expect( octreeCoordinates(0, 0, 0, 0).isAncestor(octreeCoordinates(1, 1, 1, 1)) ).toEqual(true); expect( octreeCoordinates(1, 1, 1, 1).isAncestor(octreeCoordinates(0, 0, 0, 0)) ).toEqual(false); expect( octreeCoordinates(0, 0, 0, 0).isAncestor(octreeCoordinates(3, 7, 7, 7)) ).toEqual(true); expect( octreeCoordinates(1, 0, 0, 0).isAncestor(octreeCoordinates(2, 3, 3, 3)) ).toEqual(false); }); it("isEqual throws with invalid inputs", function() { expect(function() { quadtreeCoordinates(0, 0, 0).isEqual(void 0); }).toThrowDeveloperError(); }); it("isEqual works as expected for quadtree", function() { expect( octreeCoordinates(0, 0, 0, 0).isEqual(octreeCoordinates(0, 0, 0, 0)) ).toEqual(true); expect( octreeCoordinates(0, 0, 0, 0).isEqual(octreeCoordinates(1, 0, 0, 0)) ).toEqual(false); expect( octreeCoordinates(1, 0, 0, 0).isEqual(octreeCoordinates(1, 1, 0, 0)) ).toEqual(false); expect( octreeCoordinates(1, 0, 0, 0).isEqual(octreeCoordinates(1, 0, 1, 0)) ).toEqual(false); expect( octreeCoordinates(1, 0, 0, 0).isEqual(octreeCoordinates(1, 0, 0, 1)) ).toEqual(false); expect( quadtreeCoordinates(0, 0, 0).isEqual(octreeCoordinates(0, 0, 0, 0)) ).toEqual(false); const subtreeLevelsA = 2; const subtreeLevelsB = 3; expect( quadtreeCoordinates(0, 0, 0, subtreeLevelsA).isEqual( quadtreeCoordinates(0, 0, 0, subtreeLevelsB) ) ).toEqual(false); }); it("isImplicitTilesetRoot works as expected", function() { expect(quadtreeCoordinates(0, 0, 0).isImplicitTilesetRoot()).toEqual(true); expect(quadtreeCoordinates(1, 0, 0).isImplicitTilesetRoot()).toEqual(false); expect(quadtreeCoordinates(2, 0, 0).isImplicitTilesetRoot()).toEqual(false); }); it("isSubtreeRoot works as expected", function() { expect(quadtreeCoordinates(0, 0, 0).isSubtreeRoot()).toEqual(true); expect(quadtreeCoordinates(1, 0, 0).isSubtreeRoot()).toEqual(false); expect(quadtreeCoordinates(2, 0, 0).isSubtreeRoot()).toEqual(true); expect(quadtreeCoordinates(3, 0, 0).isSubtreeRoot()).toEqual(false); }); it("isBottomOfSubtree works as expected", function() { expect(quadtreeCoordinates(0, 0, 0).isBottomOfSubtree()).toEqual(false); expect(quadtreeCoordinates(1, 0, 0).isBottomOfSubtree()).toEqual(true); expect(quadtreeCoordinates(2, 0, 0).isBottomOfSubtree()).toEqual(false); expect(quadtreeCoordinates(3, 0, 0).isBottomOfSubtree()).toEqual(true); }); it("childIndex works as expected for quadtree", function() { expect(quadtreeCoordinates(4, 3, 2).childIndex).toEqual(1); }); it("childIndex works as expected for octree", function() { expect(octreeCoordinates(4, 3, 2, 1).childIndex).toEqual(5); }); it("mortonIndex works as expected for quadtree", function() { expect(quadtreeCoordinates(4, 5, 11).mortonIndex).toEqual(155); }); it("mortonIndex works as expected for octree", function() { expect(octreeCoordinates(6, 7, 15, 32).mortonIndex).toEqual(132315); }); it("fromMortonIndex works as expected for quadtree", function() { const subtreeLevels = 6; const coordinates = import__524.ImplicitTileCoordinates.fromMortonIndex( import__524.ImplicitSubdivisionScheme.QUADTREE, subtreeLevels, 3, 42 ); expect( coordinates.isEqual(quadtreeCoordinates(3, 0, 7, subtreeLevels)) ).toEqual(true); }); it("fromMortonIndex works as expected for octree", function() { const subtreeLevels = 6; const coordinates = import__524.ImplicitTileCoordinates.fromMortonIndex( import__524.ImplicitSubdivisionScheme.OCTREE, subtreeLevels, 2, 43 ); expect( coordinates.isEqual(octreeCoordinates(2, 3, 1, 2, subtreeLevels)) ).toEqual(true); }); it("tileIndex works as expected for quadtree", function() { expect(quadtreeCoordinates(4, 5, 11).tileIndex).toEqual(240); }); it("tileIndex works as expected for octree", function() { expect(octreeCoordinates(6, 7, 15, 32).tileIndex).toEqual(169764); }); it("fromTileIndex works as expected for quadtree", function() { const subtreeLevels = 6; const coordinates = import__524.ImplicitTileCoordinates.fromTileIndex( import__524.ImplicitSubdivisionScheme.QUADTREE, subtreeLevels, 63 ); expect( coordinates.isEqual(quadtreeCoordinates(3, 0, 7, subtreeLevels)) ).toEqual(true); }); it("fromTileIndex works as expected for octree", function() { const subtreeLevels = 6; const coordinates = import__524.ImplicitTileCoordinates.fromTileIndex( import__524.ImplicitSubdivisionScheme.OCTREE, subtreeLevels, 52 ); expect( coordinates.isEqual(octreeCoordinates(2, 3, 1, 2, subtreeLevels)) ).toEqual(true); }); it("getTemplateValues works as expected for quadtree", function() { const subtreeLevels = 6; expect( quadtreeCoordinates(4, 3, 2, subtreeLevels).getTemplateValues() ).toEqual({ level: 4, x: 3, y: 2 }); }); it("getTemplateValues works as expected for octree", function() { const subtreeLevels = 6; expect( octreeCoordinates(4, 3, 2, 1, subtreeLevels).getTemplateValues() ).toEqual({ level: 4, x: 3, y: 2, z: 1 }); }); }); // packages/engine/Specs/Scene/ImplicitTilesetSpec.js var import__525 = __toESM(require_Cesium(), 1); describe("Scene/ImplicitTileset", function() { const contentUriPattern = "https://example.com/{level}/{x}/{y}.b3dm"; const subtreeUriPattern = "https://example.com/{level}/{x}/{y}.subtree"; const implicitTilingJson = { subdivisionScheme: "QUADTREE", subtreeLevels: 3, availableLevels: 5, subtrees: { uri: subtreeUriPattern } }; const implicitTilingJsonLegacy = { subdivisionScheme: "QUADTREE", subtreeLevels: 3, maximumLevel: 4, subtrees: { uri: subtreeUriPattern } }; const implicitTileJson = { geometricError: 500, refine: "ADD", boundingVolume: { region: [0, 0, Math.PI / 24, Math.PI / 24, 0, 1e3] }, content: { uri: contentUriPattern, extras: { author: "Cesium" } }, implicitTiling: implicitTilingJson, extras: { creationDate: "2021-02-22" } }; const implicitTileLegacyJson = { geometricError: 500, refine: "ADD", boundingVolume: { region: [0, 0, Math.PI / 24, Math.PI / 24, 0, 1e3] }, content: { uri: contentUriPattern, extras: { author: "Cesium" } }, extensions: { "3DTILES_implicit_tiling": implicitTilingJsonLegacy }, extras: { creationDate: "2021-02-22" } }; const baseResource = new import__525.Resource("https://example.com/tileset.json"); const contentUriTemplate = new import__525.Resource(contentUriPattern); const subtreeUriTemplate = new import__525.Resource(subtreeUriPattern); it("gathers information from both tile JSON and extension", function() { let metadataSchema; const implicitTileset = new import__525.ImplicitTileset( baseResource, implicitTileJson, metadataSchema ); expect(implicitTileset.metadataSchema).toBeUndefined(); expect(implicitTileset.subtreeLevels).toEqual(3); expect(implicitTileset.availableLevels).toEqual(5); expect(implicitTileset.subdivisionScheme).toEqual( import__525.ImplicitSubdivisionScheme.QUADTREE ); expect(implicitTileset.boundingVolume).toEqual( implicitTileJson.boundingVolume ); expect(implicitTileset.refine).toEqual(implicitTileJson.refine); expect(implicitTileset.geometricError).toEqual(500); expect(implicitTileset.contentUriTemplates).toEqual([contentUriTemplate]); expect(implicitTileset.subtreeUriTemplate).toEqual(subtreeUriTemplate); }); it("stores a template of the tile JSON structure", function() { let metadataSchema; const implicitTileset = new import__525.ImplicitTileset( baseResource, implicitTileJson, metadataSchema ); const deep = true; const expected = (0, import__525.clone)(implicitTileJson, deep); delete expected.content; delete expected.implicitTiling; expect(implicitTileset.tileHeader).toEqual(expected); }); it("tileHeader stores additional extensions", function() { const deep = true; const withExtensions = (0, import__525.clone)(implicitTileJson, deep); withExtensions.extensions = {}; withExtensions.extensions["3DTILES_extension"] = {}; let metadataSchema; const implicitTileset = new import__525.ImplicitTileset( baseResource, withExtensions, metadataSchema ); const expected = (0, import__525.clone)(withExtensions, deep); delete expected.content; delete expected.implicitTiling; expect(implicitTileset.tileHeader).toEqual(expected); }); it("stores a template of the tile content structure", function() { let metadataSchema; const implicitTileset = new import__525.ImplicitTileset( baseResource, implicitTileJson, metadataSchema ); expect(implicitTileset.contentHeaders[0]).toEqual(implicitTileJson.content); }); it("allows undefined content URI", function() { const noContentJson = (0, import__525.clone)(implicitTileJson); delete noContentJson.content; let metadataSchema; const implicitTileset = new import__525.ImplicitTileset( baseResource, noContentJson, metadataSchema ); expect(implicitTileset.contentUriTemplates).toEqual([]); }); it("accepts tilesets with 3DTILES_bounding_volume_S2", function() { const tileJson = (0, import__525.clone)(implicitTileLegacyJson, true); tileJson.boundingVolume = { extensions: { "3DTILES_bounding_volume_S2": { token: "1", minimumHeight: 0, maximumHeight: 100 } } }; const tileJsonS2 = tileJson.boundingVolume.extensions["3DTILES_bounding_volume_S2"]; let metadataSchema; const implicitTileset = new import__525.ImplicitTileset( baseResource, tileJson, metadataSchema ); const implicitTilesetS2 = implicitTileset.boundingVolume.extensions["3DTILES_bounding_volume_S2"]; expect(implicitTilesetS2.token).toEqual(tileJsonS2.token); expect(implicitTilesetS2.minimumHeight).toEqual(tileJsonS2.minimumHeight); expect(implicitTilesetS2.maximumHeight).toEqual(tileJsonS2.maximumHeight); }); it("rejects bounding spheres", function() { const sphereJson = { boundingVolume: { sphere: [0, 0, 0, 100] } }; const tileJson = (0, import__525.combine)(sphereJson, implicitTileJson); let metadataSchema; expect(function() { return new import__525.ImplicitTileset(baseResource, tileJson, metadataSchema); }).toThrowError(import__525.RuntimeError); }); describe("3DTILES_implicit_tiling", function() { it("gathers information from both tile JSON and extension (legacy)", function() { let metadataSchema; const implicitTileset = new import__525.ImplicitTileset( baseResource, implicitTileLegacyJson, metadataSchema ); expect(implicitTileset.metadataSchema).toBeUndefined(); expect(implicitTileset.subtreeLevels).toEqual(3); expect(implicitTileset.availableLevels).toEqual(5); expect(implicitTileset.subdivisionScheme).toEqual( import__525.ImplicitSubdivisionScheme.QUADTREE ); expect(implicitTileset.boundingVolume).toEqual( implicitTileJson.boundingVolume ); expect(implicitTileset.refine).toEqual(implicitTileJson.refine); expect(implicitTileset.geometricError).toEqual(500); expect(implicitTileset.contentUriTemplates).toEqual([contentUriTemplate]); expect(implicitTileset.subtreeUriTemplate).toEqual(subtreeUriTemplate); }); it("supports maximumLevel parameter in tile JSON (legacy)", function() { let metadataSchema; const implicitTileset = new import__525.ImplicitTileset( baseResource, implicitTileLegacyJson, metadataSchema ); expect(implicitTileset.availableLevels).toEqual(5); }); it("stores a template of the tile JSON structure (legacy)", function() { let metadataSchema; const implicitTileset = new import__525.ImplicitTileset( baseResource, implicitTileLegacyJson, metadataSchema ); const deep = true; const expected = (0, import__525.clone)(implicitTileLegacyJson, deep); delete expected.content; delete expected.extensions; expect(implicitTileset.tileHeader).toEqual(expected); }); it("tileHeader stores additional extensions (legacy)", function() { const deep = true; const withExtensions = (0, import__525.clone)(implicitTileLegacyJson, deep); withExtensions.extensions["3DTILES_extension"] = {}; let metadataSchema; const implicitTileset = new import__525.ImplicitTileset( baseResource, withExtensions, metadataSchema ); const expected = (0, import__525.clone)(withExtensions, deep); delete expected.content; delete expected.extensions["3DTILES_implicit_tiling"]; expect(implicitTileset.tileHeader).toEqual(expected); }); it("stores a template of the tile content structure (legacy)", function() { let metadataSchema; const implicitTileset = new import__525.ImplicitTileset( baseResource, implicitTileLegacyJson, metadataSchema ); expect(implicitTileset.contentHeaders[0]).toEqual( implicitTileJson.content ); }); it("allows undefined content URI (legacy)", function() { const noContentJson = (0, import__525.clone)(implicitTileLegacyJson); delete noContentJson.content; let metadataSchema; const implicitTileset = new import__525.ImplicitTileset( baseResource, noContentJson, metadataSchema ); expect(implicitTileset.contentUriTemplates).toEqual([]); }); it("rejects bounding spheres (legacy)", function() { const sphereJson = { boundingVolume: { sphere: [0, 0, 0, 100] } }; const tileJson = (0, import__525.combine)(sphereJson, implicitTileLegacyJson); let metadataSchema; expect(function() { return new import__525.ImplicitTileset(baseResource, tileJson, metadataSchema); }).toThrowError(import__525.RuntimeError); }); }); const b3dmPattern = "https://example.com/{level}/{x}/{y}.b3dm"; const pntsPattern = "https://example.com/{level}/{x}/{y}.pnts"; const gltfPattern = "https://example.com/{level}/{x}/{y}.gltf"; describe("multiple contents", function() { const multipleContentTile = { geometricError: 500, refine: "ADD", boundingVolume: { region: [0, 0, Math.PI / 24, Math.PI / 24, 0, 1e3] }, implicitTiling: { subdivisionScheme: "QUADTREE", subtreeLevels: 3, availableLevels: 5, subtrees: { uri: subtreeUriPattern } }, contents: [ { uri: b3dmPattern }, { uri: pntsPattern }, { uri: gltfPattern } ] }; it("gathers content URIs from contents array", function() { let metadataSchema; const implicitTileset = new import__525.ImplicitTileset( baseResource, multipleContentTile, metadataSchema ); expect(implicitTileset.contentUriTemplates).toEqual([ new import__525.Resource({ url: b3dmPattern }), new import__525.Resource({ url: pntsPattern }), new import__525.Resource({ url: gltfPattern }) ]); }); it("stores content JSON for every tile", function() { const deep = true; const withProperties = (0, import__525.clone)(multipleContentTile, deep); const extension = { "3DTILES_extension": {} }; const boundingBox = { box: [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1] }; const contents = withProperties.contents; let i; for (i = 0; i < contents.length; i++) { contents[i].boundingVolume = boundingBox; contents[i].extensions = extension; } let metadataSchema; const implicitTileset = new import__525.ImplicitTileset( baseResource, withProperties, metadataSchema ); for (i = 0; i < implicitTileset.contentHeaders.length; i++) { expect(implicitTileset.contentHeaders[i]).toEqual(contents[i]); } }); it("template tileHeader does not store multiple contents extension", function() { let metadataSchema; const implicitTileset = new import__525.ImplicitTileset( baseResource, multipleContentTile, metadataSchema ); expect(implicitTileset.tileHeader.extensions).not.toBeDefined(); }); }); describe("3DTILES_multiple_contents", function() { const multipleContentLegacyTile = { geometricError: 500, refine: "ADD", boundingVolume: { region: [0, 0, Math.PI / 24, Math.PI / 24, 0, 1e3] }, extensions: { "3DTILES_implicit_tiling": { subdivisionScheme: "QUADTREE", subtreeLevels: 3, availableLevels: 5, subtrees: { uri: subtreeUriPattern } }, "3DTILES_multiple_contents": { contents: [ { uri: b3dmPattern }, { uri: pntsPattern }, { uri: gltfPattern } ] } } }; it("gathers content URIs from multiple contents extension (legacy)", function() { let metadataSchema; const implicitTileset = new import__525.ImplicitTileset( baseResource, multipleContentLegacyTile, metadataSchema ); expect(implicitTileset.contentUriTemplates).toEqual([ new import__525.Resource({ url: b3dmPattern }), new import__525.Resource({ url: pntsPattern }), new import__525.Resource({ url: gltfPattern }) ]); }); it("stores content JSON for every tile (legacy)", function() { const deep = true; const withProperties = (0, import__525.clone)(multipleContentLegacyTile, deep); const extension = { "3DTILES_extension": {} }; const boundingBox = { box: [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1] }; const contents = withProperties.extensions["3DTILES_multiple_contents"].contents; let i; for (i = 0; i < contents.length; i++) { contents[i].boundingVolume = boundingBox; contents[i].extensions = extension; } let metadataSchema; const implicitTileset = new import__525.ImplicitTileset( baseResource, withProperties, metadataSchema ); for (i = 0; i < implicitTileset.contentHeaders.length; i++) { expect(implicitTileset.contentHeaders[i]).toEqual(contents[i]); } }); }); describe("metadata", function() { it("stores metadataSchema", function() { const schema = { classes: { tile: { properties: { buildingCount: { type: "SCALAR", componentType: "UINT16" } } } } }; const metadataSchema = import__525.MetadataSchema.fromJson(schema); const implicitTileset = new import__525.ImplicitTileset( baseResource, implicitTileJson, metadataSchema ); expect(implicitTileset.metadataSchema).toBeDefined(); expect(implicitTileset.metadataSchema.classes.tile).toBeDefined(); }); }); }); // packages/engine/Specs/Scene/InstanceAttributeSemanticSpec.js var import__526 = __toESM(require_Cesium(), 1); describe("Scene/InstanceAttributeSemantic", function() { it("fromGltfSemantic", function() { const gltfSemantics = [ "TRANSLATION", "ROTATION", "SCALE", "_FEATURE_ID_0", "_FEATURE_ID_1", "_OTHER" ]; const expectedSemantics = [ import__526.InstanceAttributeSemantic.TRANSLATION, import__526.InstanceAttributeSemantic.ROTATION, import__526.InstanceAttributeSemantic.SCALE, import__526.InstanceAttributeSemantic.FEATURE_ID, import__526.InstanceAttributeSemantic.FEATURE_ID, void 0 ]; const semanticsLength = gltfSemantics.length; for (let i = 0; i < semanticsLength; ++i) { expect( import__526.InstanceAttributeSemantic.fromGltfSemantic( gltfSemantics[i], expectedSemantics[i] ) ).toBe(expectedSemantics[i]); } }); it("fromGltfSemantic throws if gltfSemantic is undefined", function() { expect(function() { import__526.InstanceAttributeSemantic.fromGltfSemantic(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/IonImageryProviderSpec.js var import__527 = __toESM(require_Cesium(), 1); describe("Scene/IonImageryProvider", function() { async function createTestProviderAsync(endpointData) { endpointData = (0, import__527.defaultValue)(endpointData, { type: "IMAGERY", url: "http://test.invalid/layer", accessToken: "not_really_a_refresh_token", attributions: [] }); const assetId = 12335; const options = {}; const endpointResource = import__527.IonResource._createEndpointResource( assetId, options ); spyOn(import__527.IonResource, "_createEndpointResource").and.returnValue( endpointResource ); spyOn(endpointResource, "fetchJson").and.returnValue( Promise.resolve(endpointData) ); const provider = await import__527.IonImageryProvider.fromAssetId(assetId, options); expect(import__527.IonResource._createEndpointResource).toHaveBeenCalledWith( assetId, options ); return provider; } beforeEach(function() { import__527.RequestScheduler.clearForSpecs(); import__527.IonImageryProvider._endpointCache = {}; }); it("conforms to ImageryProvider interface", function() { expect(import__527.IonImageryProvider).toConformToInterface(import__527.ImageryProvider); }); it("fromAssetId throws without assetId", async function() { await expectAsync( import__527.IonImageryProvider.fromAssetId() ).toBeRejectedWithDeveloperError(); }); it("fromAssetId throws with non-imagery asset", async function() { await expectAsync( createTestProviderAsync({ type: "3DTILES", url: "http://test.invalid/layer", accessToken: "not_really_a_refresh_token", attributions: [] }) ).toBeRejectedWithError( import__527.RuntimeError, "Cesium ion asset 12335 is not an imagery asset." ); }); it("fromAssetId rejects with unknown external asset type", async function() { await expectAsync( createTestProviderAsync({ type: "IMAGERY", externalType: "TUBELCANE", options: { url: "http://test.invalid/layer" }, attributions: [] }) ).toBeRejectedWithError( import__527.RuntimeError, "Unrecognized Cesium ion imagery type: TUBELCANE" ); }); it("fromAssetId resolves to created provider", async function() { const provider = await createTestProviderAsync(); expect(provider).toBeInstanceOf(import__527.IonImageryProvider); expect(provider.errorEvent).toBeDefined(); expect(provider._imageryProvider).toBeInstanceOf( import__527.UrlTemplateImageryProvider ); }); it("Uses previously fetched endpoint cache", async function() { const endpointData = { type: "IMAGERY", url: "http://test.invalid/layer", accessToken: "not_really_a_refresh_token", attributions: [] }; const assetId = 12335; const options = { accessToken: "token", server: "http://test.invalid" }; const endpointResource = import__527.IonResource._createEndpointResource( assetId, options ); spyOn(import__527.IonResource, "_createEndpointResource").and.returnValue( endpointResource ); spyOn(endpointResource, "fetchJson").and.returnValue( Promise.resolve(endpointData) ); expect(endpointResource.fetchJson.calls.count()).toBe(0); await import__527.IonImageryProvider.fromAssetId(assetId, options); expect(endpointResource.fetchJson.calls.count()).toBe(1); const options2 = { accessToken: "token", server: "http://test.invalid" }; await import__527.IonImageryProvider.fromAssetId(assetId, options2); expect(endpointResource.fetchJson.calls.count()).toBe(1); }); it("propagates called to underlying imagery provider resolves when ready", async function() { const provider = await createTestProviderAsync(); const internalProvider = provider._imageryProvider; expect(provider.rectangle).toBe(internalProvider.rectangle); expect(provider.tileWidth).toBe(internalProvider.tileWidth); expect(provider.tileHeight).toBe(internalProvider.tileHeight); expect(provider.maximumLevel).toBe(internalProvider.maximumLevel); expect(provider.minimumLevel).toBe(internalProvider.minimumLevel); expect(provider.tilingScheme).toBe(internalProvider.tilingScheme); expect(provider.tileDiscardPolicy).toBe(internalProvider.tileDiscardPolicy); expect(provider.credit).toBe(internalProvider.credit); expect(provider.hasAlphaChannel).toBe(internalProvider.hasAlphaChannel); const image = new Image(); const request = {}; spyOn(internalProvider, "requestImage").and.returnValue( Promise.resolve(image) ); let result = await provider.requestImage(1, 2, 3, request); expect(internalProvider.requestImage).toHaveBeenCalledWith( 1, 2, 3, request ); expect(result).toBe(image); const info = {}; spyOn(internalProvider, "pickFeatures").and.returnValue( Promise.resolve(info) ); result = await provider.pickFeatures(1, 2, 3, 4, 5); expect(internalProvider.pickFeatures).toHaveBeenCalledWith(1, 2, 3, 4, 5); expect(result).toBe(info); const innerCredit = new import__527.Credit("Data provided"); spyOn(internalProvider, "getTileCredits").and.returnValue([innerCredit]); const credits = provider.getTileCredits(1, 2, 3); expect(internalProvider.getTileCredits).toHaveBeenCalledWith(1, 2, 3); expect(credits).toContain(innerCredit); }); it("handles server-sent credits", async function() { const serverCredit = { html: 'Text', collapsible: false }; const provider = await createTestProviderAsync({ type: "IMAGERY", url: "http://test.invalid/layer", accessToken: "not_really_a_refresh_token", attributions: [serverCredit] }); const credits = provider.getTileCredits(0, 0, 0); const credit = credits[0]; expect(credit).toBeInstanceOf(import__527.Credit); expect(credit.html).toEqual(serverCredit.html); expect(credit.showOnScreen).toEqual(!serverCredit.collapsible); }); async function testExternalImagery(type, options, ImageryClass) { const provider = await createTestProviderAsync({ type: "IMAGERY", externalType: type, options, attributions: [] }); expect(provider._imageryProvider).toBeInstanceOf(ImageryClass); } it("createImageryProvider works with ARCGIS_MAPSERVER", function() { spyOn(import__527.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { deferred.resolve( JSON.stringify({ imageUrl: "", imageUrlSubdomains: [], zoomMax: 0 }) ); }); return testExternalImagery( "ARCGIS_MAPSERVER", { url: "http://test.invalid" }, import__527.ArcGisMapServerImageryProvider ); }); it("createImageryProvider works with BING", function() { spyOn(import__527.Resource._Implementations, "loadAndExecuteScript").and.callFake( function(url, name, deffered) { deffered.resolve({ resourceSets: [ { resources: [{ imageUrl: "", imageUrlSubdomains: [], zoomMax: 0 }] } ] }); } ); return testExternalImagery( "BING", { url: "http://test.invalid", key: "" }, import__527.BingMapsImageryProvider ); }); it("createImageryProvider works with GOOGLE_EARTH", function() { spyOn(import__527.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { deferred.resolve(JSON.stringify({ layers: [{ id: 0, version: "" }] })); }); return testExternalImagery( "GOOGLE_EARTH", { url: "http://test.invalid", channel: 0 }, import__527.GoogleEarthEnterpriseMapsProvider ); }); it("createImageryProvider works with MAPBOX", function() { return testExternalImagery( "MAPBOX", { accessToken: "test-token", url: "http://test.invalid", mapId: 1 }, import__527.MapboxImageryProvider ); }); it("createImageryProvider works with SINGLE_TILE", function() { spyOn(import__527.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { deferred.resolve({ height: 16, width: 16 }); }); return testExternalImagery( "SINGLE_TILE", { url: "http://test.invalid" }, import__527.SingleTileImageryProvider ); }); it("createImageryProvider works with TMS", function() { return testExternalImagery( "TMS", { url: "http://test.invalid" }, import__527.UrlTemplateImageryProvider ); }); it("createImageryProvider works with URL_TEMPLATE", function() { return testExternalImagery( "URL_TEMPLATE", { url: "http://test.invalid" }, import__527.UrlTemplateImageryProvider ); }); it("createImageryProvider works with WMS", function() { return testExternalImagery( "WMS", { url: "http://test.invalid", layers: [] }, import__527.WebMapServiceImageryProvider ); }); it("createImageryProvider works with WMTS", function() { return testExternalImagery( "WMTS", { url: "http://test.invalid", layer: "", style: "", tileMatrixSetID: 1 }, import__527.WebMapTileServiceImageryProvider ); }); }); // packages/engine/Specs/Scene/JobSchedulerSpec.js var import__528 = __toESM(require_Cesium(), 1); describe("Scene/JobScheduler", function() { let originalGetTimestamp; beforeAll(function() { originalGetTimestamp = import__528.JobScheduler.getTimestamp; let time2 = 0; import__528.JobScheduler.getTimestamp = function() { return time2++; }; }); afterAll(function() { import__528.JobScheduler.getTimestamp = originalGetTimestamp; }); const MockJob = function() { this.executed = false; }; MockJob.prototype.execute = function() { this.executed = true; }; it("constructs with defaults", function() { const js = new import__528.JobScheduler(); expect(js.totalBudget).toEqual(50); const budgets = js._budgets; expect(budgets.length).toEqual(import__528.JobType.NUMBER_OF_JOB_TYPES); expect(budgets[import__528.JobType.TEXTURE].total).toEqual(10); expect(budgets[import__528.JobType.PROGRAM].total).toEqual(10); expect(budgets[import__528.JobType.BUFFER].total).toEqual(30); }); it("executes a job", function() { const js = new import__528.JobScheduler([ 2, // JobType.TEXTURE 0, // JobType.PROGRAM 0 ]); const job = new MockJob(); const executed = js.execute(job, import__528.JobType.TEXTURE); expect(executed).toEqual(true); expect(job.executed).toEqual(true); expect(js._totalUsedThisFrame).toEqual(1); expect(js._budgets[import__528.JobType.TEXTURE].total).toEqual(2); expect(js._budgets[import__528.JobType.TEXTURE].usedThisFrame).toEqual(1); }); it("disableThisFrame does not execute a job", function() { const js = new import__528.JobScheduler([2, 0, 0]); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(true); js.disableThisFrame(); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(false); }); it("executes different job types", function() { const js = new import__528.JobScheduler([1, 1, 1]); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.PROGRAM)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.BUFFER)).toEqual(true); expect(js._totalUsedThisFrame).toEqual(3); const budgets = js._budgets; expect(budgets[import__528.JobType.TEXTURE].usedThisFrame).toEqual(1); expect(budgets[import__528.JobType.PROGRAM].usedThisFrame).toEqual(1); expect(budgets[import__528.JobType.BUFFER].usedThisFrame).toEqual(1); }); it("executes a second job", function() { const js = new import__528.JobScheduler([2, 0, 0]); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(true); expect(js._totalUsedThisFrame).toEqual(2); expect(js._budgets[import__528.JobType.TEXTURE].usedThisFrame).toEqual(2); }); it("does not execute second job (exceeds total time)", function() { const js = new import__528.JobScheduler([1, 0, 0]); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(false); expect(js._budgets[import__528.JobType.TEXTURE].starvedThisFrame).toEqual(true); }); it("executes a second job (TEXTURE steals PROGRAM budget)", function() { const js = new import__528.JobScheduler([1, 1, 0]); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(true); expect(js._totalUsedThisFrame).toEqual(2); const budgets = js._budgets; expect(budgets[import__528.JobType.TEXTURE].usedThisFrame).toEqual(1); expect(budgets[import__528.JobType.TEXTURE].starvedThisFrame).toEqual(true); expect(budgets[import__528.JobType.PROGRAM].usedThisFrame).toEqual(0); expect(budgets[import__528.JobType.PROGRAM].stolenFromMeThisFrame).toEqual(1); expect(budgets[import__528.JobType.PROGRAM].starvedThisFrame).toEqual(false); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(false); expect(js.execute(new MockJob(), import__528.JobType.PROGRAM)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.PROGRAM)).toEqual(false); expect(budgets[import__528.JobType.PROGRAM].starvedThisFrame).toEqual(true); }); it("does not steal in the same frame", function() { const js = new import__528.JobScheduler([1, 1, 1]); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.PROGRAM)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.BUFFER)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(false); expect(js.execute(new MockJob(), import__528.JobType.PROGRAM)).toEqual(false); expect(js.execute(new MockJob(), import__528.JobType.BUFFER)).toEqual(false); js.resetBudgets(); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(false); expect(js.execute(new MockJob(), import__528.JobType.PROGRAM)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.PROGRAM)).toEqual(false); expect(js.execute(new MockJob(), import__528.JobType.BUFFER)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.BUFFER)).toEqual(false); }); it("does not steal from starving job types over multiple frames", function() { const js = new import__528.JobScheduler([1, 1, 0]); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(false); js.resetBudgets(); expect(js.execute(new MockJob(), import__528.JobType.PROGRAM)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.PROGRAM)).toEqual(false); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(false); js.resetBudgets(); expect(js.execute(new MockJob(), import__528.JobType.PROGRAM)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.PROGRAM)).toEqual(false); js.resetBudgets(); expect(js.execute(new MockJob(), import__528.JobType.PROGRAM)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.PROGRAM)).toEqual(true); }); it("Allows progress on all job types once per frame", function() { const js = new import__528.JobScheduler([1, 1, 1]); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(false); expect(js.execute(new MockJob(), import__528.JobType.PROGRAM)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.PROGRAM)).toEqual(false); expect(js.execute(new MockJob(), import__528.JobType.BUFFER)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.BUFFER)).toEqual(false); }); it("Long job still allows progress on other job types once per frame", function() { const js = new import__528.JobScheduler([0.5, 0.2, 0.2]); expect(js.execute(new MockJob(), import__528.JobType.TEXTURE)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.PROGRAM)).toEqual(true); expect(js.execute(new MockJob(), import__528.JobType.BUFFER)).toEqual(true); }); it("constructor throws when budgets.length is not JobType.NUMBER_OF_JOB_TYPES", function() { expect(function() { return new import__528.JobScheduler([1]); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/JsonMetadataTableSpec.js var import__529 = __toESM(require_Cesium(), 1); describe("Scene/JsonMetadataTable", function() { const properties = { priority: [2, 1, 0], labels: ["Point Cloud", "Mesh", "Raster"], uri: ["tree.las", "building.gltf", "map.tif"], sizeInfo: [ { pointCount: 100 }, { vertices: 3e3, faces: 1e3 }, { width: 1024, height: 1024 } ], mixedValues: ["red", 3, false] }; const count = 3; let table; beforeEach(function() { table = new import__529.JsonMetadataTable({ count, properties }); }); it("constructor throws without count", function() { expect(function() { return new import__529.JsonMetadataTable({ count: void 0, properties }); }).toThrowDeveloperError(); }); it("constructor throws without properties", function() { expect(function() { return new import__529.JsonMetadataTable({ count, properties: void 0 }); }).toThrowDeveloperError(); }); it("constructor clones properties", function() { const oldValue = properties.sizeInfo[0]; const sizeInfo = { lengthBytes: 1024 }; table.setProperty(0, "sizeInfo", sizeInfo); expect(properties.sizeInfo[0]).toBe(oldValue); expect(table.getProperty(0, "sizeInfo")).toEqual(sizeInfo); }); it("hasProperty returns true if the table has this property", function() { expect(table.hasProperty("priority")).toBe(true); }); it("hasProperty returns false if the table does not have this property", function() { expect(table.hasProperty("price")).toBe(false); }); it("getPropertyIds returns a list of property Ids", function() { expect(table.getPropertyIds().sort()).toEqual([ "labels", "mixedValues", "priority", "sizeInfo", "uri" ]); }); it("getProperty returns undefined for unknown property Id", function() { expect(table.getProperty(0, "color")).not.toBeDefined(); }); it("getProperty throws without index", function() { expect(function() { return table.getProperty(void 0, "priority"); }).toThrowDeveloperError(); }); it("getProperty throws for out-of-bounds index", function() { expect(function() { return table.getProperty(5, "priority"); }).toThrowDeveloperError(); }); it("getProperty throws without propertyId", function() { expect(function() { return table.getProperty(5, void 0); }).toThrowDeveloperError(); }); it("getProperty returns the property value", function() { expect(table.getProperty(0, "priority")).toBe(2); expect(table.getProperty(1, "priority")).toBe(1); expect(table.getProperty(2, "priority")).toBe(0); }); it("getProperty returns copy of value", function() { const value1 = table.getProperty(1, "sizeInfo"); const value2 = table.getProperty(1, "sizeInfo"); expect(value1).toEqual(properties.sizeInfo[1]); expect(value1).toEqual(value2); expect(value2).not.toBe(value1); }); it("getProperty works with heterogeneous values", function() { expect(table.getProperty(0, "mixedValues")).toBe("red"); expect(table.getProperty(1, "mixedValues")).toBe(3); expect(table.getProperty(2, "mixedValues")).toBe(false); }); it("setProperty throws without index", function() { expect(function() { return table.setProperty(void 0, void 0); }).toThrowDeveloperError(); }); it("setProperty throws for out-of-bounds index", function() { expect(function() { return table.setProperty(5, "priority", 3); }).toThrowDeveloperError(); }); it("setProperty throws without propertyId", function() { expect(function() { return table.setProperty(5, void 0); }).toThrowDeveloperError(); }); it("setProperty creates a new property if it doesn't exist", function() { expect(table.getProperty(0, "color")).not.toBeDefined(); table.setProperty(0, "color", [255, 255, 255, 1]); expect(table.getProperty(0, "color")).toEqual([255, 255, 255, 1]); }); it("setProperty sets property value", function() { const sizeInfo = { lengthBytes: 1024 }; table.setProperty(0, "sizeInfo", sizeInfo); expect(table.getProperty(0, "sizeInfo")).toEqual(sizeInfo); }); it("setProperty copies value", function() { const sizeInfo = { lengthBytes: 1024 }; table.setProperty(1, "sizeInfo", sizeInfo); sizeInfo.offset = 8; expect(table.getProperty(1, "sizeInfo")).not.toEqual(sizeInfo); }); }); // packages/engine/Specs/Scene/KeyframeNodeSpec.js var import__530 = __toESM(require_Cesium(), 1); var dummySpatialNode = {}; describe("Scene/KeyframeNode", function() { it("constructs", function() { const keyframe = 13; const keyframeNode = new import__530.KeyframeNode(dummySpatialNode, keyframe); expect(keyframeNode.spatialNode).toBe(dummySpatialNode); expect(keyframeNode.keyframe).toBe(keyframe); expect(keyframeNode.state).toBe(import__530.KeyframeNode.LoadState.UNLOADED); expect(keyframeNode.metadata).toEqual([]); expect(keyframeNode.megatextureIndex).toBe(-1); expect(keyframeNode.priority).toBe(-Number.MAX_VALUE); expect(keyframeNode.highPriorityFrameNumber).toBe(-1); }); it("priorityComparator compares priorities", function() { const keyframe1 = 13; const keyframe2 = 7; const keyframeNode1 = new import__530.KeyframeNode(dummySpatialNode, keyframe1); const keyframeNode2 = new import__530.KeyframeNode(dummySpatialNode, keyframe2); keyframeNode1.priority = 1; keyframeNode2.priority = 2; const comparison = import__530.KeyframeNode.priorityComparator( keyframeNode1, keyframeNode2 ); expect(comparison).toBe(-1); }); it("searchComparator compares keyframe indices", function() { const keyframe1 = 13; const keyframe2 = 7; const keyframeNode1 = new import__530.KeyframeNode(dummySpatialNode, keyframe1); const keyframeNode2 = new import__530.KeyframeNode(dummySpatialNode, keyframe2); const comparison = import__530.KeyframeNode.searchComparator( keyframeNode1, keyframeNode2 ); expect(comparison).toBe(6); }); }); // packages/engine/Specs/Scene/LabelCollectionSpec.js var import__531 = __toESM(require_Cesium(), 1); var import__532 = __toESM(require_Cesium(), 1); describe( "Scene/LabelCollection", function() { let scene2; let camera; let labels; let labelsWithHeight; const solidBox = "\u25A0"; beforeAll(function() { scene2 = createScene_default(); camera = scene2.camera; }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { scene2.morphTo3D(0); camera.position = new import__531.Cartesian3(10, 0, 0); camera.direction = import__531.Cartesian3.negate(import__531.Cartesian3.UNIT_X, new import__531.Cartesian3()); camera.up = import__531.Cartesian3.clone(import__531.Cartesian3.UNIT_Z); labels = new import__531.LabelCollection(); scene2.primitives.add(labels); }); afterEach(function() { scene2.primitives.removeAll(); }); it("has default values when adding a label", function() { const label = labels.add(); expect(label.show).toEqual(true); expect(label.position).toEqual(import__531.Cartesian3.ZERO); expect(label.text).toEqual(""); expect(label.font).toEqual("30px sans-serif"); expect(label.fillColor).toEqual(import__531.Color.WHITE); expect(label.outlineColor).toEqual(import__531.Color.BLACK); expect(label.outlineWidth).toEqual(1); expect(label.showBackground).toEqual(false); expect(label.backgroundColor).toEqual( new import__531.Color(0.165, 0.165, 0.165, 0.8) ); expect(label.backgroundPadding).toEqual(new import__531.Cartesian2(7, 5)); expect(label.style).toEqual(import__531.LabelStyle.FILL); expect(label.pixelOffset).toEqual(import__531.Cartesian2.ZERO); expect(label.eyeOffset).toEqual(import__531.Cartesian3.ZERO); expect(label.heightReference).toEqual(import__531.HeightReference.NONE); expect(label.horizontalOrigin).toEqual(import__531.HorizontalOrigin.LEFT); expect(label.verticalOrigin).toEqual(import__531.VerticalOrigin.BASELINE); expect(label.scale).toEqual(1); expect(label.id).toBeUndefined(); expect(label.translucencyByDistance).toBeUndefined(); expect(label.pixelOffsetScaleByDistance).toBeUndefined(); expect(label.scaleByDistance).toBeUndefined(); expect(label.distanceDisplayCondition).toBeUndefined(); expect(label.disableDepthTestDistance).toBeUndefined(); }); it("can add a label with specified values", function() { const show = false; const position = new import__531.Cartesian3(1, 2, 3); const text = "abc"; const font = '24px "Open Sans"'; const fillColor = { red: 2, green: 3, blue: 4, alpha: 1 }; const outlineColor = { red: 3, green: 4, blue: 2, alpha: 1 }; const outlineWidth = 2; const style = import__531.LabelStyle.FILL_AND_OUTLINE; const pixelOffset = new import__531.Cartesian2(4, 5); const eyeOffset = new import__531.Cartesian3(6, 7, 8); const horizontalOrigin = import__531.HorizontalOrigin.LEFT; const verticalOrigin = import__531.VerticalOrigin.BOTTOM; const scale = 2; const showBackground = true; const backgroundColor = import__531.Color.BLUE; const backgroundPadding = new import__531.Cartesian2(11, 12); const translucency = new import__531.NearFarScalar(1e4, 1, 1e6, 0); const pixelOffsetScale = new import__531.NearFarScalar(1e4, 1, 1e6, 0); const scaleByDistance = new import__531.NearFarScalar(1e4, 1, 1e6, 0); const distanceDisplayCondition = new import__531.DistanceDisplayCondition( 10, 100 ); const disableDepthTestDistance = 10; const label = labels.add({ show, position, text, font, fillColor, outlineColor, outlineWidth, style, showBackground, backgroundColor, backgroundPadding, pixelOffset, eyeOffset, horizontalOrigin, verticalOrigin, scale, id: "id", translucencyByDistance: translucency, pixelOffsetScaleByDistance: pixelOffsetScale, scaleByDistance, distanceDisplayCondition, disableDepthTestDistance }); expect(label.show).toEqual(show); expect(label.position).toEqual(position); expect(label.text).toEqual(text); expect(label.font).toEqual(font); expect(label.fillColor).toEqual(fillColor); expect(label.outlineColor).toEqual(outlineColor); expect(label.outlineWidth).toEqual(outlineWidth); expect(label.style).toEqual(style); expect(label.showBackground).toEqual(showBackground); expect(label.backgroundColor).toEqual(backgroundColor); expect(label.backgroundPadding).toEqual(backgroundPadding); expect(label.pixelOffset).toEqual(pixelOffset); expect(label.eyeOffset).toEqual(eyeOffset); expect(label.horizontalOrigin).toEqual(horizontalOrigin); expect(label.verticalOrigin).toEqual(verticalOrigin); expect(label.scale).toEqual(scale); expect(label.id).toEqual("id"); expect(label.translucencyByDistance).toEqual(translucency); expect(label.pixelOffsetScaleByDistance).toEqual(pixelOffsetScale); expect(label.scaleByDistance).toEqual(scaleByDistance); expect(label.distanceDisplayCondition).toEqual(distanceDisplayCondition); expect(label.disableDepthTestDistance).toEqual(disableDepthTestDistance); }); it("can specify font using units other than pixels", function() { const label = labels.add({ font: '12pt "Open Sans"', text: "Hello there" }); return allLabelsReady().then(function() { scene2.renderForSpecs(); const dimensions = label._glyphs[0].dimensions; expect(dimensions.height).toBeGreaterThan(0); }); }); it("has zero labels when constructed", function() { expect(labels.length).toEqual(0); }); it("can add a label", function() { const label = labels.add(); expect(labels.length).toEqual(1); expect(labels.get(0)).toBe(label); }); it("can remove the first label", function() { const one = labels.add(); const two = labels.add(); expect(labels.contains(one)).toEqual(true); expect(labels.contains(two)).toEqual(true); expect(labels.remove(one)).toEqual(true); expect(labels.contains(one)).toEqual(false); expect(labels.contains(two)).toEqual(true); }); it("can remove the last label", function() { const one = labels.add(); const two = labels.add(); expect(labels.contains(one)).toEqual(true); expect(labels.contains(two)).toEqual(true); expect(labels.remove(two)).toEqual(true); expect(labels.contains(one)).toEqual(true); expect(labels.contains(two)).toEqual(false); }); it("returns false when removing undefined", function() { labels.add(); expect(labels.length).toEqual(1); expect(labels.remove(void 0)).toEqual(false); expect(labels.length).toEqual(1); }); it("returns false when removing a previously removed label", function() { const label = labels.add(); expect(labels.length).toEqual(1); expect(labels.remove(label)).toEqual(true); expect(labels.remove(label)).toEqual(false); expect(labels.length).toEqual(0); }); it("is not destroyed", function() { expect(labels.isDestroyed()).toEqual(false); }); it("can add and remove multiple labels", function() { const one = labels.add(); const two = labels.add(); const three = labels.add(); expect(labels.remove(one)).toEqual(true); expect(labels.remove(two)).toEqual(true); expect(one.isDestroyed()).toEqual(true); expect(two.isDestroyed()).toEqual(true); expect(three.isDestroyed()).toEqual(false); expect(labels.contains(one)).toEqual(false); expect(labels.contains(two)).toEqual(false); expect(labels.contains(three)).toEqual(true); expect(labels.length).toEqual(1); expect(labels.get(0)).toBe(three); const four = labels.add(); expect(labels.length).toEqual(2); expect(labels.get(0)).toBe(three); expect(labels.get(1)).toBe(four); expect(labels.contains(three)).toEqual(true); expect(labels.contains(four)).toEqual(true); }); it("can remove all labels", function() { labels.add({ position: new import__531.Cartesian3(1, 2, 3) }); labels.add({ position: new import__531.Cartesian3(4, 5, 6) }); expect(labels.length).toEqual(2); labels.removeAll(); expect(labels.length).toEqual(0); }); it("can check if it contains a label", function() { const label = labels.add(); expect(labels.contains(label)).toEqual(true); }); it("returns false when checking if it contains a label it does not contain", function() { const label = labels.add(); labels.remove(label); expect(labels.contains(label)).toEqual(false); }); it("does not contain undefined", function() { expect(labels.contains(void 0)).toEqual(false); }); it("does not contain random other objects", function() { expect(labels.contains({})).toEqual(false); expect(labels.contains(new import__531.Cartesian2())).toEqual(false); }); it("does not render when constructed", function() { expect(scene2).toRender([0, 0, 0, 255]); }); function allLabelsReady() { return pollToPromise_default(function() { scene2.renderForSpecs(); const backgroundBillboard = labels._backgroundBillboardCollection.get( 0 ); return (!(0, import__531.defined)(backgroundBillboard) || backgroundBillboard.ready) && labels._labelsToUpdate.length === 0; }); } it("can render after modifying and removing a label", function() { const labelOne = labels.add({ position: import__531.Cartesian3.ZERO, text: "x", horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); labels.add({ position: import__531.Cartesian3.ZERO, text: "o", horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady().then(function() { expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(10); }); labelOne.scale = 2; labels.remove(labelOne); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("can render a label", function() { labels.add({ position: import__531.Cartesian3.ZERO, text: "x", horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady().then(function() { expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(10); }); }); }); it("renders in multiple passes", function() { labels.add({ position: import__531.Cartesian3.ZERO, text: "x", horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); camera.position = new import__531.Cartesian3(2, 0, 0); return allLabelsReady().then(function() { const frameState2 = scene2.frameState; frameState2.commandList.length = 0; labels.blendOption = import__531.BlendOption.OPAQUE_AND_TRANSLUCENT; labels.update(frameState2); expect(frameState2.commandList.length).toEqual(2); frameState2.commandList.length = 0; labels.blendOption = import__531.BlendOption.OPAQUE; labels.update(frameState2); expect(frameState2.commandList.length).toEqual(1); frameState2.commandList.length = 0; labels.blendOption = import__531.BlendOption.TRANSLUCENT; labels.update(frameState2); expect(frameState2.commandList.length).toEqual(1); }); }); it("can render after adding a label", function() { labels.add({ position: import__531.Cartesian3.ZERO, text: solidBox, horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady().then(function() { expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(200); expect(rgba[1]).toBeGreaterThan(200); expect(rgba[2]).toBeGreaterThan(200); }); labels.add({ position: new import__531.Cartesian3(1, 0, 0), // Closer to camera text: solidBox, fillColor: { red: 1, green: 0, blue: 0, alpha: 1 }, horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady(); }).then(function() { expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(200); expect(rgba[1]).toBeLessThan(10); expect(rgba[2]).toBeLessThan(10); }); }); }); it("can render after removing a label", function() { const label = labels.add({ position: import__531.Cartesian3.ZERO, text: "x", horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady().then(function() { expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(10); }); labels.remove(label); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("can render after removing and adding a label", function() { const label = labels.add({ position: import__531.Cartesian3.ZERO, text: "x", horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady().then(function() { expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(10); }); labels.remove(label); labels.add({ position: import__531.Cartesian3.ZERO, text: "x", horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady(); }).then(function() { expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(10); }); }); }); it("can render after removing all labels", function() { labels.add({ position: import__531.Cartesian3.ZERO, text: "x", horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady().then(function() { expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(10); }); labels.removeAll(); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("can render after removing all labels and adding a label", function() { labels.add({ position: import__531.Cartesian3.ZERO, text: "x", horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady().then(function() { expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(10); }); labels.removeAll(); labels.add({ position: import__531.Cartesian3.ZERO, text: "x", horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady(); }).then(function() { expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(10); }); }); }); it("can render a label background", function() { const label = labels.add({ position: import__531.Cartesian3.ZERO, text: "_", horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER, showBackground: true, backgroundColor: import__531.Color.BLUE }); return allLabelsReady().then(function() { expect(scene2).toRender([0, 0, 255, 255]); labels.remove(label); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("does not render labels with show set to false", function() { const label = labels.add({ position: import__531.Cartesian3.ZERO, text: "x", horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady().then(function() { expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(10); }); label.show = false; expect(scene2).toRender([0, 0, 0, 255]); label.show = true; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(10); }); }); }); it("does not render label background with show set to false", function() { const label = labels.add({ position: import__531.Cartesian3.ZERO, text: "_", horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER, showBackground: true, backgroundColor: import__531.Color.BLUE }); return allLabelsReady().then(function() { expect(scene2).toRender([0, 0, 255, 255]); label.show = false; expect(scene2).toRender([0, 0, 0, 255]); label.show = true; expect(scene2).toRender([0, 0, 255, 255]); }); }); it("does not render labels that are behind the viewer", function() { const label = labels.add({ position: import__531.Cartesian3.ZERO, // in front of the camera text: "x", horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady().then(function() { expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(10); }); label.position = new import__531.Cartesian3(20, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); label.position = new import__531.Cartesian3(1, 0, 0); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(10); }); }); }); it("does not render labels with a scale of zero", function() { const label = labels.add({ position: import__531.Cartesian3.ZERO, text: "x", horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); label.scale = 0; return allLabelsReady().then(function() { expect(scene2).toRender([0, 0, 0, 255]); label.scale = 2; scene2.render(); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(10); }); }); }); it("renders label with translucencyByDistance", function() { labels.add({ position: import__531.Cartesian3.ZERO, text: "x", horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER, translucencyByDistance: new import__531.NearFarScalar(2, 1, 4, 0) }); camera.position = new import__531.Cartesian3(2, 0, 0); return allLabelsReady().then(function() { expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(10); }); camera.position = new import__531.Cartesian3(4, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("renders label with pixelOffsetScaleByDistance", function() { labels.add({ position: import__531.Cartesian3.ZERO, pixelOffset: new import__531.Cartesian2(1, 0), text: solidBox, horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER, pixelOffsetScaleByDistance: new import__531.NearFarScalar(2, 0, 4, 1e3) }); return allLabelsReady().then(function() { camera.position = new import__531.Cartesian3(2, 0, 0); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(10); }); camera.position = new import__531.Cartesian3(4, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("renders label with scaleByDistance", function() { labels.add({ position: import__531.Cartesian3.ZERO, text: solidBox, horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER, scaleByDistance: new import__531.NearFarScalar(2, 1, 4, 0) }); return allLabelsReady().then(function() { camera.position = new import__531.Cartesian3(2, 0, 0); expect(scene2).toRender([255, 255, 255, 255]); camera.position = new import__531.Cartesian3(4, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("renders label with distanceDisplayCondition", function() { labels.add({ position: import__531.Cartesian3.ZERO, text: solidBox, distanceDisplayCondition: new import__531.DistanceDisplayCondition(10, 100), horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady().then(function() { camera.position = new import__531.Cartesian3(200, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); camera.position = new import__531.Cartesian3(50, 0, 0); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(200); expect(rgba[1]).toBeGreaterThan(200); expect(rgba[2]).toBeGreaterThan(200); }); camera.position = new import__531.Cartesian3(5, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("does not render label if show is false", function() { labels.add({ position: import__531.Cartesian3.ZERO, text: solidBox, horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER, scaleByDistance: new import__531.NearFarScalar(2, 1, 4, 0) }); return allLabelsReady().then(function() { camera.position = new import__531.Cartesian3(2, 0, 0); expect(scene2).toRender([255, 255, 255, 255]); labels.show = false; expect(scene2).toRender([0, 0, 0, 255]); }); }); it("throws new label with invalid distanceDisplayCondition (near >= far)", function() { const dc = new import__531.DistanceDisplayCondition(100, 10); expect(function() { labels.add({ distanceDisplayCondition: dc }); }).toThrowDeveloperError(); }); it("throws distanceDisplayCondition with near >= far", function() { const l = labels.add(); const dc = new import__531.DistanceDisplayCondition(100, 10); expect(function() { l.distanceDisplayCondition = dc; }).toThrowDeveloperError(); }); it("renders with disableDepthTestDistance", function() { const l = labels.add({ position: new import__531.Cartesian3(-1, 0, 0), text: solidBox, fillColor: import__531.Color.LIME, horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); labels.add({ position: import__531.Cartesian3.ZERO, text: solidBox, fillColor: import__531.Color.BLUE, horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady().then(function() { expect(scene2).toRender([0, 0, 255, 255]); l.disableDepthTestDistance = Number.POSITIVE_INFINITY; expect(scene2).toRender([0, 255, 0, 255]); }); }); it("throws with new label with disableDepthTestDistance less than 0.0", function() { expect(function() { labels.add({ disableDepthTestDistance: -1 }); }).toThrowDeveloperError(); }); it("throws with disableDepthTestDistance set less than 0.0", function() { const l = labels.add(); expect(function() { l.disableDepthTestDistance = -1; }).toThrowDeveloperError(); }); it("can pick a label", function() { const label = labels.add({ position: import__531.Cartesian3.ZERO, text: solidBox, horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER, id: "id" }); return allLabelsReady().then(function() { expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toEqual(label); expect(result.id).toEqual("id"); }); }); }); it("can change pick id", function() { const label = labels.add({ position: import__531.Cartesian3.ZERO, text: solidBox, horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER, id: "id" }); return allLabelsReady().then(function() { expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toEqual(label); expect(result.id).toEqual("id"); }); label.id = "id2"; expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toEqual(label); expect(result.id).toEqual("id2"); }); }); }); it("does not pick a label with show set to false", function() { labels.add({ show: false, position: import__531.Cartesian3.ZERO, text: solidBox, horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady().then(function() { expect(scene2).notToPick(); }); }); it("picks a label using translucencyByDistance", function() { const label = labels.add({ position: import__531.Cartesian3.ZERO, text: solidBox, horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady().then(function() { const translucency = new import__531.NearFarScalar(1, 0.9, 3e9, 0.8); label.translucencyByDistance = translucency; expect(scene2).toPickPrimitive(label); translucency.nearValue = 0; translucency.farValue = 0; label.translucencyByDistance = translucency; expect(scene2).notToPick(); }); }); it("picks a label using pixelOffsetScaleByDistance", function() { const label = labels.add({ position: import__531.Cartesian3.ZERO, pixelOffset: new import__531.Cartesian2(0, 100), text: solidBox, horizontalOrigin: import__531.HorizontalOrigin.CENTER, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady().then(function() { const pixelOffsetScale = new import__531.NearFarScalar(1, 0, 3e9, 0); label.pixelOffsetScaleByDistance = pixelOffsetScale; expect(scene2).toPickPrimitive(label); pixelOffsetScale.nearValue = 10; pixelOffsetScale.farValue = 10; label.pixelOffsetScaleByDistance = pixelOffsetScale; expect(scene2).notToPick(); }); }); it("throws when calling get without an index", function() { expect(function() { labels.get(); }).toThrowDeveloperError(); }); it("should reuse canvases for letters, but only if other settings are the same", function() { labels.add({ text: "a" }); let label; return allLabelsReady().then(function() { expect(Object.keys(labels._glyphTextureCache).length).toEqual(1); labels.add({ text: "a" }); return allLabelsReady(); }).then(function() { expect(Object.keys(labels._glyphTextureCache).length).toEqual(1); labels.add({ text: "abcd" }); return allLabelsReady(); }).then(function() { expect(Object.keys(labels._glyphTextureCache).length).toEqual(4); labels.add({ text: "abc" }); return allLabelsReady(); }).then(function() { expect(Object.keys(labels._glyphTextureCache).length).toEqual(4); label = labels.add({ text: "de" }); return allLabelsReady(); }).then(function() { expect(Object.keys(labels._glyphTextureCache).length).toEqual(5); const originalFont = label.font; label.font = '30px "Open Sans"'; expect(label.font).not.toEqual(originalFont); scene2.renderForSpecs(); expect(Object.keys(labels._glyphTextureCache).length).toEqual(7); label.style = import__531.LabelStyle.OUTLINE; scene2.renderForSpecs(); expect(Object.keys(labels._glyphTextureCache).length).toEqual(7); label.fillColor = new import__531.Color(1, 165 / 255, 0, 1); scene2.renderForSpecs(); expect(Object.keys(labels._glyphTextureCache).length).toEqual(7); label.outlineColor = new import__531.Color(1, 1, 1, 1); scene2.renderForSpecs(); expect(Object.keys(labels._glyphTextureCache).length).toEqual(7); label.verticalOrigin = import__531.VerticalOrigin.CENTER; scene2.renderForSpecs(); expect(Object.keys(labels._glyphTextureCache).length).toEqual(7); label.verticalOrigin = import__531.VerticalOrigin.TOP; scene2.renderForSpecs(); expect(Object.keys(labels._glyphTextureCache).length).toEqual(7); label.font = originalFont; scene2.renderForSpecs(); expect(Object.keys(labels._glyphTextureCache).length).toEqual(9); label.outlineWidth = 3; scene2.renderForSpecs(); expect(Object.keys(labels._glyphTextureCache).length).toEqual(9); }); }); it("should reuse billboards that are not needed any more", function() { const label = labels.add({ text: "abc" }); return allLabelsReady().then(function() { expect(labels._billboardCollection.length).toEqual(3); expect(labels._spareBillboards.length).toEqual(0); label.text = "a"; scene2.renderForSpecs(); expect(labels._billboardCollection.length).toEqual(3); expect(labels._spareBillboards.length).toEqual(2); label.text = "def"; scene2.renderForSpecs(); expect(labels._billboardCollection.length).toEqual(3); expect(labels._spareBillboards.length).toEqual(0); }); }); it("should not reuse background billboards that are not needed any more", function() { const label = labels.add({ text: "abc", showBackground: true }); return allLabelsReady().then(function() { expect(labels._backgroundBillboardCollection.length).toEqual(1); label.showBackground = false; scene2.renderForSpecs(); expect(labels._backgroundBillboardCollection.length).toEqual(0); label.showBackground = true; scene2.renderForSpecs(); expect(labels._backgroundBillboardCollection.length).toEqual(1); }); }); describe( "Label", function() { it("can set properties after being added", function() { const label = labels.add(); const show = false; const position = new import__531.Cartesian3(1, 2, 3); const text = "abc"; const font = '24px "Open Sans"'; const fillColor = { red: 2, green: 3, blue: 4, alpha: 1 }; const outlineColor = { red: 3, green: 4, blue: 2, alpha: 1 }; const outlineWidth = 2; const style = import__531.LabelStyle.FILL_AND_OUTLINE; const pixelOffset = new import__531.Cartesian2(4, 5); const eyeOffset = new import__531.Cartesian3(6, 7, 8); const horizontalOrigin = import__531.HorizontalOrigin.LEFT; const verticalOrigin = import__531.VerticalOrigin.BOTTOM; const scale = 2; const translucency = new import__531.NearFarScalar(1e4, 1, 1e6, 0); const pixelOffsetScale = new import__531.NearFarScalar(1e4, 1, 1e6, 0); const scaleByDistance = new import__531.NearFarScalar(1e4, 1, 1e6, 0); label.show = show; label.position = position; label.text = text; label.font = font; label.fillColor = fillColor; label.outlineColor = outlineColor; label.outlineWidth = outlineWidth; label.style = style; label.pixelOffset = pixelOffset; label.eyeOffset = eyeOffset; label.horizontalOrigin = horizontalOrigin; label.verticalOrigin = verticalOrigin; label.scale = scale; label.translucencyByDistance = translucency; label.pixelOffsetScaleByDistance = pixelOffsetScale; label.scaleByDistance = scaleByDistance; expect(label.show).toEqual(show); expect(label.position).toEqual(position); expect(label.text).toEqual(text); expect(label.font).toEqual(font); expect(label.fillColor).toEqual(fillColor); expect(label.outlineColor).toEqual(outlineColor); expect(label.outlineWidth).toEqual(outlineWidth); expect(label.style).toEqual(style); expect(label.pixelOffset).toEqual(pixelOffset); expect(label.eyeOffset).toEqual(eyeOffset); expect(label.horizontalOrigin).toEqual(horizontalOrigin); expect(label.verticalOrigin).toEqual(verticalOrigin); expect(label.scale).toEqual(scale); expect(label.translucencyByDistance).toEqual(translucency); expect(label.pixelOffsetScaleByDistance).toEqual(pixelOffsetScale); expect(label.scaleByDistance).toEqual(scaleByDistance); }); it("is destroyed after being removed", function() { const label = labels.add(); expect(label.isDestroyed()).toEqual(false); labels.remove(label); expect(label.isDestroyed()).toEqual(true); }); it("throws after being removed", function() { const label = labels.add(); labels.remove(label); expect(function() { label.equals(label); }).toThrowDeveloperError(); }); it("can compute screen space position", function() { labels.clampToPixel = false; const label = labels.add({ text: "abc", position: import__531.Cartesian3.ZERO }); scene2.renderForSpecs(); expect(label.computeScreenSpacePosition(scene2)).toEqualEpsilon( new import__531.Cartesian2(0.5, 0.5), import__532.Math.EPSILON1 ); }); it("stores screen space position in a result", function() { labels.clampToPixel = false; const label = labels.add({ text: "abc", position: import__531.Cartesian3.ZERO }); const result = new import__531.Cartesian2(); scene2.renderForSpecs(); const actual = label.computeScreenSpacePosition(scene2, result); expect(actual).toEqual(result); expect(result).toEqualEpsilon( new import__531.Cartesian2(0.5, 0.5), import__532.Math.EPSILON1 ); }); it("can compute screen space position with pixelOffset", function() { labels.clampToPixel = false; const label = labels.add({ text: "abc", position: import__531.Cartesian3.ZERO, pixelOffset: new import__531.Cartesian2(0.5, 0.5) }); scene2.renderForSpecs(); expect(label.computeScreenSpacePosition(scene2)).toEqualEpsilon( new import__531.Cartesian2(1, 1), import__532.Math.EPSILON1 ); }); it("can compute screen space position with eyeOffset", function() { labels.clampToPixel = false; const label = labels.add({ text: "abc", position: import__531.Cartesian3.ZERO, eyeOffset: new import__531.Cartesian3(1, 1, 0) }); scene2.renderForSpecs(); expect(label.computeScreenSpacePosition(scene2)).toEqualEpsilon( new import__531.Cartesian2(0.5, 0.5), import__532.Math.EPSILON1 ); }); it("computes screen space bounding box", function() { const scale = 1.5; const label = labels.add({ text: "abc", scale }); return allLabelsReady().then(function() { const bbox = import__531.Label.getScreenSpaceBoundingBox( label, import__531.Cartesian2.ZERO ); expect(bbox.x).toBeDefined(); expect(bbox.y).toBeDefined(); expect(bbox.width).toBeGreaterThan(30); expect(bbox.width).toBeLessThan(200); expect(bbox.height).toBeGreaterThan(10); expect(bbox.height).toBeLessThan(50); }); }); it("computes screen space bounding box with result", function() { const scale = 1.5; const label = labels.add({ text: "abc", scale }); return allLabelsReady().then(function() { const result = new import__531.BoundingRectangle(); const bbox = import__531.Label.getScreenSpaceBoundingBox( label, import__531.Cartesian2.ZERO, result ); expect(bbox.x).toBeDefined(); expect(bbox.y).toBeDefined(); expect(bbox.width).toBeGreaterThan(30); expect(bbox.width).toBeLessThan(200); expect(bbox.height).toBeGreaterThan(10); expect(bbox.height).toBeLessThan(50); expect(bbox).toBe(result); }); }); it("computes screen space bounding box with vertical origin center", function() { const scale = 1.5; const label = labels.add({ text: "abc", scale, verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady().then(function() { const bbox = import__531.Label.getScreenSpaceBoundingBox( label, import__531.Cartesian2.ZERO ); expect(bbox.y).toBeGreaterThan(bbox.height * -0.9); expect(bbox.y).toBeLessThan(bbox.height * -0.3); }); }); it("computes screen space bounding box with vertical origin top", function() { const scale = 1.5; const label = labels.add({ text: "abc", scale, verticalOrigin: import__531.VerticalOrigin.TOP }); return allLabelsReady().then(function() { const bbox = import__531.Label.getScreenSpaceBoundingBox( label, import__531.Cartesian2.ZERO ); expect(bbox.y).toBeLessThan(5); expect(bbox.y).toBeGreaterThan(-5); }); }); it("computes screen space bounding box with vertical origin baseline", function() { const scale = 1.5; const label = labels.add({ text: "abc", scale, verticalOrigin: import__531.VerticalOrigin.BASELINE }); return allLabelsReady().then(function() { const bbox = import__531.Label.getScreenSpaceBoundingBox( label, import__531.Cartesian2.ZERO ); expect(bbox.y).toBeLessThan(bbox.height * -0.8); expect(bbox.y).toBeGreaterThan(bbox.height * -1.2); }); }); it("computes screen space bounding box with horizontal origin", function() { const scale = 1.5; const label = labels.add({ text: "abc", scale, horizontalOrigin: import__531.HorizontalOrigin.CENTER }); return allLabelsReady().then(function() { let bbox = import__531.Label.getScreenSpaceBoundingBox(label, import__531.Cartesian2.ZERO); expect(bbox.x).toBeLessThan(bbox.width * -0.3); expect(bbox.x).toBeGreaterThan(bbox.width * -0.7); label.horizontalOrigin = import__531.HorizontalOrigin.RIGHT; scene2.renderForSpecs(); bbox = import__531.Label.getScreenSpaceBoundingBox(label, import__531.Cartesian2.ZERO); expect(bbox.x).toBeLessThan(bbox.width * -0.8); expect(bbox.x).toBeGreaterThan(bbox.width * -1.2); }); }); it("computes screen space bounding box with padded background", function() { const scale = 1.5; const label = labels.add({ text: "abc", scale, showBackground: true, backgroundPadding: new import__531.Cartesian2(15, 10) }); return allLabelsReady().then(function() { const totalScale = label.scale * label._relativeSize; const backgroundBillboard = label._backgroundBillboard; const width = backgroundBillboard.width * totalScale; const height = backgroundBillboard.height * totalScale; const x = backgroundBillboard._translate.x; let y = -(backgroundBillboard._translate.y + height); let bbox = import__531.Label.getScreenSpaceBoundingBox(label, import__531.Cartesian2.ZERO); expect(bbox.x).toEqual(x); expect(bbox.y).toEqual(y); expect(bbox.width).toEqual(width); expect(bbox.height).toEqual(height); label.verticalOrigin = import__531.VerticalOrigin.CENTER; scene2.renderForSpecs(); y = -(backgroundBillboard._translate.y + height * 0.5); bbox = import__531.Label.getScreenSpaceBoundingBox(label, import__531.Cartesian2.ZERO); expect(bbox.x).toEqual(x); expect(bbox.y).toEqual(y); expect(bbox.width).toEqual(width); expect(bbox.height).toEqual(height); }); }); it("can equal another label", function() { const label = labels.add({ position: new import__531.Cartesian3(1, 2, 3), text: "equals" }); const otherLabel = labels.add({ position: new import__531.Cartesian3(1, 2, 3), text: "equals" }); expect(label.equals(otherLabel)).toEqual(true); }); it("can differ from another label", function() { const label = labels.add({ position: new import__531.Cartesian3(1, 2, 3) }); const otherLabel = labels.add({ position: new import__531.Cartesian3(4, 5, 6) }); expect(label.equals(otherLabel)).toEqual(false); }); it("does not equal undefined", function() { const label = labels.add(); expect(label.equals(void 0)).toEqual(false); }); it("should have a number of glyphs equal to the number of characters", function() { let label = labels.add({ text: "abc" }); return allLabelsReady().then(function() { expect(label._glyphs.length).toEqual(3); label.text = "abcd"; scene2.renderForSpecs(); expect(label._glyphs.length).toEqual(4); label.text = ""; scene2.renderForSpecs(); expect(label._glyphs.length).toEqual(0); label = labels.add(); scene2.renderForSpecs(); expect(label._glyphs.length).toEqual(0); }); }); it("does not create billboards for spaces", function() { const label = labels.add({ text: "abc" }); return allLabelsReady().then(function() { expect(label._glyphs.length).toEqual(3); expect(labels._billboardCollection.length).toEqual(3); label.text = " ab c"; scene2.renderForSpecs(); expect(label._glyphs.length).toEqual(5); expect(labels._billboardCollection.length).toEqual(3); }); }); function getGlyphBillboardVertexTranslate(label, index) { return import__531.Cartesian2.clone( label._glyphs[index].billboard._translate, new import__531.Cartesian2() ); } function getBackgroundBillboardVertexTranslate(label) { return import__531.Cartesian2.clone( label._backgroundBillboard._translate, new import__531.Cartesian2() ); } it("sets billboard properties properly when they change on the label", function() { const position1 = new import__531.Cartesian3(1, 2, 3); const position2 = new import__531.Cartesian3(4, 5, 6); const pixelOffset1 = new import__531.Cartesian2(4, 5); const pixelOffset2 = new import__531.Cartesian2(6, 7); const eyeOffset1 = new import__531.Cartesian3(6, 7, 8); const eyeOffset2 = new import__531.Cartesian3(16, 17, 18); const verticalOrigin1 = import__531.VerticalOrigin.TOP; const verticalOrigin2 = import__531.VerticalOrigin.BASELINE; const scale1 = 2; const scale2 = 3; const id1 = "id1"; const id2 = "id2"; const translucency1 = new import__531.NearFarScalar(1e4, 1, 1e6, 0); const translucency2 = new import__531.NearFarScalar(11e3, 1.2, 13e5, 4); const pixelOffsetScale1 = new import__531.NearFarScalar(1e4, 1, 1e6, 0); const pixelOffsetScale2 = new import__531.NearFarScalar(15e3, 1.6, 17e5, 8); const scaleByDistance1 = new import__531.NearFarScalar(1e4, 1, 1e6, 0); const scaleByDistance2 = new import__531.NearFarScalar(15e3, 1.6, 17e5, 8); const label = labels.add({ position: position1, text: "abc", pixelOffset: pixelOffset1, eyeOffset: eyeOffset1, verticalOrigin: verticalOrigin1, scale: scale1, id: id1, translucencyByDistance: translucency1, pixelOffsetScaleByDistance: pixelOffsetScale1, scaleByDistance: scaleByDistance1, showBackground: true }); scene2.renderForSpecs(); label.position = position2; label.text = "def"; label.pixelOffset = pixelOffset2; label.eyeOffset = eyeOffset2; label.verticalOrigin = verticalOrigin2; label.scale = scale2; label.id = id2; label.translucencyByDistance = translucency2; label.pixelOffsetScaleByDistance = pixelOffsetScale2; label.scaleByDistance = scaleByDistance2; scene2.renderForSpecs(); for (let i = 0; i < label._glyphs.length; ++i) { const glyph = label._glyphs[i]; const billboard = glyph.billboard; expect(billboard.show).toEqual(label.show); expect(billboard.position).toEqual(label.position); expect(billboard.eyeOffset).toEqual(label.eyeOffset); expect(billboard.pixelOffset).toEqual(label.pixelOffset); expect(billboard.verticalOrigin).toEqual(label.verticalOrigin); expect(billboard.scale).toEqual(label.scale * label._relativeSize); expect(billboard.id).toEqual(label.id); expect(billboard.translucencyByDistance).toEqual( label.translucencyByDistance ); expect(billboard.pixelOffsetScaleByDistance).toEqual( label.pixelOffsetScaleByDistance ); expect(billboard.scaleByDistance).toEqual(label.scaleByDistance); expect(billboard.pickPrimitive).toEqual(label); } }); describe("sets individual billboard properties properly when they change on the label", function() { let label; beforeEach(function() { label = labels.add({ position: new import__531.Cartesian3(1, 2, 3), text: "abc", pixelOffset: new import__531.Cartesian2(4, 5), eyeOffset: new import__531.Cartesian3(6, 7, 8), verticalOrigin: import__531.VerticalOrigin.TOP, scale: 2, id: "id1", translucencyByDistance: new import__531.NearFarScalar(1e4, 1, 1e6, 0), pixelOffsetScaleByDistance: new import__531.NearFarScalar( 1e4, 1, 1e6, 0 ), scaleByDistance: new import__531.NearFarScalar(1e4, 1, 1e6, 0), showBackground: true }); scene2.renderForSpecs(); }); function getGlyphBillboards() { return label._glyphs.map(function(glyph) { return glyph.billboard; }); } it("position", function() { const newValue = new import__531.Cartesian3(4, 5, 6); expect(label.position).not.toEqual(newValue); label.position = newValue; scene2.renderForSpecs(); getGlyphBillboards().forEach(function(billboard) { expect(billboard.position).toEqual(label.position); }); }); it("eyeOffset", function() { const newValue = new import__531.Cartesian3(16, 17, 18); expect(label.eyeOffset).not.toEqual(newValue); label.eyeOffset = newValue; scene2.renderForSpecs(); getGlyphBillboards().forEach(function(billboard) { expect(billboard.eyeOffset).toEqual(label.eyeOffset); }); }); it("pixelOffset", function() { const newValue = new import__531.Cartesian3(16, 17, 18); expect(label.pixelOffset).not.toEqual(newValue); label.pixelOffset = newValue; scene2.renderForSpecs(); getGlyphBillboards().forEach(function(billboard) { expect(billboard.pixelOffset).toEqual(label.pixelOffset); }); }); it("verticalOrigin", function() { const newValue = import__531.VerticalOrigin.BOTTOM; expect(label.verticalOrigin).not.toEqual(newValue); label.verticalOrigin = newValue; scene2.renderForSpecs(); getGlyphBillboards().forEach(function(billboard) { expect(billboard.verticalOrigin).toEqual(label.verticalOrigin); }); }); it("scale", function() { const newValue = 3; expect(label.scale).not.toEqual(newValue); label.scale = newValue; scene2.renderForSpecs(); getGlyphBillboards().forEach(function(billboard) { expect(billboard.scale).toEqual(label.totalScale); }); }); it("showBackground", function() { expect(label.showBackground).toEqual(true); label.showBackground = false; expect(label.showBackground).toEqual(false); }); it("backgroundColor", function() { const newValue = import__531.Color.RED; expect(label.backgroundColor).not.toEqual(newValue); label.backgroundColor = newValue; expect(label.backgroundColor).toEqual(newValue); }); it("backgroundPadding", function() { const newValue = new import__531.Cartesian2(8, 5); expect(label.backgroundPadding).not.toEqual(newValue); label.backgroundPadding = newValue; expect(label.backgroundPadding).toEqual(newValue); }); it("id", function() { const newValue = "id2"; expect(label.id).not.toEqual(newValue); label.id = newValue; scene2.renderForSpecs(); getGlyphBillboards().forEach(function(billboard) { expect(billboard.id).toEqual(label.id); }); }); it("translucencyByDistance", function() { const newValue = new import__531.NearFarScalar(11e3, 1.2, 13e5, 4); expect(label.translucencyByDistance).not.toEqual(newValue); label.translucencyByDistance = newValue; scene2.renderForSpecs(); getGlyphBillboards().forEach(function(billboard) { expect(billboard.translucencyByDistance).toEqual( label.translucencyByDistance ); }); }); it("pixelOffsetScaleByDistance", function() { const newValue = new import__531.NearFarScalar(15e3, 1.6, 17e5, 8); expect(label.pixelOffsetScaleByDistance).not.toEqual(newValue); label.pixelOffsetScaleByDistance = newValue; scene2.renderForSpecs(); getGlyphBillboards().forEach(function(billboard) { expect(billboard.pixelOffsetScaleByDistance).toEqual( label.pixelOffsetScaleByDistance ); }); }); it("scaleByDistance", function() { const newValue = new import__531.NearFarScalar(15e3, 1.6, 17e5, 8); expect(label.scaleByDistance).not.toEqual(newValue); label.scaleByDistance = newValue; scene2.renderForSpecs(); getGlyphBillboards().forEach(function(billboard) { expect(billboard.scaleByDistance).toEqual(label.scaleByDistance); }); }); it("translucencyByDistance to undefined", function() { let newValue; expect(label.translucencyByDistance).not.toEqual(newValue); label.translucencyByDistance = newValue; scene2.renderForSpecs(); getGlyphBillboards().forEach(function(billboard) { expect(billboard.translucencyByDistance).toEqual( label.translucencyByDistance ); }); }); it("pixelOffsetScaleByDistance to undefined", function() { let newValue; expect(label.pixelOffsetScaleByDistance).not.toEqual(newValue); label.pixelOffsetScaleByDistance = newValue; scene2.renderForSpecs(); getGlyphBillboards().forEach(function(billboard) { expect(billboard.pixelOffsetScaleByDistance).toEqual( label.pixelOffsetScaleByDistance ); }); }); it("scaleByDistance to undefined", function() { let newValue; expect(label.scaleByDistance).not.toEqual(newValue); label.scaleByDistance = newValue; scene2.renderForSpecs(); getGlyphBillboards().forEach(function(billboard) { expect(billboard.scaleByDistance).toEqual(label.scaleByDistance); }); }); it("clusterShow", function() { expect(label.clusterShow).toEqual(true); label.clusterShow = false; expect(label.clusterShow).toEqual(false); }); }); it("should set vertexTranslate of billboards correctly when vertical origin is changed", function() { const label = labels.add({ text: "apl", font: '90px "Open Sans"', verticalOrigin: import__531.VerticalOrigin.CENTER }); return allLabelsReady().then(function() { const offset0 = getGlyphBillboardVertexTranslate(label, 0); const offset1 = getGlyphBillboardVertexTranslate(label, 1); const offset2 = getGlyphBillboardVertexTranslate(label, 2); label.verticalOrigin = import__531.VerticalOrigin.TOP; scene2.renderForSpecs(); expect(getGlyphBillboardVertexTranslate(label, 0).x).toEqual( offset0.x ); expect(getGlyphBillboardVertexTranslate(label, 1).x).toEqual( offset1.x ); expect(getGlyphBillboardVertexTranslate(label, 2).x).toEqual( offset2.x ); label.verticalOrigin = import__531.VerticalOrigin.BOTTOM; scene2.renderForSpecs(); expect(getGlyphBillboardVertexTranslate(label, 0).x).toEqual( offset0.x ); expect(getGlyphBillboardVertexTranslate(label, 1).x).toEqual( offset1.x ); expect(getGlyphBillboardVertexTranslate(label, 2).x).toEqual( offset2.x ); }); }); it("should set vertexTranslate of billboards correctly when horizontal origin is changed", function() { const label = labels.add({ text: "apl", font: '90px "Open Sans"', horizontalOrigin: import__531.HorizontalOrigin.CENTER, showBackground: true }); return allLabelsReady().then(function() { const offset0 = getGlyphBillboardVertexTranslate(label, 0); const offset1 = getGlyphBillboardVertexTranslate(label, 1); const offset2 = getGlyphBillboardVertexTranslate(label, 2); const offsetBack = getBackgroundBillboardVertexTranslate(label); label.horizontalOrigin = import__531.HorizontalOrigin.LEFT; scene2.renderForSpecs(); expect( getGlyphBillboardVertexTranslate(label, 0).x ).toBeGreaterThan(offset0.x); expect( getGlyphBillboardVertexTranslate(label, 1).x ).toBeGreaterThan(offset1.x); expect( getGlyphBillboardVertexTranslate(label, 2).x ).toBeGreaterThan(offset2.x); expect( getBackgroundBillboardVertexTranslate(label).x ).toBeGreaterThan(offsetBack.x); expect(getGlyphBillboardVertexTranslate(label, 0).y).toEqual( offset0.y ); expect(getGlyphBillboardVertexTranslate(label, 1).y).toEqual( offset1.y ); expect(getGlyphBillboardVertexTranslate(label, 2).y).toEqual( offset2.y ); expect(getBackgroundBillboardVertexTranslate(label).y).toEqual( offsetBack.y ); label.horizontalOrigin = import__531.HorizontalOrigin.RIGHT; scene2.renderForSpecs(); expect(getGlyphBillboardVertexTranslate(label, 0).x).toBeLessThan( offset0.x ); expect(getGlyphBillboardVertexTranslate(label, 1).x).toBeLessThan( offset1.x ); expect(getGlyphBillboardVertexTranslate(label, 2).x).toBeLessThan( offset2.x ); expect(getBackgroundBillboardVertexTranslate(label).x).toBeLessThan( offsetBack.x ); expect(getGlyphBillboardVertexTranslate(label, 0).y).toEqual( offset0.y ); expect(getGlyphBillboardVertexTranslate(label, 1).y).toEqual( offset1.y ); expect(getGlyphBillboardVertexTranslate(label, 2).y).toEqual( offset2.y ); expect(getBackgroundBillboardVertexTranslate(label).y).toEqual( offsetBack.y ); }); }); it("should set vertexTranslate of billboards correctly when scale is changed", function() { const label = labels.add({ text: "apl", font: '90px "Open Sans"', verticalOrigin: import__531.VerticalOrigin.CENTER, horizontalOrigin: import__531.HorizontalOrigin.CENTER }); return allLabelsReady().then(function() { let offset0 = getGlyphBillboardVertexTranslate(label, 0); let offset1 = getGlyphBillboardVertexTranslate(label, 1); let offset2 = getGlyphBillboardVertexTranslate(label, 2); label.scale = 2; scene2.renderForSpecs(); expect(getGlyphBillboardVertexTranslate(label, 0).x).toEqual( 2 * offset0.x ); expect(getGlyphBillboardVertexTranslate(label, 0).y).toEqual( 2 * offset0.y ); expect(getGlyphBillboardVertexTranslate(label, 1).x).toEqual( 2 * offset1.x ); expect(getGlyphBillboardVertexTranslate(label, 1).y).toEqual( 2 * offset1.y ); expect(getGlyphBillboardVertexTranslate(label, 2).x).toEqual( 2 * offset2.x ); expect(getGlyphBillboardVertexTranslate(label, 2).y).toEqual( 2 * offset2.y ); offset0 = getGlyphBillboardVertexTranslate(label, 0); offset1 = getGlyphBillboardVertexTranslate(label, 1); offset2 = getGlyphBillboardVertexTranslate(label, 2); label.horizontalOrigin = import__531.HorizontalOrigin.LEFT; scene2.renderForSpecs(); expect( getGlyphBillboardVertexTranslate(label, 0).x ).toBeGreaterThan(offset0.x); expect( getGlyphBillboardVertexTranslate(label, 1).x ).toBeGreaterThan(offset1.x); expect( getGlyphBillboardVertexTranslate(label, 2).x ).toBeGreaterThan(offset2.x); expect(getGlyphBillboardVertexTranslate(label, 0).y).toEqual( offset0.y ); expect(getGlyphBillboardVertexTranslate(label, 1).y).toEqual( offset1.y ); expect(getGlyphBillboardVertexTranslate(label, 2).y).toEqual( offset2.y ); label.horizontalOrigin = import__531.HorizontalOrigin.RIGHT; scene2.renderForSpecs(); expect(getGlyphBillboardVertexTranslate(label, 0).x).toBeLessThan( offset0.x ); expect(getGlyphBillboardVertexTranslate(label, 1).x).toBeLessThan( offset1.x ); expect(getGlyphBillboardVertexTranslate(label, 2).x).toBeLessThan( offset2.x ); expect(getGlyphBillboardVertexTranslate(label, 0).y).toEqual( offset0.y ); expect(getGlyphBillboardVertexTranslate(label, 1).y).toEqual( offset1.y ); expect(getGlyphBillboardVertexTranslate(label, 2).y).toEqual( offset2.y ); }); }); it("label vertex translate should remain the same when pixel offset is changed", function() { const label = labels.add({ text: "apl", font: '90px "Open Sans"' }); return allLabelsReady().then(function() { const offset0 = getGlyphBillboardVertexTranslate(label, 0); const offset1 = getGlyphBillboardVertexTranslate(label, 1); const offset2 = getGlyphBillboardVertexTranslate(label, 2); const xOffset = 20; const yOffset = -10; label.pixelOffset = new import__531.Cartesian2(xOffset, yOffset); scene2.renderForSpecs(); expect(getGlyphBillboardVertexTranslate(label, 0)).toEqual(offset0); expect(getGlyphBillboardVertexTranslate(label, 1)).toEqual(offset1); expect(getGlyphBillboardVertexTranslate(label, 2)).toEqual(offset2); expect(label.pixelOffset.x).toEqual(xOffset); expect(label.pixelOffset.y).toEqual(yOffset); }); }); it("Correctly updates billboard position when height reference changes", function() { scene2.globe = new import__531.Globe(); const labelsWithScene = new import__531.LabelCollection({ scene: scene2 }); scene2.primitives.add(labelsWithScene); const position1 = new import__531.Cartesian3(1, 2, 3); const label = labelsWithScene.add({ position: position1, text: "abc", heightReference: import__531.HeightReference.CLAMP_TO_GROUND }); return allLabelsReady().then(function() { const glyph = label._glyphs[0]; const billboard = glyph.billboard; expect(billboard.position).toEqual(label.position); label.heightReference = import__531.HeightReference.NONE; scene2.renderForSpecs(); expect(billboard.position).toEqual(label.position); scene2.primitives.remove(labelsWithScene); }); }); it("should set vertexTranslate of billboards correctly when font size changes", function() { const label = labels.add({ text: "apl", font: '80px "Open Sans"', verticalOrigin: import__531.VerticalOrigin.TOP, horizontalOrigin: import__531.HorizontalOrigin.LEFT }); return allLabelsReady().then(function() { const offset0 = getGlyphBillboardVertexTranslate(label, 0); const offset1 = getGlyphBillboardVertexTranslate(label, 1); const offset2 = getGlyphBillboardVertexTranslate(label, 2); label.font = '20px "Open Sans"'; scene2.renderForSpecs(); expect( Math.abs(getGlyphBillboardVertexTranslate(label, 0).x) ).toBeLessThanOrEqual(Math.abs(offset0.x)); expect( Math.abs(getGlyphBillboardVertexTranslate(label, 0).y) ).toBeLessThanOrEqual(Math.abs(offset0.y)); expect( Math.abs(getGlyphBillboardVertexTranslate(label, 1).x) ).toBeLessThanOrEqual(Math.abs(offset1.x)); expect( Math.abs(getGlyphBillboardVertexTranslate(label, 1).y) ).toBeLessThanOrEqual(Math.abs(offset1.y)); expect( Math.abs(getGlyphBillboardVertexTranslate(label, 2).x) ).toBeLessThanOrEqual(Math.abs(offset2.x)); expect( Math.abs(getGlyphBillboardVertexTranslate(label, 2).y) ).toBeLessThanOrEqual(Math.abs(offset2.y)); }); }); it("should have the same vertexTranslate of billboards whether values are set at construction or afterwards", function() { const text = "apl"; const scale = 2; const font = '20px "Open Sans"'; const verticalOrigin = import__531.VerticalOrigin.CENTER; const pixelOffset = new import__531.Cartesian2(10, 15); const one = labels.add({ text, scale, font, verticalOrigin, pixelOffset }); scene2.renderForSpecs(); const two = labels.add(); two.text = text; two.scale = scale; two.font = font; two.verticalOrigin = verticalOrigin; two.pixelOffset = pixelOffset; return allLabelsReady().then(function() { expect(getGlyphBillboardVertexTranslate(one, 0)).toEqual( getGlyphBillboardVertexTranslate(two, 0) ); expect(getGlyphBillboardVertexTranslate(one, 1)).toEqual( getGlyphBillboardVertexTranslate(two, 1) ); expect(getGlyphBillboardVertexTranslate(one, 2)).toEqual( getGlyphBillboardVertexTranslate(two, 2) ); }); }); it("should not change vertexTranslate of billboards when position changes", function() { const label = labels.add({ text: "apl" }); return allLabelsReady().then(function() { const offset0 = getGlyphBillboardVertexTranslate(label, 0); const offset1 = getGlyphBillboardVertexTranslate(label, 1); const offset2 = getGlyphBillboardVertexTranslate(label, 2); label.position = new import__531.Cartesian3(1, 1, 1); scene2.renderForSpecs(); expect(getGlyphBillboardVertexTranslate(label, 0)).toEqual(offset0); expect(getGlyphBillboardVertexTranslate(label, 1)).toEqual(offset1); expect(getGlyphBillboardVertexTranslate(label, 2)).toEqual(offset2); }); }); it("should not change vertexTranslate of billboards when eye offset changes", function() { const label = labels.add({ text: "apl" }); return allLabelsReady().then(function() { const offset0 = getGlyphBillboardVertexTranslate(label, 0); const offset1 = getGlyphBillboardVertexTranslate(label, 1); const offset2 = getGlyphBillboardVertexTranslate(label, 2); label.eyeOffset = new import__531.Cartesian3(10, 10, -10); scene2.renderForSpecs(); expect(getGlyphBillboardVertexTranslate(label, 0)).toEqual(offset0); expect(getGlyphBillboardVertexTranslate(label, 1)).toEqual(offset1); expect(getGlyphBillboardVertexTranslate(label, 2)).toEqual(offset2); }); }); it("should not change label dimensions when scale changes", function() { const label = labels.add({ text: "apl" }); return allLabelsReady().then(function() { const originalDimensions = label._glyphs[0].dimensions; label.scale = 3; scene2.renderForSpecs(); const dimensions = label._glyphs[0].dimensions; expect(dimensions.width).toEqual(originalDimensions.width); expect(dimensions.height).toEqual(originalDimensions.height); expect(dimensions.descent).toEqual(originalDimensions.descent); }); }); it("should not change label dimensions when font size changes", function() { const label = labels.add({ text: "apl", font: '90px "Open Sans"' }); return allLabelsReady().then(function() { const originalDimensions = label._glyphs[0].dimensions; label.font = '20px "Open Sans"'; scene2.renderForSpecs(); const dimensions = label._glyphs[0].dimensions; expect(dimensions.width).toEqual(originalDimensions.width); expect(dimensions.height).toEqual(originalDimensions.height); expect(dimensions.descent).toEqual(originalDimensions.descent); }); }); it("should increase label height and decrease width when adding newlines", function() { const label = labels.add({ text: "apl apl apl" }); return allLabelsReady().then(function() { const originalBbox = import__531.Label.getScreenSpaceBoundingBox( label, import__531.Cartesian2.ZERO ); label.text = "apl\napl\napl"; scene2.renderForSpecs(); const newlinesBbox = import__531.Label.getScreenSpaceBoundingBox( label, import__531.Cartesian2.ZERO ); expect(newlinesBbox.width).toBeLessThan(originalBbox.width); expect(newlinesBbox.height).toBeGreaterThan(originalBbox.height); }); }); it("should not modify text when rightToLeft is false", function() { const text = "bla bla bla"; const label = labels.add({ text }); return allLabelsReady().then(function() { expect(label.text).toEqual(text); }); }); it("filters out soft hyphens from input strings", function() { const softHyphen = String.fromCharCode(173); const text = `test string${softHyphen}`; const label = labels.add({ text }); return allLabelsReady().then(function() { expect(label.text).toEqual(text); expect(label._renderedText).toEqual("test string"); }); }); }, "WebGL" ); describe("right to left detection", function() { beforeAll(function() { import__531.Label.enableRightToLeftDetection = true; }); afterAll(function() { import__531.Label.enableRightToLeftDetection = false; }); it("should not modify text when rightToLeft is true and there are no RTL characters", function() { const text = "bla bla bla"; const label = labels.add({ text }); expect(label.text).toEqual(text); }); it("should reverse text when there are only hebrew characters and rightToLeft is true", function() { const text = "\u05E9\u05DC\u05D5\u05DD"; const expectedText = "\u05DD\u05D5\u05DC\u05E9"; const label = labels.add({ text }); expect(label.text).toEqual(text); expect(label._renderedText).toEqual(expectedText); }); it("should reverse text when there are only arabic characters and rightToLeft is true", function() { const text = "\u0645\u0631\u062D\u0628\u0627"; const expectedText = "\u0627\u0628\u062D\u0631\u0645"; const label = labels.add({ text }); expect(label.text).toEqual(text); expect(label._renderedText).toEqual(expectedText); }); it("should reverse part of text when there is mix of right-to-left and other kind of characters and rightToLeft is true", function() { const text = 'Master (\u05D0\u05D3\u05D5\u05DF): "Hello"\n\u05EA\u05DC\u05DE\u05D9\u05D3 (student): "\u05E9\u05DC\u05D5\u05DD"'; const expectedText = 'Master (\u05DF\u05D5\u05D3\u05D0): "Hello"\n"\u05DD\u05D5\u05DC\u05E9" :(student) \u05D3\u05D9\u05DE\u05DC\u05EA'; const label = labels.add({ text }); expect(label.text).toEqual(text); expect(label._renderedText).toEqual(expectedText); }); it("should reverse all text and replace brackets when there is right-to-left characters and rightToLeft is true", function() { const text = "\u05DE\u05E9\u05E4\u05D8 [\u05DE\u05D5\u05E8\u05DB\u05D1] {\u05E2\u05DD} \u05EA\u05D5\u05D5\u05D9\u05DD <\u05DE\u05D9\u05D5\u05D7\u05D3\u05D9\u05DD special>"; const expectedText = " \u05DD\u05D9\u05D5\u05D5\u05EA {\u05DD\u05E2} [\u05D1\u05DB\u05E8\u05D5\u05DE] \u05D8\u05E4\u05E9\u05DE"; const label = labels.add({ text }); expect(label.text).toEqual(text); expect(label._renderedText).toEqual(expectedText); }); it("should reverse only text that detected as rtl text when it begin with non rtl characters when rightToLeft is true", function() { const text = "(interesting sentence with hebrew characters) \u05E9\u05DC\u05D5\u05DD(\u05E2\u05DC\u05D9\u05DA)\u05D7\u05D1\u05D9\u05D1\u05D9."; const expectedText = "(interesting sentence with hebrew characters) \u05D9\u05D1\u05D9\u05D1\u05D7(\u05DA\u05D9\u05DC\u05E2)\u05DD\u05D5\u05DC\u05E9."; const label = labels.add({ text }); expect(label.text).toEqual(text); expect(label._renderedText).toEqual(expectedText); }); it("should not change nothing if it only non alphanumeric characters when rightToLeft is true", function() { const text = "([{- -}])"; const expectedText = "([{- -}])"; const label = labels.add({ text }); expect(label.text).toEqual(expectedText); }); it("detects characters in the range \\u05D0-\\u05EA", function() { const text = "\u05D1\u05D2"; const expectedText = "\u05D2\u05D1"; const label = labels.add({ text }); expect(label.text).toEqual(text); expect(label._renderedText).toEqual(expectedText); }); it("detects characters in the range \\u0600-\\u06FF", function() { const text = "\u0601\u0602"; const expectedText = "\u0602\u0601"; const label = labels.add({ text }); expect(label.text).toEqual(text); expect(label._renderedText).toEqual(expectedText); }); it("detects characters in the range \\u0750-\\u077F", function() { const text = "\u0751\u0752"; const expectedText = "\u0752\u0751"; const label = labels.add({ text }); expect(label.text).toEqual(text); expect(label._renderedText).toEqual(expectedText); }); it("detects characters in the range \\u08A0-\\u08FF", function() { const text = "\u08A1\u08A2"; const expectedText = "\u08A2\u08A1"; const label = labels.add({ text }); expect(label.text).toEqual(text); expect(label._renderedText).toEqual(expectedText); }); it("should reversing correctly non alphabetic characters", function() { const text = "A \u05D0\u05D1: \u05D2\n\u05D0\u05D1: \u05D2"; const expectedText = "A \u05D2 :\u05D1\u05D0\n\u05D2 :\u05D1\u05D0"; const label = labels.add({ text }); expect(label.text).toEqual(text); expect(label._renderedText).toEqual(expectedText); }); }); it("computes bounding sphere in 3D", function() { const one = labels.add({ position: import__531.Cartesian3.fromDegrees(-50, -50, 0), text: "one" }); const two = labels.add({ position: import__531.Cartesian3.fromDegrees(-50, 50, 0), text: "two" }); return allLabelsReady().then(function() { const actual = scene2.frameState.commandList[0].boundingVolume; const positions = [one.position, two.position]; const expected = import__531.BoundingSphere.fromPoints(positions); expect(actual.center).toEqual(expected.center); expect(actual.radius).toEqual(expected.radius); }); }); it("computes bounding sphere in Columbus view", function() { const originalEnableCollisionDetection = scene2.screenSpaceCameraController.enableCollisionDetection; scene2.screenSpaceCameraController.enableCollisionDetection = false; const projection = scene2.mapProjection; const ellipsoid = projection.ellipsoid; const one = labels.add({ position: import__531.Cartesian3.fromDegrees(-50, -50, 0), text: "one" }); const two = labels.add({ position: import__531.Cartesian3.fromDegrees(-50, 50, 0), text: "two" }); scene2.morphToColumbusView(0); return allLabelsReady().then(function() { const actual = scene2.frameState.commandList[0].boundingVolume; const projectedPositions = [ projection.project(ellipsoid.cartesianToCartographic(one.position)), projection.project(ellipsoid.cartesianToCartographic(two.position)) ]; const expected = import__531.BoundingSphere.fromPoints(projectedPositions); expected.center = new import__531.Cartesian3( 0, expected.center.x, expected.center.y ); expect(actual.center).toEqualEpsilon( expected.center, import__532.Math.EPSILON8 ); expect(actual.radius).toBeGreaterThanOrEqual(expected.radius); scene2.screenSpaceCameraController.enableCollisionDetection = originalEnableCollisionDetection; }); }); it("computes bounding sphere in 2D", function() { const projection = scene2.mapProjection; const ellipsoid = projection.ellipsoid; const one = labels.add({ position: import__531.Cartesian3.fromDegrees(-50, -50), text: "one" }); const two = labels.add({ position: import__531.Cartesian3.fromDegrees(-50, 50), text: "two" }); camera.setView({ destination: import__531.Rectangle.fromDegrees(-60, -60, -40, 60) }); scene2.morphTo2D(0); return allLabelsReady().then(function() { const actual = scene2.frameState.commandList[0].boundingVolume; const projectedPositions = [ projection.project(ellipsoid.cartesianToCartographic(one.position)), projection.project(ellipsoid.cartesianToCartographic(two.position)) ]; const expected = import__531.BoundingSphere.fromPoints(projectedPositions); expected.center = new import__531.Cartesian3( 0, expected.center.x, expected.center.y ); expect(actual.center).toEqualEpsilon( expected.center, import__532.Math.EPSILON8 ); expect(actual.radius).toBeGreaterThan(expected.radius); }); }); it("Label.show throws with undefined", function() { const label = labels.add(); expect(function() { label.show = void 0; }).toThrowDeveloperError(); }); it("Label.position throws with undefined", function() { const label = labels.add(); expect(function() { label.position = void 0; }).toThrowDeveloperError(); }); it("Label.text throws with undefined", function() { const label = labels.add(); expect(function() { label.text = void 0; }).toThrowDeveloperError(); }); it("Label.font throws with undefined", function() { const label = labels.add(); expect(function() { label.font = void 0; }).toThrowDeveloperError(); }); it("Label.fillColor throws with undefined", function() { const label = labels.add(); expect(function() { label.fillColor = void 0; }).toThrowDeveloperError(); }); it("Label.outlineColor throws with undefined", function() { const label = labels.add(); expect(function() { label.outlineColor = void 0; }).toThrowDeveloperError(); }); it("Label.outlineWidth throws with undefined", function() { const label = labels.add(); expect(function() { label.outlineWidth = void 0; }).toThrowDeveloperError(); }); it("Label.style throws with undefined", function() { const label = labels.add(); expect(function() { label.style = void 0; }).toThrowDeveloperError(); }); it("Label.pixelOffset throws with undefined", function() { const label = labels.add(); expect(function() { label.pixelOffset = void 0; }).toThrowDeveloperError(); }); it("Label.eyeOffset throws with undefined", function() { const label = labels.add(); expect(function() { label.eyeOffset = void 0; }).toThrowDeveloperError(); }); it("Label.horizontalOrigin throws with undefined", function() { const label = labels.add(); expect(function() { label.horizontalOrigin = void 0; }).toThrowDeveloperError(); }); it("Label.verticalOrigin throws with undefined", function() { const label = labels.add(); expect(function() { label.verticalOrigin = void 0; }).toThrowDeveloperError(); }); it("Label.scale throws with undefined", function() { const label = labels.add(); expect(function() { label.scale = void 0; }).toThrowDeveloperError(); }); it("Label.computeScreenSpacePosition throws with undefined scene", function() { const label = labels.add(); expect(function() { label.computeScreenSpacePosition(); }).toThrowDeveloperError(); }); it("Label.translucencyByDistance throws with nearDistance === farDistance", function() { const label = labels.add(); const translucency = new import__531.NearFarScalar(2e5, 1, 2e5, 0); expect(function() { label.translucencyByDistance = translucency; }).toThrowDeveloperError(); }); it("Label.pixelOffsetScaleByDistance throws with nearDistance === farDistance", function() { const label = labels.add(); const pixelOffsetScale = new import__531.NearFarScalar(2e5, 1, 2e5, 0); expect(function() { label.pixelOffsetScaleByDistance = pixelOffsetScale; }).toThrowDeveloperError(); }); it("Label.scaleByDistance throws with nearDistance === farDistance", function() { const label = labels.add(); const scaleByDistance = new import__531.NearFarScalar(2e5, 1, 2e5, 0); expect(function() { label.scaleByDistance = scaleByDistance; }).toThrowDeveloperError(); }); it("new label throws with invalid translucencyByDistance (nearDistance === farDistance)", function() { const translucency = new import__531.NearFarScalar(2e5, 1, 2e5, 0); expect(function() { labels.add({ translucencyByDistance: translucency }); }).toThrowDeveloperError(); }); it("new label throws with invalid pixelOffsetScaleByDistance (nearDistance === farDistance)", function() { const pixelOffsetScale = new import__531.NearFarScalar(2e5, 1, 2e5, 0); expect(function() { labels.add({ pixelOffsetScaleByDistance: pixelOffsetScale }); }).toThrowDeveloperError(); }); it("new label throws with invalid scaleByDistance (nearDistance === farDistance)", function() { const scaleByDistance = new import__531.NearFarScalar(2e5, 1, 2e5, 0); expect(function() { labels.add({ scaleByDistance }); }).toThrowDeveloperError(); }); it("Label.translucencyByDistance throws with nearDistance > farDistance", function() { const label = labels.add(); const translucency = new import__531.NearFarScalar(1e9, 1, 1e5, 1); expect(function() { label.translucencyByDistance = translucency; }).toThrowDeveloperError(); }); it("Label.pixelOffsetScaleByDistance throws with nearDistance > farDistance", function() { const label = labels.add(); const pixelOffsetScale = new import__531.NearFarScalar(1e9, 1, 1e5, 1); expect(function() { label.pixelOffsetScaleByDistance = pixelOffsetScale; }).toThrowDeveloperError(); }); it("Label.scaleByDistance throws with nearDistance > farDistance", function() { const label = labels.add(); const scaleByDistance = new import__531.NearFarScalar(1e9, 1, 1e5, 1); expect(function() { label.scaleByDistance = scaleByDistance; }).toThrowDeveloperError(); }); it("destroys texture atlas when destroying", function() { labels.add({ text: "a" }); return allLabelsReady().then(function() { const textureAtlas = labels._textureAtlas; expect(textureAtlas.isDestroyed()).toBe(false); scene2.primitives.removeAll(); expect(textureAtlas.isDestroyed()).toBe(true); }); }); describe("height referenced labels", function() { beforeEach(function() { scene2.globe = new import__531.Globe(); labelsWithHeight = new import__531.LabelCollection({ scene: scene2 }); scene2.primitives.add(labelsWithHeight); }); it("explicitly constructs a label with height reference", function() { const l = labelsWithHeight.add({ text: "test", heightReference: import__531.HeightReference.CLAMP_TO_GROUND }); expect(l.heightReference).toEqual(import__531.HeightReference.CLAMP_TO_GROUND); }); it("set label height reference property", function() { const l = labelsWithHeight.add({ text: "test" }); l.heightReference = import__531.HeightReference.CLAMP_TO_GROUND; expect(l.heightReference).toEqual(import__531.HeightReference.CLAMP_TO_GROUND); }); it("creating with a height reference creates a height update callback", function() { spyOn(scene2, "updateHeight"); const position = import__531.Cartesian3.fromDegrees(-72, 40); labelsWithHeight.add({ heightReference: import__531.HeightReference.CLAMP_TO_GROUND, position }); expect(scene2.updateHeight).toHaveBeenCalledWith( import__531.Cartographic.fromCartesian(position), jasmine.any(Function), import__531.HeightReference.CLAMP_TO_GROUND ); }); it("set height reference property creates a height update callback", function() { spyOn(scene2, "updateHeight"); const position = import__531.Cartesian3.fromDegrees(-72, 40); const l = labelsWithHeight.add({ position }); l.heightReference = import__531.HeightReference.CLAMP_TO_GROUND; expect(scene2.updateHeight).toHaveBeenCalledWith( import__531.Cartographic.fromCartesian(position), jasmine.any(Function), import__531.HeightReference.CLAMP_TO_GROUND ); }); it("updates the callback when the height reference changes", function() { spyOn(scene2, "updateHeight"); const position = import__531.Cartesian3.fromDegrees(-72, 40); const l = labelsWithHeight.add({ heightReference: import__531.HeightReference.CLAMP_TO_GROUND, position }); expect(scene2.updateHeight).toHaveBeenCalledWith( import__531.Cartographic.fromCartesian(position), jasmine.any(Function), import__531.HeightReference.CLAMP_TO_GROUND ); l.heightReference = import__531.HeightReference.RELATIVE_TO_GROUND; expect(scene2.updateHeight).toHaveBeenCalledWith( import__531.Cartographic.fromCartesian(position), jasmine.any(Function), import__531.HeightReference.RELATIVE_TO_GROUND ); }); it("removes the callback when the height reference changes", function() { const removeCallback = jasmine.createSpy(); spyOn(scene2, "updateHeight").and.returnValue(removeCallback); const position = import__531.Cartesian3.fromDegrees(-72, 40); const l = labelsWithHeight.add({ heightReference: import__531.HeightReference.CLAMP_TO_GROUND, position }); l.heightReference = import__531.HeightReference.NONE; expect(removeCallback).toHaveBeenCalled(); }); it("changing the position updates the callback", function() { const removeCallback = jasmine.createSpy(); spyOn(scene2, "updateHeight").and.returnValue(removeCallback); let position = import__531.Cartesian3.fromDegrees(-72, 40); const l = labelsWithHeight.add({ heightReference: import__531.HeightReference.CLAMP_TO_GROUND, position }); expect(scene2.updateHeight).toHaveBeenCalledWith( import__531.Cartographic.fromCartesian(position), jasmine.any(Function), import__531.HeightReference.CLAMP_TO_GROUND ); position = l.position = import__531.Cartesian3.fromDegrees(-73, 40); expect(removeCallback).toHaveBeenCalled(); expect(scene2.updateHeight).toHaveBeenCalledWith( import__531.Cartographic.fromCartesian(position), jasmine.any(Function), import__531.HeightReference.CLAMP_TO_GROUND ); }); it("callback updates the position", function() { let invokeCallback; spyOn(scene2, "updateHeight").and.callFake( (cartographic2, updateCallback) => { invokeCallback = (height) => { cartographic2.height = height; updateCallback(cartographic2); }; } ); const position = import__531.Cartesian3.fromDegrees(-72, 40); const l = labelsWithHeight.add({ heightReference: import__531.HeightReference.CLAMP_TO_GROUND, position }); expect(scene2.updateHeight).toHaveBeenCalled(); let cartographic = scene2.globe.ellipsoid.cartesianToCartographic( l._clampedPosition ); expect(cartographic.height).toEqual(0); invokeCallback(100); cartographic = scene2.globe.ellipsoid.cartesianToCartographic( l._clampedPosition ); expect(cartographic.height).toEqualEpsilon(100, import__532.Math.EPSILON9); }); it("resets the clamped position when HeightReference.NONE", function() { spyOn(scene2.camera, "update"); const l = labelsWithHeight.add({ heightReference: import__531.HeightReference.CLAMP_TO_GROUND, text: "t", position: import__531.Cartesian3.fromDegrees(-72, 40) }); return allLabelsReady().then(function() { expect(l._clampedPosition).toBeDefined(); expect(l._glyphs[0].billboard._clampedPosition).toBeDefined(); l.heightReference = import__531.HeightReference.NONE; expect(l._clampedPosition).toBeUndefined(); expect(l._glyphs[0].billboard._clampedPosition).toBeUndefined(); }); }); it("clears the billboard height reference callback when the label is removed", function() { spyOn(scene2.camera, "update"); const l = labelsWithHeight.add({ heightReference: import__531.HeightReference.CLAMP_TO_GROUND, text: "t", position: import__531.Cartesian3.fromDegrees(-72, 40) }); return allLabelsReady().then(function() { const billboard = l._glyphs[0].billboard; expect(billboard._removeCallbackFunc).toBeDefined(); const spy = spyOn(billboard, "_removeCallbackFunc"); labelsWithHeight.remove(l); expect(spy).toHaveBeenCalled(); expect( labelsWithHeight._spareBillboards[0]._removeCallbackFunc ).toBeUndefined(); }); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/LightSpec.js var import__533 = __toESM(require_Cesium(), 1); describe("Scene/Light", function() { it("throws", function() { const light = new import__533.Light(); expect(function() { return light.color; }).toThrowDeveloperError(); expect(function() { return light.intensity; }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/MapboxImageryProviderSpec.js var import__534 = __toESM(require_Cesium(), 1); var import__535 = __toESM(require_Cesium(), 1); describe("Scene/MapboxImageryProvider", function() { beforeEach(function() { import__534.RequestScheduler.clearForSpecs(); }); afterEach(function() { import__534.Resource._Implementations.createImage = import__534.Resource._DefaultImplementations.createImage; }); it("conforms to ImageryProvider interface", function() { expect(import__534.MapboxImageryProvider).toConformToInterface(import__534.ImageryProvider); }); it("requires the mapId to be specified", function() { expect(function() { return new import__534.MapboxImageryProvider({ accessToken: "test-token" }); }).toThrowDeveloperError(); }); it("returns valid value for hasAlphaChannel", function() { const provider = new import__534.MapboxImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", mapId: "test-id" }); expect(typeof provider.hasAlphaChannel).toBe("boolean"); }); it("supports a slash at the end of the URL", function() { const provider = new import__534.MapboxImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", mapId: "test-id" }); spyOn(import__534.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).not.toContain("//"); import__534.Resource._DefaultImplementations.createImage( new import__534.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__534.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("supports no slash at the endof the URL", function() { const provider = new import__534.MapboxImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server", mapId: "test-id" }); spyOn(import__534.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toContain("made/up/mapbox/server/"); import__534.Resource._DefaultImplementations.createImage( new import__534.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__534.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("requestImage returns a promise for an image and loads it for cross-origin use", function() { const provider = new import__534.MapboxImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", mapId: "test-id" }); expect(provider.url).toEqual( "made/up/mapbox/server/test-id/{z}/{x}/{y}.png?access_token=test-token" ); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__534.WebMercatorTilingScheme); expect(provider.rectangle).toEqual(new import__534.WebMercatorTilingScheme().rectangle); spyOn(import__534.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { import__534.Resource._DefaultImplementations.createImage( new import__534.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__534.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("rectangle passed to constructor does not affect tile numbering", function() { const rectangle = new import__534.Rectangle(0.1, 0.2, 0.3, 0.4); const provider = new import__534.MapboxImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", mapId: "test-id", rectangle }); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__534.WebMercatorTilingScheme); expect(provider.rectangle).toEqualEpsilon(rectangle, import__535.Math.EPSILON14); expect(provider.tileDiscardPolicy).toBeUndefined(); spyOn(import__534.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toContain("/0/0/0"); import__534.Resource._DefaultImplementations.createImage( new import__534.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__534.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("uses maximumLevel passed to constructor", function() { const provider = new import__534.MapboxImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", mapId: "test-id", maximumLevel: 5 }); expect(provider.maximumLevel).toEqual(5); }); it("uses minimumLevel passed to constructor", function() { const provider = new import__534.MapboxImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", mapId: "test-id", minimumLevel: 1 }); expect(provider.minimumLevel).toEqual(1); }); it("when no credit is supplied, the provider adds a default credit", function() { const provider = new import__534.MapboxImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", mapId: "test-id" }); expect(provider.credit).toBe(import__534.MapboxImageryProvider._defaultCredit); }); it("turns the supplied credit into a logo", function() { const creditText = "Thanks to our awesome made up source of this imagery!"; const providerWithCredit = new import__534.MapboxImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", mapId: "test-id", credit: creditText }); expect(providerWithCredit.credit.html).toEqual(creditText); }); it("raises error event when image cannot be loaded", function() { const provider = new import__534.MapboxImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", mapId: "test-id" }); const layer = new import__534.ImageryLayer(provider); let tries = 0; provider.errorEvent.addEventListener(function(error) { expect(error.timesRetried).toEqual(tries); ++tries; if (tries < 3) { error.retry = true; } setTimeout(function() { import__534.RequestScheduler.update(); }, 1); }); import__534.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { if (tries === 2) { import__534.Resource._DefaultImplementations.createImage( new import__534.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); } else { setTimeout(function() { deferred.reject(); }, 1); } }; const imagery = new import__534.Imagery(layer, 0, 0, 0); imagery.addReference(); layer._requestImagery(imagery); import__534.RequestScheduler.update(); return pollToPromise_default(function() { return imagery.state === import__534.ImageryState.RECEIVED; }).then(function() { expect(imagery.image).toBeImageOrImageBitmap(); expect(tries).toEqual(2); imagery.releaseReference(); }); }); it("appends specified format", function() { const provider = new import__534.MapboxImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", mapId: "test-id", format: "@2x.png" }); spyOn(import__534.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect( /made\/up\/mapbox\/server\/test-id\/0\/0\/0@2x\.png\?access_token=/.test( request.url ) ).toBe(true); import__534.Resource._DefaultImplementations.createImage( new import__534.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__534.Resource._Implementations.createImage).toHaveBeenCalled(); }); }); it("adds missing period for format", function() { const provider = new import__534.MapboxImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", mapId: "test-id", format: "png" }); spyOn(import__534.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect( /made\/up\/mapbox\/server\/test-id\/0\/0\/0\.png\?access_token=/.test( request.url ) ).toBe(true); import__534.Resource._DefaultImplementations.createImage( new import__534.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__534.Resource._Implementations.createImage).toHaveBeenCalled(); }); }); }); // packages/engine/Specs/Scene/MapboxStyleImageryProviderSpec.js var import__536 = __toESM(require_Cesium(), 1); var import__537 = __toESM(require_Cesium(), 1); describe("Scene/MapboxStyleImageryProvider", function() { beforeEach(function() { import__536.RequestScheduler.clearForSpecs(); }); afterEach(function() { import__536.Resource._Implementations.createImage = import__536.Resource._DefaultImplementations.createImage; }); it("conforms to ImageryProvider interface", function() { expect(import__536.MapboxStyleImageryProvider).toConformToInterface(import__536.ImageryProvider); }); it("requires the styleId to be specified", function() { expect(function() { return new import__536.MapboxStyleImageryProvider({ accessToken: "test-token" }); }).toThrowDeveloperError("styleId is required"); }); it("returns valid value for hasAlphaChannel", function() { const provider = new import__536.MapboxStyleImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", styleId: "test-id" }); expect(typeof provider.hasAlphaChannel).toBe("boolean"); }); it("supports a slash at the end of the URL", function() { const provider = new import__536.MapboxStyleImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", styleId: "test-id" }); spyOn(import__536.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).not.toContain("//"); import__536.Resource._DefaultImplementations.createImage( new import__536.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__536.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("supports no slash at the endof the URL", function() { const provider = new import__536.MapboxStyleImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server", styleId: "test-id" }); spyOn(import__536.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toContain("made/up/mapbox/server/"); import__536.Resource._DefaultImplementations.createImage( new import__536.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__536.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("requestImage returns a promise for an image and loads it for cross-origin use", function() { const provider = new import__536.MapboxStyleImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", styleId: "test-id" }); expect(provider.url).toEqual( "made/up/mapbox/server/mapbox/test-id/tiles/512/{z}/{x}/{y}?access_token=test-token" ); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__536.WebMercatorTilingScheme); expect(provider.rectangle).toEqual(new import__536.WebMercatorTilingScheme().rectangle); spyOn(import__536.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { import__536.Resource._DefaultImplementations.createImage( new import__536.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__536.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("rectangle passed to constructor does not affect tile numbering", function() { const rectangle = new import__536.Rectangle(0.1, 0.2, 0.3, 0.4); const provider = new import__536.MapboxStyleImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", styleId: "test-id", rectangle }); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__536.WebMercatorTilingScheme); expect(provider.rectangle).toEqualEpsilon(rectangle, import__537.Math.EPSILON14); expect(provider.tileDiscardPolicy).toBeUndefined(); spyOn(import__536.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toContain("/0/0/0"); import__536.Resource._DefaultImplementations.createImage( new import__536.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__536.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("uses maximumLevel passed to constructor", function() { const provider = new import__536.MapboxStyleImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", styleId: "test-id", maximumLevel: 5 }); expect(provider.maximumLevel).toEqual(5); }); it("uses minimumLevel passed to constructor", function() { const provider = new import__536.MapboxStyleImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", styleId: "test-id", minimumLevel: 1 }); expect(provider.minimumLevel).toEqual(1); }); it("when no credit is supplied, the provider adds a default credit", function() { const provider = new import__536.MapboxStyleImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", styleId: "test-id" }); expect(provider.credit).toBe(import__536.MapboxStyleImageryProvider._defaultCredit); }); it("turns the supplied credit into a logo", function() { const creditText = "Thanks to our awesome made up source of this imagery!"; const providerWithCredit = new import__536.MapboxStyleImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", styleId: "test-id", credit: creditText }); expect(providerWithCredit.credit.html).toEqual(creditText); }); it("raises error event when image cannot be loaded", function() { const provider = new import__536.MapboxStyleImageryProvider({ accessToken: "test-token", url: "made/up/mapbox/server/", styleId: "test-id" }); const layer = new import__536.ImageryLayer(provider); let tries = 0; provider.errorEvent.addEventListener(function(error) { expect(error.timesRetried).toEqual(tries); ++tries; if (tries < 3) { error.retry = true; } setTimeout(function() { import__536.RequestScheduler.update(); }, 1); }); import__536.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { if (tries === 2) { import__536.Resource._DefaultImplementations.createImage( new import__536.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); } else { setTimeout(function() { deferred.reject(); }, 1); } }; const imagery = new import__536.Imagery(layer, 0, 0, 0); imagery.addReference(); layer._requestImagery(imagery); import__536.RequestScheduler.update(); return pollToPromise_default(function() { return imagery.state === import__536.ImageryState.RECEIVED; }).then(function() { expect(imagery.image).toBeImageOrImageBitmap(); expect(tries).toEqual(2); imagery.releaseReference(); }); }); it("contains specified url", function() { const provider = new import__536.MapboxStyleImageryProvider({ accessToken: "test-token", url: "http://fake.map.com", styleId: "test-id" }); spyOn(import__536.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toContain("http://fake.map.com"); import__536.Resource._DefaultImplementations.createImage( new import__536.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0); }); it("contains specified username", function() { const provider = new import__536.MapboxStyleImageryProvider({ accessToken: "test-token", styleId: "test-id", username: "fakeUsername" }); spyOn(import__536.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toContain( "https://api.mapbox.com/styles/v1/fakeUsername" ); import__536.Resource._DefaultImplementations.createImage( new import__536.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0); }); it("contains specified tilesize", function() { const provider = new import__536.MapboxStyleImageryProvider({ accessToken: "test-token", styleId: "test-id", tilesize: 256 }); spyOn(import__536.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toContain( "https://api.mapbox.com/styles/v1/mapbox/test-id/tiles/256" ); import__536.Resource._DefaultImplementations.createImage( new import__536.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0); }); it("enables @2x scale factor", function() { const provider = new import__536.MapboxStyleImageryProvider({ accessToken: "test-token", styleId: "test-id", scaleFactor: true }); spyOn(import__536.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toContain( "https://api.mapbox.com/styles/v1/mapbox/test-id/tiles/512/0/0/0@2x" ); import__536.Resource._DefaultImplementations.createImage( new import__536.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0); }); }); // packages/engine/Specs/Scene/MaterialAppearanceSpec.js var import__538 = __toESM(require_Cesium(), 1); describe( "Scene/MaterialAppearance", function() { let scene2; let primitive; const rectangle = import__538.Rectangle.fromDegrees(-10, -10, 10, 10); const backgroundColor = [0, 0, 255, 255]; beforeAll(function() { scene2 = createScene_default(); import__538.Color.unpack(backgroundColor, 0, scene2.backgroundColor); scene2.primitives.destroyPrimitives = false; scene2.camera.setView({ destination: rectangle }); }); afterEach(function() { scene2.primitives.removeAll(); primitive = primitive && primitive.destroy(); }); afterAll(function() { scene2.destroyForSpecs(); }); function createPrimitive(vertexFormat) { vertexFormat = (0, import__538.defaultValue)( vertexFormat, import__538.MaterialAppearance.MaterialSupport.ALL.vertexFormat ); primitive = new import__538.Primitive({ geometryInstances: new import__538.GeometryInstance({ geometry: new import__538.RectangleGeometry({ vertexFormat, rectangle }), attributes: { color: new import__538.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }), asynchronous: false }); } it("constructor", function() { const a = new import__538.MaterialAppearance(); expect(a.materialSupport).toEqual( import__538.MaterialAppearance.MaterialSupport.TEXTURED ); expect(a.material).toBeDefined(); expect(a.material.type).toEqual(import__538.Material.ColorType); expect(a.vertexShaderSource).toEqual( import__538.MaterialAppearance.MaterialSupport.TEXTURED.vertexShaderSource ); expect(a.fragmentShaderSource).toEqual( import__538.MaterialAppearance.MaterialSupport.TEXTURED.fragmentShaderSource ); expect(a.renderState).toEqual( import__538.Appearance.getDefaultRenderState(true, false) ); expect(a.vertexFormat).toEqual( import__538.MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat ); expect(a.flat).toEqual(false); expect(a.faceForward).toEqual(true); expect(a.translucent).toEqual(true); expect(a.closed).toEqual(false); }); it("renders basic", function() { createPrimitive(import__538.MaterialAppearance.MaterialSupport.BASIC.vertexFormat); primitive.appearance = new import__538.MaterialAppearance({ materialSupport: import__538.MaterialAppearance.MaterialSupport.BASIC, translucent: false, closed: true, material: import__538.Material.fromType(import__538.Material.DotType) }); expect(scene2).toRender(backgroundColor); scene2.primitives.add(primitive); expect(scene2).notToRender(backgroundColor); }); it("renders textured", function() { createPrimitive(import__538.MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat); primitive.appearance = new import__538.MaterialAppearance({ materialSupport: import__538.MaterialAppearance.MaterialSupport.TEXTURED, translucent: false, closed: true, material: import__538.Material.fromType(import__538.Material.ImageType, { image: "../Data/images/Red16x16.png" }) }); expect(scene2).toRender(backgroundColor); scene2.primitives.add(primitive); expect(scene2).notToRender(backgroundColor); }); it("renders all", function() { createPrimitive(import__538.MaterialAppearance.MaterialSupport.ALL.vertexFormat); primitive.appearance = new import__538.MaterialAppearance({ materialSupport: import__538.MaterialAppearance.MaterialSupport.ALL, translucent: false, closed: true, material: import__538.Material.fromType(import__538.Material.NormalMapType) }); expect(scene2).toRender(backgroundColor); scene2.primitives.add(primitive); expect(scene2).notToRender(backgroundColor); }); }, "WebGL" ); // packages/engine/Specs/Scene/MaterialSpec.js var import__539 = __toESM(require_Cesium(), 1); describe( "Scene/Material", function() { let scene2; const rectangle = import__539.Rectangle.fromDegrees(-10, -10, 10, 10); let polygon; const backgroundColor = [0, 0, 128, 255]; let polylines; let polyline; beforeAll(function() { scene2 = createScene_default(); import__539.Color.fromBytes( backgroundColor[0], backgroundColor[1], backgroundColor[2], backgroundColor[3], scene2.backgroundColor ); scene2.primitives.destroyPrimitives = false; scene2.camera.setView({ destination: rectangle }); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { const vertexFormat = import__539.MaterialAppearance.MaterialSupport.ALL.vertexFormat; polygon = new import__539.Primitive({ geometryInstances: new import__539.GeometryInstance({ geometry: new import__539.RectangleGeometry({ vertexFormat, rectangle }) }), asynchronous: false }); polygon.appearance = new import__539.MaterialAppearance({ materialSupport: import__539.MaterialAppearance.MaterialSupport.ALL, translucent: false, closed: true }); polylines = new import__539.PolylineCollection(); polyline = polylines.add({ positions: import__539.Cartesian3.fromDegreesArray( [-50, 0, 50, 0], import__539.Ellipsoid.WGS84 ), width: 5 }); }); afterEach(function() { scene2.primitives.removeAll(); polygon = polygon && polygon.destroy(); polylines = polylines && polylines.destroy(); }); function renderMaterial(material, ignoreBackground, callback) { ignoreBackground = (0, import__539.defaultValue)(ignoreBackground, false); polygon.appearance.material = material; if (!ignoreBackground) { expect(scene2).toRender(backgroundColor); } scene2.primitives.removeAll(); scene2.primitives.add(polygon); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual(backgroundColor); if ((0, import__539.defined)(callback)) { callback(rgba); } }); } function renderPolylineMaterial(material) { polyline.material = material; expect(scene2).toRender(backgroundColor); scene2.primitives.removeAll(); scene2.primitives.add(polylines); let result; expect(scene2).toRenderAndCall(function(rgba) { result = rgba; expect(rgba).not.toEqual(backgroundColor); }); return result; } function verifyMaterial(type) { const material = new import__539.Material({ strict: true, fabric: { type } }); renderMaterial(material); } function verifyPolylineMaterial(type) { const material = new import__539.Material({ strict: true, fabric: { type } }); renderPolylineMaterial(material); } it("draws Color built-in material", function() { verifyMaterial("Color"); }); it("draws Image built-in material", function() { verifyMaterial("Image"); }); it("draws DiffuseMap built-in material", function() { verifyMaterial("DiffuseMap"); }); it("draws AlphaMap built-in material", function() { verifyMaterial("AlphaMap"); }); it("draws SpecularMap built-in material", function() { verifyMaterial("SpecularMap"); }); it("draws EmissionMap built-in material", function() { verifyMaterial("EmissionMap"); }); it("draws BumpMap built-in material", function() { verifyMaterial("BumpMap"); }); it("draws NormalMap built-in material", function() { verifyMaterial("NormalMap"); }); it("draws Grid built-in material", function() { verifyMaterial("Grid"); }); it("draws Stripe built-in material", function() { verifyMaterial("Stripe"); }); it("draws Checkerboard built-in material", function() { verifyMaterial("Checkerboard"); }); it("draws Dot built-in material", function() { verifyMaterial("Dot"); }); it("draws Water built-in material", function() { verifyMaterial("Water"); }); it("draws RimLighting built-in material", function() { verifyMaterial("RimLighting"); }); it("draws Fade built-in material", function() { verifyMaterial("Fade"); }); it("draws PolylineArrow built-in material", function() { verifyPolylineMaterial("PolylineArrow"); }); it("draws PolylineDash built-in material", function() { verifyPolylineMaterial("PolylineDash"); }); it("draws PolylineGlow built-in material", function() { verifyPolylineMaterial("PolylineGlow"); }); it("draws PolylineOutline built-in material", function() { verifyPolylineMaterial("PolylineOutline"); }); it("gets the material type", function() { const material = new import__539.Material({ strict: true, fabric: { type: "Color" } }); expect(material.type).toEqual("Color"); }); it("creates opaque/translucent materials", function() { let material = new import__539.Material({ translucent: true, strict: true, fabric: { type: "Color" } }); expect(material.isTranslucent()).toEqual(true); material = new import__539.Material({ translucent: false, strict: true, fabric: { type: "Color" } }); expect(material.isTranslucent()).toEqual(false); }); it("creates a new material type and builds off of it", function() { const material1 = new import__539.Material({ strict: true, fabric: { type: "New", components: { diffuse: "vec3(0.0, 0.0, 0.0)" } } }); const material2 = new import__539.Material({ strict: true, fabric: { materials: { first: { type: "New" } }, components: { diffuse: "first.diffuse" } } }); renderMaterial(material1); renderMaterial(material2, true); }); it("accesses material properties after construction", function() { const material = new import__539.Material({ strict: true, fabric: { materials: { first: { type: "DiffuseMap" } }, uniforms: { value: { x: 0, y: 0, z: 0 } }, components: { diffuse: "value + first.diffuse" } } }); material.uniforms.value.x = 1; material.materials.first.uniforms.repeat.x = 2; renderMaterial(material); }); it("creates a material inside a material inside a material", function() { const material = new import__539.Material({ strict: true, fabric: { materials: { first: { materials: { second: { components: { diffuse: "vec3(0.0, 0.0, 0.0)" } } }, components: { diffuse: "second.diffuse" } } }, components: { diffuse: "first.diffuse" } } }); renderMaterial(material); }); it("creates a material with an image uniform", function() { const material = new import__539.Material({ strict: true, fabric: { type: "DiffuseMap", uniforms: { image: "./Data/Images/Blue.png" } } }); renderMaterial(material); }); it("creates a material with an image resource uniform", function() { const material = new import__539.Material({ strict: true, fabric: { type: "DiffuseMap", uniforms: { image: new import__539.Resource("./Data/Images/Blue.png") } } }); renderMaterial(material); }); it("creates a material with an image canvas uniform", function() { const canvas = document.createElement("canvas"); const context2D = canvas.getContext("2d"); context2D.width = 1; context2D.height = 1; context2D.fillStyle = "rgb(0,0,255)"; context2D.fillRect(0, 0, 1, 1); const material = new import__539.Material({ strict: true, fabric: { type: "DiffuseMap", uniforms: { image: canvas } } }); renderMaterial(material); }); it("creates a material with an KTX2 compressed image uniform", function() { let compressedUrl; if (import__539.FeatureDetection.supportsBasis(scene2)) { compressedUrl = "./Data/Images/Green4x4.ktx2"; } else { return; } const material = new import__539.Material({ strict: true, fabric: { type: "DiffuseMap", uniforms: { image: compressedUrl } } }); renderMaterial(material); }); it("creates a material with a cube map uniform", function() { const material = new import__539.Material({ strict: true, fabric: { uniforms: { cubeMap: { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" } }, source: "uniform samplerCube cubeMap;\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n material.diffuse = czm_textureCube(cubeMap, vec3(1.0)).xyz;\n return material;\n}\n" } }); renderMaterial(material); }); it("does not crash if source uniform is formatted differently", function() { const material = new import__539.Material({ strict: true, fabric: { uniforms: { cubeMap: { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" } }, source: "uniform samplerCube cubeMap ;\r\nczm_material czm_getMaterial(czm_materialInput materialInput)\r\n{\r\n czm_material material = czm_getDefaultMaterial(materialInput);\r\n material.diffuse = czm_textureCube(cubeMap, vec3(1.0)).xyz;\r\n return material;\r\n}" } }); renderMaterial(material); }); it("creates a material with a boolean uniform", function() { const material = new import__539.Material({ strict: true, fabric: { uniforms: { value: true }, components: { diffuse: "float(value) * vec3(1.0)" } } }); renderMaterial(material); }); it("create a material with a matrix uniform", function() { const material1 = new import__539.Material({ strict: true, fabric: { uniforms: { value: [0.5, 0.5, 0.5, 0.5] }, components: { diffuse: "vec3(value[0][0], value[0][1], value[1][0])", alpha: "value[1][1]" } } }); renderMaterial(material1); const material2 = new import__539.Material({ strict: true, fabric: { uniforms: { value: [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5] }, components: { diffuse: "vec3(value[0][0], value[0][1], value[1][0])", alpha: "value[2][2]" } } }); renderMaterial(material2, true); const material3 = new import__539.Material({ strict: true, fabric: { uniforms: { value: [ 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5 ] }, components: { diffuse: "vec3(value[0][0], value[0][1], value[1][0])", alpha: "value[3][3]" } } }); renderMaterial(material3, true); }); it("creates a material using unusual uniform and material names", function() { const material = new import__539.Material({ strict: true, fabric: { uniforms: { i: 0.5 }, materials: { d: { type: "Color" }, diffuse: { type: "Color" } }, components: { diffuse: "(d.diffuse + diffuse.diffuse)*i", specular: "i" } } }); renderMaterial(material); }); it("create a material using fromType", function() { const material = import__539.Material.fromType("Color"); renderMaterial(material); }); it("create material using fromType and overide default uniforms", function() { const material1 = import__539.Material.fromType("Color", { color: new import__539.Color(0, 1, 0, 1) }); renderMaterial(material1, false, function(rgba) { expect(rgba).toEqual([0, 255, 0, 255]); }); }); it("create multiple materials from the same type", function() { const material1 = import__539.Material.fromType("Color", { color: new import__539.Color(0, 1, 0, 1) }); const material2 = import__539.Material.fromType("Color", { color: new import__539.Color(1, 0, 0, 1) }); expect(material1.shaderSource).toEqual(material2.shaderSource); renderMaterial(material2, false, function(rgba) { expect(rgba).toEqual([255, 0, 0, 255]); }); renderMaterial(material1, true, function(rgba) { expect(rgba).toEqual([0, 255, 0, 255]); }); }); it("create material with sub-materials of the same type", function() { const material = new import__539.Material({ fabric: { materials: { color1: { type: "Color", uniforms: { color: new import__539.Color(0, 1, 0, 1) } }, color2: { type: "Color", uniforms: { color: new import__539.Color(0, 0, 1, 1) } } }, components: { diffuse: "color1.diffuse + color2.diffuse" } } }); renderMaterial(material, false, function(rgba) { expect(rgba).toEqual([0, 255, 255, 255]); }); }); it("creates material with custom texture filter", function() { const materialLinear = new import__539.Material({ fabric: { type: "DiffuseMap", uniforms: { image: "./Data/Images/BlueOverRed.png" } }, minificationFilter: import__539.TextureMinificationFilter.LINEAR, magnificationFilter: import__539.TextureMagnificationFilter.LINEAR }); const materialNearest = new import__539.Material({ fabric: { type: "DiffuseMap", uniforms: { image: "./Data/Images/BlueOverRed.png" } }, minificationFilter: import__539.TextureMinificationFilter.NEAREST, magnificationFilter: import__539.TextureMagnificationFilter.NEAREST }); const purple = [127, 0, 127, 255]; const ignoreBackground = true; renderMaterial(materialLinear, ignoreBackground); return pollToPromise_default(function() { const imageLoaded = materialLinear._loadedImages.length !== 0; scene2.renderForSpecs(); return imageLoaded; }).then(function() { renderMaterial(materialLinear, ignoreBackground, function(rgba) { expect(rgba).toEqualEpsilon(purple, 1); }); }).then(function() { renderMaterial(materialNearest, ignoreBackground); return pollToPromise_default(function() { const imageLoaded = materialNearest._loadedImages.length !== 0; scene2.renderForSpecs(); return imageLoaded; }).then(function() { renderMaterial(materialNearest, ignoreBackground, function(rgba) { expect(rgba).not.toEqualEpsilon(purple, 1); }); }); }); }); it("handles when material image is undefined", function() { const material = import__539.Material.fromType(import__539.Material.ImageType, { image: void 0, color: import__539.Color.RED }); renderMaterial(material, false, function(rgba) { expect(rgba).toEqual([255, 0, 0, 255]); }); }); it("handles when material image is set to default image", function() { const material = import__539.Material.fromType(import__539.Material.ImageType, { image: import__539.Material.DefaultImageId, color: import__539.Color.RED }); renderMaterial(material, false, function(rgba) { expect(rgba).toEqual([255, 0, 0, 255]); }); }); it("handles when material image is changed from undefined to some image", function() { const material = import__539.Material.fromType(import__539.Material.ImageType, { image: void 0, color: import__539.Color.WHITE }); renderMaterial(material, false, function(rgba) { expect(rgba).toEqual([255, 255, 255, 255]); }); material.uniforms.image = "./Data/Images/Green.png"; return pollToPromise_default(function() { renderMaterial(material, true); return material._textures["image"] !== material._defaultTexture; }).then(function() { renderMaterial(material, true, function(rgba) { expect(rgba).toEqual([0, 255, 0, 255]); }); }); }); it("handles when material image is changed from default to some image", function() { const material = import__539.Material.fromType(import__539.Material.ImageType, { image: import__539.Material.DefaultImageId, color: import__539.Color.WHITE }); renderMaterial(material, false, function(rgba) { expect(rgba).toEqual([255, 255, 255, 255]); }); material.uniforms.image = "./Data/Images/Green.png"; return pollToPromise_default(function() { renderMaterial(material, true); return material._textures["image"] !== material._defaultTexture; }).then(function() { renderMaterial(material, true, function(rgba) { expect(rgba).toEqual([0, 255, 0, 255]); }); }); }); it("handles when material image is changed from some image to undefined", function() { const material = import__539.Material.fromType(import__539.Material.ImageType, { image: "./Data/Images/Green.png", color: import__539.Color.WHITE }); return pollToPromise_default(function() { renderMaterial(material, true); return material._textures["image"] !== material._defaultTexture; }).then(function() { renderMaterial(material, true, function(rgba) { expect(rgba).toEqual([0, 255, 0, 255]); }); material.uniforms.image = void 0; renderMaterial(material, true, function(rgba) { expect(rgba).toEqual([255, 255, 255, 255]); }); }); }); it("handles when material image is changed from some image to default", function() { const material = import__539.Material.fromType(import__539.Material.ImageType, { image: "./Data/Images/Green.png", color: import__539.Color.WHITE }); return pollToPromise_default(function() { renderMaterial(material, true); return material._textures["image"] !== material._defaultTexture; }).then(function() { renderMaterial(material, true, function(rgba) { expect(rgba).toEqual([0, 255, 0, 255]); }); material.uniforms.image = import__539.Material.DefaultImageId; renderMaterial(material, true, function(rgba) { expect(rgba).toEqual([255, 255, 255, 255]); }); }); }); it("handles when material image is changed from some image to another", function() { const material = import__539.Material.fromType(import__539.Material.ImageType, { image: "./Data/Images/Green.png", color: import__539.Color.WHITE }); let greenTextureId; return pollToPromise_default(function() { renderMaterial(material, true); return material._textures["image"] !== material._defaultTexture; }).then(function() { greenTextureId = material._textures["image"].id; renderMaterial(material, true, function(rgba) { expect(rgba).toEqual([0, 255, 0, 255]); }); material.uniforms.image = "./Data/Images/Blue.png"; return pollToPromise_default(function() { renderMaterial(material, true); return material._textures["image"].id !== greenTextureId; }).then(function() { renderMaterial(material, true, function(rgba) { expect(rgba).toEqual([0, 0, 255, 255]); }); }); }); }); it("handles when material image is changed from some image to invalid image", function() { const material = import__539.Material.fromType(import__539.Material.ImageType, { image: "./Data/Images/Green.png", color: import__539.Color.WHITE }); let greenTextureId; return pollToPromise_default(function() { renderMaterial(material, true); return material._textures["image"] !== material._defaultTexture; }).then(function() { greenTextureId = material._textures["image"].id; renderMaterial(material, true, function(rgba) { expect(rgba).toEqual([0, 255, 0, 255]); }); material.uniforms.image = "i_dont_exist.png"; return pollToPromise_default(function() { renderMaterial(material, true); return material._textures["image"].id !== greenTextureId; }).then(function() { renderMaterial(material, true, function(rgba) { expect(rgba).toEqual([255, 255, 255, 255]); }); }); }); }); it("throws with source and components in same template", function() { expect(function() { return new import__539.Material({ strict: true, fabric: { components: { diffuse: "vec3(0.0, 0.0, 0.0)" }, source: "czm_material czm_getMaterial(czm_materialInput materialInput)\n{\nczm_material material = czm_getDefaultMaterial(materialInput);\nreturn material;\n}\n" } }); }).toThrowDeveloperError(); expect(function() { return new import__539.Material({ strict: true, fabric: { type: "DiffuseMap", components: { diffuse: "vec3(0.0, 0.0, 0.0)" } } }); }).toThrowDeveloperError(); }); it("throws with duplicate names in materials and uniforms", function() { expect(function() { return new import__539.Material({ strict: false, fabric: { uniforms: { first: 0, second: 0 }, materials: { second: {} } } }); }).toThrowDeveloperError(); }); it("throws with invalid template type", function() { expect(function() { return new import__539.Material({ strict: true, fabric: { invalid: 3 } }); }).toThrowDeveloperError(); }); it("throws with invalid component type", function() { expect(function() { return new import__539.Material({ strict: true, fabric: { components: { difuse: "vec3(0.0, 0.0, 0.0)" } } }); }).toThrowDeveloperError(); }); it("throws with invalid uniform type", function() { expect(function() { return new import__539.Material({ strict: true, fabric: { uniforms: { value: { x: 0, y: 0, z: 0, w: 0, t: 0 } } } }); }).toThrowDeveloperError(); expect(function() { return new import__539.Material({ strict: true, fabric: { uniforms: { value: [0, 0, 0, 0, 0] } } }); }).toThrowDeveloperError(); }); it("throws with unused channels", function() { expect(function() { return new import__539.Material({ strict: true, fabric: { uniforms: { nonexistant: "rgb" } } }); }).toThrowDeveloperError(); const material = new import__539.Material({ strict: false, fabric: { uniforms: { nonexistant: "rgb" } } }); renderMaterial(material); }); it("throws with unused uniform", function() { expect(function() { return new import__539.Material({ strict: true, fabric: { uniforms: { first: { x: 0, y: 0, z: 0 } } } }); }).toThrowDeveloperError(); const material = new import__539.Material({ strict: false, fabric: { uniforms: { first: { x: 0, y: 0, z: 0 } } } }); renderMaterial(material); }); it("throws with unused material", function() { expect(function() { return new import__539.Material({ strict: true, fabric: { materials: { first: { type: "DiffuseMap" } } } }); }).toThrowDeveloperError(); const material = new import__539.Material({ strict: false, fabric: { materials: { first: { type: "DiffuseMap" } } } }); renderMaterial(material); }); it("throws with invalid type sent to fromType", function() { expect(function() { return import__539.Material.fromType("Nothing"); }).toThrowDeveloperError(); }); it("destroys material with texture", function() { const material = import__539.Material.fromType(import__539.Material.DiffuseMapType); material.uniforms.image = "./Data/Images/Green.png"; renderMaterial(material); return pollToPromise_default(function() { const result = material._loadedImages.length !== 0; scene2.renderForSpecs(); return result; }).then(function() { material.destroy(); expect(material.isDestroyed()).toEqual(true); }); }); it("destroys sub-materials", function() { const material = new import__539.Material({ strict: true, fabric: { materials: { diffuseMap: { type: "DiffuseMap" } }, uniforms: { value: { x: 0, y: 0, z: 0 } }, components: { diffuse: "value + diffuseMap.diffuse" } } }); material.materials.diffuseMap.uniforms.image = "./Data/Images/Green.png"; renderMaterial(material); return pollToPromise_default(function() { const result = material.materials.diffuseMap._loadedImages.length !== 0; scene2.renderForSpecs(); return result; }).then(function() { const diffuseMap = material.materials.diffuseMap; material.destroy(); expect(material.isDestroyed()).toEqual(true); expect(diffuseMap.isDestroyed()).toEqual(true); }); }); it("does not destroy default material", function() { const material = import__539.Material.fromType(import__539.Material.DiffuseMapType); renderMaterial(material); material.destroy(); }); }, "WebGL" ); // packages/engine/Specs/Scene/MegatextureSpec.js var import__540 = __toESM(require_Cesium(), 1); describe("Scene/Megatexture", function() { const scene2 = createScene_default(); it("constructs", function() { const dimensions = new import__540.Cartesian3(16, 16, 16); const channelCount = 4; const componentType = import__540.MetadataComponentType.FLOAT32; const textureMemoryByteLength = 16 * 16 * 16 * 4 * 4; expect(function() { return new import__540.Megatexture( scene2.context, dimensions, channelCount, componentType, textureMemoryByteLength / 2 ); }).toThrowError(import__540.RuntimeError); const megatexture = new import__540.Megatexture( scene2.context, dimensions, channelCount, componentType, textureMemoryByteLength ); expect(megatexture.channelCount).toBe(channelCount); expect(megatexture.componentType).toBe(componentType); expect(megatexture.voxelCountPerTile).toEqual(dimensions); }); it("adds data to an existing megatexture", function() { const dimension = 16; const dimensions = new import__540.Cartesian3(dimension, dimension, dimension); const channelCount = 4; const componentType = import__540.MetadataComponentType.UINT16; const tileSize = dimension ** 3 * channelCount * import__540.MetadataComponentType.getSizeInBytes(componentType); const megatexture = new import__540.Megatexture( scene2.context, dimensions, channelCount, componentType ); const data = new Uint16Array(tileSize); const index = megatexture.add(data); expect(index).toBe(0); }); it("throws if trying to add to a full megatexture", function() { const dimension = 16; const dimensions = new import__540.Cartesian3(dimension, dimension, dimension); const channelCount = 1; const componentType = import__540.MetadataComponentType.FLOAT32; const tileSize = dimension ** 3 * channelCount * import__540.MetadataComponentType.getSizeInBytes(componentType); const tileCount = 1; const textureMemoryByteLength = tileCount * tileSize; const megatexture = new import__540.Megatexture( scene2.context, dimensions, channelCount, componentType, textureMemoryByteLength ); const data = new Float32Array(tileSize); megatexture.add(data); expect(function() { return megatexture.add(data); }).toThrowDeveloperError(); }); it("removes tile from a texture", function() { const dimension = 16; const dimensions = new import__540.Cartesian3(dimension, dimension, dimension); const channelCount = 1; const componentType = import__540.MetadataComponentType.FLOAT32; const tileSize = dimension ** 3 * channelCount * import__540.MetadataComponentType.getSizeInBytes(componentType); const tileCount = 4; const textureMemoryByteLength = tileCount * tileSize; const megatexture = new import__540.Megatexture( scene2.context, dimensions, channelCount, componentType, textureMemoryByteLength ); expect(megatexture.occupiedCount).toBe(0); const data = new Float32Array(tileSize); megatexture.add(data); megatexture.add(data); const index2 = megatexture.add(data); megatexture.add(data); expect(megatexture.occupiedCount).toBe(4); expect(function() { return megatexture.add(data); }).toThrowDeveloperError(); megatexture.remove(index2); expect(megatexture.occupiedCount).toBe(3); megatexture.add(data); expect(megatexture.occupiedCount).toBe(4); expect(function() { megatexture.remove(-1); }).toThrowDeveloperError(); expect(function() { megatexture.remove(4); }).toThrowDeveloperError(); }); it("reports approximate memory size", function() { const tileCount = 4; const dimension = 16; const dimensions = new import__540.Cartesian3(dimension, dimension, dimension); const channelCount = 4; const componentType = import__540.MetadataComponentType.FLOAT32; const textureMemoryByteLength = tileCount * dimension ** 3 * channelCount * import__540.MetadataComponentType.getSizeInBytes(componentType); expect( import__540.Megatexture.getApproximateTextureMemoryByteLength( tileCount, dimensions, channelCount, componentType ) ).toBe(textureMemoryByteLength); }); it("destroys", function() { const tileCount = 4; const dimension = 16; const dimensions = new import__540.Cartesian3(dimension, dimension, dimension); const channelCount = 4; const componentType = import__540.MetadataComponentType.FLOAT32; const textureMemoryByteLength = tileCount * dimension ** 3 * channelCount * import__540.MetadataComponentType.getSizeInBytes(componentType); const megatexture = new import__540.Megatexture( scene2.context, dimensions, channelCount, componentType, textureMemoryByteLength ); expect(megatexture.maximumTileCount).toBe(4); megatexture.remove(0); expect(megatexture.isDestroyed()).toBe(false); megatexture.destroy(); expect(megatexture.isDestroyed()).toBe(true); expect(function() { return megatexture.remove(0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/MetadataClassPropertySpec.js var import__541 = __toESM(require_Cesium(), 1); describe("Scene/MetadataClassProperty", function() { it("creates property with default values", function() { const property = import__541.MetadataClassProperty.fromJson({ id: "height", property: { type: "SCALAR", componentType: "FLOAT32" } }); expect(property.id).toBe("height"); expect(property.name).toBeUndefined(); expect(property.description).toBeUndefined(); expect(property.type).toBe(import__541.MetadataType.SCALAR); expect(property.enumType).toBeUndefined(); expect(property.componentType).toBe(import__541.MetadataComponentType.FLOAT32); expect(property.valueType).toBe(import__541.MetadataComponentType.FLOAT32); expect(property.isArray).toBe(false); expect(property.isVariableLengthArray).toBe(false); expect(property.arrayLength).not.toBeDefined(); expect(property.normalized).toBe(false); expect(property.max).toBeUndefined(); expect(property.min).toBeUndefined(); expect(property.default).toBeUndefined(); expect(property.required).toBe(false); expect(property.semantic).toBeUndefined(); expect(property.extras).toBeUndefined(); expect(property.extensions).toBeUndefined(); expect(property._isLegacyExtension).toBe(false); }); it("creates property", function() { const max = [32767, 0, 100]; const min = [-32768, 0, -100]; const propertyDefault = [0, 0, 0]; const extras = { coordinates: [0, 1, 2] }; const extensions = { EXT_other_extension: {} }; const property = import__541.MetadataClassProperty.fromJson({ id: "position", property: { name: "Position", description: "Position (X, Y, Z)", array: true, count: 3, type: "SCALAR", componentType: "INT16", normalized: true, max, min, default: propertyDefault, required: true, semantic: "_POSITION", extras, extensions } }); expect(property.id).toBe("position"); expect(property.name).toBe("Position"); expect(property.description).toBe("Position (X, Y, Z)"); expect(property.type).toBe(import__541.MetadataType.SCALAR); expect(property.enumType).toBeUndefined(); expect(property.componentType).toBe(import__541.MetadataComponentType.INT16); expect(property.valueType).toBe(import__541.MetadataComponentType.INT16); expect(property.isArray).toBe(true); expect(property.isVariableLengthArray).toBe(false); expect(property.arrayLength).toBe(3); expect(property.normalized).toBe(true); expect(property.max).toEqual(max); expect(property.min).toEqual(min); expect(property.default).toEqual(propertyDefault); expect(property.required).toBe(true); expect(property.semantic).toBe("_POSITION"); expect(property.extras).toEqual(extras); expect(property.extensions).toEqual(extensions); expect(property._isLegacyExtension).toBe(false); }); it("transcodes single properties from EXT_feature_metadata", function() { const max = [32767, 0, 100]; const min = [-32768, 0, -100]; const propertyDefault = [0, 0, 0]; const extras = { coordinates: [0, 1, 2] }; const extensions = { EXT_other_extension: {} }; const property = import__541.MetadataClassProperty.fromJson({ id: "population", property: { name: "Population", description: "Population (thousands)", type: "INT32", normalized: true, max, min, default: propertyDefault, optional: false, semantic: "_POSITION", extras, extensions } }); expect(property.id).toBe("population"); expect(property.name).toBe("Population"); expect(property.description).toBe("Population (thousands)"); expect(property.type).toBe(import__541.MetadataType.SCALAR); expect(property.enumType).toBeUndefined(); expect(property.componentType).toBe(import__541.MetadataComponentType.INT32); expect(property.valueType).toBe(import__541.MetadataComponentType.INT32); expect(property.isArray).toBe(false); expect(property.isVariableLengthArray).toBe(false); expect(property.arrayLength).not.toBeDefined(); expect(property.normalized).toBe(true); expect(property.max).toEqual(max); expect(property.min).toEqual(min); expect(property.default).toEqual(propertyDefault); expect(property.required).toBe(true); expect(property.semantic).toBe("_POSITION"); expect(property.extras).toEqual(extras); expect(property.extensions).toEqual(extensions); expect(property._isLegacyExtension).toBe(true); }); it("creates enum property", function() { const colorEnum = import__541.MetadataEnum.fromJson({ id: "color", enum: { values: [ { name: "RED", value: 0 } ] } }); const enums = { color: colorEnum }; const property = import__541.MetadataClassProperty.fromJson({ id: "color", property: { type: "ENUM", enumType: "color", required: true }, enums }); expect(property.required).toBe(true); expect(property.isArray).toBe(false); expect(property.isVariableLengthArray).toBe(false); expect(property.arrayLength).not.toBeDefined(); expect(property.type).toBe(import__541.MetadataType.ENUM); expect(property.componentType).not.toBeDefined(); expect(property.enumType).toBe(colorEnum); expect(property.valueType).toBe(import__541.MetadataComponentType.UINT16); expect(property._isLegacyExtension).toBe(false); }); it("creates array of enums with EXT_feature_metadata", function() { const colorEnum = import__541.MetadataEnum.fromJson({ id: "color", enum: { valueType: "UINT32", values: [ { name: "RED", value: 0 } ] } }); const enums = { color: colorEnum }; const property = import__541.MetadataClassProperty.fromJson({ id: "color", property: { type: "ARRAY", componentType: "ENUM", componentCount: 4, enumType: "color" }, enums }); expect(property.isArray).toBe(true); expect(property.isVariableLengthArray).toBe(false); expect(property.arrayLength).toBe(4); expect(property.type).toBe(import__541.MetadataType.ENUM); expect(property.componentType).not.toBeDefined(); expect(property.enumType).toBe(colorEnum); expect(property.valueType).toBe(import__541.MetadataComponentType.UINT32); expect(property._isLegacyExtension).toBe(true); }); it("creates vector and matrix types", function() { let property = import__541.MetadataClassProperty.fromJson({ id: "speed", property: { type: "VEC2", componentType: "FLOAT32" } }); expect(property.id).toBe("speed"); expect(property.type).toBe(import__541.MetadataType.VEC2); expect(property.isArray).toBe(false); expect(property.isVariableLengthArray).toBe(false); expect(property.arrayLength).not.toBeDefined(); expect(property.componentType).toBe(import__541.MetadataComponentType.FLOAT32); expect(property.valueType).toBe(import__541.MetadataComponentType.FLOAT32); expect(property._isLegacyExtension).toBe(false); property = import__541.MetadataClassProperty.fromJson({ id: "scale", property: { type: "MAT3", componentType: "FLOAT64" } }); expect(property.id).toBe("scale"); expect(property.type).toBe(import__541.MetadataType.MAT3); expect(property.isArray).toBe(false); expect(property.isVariableLengthArray).toBe(false); expect(property.arrayLength).not.toBeDefined(); expect(property.componentType).toBe(import__541.MetadataComponentType.FLOAT64); expect(property.valueType).toBe(import__541.MetadataComponentType.FLOAT64); expect(property._isLegacyExtension).toBe(false); }); it("creates arrays of BOOLEAN and STRING with EXT_feature_metadata", function() { let property = import__541.MetadataClassProperty.fromJson({ id: "booleanArray", property: { type: "ARRAY", componentType: "BOOLEAN" } }); expect(property.id).toBe("booleanArray"); expect(property.type).toBe(import__541.MetadataType.BOOLEAN); expect(property.isArray).toBe(true); expect(property.isVariableLengthArray).toBe(true); expect(property.arrayLength).not.toBeDefined(); expect(property.componentType).not.toBeDefined(); expect(property.valueType).not.toBeDefined(); expect(property._isLegacyExtension).toBe(true); property = import__541.MetadataClassProperty.fromJson({ id: "stringArray", property: { type: "ARRAY", componentType: "STRING", componentCount: 2 } }); expect(property.id).toBe("stringArray"); expect(property.type).toBe(import__541.MetadataType.STRING); expect(property.isArray).toBe(true); expect(property.isVariableLengthArray).toBe(false); expect(property.arrayLength).toBe(2); expect(property.componentType).not.toBeDefined(); expect(property.valueType).not.toBeDefined(); expect(property._isLegacyExtension).toBe(true); }); it("creates arrays of vector and matrix types", function() { let property = import__541.MetadataClassProperty.fromJson({ id: "speeds", property: { type: "VEC2", componentType: "FLOAT32", array: true } }); expect(property.id).toBe("speeds"); expect(property.type).toBe(import__541.MetadataType.VEC2); expect(property.isArray).toBe(true); expect(property.isVariableLengthArray).toBe(true); expect(property.arrayLength).not.toBeDefined(); expect(property.componentType).toBe(import__541.MetadataComponentType.FLOAT32); expect(property.valueType).toBe(import__541.MetadataComponentType.FLOAT32); expect(property._isLegacyExtension).toBe(false); property = import__541.MetadataClassProperty.fromJson({ id: "scaleFactors", property: { type: "MAT3", componentType: "FLOAT64", array: true, count: 2 } }); expect(property.id).toBe("scaleFactors"); expect(property.type).toBe(import__541.MetadataType.MAT3); expect(property.isArray).toBe(true); expect(property.isVariableLengthArray).toBe(false); expect(property.arrayLength).toBe(2); expect(property.componentType).toBe(import__541.MetadataComponentType.FLOAT64); expect(property.valueType).toBe(import__541.MetadataComponentType.FLOAT64); expect(property._isLegacyExtension).toBe(false); }); it("handles ambiguous extension gracefully", function() { const property = import__541.MetadataClassProperty.fromJson({ id: "name", property: { // this is valid in both EXT_structural_metadata and EXT_feature_metadata type: "STRING" } }); expect(property.id).toBe("name"); expect(property.required).toBe(false); expect(property.type).toBe(import__541.MetadataType.STRING); expect(property.isArray).toBe(false); expect(property.isVariableLengthArray).toBe(false); expect(property.arrayLength).not.toBeDefined(); expect(property.componentType).not.toBeDefined(); expect(property.valueType).not.toBeDefined(); expect(property._isLegacyExtension).not.toBeDefined(); }); it("constructor throws with invalid type definition", function() { expect(function() { return import__541.MetadataClassProperty.fromJson({ id: "propertyId", property: { type: "NOT_A_TYPE" } }); }).toThrowDeveloperError(); }); it("constructor throws without id", function() { expect(function() { return import__541.MetadataClassProperty.fromJson({ id: void 0, property: { type: "VEC2", componentType: "FLOAT32" } }); }).toThrowDeveloperError(); }); it("constructor throws without property", function() { expect(function() { return import__541.MetadataClassProperty.fromJson({ id: "propertyId", property: void 0 }); }).toThrowDeveloperError(); }); it("constructor throws without property.type", function() { expect(function() { return import__541.MetadataClassProperty.fromJson({ id: "propertyId", property: { type: void 0, componentType: "FLOAT32" } }); }).toThrowDeveloperError(); }); describe("expandConstant", function() { it("works for scalars", function() { const property = import__541.MetadataClassProperty.fromJson({ id: "propertyId", property: { type: "SCALAR", componentType: "FLOAT32" } }); expect(property.expandConstant(1)).toBe(1); }); it("works for vectors and matrices", function() { let property = import__541.MetadataClassProperty.fromJson({ id: "propertyId", property: { type: "VEC3", componentType: "FLOAT32" } }); expect(property.expandConstant(1)).toEqual([1, 1, 1]); property = import__541.MetadataClassProperty.fromJson({ id: "propertyId", property: { type: "MAT3", componentType: "FLOAT32" } }); expect(property.expandConstant(1)).toEqual([1, 1, 1, 1, 1, 1, 1, 1, 1]); }); it("works for arrays of scalars", function() { const property = import__541.MetadataClassProperty.fromJson({ id: "propertyId", property: { array: true, count: 4, type: "SCALAR", componentType: "FLOAT32" } }); expect(property.expandConstant(1)).toEqual([1, 1, 1, 1]); }); it("works for arrays of vectors and matrices", function() { let property = import__541.MetadataClassProperty.fromJson({ id: "propertyId", property: { array: true, count: 3, type: "VEC3", componentType: "FLOAT32" } }); const isNested = false; expect(property.expandConstant(1, isNested)).toEqual([ 1, 1, 1, 1, 1, 1, 1, 1, 1 ]); property = import__541.MetadataClassProperty.fromJson({ id: "propertyId", property: { array: true, count: 2, type: "MAT3", componentType: "FLOAT32" } }); expect(property.expandConstant(1, isNested)).toEqual([ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]); }); it("works for nested arrays of vectors and matrices", function() { let property = import__541.MetadataClassProperty.fromJson({ id: "propertyId", property: { array: true, count: 3, type: "VEC3", componentType: "FLOAT32" } }); const isNested = true; expect(property.expandConstant(1, isNested)).toEqual([ [1, 1, 1], [1, 1, 1], [1, 1, 1] ]); property = import__541.MetadataClassProperty.fromJson({ id: "propertyId", property: { array: true, count: 2, type: "MAT3", componentType: "FLOAT32" } }); expect(property.expandConstant(1, isNested)).toEqual([ [1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1] ]); }); }); describe("normalize and unnormalize", function() { let scalarProperties; let scalarValues; let normalizedScalarValues; let arrayProperties; let arrayValues; let normalizedArrayValues; let vectorProperties; let vectorValues; let normalizedVectorValues; let arrayOfVectorProperties; let arrayOfVectorValues; let normalizedArrayOfVectorValues; let myEnum; let nonIntegerProperties; let nonIntegerValues; beforeAll(function() { scalarProperties = { propertyInt8: { type: "SCALAR", componentType: "INT8", normalized: true }, propertyUint8: { type: "SCALAR", componentType: "UINT8", normalized: true }, propertyInt16: { type: "SCALAR", componentType: "INT16", normalized: true }, propertyUint16: { type: "SCALAR", componentType: "UINT16", normalized: true }, propertyInt32: { type: "SCALAR", componentType: "INT32", normalized: true }, propertyUint32: { type: "SCALAR", componentType: "UINT32", normalized: true }, propertyInt64: { type: "SCALAR", componentType: "INT64", normalized: true }, propertyUint64: { type: "SCALAR", componentType: "UINT64", normalized: true } }; scalarValues = { propertyInt8: [-127, 0, 127], propertyUint8: [0, 51, 255], propertyInt16: [-32767, 0, 32767], propertyUint16: [0, 13107, 65535], propertyInt32: [-2147483647, 0, 2147483647], propertyUint32: [0, 858993459, 4294967295], propertyInt64: [ BigInt("-9223372036854775807"), // eslint-disable-line BigInt(0), // eslint-disable-line BigInt("9223372036854775807") // eslint-disable-line ], propertyUint64: [ BigInt(0), // eslint-disable-line BigInt("3689348814741910528"), // eslint-disable-line BigInt("18446744073709551615") // eslint-disable-line ] }; normalizedScalarValues = { propertyInt8: [-1, 0, 1], propertyUint8: [0, 0.2, 1], propertyInt16: [-1, 0, 1], propertyUint16: [0, 0.2, 1], propertyInt32: [-1, 0, 1], propertyUint32: [0, 0.2, 1], propertyInt64: [-1, 0, 1], propertyUint64: [0, 0.2, 1] }; arrayProperties = { propertyInt8: { array: true, type: "SCALAR", componentType: "INT8", normalized: true }, propertyUint8: { array: true, count: 2, type: "SCALAR", componentType: "UINT8", normalized: true }, propertyVector: { type: "VEC3", componentType: "UINT8", normalized: true, array: true, count: 3 }, propertyMatrix: { type: "MAT2", componentType: "UINT8", normalized: true, array: true } }; arrayValues = { propertyInt8: [[-127, 0], [127], []], propertyUint8: [ [0, 255], [0, 51], [255, 255] ], propertyVector: [ [255, 0, 0], [0, 255, 0], [0, 0, 255] ], propertyMatrix: [ [255, 255, 255, 255], [51, 0, 0, 51] ] }; normalizedArrayValues = { propertyInt8: [[-1, 0], [1], []], propertyUint8: [ [0, 1], [0, 0.2], [1, 1] ], propertyVector: [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ], propertyMatrix: [ [1, 1, 1, 1], [0.2, 0, 0, 0.2] ] }; vectorProperties = { vec4Int8: { type: "VEC4", componentType: "INT8", normalized: true }, mat2Uint8: { type: "MAT2", componentType: "UINT8", normalized: true } }; vectorValues = { vec4Int8: [ [-127, 0, 127, 0], [-127, -127, -127, 0], [127, 127, 127, 127] ], mat2Uint8: [ [0, 255, 0, 0], [0, 51, 51, 0], [255, 0, 0, 255] ] }; normalizedVectorValues = { vec4Int8: [ [-1, 0, 1, 0], [-1, -1, -1, 0], [1, 1, 1, 1] ], mat2Uint8: [ [0, 1, 0, 0], [0, 0.2, 0.2, 0], [1, 0, 0, 1] ] }; arrayOfVectorProperties = { propertyVector: { type: "VEC3", componentType: "UINT8", normalized: true, array: true, count: 2 }, propertyMatrix: { type: "MAT2", componentType: "UINT8", normalized: true, array: true } }; arrayOfVectorValues = { propertyVector: [ [ [255, 0, 0], [0, 255, 0] ], [ [0, 0, 255], [255, 255, 0] ] ], propertyMatrix: [ [ [255, 255, 255, 255], [51, 0, 0, 51] ], [] ] }; normalizedArrayOfVectorValues = { propertyVector: [ [ [1, 0, 0], [0, 1, 0] ], [ [0, 0, 1], [1, 1, 0] ] ], propertyMatrix: [ [ [1, 1, 1, 1], [0.2, 0, 0, 0.2] ], [] ] }; myEnum = import__541.MetadataEnum.fromJson({ id: "myEnum", enum: { values: [ { value: 0, name: "ValueA" }, { value: 1, name: "ValueB" }, { value: 999, name: "Other" } ] } }); nonIntegerProperties = { propertyEnum: { type: "ENUM", enumType: "myEnum" }, propertyEnumArray: { type: "ENUM", array: true, enumType: "myEnum" }, propertyString: { type: "STRING" }, propertyBoolean: { type: "BOOLEAN" } }; nonIntegerValues = { propertyEnum: ["Other", "ValueA", "ValueB"], propertyEnumArray: [["Other", "ValueA"], ["ValueB"], []], propertyString: ["a", "bc", ""], propertyBoolean: [true, false, false] }; }); it("normalizes scalar values", function() { if (!import__541.FeatureDetection.supportsBigInt()) { return; } for (const propertyId in scalarProperties) { if (scalarProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: scalarProperties[propertyId] }); const length2 = normalizedScalarValues[propertyId].length; for (let i = 0; i < length2; ++i) { const value = scalarValues[propertyId][i]; const normalizedValue = property.normalize(value); expect(normalizedValue).toEqual( normalizedScalarValues[propertyId][i] ); } } } }); it("unnormalizes scalar values", function() { if (!import__541.FeatureDetection.supportsBigInt()) { return; } for (const propertyId in scalarProperties) { if (scalarProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: scalarProperties[propertyId] }); const length2 = scalarValues[propertyId].length; for (let i = 0; i < length2; ++i) { const normalizedValue = normalizedScalarValues[propertyId][i]; const value = property.unnormalize(normalizedValue); expect(value).toEqual(scalarValues[propertyId][i]); } } } }); it("normalizes array values", function() { for (const propertyId in arrayProperties) { if (arrayProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: arrayProperties[propertyId] }); const length2 = normalizedArrayValues[propertyId].length; for (let i = 0; i < length2; ++i) { const value = arrayValues[propertyId][i]; const normalizedValue = property.normalize((0, import__541.clone)(value, true)); expect(normalizedValue).toEqual( normalizedArrayValues[propertyId][i] ); } } } }); it("unnormalizes array values", function() { for (const propertyId in arrayProperties) { if (arrayProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: arrayProperties[propertyId] }); const length2 = arrayValues[propertyId].length; for (let i = 0; i < length2; ++i) { const normalizedValue = normalizedArrayValues[propertyId][i]; const value = property.unnormalize((0, import__541.clone)(normalizedValue, true)); expect(value).toEqual(arrayValues[propertyId][i]); } } } }); it("normalizes vector and matrix values", function() { for (const propertyId in vectorProperties) { if (vectorProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: vectorProperties[propertyId] }); const length2 = normalizedVectorValues[propertyId].length; for (let i = 0; i < length2; ++i) { const value = vectorValues[propertyId][i]; const normalizedValue = property.normalize((0, import__541.clone)(value, true)); expect(normalizedValue).toEqual( normalizedVectorValues[propertyId][i] ); } } } }); it("unnormalizes vector and matrix values", function() { for (const propertyId in vectorProperties) { if (vectorProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: vectorProperties[propertyId] }); const length2 = vectorValues[propertyId].length; for (let i = 0; i < length2; ++i) { const normalizedValue = normalizedVectorValues[propertyId][i]; const value = property.unnormalize((0, import__541.clone)(normalizedValue, true)); expect(value).toEqual(vectorValues[propertyId][i]); } } } }); it("normalizes nested arrays of vectors", function() { for (const propertyId in arrayOfVectorProperties) { if (arrayOfVectorProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: arrayOfVectorProperties[propertyId] }); const length2 = normalizedArrayOfVectorValues[propertyId].length; for (let i = 0; i < length2; ++i) { const value = arrayOfVectorValues[propertyId][i]; const normalizedValue = property.normalize((0, import__541.clone)(value, true)); expect(normalizedValue).toEqual( normalizedArrayOfVectorValues[propertyId][i] ); } } } }); it("unnormalizes nested arrays of vectors", function() { for (const propertyId in arrayOfVectorProperties) { if (arrayOfVectorProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: arrayOfVectorProperties[propertyId] }); const length2 = arrayOfVectorValues[propertyId].length; for (let i = 0; i < length2; ++i) { const normalizedValue = normalizedArrayOfVectorValues[propertyId][i]; const value = property.unnormalize((0, import__541.clone)(normalizedValue, true)); expect(value).toEqual(arrayOfVectorValues[propertyId][i]); } } } }); it("does not normalize non integer types", function() { for (const propertyId in nonIntegerProperties) { if (nonIntegerProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: nonIntegerProperties[propertyId], enums: { myEnum } }); const length2 = nonIntegerValues[propertyId].length; for (let i = 0; i < length2; ++i) { const value = nonIntegerValues[propertyId][i]; const normalizedValue = property.normalize(value); expect(normalizedValue).toEqual(value); } } } }); it("does not unnormalize non integer types", function() { for (const propertyId in nonIntegerProperties) { if (nonIntegerProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: nonIntegerProperties[propertyId], enums: { myEnum } }); const length2 = nonIntegerValues[propertyId].length; for (let i = 0; i < length2; ++i) { const normalizedValue = nonIntegerValues[propertyId][i]; const value = property.unnormalize(normalizedValue); expect(value).toEqual(normalizedValue); } } } }); }); describe("value transform", function() { let scalarProperties; let scalarValues; let transformedScalarValues; let arrayProperties; let arrayValues; let transformedArrayValues; let vectorProperties; let vectorValues; let transformedVectorValues; let arrayOfVectorProperties; let arrayOfVectorValues; let transformedArrayOfVectorValues; let myEnum; let otherProperties; let otherValues; beforeAll(function() { scalarProperties = { propertyInt8: { type: "SCALAR", componentType: "INT8", normalized: true, offset: 1, scale: 2 }, propertyUint8: { type: "SCALAR", componentType: "UINT8", normalized: true, offset: 2, scale: 2 }, propertyInt16: { type: "SCALAR", componentType: "INT16", normalized: true, scale: 2 }, propertyUint16: { type: "SCALAR", componentType: "UINT16", normalized: true, offset: 4 }, propertyInt32: { type: "SCALAR", componentType: "INT32", normalized: true, offset: 0, scale: 1 }, propertyUint32: { type: "SCALAR", componentType: "UINT32", normalized: true, scale: 2, offset: 2 }, propertyInt64: { type: "SCALAR", componentType: "INT64", normalized: true, offset: -1, scale: 0.5 }, propertyUint64: { type: "SCALAR", componentType: "UINT64", normalized: true, offset: 1, scale: 2 }, propertyFloat32: { type: "SCALAR", componentType: "FLOAT32", offset: 8, scale: 4 }, propertyFloat64: { type: "SCALAR", componentType: "FLOAT64", offset: 4, scale: 2 } }; scalarValues = { // Integer properties must be normalized to use valueTransform propertyInt8: [-1, 0, 1], propertyUint8: [0, 0.5, 1], propertyInt16: [-1, 0, 1], propertyUint16: [0, 0.5, 1], propertyInt32: [-1, 0, 1], propertyUint32: [0, 0.5, 1], propertyInt64: [-1, 0, 1], propertyUint64: [0, 0.5, 1], // Float properties do not have such restriction propertyFloat32: [-8, 3, 256], propertyFloat64: [-4.5, 0, 45] }; transformedScalarValues = { propertyInt8: [-1, 1, 3], propertyUint8: [2, 3, 4], propertyInt16: [-2, 0, 2], propertyUint16: [4, 4.5, 5], propertyInt32: [-1, 0, 1], propertyUint32: [2, 3, 4], propertyInt64: [-1.5, -1, -0.5], propertyUint64: [1, 2, 3], propertyFloat32: [-24, 20, 1032], propertyFloat64: [-5, 4, 94] }; arrayProperties = { propertyInt8: { array: true, count: 3, type: "SCALAR", componentType: "INT8", normalized: true, offset: [1, 2, 3], scale: [2, 2, 2] }, propertyFloat32: { array: true, count: 2, type: "SCALAR", componentType: "FLOAT32", normalized: true, offset: [-1, -1], scale: [2, 1] }, propertyDefaultOffset: { array: true, count: 2, type: "SCALAR", componentType: "FLOAT32", normalized: true, scale: [2, 2] }, propertyDefaultScale: { array: true, count: 2, type: "SCALAR", componentType: "FLOAT32", normalized: true, offset: [1, 2] } }; arrayValues = { propertyInt8: [ [-1, 0, 1], [1, 1, 1], [0, 0.5, 1] ], propertyFloat32: [ [0, 1], [0, 0.125], [1, 1] ], propertyDefaultOffset: [ [-1, 1], [-2, 4], [-0.5, 0.5] ], propertyDefaultScale: [ [-1, 1], [-2, 4], [-0.5, 0.5] ] }; transformedArrayValues = { propertyInt8: [ [-1, 2, 5], [3, 4, 5], [1, 3, 5] ], propertyFloat32: [ [-1, 0], [-1, -0.875], [1, 0] ], propertyDefaultOffset: [ [-2, 2], [-4, 8], [-1, 1] ], propertyDefaultScale: [ [0, 3], [-1, 6], [0.5, 2.5] ] }; vectorProperties = { vec4Int8: { type: "VEC4", componentType: "INT8", normalized: true, offset: [3, 3, 0, 1], scale: [2, 8, 4, 1] }, mat2Float32: { type: "MAT2", componentType: "FLOAT32", normalized: true, scale: [0.25, 0.25, 1, 1] } }; vectorValues = { vec4Int8: [ [-1, 0, 1, 0], [-1, -1, -1, 0], [1, 1, 1, 1] ], mat2Float32: [ [0, 1, 0, 0], [0, 0.25, 0.25, 0], [1, 0, 0, 1] ] }; transformedVectorValues = { vec4Int8: [ [1, 3, 4, 1], [1, -5, -4, 1], [5, 11, 4, 2] ], mat2Float32: [ [0, 0.25, 0, 0], [0, 0.0625, 0.25, 0], [0.25, 0, 0, 1] ] }; arrayOfVectorProperties = { propertyVector: { type: "VEC3", componentType: "UINT8", normalized: true, array: true, count: 2, offset: [ [2, 2, 2], [0, 1, 2] ] }, propertyMatrix: { type: "MAT2", componentType: "UINT8", normalized: true, array: true, count: 2, scale: [ [2, 2, 2, 1], [1, 1, 1, 1] ] } }; arrayOfVectorValues = { propertyVector: [ [ [1, 0, 0], [0, 1, 0] ], [ [0, 0, 1], [1, 1, 0] ] ], propertyMatrix: [ [ [1, 1, 1, 1], [0.25, 0, 0, 0.25] ], [ [0, -1, 1, 0], [2, 0, 0, 2] ] ] }; transformedArrayOfVectorValues = { propertyVector: [ [ [1, 0, 0], [0, 1, 0] ], [ [0, 0, 1], [1, 1, 0] ] ], propertyMatrix: [ [ [1, 1, 1, 1], [0.25, 0, 0, 0.25] ], [ [0, -1, 1, 0], [2, 0, 0, 2] ] ] }; transformedArrayOfVectorValues = { propertyVector: [ [ [3, 2, 2], [0, 2, 2] ], [ [2, 2, 3], [1, 2, 2] ] ], propertyMatrix: [ [ [2, 2, 2, 1], [0.25, 0, 0, 0.25] ], [ [0, -2, 2, 0], [2, 0, 0, 2] ] ] }; myEnum = import__541.MetadataEnum.fromJson({ id: "myEnum", enum: { values: [ { value: 0, name: "ValueA" }, { value: 1, name: "ValueB" }, { value: 999, name: "Other" } ] } }); otherProperties = { propertyEnum: { type: "ENUM", enumType: "myEnum" }, propertyEnumArray: { type: "ENUM", array: true, enumType: "myEnum" }, propertyString: { type: "STRING" }, propertyBoolean: { type: "BOOLEAN" }, propertyIntegerNotNormalized: { type: "SCALAR", normalized: false, offset: 1, scale: 2 } }; otherValues = { propertyEnum: ["Other", "ValueA", "ValueB"], propertyEnumArray: [["Other", "ValueA"], ["ValueB"], []], propertyString: ["a", "bc", ""], propertyBoolean: [true, false, false], propertyIntegerNotNormalized: [1, 2, 3] }; }); it("applies value transform for scalar values", function() { if (!import__541.FeatureDetection.supportsBigInt()) { return; } for (const propertyId in scalarProperties) { if (scalarProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: scalarProperties[propertyId] }); const length2 = transformedScalarValues[propertyId].length; for (let i = 0; i < length2; ++i) { const value = scalarValues[propertyId][i]; const transformedValue = property.applyValueTransform(value); expect(transformedValue).toEqual( transformedScalarValues[propertyId][i] ); } } } }); it("un-applies value transform for scalar values", function() { if (!import__541.FeatureDetection.supportsBigInt()) { return; } for (const propertyId in scalarProperties) { if (scalarProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: scalarProperties[propertyId] }); const length2 = scalarValues[propertyId].length; for (let i = 0; i < length2; ++i) { const transformedValue = transformedScalarValues[propertyId][i]; const value = property.unapplyValueTransform(transformedValue); expect(value).toEqual(scalarValues[propertyId][i]); } } } }); it("unapplyValueTransform returns 0 when scale is 0", function() { const property = import__541.MetadataClassProperty.fromJson({ id: "zeroScale", property: { type: "SCALAR", componentType: "FLOAT32", offset: 1, scale: 0 } }); expect(property.unapplyValueTransform(35)).toBe(0); }); it("value transformations are no-ops for identity transformations", function() { const valueTransformInPlace = spyOn( import__541.MetadataClassProperty, "valueTransformInPlace" ); const property = import__541.MetadataClassProperty.fromJson({ id: "identityTransform", property: { type: "SCALAR", componentType: "FLOAT32" } }); expect(property.applyValueTransform(5)).toBe(5); expect(property.unapplyValueTransform(5)).toBe(5); expect(valueTransformInPlace).not.toHaveBeenCalled(); }); it("applies value transform for array values", function() { for (const propertyId in arrayProperties) { if (arrayProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: arrayProperties[propertyId] }); const length2 = transformedArrayValues[propertyId].length; for (let i = 0; i < length2; ++i) { const value = arrayValues[propertyId][i]; const transformedValue = property.applyValueTransform( (0, import__541.clone)(value, true) ); expect(transformedValue).toEqual( transformedArrayValues[propertyId][i] ); } } } }); it("un-applies value transform for array values", function() { for (const propertyId in arrayProperties) { if (arrayProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: arrayProperties[propertyId] }); const length2 = arrayValues[propertyId].length; for (let i = 0; i < length2; ++i) { const transformedValue = transformedArrayValues[propertyId][i]; const value = property.unapplyValueTransform( (0, import__541.clone)(transformedValue, true) ); expect(value).toEqual(arrayValues[propertyId][i]); } } } }); it("value transforms do not transform variable length arrays", function() { const valueTransformInPlace = spyOn( import__541.MetadataClassProperty, "valueTransformInPlace" ); const property = import__541.MetadataClassProperty.fromJson({ id: "zeroScale", property: { type: "SCALAR", componentType: "FLOAT32", array: true, // In this case the implementation should ignore offset/scale offset: [1, 2, 3], scale: [2, 2, 2] } }); const values = [-1, 0, 5, 4]; expect(property.applyValueTransform((0, import__541.clone)(values, true))).toEqual(values); expect(property.unapplyValueTransform((0, import__541.clone)(values, true))).toEqual( values ); expect(valueTransformInPlace).not.toHaveBeenCalled(); }); it("applies value transform for vector and matrix values", function() { for (const propertyId in vectorProperties) { if (vectorProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: vectorProperties[propertyId] }); const length2 = transformedVectorValues[propertyId].length; for (let i = 0; i < length2; ++i) { const value = vectorValues[propertyId][i]; const transformedValue = property.applyValueTransform( (0, import__541.clone)(value, true) ); expect(transformedValue).toEqual( transformedVectorValues[propertyId][i] ); } } } }); it("un-applies value transform for vector and matrix values", function() { for (const propertyId in vectorProperties) { if (vectorProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: vectorProperties[propertyId] }); const length2 = vectorValues[propertyId].length; for (let i = 0; i < length2; ++i) { const transformedValue = transformedVectorValues[propertyId][i]; const value = property.unapplyValueTransform( (0, import__541.clone)(transformedValue, true) ); expect(value).toEqual(vectorValues[propertyId][i]); } } } }); it("applies value transform for arrays of vectors", function() { for (const propertyId in arrayOfVectorProperties) { if (arrayOfVectorProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: arrayOfVectorProperties[propertyId] }); const length2 = transformedArrayOfVectorValues[propertyId].length; for (let i = 0; i < length2; ++i) { const value = arrayOfVectorValues[propertyId][i]; const transformedValue = property.applyValueTransform( (0, import__541.clone)(value, true) ); expect(transformedValue).toEqual( transformedArrayOfVectorValues[propertyId][i] ); } } } }); it("un-applies value transform for arrays of vectors", function() { for (const propertyId in arrayOfVectorProperties) { if (arrayOfVectorProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: arrayOfVectorProperties[propertyId] }); const length2 = arrayOfVectorValues[propertyId].length; for (let i = 0; i < length2; ++i) { const transformedValue = transformedArrayOfVectorValues[propertyId][i]; const value = property.unapplyValueTransform( (0, import__541.clone)(transformedValue, true) ); expect(value).toEqual(arrayOfVectorValues[propertyId][i]); } } } }); it("does not apply transform to other types", function() { for (const propertyId in otherProperties) { if (otherProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: otherProperties[propertyId], enums: { myEnum } }); const length2 = otherValues[propertyId].length; for (let i = 0; i < length2; ++i) { const value = otherValues[propertyId][i]; const normalizedValue = property.normalize(value); expect(normalizedValue).toEqual(value); } } } }); it("does not unaapply transform to other types", function() { for (const propertyId in otherProperties) { if (otherProperties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: otherProperties[propertyId], enums: { myEnum } }); const length2 = otherValues[propertyId].length; for (let i = 0; i < length2; ++i) { const value = otherValues[propertyId][i]; const normalizedValue = property.normalize(value); expect(normalizedValue).toEqual(value); } } } }); }); describe("handleNoData", function() { let properties; beforeAll(function() { properties = { float: { type: "SCALAR", componentType: "FLOAT64", noData: -1 }, array: { array: true, count: 4, type: "SCALAR", componentType: "UINT8", noData: [255, 255, 255, 255] }, variableLengthArray: { array: true, type: "STRING", noData: [] }, arrayOfVector: { array: true, count: 2, type: "VEC2", componentType: "FLOAT32", noData: [ [0, 0], [0, 0] ] } }; }); it("passes through valid values unchanged", function() { const propertyValues = { float: 1, array: [0, 0, 0, 255], variableLengthArray: ["Hello", "World"], arrayOfVector: [ [1, 1], [2, -1] ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: properties[propertyId] }); const expected = propertyValues[propertyId]; const actual = property.handleNoData(expected); expect(actual).toBe(expected); } } }); it("converts noData values to undefined", function() { const propertyValues = { float: -1, array: [255, 255, 255, 255], variableLengthArray: [], arrayOfVector: [ [0, 0], [0, 0] ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: properties[propertyId] }); const value = propertyValues[propertyId]; const actual = property.handleNoData(value); expect(actual).not.toBeDefined(); } } }); }); it("packVectorAndMatrixTypes packs vectors and matrices", function() { const properties = { propertyVec2: { type: "VEC2", componentType: "FLOAT32" }, propertyIVec3: { type: "VEC3", componentType: "INT32" }, propertyDVec4: { type: "VEC4", componentType: "FLOAT64" }, propertyMat4: { type: "MAT4", componentType: "FLOAT32" }, propertyIMat3: { type: "MAT3", componentType: "FLOAT32" }, propertyDMat2: { type: "MAT2", componentType: "FLOAT32" } }; const propertyValues = { propertyVec2: [ new import__541.Cartesian2(0.1, 0.8), new import__541.Cartesian2(0.3, 0.5), new import__541.Cartesian2(0.7, 0.2) ], propertyIVec3: [ new import__541.Cartesian3(1, 2, 3), new import__541.Cartesian3(4, 5, 6), new import__541.Cartesian3(7, 8, 9) ], propertyDVec4: [ new import__541.Cartesian4(0.1, 0.2, 0.3, 0.4), new import__541.Cartesian4(0.3, 0.2, 0.1, 0), new import__541.Cartesian4(0.1, 0.2, 0.4, 0.5) ], propertyMat4: [ new import__541.Matrix4(1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1), new import__541.Matrix4(0, 2.5, 0, 0, 0, 0.5, 0.25, 0, 0, 0, 3.5, 0, 0, 0, 0, 1), new import__541.Matrix4(1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0) ], propertyIMat3: [ new import__541.Matrix3(2, 0, 0, 0, 2, 0, 0, 0, 2), new import__541.Matrix3(1, 0, 0, 0, 1, 0, 0, 0, 1), new import__541.Matrix3(1, 2, 3, 2, 3, 1, 3, 1, 2) ], propertyDMat2: [ new import__541.Matrix2(1.5, 0, 0, 2.5), new import__541.Matrix2(1, 0, 0, 1), new import__541.Matrix2(1.5, 2.5, 3.5, 4.5) ] }; const packedValues = { propertyVec2: [ [0.1, 0.8], [0.3, 0.5], [0.7, 0.2] ], propertyIVec3: [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ], propertyDVec4: [ [0.1, 0.2, 0.3, 0.4], [0.3, 0.2, 0.1, 0], [0.1, 0.2, 0.4, 0.5] ], propertyMat4: [ // the MatrixN constructor is row-major, but internally things are // stored column-major. So these are the transpose of the above [1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1], [0, 0, 0, 0, 2.5, 0.5, 0, 0, 0, 0.25, 3.5, 0, 0, 0, 0, 1], [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0] ], propertyIMat3: [ [2, 0, 0, 0, 2, 0, 0, 0, 2], [1, 0, 0, 0, 1, 0, 0, 0, 1], [1, 2, 3, 2, 3, 1, 3, 1, 2] ], propertyDMat2: [ [1.5, 0, 0, 2.5], [1, 0, 0, 1], [1.5, 3.5, 2.5, 4.5] ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: properties[propertyId] }); const length2 = propertyValues[propertyId].length; for (let i = 0; i < length2; ++i) { const value = propertyValues[propertyId][i]; const packed = property.packVectorAndMatrixTypes(value); expect(packed).toEqual(packedValues[propertyId][i]); } } } }); it("packVectorAndMatrixTypes packs arrays of vectors and matrices", function() { const properties = { propertyVec2: { type: "VEC2", componentType: "FLOAT32", array: true }, propertyIVec3: { type: "VEC3", componentType: "INT32", array: true, count: 3 }, propertyDVec4: { type: "VEC4", componentType: "FLOAT64", array: true }, propertyMat4: { type: "MAT4", componentType: "FLOAT32", array: true }, propertyIMat3: { type: "MAT3", componentType: "FLOAT32", array: true, count: 3 }, propertyDMat2: { type: "MAT2", componentType: "FLOAT32", array: true, count: 3 } }; const propertyValues = { propertyVec2: [ new import__541.Cartesian2(0.1, 0.8), new import__541.Cartesian2(0.3, 0.5), new import__541.Cartesian2(0.7, 0.2) ], propertyIVec3: [ new import__541.Cartesian3(1, 2, 3), new import__541.Cartesian3(4, 5, 6), new import__541.Cartesian3(7, 8, 9) ], propertyDVec4: [ new import__541.Cartesian4(0.1, 0.2, 0.3, 0.4), new import__541.Cartesian4(0.3, 0.2, 0.1, 0), new import__541.Cartesian4(0.1, 0.2, 0.4, 0.5) ], propertyMat4: [ new import__541.Matrix4(1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1), new import__541.Matrix4(0, 2.5, 0, 0, 0, 0.5, 0.25, 0, 0, 0, 3.5, 0, 0, 0, 0, 1), new import__541.Matrix4(1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0) ], propertyIMat3: [ new import__541.Matrix3(2, 0, 0, 0, 2, 0, 0, 0, 2), new import__541.Matrix3(1, 0, 0, 0, 1, 0, 0, 0, 1), new import__541.Matrix3(1, 2, 3, 2, 3, 1, 3, 1, 2) ], propertyDMat2: [ new import__541.Matrix2(1.5, 0, 0, 2.5), new import__541.Matrix2(1, 0, 0, 1), new import__541.Matrix2(1.5, 2.5, 3.5, 4.5) ] }; const packedValues = { propertyVec2: [ 0.1, 0.8, 0.3, 0.5, 0.7, 0.2 ], propertyIVec3: [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ], propertyDVec4: [ 0.1, 0.2, 0.3, 0.4, 0.3, 0.2, 0.1, 0, 0.1, 0.2, 0.4, 0.5 ], propertyMat4: [ // the MatrixN constructor is row-major, but internally things are // stored column-major. So these are the transpose of the above 1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2.5, 0.5, 0, 0, 0, 0.25, 3.5, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0 ], propertyIMat3: [ 2, 0, 0, 0, 2, 0, 0, 0, 2, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 2, 3, 2, 3, 1, 3, 1, 2 ], propertyDMat2: [ 1.5, 0, 0, 2.5, 1, 0, 0, 1, 1.5, 3.5, 2.5, 4.5 ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: properties[propertyId] }); const value = propertyValues[propertyId]; const packed = property.packVectorAndMatrixTypes(value); const expected = packedValues[propertyId]; expect(packed).toEqual(expected); } } }); it("packVectorAndMatrixTypes packs nested arrays of vectors", function() { const properties = { propertyVec2: { type: "VEC2", componentType: "FLOAT32", array: true }, propertyIVec3: { type: "VEC3", componentType: "INT32", array: true, count: 3 }, propertyDVec4: { type: "VEC4", componentType: "FLOAT64", array: true }, propertyMat4: { type: "MAT4", componentType: "FLOAT32", array: true }, propertyIMat3: { type: "MAT3", componentType: "FLOAT32", array: true, count: 3 }, propertyDMat2: { type: "MAT2", componentType: "FLOAT32", array: true, count: 3 } }; const propertyValues = { propertyVec2: [ new import__541.Cartesian2(0.1, 0.8), new import__541.Cartesian2(0.3, 0.5), new import__541.Cartesian2(0.7, 0.2) ], propertyIVec3: [ new import__541.Cartesian3(1, 2, 3), new import__541.Cartesian3(4, 5, 6), new import__541.Cartesian3(7, 8, 9) ], propertyDVec4: [ new import__541.Cartesian4(0.1, 0.2, 0.3, 0.4), new import__541.Cartesian4(0.3, 0.2, 0.1, 0), new import__541.Cartesian4(0.1, 0.2, 0.4, 0.5) ], propertyMat4: [ new import__541.Matrix4(1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1), new import__541.Matrix4(0, 2.5, 0, 0, 0, 0.5, 0.25, 0, 0, 0, 3.5, 0, 0, 0, 0, 1), new import__541.Matrix4(1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0) ], propertyIMat3: [ new import__541.Matrix3(2, 0, 0, 0, 2, 0, 0, 0, 2), new import__541.Matrix3(1, 0, 0, 0, 1, 0, 0, 0, 1), new import__541.Matrix3(1, 2, 3, 2, 3, 1, 3, 1, 2) ], propertyDMat2: [ new import__541.Matrix2(1.5, 0, 0, 2.5), new import__541.Matrix2(1, 0, 0, 1), new import__541.Matrix2(1.5, 2.5, 3.5, 4.5) ] }; const packedValues = { propertyVec2: [ [0.1, 0.8], [0.3, 0.5], [0.7, 0.2] ], propertyIVec3: [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ], propertyDVec4: [ [0.1, 0.2, 0.3, 0.4], [0.3, 0.2, 0.1, 0], [0.1, 0.2, 0.4, 0.5] ], propertyMat4: [ // the MatrixN constructor is row-major, but internally things are // stored column-major. So these are the transpose of the above [1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1], [0, 0, 0, 0, 2.5, 0.5, 0, 0, 0, 0.25, 3.5, 0, 0, 0, 0, 1], [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0] ], propertyIMat3: [ [2, 0, 0, 0, 2, 0, 0, 0, 2], [1, 0, 0, 0, 1, 0, 0, 0, 1], [1, 2, 3, 2, 3, 1, 3, 1, 2] ], propertyDMat2: [ [1.5, 0, 0, 2.5], [1, 0, 0, 1], [1.5, 3.5, 2.5, 4.5] ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: properties[propertyId] }); const value = propertyValues[propertyId]; const nested = true; const packed = property.packVectorAndMatrixTypes(value, nested); const expected = packedValues[propertyId]; expect(packed).toEqual(expected); } } }); it("packVectorAndMatrixTypes does not affect other types", function() { if (!import__541.FeatureDetection.supportsBigInt()) { return; } const properties = { propertyString: { type: "STRING" }, propertyBoolean: { type: "BOOLEAN" }, propertyArray: { type: "SCALAR", componentType: "UINT8", array: true, count: 5 }, propertyBigIntArray: { type: "SCALAR", componentType: "UINT64", array: true, count: 2 } }; const propertyValues = { propertyString: ["a", "bc", ""], propertyBoolean: [true, false, false], propertyArray: [ [1, 2, 3, 4, 5], [0, 1, 2, 3, 4], [1, 4, 9, 16, 25] ], propertyBigIntArray: [ [BigInt(0), BigInt(0)], // eslint-disable-line [BigInt(1), BigInt(3)], // eslint-disable-line [BigInt(45), BigInt(32)] // eslint-disable-line ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: properties[propertyId] }); const length2 = propertyValues[propertyId].length; for (let i = 0; i < length2; ++i) { const value = propertyValues[propertyId][i]; const packed = property.packVectorAndMatrixTypes(value); expect(packed).toEqual(value); } } } }); it("unpackVectorAndMatrixTypes unpacks vectors and matrices", function() { const properties = { propertyVec2: { type: "VEC2", componentType: "FLOAT32" }, propertyIVec3: { type: "VEC3", componentType: "INT32" }, propertyDVec4: { type: "VEC4", componentType: "FLOAT64" }, propertyMat4: { type: "MAT4", componentType: "FLOAT32" }, propertyIMat3: { type: "MAT3", componentType: "FLOAT32" }, propertyDMat2: { type: "MAT2", componentType: "FLOAT32" } }; const propertyValues = { propertyVec2: [ new import__541.Cartesian2(0.1, 0.8), new import__541.Cartesian2(0.3, 0.5), new import__541.Cartesian2(0.7, 0.2) ], propertyIVec3: [ new import__541.Cartesian3(1, 2, 3), new import__541.Cartesian3(4, 5, 6), new import__541.Cartesian3(7, 8, 9) ], propertyDVec4: [ new import__541.Cartesian4(0.1, 0.2, 0.3, 0.4), new import__541.Cartesian4(0.3, 0.2, 0.1, 0), new import__541.Cartesian4(0.1, 0.2, 0.4, 0.5) ], propertyMat4: [ new import__541.Matrix4(1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1), new import__541.Matrix4(0, 2.5, 0, 0, 0, 0.5, 0.25, 0, 0, 0, 3.5, 0, 0, 0, 0, 1), new import__541.Matrix4(1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0) ], propertyIMat3: [ new import__541.Matrix3(2, 0, 0, 0, 2, 0, 0, 0, 2), new import__541.Matrix3(1, 0, 0, 0, 1, 0, 0, 0, 1), new import__541.Matrix3(1, 2, 3, 2, 3, 1, 3, 1, 2) ], propertyDMat2: [ new import__541.Matrix2(1.5, 0, 0, 2.5), new import__541.Matrix2(1, 0, 0, 1), new import__541.Matrix2(1.5, 2.5, 3.5, 4.5) ] }; const packedValues = { propertyVec2: [ [0.1, 0.8], [0.3, 0.5], [0.7, 0.2] ], propertyIVec3: [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ], propertyDVec4: [ [0.1, 0.2, 0.3, 0.4], [0.3, 0.2, 0.1, 0], [0.1, 0.2, 0.4, 0.5] ], propertyMat4: [ // the MatrixN constructor is row-major, but internally things are // stored column-major. So these are the transpose of the above [1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1], [0, 0, 0, 0, 2.5, 0.5, 0, 0, 0, 0.25, 3.5, 0, 0, 0, 0, 1], [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0] ], propertyIMat3: [ [2, 0, 0, 0, 2, 0, 0, 0, 2], [1, 0, 0, 0, 1, 0, 0, 0, 1], [1, 2, 3, 2, 3, 1, 3, 1, 2] ], propertyDMat2: [ [1.5, 0, 0, 2.5], [1, 0, 0, 1], [1.5, 3.5, 2.5, 4.5] ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: properties[propertyId] }); const length2 = propertyValues[propertyId].length; for (let i = 0; i < length2; ++i) { const value = packedValues[propertyId][i]; const unpacked = property.unpackVectorAndMatrixTypes(value); expect(unpacked).toEqual(propertyValues[propertyId][i]); } } } }); it("unpackVectorAndMatrixTypes unpacks arrays of vectors and matrices", function() { const properties = { propertyVec2: { type: "VEC2", componentType: "FLOAT32", array: true }, propertyIVec3: { type: "VEC3", componentType: "INT32", array: true, count: 3 }, propertyDVec4: { type: "VEC4", componentType: "FLOAT64", array: true }, propertyMat4: { type: "MAT4", componentType: "FLOAT32", array: true }, propertyIMat3: { type: "MAT3", componentType: "FLOAT32", array: true, count: 3 }, propertyDMat2: { type: "MAT2", componentType: "FLOAT32", array: true, count: 3 } }; const propertyValues = { propertyVec2: [ new import__541.Cartesian2(0.1, 0.8), new import__541.Cartesian2(0.3, 0.5), new import__541.Cartesian2(0.7, 0.2) ], propertyIVec3: [ new import__541.Cartesian3(1, 2, 3), new import__541.Cartesian3(4, 5, 6), new import__541.Cartesian3(7, 8, 9) ], propertyDVec4: [ new import__541.Cartesian4(0.1, 0.2, 0.3, 0.4), new import__541.Cartesian4(0.3, 0.2, 0.1, 0), new import__541.Cartesian4(0.1, 0.2, 0.4, 0.5) ], propertyMat4: [ new import__541.Matrix4(1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1), new import__541.Matrix4(0, 2.5, 0, 0, 0, 0.5, 0.25, 0, 0, 0, 3.5, 0, 0, 0, 0, 1), new import__541.Matrix4(1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0) ], propertyIMat3: [ new import__541.Matrix3(2, 0, 0, 0, 2, 0, 0, 0, 2), new import__541.Matrix3(1, 0, 0, 0, 1, 0, 0, 0, 1), new import__541.Matrix3(1, 2, 3, 2, 3, 1, 3, 1, 2) ], propertyDMat2: [ new import__541.Matrix2(1.5, 0, 0, 2.5), new import__541.Matrix2(1, 0, 0, 1), new import__541.Matrix2(1.5, 2.5, 3.5, 4.5) ] }; const packedValues = { propertyVec2: [ 0.1, 0.8, 0.3, 0.5, 0.7, 0.2 ], propertyIVec3: [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ], propertyDVec4: [ 0.1, 0.2, 0.3, 0.4, 0.3, 0.2, 0.1, 0, 0.1, 0.2, 0.4, 0.5 ], propertyMat4: [ // the MatrixN constructor is row-major, but internally things are // stored column-major. So these are the transpose of the above 1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2.5, 0.5, 0, 0, 0, 0.25, 3.5, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0 ], propertyIMat3: [ 2, 0, 0, 0, 2, 0, 0, 0, 2, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 2, 3, 2, 3, 1, 3, 1, 2 ], propertyDMat2: [ 1.5, 0, 0, 2.5, 1, 0, 0, 1, 1.5, 3.5, 2.5, 4.5 ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: properties[propertyId] }); const packed = packedValues[propertyId]; const unpacked = property.unpackVectorAndMatrixTypes(packed); const expected = propertyValues[propertyId]; expect(unpacked).toEqual(expected); } } }); it("unpackVectorAndMatrixTypes unpacks nested arrays of vectors", function() { const properties = { propertyVec2: { type: "VEC2", componentType: "FLOAT32", array: true }, propertyIVec3: { type: "VEC3", componentType: "INT32", array: true, count: 3 }, propertyDVec4: { type: "VEC4", componentType: "FLOAT64", array: true }, propertyMat4: { type: "MAT4", componentType: "FLOAT32", array: true }, propertyIMat3: { type: "MAT3", componentType: "FLOAT32", array: true, count: 3 }, propertyDMat2: { type: "MAT2", componentType: "FLOAT32", array: true, count: 3 } }; const propertyValues = { propertyVec2: [ new import__541.Cartesian2(0.1, 0.8), new import__541.Cartesian2(0.3, 0.5), new import__541.Cartesian2(0.7, 0.2) ], propertyIVec3: [ new import__541.Cartesian3(1, 2, 3), new import__541.Cartesian3(4, 5, 6), new import__541.Cartesian3(7, 8, 9) ], propertyDVec4: [ new import__541.Cartesian4(0.1, 0.2, 0.3, 0.4), new import__541.Cartesian4(0.3, 0.2, 0.1, 0), new import__541.Cartesian4(0.1, 0.2, 0.4, 0.5) ], propertyMat4: [ new import__541.Matrix4(1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1), new import__541.Matrix4(0, 2.5, 0, 0, 0, 0.5, 0.25, 0, 0, 0, 3.5, 0, 0, 0, 0, 1), new import__541.Matrix4(1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0) ], propertyIMat3: [ new import__541.Matrix3(2, 0, 0, 0, 2, 0, 0, 0, 2), new import__541.Matrix3(1, 0, 0, 0, 1, 0, 0, 0, 1), new import__541.Matrix3(1, 2, 3, 2, 3, 1, 3, 1, 2) ], propertyDMat2: [ new import__541.Matrix2(1.5, 0, 0, 2.5), new import__541.Matrix2(1, 0, 0, 1), new import__541.Matrix2(1.5, 2.5, 3.5, 4.5) ] }; const packedValues = { propertyVec2: [ [0.1, 0.8], [0.3, 0.5], [0.7, 0.2] ], propertyIVec3: [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ], propertyDVec4: [ [0.1, 0.2, 0.3, 0.4], [0.3, 0.2, 0.1, 0], [0.1, 0.2, 0.4, 0.5] ], propertyMat4: [ // the MatrixN constructor is row-major, but internally things are // stored column-major. So these are the transpose of the above [1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1.5, 0, 0, 0, 0, 1], [0, 0, 0, 0, 2.5, 0.5, 0, 0, 0, 0.25, 3.5, 0, 0, 0, 0, 1], [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0] ], propertyIMat3: [ [2, 0, 0, 0, 2, 0, 0, 0, 2], [1, 0, 0, 0, 1, 0, 0, 0, 1], [1, 2, 3, 2, 3, 1, 3, 1, 2] ], propertyDMat2: [ [1.5, 0, 0, 2.5], [1, 0, 0, 1], [1.5, 3.5, 2.5, 4.5] ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: properties[propertyId] }); const packed = packedValues[propertyId]; const nested = true; const unpacked = property.unpackVectorAndMatrixTypes(packed, nested); const expected = propertyValues[propertyId]; expect(unpacked).toEqual(expected); } } }); it("unpackVectorAndMatrixTypes does not affect other types", function() { if (!import__541.FeatureDetection.supportsBigInt()) { return; } const properties = { propertyString: { type: "STRING" }, propertyBoolean: { type: "BOOLEAN" }, propertyArray: { type: "SCALAR", componentType: "UINT8", array: true, count: 5 }, propertyBigIntArray: { type: "SCALAR", componentType: "UINT64", array: true, count: 2 } }; const propertyValues = { propertyString: ["a", "bc", ""], propertyBoolean: [true, false, false], propertyArray: [ [1, 2, 3, 4, 5], [0, 1, 2, 3, 4], [1, 4, 9, 16, 25] ], propertyBigIntArray: [ [BigInt(0), BigInt(0)], // eslint-disable-line [BigInt(1), BigInt(3)], // eslint-disable-line [BigInt(45), BigInt(32)] // eslint-disable-line ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = import__541.MetadataClassProperty.fromJson({ id: propertyId, property: properties[propertyId] }); const length2 = propertyValues[propertyId].length; for (let i = 0; i < length2; ++i) { const value = propertyValues[propertyId][i]; const unpacked = property.unpackVectorAndMatrixTypes(value); expect(unpacked).toEqual(value); } } } }); it("validate returns undefined if the value is valid", function() { const property = import__541.MetadataClassProperty.fromJson({ id: "position", property: { type: "VEC3", componentType: "FLOAT32" } }); expect(property.validate(new import__541.Cartesian3(1, 2, 3))).toBeUndefined(); }); it("validate returns undefined for valid arrays of vectors", function() { const property = import__541.MetadataClassProperty.fromJson({ id: "position", property: { type: "VEC3", componentType: "FLOAT32", array: true, count: 3 } }); expect( property.validate([ new import__541.Cartesian3(1, 2, 3), new import__541.Cartesian3(4, 5, 6), new import__541.Cartesian3(7, 8, 9) ]) ).toBeUndefined(); }); it("validate returns undefined for valid arrays of matrices", function() { const property = import__541.MetadataClassProperty.fromJson({ id: "position", property: { type: "MAT3", componentType: "FLOAT32", array: true, count: 3 } }); expect( property.validate([ new import__541.Matrix3(1, 0, 0, 0, 1, 0, 0, 0, 1), new import__541.Matrix3(2, 0, 0, 0, 2, 0, 0, 0, 2), new import__541.Matrix3(3, 0, 0, 0, 3, 0, 0, 0, 3) ]) ).toBeUndefined(); }); it("validate returns error message if property is required but value is undefined", function() { const property = import__541.MetadataClassProperty.fromJson({ id: "position", property: { type: "SCALAR", componentType: "FLOAT32", required: true } }); expect(property.validate(void 0)).toBe( "required property must have a value" ); }); it("validate returns undefined if value is undefined but a default is available", function() { const property = import__541.MetadataClassProperty.fromJson({ id: "position", property: { type: "SCALAR", componentType: "FLOAT32", required: true, default: -1 } }); expect(property.validate(void 0)).not.toBeDefined(); }); it("validate returns error message if type is ARRAY and value is not an array", function() { const property = import__541.MetadataClassProperty.fromJson({ id: "position", property: { type: "SCALAR", componentType: "FLOAT32", array: true, count: 8 } }); expect(property.validate(8)).toBe("value 8 must be an array"); }); it("validate returns error message if type is a vector and the component type is not vector-compatibile", function() { const property = import__541.MetadataClassProperty.fromJson({ id: "position", property: { type: "VEC2", componentType: "STRING" } }); expect(property.validate(8)).toBe( "componentType STRING is incompatible with vector type VEC2" ); }); it("validate returns error message if type is a matrix and the component type is not vector-compatibile", function() { const property = import__541.MetadataClassProperty.fromJson({ id: "position", property: { type: "MAT3", componentType: "INT64" } }); expect(property.validate(8)).toBe( "componentType INT64 is incompatible with matrix type MAT3" ); }); it("validate returns error message if type is a vector and value is not a Cartesian", function() { let property = import__541.MetadataClassProperty.fromJson({ id: "position", property: { type: "VEC2", componentType: "FLOAT32" } }); expect(property.validate(8)).toBe("vector value 8 must be a Cartesian2"); property = import__541.MetadataClassProperty.fromJson({ id: "position", property: { type: "VEC3", componentType: "FLOAT32" } }); expect(property.validate(8)).toBe("vector value 8 must be a Cartesian3"); property = import__541.MetadataClassProperty.fromJson({ id: "position", property: { type: "VEC4", componentType: "FLOAT32" } }); expect(property.validate(8)).toBe("vector value 8 must be a Cartesian4"); }); it("validate returns error message if type is a matrix and value is not a Matrix", function() { let property = import__541.MetadataClassProperty.fromJson({ id: "position", property: { type: "MAT2", componentType: "FLOAT32" } }); expect(property.validate(8)).toBe("matrix value 8 must be a Matrix2"); property = import__541.MetadataClassProperty.fromJson({ id: "position", property: { type: "MAT3", componentType: "FLOAT32" } }); expect(property.validate(8)).toBe("matrix value 8 must be a Matrix3"); property = import__541.MetadataClassProperty.fromJson({ id: "position", property: { type: "MAT4", componentType: "FLOAT32" } }); expect(property.validate(8)).toBe("matrix value 8 must be a Matrix4"); }); it("validate returns error message for an array that doesn't match the count", function() { const property = import__541.MetadataClassProperty.fromJson({ id: "position", property: { type: "SCALAR", componentType: "FLOAT32", array: true, count: 6 } }); expect(property.validate([1, 2])).toBe( "Array length does not match property.arrayLength" ); }); it("validate returns error message if enum name is invalid", function() { const myEnum = import__541.MetadataEnum.fromJson({ id: "myEnum", enum: { values: [ { value: 0, name: "ValueA" }, { value: 1, name: "ValueB" }, { value: 999, name: "Other" } ] } }); const property = import__541.MetadataClassProperty.fromJson({ id: "myEnum", property: { type: "ENUM", enumType: "myEnum" }, enums: { myEnum } }); expect(property.validate("INVALID")).toBe( "value INVALID is not a valid enum name for myEnum" ); expect(property.validate(0)).toBe( "value 0 is not a valid enum name for myEnum" ); }); it("validate returns error message if value does not match the type (SCALAR)", function() { const types = [ "INT8", "UINT8", "INT16", "UINT16", "INT32", "UINT32", "INT64", "UINT64", "FLOAT32", "FLOAT64" ]; for (let i = 0; i < types.length; ++i) { const property = import__541.MetadataClassProperty.fromJson({ id: "property", property: { type: "SCALAR", componentType: types[i] } }); expect(property.validate({})).toBe( `value [object Object] does not match type ${types[i]}` ); } }); it("validate returns error message if value does not match the type (BOOLEAN)", function() { const property = import__541.MetadataClassProperty.fromJson({ id: "property", property: { type: "BOOLEAN" } }); expect(property.validate({})).toBe( `value [object Object] does not match type BOOLEAN` ); }); it("validate returns error message if value does not match the type (STRING)", function() { const property = import__541.MetadataClassProperty.fromJson({ id: "property", property: { type: "STRING" } }); expect(property.validate({})).toBe( `value [object Object] does not match type STRING` ); }); it("validate returns error message if value is out of range", function() { if (!import__541.FeatureDetection.supportsBigInt()) { return; } const outOfRangeValues = { INT8: [-129, 128], UINT8: [-1, 256], INT16: [-32769, 32768], UINT16: [-1, 65536], INT32: [-2147483649, 2147483648], UINT32: [-1, 4294967296], INT64: [ BigInt("-9223372036854775809"), // eslint-disable-line BigInt("9223372036854775808") // eslint-disable-line ], UINT64: [ BigInt(-1), // eslint-disable-line BigInt("18446744073709551616") // eslint-disable-line ], FLOAT32: [-Number.MAX_VALUE, Number.MAX_VALUE] }; for (const type in outOfRangeValues) { if (outOfRangeValues.hasOwnProperty(type)) { const values = outOfRangeValues[type]; const property = import__541.MetadataClassProperty.fromJson({ id: "property", property: { type: "SCALAR", componentType: type } }); for (let i = 0; i < values.length; ++i) { expect(property.validate(values[i])).toBe( `value ${values[i]} is out of range for type ${type}` ); } } } }); it("validate returns error message for non-finite values", function() { if (!import__541.FeatureDetection.supportsBigInt()) { return; } const nonFiniteValues = [ NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY ]; const types = [ "INT8", "UINT8", "INT16", "UINT16", "INT32", "UINT32", "INT64", "UINT64", "FLOAT32", "FLOAT64" ]; for (let i = 0; i < types.length; i++) { const type = types[i]; const property = import__541.MetadataClassProperty.fromJson({ id: "property", property: { type: "SCALAR", componentType: type } }); for (let i2 = 0; i2 < nonFiniteValues.length; ++i2) { expect(property.validate(nonFiniteValues[i2])).toBe( `value ${nonFiniteValues[i2]} of type ${type} must be finite` ); } } }); it("validate returns error message if component value is out of range", function() { if (!import__541.FeatureDetection.supportsBigInt()) { return; } const outOfRangeValues = { INT8: [-129, 128], UINT8: [-1, 256], INT16: [-32769, 32768], UINT16: [-1, 65536], INT32: [-2147483649, 2147483648], UINT32: [-1, 4294967296], INT64: [ BigInt("-9223372036854775809"), // eslint-disable-line BigInt("9223372036854775808") // eslint-disable-line ], UINT64: [ BigInt(-1), // eslint-disable-line BigInt("18446744073709551616") // eslint-disable-line ], FLOAT32: [-Number.MAX_VALUE, Number.MAX_VALUE] }; for (const componentType in outOfRangeValues) { if (outOfRangeValues.hasOwnProperty(componentType)) { const values = outOfRangeValues[componentType]; const property = import__541.MetadataClassProperty.fromJson({ id: "property", property: { array: true, type: "SCALAR", componentType } }); for (let i = 0; i < values.length; ++i) { expect(property.validate(values)).toBe( `value ${values[0]} is out of range for type ${componentType}` ); } } } }); it("validate returns error message if value is outside the normalized range", function() { const propertyInt8 = import__541.MetadataClassProperty.fromJson({ id: "property", property: { type: "SCALAR", componentType: "INT8", normalized: true } }); const propertyUint8 = import__541.MetadataClassProperty.fromJson({ id: "property", property: { type: "SCALAR", componentType: "UINT8", normalized: true } }); expect(propertyInt8.validate(-1.1)).toBe( "value -1.1 is out of range for type INT8 (normalized)" ); expect(propertyInt8.validate(1.1)).toBe( "value 1.1 is out of range for type INT8 (normalized)" ); expect(propertyUint8.validate(-0.1)).toBe( "value -0.1 is out of range for type UINT8 (normalized)" ); expect(propertyUint8.validate(1.1)).toBe( "value 1.1 is out of range for type UINT8 (normalized)" ); }); describe("valueTransformInPlace", function() { it("applies function to a scalar", function() { const value = 1; const offset = 1; const scale = 2; const result = import__541.MetadataClassProperty.valueTransformInPlace( value, offset, scale, import__541.MetadataComponentType.applyValueTransform ); expect(result).toBe(3); }); it("applies function to a flat array", function() { const value = [1, 1, 1]; const offset = [1, 2, 3]; const scale = [2, 2, 2]; const result = import__541.MetadataClassProperty.valueTransformInPlace( value, offset, scale, import__541.MetadataComponentType.applyValueTransform ); expect(result).toEqual([3, 4, 5]); }); it("applies function to a nested array", function() { const values = [ [1, 1, 1], [1, 1, 1], [1, 1, 1] ]; const offset = [ [1, 2, 3], [1, 2, 3], [1, 2, 3] ]; const scale = [ [2, 2, 2], [2, 2, 2], [2, 2, 2] ]; const result = import__541.MetadataClassProperty.valueTransformInPlace( values, offset, scale, import__541.MetadataComponentType.applyValueTransform ); expect(result).toEqual([ [3, 4, 5], [3, 4, 5], [3, 4, 5] ]); }); }); }); // packages/engine/Specs/Scene/MetadataClassSpec.js var import__542 = __toESM(require_Cesium(), 1); describe("Scene/MetadataClass", function() { it("creates class with default values", function() { const buildingClass = import__542.MetadataClass.fromJson({ id: "building", class: {} }); expect(buildingClass.id).toBe("building"); expect(buildingClass.properties).toEqual({}); expect(buildingClass.propertiesBySemantic).toEqual({}); expect(buildingClass.name).toBeUndefined(); expect(buildingClass.description).toBeUndefined(); expect(buildingClass.extras).toBeUndefined(); expect(buildingClass.extensions).toBeUndefined(); }); it("creates class", function() { const extras = { cityInfo: { name: "city" } }; const extensions = { EXT_other_extension: {} }; const buildingClass = import__542.MetadataClass.fromJson({ id: "building", class: { name: "Building", description: "Building Class", extras, extensions, properties: { height: { type: "SCALAR", componentType: "FLOAT32" }, position: { type: "SCALAR", componentType: "FLOAT32", array: true, count: 3, semantic: "_POSITION" }, color: { type: "STRING", semantic: "_COLOR" } } } }); expect(buildingClass.id).toBe("building"); expect(buildingClass.name).toBe("Building"); expect(buildingClass.description).toBe("Building Class"); expect(buildingClass.extras).toEqual(extras); expect(buildingClass.extensions).toEqual(extensions); const properties = buildingClass.properties; const heightProperty = properties.height; const positionProperty = properties.position; const colorProperty = properties.color; expect(heightProperty.type).toBe(import__542.MetadataType.SCALAR); expect(heightProperty.componentType).toBe(import__542.MetadataComponentType.FLOAT32); expect(positionProperty.type).toBe(import__542.MetadataType.SCALAR); expect(positionProperty.componentType).toBe(import__542.MetadataComponentType.FLOAT32); expect(colorProperty.type).toBe(import__542.MetadataType.STRING); expect(colorProperty.componentType).not.toBeDefined(); expect(Object.keys(properties).sort()).toEqual([ "color", "height", "position" ]); const propertiesBySemantic = buildingClass.propertiesBySemantic; expect(propertiesBySemantic._COLOR).toBe(colorProperty); expect(propertiesBySemantic._POSITION).toBe(positionProperty); expect(Object.keys(propertiesBySemantic).sort()).toEqual([ "_COLOR", "_POSITION" ]); }); it("creates class with enum property", function() { const colorEnum = import__542.MetadataEnum.fromJson({ id: "color", enum: { values: [ { name: "RED", value: 0 } ] } }); const enums = { color: colorEnum }; const buildingClass = import__542.MetadataClass.fromJson({ id: "building", class: { properties: { color: { type: "ENUM", enumType: "color" } } }, enums }); expect(buildingClass.properties.color.type).toBe(import__542.MetadataType.ENUM); expect(buildingClass.properties.color.componentType).not.toBeDefined(); expect(buildingClass.properties.color.enumType).toBe(colorEnum); }); it("constructor throws without id", function() { expect(function() { return import__542.MetadataClass.fromJson({ class: {} }); }).toThrowDeveloperError(); }); it("constructor throws without class", function() { expect(function() { return import__542.MetadataClass.fromJson({ id: "classId" }); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/MetadataComponentTypeSpec.js var import__543 = __toESM(require_Cesium(), 1); describe("Scene/MetadataComponentType", function() { it("getMinimum", function() { expect(import__543.MetadataComponentType.getMinimum(import__543.MetadataComponentType.INT8)).toBe( -128 ); expect(import__543.MetadataComponentType.getMinimum(import__543.MetadataComponentType.UINT8)).toBe( 0 ); expect(import__543.MetadataComponentType.getMinimum(import__543.MetadataComponentType.INT16)).toBe( -32768 ); expect(import__543.MetadataComponentType.getMinimum(import__543.MetadataComponentType.UINT16)).toBe( 0 ); expect(import__543.MetadataComponentType.getMinimum(import__543.MetadataComponentType.INT32)).toBe( -2147483648 ); expect(import__543.MetadataComponentType.getMinimum(import__543.MetadataComponentType.UINT32)).toBe( 0 ); expect( import__543.MetadataComponentType.getMinimum(import__543.MetadataComponentType.FLOAT32) ).toBe(-34028234663852886e22); expect( import__543.MetadataComponentType.getMinimum(import__543.MetadataComponentType.FLOAT64) ).toBe(-Number.MAX_VALUE); if (import__543.FeatureDetection.supportsBigInt()) { expect( import__543.MetadataComponentType.getMinimum(import__543.MetadataComponentType.INT64) ).toBe( BigInt("-9223372036854775808") // eslint-disable-line ); expect( import__543.MetadataComponentType.getMinimum(import__543.MetadataComponentType.UINT64) ).toBe( BigInt(0) // eslint-disable-line ); } }); it("getMinimum returns approximate number for INT64 when BigInt is not supported", function() { spyOn(import__543.FeatureDetection, "supportsBigInt").and.returnValue(false); expect(import__543.MetadataComponentType.getMinimum(import__543.MetadataComponentType.INT64)).toBe( -Math.pow(2, 63) ); }); it("getMinimum returns number for UINT64 when BigInt is not supported", function() { spyOn(import__543.FeatureDetection, "supportsBigInt").and.returnValue(false); expect(import__543.MetadataComponentType.getMinimum(import__543.MetadataComponentType.UINT64)).toBe( 0 ); }); it("getMinimum throws without type", function() { expect(function() { import__543.MetadataComponentType.getMinimum(); }).toThrowDeveloperError(); }); it("getMinimum throws if type is not a numeric type", function() { expect(function() { import__543.MetadataComponentType.getMinimum(import__543.MetadataComponentType.STRING); }).toThrowDeveloperError(); }); it("getMaximum", function() { expect(import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType.INT8)).toBe( 127 ); expect(import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType.UINT8)).toBe( 255 ); expect(import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType.INT16)).toBe( 32767 ); expect(import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType.UINT16)).toBe( 65535 ); expect(import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType.INT32)).toBe( 2147483647 ); expect(import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType.UINT32)).toBe( 4294967295 ); expect( import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType.FLOAT32) ).toBe(34028234663852886e22); expect( import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType.FLOAT64) ).toBe(Number.MAX_VALUE); if (import__543.FeatureDetection.supportsBigInt()) { expect( import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType.INT64) ).toBe( BigInt("9223372036854775807") // eslint-disable-line ); expect( import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType.UINT64) ).toBe( BigInt("18446744073709551615") // eslint-disable-line ); } }); it("getMaximum returns approximate number for INT64 when BigInt is not supported", function() { spyOn(import__543.FeatureDetection, "supportsBigInt").and.returnValue(false); expect(import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType.INT64)).toBe( Math.pow(2, 63) - 1 ); }); it("getMaximum returns approximate number for UINT64 when BigInt is not supported", function() { spyOn(import__543.FeatureDetection, "supportsBigInt").and.returnValue(false); expect(import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType.UINT64)).toBe( Math.pow(2, 64) - 1 ); }); it("getMaximum throws without type", function() { expect(function() { import__543.MetadataComponentType.getMaximum(); }).toThrowDeveloperError(); }); it("getMaximum throws if type is not a numeric type", function() { expect(function() { import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType.STRING); }).toThrowDeveloperError(); }); it("isIntegerType", function() { expect( import__543.MetadataComponentType.isIntegerType(import__543.MetadataComponentType.INT8) ).toBe(true); expect( import__543.MetadataComponentType.isIntegerType(import__543.MetadataComponentType.UINT8) ).toBe(true); expect( import__543.MetadataComponentType.isIntegerType(import__543.MetadataComponentType.INT16) ).toBe(true); expect( import__543.MetadataComponentType.isIntegerType(import__543.MetadataComponentType.UINT16) ).toBe(true); expect( import__543.MetadataComponentType.isIntegerType(import__543.MetadataComponentType.INT32) ).toBe(true); expect( import__543.MetadataComponentType.isIntegerType(import__543.MetadataComponentType.UINT32) ).toBe(true); expect( import__543.MetadataComponentType.isIntegerType(import__543.MetadataComponentType.INT64) ).toBe(true); expect( import__543.MetadataComponentType.isIntegerType(import__543.MetadataComponentType.UINT64) ).toBe(true); expect( import__543.MetadataComponentType.isIntegerType(import__543.MetadataComponentType.FLOAT32) ).toBe(false); expect( import__543.MetadataComponentType.isIntegerType(import__543.MetadataComponentType.FLOAT64) ).toBe(false); }); it("isIntegerType throws without type", function() { expect(function() { import__543.MetadataComponentType.isIntegerType(); }).toThrowDeveloperError(); }); it("isUnsignedIntegerType", function() { expect( import__543.MetadataComponentType.isUnsignedIntegerType(import__543.MetadataComponentType.INT8) ).toBe(false); expect( import__543.MetadataComponentType.isUnsignedIntegerType(import__543.MetadataComponentType.UINT8) ).toBe(true); expect( import__543.MetadataComponentType.isUnsignedIntegerType(import__543.MetadataComponentType.INT16) ).toBe(false); expect( import__543.MetadataComponentType.isUnsignedIntegerType(import__543.MetadataComponentType.UINT16) ).toBe(true); expect( import__543.MetadataComponentType.isUnsignedIntegerType(import__543.MetadataComponentType.INT32) ).toBe(false); expect( import__543.MetadataComponentType.isUnsignedIntegerType(import__543.MetadataComponentType.UINT32) ).toBe(true); expect( import__543.MetadataComponentType.isUnsignedIntegerType(import__543.MetadataComponentType.INT64) ).toBe(false); expect( import__543.MetadataComponentType.isUnsignedIntegerType(import__543.MetadataComponentType.UINT64) ).toBe(true); expect( import__543.MetadataComponentType.isUnsignedIntegerType(import__543.MetadataComponentType.FLOAT32) ).toBe(false); expect( import__543.MetadataComponentType.isUnsignedIntegerType(import__543.MetadataComponentType.FLOAT64) ).toBe(false); }); it("isUnsignedIntegerType throws without type", function() { expect(function() { import__543.MetadataComponentType.isUnsignedIntegerType(); }).toThrowDeveloperError(); }); it("normalizes signed integers", function() { const signedTypes = ["INT8", "INT16", "INT32"]; const middle = [0.5039370078740157, 0.500015259254738, 0.5000000002328306]; for (let i = 0; i < signedTypes.length; ++i) { const type = signedTypes[i]; const min = import__543.MetadataComponentType.getMinimum(import__543.MetadataComponentType[type]); const max = import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType[type]); const values = [min, min + 1, min / 2, 0, (max + 1) / 2, max]; const expectedResults = [-1, -1, -middle[i], 0, middle[i], 1]; for (let j = 0; j < values.length; ++j) { const result = import__543.MetadataComponentType.normalize(values[j], type); expect(result).toBe(expectedResults[j]); } } }); it("normalizes unsigned integers", function() { const unsignedTypes = ["UINT8", "UINT16", "UINT32"]; for (let i = 0; i < unsignedTypes.length; ++i) { const type = unsignedTypes[i]; const max = import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType[type]); const values = [0, max / 5, max]; const expectedResults = [0, 0.2, 1]; for (let j = 0; j < values.length; ++j) { const result = import__543.MetadataComponentType.normalize(values[j], type); expect(result).toBe(expectedResults[j]); } } }); it("normalizes INT64 integers", function() { if (!import__543.FeatureDetection.supportsBigInt()) { return; } const min = import__543.MetadataComponentType.getMinimum(import__543.MetadataComponentType.INT64); const max = import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType.INT64); const values = [ min, // eslint-disable-next-line no-undef min + BigInt(1), // eslint-disable-next-line no-undef min / BigInt(2), 0, // eslint-disable-next-line no-undef (max + BigInt(1)) / BigInt(2), max ]; const expectedResults = [-1, -1, -0.5, 0, 0.5, 1]; for (let j = 0; j < values.length; ++j) { const result = import__543.MetadataComponentType.normalize( values[j], import__543.MetadataComponentType.INT64 ); expect(result).toBe(expectedResults[j]); } }); it("normalizes UINT64 integers", function() { if (!import__543.FeatureDetection.supportsBigInt()) { return; } const max = import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType.UINT64); const values = [BigInt(0), max / BigInt(5), max]; const expectedResults = [0, 0.2, 1]; for (let j = 0; j < values.length; ++j) { const result = import__543.MetadataComponentType.normalize( values[j], import__543.MetadataComponentType.UINT64 ); expect(result).toBe(expectedResults[j]); } }); it("normalize throws without value", function() { expect(function() { import__543.MetadataComponentType.normalize(); }).toThrowDeveloperError(); }); it("normalize throws without type", function() { expect(function() { import__543.MetadataComponentType.normalize(10); }).toThrowDeveloperError(); }); it("normalize throws if value is not a number or BigInt", function() { expect(function() { import__543.MetadataComponentType.normalize("10", import__543.MetadataComponentType.INT16); }).toThrowDeveloperError(); }); it("normalize throws if type is not an integer type", function() { expect(function() { import__543.MetadataComponentType.normalize(10, import__543.MetadataComponentType.STRING); }).toThrowDeveloperError(); }); it("unnormalizes signed numbers", function() { const signedTypes = ["INT8", "INT16", "INT32"]; const middle = [0.5039370078740157, 0.500015259254738, 0.5000000002328306]; for (let i = 0; i < signedTypes.length; ++i) { const type = signedTypes[i]; const min = import__543.MetadataComponentType.getMinimum(import__543.MetadataComponentType[type]); const max = import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType[type]); const values = [-1, -middle[i], -0.5, 0, middle[i], 0.5, 1]; const expectedResults = [ min + 1, min / 2, min / 2, 0, (max + 1) / 2, (max + 1) / 2, max ]; for (let j = 0; j < values.length; ++j) { const result = import__543.MetadataComponentType.unnormalize(values[j], type); expect(result).toBe(expectedResults[j]); } } }); it("unnormalizes unsigned numbers", function() { const unsignedTypes = ["UINT8", "UINT16", "UINT32"]; for (let i = 0; i < unsignedTypes.length; ++i) { const type = unsignedTypes[i]; const max = import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType[type]); const values = [0, 0.2, 0.5, 1]; const expectedResults = [0, max / 5, (max + 1) / 2, max]; for (let j = 0; j < values.length; ++j) { const result = import__543.MetadataComponentType.unnormalize(values[j], type); expect(result).toBe(expectedResults[j]); } } }); it("unnormalizes INT64", function() { if (!import__543.FeatureDetection.supportsBigInt()) { return; } const min = import__543.MetadataComponentType.getMinimum(import__543.MetadataComponentType.INT64); const max = import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType.INT64); const values = [-1, -0.5, 0, 0.5, 1]; const expectedResults = [ min + BigInt(1), // eslint-disable-line min / BigInt(2), // eslint-disable-line BigInt(0), // eslint-disable-line (max + BigInt(1)) / BigInt(2), // eslint-disable-line max ]; for (let i = 0; i < values.length; ++i) { const result = import__543.MetadataComponentType.unnormalize( values[i], import__543.MetadataComponentType.INT64 ); expect(result).toBe(expectedResults[i]); } }); it("unnormalizes UINT64", function() { if (!import__543.FeatureDetection.supportsBigInt()) { return; } const max = import__543.MetadataComponentType.getMaximum(import__543.MetadataComponentType.UINT64); const values = [0, 0.2, 0.5, 1]; const expectedResults = [ BigInt(0), // eslint-disable-line BigInt(3689348814741910500), // eslint-disable-line BigInt(9223372036854776e3), // eslint-disable-line max ]; for (let i = 0; i < values.length; ++i) { const result = import__543.MetadataComponentType.unnormalize( values[i], import__543.MetadataComponentType.UINT64 ); expect(result).toBe(expectedResults[i]); } }); it("unnormalize clamps values outside the range", function() { expect( import__543.MetadataComponentType.unnormalize(-1.1, import__543.MetadataComponentType.INT8) ).toBe(-127); expect( import__543.MetadataComponentType.unnormalize(-0.1, import__543.MetadataComponentType.UINT8) ).toBe(0); expect( import__543.MetadataComponentType.unnormalize(1.1, import__543.MetadataComponentType.INT8) ).toBe(127); expect( import__543.MetadataComponentType.unnormalize(1.1, import__543.MetadataComponentType.UINT8) ).toBe(255); }); it("unnormalize throws without value", function() { expect(function() { import__543.MetadataComponentType.unnormalize(); }).toThrowDeveloperError(); }); it("unnormalize throws without type", function() { expect(function() { import__543.MetadataComponentType.unnormalize(10); }).toThrowDeveloperError(); }); it("unnormalize throws if type is not an integer type", function() { expect(function() { import__543.MetadataComponentType.unnormalize(10, import__543.MetadataComponentType.FLOAT32); }).toThrowDeveloperError(); }); it("getSizeInBytes", function() { expect( import__543.MetadataComponentType.getSizeInBytes(import__543.MetadataComponentType.INT8) ).toBe(1); expect( import__543.MetadataComponentType.getSizeInBytes(import__543.MetadataComponentType.UINT8) ).toBe(1); expect( import__543.MetadataComponentType.getSizeInBytes(import__543.MetadataComponentType.INT16) ).toBe(2); expect( import__543.MetadataComponentType.getSizeInBytes(import__543.MetadataComponentType.UINT16) ).toBe(2); expect( import__543.MetadataComponentType.getSizeInBytes(import__543.MetadataComponentType.INT32) ).toBe(4); expect( import__543.MetadataComponentType.getSizeInBytes(import__543.MetadataComponentType.UINT32) ).toBe(4); expect( import__543.MetadataComponentType.getSizeInBytes(import__543.MetadataComponentType.INT64) ).toBe(8); expect( import__543.MetadataComponentType.getSizeInBytes(import__543.MetadataComponentType.UINT64) ).toBe(8); expect( import__543.MetadataComponentType.getSizeInBytes(import__543.MetadataComponentType.FLOAT32) ).toBe(4); expect( import__543.MetadataComponentType.getSizeInBytes(import__543.MetadataComponentType.FLOAT64) ).toBe(8); }); it("getSizeInBytes throws without type", function() { expect(function() { import__543.MetadataComponentType.getSizeInBytes(); }).toThrowDeveloperError(); }); it("getSizeInBytes throws if type is not a numeric type", function() { expect(function() { import__543.MetadataComponentType.getSizeInBytes(import__543.MetadataComponentType.STRING); }).toThrowDeveloperError(); }); it("fromComponentDatatype", function() { expect( import__543.MetadataComponentType.fromComponentDatatype(import__543.ComponentDatatype.BYTE) ).toBe(import__543.MetadataComponentType.INT8); expect( import__543.MetadataComponentType.fromComponentDatatype( import__543.ComponentDatatype.UNSIGNED_BYTE ) ).toBe(import__543.MetadataComponentType.UINT8); expect( import__543.MetadataComponentType.fromComponentDatatype(import__543.ComponentDatatype.SHORT) ).toBe(import__543.MetadataComponentType.INT16); expect( import__543.MetadataComponentType.fromComponentDatatype( import__543.ComponentDatatype.UNSIGNED_SHORT ) ).toBe(import__543.MetadataComponentType.UINT16); expect( import__543.MetadataComponentType.fromComponentDatatype(import__543.ComponentDatatype.INT) ).toBe(import__543.MetadataComponentType.INT32); expect( import__543.MetadataComponentType.fromComponentDatatype( import__543.ComponentDatatype.UNSIGNED_INT ) ).toBe(import__543.MetadataComponentType.UINT32); expect( import__543.MetadataComponentType.fromComponentDatatype(import__543.ComponentDatatype.FLOAT) ).toBe(import__543.MetadataComponentType.FLOAT32); expect( import__543.MetadataComponentType.fromComponentDatatype(import__543.ComponentDatatype.DOUBLE) ).toBe(import__543.MetadataComponentType.FLOAT64); }); it("fromComponentDatatype throws without componentDatatype", function() { expect(function() { import__543.MetadataComponentType.fromComponentDatatype(); }).toThrowDeveloperError(); }); it("toComponentDatatype", function() { expect( import__543.MetadataComponentType.toComponentDatatype(import__543.MetadataComponentType.INT8) ).toBe(import__543.ComponentDatatype.BYTE); expect( import__543.MetadataComponentType.toComponentDatatype(import__543.MetadataComponentType.UINT8) ).toBe(import__543.ComponentDatatype.UNSIGNED_BYTE); expect( import__543.MetadataComponentType.toComponentDatatype(import__543.MetadataComponentType.INT16) ).toBe(import__543.ComponentDatatype.SHORT); expect( import__543.MetadataComponentType.toComponentDatatype(import__543.MetadataComponentType.UINT16) ).toBe(import__543.ComponentDatatype.UNSIGNED_SHORT); expect( import__543.MetadataComponentType.toComponentDatatype(import__543.MetadataComponentType.INT32) ).toBe(import__543.ComponentDatatype.INT); expect( import__543.MetadataComponentType.toComponentDatatype(import__543.MetadataComponentType.UINT32) ).toBe(import__543.ComponentDatatype.UNSIGNED_INT); expect( import__543.MetadataComponentType.toComponentDatatype(import__543.MetadataComponentType.FLOAT32) ).toBe(import__543.ComponentDatatype.FLOAT); expect( import__543.MetadataComponentType.toComponentDatatype(import__543.MetadataComponentType.FLOAT64) ).toBe(import__543.ComponentDatatype.DOUBLE); }); it("toComponentDatatype returns undefined for INT64", function() { expect( import__543.MetadataComponentType.toComponentDatatype(import__543.MetadataComponentType.INT64) ).toBeUndefined(); }); it("toComponentDatatype returns undefined for UINT64", function() { expect( import__543.MetadataComponentType.toComponentDatatype(import__543.MetadataComponentType.UINT64) ).toBeUndefined(); }); it("toComponentDatatype throws without type", function() { expect(function() { import__543.MetadataComponentType.toComponentDatatype(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/MetadataEntitySpec.js var import__544 = __toESM(require_Cesium(), 1); describe("Scene/MetadataEntity", function() { let classWithNoPropertiesDefinition; let classDefinition; let properties; let classWithNoDataValues; beforeAll(function() { classWithNoPropertiesDefinition = import__544.MetadataClass.fromJson({ id: "building", class: {} }); classDefinition = import__544.MetadataClass.fromJson({ id: "building", class: { properties: { name: { type: "STRING", semantic: "NAME", required: true }, height: { type: "SCALAR", componentType: "FLOAT32", required: false, default: 10 }, position: { type: "SCALAR", componentType: "FLOAT32", array: true, count: 3, required: true }, axisColors: { array: true, count: 3, type: "VEC3", componentType: "UINT8", normalized: true, required: true }, temperature: { type: "SCALAR", componentType: "UINT8", normalized: true, offset: 32, scale: 180 }, temperatureArray: { array: true, count: 4, type: "SCALAR", componentType: "UINT8", normalized: true, offset: [32, 32, 32, 32], scale: [180, 180, 180, 180] } } } }); classWithNoDataValues = import__544.MetadataClass.fromJson({ id: "noData", class: { properties: { noDefault: { type: "SCALAR", componentType: "INT32", required: false, noData: -1 }, hasDefault: { type: "SCALAR", componentType: "INT32", required: false, noData: -1, default: 100 }, noDefaultVector: { type: "VEC2", componentType: "FLOAT32", required: false, noData: [0, 0] }, hasDefaultVector: { type: "VEC2", componentType: "FLOAT32", required: false, noData: [0, 0], default: [100, 100] }, noDefaultArray: { array: true, type: "SCALAR", componentType: "UINT8", count: 3, required: false, noData: [0, 0, 0] }, hasDefaultArray: { array: true, type: "SCALAR", componentType: "UINT8", required: false, noData: [], default: [1, 1, 1] }, noDefaultArrayOfVector: { array: true, type: "VEC2", componentType: "FLOAT32", count: 3, required: false, noData: [ [0, 0], [0, 0], [0, 0] ] }, hasDefaultArrayOfVector: { array: true, type: "VEC2", componentType: "FLOAT32", required: false, noData: [], default: [ [1, 1], [1, 1] ] } } } }); }); beforeEach(function() { properties = { name: "Building A", position: [0, 0, 0], axisColors: [ [255, 0, 0], [0, 255, 0], [0, 0, 255] ], temperature: 0, temperatureArray: [0, 255, 255, 0] }; }); const noDataProperties = { noDefault: -1, hasDefault: -1, noDefaultVector: [0, 0], hasDefaultVector: [0, 0], noDefaultArray: [0, 0, 0], hasDefaultArray: [], noDefaultArrayOfVector: [ [0, 0], [0, 0], [0, 0] ], hasDefaultArrayOfVector: [] }; it("throws when using MetadataEntity directly", function() { const entity = new import__544.MetadataEntity(); expect(function() { return entity.class; }).toThrowDeveloperError(); expect(function() { entity.hasProperty(); }).toThrowDeveloperError(); expect(function() { entity.hasPropertyBySemantic(); }).toThrowDeveloperError(); expect(function() { entity.getPropertyIds(); }).toThrowDeveloperError(); expect(function() { entity.getProperty(); }).toThrowDeveloperError(); expect(function() { entity.setProperty(); }).toThrowDeveloperError(); expect(function() { entity.getPropertyBySemantic(); }).toThrowDeveloperError(); expect(function() { entity.setPropertyBySemantic(); }).toThrowDeveloperError(); }); it("hasProperty returns false when there are no properties", function() { expect( import__544.MetadataEntity.hasProperty("name", {}, classWithNoPropertiesDefinition) ).toBe(false); }); it("hasProperty returns false when there's no property with the given property ID", function() { expect( import__544.MetadataEntity.hasProperty("volume", properties, classDefinition) ).toBe(false); }); it("hasProperty returns true when there's a property with the given property ID", function() { expect( import__544.MetadataEntity.hasProperty("name", properties, classDefinition) ).toBe(true); }); it("hasProperty returns true when the class has a default value for a missing property", function() { expect( import__544.MetadataEntity.hasProperty("height", properties, classDefinition) ).toBe(true); }); it("hasProperty throws without propertyId", function() { expect(function() { import__544.MetadataEntity.hasProperty(void 0, properties, classDefinition); }).toThrowDeveloperError(); }); it("hasProperty throws without properties", function() { expect(function() { import__544.MetadataEntity.hasProperty("name", void 0, classDefinition); }).toThrowDeveloperError(); }); it("hasProperty throws without classDefinition", function() { expect(function() { import__544.MetadataEntity.hasProperty("name", properties, void 0); }).toThrowDeveloperError(); }); it("hasPropertyBySemantic returns false when there's no properties", function() { expect( import__544.MetadataEntity.hasPropertyBySemantic( "NAME", {}, classWithNoPropertiesDefinition ) ).toBe(false); }); it("hasPropertyBySemantic returns false when there's no property with the given property ID", function() { expect( import__544.MetadataEntity.hasPropertyBySemantic( "VOLUME", properties, classDefinition ) ).toBe(false); }); it("hasPropertyBySemantic returns true when there's a property with the given property ID", function() { expect( import__544.MetadataEntity.hasPropertyBySemantic("NAME", properties, classDefinition) ).toBe(true); }); it("hasPropertyBySemantic returns true when the class has a default value for a missing property", function() { expect( import__544.MetadataEntity.hasPropertyBySemantic("NAME", properties, classDefinition) ).toBe(true); }); it("hasPropertyBySemantic throws without semantic", function() { expect(function() { import__544.MetadataEntity.hasPropertyBySemantic( void 0, properties, classDefinition ); }).toThrowDeveloperError(); }); it("hasPropertyBySemantic throws without properties", function() { expect(function() { import__544.MetadataEntity.hasPropertyBySemantic("NAME", void 0, classDefinition); }).toThrowDeveloperError(); }); it("hasPropertyBySemantic throws without class definition", function() { expect(function() { import__544.MetadataEntity.hasPropertyBySemantic("NAME", properties, void 0); }).toThrowDeveloperError(); }); it("getPropertyIds returns empty array when there are no properties", function() { expect( import__544.MetadataEntity.getPropertyIds({}, classWithNoPropertiesDefinition).length ).toBe(0); }); it("getPropertyIds returns array of property IDs", function() { expect( import__544.MetadataEntity.getPropertyIds(properties, classDefinition).sort() ).toEqual([ "axisColors", "height", "name", "position", "temperature", "temperatureArray" ]); }); it("getPropertyIds uses results argument", function() { const results = []; const returnedResults = import__544.MetadataEntity.getPropertyIds( properties, classDefinition, results ); expect(results).toBe(returnedResults); expect(results.sort()).toEqual([ "axisColors", "height", "name", "position", "temperature", "temperatureArray" ]); }); it("getPropertyIds throws without properties", function() { expect(function() { import__544.MetadataEntity.getPropertyIds(void 0, classDefinition); }).toThrowDeveloperError(); }); it("getPropertyIds throws without classDefinition", function() { expect(function() { const results = []; import__544.MetadataEntity.getPropertyIds(properties, void 0, results); }).toThrowDeveloperError(); }); it("getProperty throws when there's no property with the given property ID", function() { expect(function() { return import__544.MetadataEntity.getProperty("volume", properties, classDefinition); }).toThrowDeveloperError(); }); it("getProperty returns the property value", function() { const value = import__544.MetadataEntity.getProperty( "position", properties, classDefinition ); expect(value).toEqual(properties.position); }); it("getProperty returns the default value when the property is missing", function() { expect( import__544.MetadataEntity.getProperty("height", properties, classDefinition) ).toBe(10); }); it("getProperty handles noData correctly", function() { expect( import__544.MetadataEntity.getProperty( "noDefault", noDataProperties, classWithNoDataValues ) ).not.toBeDefined(); expect( import__544.MetadataEntity.getProperty( "hasDefault", noDataProperties, classWithNoDataValues ) ).toBe(100); expect( import__544.MetadataEntity.getProperty( "noDefaultVector", noDataProperties, classWithNoDataValues ) ).not.toBeDefined(); expect( import__544.MetadataEntity.getProperty( "hasDefaultVector", noDataProperties, classWithNoDataValues ) ).toEqual(new import__544.Cartesian2(100, 100)); expect( import__544.MetadataEntity.getProperty( "noDefaultArray", noDataProperties, classWithNoDataValues ) ).not.toBeDefined(); expect( import__544.MetadataEntity.getProperty( "hasDefaultArray", noDataProperties, classWithNoDataValues ) ).toEqual([1, 1, 1]); expect( import__544.MetadataEntity.getProperty( "noDefaultArrayOfVector", noDataProperties, classWithNoDataValues ) ).not.toBeDefined(); expect( import__544.MetadataEntity.getProperty( "hasDefaultArrayOfVector", noDataProperties, classWithNoDataValues ) ).toEqual([new import__544.Cartesian2(1, 1), new import__544.Cartesian2(1, 1)]); }); it("handles offset and scale", function() { expect( import__544.MetadataEntity.getProperty("temperature", properties, classDefinition) ).toEqual(32); expect( import__544.MetadataEntity.getProperty( "temperatureArray", properties, classDefinition ) ).toEqual([32, 212, 212, 32]); }); it("getProperty throws without propertyId", function() { expect(function() { import__544.MetadataEntity.getProperty(void 0, properties, classDefinition); }).toThrowDeveloperError(); }); it("getProperty throws without properties", function() { expect(function() { import__544.MetadataEntity.getProperty("name", void 0, classDefinition); }).toThrowDeveloperError(); }); it("getProperty throws without classDefinition", function() { expect(function() { import__544.MetadataEntity.getProperty("name", properties, void 0); }).toThrowDeveloperError(); }); it("getProperty handles arrays of vectors correctly", function() { expect( import__544.MetadataEntity.getProperty("axisColors", properties, classDefinition) ).toEqual([ new import__544.Cartesian3(1, 0, 0), new import__544.Cartesian3(0, 1, 0), new import__544.Cartesian3(0, 0, 1) ]); }); it("setProperty returns false if property doesn't exist", function() { expect( import__544.MetadataEntity.setProperty("volume", 100, properties, classDefinition) ).toBe(false); }); it("setProperty sets property value", function() { const position = [1, 1, 1]; expect( import__544.MetadataEntity.setProperty( "position", position, properties, classDefinition ) ).toBe(true); const retrievedPosition = import__544.MetadataEntity.getProperty( "position", properties, classDefinition ); expect(retrievedPosition).toEqual(position); expect(retrievedPosition).not.toBe(position); }); it("setProperty handles arrays of vectors correctly", function() { const axisColors = [ new import__544.Cartesian3(1, 0, 0), new import__544.Cartesian3(0, 1, 0), new import__544.Cartesian3(0, 0, 1) ]; expect( import__544.MetadataEntity.setProperty( "axisColors", axisColors, properties, classDefinition ) ).toBe(true); const retrievedPosition = import__544.MetadataEntity.getProperty( "axisColors", properties, classDefinition ); expect(retrievedPosition).toEqual(axisColors); expect(retrievedPosition).not.toBe(axisColors); }); it("handles offset and scale", function() { expect( import__544.MetadataEntity.setProperty("temperature", 70, properties, classDefinition) ).toBe(true); expect( import__544.MetadataEntity.getProperty("temperature", properties, classDefinition) ).toEqualEpsilon(70.11764705882354, import__544.Math.EPSILON15); const values = [32, 32, 32, 32]; expect( import__544.MetadataEntity.setProperty( "temperatureArray", values, properties, classDefinition ) ).toBe(true); const result = import__544.MetadataEntity.getProperty( "temperatureArray", properties, classDefinition ); expect(result).toEqual(values); expect(result).not.toBe(values); }); it("setProperty throws without propertyId", function() { expect(function() { import__544.MetadataEntity.setProperty( void 0, "Building B", properties, classDefinition ); }).toThrowDeveloperError(); }); it("setProperty throws without value", function() { expect(function() { import__544.MetadataEntity.setProperty( "name", void 0, properties, classDefinition ); }).toThrowDeveloperError(); }); it("setProperty throws without properties", function() { expect(function() { import__544.MetadataEntity.setProperty( "name", "Building B", void 0, classDefinition ); }).toThrowDeveloperError(); }); it("setProperty throws without classDefinition", function() { expect(function() { import__544.MetadataEntity.setProperty("name", "Building B", properties, void 0); }).toThrowDeveloperError(); }); it("getPropertyBySemantic returns undefined when there's no property with the given semantic", function() { expect( import__544.MetadataEntity.getPropertyBySemantic( "HEIGHT", properties, classDefinition ) ).toBeUndefined(); }); it("getPropertyBySemantic returns the property value", function() { expect( import__544.MetadataEntity.getPropertyBySemantic("NAME", properties, classDefinition) ).toBe("Building A"); }); it("getPropertyBySemantic throws without semantic", function() { expect(function() { import__544.MetadataEntity.getPropertyBySemantic( void 0, properties, classDefinition ); }).toThrowDeveloperError(); }); it("getPropertyBySemantic throws without properties", function() { expect(function() { import__544.MetadataEntity.getPropertyBySemantic("NAME", void 0, classDefinition); }).toThrowDeveloperError(); }); it("getPropertyBySemantic throws without classDefinition", function() { expect(function() { import__544.MetadataEntity.getPropertyBySemantic("NAME", properties, void 0); }).toThrowDeveloperError(); }); it("setPropertyBySemantic sets property value", function() { expect( import__544.MetadataEntity.setPropertyBySemantic( "NAME", "Building B", properties, classDefinition ) ).toBe(true); expect( import__544.MetadataEntity.getProperty("name", properties, classDefinition) ).toBe("Building B"); }); it("setPropertyBySemantic returns false if the semantic does not exist", function() { expect( import__544.MetadataEntity.setPropertyBySemantic( "HEIGHT", 20, properties, classDefinition ) ).toBe(false); }); it("setPropertyBySemantic throws without semantic", function() { expect(function() { import__544.MetadataEntity.setPropertyBySemantic( void 0, "Building B", properties, classDefinition ); }).toThrowDeveloperError(); }); it("setPropertyBySemantic throws without value", function() { expect(function() { import__544.MetadataEntity.setPropertyBySemantic( "NAME", void 0, properties, classDefinition ); }).toThrowDeveloperError(); }); it("setPropertyBySemantic throws without properties", function() { expect(function() { import__544.MetadataEntity.setPropertyBySemantic( "NAME", "Building B", void 0, classDefinition ); }).toThrowDeveloperError(); }); it("setPropertyBySemantic throws without classDefinition", function() { expect(function() { import__544.MetadataEntity.setPropertyBySemantic( "NAME", "Building B", properties, void 0 ); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/MetadataEnumSpec.js var import__545 = __toESM(require_Cesium(), 1); describe("Scene/MetadataEnum", function() { it("creates enum with default values", function() { const colorEnum = import__545.MetadataEnum.fromJson({ id: "color", enum: { values: [ { name: "RED", value: 0 }, { name: "GREEN", value: 1 }, { name: "BLUE", value: 2 } ] } }); expect(colorEnum.values[0].name).toBe("RED"); expect(colorEnum.values[1].name).toBe("GREEN"); expect(colorEnum.values[2].name).toBe("BLUE"); expect(colorEnum.valueType).toBe(import__545.MetadataComponentType.UINT16); expect(colorEnum.id).toBe("color"); expect(colorEnum.name).toBeUndefined(); expect(colorEnum.description).toBeUndefined(); expect(colorEnum.extras).toBeUndefined(); expect(colorEnum.extensions).toBeUndefined(); }); it("creates enum", function() { const extras = { gain: 0.5, offset: 0.1 }; const extensions = { EXT_other_extension: {} }; const colorEnum = import__545.MetadataEnum.fromJson({ id: "color", enum: { name: "Color", description: "Common colors", extras, extensions, valueType: import__545.MetadataComponentType.UINT64, values: [ { name: "RED", value: 0 }, { name: "GREEN", value: 1 }, { name: "BLUE", value: 2 } ] } }); expect(colorEnum.values[0].name).toBe("RED"); expect(colorEnum.values[1].name).toBe("GREEN"); expect(colorEnum.values[2].name).toBe("BLUE"); expect(colorEnum.valueType).toBe(import__545.MetadataComponentType.UINT64); expect(colorEnum.id).toBe("color"); expect(colorEnum.name).toBe("Color"); expect(colorEnum.description).toBe("Common colors"); expect(colorEnum.extras).toEqual(extras); expect(colorEnum.extensions).toEqual(extensions); }); it("constructor throws without id", function() { expect(function() { return import__545.MetadataEnum.fromJson({ enum: { values: [ { name: "RED", value: 0 } ] } }); }).toThrowDeveloperError(); }); it("constructor throws without enum", function() { expect(function() { return import__545.MetadataEnum.fromJson({ id: "enumId" }); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/MetadataEnumValueSpec.js var import__546 = __toESM(require_Cesium(), 1); describe("Scene/MetadataEnumValue", function() { it("creates enum value", function() { const extras = { gain: 0.5, offset: 0.1 }; const extensions = { EXT_other_extension: {} }; const enumValue = import__546.MetadataEnumValue.fromJson({ name: "RED", description: "Red color", value: 0, extras, extensions }); expect(enumValue.name).toBe("RED"); expect(enumValue.description).toBe("Red color"); expect(enumValue.value).toBe(0); expect(enumValue.extras).toEqual(extras); expect(enumValue.extensions).toEqual(extensions); }); it("constructor throws without value", function() { expect(function() { return import__546.MetadataEnumValue.fromJson(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/MetadataSchemaLoaderSpec.js var import__547 = __toESM(require_Cesium(), 1); describe("Scene/MetadataSchemaLoader", function() { const schemaJson = { classes: { tree: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" }, type: { type: "ENUM", enumType: "treeType" } } } }, enums: { treeType: { values: [ { name: "Coniferous", value: 0 }, { name: "Deciduous", value: 1 } ] } } }; const resource = new import__547.Resource({ url: "https://example.com/schema.json" }); afterEach(function() { import__547.ResourceCache.clearForSpecs(); }); it("throws if neither options.schema nor options.resource are defined", function() { expect(function() { return new import__547.MetadataSchemaLoader({ schema: void 0, resource: void 0 }); }).toThrowDeveloperError(); }); it("throws if both options.schema and options.resource are defined", function() { expect(function() { return new import__547.MetadataSchemaLoader({ resource, schema: schemaJson }); }).toThrowDeveloperError(); }); it("load throws if schema cannot be fetched", async function() { spyOn(import__547.Resource.prototype, "fetchJson").and.callFake(function() { const error = new Error("404 Not Found"); return Promise.reject(error); }); const schemaLoader = new import__547.MetadataSchemaLoader({ resource }); await expectAsync(schemaLoader.load()).toBeRejectedWithError( import__547.RuntimeError, "Failed to load schema: https://example.com/schema.json\n404 Not Found" ); }); it("loads schema from JSON", async function() { const schemaLoader = new import__547.MetadataSchemaLoader({ schema: schemaJson }); await schemaLoader.load(); const schema = schemaLoader.schema; expect(schema).toBeDefined(); const enums = schema.enums; expect(enums.treeType).toBeDefined(); const classes = schema.classes; expect(classes.tree).toBeDefined(); }); it("loads external schema", async function() { const fetchJson = spyOn(import__547.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(schemaJson) ); const schemaLoader = new import__547.MetadataSchemaLoader({ resource }); await schemaLoader.load(); expect(fetchJson).toHaveBeenCalled(); const schema = schemaLoader.schema; expect(schema).toBeDefined(); const enums = schema.enums; expect(enums.treeType).toBeDefined(); const classes = schema.classes; expect(classes.tree).toBeDefined(); }); it("destroys schema", async function() { spyOn(import__547.Resource.prototype, "fetchJson").and.returnValue( Promise.resolve(schemaJson) ); const schemaLoader = new import__547.MetadataSchemaLoader({ resource }); expect(schemaLoader.schema).not.toBeDefined(); await schemaLoader.load(); expect(schemaLoader.schema).toBeDefined(); expect(schemaLoader.isDestroyed()).toBe(false); schemaLoader.destroy(); expect(schemaLoader.schema).not.toBeDefined(); expect(schemaLoader.isDestroyed()).toBe(true); }); async function resolveJsonAfterDestroy(rejectPromise) { spyOn(import__547.Resource.prototype, "fetchJson").and.callFake( () => rejectPromise ? Promise.reject(new Error()) : Promise.resolve(schemaJson) ); const schemaLoader = new import__547.MetadataSchemaLoader({ resource }); expect(schemaLoader.schema).not.toBeDefined(); const promise = schemaLoader.load(); expect(schemaLoader._state).toBe(import__547.ResourceLoaderState.LOADING); schemaLoader.destroy(); await expectAsync(promise).toBeResolved(); expect(schemaLoader.schema).not.toBeDefined(); expect(schemaLoader.isDestroyed()).toBe(true); } it("handles resolving json after destroy", function() { return resolveJsonAfterDestroy(false); }); it("handles rejecting json after destroy", function() { return resolveJsonAfterDestroy(true); }); }); // packages/engine/Specs/Scene/MetadataSchemaSpec.js var import__548 = __toESM(require_Cesium(), 1); describe("Scene/MetadataSchema", function() { it("creates schema with default values", function() { const schema = import__548.MetadataSchema.fromJson({}); expect(schema.classes).toEqual({}); expect(schema.enums).toEqual({}); expect(schema.name).toBeUndefined(); expect(schema.description).toBeUndefined(); expect(schema.version).toBeUndefined(); expect(schema.extras).toBeUndefined(); }); it("creates schema", function() { const extras = { description: "Extra" }; const extensions = { EXT_other_extension: {} }; const schema = import__548.MetadataSchema.fromJson({ enums: { color: { values: [ { name: "RED", value: 0 }, { name: "GREEN", value: 1 }, { name: "BLUE", value: 2 } ] }, species: { values: [ { name: "Oak", value: 0 }, { name: "Pine", value: 1 }, { name: "Other", value: -1 } ] } }, classes: { city: { properties: { name: { type: "STRING" } } }, neighborhood: { properties: { color: { type: "ENUM", enumType: "color" }, coordinates: { type: "SCALAR", componentType: "FLOAT64", array: true, count: 2 } } }, tree: { properties: { species: { type: "ENUM", array: true, enumType: "species" }, height: { type: "SCALAR", componentType: "FLOAT32" } } } }, id: "mySchema", name: "My Schema", description: "My Schema Description", version: "3.1.0", extras, extensions }); const cityClass = schema.classes.city; const neighborhoodClass = schema.classes.neighborhood; const treeClass = schema.classes.tree; const cityProperties = cityClass.properties; const neighborhoodProperties = neighborhoodClass.properties; const treeProperties = treeClass.properties; expect(cityClass.id).toBe("city"); expect(neighborhoodClass.id).toBe("neighborhood"); expect(treeClass.id).toBe("tree"); expect(cityProperties.name.id).toBe("name"); expect(neighborhoodProperties.color.enumType.id).toBe("color"); expect(neighborhoodProperties.coordinates.id).toBe("coordinates"); expect(treeProperties.species.enumType.id).toBe("species"); expect(treeProperties.height.id).toBe("height"); expect(schema.id).toBe("mySchema"); expect(schema.name).toBe("My Schema"); expect(schema.description).toBe("My Schema Description"); expect(schema.version).toBe("3.1.0"); expect(schema.extras).toEqual(extras); expect(schema.extensions).toEqual(extensions); }); it("constructor throws without schema", function() { expect(function() { return import__548.MetadataSchema.fromJson(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/MetadataTablePropertySpec.js var import__549 = __toESM(require_Cesium(), 1); describe("Scene/MetadataTableProperty", function() { if (!MetadataTester_default.isSupported()) { return; } const enums = { myEnum: { values: [ { value: 0, name: "ValueA" }, { value: 1, name: "ValueB" }, { value: 999, name: "Other" } ] } }; it("creates metadata table property", function() { const extras = { other: 0 }; const extensions = { EXT_other_extension: {} }; const property = new import__549.MetadataTableProperty({ count: 2, property: { values: 0, extras, extensions }, classProperty: import__549.MetadataClassProperty.fromJson({ id: "property", property: { type: "SCALAR", componentType: "FLOAT32" } }), bufferViews: { 0: new Uint8Array(8) } }); expect(property.extras).toBe(extras); expect(property.extensions).toBe(extensions); expect(property.byteLength).toBe(8); }); it("constructs properties with stringOffsets and arrayOffsets", function() { const extras = { other: 0 }; const extensions = { EXT_other_extension: {} }; const a = 97; const b = 98; const c = 99; const d = 100; const e = 101; const property = new import__549.MetadataTableProperty({ count: 2, property: { values: 0, extras, extensions, stringOffsetType: "UINT16", stringOffsets: 1, arrayOffsetType: "UINT8", arrayOffsets: 2 }, classProperty: import__549.MetadataClassProperty.fromJson({ id: "property", property: { type: "STRING", array: true } }), bufferViews: { 0: new Uint8Array([a, b, b, c, c, c, d, d, d, d, e, e, e, e, e]), 1: new Uint8Array([0, 0, 1, 0, 3, 0, 6, 0, 10, 0, 15, 0]), 2: new Uint8Array([0, 3, 5]) } }); expect(property.extras).toBe(extras); expect(property.extensions).toBe(extensions); expect(property._stringOffsets._componentType).toBe( import__549.MetadataComponentType.UINT16 ); expect(property._arrayOffsets._componentType).toBe( import__549.MetadataComponentType.UINT8 ); expect(property.get(0)).toEqual(["a", "bb", "ccc"]); expect(property.get(1)).toEqual(["dddd", "eeeee"]); expect(property.byteLength).toBe(30); }); it("constructs property with EXT_feature_metadata schema", function() { const extras = { other: 0 }; const extensions = { EXT_other_extension: {} }; const a = 97; const b = 98; const c = 99; const d = 100; const e = 101; const property = new import__549.MetadataTableProperty({ count: 2, property: { bufferView: 0, extras, extensions, offsetType: "UINT16", stringOffsetBufferView: 1, arrayOffsetBufferView: 2 }, classProperty: import__549.MetadataClassProperty.fromJson({ id: "property", property: { type: "STRING", array: true } }), bufferViews: { 0: new Uint8Array([a, b, b, c, c, c, d, d, d, d, e, e, e, e, e]), 1: new Uint8Array([0, 0, 1, 0, 3, 0, 6, 0, 10, 0, 15, 0]), 2: new Uint8Array([0, 0, 3, 0, 5, 0]) } }); expect(property.extras).toBe(extras); expect(property.extensions).toBe(extensions); expect(property._stringOffsets._componentType).toBe( import__549.MetadataComponentType.UINT16 ); expect(property._arrayOffsets._componentType).toBe( import__549.MetadataComponentType.UINT16 ); expect(property.get(0)).toEqual(["a", "bb", "ccc"]); expect(property.get(1)).toEqual(["dddd", "eeeee"]); expect(property.byteLength).toBe(33); }); it("creates with offset and scale", function() { const property = new import__549.MetadataTableProperty({ count: 2, property: { values: 0, offset: [ [-1, -1], [-1, -1] ], scale: [ [2, 2], [2, 2] ] }, classProperty: import__549.MetadataClassProperty.fromJson({ id: "property", property: { type: "VEC2", componentType: "UINT8", normalized: true, array: true, count: 2, offset: [ [-1, -1], [0, 0] ], scale: [ [2, 2], [4, 4] ] } }), bufferViews: { 0: new Uint8Array([0, 127, 127, 255, 0, 0, 255, 255]) } }); expect(property.hasValueTransform).toBe(true); expect(property.offset).toEqual([-1, -1, -1, -1]); expect(property.scale).toEqual([2, 2, 2, 2]); expect(property.byteLength).toBe(8); }); it("creates with offset and scale inherited from class property", function() { const property = new import__549.MetadataTableProperty({ count: 2, property: { values: 0 }, classProperty: import__549.MetadataClassProperty.fromJson({ id: "property", property: { type: "VEC2", componentType: "UINT8", normalized: true, array: true, count: 2, offset: [ [-1, -1], [-1, -1] ], scale: [ [2, 2], [2, 2] ] } }), bufferViews: { 0: new Uint8Array([0, 127, 127, 255, 0, 0, 255, 255]) } }); expect(property.hasValueTransform).toBe(true); expect(property.offset).toEqual([-1, -1, -1, -1]); expect(property.scale).toEqual([2, 2, 2, 2]); expect(property.byteLength).toBe(8); }); it("creates with default offset and scale", function() { const property = new import__549.MetadataTableProperty({ count: 2, property: { values: 0 }, classProperty: import__549.MetadataClassProperty.fromJson({ id: "property", property: { type: "VEC2", componentType: "UINT8", normalized: true, array: true, count: 2 } }), bufferViews: { 0: new Uint8Array([0, 127, 127, 255, 0, 0, 255, 255]) } }); expect(property.hasValueTransform).toBe(false); expect(property.offset).toEqual([0, 0, 0, 0]); expect(property.scale).toEqual([1, 1, 1, 1]); expect(property.byteLength).toBe(8); }); it("constructor throws without count", function() { expect(function() { return new import__549.MetadataTableProperty({ property: {}, classProperty: {}, bufferViews: {} }); }).toThrowDeveloperError(); }); it("constructor throws if count is less than 1", function() { expect(function() { return new import__549.MetadataTableProperty({ count: 0, property: {}, classProperty: {}, bufferViews: {} }); }).toThrowDeveloperError(); }); it("constructor throws without property", function() { expect(function() { return new import__549.MetadataTableProperty({ count: 1, classProperty: {}, bufferViews: {} }); }).toThrowDeveloperError(); }); it("constructor throws without bufferViews", function() { expect(function() { return new import__549.MetadataTableProperty({ count: 1, property: {}, classProperty: {} }); }).toThrowDeveloperError(); }); function testGetUint64(options) { options = (0, import__549.defaultValue)(options, import__549.defaultValue.EMPTY_OBJECT); const disableBigIntSupport = options.disableBigIntSupport; const disableBigUint64ArraySupport = options.disableBigUint64ArraySupport; const originalValues = [ BigInt(0), // eslint-disable-line BigInt(10), // eslint-disable-line BigInt("4611686018427387833"), // eslint-disable-line BigInt("18446744073709551615") // eslint-disable-line ]; let expectedValues = originalValues; if (disableBigUint64ArraySupport && disableBigIntSupport) { expectedValues = [0, 10, 4611686018427388e3, 18446744073709552e3]; } const classProperty = { type: "SCALAR", componentType: "UINT64" }; const property = MetadataTester_default.createProperty({ property: classProperty, values: originalValues, disableBigUint64ArraySupport, disableBigIntSupport }); const length2 = originalValues.length; for (let i = 0; i < length2; ++i) { const value = property.get(i); expect(value).toEqual(expectedValues[i]); } } function testGetInt64(options) { options = (0, import__549.defaultValue)(options, import__549.defaultValue.EMPTY_OBJECT); const disableBigIntSupport = options.disableBigIntSupport; const disableBigInt64ArraySupport = options.disableBigInt64ArraySupport; const originalValues = [ BigInt("-9223372036854775808"), // eslint-disable-line BigInt("-4611686018427387833"), // eslint-disable-line BigInt(-10), // eslint-disable-line BigInt(0), // eslint-disable-line BigInt(10), // eslint-disable-line BigInt("4611686018427387833"), // eslint-disable-line BigInt("9223372036854775807") // eslint-disable-line ]; let expectedValues = originalValues; if (disableBigInt64ArraySupport && disableBigIntSupport) { expectedValues = [ -9223372036854776e3, -4611686018427388e3, -10, 0, 10, 4611686018427388e3, 9223372036854776e3 ]; } const classProperty = { type: "SCALAR", componentType: "INT64" }; const property = MetadataTester_default.createProperty({ property: classProperty, values: originalValues, disableBigInt64ArraySupport, disableBigIntSupport }); const length2 = originalValues.length; for (let i = 0; i < length2; ++i) { const value = property.get(i); expect(value).toEqual(expectedValues[i]); } } it("get returns UINT64 property as BigInt when BigUint64Array is not supported and BigInt is supported", function() { testGetUint64({ disableBigUint64ArraySupport: true }); }); it("get returns UINT64 property as number when BigUint64Array is not supported and BigInt is not supported", function() { testGetUint64({ disableBigUint64ArraySupport: true, disableBigIntSupport: true }); }); it("get returns INT64 property as BigInt when BigInt64Array is supported and BigInt is supported", function() { testGetInt64(); }); it("get returns INT64 property as BigInt when BigInt64Array is not supported and BigInt is supported", function() { testGetInt64({ disableBigInt64ArraySupport: true }); }); it("get returns INT64 property as number when BigInt64Array is not supported and BigInt is not supported", function() { testGetInt64({ disableBigInt64ArraySupport: true, disableBigIntSupport: true }); }); it("get returns single values", function() { const properties = { propertyInt8: { type: "SCALAR", componentType: "INT8" }, propertyUint8: { type: "SCALAR", componentType: "UINT8" }, propertyInt16: { type: "SCALAR", componentType: "INT16" }, propertyUint16: { type: "SCALAR", componentType: "UINT16" }, propertyInt32: { type: "SCALAR", componentType: "INT32" }, propertyUint32: { type: "SCALAR", componentType: "UINT32" }, propertyFloat32: { type: "SCALAR", componentType: "FLOAT32" }, propertyFloat64: { type: "SCALAR", componentType: "FLOAT64" }, propertyBoolean: { type: "BOOLEAN" }, propertyString: { type: "STRING" }, propertyEnum: { type: "ENUM", enumType: "myEnum" } }; const propertyValues = { propertyInt8: [-128, -10, 0, 10, 127], propertyUint8: [0, 10, 20, 30, 255], propertyInt16: [-32768, -10, 0, 10, 32767], propertyUint16: [0, 10, 20, 30, 65535], propertyInt32: [-2147483648, -10, 0, 10, 2147483647], propertyUint32: [0, 10, 20, 30, 4294967295], propertyFloat32: [-2.5, -1, 0, 700, Number.POSITIVE_INFINITY], propertyFloat64: [-234934.12, -1, 0, 700, Number.POSITIVE_INFINITY], propertyBoolean: [false, true, false, true, false], propertyString: ["\u304A\u306F\u3088\u3046\u3054\u3056\u3044\u307E\u3059\u3002\u{1F603}", "a", "", "def", "0001"], propertyEnum: ["ValueA", "ValueB", "Other", "ValueA", "ValueA"] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = MetadataTester_default.createProperty({ property: properties[propertyId], values: propertyValues[propertyId], enums }); const expectedValues = propertyValues[propertyId]; const length2 = expectedValues.length; for (let i = 0; i < length2; ++i) { const value = property.get(i); expect(value).toEqual(expectedValues[i]); } } } }); it("get returns vector values", function() { const properties = { propertyInt8: { type: "VEC3", componentType: "INT8" }, propertyUint8: { type: "VEC3", componentType: "UINT8" }, propertyInt16: { type: "VEC3", componentType: "INT16" }, propertyUint16: { type: "VEC3", componentType: "UINT16" }, propertyInt32: { type: "VEC3", componentType: "INT32" }, propertyUint32: { type: "VEC3", componentType: "UINT32" }, propertyFloat32: { type: "VEC3", componentType: "FLOAT32" }, propertyFloat64: { type: "VEC3", componentType: "FLOAT64" } }; const propertyValues = { propertyInt8: [ [-2, -1, 0], [1, 2, 3] ], propertyUint8: [ [0, 1, 2], [3, 4, 5] ], propertyInt16: [ [-2, -1, 0], [1, 2, 3] ], propertyUint16: [ [0, 1, 2], [3, 4, 5] ], propertyInt32: [ [-2, -1, 0], [1, 2, 3] ], propertyUint32: [ [0, 1, 2], [3, 4, 5] ], propertyFloat32: [ [-2, -1, 0], [1, 2, 3] ], propertyFloat64: [ [-2, -1, 0], [1, 2, 3] ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = MetadataTester_default.createProperty({ property: properties[propertyId], values: propertyValues[propertyId], enums }); const expectedValues = propertyValues[propertyId]; const length2 = expectedValues.length; for (let i = 0; i < length2; ++i) { const value = property.get(i); expect(value).toEqual(import__549.Cartesian3.unpack(expectedValues[i])); } } } }); it("get returns fixed size arrays", function() { const properties = { propertyInt64: { type: "SCALAR", componentType: "INT64", array: true, count: 3 }, propertyUint64: { type: "SCALAR", componentType: "UINT64", array: true, count: 3 }, propertyBoolean: { type: "BOOLEAN", array: true, count: 3 }, propertyString: { type: "STRING", array: true, count: 3 }, propertyEnum: { type: "ENUM", enumType: "myEnum", array: true, count: 3 }, propertyUint32: { type: "SCALAR", componentType: "UINT32", array: true, count: 3 }, propertyFloat32: { type: "SCALAR", componentType: "FLOAT32", array: true, count: 3 } }; const propertyValues = { propertyInt64: [ [BigInt(-2), BigInt(-1), BigInt(0)], // eslint-disable-line [BigInt(1), BigInt(2), BigInt(3)] // eslint-disable-line ], propertyUint64: [ [BigInt(0), BigInt(1), BigInt(2)], // eslint-disable-line [BigInt(3), BigInt(4), BigInt(5)] // eslint-disable-line ], propertyBoolean: [ [false, true, false], [true, false, true] ], propertyString: [ ["a", "bc", "def"], ["dog", "cat", "\u{1F603}\u{1F603}\u{1F603}"] ], propertyEnum: [ ["ValueA", "ValueB", "Other"], ["ValueA", "ValueA", "ValueA"] ], propertyUint32: [ [0, 1, 2], [3, 4, 5] ], propertyFloat32: [ [-2, -1, 0], [1, 2, 3] ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = MetadataTester_default.createProperty({ property: properties[propertyId], values: propertyValues[propertyId], enums }); const expectedValues = propertyValues[propertyId]; const length2 = expectedValues.length; for (let i = 0; i < length2; ++i) { const value = property.get(i); expect(value).toEqual(expectedValues[i]); } } } }); it("get returns variable size arrays", function() { const properties = { propertyInt8: { type: "SCALAR", componentType: "INT8", array: true }, propertyUint8: { type: "SCALAR", componentType: "UINT8", array: true }, propertyInt16: { type: "SCALAR", componentType: "INT16", array: true }, propertyUint16: { type: "SCALAR", componentType: "UINT16", array: true }, propertyInt32: { type: "SCALAR", componentType: "INT32", array: true }, propertyUint32: { type: "SCALAR", componentType: "UINT32", array: true }, propertyInt64: { type: "SCALAR", componentType: "INT64", array: true }, propertyUint64: { type: "SCALAR", componentType: "UINT64", array: true }, propertyFloat32: { type: "SCALAR", componentType: "FLOAT32", array: true }, propertyFloat64: { type: "SCALAR", componentType: "FLOAT64", array: true }, propertyBoolean: { type: "BOOLEAN", array: true }, propertyString: { type: "STRING", array: true }, propertyEnum: { type: "ENUM", enumType: "myEnum", array: true } }; const propertyValues = { propertyInt8: [[-2], [-1, 0], [1, 2, 3], []], propertyUint8: [[0], [1, 2], [3, 4, 5], []], propertyInt16: [[-2], [-1, 0], [1, 2, 3], []], propertyUint16: [[0], [1, 2], [3, 4, 5], []], propertyInt32: [[-2], [-1, 0], [1, 2, 3], []], propertyUint32: [[0], [1, 2], [3, 4, 5], []], propertyInt64: [ [BigInt(-2)], // eslint-disable-line [BigInt(-1), BigInt(0)], // eslint-disable-line [BigInt(1), BigInt(2), BigInt(3)], // eslint-disable-line [] ], propertyUint64: [ [BigInt(0)], // eslint-disable-line [BigInt(1), BigInt(2)], // eslint-disable-line [BigInt(3), BigInt(4), BigInt(5)], // eslint-disable-line [] ], propertyFloat32: [[-2], [-1, 0], [1, 2, 3], []], propertyFloat64: [[-2], [-1, 0], [1, 2, 3], []], propertyBoolean: [[false], [true, false], [true, false, true], []], propertyString: [["a"], ["bc", "def"], ["dog", "cat", "\u{1F603}\u{1F603}\u{1F603}"], []], propertyEnum: [ ["ValueA"], ["ValueB", "Other"], ["ValueA", "ValueA", "ValueA"], [] ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = MetadataTester_default.createProperty({ property: properties[propertyId], values: propertyValues[propertyId], enums }); const expectedValues = propertyValues[propertyId]; const length2 = expectedValues.length; for (let i = 0; i < length2; ++i) { const value = property.get(i); expect(value).toEqual(expectedValues[i]); } } } }); it("get returns arrays of vectors and matrices", function() { const properties = { propertyVec4: { type: "VEC4", componentType: "FLOAT32", array: true, count: 2 }, propertyDVec2: { type: "VEC2", componentType: "FLOAT64", array: true }, propertyU8Mat3: { type: "MAT3", componentType: "UINT8", array: true, count: 2 }, propertyDMat2: { type: "MAT2", componentType: "FLOAT64", array: true } }; const mathTypes = { propertyVec4: import__549.Cartesian4, propertyDVec2: import__549.Cartesian2, propertyU8Mat3: import__549.Matrix3, propertyDMat2: import__549.Matrix2 }; const propertyValues = { propertyVec4: [ [ 1, 1, 0, 1, 1, 1, 0, 1 ], [ 1, 2, 3, 4, 1, 2, 3, 4 ] ], propertyDVec2: [ [ 1, 2, 3, 4, 5, 6 ], [1, 2] ], propertyU8Mat3: [ [ 2, 0, 0, 0, 2, 0, 0, 0, 2, 1, 2, 3, 1, 2, 3, 1, 2, 3 ], [ 255, 128, 0, 0, 255, 0, 0, 255, 255, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] ], propertyDMat2: [ [ 1, 2, 3, 4, 1, 0, 0, 1, 0, 0, 0, 1 ], [ 1, 2, 1, 2, 1, 0, 0, 2 ] ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = MetadataTester_default.createProperty({ property: properties[propertyId], values: propertyValues[propertyId] }); const expectedValues = propertyValues[propertyId]; const length2 = expectedValues.length; const MathType = mathTypes[propertyId]; for (let i = 0; i < length2; ++i) { const value = property.get(i); expect(value).toEqual(MathType.unpackArray(expectedValues[i])); } } } }); it("get returns normalized value", function() { const propertyInt8 = MetadataTester_default.createProperty({ property: { type: "SCALAR", componentType: "INT8", normalized: true }, values: [-127] }); const propertyUint8 = MetadataTester_default.createProperty({ property: { type: "SCALAR", componentType: "UINT8", normalized: true }, values: [255] }); expect(propertyInt8.get(0)).toBe(-1); expect(propertyUint8.get(0)).toBe(1); }); it("get applies offset/scale", function() { const propertyInt8 = MetadataTester_default.createProperty({ property: { type: "SCALAR", componentType: "INT8", normalized: true, offset: 0.5, scale: 0.5 }, values: [-127] }); const propertyArrayOfVector = MetadataTester_default.createProperty({ property: { type: "VEC3", componentType: "FLOAT32", array: true, count: 2, scale: [ [2, 2, 2], [1, 1, 1] ] }, values: [[1, 1, 1, 1, 2, 3]] }); expect(propertyInt8.get(0)).toBe(0); expect(propertyArrayOfVector.get(0)).toEqual([ new import__549.Cartesian3(2, 2, 2), new import__549.Cartesian3(1, 2, 3) ]); }); it("get handles noData correctly", function() { const properties = { noDefault: { type: "SCALAR", componentType: "INT32", required: false, noData: -1 }, hasDefault: { type: "SCALAR", componentType: "INT32", required: false, noData: -1, default: 100 }, noDefaultVector: { type: "VEC2", componentType: "FLOAT32", required: false, noData: [0, 0] }, hasDefaultVector: { type: "VEC2", componentType: "FLOAT32", required: false, noData: [0, 0], default: [100, 100] }, noDefaultArray: { array: true, type: "SCALAR", componentType: "UINT8", count: 3, required: false, noData: [0, 0, 0] }, hasDefaultArray: { array: true, type: "SCALAR", componentType: "UINT8", required: false, noData: [], default: [1, 1, 1] }, noDefaultArrayOfVector: { array: true, type: "VEC2", componentType: "FLOAT32", count: 3, required: false, noData: [ [0, 0], [0, 0] ] }, hasDefaultArrayOfVector: { array: true, type: "VEC2", componentType: "FLOAT32", required: false, noData: [], default: [ [1, 1], [1, 1] ] } }; const propertyValues = { noDefault: [-1, 0], hasDefault: [-1, 0], noDefaultVector: [ [0, 0], [0, 1] ], hasDefaultVector: [ [0, 0], [0, 1] ], noDefaultArray: [ [0, 0, 0], [1, 0, 0] ], hasDefaultArray: [[], [1, 2]], noDefaultArrayOfVector: [ [0, 0, 0, 0, 0, 0], [1, 0, 1, 1, 0, 0] ], hasDefaultArrayOfVector: [[], [1, 0]] }; const expectedValues = { noDefault: [void 0, 0], hasDefault: [100, 0], noDefaultVector: [void 0, new import__549.Cartesian2(0, 1)], hasDefaultVector: [ new import__549.Cartesian2(100, 100), new import__549.Cartesian2(0, 1) ], noDefaultArray: [void 0, [1, 0, 0]], hasDefaultArray: [ [1, 1, 1], [1, 2] ], noDefaultArrayOfVector: [ void 0, [ [1, 0], [1, 1], [0, 0] ] ], hasDefaultArrayOfVector: [ [new import__549.Cartesian2(1, 1), new import__549.Cartesian2(1, 1)], [new import__549.Cartesian2(1, 0)] ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = MetadataTester_default.createProperty({ property: properties[propertyId], values: propertyValues[propertyId] }); const length2 = expectedValues.length; for (let i = 0; i < length2; ++i) { const value = property.get(i); expect(value).toEqual(expectedValues[propertyId][i]); } } } }); it("get throws without index", function() { const property = MetadataTester_default.createProperty({ property: { type: "SCALAR", componentType: "FLOAT32" }, values: [1, 2] }); expect(function() { property.get(); }).toThrowDeveloperError(); }); it("get throws if index is out of bounds", function() { const property = MetadataTester_default.createProperty({ property: { type: "SCALAR", componentType: "FLOAT32" }, values: [1, 2] }); expect(property.get(0)).toBe(1); expect(property.get(1)).toBe(2); expect(function() { property.get(2); }).toThrowDeveloperError(); }); it("set sets scalar values", function() { const properties = { propertyInt8: { type: "SCALAR", componentType: "INT8" }, propertyUint8: { type: "SCALAR", componentType: "UINT8" }, propertyInt16: { type: "SCALAR", componentType: "INT16" }, propertyUint16: { type: "SCALAR", componentType: "UINT16" }, propertyInt32: { type: "SCALAR", componentType: "INT32" }, propertyUint32: { type: "SCALAR", componentType: "UINT32" }, propertyInt64: { type: "SCALAR", componentType: "INT64" }, propertyUint64: { type: "SCALAR", componentType: "UINT64" }, propertyFloat32: { type: "SCALAR", componentType: "FLOAT32" }, propertyFloat64: { type: "SCALAR", componentType: "FLOAT64" }, propertyBoolean: { type: "BOOLEAN" }, propertyString: { type: "STRING" }, propertyEnum: { type: "ENUM", enumType: "myEnum" } }; const propertyValues = { propertyInt8: [0, 0, 0, 0, 0], propertyUint8: [0, 0, 0, 0, 0], propertyInt16: [0, 0, 0, 0, 0], propertyUint16: [0, 0, 0, 0, 0], propertyInt32: [0, 0, 0, 0, 0], propertyUint32: [0, 0, 0, 0, 0], propertyInt64: [BigInt(0), BigInt(0), BigInt(0), BigInt(0), BigInt(0)], // eslint-disable-line propertyUint64: [BigInt(0), BigInt(0), BigInt(0), BigInt(0), BigInt(0)], // eslint-disable-line propertyFloat32: [0, 0, 0, 0, 0], propertyFloat64: [0, 0, 0, 0, 0], propertyBoolean: [false, false, true, false, true], propertyString: ["", "", "", "", ""], propertyEnum: ["Other", "Other", "Other", "Other", "Other"] }; const valuesToSet = { propertyInt8: [-128, -10, 0, 10, 127], propertyUint8: [0, 10, 20, 30, 255], propertyInt16: [-32768, -10, 0, 10, 32767], propertyUint16: [0, 10, 20, 30, 65535], propertyInt32: [-2147483648, -10, 0, 10, 2147483647], propertyUint32: [0, 10, 20, 30, 4294967295], propertyInt64: [ BigInt("-9223372036854775808"), // eslint-disable-line BigInt("-4611686018427387833"), // eslint-disable-line BigInt(0), // eslint-disable-line BigInt("4611686018427387833"), // eslint-disable-line BigInt("9223372036854775807") // eslint-disable-line ], propertyUint64: [ BigInt(0), // eslint-disable-line BigInt(10), // eslint-disable-line BigInt(100), // eslint-disable-line BigInt("4611686018427387833"), // eslint-disable-line BigInt("18446744073709551615") // eslint-disable-line ], propertyFloat32: [-2.5, -1, 0, 700, 38], propertyFloat64: [-234934.12, -1, 0, 700, Math.PI], propertyBoolean: [true, true, false, false, true], propertyString: ["\u304A\u306F\u3088\u3046\u3054\u3056\u3044\u307E\u3059\u3002\u{1F603}", "a", "", "def", "0001"], propertyEnum: ["ValueA", "ValueB", "Other", "ValueA", "ValueA"] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = MetadataTester_default.createProperty({ property: properties[propertyId], values: propertyValues[propertyId], enums }); const expectedValues = valuesToSet[propertyId]; const length2 = expectedValues.length; for (let i = 0; i < length2; ++i) { property.set(i, expectedValues[i]); let value = property.get(i); expect(value).toEqual(expectedValues[i]); property.set(i, expectedValues[i]); value = property.get(i); expect(value).toEqual(expectedValues[i]); } } } }); it("set sets vector values", function() { const properties = { propertyInt8: { type: "VEC3", componentType: "INT8" }, propertyUint8: { type: "VEC3", componentType: "UINT8" }, propertyInt16: { type: "VEC3", componentType: "INT16" }, propertyUint16: { type: "VEC3", componentType: "UINT16" }, propertyInt32: { type: "VEC3", componentType: "INT32" }, propertyUint32: { type: "VEC3", componentType: "UINT32" }, propertyFloat32: { type: "VEC3", componentType: "FLOAT32" }, propertyFloat64: { type: "VEC3", componentType: "FLOAT64" } }; const propertyValues = { propertyInt8: [ [0, 0, 0], [0, 0, 0] ], propertyUint8: [ [0, 0, 0], [0, 0, 0] ], propertyInt16: [ [0, 0, 0], [0, 0, 0] ], propertyUint16: [ [0, 0, 0], [0, 0, 0] ], propertyInt32: [ [0, 0, 0], [0, 0, 0] ], propertyUint32: [ [0, 0, 0], [0, 0, 0] ], propertyFloat32: [ [0, 0, 0], [0, 0, 0] ], propertyFloat64: [ [0, 0, 0], [0, 0, 0] ] }; const valuesToSet = { propertyInt8: [new import__549.Cartesian3(-2, -1, 0), new import__549.Cartesian3(1, 2, 3)], propertyUint8: [new import__549.Cartesian3(0, 1, 2), new import__549.Cartesian3(3, 4, 5)], propertyInt16: [new import__549.Cartesian3(-2, -1, 0), new import__549.Cartesian3(1, 2, 3)], propertyUint16: [new import__549.Cartesian3(0, 1, 2), new import__549.Cartesian3(3, 4, 5)], propertyInt32: [new import__549.Cartesian3(-2, -1, 0), new import__549.Cartesian3(1, 2, 3)], propertyUint32: [new import__549.Cartesian3(0, 1, 2), new import__549.Cartesian3(3, 4, 5)], propertyFloat32: [ new import__549.Cartesian3(-2, -1, 0), new import__549.Cartesian3(1, 2, 3) ], propertyFloat64: [ new import__549.Cartesian3(-2, -1, 0), new import__549.Cartesian3(1, 2, 3) ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = MetadataTester_default.createProperty({ property: properties[propertyId], values: propertyValues[propertyId], enums }); const expectedValues = valuesToSet[propertyId]; const length2 = expectedValues.length; for (let i = 0; i < length2; ++i) { property.set(i, expectedValues[i]); let value = property.get(i); expect(value).toEqual(expectedValues[i]); property.set(i, expectedValues[i]); value = property.get(i); expect(value).toEqual(expectedValues[i]); } } } }); it("set sets fixed size arrays", function() { const properties = { propertyInt64: { type: "SCALAR", componentType: "INT64", array: true, count: 3 }, propertyUint64: { type: "SCALAR", componentType: "UINT64", array: true, count: 3 }, propertyBoolean: { type: "BOOLEAN", array: true, count: 3 }, propertyString: { type: "STRING", array: true, count: 3 }, propertyEnum: { type: "ENUM", enumType: "myEnum", array: true, count: 3 }, propertyUint32: { type: "SCALAR", componentType: "UINT32", array: true, count: 3 }, propertyFloat32: { type: "SCALAR", componentType: "FLOAT32", array: true, count: 2 } }; const propertyValues = { propertyInt64: [ [BigInt(0), BigInt(0), BigInt(0)], // eslint-disable-line [BigInt(0), BigInt(0), BigInt(0)] // eslint-disable-line ], propertyUint64: [ [BigInt(0), BigInt(0), BigInt(0)], // eslint-disable-line [BigInt(0), BigInt(0), BigInt(0)] // eslint-disable-line ], propertyBoolean: [ [false, false, false], [true, true, true] ], propertyString: [ ["", "", ""], ["", "", ""] ], propertyEnum: [ ["Other", "Other", "Other"], ["Other", "Other", "Other"] ], propertyUint32: [ [0, 0, 0], [0, 0, 0] ], propertyFloat32: [ [0, 0], [0, 0] ] }; const valuesToSet = { propertyInt64: [ [BigInt(-2), BigInt(-1), BigInt(0)], // eslint-disable-line [BigInt(1), BigInt(2), BigInt(3)] // eslint-disable-line ], propertyUint64: [ [BigInt(0), BigInt(1), BigInt(2)], // eslint-disable-line [BigInt(3), BigInt(4), BigInt(5)] // eslint-disable-line ], propertyBoolean: [ [false, true, false], [true, false, true] ], propertyString: [ ["a", "bc", "def"], ["dog", "cat", "\u{1F603}\u{1F603}\u{1F603}"] ], propertyEnum: [ ["ValueA", "ValueB", "Other"], ["ValueA", "ValueA", "ValueA"] ], propertyUint32: [ [1, 0, 0], [0, 2, 0] ], propertyFloat32: [ [0, 0.5], [0.25, 0.25] ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = MetadataTester_default.createProperty({ property: properties[propertyId], values: propertyValues[propertyId], enums }); const expectedValues = valuesToSet[propertyId]; const length2 = expectedValues.length; for (let i = 0; i < length2; ++i) { property.set(i, expectedValues[i]); let value = property.get(i); expect(value).toEqual(expectedValues[i]); property.set(i, expectedValues[i]); value = property.get(i); expect(value).toEqual(expectedValues[i]); } } } }); it("set sets arrays of vectors and matrices", function() { const properties = { propertyVec4: { type: "VEC4", componentType: "FLOAT32", array: true, count: 2 }, propertyDVec2: { type: "VEC2", componentType: "FLOAT64", array: true }, propertyU8Mat3: { type: "MAT3", componentType: "UINT8", array: true, count: 2 }, propertyDMat2: { type: "MAT2", componentType: "FLOAT64", array: true } }; const propertyValues = { propertyVec4: [ [ 1, 1, 0, 1, 1, 1, 0, 1 ], [ 1, 2, 3, 4, 1, 2, 3, 4 ] ], propertyDVec2: [ [ 1, 2, 3, 4, 5, 6 ], [1, 2] ], propertyU8Mat3: [ [ 2, 0, 0, 0, 2, 0, 0, 0, 2, 1, 2, 3, 1, 2, 3, 1, 2, 3 ], [ 255, 128, 0, 0, 255, 0, 0, 255, 255, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] ], propertyDMat2: [ [ 1, 2, 3, 4, 1, 0, 0, 1, 0, 0, 0, 1 ], [ 1, 2, 1, 2, 1, 0, 0, 2 ] ] }; const valuesToSet = { propertyVec4: [ [new import__549.Cartesian4(1, 1, 0, 1), new import__549.Cartesian4(1, 1, 0, 1)], [new import__549.Cartesian4(1, 2, 3, 4), new import__549.Cartesian4(1, 2, 3, 4)] ], propertyDVec2: [ [new import__549.Cartesian2(1, 2), new import__549.Cartesian2(3, 4), new import__549.Cartesian2(5, 6)], [new import__549.Cartesian2(1, 2)] ], propertyU8Mat3: [ [ new import__549.Matrix3(2, 0, 0, 0, 2, 0, 0, 0, 2), new import__549.Matrix3(1, 2, 3, 1, 2, 3, 1, 2, 3) ], [ new import__549.Matrix3(255, 128, 0, 0, 255, 0, 0, 255, 255), new import__549.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 9) ] ], propertyDMat2: [ [ new import__549.Matrix2(1, 2, 3, 4), new import__549.Matrix2(1, 0, 0, 1), new import__549.Matrix2(0, 0, 0, 1) ], [new import__549.Matrix2(1, 2, 1, 2), new import__549.Matrix2(1, 0, 0, 2)] ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = MetadataTester_default.createProperty({ property: properties[propertyId], values: propertyValues[propertyId] }); const expectedValues = valuesToSet[propertyId]; const length2 = expectedValues.length; for (let i = 0; i < length2; ++i) { property.set(i, expectedValues[i]); let value = property.get(i); expect(value).toEqual(expectedValues[i]); property.set(i, expectedValues[i]); value = property.get(i); expect(value).toEqual(expectedValues[i]); } } } }); it("set sets variable size arrays with arrays of the same length", function() { const properties = { propertyInt8: { type: "SCALAR", componentType: "INT8", array: true }, propertyUint8: { type: "SCALAR", componentType: "UINT8", array: true }, propertyInt16: { type: "SCALAR", componentType: "INT16", array: true }, propertyUint16: { type: "SCALAR", componentType: "UINT16", array: true }, propertyInt32: { type: "SCALAR", componentType: "INT32", array: true }, propertyUint32: { type: "SCALAR", componentType: "UINT32", array: true }, propertyInt64: { type: "SCALAR", componentType: "INT64", array: true }, propertyUint64: { type: "SCALAR", componentType: "UINT64", array: true }, propertyFloat32: { type: "SCALAR", componentType: "FLOAT32", array: true }, propertyFloat64: { type: "SCALAR", componentType: "FLOAT64", array: true }, propertyBoolean: { type: "BOOLEAN", array: true }, propertyString: { type: "STRING", array: true }, propertyEnum: { type: "ENUM", enumType: "myEnum", array: true } }; const propertyValues = { propertyInt8: [[0], [0, 0], [0, 0, 0], []], propertyUint8: [[0], [0, 0], [0, 0, 0], []], propertyInt16: [[0], [0, 0], [0, 0, 0], []], propertyUint16: [[0], [0, 0], [0, 0, 0], []], propertyInt32: [[0], [0, 0], [0, 0, 0], []], propertyUint32: [[0], [0, 0], [0, 0, 0], []], propertyInt64: [ [BigInt(0)], // eslint-disable-line [BigInt(0), BigInt(0)], // eslint-disable-line [BigInt(0), BigInt(0), BigInt(0)], // eslint-disable-line [] ], propertyUint64: [ [BigInt(0)], // eslint-disable-line [BigInt(0), BigInt(0)], // eslint-disable-line [BigInt(0), BigInt(0), BigInt(0)], // eslint-disable-line [] ], propertyFloat32: [[0], [0, 0], [0, 0, 0], []], propertyFloat64: [[0], [0, 0], [0, 0, 0], []], propertyBoolean: [[false], [false, false], [false, false, false], []], propertyString: [[""], ["", ""], ["", "", ""], []], propertyEnum: [ ["Other"], ["Other", "Other"], ["Other", "Other", "Other"], [] ] }; const valuesToSet = { propertyInt8: [[-2], [-1, 0], [1, 2, 3], []], propertyUint8: [[0], [1, 2], [3, 4, 5], []], propertyInt16: [[-2], [-1, 0], [1, 2, 3], []], propertyUint16: [[0], [1, 2], [3, 4, 5], []], propertyInt32: [[-2], [-1, 0], [1, 2, 3], []], propertyUint32: [[0], [1, 2], [3, 4, 5], []], propertyInt64: [ [BigInt(-2)], // eslint-disable-line [BigInt(-1), BigInt(0)], // eslint-disable-line [BigInt(1), BigInt(2), BigInt(3)], // eslint-disable-line [] ], propertyUint64: [ [BigInt(0)], // eslint-disable-line [BigInt(1), BigInt(2)], // eslint-disable-line [BigInt(3), BigInt(4), BigInt(5)], // eslint-disable-line [] ], propertyFloat32: [[-2], [-1, 0], [1, 2, 3], []], propertyFloat64: [[-2], [-1, 0], [1, 2, 3], []], propertyBoolean: [[false], [true, false], [true, false, true], []], propertyString: [["a"], ["bc", "def"], ["dog", "cat", "\u{1F603}\u{1F603}\u{1F603}"], []], propertyEnum: [ ["ValueA"], ["ValueB", "Other"], ["ValueA", "ValueA", "ValueA"], [] ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = MetadataTester_default.createProperty({ property: properties[propertyId], values: propertyValues[propertyId], enums }); const expectedValues = valuesToSet[propertyId]; const length2 = expectedValues.length; for (let i = 0; i < length2; ++i) { property.set(i, expectedValues[i]); let value = property.get(i); expect(value).toEqual(expectedValues[i]); property.set(i, expectedValues[i]); value = property.get(i); expect(value).toEqual(expectedValues[i]); } } } }); it("set sets variable size arrays with arrays of different lengths", function() { const properties = { propertyInt8: { type: "SCALAR", componentType: "INT8", array: true }, propertyUint8: { type: "SCALAR", componentType: "UINT8", array: true }, propertyInt16: { type: "SCALAR", componentType: "INT16", array: true }, propertyUint16: { type: "SCALAR", componentType: "UINT16", array: true }, propertyInt32: { type: "SCALAR", componentType: "INT32", array: true }, propertyUint32: { type: "SCALAR", componentType: "UINT32", array: true }, propertyInt64: { type: "SCALAR", componentType: "INT64", array: true }, propertyUint64: { type: "SCALAR", componentType: "UINT64", array: true }, propertyFloat32: { type: "SCALAR", componentType: "FLOAT32", array: true }, propertyFloat64: { type: "SCALAR", componentType: "FLOAT64", array: true }, propertyBoolean: { type: "BOOLEAN", array: true }, propertyString: { type: "STRING", array: true }, propertyEnum: { type: "ENUM", enumType: "myEnum", array: true } }; const propertyValues = { propertyInt8: [[0], [0, 0], [0, 0, 0], []], propertyUint8: [[0], [0, 0], [0, 0, 0], []], propertyInt16: [[0], [0, 0], [0, 0, 0], []], propertyUint16: [[0], [0, 0], [0, 0, 0], []], propertyInt32: [[0], [0, 0], [0, 0, 0], []], propertyUint32: [[0], [0, 0], [0, 0, 0], []], propertyInt64: [ [BigInt(0)], // eslint-disable-line [BigInt(0), BigInt(0)], // eslint-disable-line [BigInt(0), BigInt(0), BigInt(0)], // eslint-disable-line [] ], propertyUint64: [ [BigInt(0)], // eslint-disable-line [BigInt(0), BigInt(0)], // eslint-disable-line [BigInt(0), BigInt(0), BigInt(0)], // eslint-disable-line [] ], propertyFloat32: [[0], [0, 0], [0, 0, 0], []], propertyFloat64: [[0], [0, 0], [0, 0, 0], []], propertyBoolean: [[false], [false, false], [false, false, false], []], propertyString: [[""], ["", ""], ["", "", ""], []], propertyEnum: [ ["Other"], ["Other", "Other"], ["Other", "Other", "Other"], [] ] }; const valuesToSet = { propertyInt8: [[1, 2, 3], [], [-2], [-1, 0]], propertyUint8: [[3, 4, 5], [0], [], [1, 2]], propertyInt16: [[], [1, 2, 3], [-2], [-1, 0]], propertyUint16: [[3, 4, 5], [1, 2], [], [0]], propertyInt32: [[1, 2, 3], [], [-2], [-1, 0]], propertyUint32: [[0], [3, 4, 5], [1, 2], []], propertyInt64: [ [BigInt(-1), BigInt(0)], // eslint-disable-line [BigInt(-2)], // eslint-disable-line [], [BigInt(1), BigInt(2), BigInt(3)] // eslint-disable-line ], propertyUint64: [ [BigInt(0)], // eslint-disable-line [], [BigInt(1), BigInt(2)], // eslint-disable-line [BigInt(3), BigInt(4), BigInt(5)] // eslint-disable-line ], propertyFloat32: [[-1, 0], [1, 2, 3], [], [-2]], propertyFloat64: [[-2], [1, 2, 3], [-1, 0], []], propertyBoolean: [[true, false, true], [], [false], [true, false]], propertyString: [[], ["bc", "def"], ["a"], ["dog", "cat", "\u{1F603}\u{1F603}\u{1F603}"]], propertyEnum: [ [], ["ValueA", "ValueA", "ValueA"], ["ValueA"], ["ValueB", "Other"] ] }; for (const propertyId in properties) { if (properties.hasOwnProperty(propertyId)) { const property = MetadataTester_default.createProperty({ property: properties[propertyId], values: propertyValues[propertyId], enums }); const expectedValues = valuesToSet[propertyId]; const length2 = expectedValues.length; for (let i = 0; i < length2; ++i) { property.set(i, expectedValues[i]); let value = property.get(i); expect(value).toEqual(expectedValues[i]); property.set(i, expectedValues[i]); value = property.get(i); expect(value).toEqual(expectedValues[i]); } } } }); it("set throws if Infinity is given for FLOAT32 and FLOAT64", function() { const propertyFloat32 = MetadataTester_default.createProperty({ property: { type: "SCALAR", componentType: "FLOAT32" }, values: [0, 0] }); const propertyFloat64 = MetadataTester_default.createProperty({ property: { type: "SCALAR", componentType: "FLOAT64" }, values: [0, 0] }); expect(function() { propertyFloat32.set(0, Number.POSITIVE_INFINITY); }).toThrowDeveloperError(); expect(function() { propertyFloat32.set(1, Number.NEGATIVE_INFINITY); }).toThrowDeveloperError(); expect(function() { propertyFloat64.set(0, Number.POSITIVE_INFINITY); }).toThrowDeveloperError(); expect(function() { propertyFloat32.set(1, Number.NEGATIVE_INFINITY); }).toThrowDeveloperError(); expect(propertyFloat32.get(0)).toBe(0); expect(propertyFloat32.get(1)).toBe(0); expect(propertyFloat64.get(0)).toBe(0); expect(propertyFloat64.get(1)).toBe(0); }); it("set throws if a NaN is given for FLOAT32 and FLOAT64", function() { const propertyFloat32 = MetadataTester_default.createProperty({ property: { type: "SCALAR", componentType: "FLOAT32" }, values: [0] }); const propertyFloat64 = MetadataTester_default.createProperty({ property: { type: "SCALAR", componentType: "FLOAT64" }, values: [0] }); expect(function() { propertyFloat32.set(0, NaN); }).toThrowDeveloperError(); expect(function() { propertyFloat64.set(0, NaN); }).toThrowDeveloperError(); expect(propertyFloat32.get(0)).toBe(0); expect(propertyFloat64.get(0)).toBe(0); }); it("set sets value for normalized property", function() { const propertyInt8 = MetadataTester_default.createProperty({ property: { type: "SCALAR", componentType: "INT8", normalized: true }, values: [0] }); const propertyUint8 = MetadataTester_default.createProperty({ property: { type: "SCALAR", componentType: "UINT8", normalized: true }, values: [255] }); propertyInt8.set(0, -1); propertyUint8.get(0, 1); expect(propertyInt8.get(0)).toBe(-1); expect(propertyUint8.get(0)).toBe(1); }); it("get applies offset/scale", function() { const propertyInt8 = MetadataTester_default.createProperty({ property: { type: "SCALAR", componentType: "INT8", normalized: true, offset: 0.5, scale: 0.5 }, values: [-127] }); const propertyArrayOfVector = MetadataTester_default.createProperty({ property: { type: "VEC3", componentType: "FLOAT32", array: true, count: 2, scale: [ [2, 2, 2], [1, 1, 1] ] }, values: [[1, 1, 1, 1, 2, 3]] }); propertyInt8.set(0, 1); propertyArrayOfVector.set(0, [ new import__549.Cartesian3(1, 1, 1), new import__549.Cartesian3(2, 4, 8) ]); expect(propertyInt8.get(0)).toBe(1); expect(propertyArrayOfVector.get(0)).toEqual([ new import__549.Cartesian3(1, 1, 1), new import__549.Cartesian3(2, 4, 8) ]); }); it("set throws without index", function() { const property = MetadataTester_default.createProperty({ property: { type: "SCALAR", componentType: "FLOAT32" }, values: [1, 2] }); expect(function() { property.set(); }).toThrowDeveloperError(); }); it("set throws if index is out of bounds", function() { const property = MetadataTester_default.createProperty({ property: { type: "SCALAR", componentType: "FLOAT32" }, values: [1, 2] }); expect(function() { property.set(-1, 0); }).toThrowDeveloperError(); property.set(0, 0); property.set(1, 0); expect(function() { property.set(2, 0); }).toThrowDeveloperError(); }); it("set throws if value doesn't conform to the class property", function() { const property = MetadataTester_default.createProperty({ property: { type: "SCALAR", componentType: "FLOAT32", array: true, count: 3 }, values: [[1, 2, 3]] }); expect(function() { property.set(0, 8); }).toThrowDeveloperError(); }); it("getTypedArray returns typed array", function() { const propertyInt32 = { type: "SCALAR", componentType: "INT32", array: true, count: 3 }; const propertyValues = [ [-2, -1, 0], [1, 2, 3] ]; const expectedTypedArray = new Int32Array([-2, -1, 0, 1, 2, 3]); const property = MetadataTester_default.createProperty({ property: propertyInt32, values: propertyValues }); expect(property.getTypedArray()).toEqual(expectedTypedArray); }); it("getTypedArray returns undefined if values are unpacked", function() { const propertyInt32 = { type: "SCALAR", componentType: "INT32", array: true }; const propertyValues = [ [-2, -1, 0], [1, 2, 3] ]; const expectedTypedArray = new Int32Array([-2, -1, 0, 1, 2, 3]); const property = MetadataTester_default.createProperty({ property: propertyInt32, values: propertyValues }); expect(property.getTypedArray()).toEqual(expectedTypedArray); property.set(0, [-2, -1]); expect(property.getTypedArray()).toBeUndefined(); }); }); // packages/engine/Specs/Scene/MetadataTableSpec.js var import__550 = __toESM(require_Cesium(), 1); describe("Scene/MetadataTable", function() { if (!MetadataTester_default.isSupported()) { return; } const enums = { myEnum: { values: [ { value: 0, name: "ValueA" }, { value: 1, name: "ValueB" }, { value: 999, name: "Other" } ] } }; it("creates metadata table with default values", function() { const metadataTable = new import__550.MetadataTable({ count: 10, class: {} }); expect(metadataTable.count).toBe(10); expect(metadataTable.byteLength).toBe(0); }); it("creates metadata table", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" }, name: { type: "STRING" } }; const propertyValues = { height: [1, 2], name: ["A", "B"] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); const expectedPropertyNames = ["height", "name"]; expect(metadataTable.count).toBe(2); expect(metadataTable.getPropertyIds().sort()).toEqual( expectedPropertyNames ); expect(Object.keys(metadataTable.class.properties).sort()).toEqual( expectedPropertyNames ); const heightSize = 2 * 4; const nameCharArraySize = 2; const nameOffsetSize = 3 * 4; const totalSize = heightSize + nameCharArraySize + nameOffsetSize; expect(metadataTable.byteLength).toBe(totalSize); }); it("constructor throws without count", function() { expect(function() { return new import__550.MetadataTable({ class: {} }); }).toThrowDeveloperError(); }); it("constructor throws if count is less than 1", function() { expect(function() { return new import__550.MetadataTable({ count: 0, class: {} }); }).toThrowDeveloperError(); }); it("constructor throws if class is undefined", function() { expect(function() { return new import__550.MetadataTable({ count: 1, class: void 0 }); }).toThrowDeveloperError(); }); it("hasProperty returns false when there's no properties", function() { const metadataTable = new import__550.MetadataTable({ count: 10, class: {} }); expect(metadataTable.hasProperty("height")).toBe(false); }); it("hasProperty returns false when there's no property with the given property ID", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(metadataTable.hasProperty("color")).toBe(false); }); it("hasProperty returns true when there's a property with the given property ID", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(metadataTable.hasProperty("height")).toBe(true); }); it("hasProperty returns true when the class has a default value for a missing property", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32", default: 10, required: false }, name: { type: "STRING" } }; const propertyValues = { name: ["A", "B"] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(metadataTable.hasProperty("height")).toBe(true); }); it("hasProperty throws without propertyId", function() { const metadataTable = new import__550.MetadataTable({ count: 10, class: {} }); expect(function() { metadataTable.hasProperty(); }).toThrowDeveloperError(); }); it("hasPropertyBySemantic returns false when there's no properties", function() { const metadataTable = new import__550.MetadataTable({ count: 10, class: {} }); expect(metadataTable.hasPropertyBySemantic("HEIGHT")).toBe(false); }); it("hasPropertyBySemantic returns false when there's no property with the given semantic", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(metadataTable.hasPropertyBySemantic("HEIGHT")).toBe(false); }); it("hasPropertyBySemantic returns true when there's a property with the given semantic", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "HEIGHT" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(metadataTable.hasPropertyBySemantic("HEIGHT")).toBe(true); }); it("hasPropertyBySemantic returns true when the class has a default value for a missing property", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "HEIGHT", default: 10, required: false }, name: { type: "STRING" } }; const propertyValues = { name: ["A", "B"] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(metadataTable.hasPropertyBySemantic("HEIGHT")).toBe(true); }); it("hasPropertyBySemantic throws without semantic", function() { const metadataTable = new import__550.MetadataTable({ count: 10, class: {} }); expect(function() { metadataTable.hasPropertyBySemantic(void 0); }).toThrowDeveloperError(); }); it("getPropertyIds returns empty array when there are no properties", function() { const metadataTable = new import__550.MetadataTable({ count: 10, class: {} }); expect(metadataTable.getPropertyIds().length).toBe(0); }); it("getPropertyIds returns array of property IDs", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" }, name: { type: "STRING" } }; const propertyValues = { height: [1, 2], name: ["A", "B"] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(metadataTable.getPropertyIds().sort()).toEqual(["height", "name"]); }); it("getPropertyIds includes properties with default values", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32", default: 10, required: false }, name: { type: "STRING" } }; const propertyValues = { name: ["A", "B"] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(metadataTable.getPropertyIds().sort()).toEqual(["height", "name"]); }); it("getPropertyIds uses results argument", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" }, name: { type: "STRING" } }; const propertyValues = { height: [1, 2], name: ["A", "B"] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); const results = []; const returnedResults = metadataTable.getPropertyIds(results); expect(results).toBe(returnedResults); expect(results.sort()).toEqual(["height", "name"]); }); it("getProperty", function() { const properties = { propertyInt8: { type: "SCALAR", componentType: "INT8" } }; const propertyValues = [-128, 10]; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues: { propertyInt8: propertyValues } }); const length2 = propertyValues.length; for (let i = 0; i < length2; ++i) { const value = metadataTable.getProperty(i, "propertyInt8"); expect(value).toEqual(propertyValues[i]); } }); it("getProperty returns undefined when there's no properties", function() { const metadataTable = new import__550.MetadataTable({ count: 10, class: {} }); expect(metadataTable.getProperty(0, "height")).toBeUndefined(); }); it("getProperty returns undefined when there's no property with the given property ID", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(metadataTable.getProperty(0, "name")).toBeUndefined(); }); it("getProperty returns the default value when the property is missing", function() { const position = [0, 0, 0]; const defaultBoundingSphere = [0, 0, 0, 1]; const properties = { position: { type: "VEC3", componentType: "FLOAT32", required: false, default: position }, name: { type: "STRING" }, type: { type: "ENUM", enumType: "myEnum", required: false, default: "Other" }, boundingSphere: { type: "SCALAR", componentType: "FLOAT64", array: true, count: 4, default: defaultBoundingSphere } }; const propertyValues = { name: ["A", "B"] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues, enums }); const value = metadataTable.getProperty(0, "position"); expect(value).toEqual(import__550.Cartesian3.unpack(position)); expect(metadataTable.getProperty(0, "type")).toBe("Other"); const sphere = metadataTable.getProperty(0, "boundingSphere"); expect(sphere).toEqual(defaultBoundingSphere); expect(sphere).not.toBe(defaultBoundingSphere); }); it("getProperty throws without index", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(function() { metadataTable.getProperty(); }).toThrowDeveloperError(); }); it("getProperty throws without propertyId", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(function() { metadataTable.getProperty(0); }).toThrowDeveloperError(); }); it("getProperty throws if index is out of bounds", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(function() { metadataTable.getProperty(-1, "height"); }).toThrowDeveloperError(); expect(metadataTable.getProperty(0, "height")).toBe(1); expect(metadataTable.getProperty(1, "height")).toBe(2); expect(function() { metadataTable.getProperty(2, "height"); }).toThrowDeveloperError(); }); it("setProperty sets values", function() { const properties = { propertyInt8: { type: "SCALAR", componentType: "INT8" } }; const propertyValues = [0, 0]; const valuesToSet = [-128, 10]; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues: { propertyInt8: propertyValues } }); const length2 = valuesToSet.length; for (let i = 0; i < length2; ++i) { expect(metadataTable.setProperty(i, "propertyInt8", valuesToSet[i])).toBe( true ); let value = metadataTable.getProperty(i, "propertyInt8"); expect(value).toEqual(valuesToSet[i]); expect(metadataTable.setProperty(i, "propertyInt8", valuesToSet[i])).toBe( true ); value = metadataTable.getProperty(i, "propertyInt8"); expect(value).toEqual(valuesToSet[i]); } }); it("setProperty returns false if the property ID doesn't exist", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(metadataTable.setProperty(0, "name", "A")).toBe(false); }); it("setProperty throws without index", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(function() { metadataTable.setProperty(); }).toThrowDeveloperError(); }); it("setProperty throws without propertyId", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(function() { metadataTable.setProperty(0); }).toThrowDeveloperError(); }); it("setProperty throws without value", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(function() { metadataTable.setProperty(0, "height"); }).toThrowDeveloperError(); }); it("setProperty throws if index is out of bounds", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(function() { metadataTable.setProperty(-1, "height", 0); }).toThrowDeveloperError(); metadataTable.setProperty(0, "height", 0); metadataTable.setProperty(1, "height", 0); expect(function() { metadataTable.setProperty(2, "height", 0); }).toThrowDeveloperError(); }); it("getPropertyBySemantic returns undefined when there's no class", function() { const metadataTable = new import__550.MetadataTable({ count: 10, class: {} }); expect(metadataTable.getPropertyBySemantic(0, "_HEIGHT")).toBeUndefined(); }); it("getPropertyBySemantic returns undefined when there's no property with the given semantic", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(metadataTable.getPropertyBySemantic(0, "_HEIGHT")).toBeUndefined(); }); it("getPropertyBySemantic returns the property value", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "_HEIGHT" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(metadataTable.getPropertyBySemantic(0, "_HEIGHT")).toBe(1); }); it("getPropertyBySemantic throws without index", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "_HEIGHT" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(function() { metadataTable.getPropertyBySemantic(); }).toThrowDeveloperError(); }); it("getPropertyBySemantic throws without semantic", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "_HEIGHT" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(function() { metadataTable.getPropertyBySemantic(0); }).toThrowDeveloperError(); }); it("getPropertyBySemantic throws if index is out of bounds", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "_HEIGHT" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(function() { metadataTable.getPropertyBySemantic(-1, "_HEIGHT"); }).toThrowDeveloperError(); metadataTable.getPropertyBySemantic(0, "_HEIGHT"); metadataTable.getPropertyBySemantic(1, "_HEIGHT"); expect(function() { metadataTable.getPropertyBySemantic(2, "_HEIGHT"); }).toThrowDeveloperError(); }); it("setPropertyBySemantic doesn't set property value when there's no class", function() { const metadataTable = new import__550.MetadataTable({ count: 10, class: {} }); metadataTable.setPropertyBySemantic(0, "_HEIGHT", 20); expect(metadataTable.getPropertyBySemantic(0, "_HEIGHT")).toBeUndefined(); }); it("setPropertyBySemantic returns false if the semantic doesn't exist", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(metadataTable.setPropertyBySemantic(0, "_HEIGHT", 20)).toBe(false); }); it("setPropertyBySemantic sets property value", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "_HEIGHT" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(metadataTable.setPropertyBySemantic(0, "_HEIGHT", 20)).toBe(true); expect(metadataTable.getPropertyBySemantic(0, "_HEIGHT")).toBe(20); }); it("setPropertyBySemantic throws without index", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "_HEIGHT" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(function() { metadataTable.setPropertyBySemantic(); }).toThrowDeveloperError(); }); it("setPropertyBySemantic throws without semantic", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "_HEIGHT" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(function() { metadataTable.setPropertyBySemantic(0); }).toThrowDeveloperError(); }); it("setPropertyBySemantic throws without value", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "_HEIGHT" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(function() { metadataTable.setPropertyBySemantic(0, "_HEIGHT"); }).toThrowDeveloperError(); }); it("setPropertyBySemantic throws if index is out of bounds", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "_HEIGHT" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(function() { metadataTable.setPropertyBySemantic(-1, "_HEIGHT", 0); }).toThrowDeveloperError(); metadataTable.setPropertyBySemantic(0, "_HEIGHT", 0); metadataTable.setPropertyBySemantic(1, "_HEIGHT", 0); expect(function() { metadataTable.setPropertyBySemantic(2, "_HEIGHT", 0); }).toThrowDeveloperError(); }); it("getPropertyTypedArray returns typed array", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); const expectedTypedArray = new Float32Array([1, 2]); expect(metadataTable.getPropertyTypedArray("height")).toEqual( expectedTypedArray ); }); it("getPropertyTypedArray returns undefined if property does not exist", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect(metadataTable.getPropertyTypedArray("volume")).toBeUndefined(); }); it("getPropertyTypedArray throws if propertyId is undefined", function() { const metadataTable = new import__550.MetadataTable({ count: 10, class: {} }); expect(function() { metadataTable.getPropertyTypedArray(void 0); }).toThrowDeveloperError(); }); it("getPropertyTypedArrayBySemantic returns typed array", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "HEIGHT" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); const expectedTypedArray = new Float32Array([1, 2]); expect(metadataTable.getPropertyTypedArrayBySemantic("HEIGHT")).toEqual( expectedTypedArray ); }); it("getPropertyTypedArrayBySemantic returns undefined if semantic does not exist", function() { const properties = { height: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1, 2] }; const metadataTable = MetadataTester_default.createMetadataTable({ properties, propertyValues }); expect( metadataTable.getPropertyTypedArrayBySemantic("HEIGHT") ).toBeUndefined(); }); it("getPropertyTypedArrayBySemantic throws if semantic is undefined", function() { const metadataTable = new import__550.MetadataTable({ count: 10, class: {} }); expect(function() { metadataTable.getPropertyTypedArrayBySemantic(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/MetadataTypeSpec.js var import__551 = __toESM(require_Cesium(), 1); describe("Scene/MetadataType", function() { it("isVectorType works", function() { expect(import__551.MetadataType.isVectorType(import__551.MetadataType.VEC2)).toBe(true); expect(import__551.MetadataType.isVectorType(import__551.MetadataType.VEC3)).toBe(true); expect(import__551.MetadataType.isVectorType(import__551.MetadataType.VEC4)).toBe(true); expect(import__551.MetadataType.isVectorType(import__551.MetadataType.MAT2)).toBe(false); expect(import__551.MetadataType.isVectorType(import__551.MetadataType.MAT2)).toBe(false); expect(import__551.MetadataType.isVectorType(import__551.MetadataType.MAT2)).toBe(false); expect(import__551.MetadataType.isVectorType(import__551.MetadataType.SCALAR)).toBe(false); expect(import__551.MetadataType.isVectorType(import__551.MetadataType.ENUM)).toBe(false); expect(import__551.MetadataType.isVectorType(import__551.MetadataType.BOOLEAN)).toBe(false); expect(import__551.MetadataType.isVectorType(import__551.MetadataType.STRING)).toBe(false); }); it("isMatrixType works", function() { expect(import__551.MetadataType.isMatrixType(import__551.MetadataType.VEC2)).toBe(false); expect(import__551.MetadataType.isMatrixType(import__551.MetadataType.VEC3)).toBe(false); expect(import__551.MetadataType.isMatrixType(import__551.MetadataType.VEC4)).toBe(false); expect(import__551.MetadataType.isMatrixType(import__551.MetadataType.MAT2)).toBe(true); expect(import__551.MetadataType.isMatrixType(import__551.MetadataType.MAT2)).toBe(true); expect(import__551.MetadataType.isMatrixType(import__551.MetadataType.MAT2)).toBe(true); expect(import__551.MetadataType.isMatrixType(import__551.MetadataType.SCALAR)).toBe(false); expect(import__551.MetadataType.isMatrixType(import__551.MetadataType.ENUM)).toBe(false); expect(import__551.MetadataType.isMatrixType(import__551.MetadataType.BOOLEAN)).toBe(false); expect(import__551.MetadataType.isMatrixType(import__551.MetadataType.STRING)).toBe(false); }); it("getComponentCount works", function() { expect(import__551.MetadataType.getComponentCount(import__551.MetadataType.VEC2)).toBe(2); expect(import__551.MetadataType.getComponentCount(import__551.MetadataType.VEC3)).toBe(3); expect(import__551.MetadataType.getComponentCount(import__551.MetadataType.VEC4)).toBe(4); expect(import__551.MetadataType.getComponentCount(import__551.MetadataType.MAT2)).toBe(4); expect(import__551.MetadataType.getComponentCount(import__551.MetadataType.MAT3)).toBe(9); expect(import__551.MetadataType.getComponentCount(import__551.MetadataType.MAT4)).toBe(16); expect(import__551.MetadataType.getComponentCount(import__551.MetadataType.SCALAR)).toBe(1); expect(import__551.MetadataType.getComponentCount(import__551.MetadataType.ENUM)).toBe(1); expect(import__551.MetadataType.getComponentCount(import__551.MetadataType.BOOLEAN)).toBe(1); expect(import__551.MetadataType.getComponentCount(import__551.MetadataType.STRING)).toBe(1); }); it("getComponentCount throws for invalid type", function() { expect(function() { return import__551.MetadataType.getComponentCount("NOT_A_TYPE"); }).toThrowDeveloperError(); }); it("getMathType works", function() { expect(import__551.MetadataType.getMathType(import__551.MetadataType.VEC2)).toBe(import__551.Cartesian2); expect(import__551.MetadataType.getMathType(import__551.MetadataType.VEC3)).toBe(import__551.Cartesian3); expect(import__551.MetadataType.getMathType(import__551.MetadataType.VEC4)).toBe(import__551.Cartesian4); expect(import__551.MetadataType.getMathType(import__551.MetadataType.MAT2)).toBe(import__551.Matrix2); expect(import__551.MetadataType.getMathType(import__551.MetadataType.MAT3)).toBe(import__551.Matrix3); expect(import__551.MetadataType.getMathType(import__551.MetadataType.MAT4)).toBe(import__551.Matrix4); expect(import__551.MetadataType.getMathType(import__551.MetadataType.SCALAR)).not.toBeDefined(); expect(import__551.MetadataType.getMathType(import__551.MetadataType.ENUM)).not.toBeDefined(); expect(import__551.MetadataType.getMathType(import__551.MetadataType.BOOLEAN)).not.toBeDefined(); expect(import__551.MetadataType.getMathType(import__551.MetadataType.STRING)).not.toBeDefined(); }); }); // packages/engine/Specs/Scene/MoonSpec.js var import__552 = __toESM(require_Cesium(), 1); describe( "Scene/Moon", function() { let scene2; const backgroundColor = [255, 0, 0, 255]; beforeAll(function() { scene2 = createScene_default(); import__552.Color.unpack(backgroundColor, 0, scene2.backgroundColor); }); afterAll(function() { scene2.destroyForSpecs(); }); function lookAtMoon(camera, date) { const icrfToFixed = new import__552.Matrix3(); if (!(0, import__552.defined)(import__552.Transforms.computeIcrfToFixedMatrix(date, icrfToFixed))) { import__552.Transforms.computeTemeToPseudoFixedMatrix(date, icrfToFixed); } const moonPosition = import__552.Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame( date ); import__552.Matrix3.multiplyByVector(icrfToFixed, moonPosition, moonPosition); camera.viewBoundingSphere( new import__552.BoundingSphere(moonPosition, import__552.Ellipsoid.MOON.maximumRadius) ); } it("default constructs the moon", function() { const moon = new import__552.Moon(); expect(moon.show).toEqual(true); expect(moon.textureUrl).toContain("Assets/Textures/moonSmall.jpg"); expect(moon.ellipsoid).toBe(import__552.Ellipsoid.MOON); expect(moon.onlySunLighting).toEqual(true); }); it("draws in 3D", function() { expect(scene2).toRender(backgroundColor); scene2.moon = new import__552.Moon(); lookAtMoon(scene2.camera, scene2.frameState.time); expect(scene2).notToRender(backgroundColor); scene2.moon = scene2.moon.destroy(); }); it("does not render when show is false", function() { expect(scene2).toRender(backgroundColor); scene2.moon = new import__552.Moon(); lookAtMoon(scene2.camera, scene2.frameState.time); expect(scene2).notToRender(backgroundColor); scene2.moon.show = false; expect(scene2).toRender(backgroundColor); scene2.moon = scene2.moon.destroy(); }); it("isDestroyed", function() { const moon = new import__552.Moon(); expect(moon.isDestroyed()).toEqual(false); moon.destroy(); expect(moon.isDestroyed()).toEqual(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/MultifrustumSpec.js var import__553 = __toESM(require_Cesium(), 1); var import__554 = __toESM(require_Cesium(), 1); describe( "Scene/Multifrustum", function() { let scene2; let context; let primitives; let atlas; let greenImage; let blueImage; let whiteImage; let logDepth; beforeAll(function() { scene2 = createScene_default(); logDepth = scene2.logarithmicDepthBuffer; scene2.destroyForSpecs(); return Promise.all([ import__553.Resource.fetchImage("./Data/Images/Green.png").then(function(image) { greenImage = image; }), import__553.Resource.fetchImage("./Data/Images/Blue.png").then(function(image) { blueImage = image; }), import__553.Resource.fetchImage("./Data/Images/White.png").then(function(image) { whiteImage = image; }) ]); }); beforeEach(function() { scene2 = createScene_default(); context = scene2.context; primitives = scene2.primitives; scene2.logarithmicDepthBuffer = false; const camera = scene2.camera; camera.position = new import__553.Cartesian3(); camera.direction = import__553.Cartesian3.negate(import__553.Cartesian3.UNIT_Z, new import__553.Cartesian3()); camera.up = import__553.Cartesian3.clone(import__553.Cartesian3.UNIT_Y); camera.right = import__553.Cartesian3.clone(import__553.Cartesian3.UNIT_X); camera.frustum.near = 1; camera.frustum.far = 1e9; camera.frustum.fov = import__554.Math.toRadians(60); camera.frustum.aspectRatio = 1; }); afterEach(function() { atlas = atlas && atlas.destroy(); scene2.destroyForSpecs(); }); let billboard0; let billboard1; let billboard2; function createBillboards() { atlas = new import__553.TextureAtlas({ context, borderWidthInPixels: 1, initialSize: new import__553.Cartesian2(3, 3) }); atlas.texture.sampler = import__553.Sampler.NEAREST; let billboards = new import__553.BillboardCollection(); billboards.textureAtlas = atlas; billboards.destroyTextureAtlas = false; billboard0 = billboards.add({ position: new import__553.Cartesian3(0, 0, -50), image: greenImage }); primitives.add(billboards); billboards = new import__553.BillboardCollection(); billboards.textureAtlas = atlas; billboards.destroyTextureAtlas = false; billboard1 = billboards.add({ position: new import__553.Cartesian3(0, 0, -5e4), image: blueImage }); primitives.add(billboards); billboards = new import__553.BillboardCollection(); billboards.textureAtlas = atlas; billboards.destroyTextureAtlas = false; billboard2 = billboards.add({ position: new import__553.Cartesian3(0, 0, -5e7), image: whiteImage }); primitives.add(billboards); return pollToPromise_default(function() { scene2.renderForSpecs(); return billboard0.ready && billboard1.ready && billboard2.ready; }); } it("renders primitive in closest frustum", function() { return createBillboards().then(function() { expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toEqual(0); expect(rgba[1]).not.toEqual(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toEqual(0); expect(rgba[1]).not.toEqual(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); }); }); it("renders primitive in middle frustum", function() { return createBillboards().then(function() { billboard0.color = new import__553.Color(1, 1, 1, 0); expect(scene2).toRender([0, 0, 255, 255]); expect(scene2).toRender([0, 0, 255, 255]); }); }); it("renders primitive in last frustum", function() { return createBillboards().then(function() { const color = new import__553.Color(1, 1, 1, 0); billboard0.color = color; billboard1.color = color; expect(scene2).toRender([255, 255, 255, 255]); expect(scene2).toRender([255, 255, 255, 255]); }); }); it("renders primitive in last frustum with debugShowFrustums", function() { return createBillboards().then(function() { const color = new import__553.Color(1, 1, 1, 1); billboard0.color = color; billboard1.color = color; spyOn(import__553.DrawCommand.prototype, "execute"); scene2.debugShowFrustums = true; scene2.renderForSpecs(); expect(import__553.DrawCommand.prototype.execute).toHaveBeenCalled(); const calls = import__553.DrawCommand.prototype.execute.calls.all(); let billboardCall; let i; for (i = 0; i < calls.length; ++i) { if (calls[i].object.owner instanceof import__553.BillboardCollection) { billboardCall = calls[i]; break; } } expect(billboardCall).toBeDefined(); expect(billboardCall.args.length).toEqual(2); let found = false; const sources = billboardCall.object.shaderProgram.fragmentShaderSource.sources; for (let j = 0; j < sources.length; ++j) { if (sources[j].indexOf("czm_Debug_main") !== -1) { found = true; break; } } expect(found).toBe(true); }); }); function createPrimitive(bounded, closestFrustum) { bounded = (0, import__553.defaultValue)(bounded, true); closestFrustum = (0, import__553.defaultValue)(closestFrustum, false); function Primitive26() { this._va = void 0; this._sp = void 0; this._rs = void 0; this._modelMatrix = import__553.Matrix4.fromTranslation( new import__553.Cartesian3(0, 0, -5e4), new import__553.Matrix4() ); this.color = new import__553.Color(1, 1, 0, 1); const that = this; this._um = { u_color: function() { return that.color; }, u_model: function() { return that._modelMatrix; } }; } Primitive26.prototype.update = function(frameState2) { if (!(0, import__553.defined)(this._sp)) { let vs = ""; vs += "in vec4 position;"; vs += "void main()"; vs += "{"; vs += " gl_Position = czm_modelViewProjection * position;"; vs += closestFrustum ? " gl_Position.z = clamp(gl_Position.z, gl_DepthRange.near, gl_DepthRange.far);" : ""; vs += "}"; let fs = ""; fs += "uniform vec4 u_color;"; fs += "void main()"; fs += "{"; fs += " out_FragColor = u_color;"; fs += "}"; const dimensions = new import__553.Cartesian3(5e5, 5e5, 5e5); const maximum = import__553.Cartesian3.multiplyByScalar( dimensions, 0.5, new import__553.Cartesian3() ); const minimum = import__553.Cartesian3.negate(maximum, new import__553.Cartesian3()); const geometry = import__553.BoxGeometry.createGeometry( new import__553.BoxGeometry({ minimum, maximum }) ); const attributeLocations = import__553.GeometryPipeline.createAttributeLocations( geometry ); this._va = import__553.VertexArray.fromGeometry({ context: frameState2.context, geometry, attributeLocations, bufferUsage: import__553.BufferUsage.STATIC_DRAW }); this._sp = import__553.ShaderProgram.fromCache({ context: frameState2.context, vertexShaderSource: vs, fragmentShaderSource: fs, attributeLocations }); this._rs = import__553.RenderState.fromCache({ blending: import__553.BlendingState.ALPHA_BLEND }); } frameState2.commandList.push( new import__553.DrawCommand({ renderState: this._rs, shaderProgram: this._sp, vertexArray: this._va, uniformMap: this._um, modelMatrix: this._modelMatrix, executeInClosestFrustum: closestFrustum, boundingVolume: bounded ? new import__553.BoundingSphere(import__553.Cartesian3.clone(import__553.Cartesian3.ZERO), 5e5) : void 0, pass: import__553.Pass.OPAQUE }) ); }; Primitive26.prototype.destroy = function() { this._va = this._va && this._va.destroy(); this._sp = this._sp && this._sp.destroy(); return (0, import__553.destroyObject)(this); }; Primitive26.prototype.isDestroyed = () => { return false; }; return new Primitive26(); } it("renders primitive with undefined bounding volume", function() { const primitive = createPrimitive(false); primitives.add(primitive); expect(scene2).toRender([255, 255, 0, 255]); expect(scene2).toRender([255, 255, 0, 255]); }); it("renders only in the closest frustum", function() { return createBillboards().then(function() { const color = new import__553.Color(1, 1, 1, 0); billboard0.color = color; billboard1.color = color; billboard2.color = color; const primitive = createPrimitive(true, true); primitive.color = new import__553.Color(1, 1, 0, 0.5); primitives.add(primitive); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).not.toEqual(0); expect(rgba[1]).not.toEqual(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).not.toEqual(0); expect(rgba[1]).not.toEqual(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); }); }); it("render without a central body or any primitives", function() { scene2.renderForSpecs(); }); it("does not crash when near plane is greater than or equal to the far plane", function() { const camera = scene2.camera; camera.frustum.far = 1e3; camera.position = new import__553.Cartesian3(0, 0, 1e12); return createBillboards(); }); it("log depth uses less frustums", function() { if (!logDepth) { return; } return createBillboards().then(function() { scene2.render(); expect(scene2.frustumCommandsList.length).toEqual(3); scene2.logarithmicDepthBuffer = true; scene2.render(); expect(scene2.frustumCommandsList.length).toEqual(1); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Multiple3DTileContentSpec.js var import__555 = __toESM(require_Cesium(), 1); describe( "Scene/Multiple3DTileContent", function() { let scene2; const centerLongitude = -1.31968; const centerLatitude = 0.698874; const multipleContentsUrl = "./Data/Cesium3DTiles/MultipleContents/MultipleContents/tileset_1.1.json"; const multipleContentsLegacyUrl = "./Data/Cesium3DTiles/MultipleContents/MultipleContents/tileset_1.0.json"; const multipleContentsLegacyWithContentUrl = "./Data/Cesium3DTiles/MultipleContents/MultipleContents/tileset_1.0_content.json"; const tilesetResource = new import__555.Resource({ url: "http://example.com" }); const contents = [ { uri: "pointcloud.pnts" }, { uri: "batched.b3dm" }, { uri: "gltfModel.glb" } ]; const contentsJson = { contents }; const contentJson = { content: contents }; function makeGltfBuffer() { const gltf = { asset: { version: "1.0" } }; return generateJsonBuffer_default(gltf).buffer; } let originalRequestsPerServer; function setZoom(distance) { const center = import__555.Cartesian3.fromRadians(centerLongitude, centerLatitude); scene2.camera.lookAt(center, new import__555.HeadingPitchRange(0, -1.57, distance)); } function viewAllTiles() { setZoom(26); } function viewNothing() { setZoom(200); } beforeAll(function() { scene2 = createScene_default(); originalRequestsPerServer = import__555.RequestScheduler.maximumRequestsPerServer; }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { import__555.RequestScheduler.maximumRequestsPerServer = originalRequestsPerServer; viewAllTiles(); }); afterEach(function() { scene2.primitives.removeAll(); }); function expectRenderMultipleContents(tileset) { expect(scene2).toPickAndCall(function(result) { const pickedBuilding = result; expect(pickedBuilding).toBeDefined(); pickedBuilding.color = import__555.Color.clone(import__555.Color.YELLOW, pickedBuilding.color); Cesium3DTilesTester_default.expectRender(scene2, tileset, function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toBeGreaterThan(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); pickedBuilding.show = false; let pickedInstance; expect(scene2).toPickAndCall(function(result2) { pickedInstance = result2; expect(pickedInstance).toBeDefined(); expect(pickedInstance).not.toEqual(pickedBuilding); }); pickedInstance.color = import__555.Color.clone(import__555.Color.GREEN, pickedInstance.color); Cesium3DTilesTester_default.expectRender(scene2, tileset, function(rgba) { expect(rgba[0]).toEqual(0); expect(rgba[1]).toBeGreaterThan(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); pickedInstance.show = false; Cesium3DTilesTester_default.expectRenderBlank(scene2, tileset); }); } it("innerContentUrls returns the urls from object containing contents array", function() { const tileset = {}; const tile = {}; const content = new import__555.Multiple3DTileContent( tileset, tile, tilesetResource, contentsJson ); expect(content.innerContentUrls).toEqual([ "pointcloud.pnts", "batched.b3dm", "gltfModel.glb" ]); }); it("innerContentUrls returns the urls from object containing content (legacy)", function() { const tileset = {}; const tile = {}; const content = new import__555.Multiple3DTileContent( tileset, tile, tilesetResource, contentJson ); expect(content.innerContentUrls).toEqual([ "pointcloud.pnts", "batched.b3dm", "gltfModel.glb" ]); }); it("requestInnerContents returns promise that resolves to content if successful", async function() { const mockTileset = { statistics: { numberOfPendingRequests: 0, numberOfAttemptedRequests: 0 } }; const tile = {}; const content = new import__555.Multiple3DTileContent( mockTileset, tile, tilesetResource, contentsJson ); spyOn(import__555.Resource.prototype, "fetchArrayBuffer").and.callFake(function() { return Promise.resolve(makeGltfBuffer()); }); const promise = content.requestInnerContents(); expect(mockTileset.statistics.numberOfPendingRequests).toBe(3); expect(mockTileset.statistics.numberOfAttemptedRequests).toBe(0); await expectAsync(promise).toBeResolvedTo(jasmine.any(Array)); expect(mockTileset.statistics.numberOfPendingRequests).toBe(0); expect(mockTileset.statistics.numberOfAttemptedRequests).toBe(0); }); it("requestInnerContents returns undefined and updates statistics if all requests cannot be scheduled", function() { const mockTileset = { statistics: { numberOfPendingRequests: 0, numberOfAttemptedRequests: 0 } }; const tile = {}; const content = new import__555.Multiple3DTileContent( mockTileset, tile, tilesetResource, contentsJson ); import__555.RequestScheduler.maximumRequestsPerServer = 2; expect(content.requestInnerContents()).toBeUndefined(); expect(mockTileset.statistics.numberOfPendingRequests).toBe(0); expect(mockTileset.statistics.numberOfAttemptedRequests).toBe(3); }); it("requestInnerContents handles inner content failures", async function() { const mockTileset = { statistics: { numberOfPendingRequests: 0, numberOfAttemptedRequests: 0 }, tileFailed: new import__555.Event() }; const tile = {}; const content = new import__555.Multiple3DTileContent( mockTileset, tile, tilesetResource, contentsJson ); spyOn(import__555.Resource.prototype, "fetchArrayBuffer").and.callFake(function() { return Promise.reject(new Error("my error")); }); const failureSpy = jasmine.createSpy(); mockTileset.tileFailed.addEventListener(failureSpy); const promise = content.requestInnerContents(); expect(mockTileset.statistics.numberOfPendingRequests).toBe(3); expect(mockTileset.statistics.numberOfAttemptedRequests).toBe(0); await expectAsync(promise).toBeResolved(); expect(mockTileset.statistics.numberOfPendingRequests).toBe(0); expect(mockTileset.statistics.numberOfAttemptedRequests).toBe(0); expect(failureSpy).toHaveBeenCalledWith( jasmine.objectContaining({ message: "my error" }) ); }); it("requestInnerContents handles cancelled requests", async function() { const mockTileset = { statistics: { numberOfPendingRequests: 0, numberOfAttemptedRequests: 0 } }; const tile = {}; const content = new import__555.Multiple3DTileContent( mockTileset, tile, tilesetResource, contentsJson ); spyOn(import__555.Resource.prototype, "fetchArrayBuffer").and.callFake(function() { return Promise.resolve(makeGltfBuffer()); }); const promise = content.requestInnerContents(); expect(mockTileset.statistics.numberOfPendingRequests).toBe(3); expect(mockTileset.statistics.numberOfAttemptedRequests).toBe(0); content.cancelRequests(); await expectAsync(promise).toBeResolved(); expect(mockTileset.statistics.numberOfPendingRequests).toBe(0); expect(mockTileset.statistics.numberOfAttemptedRequests).toBe(3); }); it("becomes ready", async function() { const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, multipleContentsUrl ); expect(tileset.root.contentReady).toBeTrue(); expect(tileset.root.content).toBeDefined(); }); it("renders multiple contents", function() { return Cesium3DTilesTester_default.loadTileset(scene2, multipleContentsUrl).then( expectRenderMultipleContents ); }); it("renders multiple contents (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, multipleContentsLegacyUrl ).then(expectRenderMultipleContents); }); it("renders multiple contents (legacy with 'content')", function() { return Cesium3DTilesTester_default.loadTileset( scene2, multipleContentsLegacyWithContentUrl ).then(expectRenderMultipleContents); }); it("renders valid tiles after tile failure", function() { const originalLoadJson = import__555.Cesium3DTileset.loadJson; spyOn(import__555.Cesium3DTileset, "loadJson").and.callFake(function(tilesetUrl) { return originalLoadJson(tilesetUrl).then(function(tilesetJson) { const contents2 = tilesetJson.root.contents; const badTile = { uri: "nonexistent.b3dm" }; contents2.splice(1, 0, badTile); return tilesetJson; }); }); return Cesium3DTilesTester_default.loadTileset(scene2, multipleContentsUrl).then( expectRenderMultipleContents ); }); it("renders valid tiles after tile failure (legacy)", function() { const originalLoadJson = import__555.Cesium3DTileset.loadJson; spyOn(import__555.Cesium3DTileset, "loadJson").and.callFake(function(tilesetUrl) { return originalLoadJson(tilesetUrl).then(function(tilesetJson) { const content = tilesetJson.root.extensions["3DTILES_multiple_contents"].contents; const badTile = { uri: "nonexistent.b3dm" }; content.splice(1, 0, badTile); return tilesetJson; }); }); return Cesium3DTilesTester_default.loadTileset( scene2, multipleContentsLegacyUrl ).then(expectRenderMultipleContents); }); it("cancelRequests cancels in-flight requests", function() { viewNothing(); return Cesium3DTilesTester_default.loadTileset(scene2, multipleContentsUrl).then( function(tileset) { viewAllTiles(); scene2.renderForSpecs(); const multipleContents = tileset.root.content; multipleContents.cancelRequests(); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset).then( function() { expect(multipleContents._cancelCount).toBe(1); } ); } ); }); it("destroys", function() { return Cesium3DTilesTester_default.tileDestroys(scene2, multipleContentsUrl); }); describe("metadata", function() { const withGroupMetadataUrl = "./Data/Cesium3DTiles/MultipleContents/GroupMetadata/tileset_1.1.json"; const withGroupMetadataLegacyUrl = "./Data/Cesium3DTiles/MultipleContents/GroupMetadata/tileset_1.0.json"; const withExplicitContentMetadataUrl = "./Data/Cesium3DTiles/Metadata/MultipleContentsWithMetadata/tileset_1.1.json"; const withExplicitContentMetadataLegacyUrl = "./Data/Cesium3DTiles/Metadata/MultipleContentsWithMetadata/tileset_1.0.json"; const withImplicitContentMetadataUrl = "./Data/Cesium3DTiles/Metadata/ImplicitMultipleContentsWithMetadata/tileset_1.1.json"; const withImplicitContentMetadataLegacyUrl = "./Data/Cesium3DTiles/Metadata/ImplicitMultipleContentsWithMetadata/tileset_1.0.json"; let metadataClass; let groupMetadata; beforeAll(function() { metadataClass = import__555.MetadataClass.fromJson({ id: "test", class: { properties: { name: { type: "STRING" }, height: { type: "SCALAR", componentType: "FLOAT32" } } } }); groupMetadata = new import__555.GroupMetadata({ id: "testGroup", group: { properties: { name: "Test Group", height: 35.6 } }, class: metadataClass }); }); it("group metadata returns undefined", function() { return Cesium3DTilesTester_default.loadTileset(scene2, multipleContentsUrl).then( function(tileset) { const content = tileset.root.content; expect(content.group).not.toBeDefined(); } ); }); it("assigning group metadata throws", function() { return Cesium3DTilesTester_default.loadTileset(scene2, multipleContentsUrl).then( function(tileset) { expect(function() { const content = tileset.root.content; content.group = new import__555.Cesium3DContentGroup({ metadata: groupMetadata }); }).toThrowDeveloperError(); } ); }); it("initializes group metadata for inner contents", function() { return Cesium3DTilesTester_default.loadTileset( scene2, withGroupMetadataUrl ).then(function(tileset) { const multipleContents = tileset.root.content; const innerContents = multipleContents.innerContents; const buildingsContent = innerContents[0]; let groupMetadata2 = buildingsContent.group.metadata; expect(groupMetadata2).toBeDefined(); expect(groupMetadata2.getProperty("color")).toEqual( new import__555.Cartesian3(255, 127, 0) ); expect(groupMetadata2.getProperty("priority")).toBe(10); expect(groupMetadata2.getProperty("isInstanced")).toBe(false); const cubesContent = innerContents[1]; groupMetadata2 = cubesContent.group.metadata; expect(groupMetadata2).toBeDefined(); expect(groupMetadata2.getProperty("color")).toEqual( new import__555.Cartesian3(0, 255, 127) ); expect(groupMetadata2.getProperty("priority")).toBe(5); expect(groupMetadata2.getProperty("isInstanced")).toBe(true); }); }); it("initializes group metadata for inner contents (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, withGroupMetadataLegacyUrl ).then(function(tileset) { const multipleContents = tileset.root.content; const innerContents = multipleContents.innerContents; const buildingsContent = innerContents[0]; let groupMetadata2 = buildingsContent.group.metadata; expect(groupMetadata2).toBeDefined(); expect(groupMetadata2.getProperty("color")).toEqual( new import__555.Cartesian3(255, 127, 0) ); expect(groupMetadata2.getProperty("priority")).toBe(10); expect(groupMetadata2.getProperty("isInstanced")).toBe(false); const cubesContent = innerContents[1]; groupMetadata2 = cubesContent.group.metadata; expect(groupMetadata2).toBeDefined(); expect(groupMetadata2.getProperty("color")).toEqual( new import__555.Cartesian3(0, 255, 127) ); expect(groupMetadata2.getProperty("priority")).toBe(5); expect(groupMetadata2.getProperty("isInstanced")).toBe(true); }); }); it("content metadata returns undefined", function() { return Cesium3DTilesTester_default.loadTileset(scene2, multipleContentsUrl).then( function(tileset) { const content = tileset.root.content; expect(content.metadata).not.toBeDefined(); } ); }); it("assigning content metadata throws", function() { return Cesium3DTilesTester_default.loadTileset(scene2, multipleContentsUrl).then( function(tileset) { expect(function() { const content = tileset.root.content; content.metadata = {}; }).toThrowDeveloperError(); } ); }); it("initializes explicit content metadata for inner contents", function() { return Cesium3DTilesTester_default.loadTileset( scene2, withExplicitContentMetadataUrl ).then(function(tileset) { const multipleContents = tileset.root.content; const innerContents = multipleContents.innerContents; const batchedContent = innerContents[0]; const batchedMetadata = batchedContent.metadata; expect(batchedMetadata).toBeDefined(); expect(batchedMetadata.getProperty("highlightColor")).toEqual( new import__555.Cartesian3(0, 0, 255) ); expect(batchedMetadata.getProperty("author")).toEqual("Cesium"); const instancedContent = innerContents[1]; const instancedMetadata = instancedContent.metadata; expect(instancedMetadata).toBeDefined(); expect(instancedMetadata.getProperty("numberOfInstances")).toEqual( 50 ); expect(instancedMetadata.getProperty("author")).toEqual( "Sample Author" ); }); }); it("initializes explicit content metadata for inner contents (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, withExplicitContentMetadataLegacyUrl ).then(function(tileset) { const multipleContents = tileset.root.content; const innerContents = multipleContents.innerContents; const batchedContent = innerContents[0]; const batchedMetadata = batchedContent.metadata; expect(batchedMetadata).toBeDefined(); expect(batchedMetadata.getProperty("highlightColor")).toEqual( new import__555.Cartesian3(0, 0, 255) ); expect(batchedMetadata.getProperty("author")).toEqual("Cesium"); const instancedContent = innerContents[1]; const instancedMetadata = instancedContent.metadata; expect(instancedMetadata).toBeDefined(); expect(instancedMetadata.getProperty("numberOfInstances")).toEqual( 50 ); expect(instancedMetadata.getProperty("author")).toEqual( "Sample Author" ); }); }); it("initializes implicit content metadata for inner contents", function() { return Cesium3DTilesTester_default.loadTileset( scene2, withImplicitContentMetadataUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const subtreeChildTile = subtreeRootTile.children[0]; const multipleContents = subtreeChildTile.content; const innerContents = multipleContents.innerContents; const buildingContent = innerContents[0]; const buildingMetadata = buildingContent.metadata; expect(buildingMetadata).toBeDefined(); expect(buildingMetadata.getProperty("height")).toEqual(50); expect(buildingMetadata.getProperty("color")).toEqual( new import__555.Cartesian3(0, 0, 255) ); const treeContent = innerContents[1]; const treeMetadata = treeContent.metadata; expect(treeMetadata).toBeDefined(); expect(treeMetadata.getProperty("age")).toEqual(16); }); }); it("initializes implicit content metadata for inner contents (legacy)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, withImplicitContentMetadataLegacyUrl ).then(function(tileset) { const placeholderTile = tileset.root; const subtreeRootTile = placeholderTile.children[0]; const subtreeChildTile = subtreeRootTile.children[0]; const multipleContents = subtreeChildTile.content; const innerContents = multipleContents.innerContents; const buildingContent = innerContents[0]; const buildingMetadata = buildingContent.metadata; expect(buildingMetadata).toBeDefined(); expect(buildingMetadata.getProperty("height")).toEqual(50); expect(buildingMetadata.getProperty("color")).toEqual( new import__555.Cartesian3(0, 0, 255) ); const treeContent = innerContents[1]; const treeMetadata = treeContent.metadata; expect(treeMetadata).toBeDefined(); expect(treeMetadata.getProperty("age")).toEqual(16); }); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/OctahedralProjectedCubeMapSpec.js var import__556 = __toESM(require_Cesium(), 1); var import__557 = __toESM(require_Cesium(), 1); describe( "Scene/OctahedralProjectedCubeMap", function() { let context; let computeEngine; let octahedralMap; const environmentMapUrl = "./Data/EnvironmentMap/kiara_6_afternoon_2k_ibl.ktx2"; const fsOctahedralMap = "uniform sampler2D projectedMap;uniform vec2 textureSize;uniform vec3 direction;uniform float lod;uniform float maxLod;void main() { vec3 color = czm_sampleOctahedralProjection(projectedMap, textureSize, direction, lod, maxLod); out_FragColor = vec4(color, 1.0);}"; const fsCubeMap = "uniform samplerCube cubeMap;uniform vec3 direction;void main() { vec4 rgba = czm_textureCube(cubeMap, direction); out_FragColor = vec4(rgba.rgb, 1.0);}"; beforeAll(function() { context = createContext_default(); computeEngine = new import__556.ComputeEngine(context); }); afterAll(function() { context.destroyForSpecs(); computeEngine.destroy(); }); afterEach(function() { octahedralMap = octahedralMap && octahedralMap.destroy(); context.textureCache.destroyReleasedTextures(); }); function executeCommands2(frameState2) { const length2 = frameState2.commandList.length; for (let i = 0; i < length2; ++i) { const command = frameState2.commandList[i]; if (command.pass === import__556.Pass.COMPUTE) { command.execute(computeEngine); } else { command.execute(context); } } frameState2.commandList.length = 0; } function sampleOctahedralMap(octahedralMap2, direction, lod, callback) { expect({ context, fragmentShader: fsOctahedralMap, uniformMap: { projectedMap: function() { return octahedralMap2.texture; }, textureSize: function() { return octahedralMap2.texture.dimensions; }, direction: function() { return direction; }, lod: function() { return lod; }, maxLod: function() { return octahedralMap2.maximumMipmapLevel; } } }).contextToRenderAndCall(callback); } function sampleCubeMap(cubeMap, direction, callback) { expect({ context, fragmentShader: fsCubeMap, uniformMap: { cubeMap: function() { return cubeMap; }, direction: function() { return direction; } } }).contextToRenderAndCall(callback); } function expectCubeMapAndOctahedralMapEqual(octahedralMap2, direction, lod) { return sampleCubeMap(octahedralMap2._cubeMaps[lod], direction, function(cubeMapColor) { const directionFlipY = direction.clone(); directionFlipY.y *= -1; sampleOctahedralMap(octahedralMap2, directionFlipY, lod, function(octahedralMapColor) { return expect(cubeMapColor).toEqualEpsilon(octahedralMapColor, 6); }); }); } it("creates a packed texture with the right dimensions", function() { if (!import__556.OctahedralProjectedCubeMap.isSupported(context)) { return; } octahedralMap = new import__556.OctahedralProjectedCubeMap(environmentMapUrl); const frameState2 = createFrameState_default(context); return pollToPromise_default(function() { octahedralMap.update(frameState2); return octahedralMap.ready; }).then(function() { expect(octahedralMap.texture.width).toEqual(770); expect(octahedralMap.texture.height).toEqual(512); expect(octahedralMap.maximumMipmapLevel).toEqual(5); }); }); it("correctly projects the given cube map and all mip levels", function() { if (!import__556.OctahedralProjectedCubeMap.isSupported(context)) { return; } octahedralMap = new import__556.OctahedralProjectedCubeMap(environmentMapUrl); const frameState2 = createFrameState_default(context); return pollToPromise_default(function() { octahedralMap.update(frameState2); executeCommands2(frameState2); return octahedralMap.ready; }).then(function() { const directions = { positiveX: new import__557.Cartesian3(1, 0, 0), negativeX: new import__557.Cartesian3(-1, 0, 0), positiveY: new import__557.Cartesian3(0, 1, 0), negativeY: new import__557.Cartesian3(0, -1, 0), positiveZ: new import__557.Cartesian3(0, 0, 1), negativeZ: new import__557.Cartesian3(0, 0, -1) }; for (let mipLevel = 0; mipLevel < octahedralMap.maximumMipmapLevel; mipLevel++) { for (const key in directions) { if (directions.hasOwnProperty(key)) { const direction = directions[key]; expectCubeMapAndOctahedralMapEqual( octahedralMap, direction, mipLevel ); } } } }); }); it("caches projected textures", function() { if (!import__556.OctahedralProjectedCubeMap.isSupported(context)) { return; } const projection = new import__556.OctahedralProjectedCubeMap(environmentMapUrl); const frameState2 = createFrameState_default(context); return pollToPromise_default(function() { projection.update(frameState2); return projection.ready; }).then(function() { const projection2 = new import__556.OctahedralProjectedCubeMap(environmentMapUrl); projection2.update(frameState2); expect(projection2.ready).toEqual(true); expect(projection.texture).toEqual(projection2.texture); projection2.destroy(); }).finally(function() { projection.destroy(); }); }); it("raises error event when environment map fails to load.", async function() { if (!import__556.OctahedralProjectedCubeMap.isSupported(context)) { return; } const projection = new import__556.OctahedralProjectedCubeMap("http://invalid.url"); const frameState2 = createFrameState_default(context); let error; const promise = new Promise((resolve, reject) => { const removeListener = projection.errorEvent.addEventListener((e) => { error = e; expect(error).toBeDefined(); expect(projection.ready).toEqual(false); removeListener(); resolve(); }); }); await pollToPromise_default(function() { projection.update(frameState2); return (0, import__557.defined)(error); }); return promise; }); }, "WebGL" ); // packages/engine/Specs/Scene/OpenStreetMapImageryProviderSpec.js var import__558 = __toESM(require_Cesium(), 1); var import__559 = __toESM(require_Cesium(), 1); describe("Scene/OpenStreetMapImageryProvider", function() { beforeEach(function() { import__558.RequestScheduler.clearForSpecs(); }); afterEach(function() { import__558.Resource._Implementations.createImage = import__558.Resource._DefaultImplementations.createImage; }); it("return a UrlTemplateImageryProvider", function() { const provider = new import__558.OpenStreetMapImageryProvider(); expect(provider).toBeInstanceOf(import__558.UrlTemplateImageryProvider); }); it("returns valid value for hasAlphaChannel", function() { const provider = new import__558.OpenStreetMapImageryProvider({ url: "made/up/osm/server/" }); expect(typeof provider.hasAlphaChannel).toBe("boolean"); }); it("supports a Resource for the url", function() { const resource = new import__558.Resource({ url: "made/up/osm/server/" }); const provider = new import__558.OpenStreetMapImageryProvider({ url: resource }); spyOn(import__558.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).not.toContain("//"); import__558.Resource._DefaultImplementations.createImage( new import__558.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__558.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("supports a slash at the end of the URL", function() { const provider = new import__558.OpenStreetMapImageryProvider({ url: "made/up/osm/server/" }); spyOn(import__558.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).not.toContain("//"); import__558.Resource._DefaultImplementations.createImage( new import__558.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__558.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("supports no slash at the endof the URL", function() { const provider = new import__558.OpenStreetMapImageryProvider({ url: "made/up/osm/server" }); spyOn(import__558.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toContain("made/up/osm/server/"); import__558.Resource._DefaultImplementations.createImage( new import__558.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__558.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("requestImage returns a promise for an image and loads it for cross-origin use", function() { const provider = new import__558.OpenStreetMapImageryProvider({ url: "made/up/osm/server/" }); expect(provider.url).toContain("made/up/osm/server/"); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__558.WebMercatorTilingScheme); expect(provider.rectangle).toEqual(new import__558.WebMercatorTilingScheme().rectangle); spyOn(import__558.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { import__558.Resource._DefaultImplementations.createImage( new import__558.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__558.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("when no credit is supplied, a default one is used", function() { const provider = new import__558.OpenStreetMapImageryProvider({ url: "made/up/osm/server" }); expect(provider.credit).toBeDefined(); }); it("turns the supplied credit into a logo", function() { const providerWithCredit = new import__558.OpenStreetMapImageryProvider({ url: "made/up/osm/server", credit: "Thanks to our awesome made up source of this imagery!" }); expect(providerWithCredit.credit).toBeDefined(); }); it("rectangle passed to constructor does not affect tile numbering", function() { const rectangle = new import__558.Rectangle(0.1, 0.2, 0.3, 0.4); const provider = new import__558.OpenStreetMapImageryProvider({ url: "made/up/osm/server", rectangle }); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__558.WebMercatorTilingScheme); expect(provider.rectangle.west).toBeCloseTo( rectangle.west, import__559.Math.EPSILON10 ); expect(provider.rectangle.south).toBeCloseTo( rectangle.south, import__559.Math.EPSILON10 ); expect(provider.rectangle.east).toBeCloseTo( rectangle.east, import__559.Math.EPSILON10 ); expect(provider.rectangle.north).toBeCloseTo( rectangle.north, import__559.Math.EPSILON10 ); expect(provider.tileDiscardPolicy).toBeUndefined(); spyOn(import__558.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toContain("/0/0/0"); import__558.Resource._DefaultImplementations.createImage( new import__558.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__558.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("uses maximumLevel passed to constructor", function() { const provider = new import__558.OpenStreetMapImageryProvider({ url: "made/up/osm/server", maximumLevel: 5 }); expect(provider.maximumLevel).toEqual(5); }); it("uses minimumLevel passed to constructor", function() { const provider = new import__558.OpenStreetMapImageryProvider({ url: "made/up/osm/server", minimumLevel: 1 }); expect(provider.minimumLevel).toEqual(1); }); it("uses retinaTiles passed to constructor", async function() { const provider = new import__558.OpenStreetMapImageryProvider({ url: "made/up/osm/server", retinaTiles: true }); spyOn(import__558.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toContain("0/0/0@2x.png"); import__558.Resource._DefaultImplementations.createImage( new import__558.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); const image = await provider.requestImage(0, 0, 0); expect(import__558.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); it("raises error event when image cannot be loaded", function() { const provider = new import__558.OpenStreetMapImageryProvider({ url: "made/up/osm/server" }); const layer = new import__558.ImageryLayer(provider); let tries = 0; provider.errorEvent.addEventListener(function(error) { expect(error.timesRetried).toEqual(tries); ++tries; if (tries < 3) { error.retry = true; } setTimeout(function() { import__558.RequestScheduler.update(); }, 1); }); import__558.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { if (tries === 2) { import__558.Resource._DefaultImplementations.createImage( new import__558.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); } else { setTimeout(function() { deferred.reject(); }, 1); } }; const imagery = new import__558.Imagery(layer, 0, 0, 0); imagery.addReference(); layer._requestImagery(imagery); import__558.RequestScheduler.update(); return pollToPromise_default(function() { return imagery.state === import__558.ImageryState.RECEIVED; }).then(function() { expect(imagery.image).toBeImageOrImageBitmap(); expect(tries).toEqual(2); imagery.releaseReference(); }); }); it("throws with more than four tiles at the minimum", function() { const rectangle = new import__558.Rectangle( 0, 0, import__559.Math.toRadians(1), import__559.Math.toRadians(1) ); expect(function() { return new import__558.OpenStreetMapImageryProvider({ minimumLevel: 9, rectangle }); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/OrderedGroundPrimitiveCollectionSpec.js var import__560 = __toESM(require_Cesium(), 1); describe("Scene/OrderedGroundPrimitiveCollection", function() { let updateCallOrder; beforeEach(function() { updateCallOrder = []; }); function MockPrimitive() { } MockPrimitive.prototype.update = function() { updateCallOrder.push(this); }; MockPrimitive.prototype.isDestroyed = function() { return false; }; MockPrimitive.prototype.destroy = function() { return (0, import__560.destroyObject)(this); }; it("constructs", function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); expect(collection.length).toBe(0); expect(collection.show).toBe(true); }); it("add throws without primitive", function() { expect(function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); collection.add(); }).toThrowDeveloperError(); }); it("add throws if zIndex is not a number", function() { expect(function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); collection.add(new MockPrimitive(), "3"); }).toThrowDeveloperError(); }); it("adds a primitive", function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); collection.add(new MockPrimitive()); expect(collection.length).toBe(1); }); it("add handles multiple zIndexes", function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); const p1 = collection.add(new MockPrimitive()); const p2 = collection.add(new MockPrimitive(), 0); const p3 = collection.add(new MockPrimitive(), 2); const p4 = collection.add(new MockPrimitive(), 1); expect(collection.length).toBe(4); const array = collection._collectionsArray; expect(array.length).toBe(3); expect(array[0].length).toBe(2); expect(array[0].get(0)).toBe(p1); expect(array[0].get(1)).toBe(p2); expect(array[1].length).toBe(1); expect(array[1].get(0)).toBe(p4); expect(array[2].length).toBe(1); expect(array[2].get(0)).toBe(p3); }); it("add works with negative zIndexes", function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); const p1 = collection.add(new MockPrimitive(), 0); const p2 = collection.add(new MockPrimitive(), -3); const p3 = collection.add(new MockPrimitive(), -1); const p4 = collection.add(new MockPrimitive(), -3); expect(collection.length).toBe(4); const array = collection._collectionsArray; expect(array.length).toBe(3); expect(array[0].length).toBe(2); expect(array[0].get(0)).toBe(p2); expect(array[0].get(1)).toBe(p4); expect(array[1].length).toBe(1); expect(array[1].get(0)).toBe(p3); expect(array[2].length).toBe(1); expect(array[2].get(0)).toBe(p1); }); it("set throws without primitive", function() { expect(function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); collection.set(void 0, 3); }).toThrowDeveloperError(); }); it("set throws without zIndex", function() { expect(function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); collection.set(new MockPrimitive(), void 0); }).toThrowDeveloperError(); }); it("set throws if zIndex is not a number", function() { expect(function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); collection.set(new MockPrimitive(), "3"); }).toThrowDeveloperError(); }); it("set adds primitive if it is not in the collection", function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); collection.set(new MockPrimitive(), 3); expect(collection.length).toBe(1); }); it("set changes a primitives index", function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); const p1 = collection.add(new MockPrimitive(), 0); const p2 = collection.add(new MockPrimitive(), 0); const p3 = collection.add(new MockPrimitive(), 2); const p4 = collection.add(new MockPrimitive(), 1); expect(collection.length).toBe(4); collection.set(p4, 2); expect(collection.length).toBe(4); const array = collection._collectionsArray; expect(array.length).toBe(2); expect(array[0].length).toBe(2); expect(array[0].get(0)).toBe(p1); expect(array[0].get(1)).toBe(p2); expect(array[1].length).toBe(2); expect(array[1].get(0)).toBe(p3); expect(array[1].get(1)).toBe(p4); }); it("set works with negative indexes", function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); const p1 = collection.add(new MockPrimitive(), 0); const p2 = collection.add(new MockPrimitive(), 0); expect(collection.length).toBe(2); collection.set(p2, -1); const array = collection._collectionsArray; expect(array.length).toBe(2); expect(array[0].length).toBe(1); expect(array[0].get(0)).toBe(p2); expect(array[1].length).toBe(1); expect(array[1].get(0)).toBe(p1); }); it("set throws without primitive", function() { expect(function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); collection.set(void 0, 3); }).toThrowDeveloperError(); }); it("removes a primitive", function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); const p = collection.add(new MockPrimitive()); const result = collection.remove(p); expect(result).toBe(true); expect(collection.length).toBe(0); expect(collection._collectionsArray.length).toBe(0); expect(p.isDestroyed()).toBe(true); }); it("removes handles multiple zIndexes", function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); const p1 = collection.add(new MockPrimitive(), 0); const p2 = collection.add(new MockPrimitive(), 2); const p3 = collection.add(new MockPrimitive(), 2); const p4 = collection.add(new MockPrimitive(), 1); expect(collection.length).toBe(4); const array = collection._collectionsArray; expect(array.length).toBe(3); collection.remove(p3); expect(array.length).toBe(3); collection.remove(p2); expect(array.length).toBe(2); expect(array[0].get(0)).toBe(p1); expect(array[1].get(0)).toBe(p4); }); it("removes null", function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); expect(collection.remove()).toEqual(false); }); it("removeAll removes and destroys all primitives", function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); const p1 = collection.add(new MockPrimitive(), 0); const p2 = collection.add(new MockPrimitive(), 0); const p3 = collection.add(new MockPrimitive(), 2); const p4 = collection.add(new MockPrimitive(), 1); expect(collection.length).toBe(4); collection.removeAll(); expect(collection.length).toBe(0); expect(p1.isDestroyed()).toBe(true); expect(p2.isDestroyed()).toBe(true); expect(p3.isDestroyed()).toBe(true); expect(p4.isDestroyed()).toBe(true); }); it("contains primitive", function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); const p1 = collection.add(new MockPrimitive()); expect(collection.contains(p1)).toBe(true); }); it("does not contain primitive", function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); const p1 = new MockPrimitive(); expect(collection.contains(p1)).toBe(false); }); it("does not contain undefined", function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); expect(collection.contains()).toEqual(false); }); it("update is called in the correct order", function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); const p1 = collection.add(new MockPrimitive(), 0); const p2 = collection.add(new MockPrimitive(), 3); const p3 = collection.add(new MockPrimitive(), 1); const p4 = collection.add(new MockPrimitive(), 2); collection.update(); expect(updateCallOrder).toEqual([p1, p3, p4, p2]); updateCallOrder = []; collection.set(p1, 4); collection.update(); expect(updateCallOrder).toEqual([p3, p4, p2, p1]); updateCallOrder = []; collection.set(p2, 0); collection.update(); expect(updateCallOrder).toEqual([p2, p3, p4, p1]); updateCallOrder = []; collection.set(p4, -1); collection.update(); expect(updateCallOrder).toEqual([p4, p2, p3, p1]); }); it("update is not called when show is false", function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); collection.add(new MockPrimitive(), 0); collection.add(new MockPrimitive(), 3); collection.show = false; collection.update(); expect(updateCallOrder).toEqual([]); }); it("destroys", function() { const collection = new import__560.OrderedGroundPrimitiveCollection(); expect(collection.isDestroyed()).toBe(false); collection.destroy(); expect(collection.isDestroyed()).toBe(true); }); }); // packages/engine/Specs/Scene/ParticleSpec.js var import__561 = __toESM(require_Cesium(), 1); describe("Scene/Particle", function() { it("default constructor", function() { const p = new import__561.Particle(); expect(p.mass).toEqual(1); expect(p.position).toEqual(import__561.Cartesian3.ZERO); expect(p.velocity).toEqual(import__561.Cartesian3.ZERO); expect(p.life).toEqual(Number.MAX_VALUE); expect(p.image).toBeUndefined(); expect(p.startColor).toEqual(import__561.Color.WHITE); expect(p.endColor).toEqual(import__561.Color.WHITE); expect(p.startScale).toEqual(1); expect(p.endScale).toEqual(1); expect(p.imageSize).toEqual(new import__561.Cartesian2(1, 1)); }); it("constructor", function() { const options = { mass: 10, position: new import__561.Cartesian3(1, 2, 3), velocity: new import__561.Cartesian3(4, 5, 6), life: 15, image: "url/to/image", startColor: import__561.Color.MAGENTA, endColor: import__561.Color.LIME, startScale: 0.5, endScale: 20, imageSize: new import__561.Cartesian2(7, 8) }; const p = new import__561.Particle(options); expect(p.mass).toEqual(options.mass); expect(p.position).toEqual(options.position); expect(p.velocity).toEqual(options.velocity); expect(p.life).toEqual(options.life); expect(p.image).toEqual(options.image); expect(p.startColor).toEqual(options.startColor); expect(p.endColor).toEqual(options.endColor); expect(p.startScale).toEqual(options.startScale); expect(p.endScale).toEqual(options.endScale); expect(p.imageSize).toEqual(options.imageSize); }); it("update without update function", function() { const position = new import__561.Cartesian3(1, 2, 3); const velocity = import__561.Cartesian3.normalize( new import__561.Cartesian3(-1, 1, 1), new import__561.Cartesian3() ); const p = new import__561.Particle({ life: 15, position, velocity }); const dt = 10; const expectedPosition = import__561.Cartesian3.add( p.position, import__561.Cartesian3.multiplyByScalar(p.velocity, dt, new import__561.Cartesian3()), new import__561.Cartesian3() ); expect(p.update(dt)).toEqual(true); expect(p.position).toEqual(expectedPosition); expect(p.velocity).toEqual(velocity); expect(p.age).toEqual(dt); expect(p.normalizedAge).toEqual(dt / p.life); expect(p.update(dt)).toEqual(false); }); it("update with updateFunction", function() { const increaseMass = function(particle, dt2) { particle.mass++; }; const forces = increaseMass; const position = new import__561.Cartesian3(1, 2, 3); const velocity = import__561.Cartesian3.normalize( new import__561.Cartesian3(-1, 1, 1), new import__561.Cartesian3() ); const p = new import__561.Particle({ life: 15, position, velocity }); const dt = 10; const expectedMass = p.mass + 1; const expectedPosition = import__561.Cartesian3.add( p.position, import__561.Cartesian3.multiplyByScalar(p.velocity, dt, new import__561.Cartesian3()), new import__561.Cartesian3() ); expect(p.update(dt, forces)).toEqual(true); expect(p.position).toEqual(expectedPosition); expect(p.velocity).toEqual(velocity); expect(p.age).toEqual(dt); expect(p.normalizedAge).toEqual(dt / p.life); expect(p.mass).toEqual(expectedMass); expect(p.update(dt)).toEqual(false); }); }); // packages/engine/Specs/Scene/ParticleSystemSpec.js var import__562 = __toESM(require_Cesium(), 1); describe("Scene/ParticleSystem", function() { let scene2; let greenImage; beforeAll(function() { scene2 = createScene_default(); return import__562.Resource.fetchImage("./Data/Images/Green2x2.png").then(function(result) { greenImage = result; }); }); afterAll(function() { scene2.destroyForSpecs(); }); it("default constructor", function() { const p = new import__562.ParticleSystem(); expect(p.show).toEqual(true); expect(p.forces).toBeUndefined(); expect(p.emitter).toBeDefined(); expect(p.modelMatrix).toEqual(import__562.Matrix4.IDENTITY); expect(p.emitterModelMatrix).toEqual(import__562.Matrix4.IDENTITY); expect(p.startColor).toEqual(import__562.Color.WHITE); expect(p.endColor).toEqual(import__562.Color.WHITE); expect(p.startScale).toEqual(1); expect(p.endScale).toEqual(1); expect(p.emissionRate).toEqual(5); expect(p.bursts).toBeUndefined(); expect(p.loop).toEqual(true); expect(p.minimumSpeed).toEqual(1); expect(p.maximumSpeed).toEqual(1); expect(p.minimumParticleLife).toEqual(5); expect(p.maximumParticleLife).toEqual(5); expect(p.minimumMass).toEqual(1); expect(p.maximumMass).toEqual(1); expect(p.image).toBeUndefined(); expect(p.minimumImageSize.x).toEqual(1); expect(p.minimumImageSize.y).toEqual(1); expect(p.maximumImageSize.x).toEqual(1); expect(p.maximumImageSize.y).toEqual(1); expect(p.lifetime).toEqual(Number.MAX_VALUE); expect(p.complete).toBeDefined(); expect(p.isComplete).toEqual(false); expect(p.sizeInMeters).toEqual(false); }); it("constructor", function() { const options = { show: false, updateCallback: function(p2) { p2.mass++; }, emitter: new import__562.CircleEmitter(10), modelMatrix: new import__562.Matrix4(1, 2, 3, 4, 5, 6, 7, 8, 9), emitterModelMatrix: new import__562.Matrix4( 10, 11, 12, 13, 14, 15, 16, 17, 18 ), startColor: import__562.Color.MAGENTA, endColor: import__562.Color.LAVENDAR_BLUSH, startScale: 19, endScale: 20, emissionRate: 21, bursts: [new import__562.ParticleBurst()], loop: false, minimumSpeed: 22, maximumSpeed: 23, minimumParticleLife: 24, maximumParticleLife: 25, minimumMass: 26, maximumMass: 27, image: "url/to/image", minimumImageSize: new import__562.Cartesian2(28, 30), maximumImageSize: new import__562.Cartesian2(29, 31), lifetime: 32, sizeInMeters: true }; const p = new import__562.ParticleSystem(options); expect(p.show).toEqual(options.show); expect(p.updateCallback).toEqual(options.updateCallback); expect(p.emitter).toEqual(options.emitter); expect(p.modelMatrix).toEqual(options.modelMatrix); expect(p.emitterModelMatrix).toEqual(options.emitterModelMatrix); expect(p.startColor).toEqual(options.startColor); expect(p.endColor).toEqual(options.endColor); expect(p.startScale).toEqual(options.startScale); expect(p.endScale).toEqual(options.endScale); expect(p.emissionRate).toEqual(options.emissionRate); expect(p.bursts).toEqual(options.bursts); expect(p.loop).toEqual(options.loop); expect(p.minimumSpeed).toEqual(options.minimumSpeed); expect(p.maximumSpeed).toEqual(options.maximumSpeed); expect(p.minimumParticleLife).toEqual(options.minimumParticleLife); expect(p.maximumParticleLife).toEqual(options.maximumParticleLife); expect(p.minimumMass).toEqual(options.minimumMass); expect(p.maximumMass).toEqual(options.maximumMass); expect(p.image).toEqual(options.image); expect(p.minimumImageSize).toEqual(options.minimumImageSize); expect(p.maximumImageSize).toEqual(options.maximumImageSize); expect(p.lifetime).toEqual(options.lifetime); expect(p.complete).toBeDefined(); expect(p.isComplete).toEqual(false); expect(p.sizeInMeters).toEqual(true); }); it("getters/setters", function() { const show = false; const forces = [ function(p2) { p2.mass++; } ]; const emitter = new import__562.CircleEmitter(10); const modelMatrix = new import__562.Matrix4( 1, 2, 3, 4, 5, 6, 7, 8, 9 ); const emitterModelMatrix = new import__562.Matrix4( 10, 11, 12, 13, 14, 15, 16, 17, 18 ); const startColor = import__562.Color.MAGENTA; const endColor = import__562.Color.LAVENDAR_BLUSH; const startScale = 19; const endScale = 20; const emissionRate = 21; const bursts = [new import__562.ParticleBurst()]; const loop = false; const minimumSpeed = 22; const maximumSpeed = 23; const minimumParticleLife = 24; const maximumParticleLife = 25; const minimumMass = 26; const maximumMass = 27; const image = "url/to/image"; const minimumImageSize = new import__562.Cartesian2(28, 30); const maximumImageSize = new import__562.Cartesian2(29, 31); const lifetime = 32; const sizeInMeters = true; const p = new import__562.ParticleSystem(); p.show = show; p.forces = forces; p.emitter = emitter; p.modelMatrix = modelMatrix; p.emitterModelMatrix = emitterModelMatrix; p.startColor = startColor; p.endColor = endColor; p.startScale = startScale; p.endScale = endScale; p.emissionRate = emissionRate; p.bursts = bursts; p.loop = loop; p.minimumSpeed = minimumSpeed; p.maximumSpeed = maximumSpeed; p.minimumParticleLife = minimumParticleLife; p.maximumParticleLife = maximumParticleLife; p.minimumMass = minimumMass; p.maximumMass = maximumMass; p.image = image; p.minimumImageSize = import__562.Cartesian2.clone(minimumImageSize, new import__562.Cartesian2()); p.maximumImageSize = import__562.Cartesian2.clone(maximumImageSize, new import__562.Cartesian2()); p.lifetime = lifetime; p.sizeInMeters = sizeInMeters; expect(p.show).toEqual(show); expect(p.forces).toEqual(forces); expect(p.emitter).toEqual(emitter); expect(p.modelMatrix).toEqual(modelMatrix); expect(p.emitterModelMatrix).toEqual(emitterModelMatrix); expect(p.startColor).toEqual(startColor); expect(p.endColor).toEqual(endColor); expect(p.startScale).toEqual(startScale); expect(p.endScale).toEqual(endScale); expect(p.emissionRate).toEqual(emissionRate); expect(p.bursts).toEqual(bursts); expect(p.loop).toEqual(loop); expect(p.minimumSpeed).toEqual(minimumSpeed); expect(p.maximumSpeed).toEqual(maximumSpeed); expect(p.minimumParticleLife).toEqual(minimumParticleLife); expect(p.maximumParticleLife).toEqual(maximumParticleLife); expect(p.minimumMass).toEqual(minimumMass); expect(p.maximumMass).toEqual(maximumMass); expect(p.image).toEqual(image); expect(p.minimumImageSize).toEqual(minimumImageSize); expect(p.maximumImageSize).toEqual(maximumImageSize); expect(p.lifetime).toEqual(lifetime); expect(p.complete).toBeDefined(); expect(p.isComplete).toEqual(false); expect(p.sizeInMeters).toEqual(sizeInMeters); }); it("throws with invalid emitter", function() { const p = new import__562.ParticleSystem(); expect(function() { p.emitter = void 0; }).toThrowDeveloperError(); }); it("throws with invalid modelMatrix", function() { const p = new import__562.ParticleSystem(); expect(function() { p.modelMatrix = void 0; }).toThrowDeveloperError(); }); it("throws with invalid emitterModelMatrix", function() { const p = new import__562.ParticleSystem(); expect(function() { p.emitterModelMatrix = void 0; }).toThrowDeveloperError(); }); it("throws with invalid startColor", function() { const p = new import__562.ParticleSystem(); expect(function() { p.startColor = void 0; }).toThrowDeveloperError(); }); it("throws with invalid endColor", function() { const p = new import__562.ParticleSystem(); expect(function() { p.endColor = void 0; }).toThrowDeveloperError(); }); it("throws with invalid startScale", function() { const p = new import__562.ParticleSystem(); expect(function() { p.startScale = -1; }).toThrowDeveloperError(); }); it("throws with invalid endScale", function() { const p = new import__562.ParticleSystem(); expect(function() { p.endScale = -1; }).toThrowDeveloperError(); }); it("throws with invalid emissionRate", function() { const p = new import__562.ParticleSystem(); expect(function() { p.emissionRate = -1; }).toThrowDeveloperError(); }); it("throws with invalid minimumSpeed", function() { const p = new import__562.ParticleSystem(); expect(function() { p.minimumSpeed = -1; }).toThrowDeveloperError(); }); it("throws with invalid maximumSpeed", function() { const p = new import__562.ParticleSystem(); expect(function() { p.maximumSpeed = -1; }).toThrowDeveloperError(); }); it("throws with invalid minimumParticleLife", function() { const p = new import__562.ParticleSystem(); expect(function() { p.minimumParticleLife = -1; }).toThrowDeveloperError(); }); it("throws with invalid maximumParticleLife", function() { const p = new import__562.ParticleSystem(); expect(function() { p.maximumParticleLife = -1; }).toThrowDeveloperError(); }); it("throws with invalid minimumMass", function() { const p = new import__562.ParticleSystem(); expect(function() { p.minimumMass = -1; }).toThrowDeveloperError(); }); it("throws with invalid maximumMass", function() { const p = new import__562.ParticleSystem(); expect(function() { p.maximumMass = -1; }).toThrowDeveloperError(); }); it("throws with invalid minimumWidth", function() { const p = new import__562.ParticleSystem(); expect(function() { p.minimumImageSize = new import__562.Cartesian2(-1, 2); }).toThrowDeveloperError(); }); it("throws with invalid maximumWidth", function() { const p = new import__562.ParticleSystem(); expect(function() { p.maximumImageSize = new import__562.Cartesian2(-1, 2); }).toThrowDeveloperError(); }); it("throws with invalid minimumHeight", function() { const p = new import__562.ParticleSystem(); expect(function() { p.minimumImageSize = new import__562.Cartesian2(2, -1); }).toThrowDeveloperError(); }); it("throws with invalid maximumHeight", function() { const p = new import__562.ParticleSystem(); expect(function() { p.maximumImageSize = new import__562.Cartesian2(2, -1); }).toThrowDeveloperError(); }); it("throws with invalid lifetime", function() { const p = new import__562.ParticleSystem(); expect(function() { p.lifetime = -1; }).toThrowDeveloperError(); }); it("clones default image size", function() { const p = new import__562.ParticleSystem(); expect(p.maximumImageSize).not.toBe(p.minimumImageSize); }); it("renders", function() { const system = scene2.primitives.add( new import__562.ParticleSystem({ image: greenImage, emitter: new import__562.CircleEmitter(1), emissionRate: 1e4, imageSize: new import__562.Cartesian2(100, 100) }) ); scene2.camera.position = new import__562.Cartesian3(0, 0, 20); scene2.camera.direction = new import__562.Cartesian3(0, 0, -1); scene2.camera.up = import__562.Cartesian3.clone(import__562.Cartesian3.UNIT_Y); scene2.camera.right = import__562.Cartesian3.clone(import__562.Cartesian3.UNIT_X); scene2.renderForSpecs(); return pollToPromise_default(function() { scene2.renderForSpecs(); return system._billboardCollection.get(0).ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); }); }); it("isDestroyed", function() { const p = new import__562.ParticleSystem(); expect(p.isDestroyed()).toEqual(false); p.destroy(); expect(p.isDestroyed()).toEqual(true); }); }); // packages/engine/Specs/Scene/PerInstanceColorAppearanceSpec.js var import__563 = __toESM(require_Cesium(), 1); describe( "Scene/PerInstanceColorAppearance", function() { let scene2; let rectangle; let primitive; beforeAll(function() { scene2 = createScene_default(); scene2.primitives.destroyPrimitives = false; rectangle = import__563.Rectangle.fromDegrees(-10, -10, 10, 10); scene2.camera.setView({ destination: rectangle }); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { primitive = new import__563.Primitive({ geometryInstances: new import__563.GeometryInstance({ geometry: new import__563.RectangleGeometry({ vertexFormat: import__563.PerInstanceColorAppearance.VERTEX_FORMAT, rectangle }), attributes: { color: new import__563.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }), asynchronous: false }); }); afterEach(function() { scene2.primitives.removeAll(); primitive = primitive && primitive.destroy(); }); it("constructor", function() { const a = new import__563.PerInstanceColorAppearance(); expect(a.material).not.toBeDefined(); expect(a.vertexShaderSource).toBeDefined(); expect(a.fragmentShaderSource).toBeDefined(); expect(a.renderState).toEqual( import__563.Appearance.getDefaultRenderState(true, false) ); expect(a.vertexFormat).toEqual(import__563.PerInstanceColorAppearance.VERTEX_FORMAT); expect(a.flat).toEqual(false); expect(a.faceForward).toEqual(true); expect(a.translucent).toEqual(true); expect(a.closed).toEqual(false); }); it("renders", function() { primitive.appearance = new import__563.PerInstanceColorAppearance(); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders flat", function() { primitive.appearance = new import__563.PerInstanceColorAppearance({ flat: true, translucent: false, closed: true }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive); expect(scene2).notToRender([0, 0, 0, 255]); }); }, "WebGL" ); // packages/engine/Specs/Scene/PickingSpec.js var import__564 = __toESM(require_Cesium(), 1); var import__565 = __toESM(require_Cesium(), 1); describe( "Scene/Pick", function() { const webglStub = !!window.webglStub; let scene2; let primitives; let camera; const largeRectangle = import__564.Rectangle.fromDegrees(-1, -1, 1, 1); const smallRectangle = import__564.Rectangle.fromDegrees( -1e-4, -1e-4, 1e-4, 1e-4 ); const offscreenRectangle = import__564.Rectangle.fromDegrees( -45.0002, -1.0002, -45.0001, -1.0001 ); let primitiveRay; let offscreenRay; const batchedTilesetUrl = "Data/Cesium3DTiles/Batched/BatchedWithTransformBox/tileset.json"; const pointCloudTilesetUrl = "Data/Cesium3DTiles/PointCloud/PointCloudWithTransform/tileset.json"; const voxelTilesetUrl = "Data/Cesium3DTiles/Voxel/VoxelBox3DTiles/tileset.json"; beforeAll(function() { scene2 = createScene_default({ canvas: createCanvas_default(10, 10), contextOptions: { requestWebgl1: true } }); primitives = scene2.primitives; camera = scene2.camera; camera.setView({ destination: largeRectangle }); primitiveRay = new import__564.Ray(camera.positionWC, camera.directionWC); camera.setView({ destination: offscreenRectangle }); offscreenRay = new import__564.Ray(camera.positionWC, camera.directionWC); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { scene2.mode = import__564.SceneMode.SCENE3D; scene2.morphTime = import__564.SceneMode.getMorphTime(scene2.mode); camera.setView({ destination: largeRectangle }); camera.frustum = new import__564.PerspectiveFrustum(); camera.frustum.fov = import__565.Math.toRadians(60); camera.frustum.aspectRatio = 1; }); afterEach(function() { primitives.removeAll(); scene2.globe = void 0; }); function createRectangle(height, rectangle) { const e = new import__564.Primitive({ geometryInstances: new import__564.GeometryInstance({ geometry: new import__564.RectangleGeometry({ rectangle, vertexFormat: import__564.EllipsoidSurfaceAppearance.VERTEX_FORMAT, granularity: import__565.Math.toRadians(20), height }) }), appearance: new import__564.EllipsoidSurfaceAppearance({ aboveGround: false }), asynchronous: false }); primitives.add(e); return e; } function createLargeRectangle(height) { return createRectangle(height, largeRectangle); } function createSmallRectangle(height) { return createRectangle(height, smallRectangle); } async function createTileset(url) { const options = { maximumScreenSpaceError: 0, // Dynamic screen space error seems to cause a race condition in // waitForTilesLoaded. // See https://github.com/CesiumGS/cesium/issues/11732 dynamicScreenSpaceError: false }; const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, url, options ); const cartographic = import__564.Rectangle.center(largeRectangle); const cartesian = import__564.Cartographic.toCartesian(cartographic); tileset.root.transform = import__564.Matrix4.IDENTITY; tileset.modelMatrix = import__564.Transforms.eastNorthUpToFixedFrame(cartesian); return Cesium3DTilesTester_default.waitForTilesLoaded(scene2, tileset); } function createGlobe2() { const globe2 = new import__564.Globe(); scene2.globe = globe2; globe2.depthTestAgainstTerrain = true; return pollToPromise_default(function() { scene2.render(); return globe2.tilesLoaded; }); } describe("pick", function() { it("throws when window position is undefined", function() { expect(function() { scene2.pick(void 0); }).toThrowDeveloperError(); }); it("picks a primitive", function() { const rectangle = createLargeRectangle(0); expect(scene2).toPickPrimitive(rectangle); }); it("picks a primitive with a modified pick search area", function() { camera.setView({ destination: import__564.Rectangle.fromDegrees(-10, -10, 10, 10) }); const rectangle = createLargeRectangle(0); expect(scene2).toPickPrimitive(rectangle, 7, 7, 5); expect(scene2).notToPick(7, 7, 3); }); it("does not pick primitives when show is false", function() { const rectangle = createLargeRectangle(0); rectangle.show = false; expect(scene2).notToPick(); }); it("does not pick primitives when alpha is zero", function() { const rectangle = createLargeRectangle(0); rectangle.appearance.material.uniforms.color.alpha = 0; expect(scene2).notToPick(); }); it("picks the top primitive", function() { createLargeRectangle(0); const rectangle2 = createLargeRectangle(1); expect(scene2).toPickPrimitive(rectangle2); }); it("picks in 2D", function() { scene2.morphTo2D(0); camera.setView({ destination: largeRectangle }); const rectangle = createLargeRectangle(0); scene2.renderForSpecs(); expect(scene2).toPickPrimitive(rectangle); }); it("picks in 3D with orthographic projection", function() { const frustum = new import__564.OrthographicFrustum(); frustum.aspectRatio = 1; frustum.width = 20; camera.frustum = frustum; expect(frustum.projectionMatrix).toBeDefined(); camera.setView({ destination: largeRectangle }); const rectangle = createLargeRectangle(0); scene2.renderForSpecs(); expect(scene2).toPickPrimitive(rectangle); }); }); describe("pickVoxelCoordinate", function() { it("throws when window position is undefined", function() { expect(function() { scene2._picking.pickVoxelCoordinate(void 0); }).toThrowDeveloperError(); }); it("picks a voxel coordinate from a VoxelPrimitive", async function() { const provider = await import__564.Cesium3DTilesVoxelProvider.fromUrl( voxelTilesetUrl ); const primitive = new import__564.VoxelPrimitive({ provider }); scene2.primitives.add(primitive); scene2.renderForSpecs(); const voxelCoordinate = scene2._picking.pickVoxelCoordinate( scene2, new import__564.Cartesian2(0, 0) ); expect(voxelCoordinate).toEqual(new Uint8Array(4)); }); }); describe("pickVoxel", function() { it("does not pick undefined window positions", function() { expect(function() { scene2.pickVoxel(void 0); }).toThrowDeveloperError(); }); it("picks a voxel cell from a VoxelPrimitive", async function() { const provider = await import__564.Cesium3DTilesVoxelProvider.fromUrl( voxelTilesetUrl ); const modelMatrix = import__564.Matrix4.fromUniformScale( import__564.Ellipsoid.WGS84.maximumRadius ); const primitive = new import__564.VoxelPrimitive({ provider, modelMatrix }); scene2.primitives.add(primitive); await pollToPromise_default(function() { scene2.renderForSpecs(); const traversal = primitive._traversal; return traversal.isRenderable(traversal.rootNode); }); expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toBe(primitive); }); expect(scene2).toPickVoxelAndCall(function(voxelCell) { expect(voxelCell.tileIndex).toBe(0); expect(voxelCell.sampleIndex).toBe(0); expect(voxelCell.hasProperty("a")).toBe(true); expect(voxelCell.getProperty("a")).toEqual(new Float32Array(1)); }); }); }); describe("drillPick", function() { it("drill picks a primitive with a modified pick search area", function() { camera.setView({ destination: import__564.Rectangle.fromDegrees(-10, -10, 10, 10) }); const rectangle = createLargeRectangle(0); expect(scene2).toDrillPickPrimitive(rectangle, 7, 7, 5); expect(scene2).notToDrillPick(7, 7, 3); }); it("does not drill pick undefined window positions", function() { expect(function() { scene2.pick(void 0); }).toThrowDeveloperError(); }); it("drill picks multiple objects", function() { const rectangle1 = createLargeRectangle(0); const rectangle2 = createLargeRectangle(1); expect(scene2).toDrillPickAndCall(function(pickedObjects) { expect(pickedObjects.length).toEqual(2); expect(pickedObjects[0].primitive).toEqual(rectangle2); expect(pickedObjects[1].primitive).toEqual(rectangle1); }); }); it("does not drill pick when show is false", function() { const rectangle1 = createLargeRectangle(0); const rectangle2 = createLargeRectangle(1); rectangle2.show = false; expect(scene2).toDrillPickAndCall(function(pickedObjects) { expect(pickedObjects.length).toEqual(1); expect(pickedObjects[0].primitive).toEqual(rectangle1); }); }); it("does not drill pick when alpha is zero", function() { const rectangle1 = createLargeRectangle(0); const rectangle2 = createLargeRectangle(1); rectangle2.appearance.material.uniforms.color.alpha = 0; expect(scene2).toDrillPickAndCall(function(pickedObjects) { expect(pickedObjects.length).toEqual(1); expect(pickedObjects[0].primitive).toEqual(rectangle1); }); }); it("can drill pick batched Primitives with show attribute", function() { const geometry = new import__564.RectangleGeometry({ rectangle: import__564.Rectangle.fromDegrees(-50, -50, 50, 50), granularity: import__565.Math.toRadians(20), vertexFormat: import__564.EllipsoidSurfaceAppearance.VERTEX_FORMAT, height: 0 }); const geometryWithHeight = new import__564.RectangleGeometry({ rectangle: import__564.Rectangle.fromDegrees(-50, -50, 50, 50), granularity: import__565.Math.toRadians(20), vertexFormat: import__564.EllipsoidSurfaceAppearance.VERTEX_FORMAT, height: 20 }); const instance1 = new import__564.GeometryInstance({ id: 1, geometry, attributes: { show: new import__564.ShowGeometryInstanceAttribute(true) } }); const instance2 = new import__564.GeometryInstance({ id: 2, geometry, attributes: { show: new import__564.ShowGeometryInstanceAttribute(false) } }); const instance3 = new import__564.GeometryInstance({ id: 3, geometry: geometryWithHeight, attributes: { show: new import__564.ShowGeometryInstanceAttribute(true) } }); const primitive = primitives.add( new import__564.Primitive({ geometryInstances: [instance1, instance2, instance3], asynchronous: false, appearance: new import__564.EllipsoidSurfaceAppearance() }) ); expect(scene2).toDrillPickAndCall(function(pickedObjects) { expect(pickedObjects.length).toEqual(2); expect(pickedObjects[0].primitive).toEqual(primitive); expect(pickedObjects[0].id).toEqual(3); expect(pickedObjects[1].primitive).toEqual(primitive); expect(pickedObjects[1].id).toEqual(1); }); }); it("can drill pick without ID", function() { const geometry = new import__564.RectangleGeometry({ rectangle: import__564.Rectangle.fromDegrees(-50, -50, 50, 50), granularity: import__565.Math.toRadians(20), vertexFormat: import__564.EllipsoidSurfaceAppearance.VERTEX_FORMAT }); const instance1 = new import__564.GeometryInstance({ geometry, attributes: { show: new import__564.ShowGeometryInstanceAttribute(true) } }); const instance2 = new import__564.GeometryInstance({ geometry, attributes: { show: new import__564.ShowGeometryInstanceAttribute(true) } }); const primitive = primitives.add( new import__564.Primitive({ geometryInstances: [instance1, instance2], asynchronous: false, appearance: new import__564.EllipsoidSurfaceAppearance() }) ); expect(scene2).toDrillPickAndCall(function(pickedObjects) { expect(pickedObjects.length).toEqual(1); expect(pickedObjects[0].primitive).toEqual(primitive); }); }); it("can drill pick batched Primitives without show attribute", function() { const geometry = new import__564.RectangleGeometry({ rectangle: import__564.Rectangle.fromDegrees(-50, -50, 50, 50), granularity: import__565.Math.toRadians(20), vertexFormat: import__564.EllipsoidSurfaceAppearance.VERTEX_FORMAT, height: 0 }); const geometryWithHeight = new import__564.RectangleGeometry({ rectangle: import__564.Rectangle.fromDegrees(-50, -50, 50, 50), granularity: import__565.Math.toRadians(20), vertexFormat: import__564.EllipsoidSurfaceAppearance.VERTEX_FORMAT, height: 20 }); const instance1 = new import__564.GeometryInstance({ id: 1, geometry }); const instance2 = new import__564.GeometryInstance({ id: 2, geometry }); const instance3 = new import__564.GeometryInstance({ id: 3, geometry: geometryWithHeight }); const primitive = primitives.add( new import__564.Primitive({ geometryInstances: [instance1, instance2, instance3], asynchronous: false, appearance: new import__564.EllipsoidSurfaceAppearance() }) ); expect(scene2).toDrillPickAndCall(function(pickedObjects) { expect(pickedObjects.length).toEqual(1); expect(pickedObjects[0].primitive).toEqual(primitive); expect(pickedObjects[0].id).toEqual(3); }); }); it("stops drill picking when the limit is reached.", function() { createLargeRectangle(0); const rectangle2 = createLargeRectangle(1); const rectangle3 = createLargeRectangle(2); const rectangle4 = createLargeRectangle(3); expect(scene2).toDrillPickAndCall(function(pickedObjects) { expect(pickedObjects.length).toEqual(3); expect(pickedObjects[0].primitive).toEqual(rectangle4); expect(pickedObjects[1].primitive).toEqual(rectangle3); expect(pickedObjects[2].primitive).toEqual(rectangle2); }, 3); }); }); async function picksFromRayTileset(style) { const tileset = await createTileset(batchedTilesetUrl); tileset.style = style; expect(scene2).toPickFromRayAndCall(function(result) { const primitive = result.object.primitive; const position = result.position; expect(primitive).toBe(tileset); if (scene2.context.depthTexture) { const minimumHeight = import__564.Cartesian3.fromRadians(0, 0).x; const maximumHeight = minimumHeight + 20; expect(position.x).toBeGreaterThan(minimumHeight); expect(position.x).toBeLessThan(maximumHeight); expect(position.y).toEqualEpsilon(0, import__565.Math.EPSILON5); expect(position.z).toEqualEpsilon(0, import__565.Math.EPSILON5); } }, primitiveRay); } describe("pickFromRay", function() { it("picks a tileset", function() { return picksFromRayTileset(); }); it("picks a translucent tileset", function() { const style = new import__564.Cesium3DTileStyle({ color: 'color("white", 0.5)' }); return picksFromRayTileset(style); }); it("picks the globe", async function() { if (!scene2.context.depthTexture) { return; } await createGlobe2(); expect(scene2).toPickFromRayAndCall(function(result) { expect(result.object).toBeUndefined(); expect(result.position).toBeDefined(); expect(result.position.x).toBeGreaterThan( import__564.Ellipsoid.WGS84.minimumRadius ); expect(result.position.y).toEqualEpsilon(0, import__565.Math.EPSILON5); expect(result.position.z).toEqualEpsilon(0, import__565.Math.EPSILON5); }, primitiveRay); }); it("picks a primitive", function() { const rectangle = createSmallRectangle(0); expect(scene2).toPickFromRayAndCall(function(result) { const primitive = result.object.primitive; const position = result.position; expect(primitive).toBe(rectangle); if (scene2.context.depthTexture) { const expectedPosition = import__564.Cartesian3.fromRadians(0, 0); expect(position).toEqualEpsilon( expectedPosition, import__565.Math.EPSILON5 ); } }, primitiveRay); }); it("returns undefined if no primitives are picked", function() { createLargeRectangle(0); expect(scene2).toPickFromRayAndCall(function(result) { expect(result).toBeUndefined(); }, offscreenRay); }); it("does not pick primitives when show is false", function() { const rectangle = createLargeRectangle(0); rectangle.show = false; expect(scene2).toPickFromRayAndCall(function(result) { expect(result).toBeUndefined(); }, primitiveRay); }); it("does not pick primitives when alpha is zero", function() { const rectangle = createLargeRectangle(0); rectangle.appearance.material.uniforms.color.alpha = 0; expect(scene2).toPickFromRayAndCall(function(result) { expect(result).toBeUndefined(); }, primitiveRay); }); it("picks the top primitive", function() { createLargeRectangle(0); const rectangle2 = createLargeRectangle(1); expect(scene2).toPickFromRayAndCall(function(result) { expect(result.object.primitive).toBe(rectangle2); }, primitiveRay); }); it("excludes objects", function() { const rectangle1 = createLargeRectangle(0); const rectangle2 = createLargeRectangle(1); const rectangle3 = createLargeRectangle(2); const rectangle4 = createLargeRectangle(3); rectangle4.show = false; expect(scene2).toPickFromRayAndCall( function(result) { expect(result.object.primitive).toBe(rectangle1); }, primitiveRay, [rectangle2, rectangle3, rectangle4] ); expect(scene2).toPickFromRayAndCall(function(result) { expect(result.object.primitive).toBe(rectangle3); }, primitiveRay); }); it("picks primitive that doesn't write depth", function() { const collection = scene2.primitives.add(new import__564.PointPrimitiveCollection()); const point = collection.add({ position: import__564.Cartographic.fromRadians(0, 0, 100), disableDepthTestDistance: Number.POSITIVE_INFINITY }); expect(scene2).toPickFromRayAndCall( function(result) { expect(result.object.primitive).toBe(point); expect(result.position).toBeUndefined(); }, primitiveRay, [], 0.01 ); }); it("changes width", async function() { await createTileset(pointCloudTilesetUrl); expect(scene2).toPickFromRayAndCall( function(result) { expect(result).toBeUndefined(); }, primitiveRay, [], 0.1 ); expect(scene2).toPickFromRayAndCall( function(result) { expect(result).toBeDefined(); }, primitiveRay, [], 1 ); }); it("throws if ray is undefined", function() { expect(function() { scene2.pickFromRay(void 0); }).toThrowDeveloperError(); }); it("throws if scene camera is in 2D", function() { scene2.morphTo2D(0); expect(function() { scene2.pickFromRay(primitiveRay); }).toThrowDeveloperError(); }); it("throws if scene camera is in CV", function() { scene2.morphToColumbusView(0); expect(function() { scene2.pickFromRay(primitiveRay); }).toThrowDeveloperError(); }); }); describe("drillPickFromRay", function() { it("drill picks a primitive", function() { const rectangle = createSmallRectangle(0); expect(scene2).toDrillPickFromRayAndCall(function(results) { expect(results.length).toBe(1); const primitive = results[0].object.primitive; const position = results[0].position; expect(primitive).toBe(rectangle); if (scene2.context.depthTexture) { const expectedPosition = import__564.Cartesian3.fromRadians(0, 0); expect(position).toEqualEpsilon( expectedPosition, import__565.Math.EPSILON5 ); } else { expect(position).toBeUndefined(); } }, primitiveRay); }); it("drill picks multiple primitives", function() { const rectangle1 = createSmallRectangle(0); const rectangle2 = createSmallRectangle(1); expect(scene2).toDrillPickFromRayAndCall(function(results) { expect(results.length).toBe(2); expect(results[0].object.primitive).toBe(rectangle2); expect(results[1].object.primitive).toBe(rectangle1); if (scene2.context.depthTexture) { const rectangleCenter1 = import__564.Cartesian3.fromRadians(0, 0, 0); const rectangleCenter2 = import__564.Cartesian3.fromRadians(0, 0, 1); expect(results[0].position).toEqualEpsilon( rectangleCenter2, import__565.Math.EPSILON5 ); expect(results[1].position).toEqualEpsilon( rectangleCenter1, import__565.Math.EPSILON5 ); } else { expect(results[0].position).toBeUndefined(); expect(results[1].position).toBeUndefined(); } }, primitiveRay); }); it("does not drill pick when show is false", function() { const rectangle1 = createLargeRectangle(0); const rectangle2 = createLargeRectangle(1); rectangle2.show = false; expect(scene2).toDrillPickFromRayAndCall(function(results) { expect(results.length).toEqual(1); expect(results[0].object.primitive).toEqual(rectangle1); }, primitiveRay); }); it("does not drill pick when alpha is zero", function() { const rectangle1 = createLargeRectangle(0); const rectangle2 = createLargeRectangle(1); rectangle2.appearance.material.uniforms.color.alpha = 0; expect(scene2).toDrillPickFromRayAndCall(function(results) { expect(results.length).toEqual(1); expect(results[0].object.primitive).toEqual(rectangle1); }, primitiveRay); }); it("returns empty array if no primitives are picked", function() { createLargeRectangle(0); createLargeRectangle(1); expect(scene2).toDrillPickFromRayAndCall(function(results) { expect(results.length).toEqual(0); }, offscreenRay); }); it("can drill pick batched Primitives with show attribute", function() { const geometry = new import__564.RectangleGeometry({ rectangle: import__564.Rectangle.fromDegrees(-50, -50, 50, 50), granularity: import__565.Math.toRadians(20), vertexFormat: import__564.EllipsoidSurfaceAppearance.VERTEX_FORMAT, height: 0 }); const geometryWithHeight = new import__564.RectangleGeometry({ rectangle: import__564.Rectangle.fromDegrees(-50, -50, 50, 50), granularity: import__565.Math.toRadians(20), vertexFormat: import__564.EllipsoidSurfaceAppearance.VERTEX_FORMAT, height: 1 }); const instance1 = new import__564.GeometryInstance({ id: 1, geometry, attributes: { show: new import__564.ShowGeometryInstanceAttribute(true) } }); const instance2 = new import__564.GeometryInstance({ id: 2, geometry, attributes: { show: new import__564.ShowGeometryInstanceAttribute(false) } }); const instance3 = new import__564.GeometryInstance({ id: 3, geometry: geometryWithHeight, attributes: { show: new import__564.ShowGeometryInstanceAttribute(true) } }); const primitive = primitives.add( new import__564.Primitive({ geometryInstances: [instance1, instance2, instance3], asynchronous: false, appearance: new import__564.EllipsoidSurfaceAppearance() }) ); expect(scene2).toDrillPickFromRayAndCall(function(results) { expect(results.length).toEqual(2); expect(results[0].object.primitive).toEqual(primitive); expect(results[0].object.id).toEqual(3); expect(results[1].object.primitive).toEqual(primitive); expect(results[1].object.id).toEqual(1); }, primitiveRay); }); it("can drill pick without ID", function() { const geometry = new import__564.RectangleGeometry({ rectangle: import__564.Rectangle.fromDegrees(-50, -50, 50, 50), granularity: import__565.Math.toRadians(20), vertexFormat: import__564.EllipsoidSurfaceAppearance.VERTEX_FORMAT }); const instance1 = new import__564.GeometryInstance({ geometry, attributes: { show: new import__564.ShowGeometryInstanceAttribute(true) } }); const instance2 = new import__564.GeometryInstance({ geometry, attributes: { show: new import__564.ShowGeometryInstanceAttribute(true) } }); const primitive = primitives.add( new import__564.Primitive({ geometryInstances: [instance1, instance2], asynchronous: false, appearance: new import__564.EllipsoidSurfaceAppearance() }) ); expect(scene2).toDrillPickFromRayAndCall(function(results) { expect(results.length).toEqual(1); expect(results[0].object.primitive).toEqual(primitive); }, primitiveRay); }); it("can drill pick batched Primitives without show attribute", function() { const geometry = new import__564.RectangleGeometry({ rectangle: import__564.Rectangle.fromDegrees(-50, -50, 50, 50), granularity: import__565.Math.toRadians(20), vertexFormat: import__564.EllipsoidSurfaceAppearance.VERTEX_FORMAT, height: 0 }); const geometryWithHeight = new import__564.RectangleGeometry({ rectangle: import__564.Rectangle.fromDegrees(-50, -50, 50, 50), granularity: import__565.Math.toRadians(20), vertexFormat: import__564.EllipsoidSurfaceAppearance.VERTEX_FORMAT, height: 1 }); const instance1 = new import__564.GeometryInstance({ id: 1, geometry }); const instance2 = new import__564.GeometryInstance({ id: 2, geometry }); const instance3 = new import__564.GeometryInstance({ id: 3, geometry: geometryWithHeight }); const primitive = primitives.add( new import__564.Primitive({ geometryInstances: [instance1, instance2, instance3], asynchronous: false, appearance: new import__564.EllipsoidSurfaceAppearance() }) ); expect(scene2).toDrillPickFromRayAndCall(function(results) { expect(results.length).toEqual(1); expect(results[0].object.primitive).toEqual(primitive); expect(results[0].object.id).toEqual(3); }, primitiveRay); }); it("stops drill picking when the limit is reached.", function() { createLargeRectangle(0); const rectangle2 = createLargeRectangle(1); const rectangle3 = createLargeRectangle(2); const rectangle4 = createLargeRectangle(3); expect(scene2).toDrillPickFromRayAndCall( function(results) { expect(results.length).toEqual(3); expect(results[0].object.primitive).toEqual(rectangle4); expect(results[1].object.primitive).toEqual(rectangle3); expect(results[2].object.primitive).toEqual(rectangle2); }, primitiveRay, 3 ); }); it("excludes objects", function() { createLargeRectangle(0); const rectangle2 = createLargeRectangle(1); const rectangle3 = createLargeRectangle(2); const rectangle4 = createLargeRectangle(3); const rectangle5 = createLargeRectangle(4); expect(scene2).toDrillPickFromRayAndCall( function(results) { expect(results.length).toBe(2); expect(results[0].object.primitive).toBe(rectangle4); expect(results[1].object.primitive).toBe(rectangle2); }, primitiveRay, 2, [rectangle5, rectangle3] ); }); it("changes width", async function() { await createTileset(pointCloudTilesetUrl); expect(scene2).toDrillPickFromRayAndCall( function(result) { expect(result.length).toBe(0); }, primitiveRay, [], 0.1 ); expect(scene2).toDrillPickFromRayAndCall( function(result) { expect(result.length).toBe(1); }, primitiveRay, Number.POSITIVE_INFINITY, [], 1 ); }); it("throws if ray is undefined", function() { expect(function() { scene2.drillPickFromRay(void 0); }).toThrowDeveloperError(); }); it("throws if scene camera is in 2D", function() { scene2.morphTo2D(0); expect(function() { scene2.drillPickFromRay(primitiveRay); }).toThrowDeveloperError(); }); it("throws if scene camera is in CV", function() { scene2.morphToColumbusView(0); expect(function() { scene2.drillPickFromRay(primitiveRay); }).toThrowDeveloperError(); }); }); describe("sampleHeight", function() { it("samples height from tileset", async function() { if (!scene2.sampleHeightSupported) { return; } const cartographic = new import__564.Cartographic(0, 0); await createTileset(batchedTilesetUrl); expect(scene2).toSampleHeightAndCall(function(height) { expect(height).toBeGreaterThan(0); expect(height).toBeLessThan(20); }, cartographic); }); it("samples height from the globe", async function() { if (!scene2.sampleHeightSupported) { return; } const cartographic = new import__564.Cartographic(0, 0); await createGlobe2(); expect(scene2).toSampleHeightAndCall(function(height) { expect(height).toBeDefined(); }, cartographic); }); it("samples height from primitive", function() { if (!scene2.sampleHeightSupported) { return; } createSmallRectangle(0); const cartographic = new import__564.Cartographic(0, 0); expect(scene2).toSampleHeightAndCall(function(height) { expect(height).toEqualEpsilon(0, import__565.Math.EPSILON3); }, cartographic); }); it("samples height from the top primitive", function() { if (!scene2.sampleHeightSupported) { return; } createSmallRectangle(0); createSmallRectangle(1); const cartographic = new import__564.Cartographic(0, 0); expect(scene2).toSampleHeightAndCall(function(height) { expect(height).toEqualEpsilon(1, import__565.Math.EPSILON3); }, cartographic); }); it("returns undefined if no height is sampled", function() { if (!scene2.sampleHeightSupported) { return; } createSmallRectangle(0); const cartographic = new import__564.Cartographic(1, 0); expect(scene2).toSampleHeightAndCall(function(height) { expect(height).toBeUndefined(); }, cartographic); }); it("excludes objects", function() { if (!scene2.sampleHeightSupported) { return; } createSmallRectangle(0); const rectangle2 = createSmallRectangle(1); const rectangle3 = createSmallRectangle(2); const cartographic = new import__564.Cartographic(0, 0); expect(scene2).toSampleHeightAndCall( function(height) { expect(height).toEqualEpsilon(0, import__565.Math.EPSILON3); }, cartographic, [rectangle2, rectangle3] ); }); it("excludes primitive that doesn't write depth", function() { if (!scene2.sampleHeightSupported) { return; } const rectangle = createSmallRectangle(0); const height = 100; const cartographic = new import__564.Cartographic(0, 0, height); const collection = scene2.primitives.add(new import__564.PointPrimitiveCollection()); const point = collection.add({ position: import__564.Cartographic.toCartesian(cartographic) }); expect(scene2).toSampleHeightAndCall(function(height2) { expect(height2).toEqualEpsilon(height2, import__565.Math.EPSILON3); }, cartographic); point.disableDepthTestDistance = Number.POSITIVE_INFINITY; expect(scene2).toSampleHeightAndCall(function(height2) { expect(height2).toEqualEpsilon(0, import__565.Math.EPSILON3); }, cartographic); rectangle.show = false; expect(scene2).toSampleHeightAndCall(function(height2) { expect(height2).toBeUndefined(); }, cartographic); }); it("changes width", async function() { if (!scene2.sampleHeightSupported) { return; } const cartographic = new import__564.Cartographic(0, 0); await createTileset(pointCloudTilesetUrl); expect(scene2).toSampleHeightAndCall( function(height) { expect(height).toBeUndefined(); }, cartographic, [], 0.1 ); expect(scene2).toSampleHeightAndCall( function(height) { expect(height).toBeDefined(); }, cartographic, [], 1 ); }); it("throws if position is undefined", function() { if (!scene2.sampleHeightSupported) { return; } expect(function() { scene2.sampleHeight(void 0); }).toThrowDeveloperError(); }); it("throws if scene camera is in 2D", function() { if (!scene2.sampleHeightSupported) { return; } scene2.morphTo2D(0); const cartographic = new import__564.Cartographic(0, 0); expect(function() { scene2.sampleHeight(cartographic); }).toThrowDeveloperError(); }); it("throws if scene camera is in CV", function() { if (!scene2.sampleHeightSupported) { return; } scene2.morphToColumbusView(0); const cartographic = new import__564.Cartographic(0, 0); expect(function() { scene2.sampleHeight(cartographic); }).toThrowDeveloperError(); }); it("throws if sampleHeight is not supported", function() { if (!scene2.sampleHeightSupported) { return; } const depthTexture = scene2.context._depthTexture; scene2.context._depthTexture = false; const cartographic = new import__564.Cartographic(0, 0); expect(function() { scene2.sampleHeight(cartographic); }).toThrowDeveloperError(); scene2.context._depthTexture = depthTexture; }); }); describe("clampToHeight", function() { it("clamps to tileset", async function() { if (!scene2.clampToHeightSupported) { return; } const cartesian = import__564.Cartesian3.fromRadians(0, 0, 1e5); await createTileset(batchedTilesetUrl); expect(scene2).toClampToHeightAndCall(function(position) { const minimumHeight = import__564.Cartesian3.fromRadians(0, 0).x; const maximumHeight = minimumHeight + 20; expect(position.x).toBeGreaterThan(minimumHeight); expect(position.x).toBeLessThan(maximumHeight); expect(position.y).toEqualEpsilon(0, import__565.Math.EPSILON5); expect(position.z).toEqualEpsilon(0, import__565.Math.EPSILON5); }, cartesian); }); it("clamps to the globe", async function() { if (!scene2.clampToHeightSupported) { return; } const cartesian = import__564.Cartesian3.fromRadians(0, 0, 1e5); await createGlobe2(); expect(scene2).toClampToHeightAndCall(function(position) { expect(position).toBeDefined(); }, cartesian); }); it("clamps to primitive", function() { if (!scene2.clampToHeightSupported) { return; } createSmallRectangle(0); const cartesian = import__564.Cartesian3.fromRadians(0, 0, 1e5); expect(scene2).toClampToHeightAndCall(function(cartesian2) { const expectedCartesian = import__564.Cartesian3.fromRadians(0, 0); expect(cartesian2).toEqualEpsilon( expectedCartesian, import__565.Math.EPSILON5 ); }, cartesian); }); it("clamps to top primitive", function() { if (!scene2.clampToHeightSupported) { return; } createSmallRectangle(0); createSmallRectangle(1); const cartesian = import__564.Cartesian3.fromRadians(0, 0, 1e5); expect(scene2).toClampToHeightAndCall(function(cartesian2) { const expectedCartesian = import__564.Cartesian3.fromRadians(0, 0, 1); expect(cartesian2).toEqualEpsilon( expectedCartesian, import__565.Math.EPSILON5 ); }, cartesian); }); it("returns undefined if there was nothing to clamp to", function() { if (!scene2.clampToHeightSupported) { return; } createSmallRectangle(0); const cartesian = import__564.Cartesian3.fromRadians(1, 0, 1e5); expect(scene2).toClampToHeightAndCall(function(cartesian2) { expect(cartesian2).toBeUndefined(); }, cartesian); }); it("excludes objects", function() { if (!scene2.clampToHeightSupported) { return; } createSmallRectangle(0); const rectangle2 = createSmallRectangle(1); const rectangle3 = createSmallRectangle(2); const cartesian = import__564.Cartesian3.fromRadians(0, 0, 1e5); expect(scene2).toClampToHeightAndCall( function(cartesian2) { const expectedCartesian = import__564.Cartesian3.fromRadians(0, 0); expect(cartesian2).toEqualEpsilon( expectedCartesian, import__565.Math.EPSILON5 ); }, cartesian, [rectangle2, rectangle3] ); }); it("excludes primitive that doesn't write depth", function() { if (!scene2.clampToHeightSupported) { return; } const rectangle = createSmallRectangle(0); const cartesian = import__564.Cartesian3.fromRadians(0, 0, 100); const collection = scene2.primitives.add(new import__564.PointPrimitiveCollection()); const point = collection.add({ position: cartesian }); expect(scene2).toClampToHeightAndCall(function(clampedCartesian) { expect(clampedCartesian).toEqualEpsilon( cartesian, import__565.Math.EPSILON3 ); }, cartesian); point.disableDepthTestDistance = Number.POSITIVE_INFINITY; expect(scene2).toClampToHeightAndCall(function(clampedCartesian) { expect(clampedCartesian).toEqualEpsilon( cartesian, import__565.Math.EPSILON3 ); }, cartesian); rectangle.show = false; expect(scene2).toClampToHeightAndCall(function(clampedCartesian) { expect(clampedCartesian).toBeUndefined(); }, cartesian); }); it("changes width", async function() { if (!scene2.clampToHeightSupported) { return; } const cartesian = import__564.Cartesian3.fromRadians(0, 0, 100); await createTileset(pointCloudTilesetUrl); expect(scene2).toClampToHeightAndCall( function(clampedCartesian) { expect(clampedCartesian).toBeUndefined(); }, cartesian, [], 0.1 ); expect(scene2).toClampToHeightAndCall( function(clampedCartesian) { expect(clampedCartesian).toBeDefined(); }, cartesian, [], 1 ); }); it("throws if cartesian is undefined", function() { if (!scene2.clampToHeightSupported) { return; } expect(function() { scene2.clampToHeight(void 0); }).toThrowDeveloperError(); }); it("throws if scene camera is in 2D", function() { if (!scene2.clampToHeightSupported) { return; } scene2.morphTo2D(0); const cartesian = import__564.Cartesian3.fromRadians(0, 0, 1e5); expect(function() { scene2.clampToHeight(cartesian); }).toThrowDeveloperError(); }); it("throws if scene camera is in CV", function() { if (!scene2.clampToHeightSupported) { return; } scene2.morphToColumbusView(0); const cartesian = import__564.Cartesian3.fromRadians(0, 0, 1e5); expect(function() { scene2.clampToHeight(cartesian); }).toThrowDeveloperError(); }); it("throws if clampToHeight is not supported", function() { if (!scene2.clampToHeightSupported) { return; } const depthTexture = scene2.context._depthTexture; scene2.context._depthTexture = false; const cartesian = import__564.Cartesian3.fromRadians(0, 0, 1e5); expect(function() { scene2.clampToHeight(cartesian); }).toThrowDeveloperError(); scene2.context._depthTexture = depthTexture; }); }); function pickFromRayMostDetailed(ray, objectsToExclude, width) { let result; let completed = false; scene2.pickFromRayMostDetailed(ray, objectsToExclude, width).then(function(pickResult) { result = pickResult; completed = true; }); return pollToPromise_default(function() { scene2.render(); return completed; }).then(function() { return result; }); } function drillPickFromRayMostDetailed(ray, limit, objectsToExclude, width) { let result; let completed = false; scene2.drillPickFromRayMostDetailed(ray, limit, objectsToExclude, width).then(function(pickResult) { result = pickResult; completed = true; }); return pollToPromise_default(function() { scene2.render(); return completed; }).then(function() { return result; }); } function sampleHeightMostDetailed(cartographics, objectsToExclude, width) { let result; let completed = false; scene2.sampleHeightMostDetailed(cartographics, objectsToExclude, width).then(function(pickResult) { result = pickResult; completed = true; }); return pollToPromise_default(function() { scene2.render(); return completed; }).then(function() { return result; }); } function clampToHeightMostDetailed(cartesians, objectsToExclude, width) { let result; let completed = false; scene2.clampToHeightMostDetailed(cartesians, objectsToExclude, width).then(function(pickResult) { result = pickResult; completed = true; }); return pollToPromise_default(function() { scene2.render(); return completed; }).then(function() { return result; }); } describe("pickFromRayMostDetailed", function() { it("picks a tileset", async function() { if (webglStub) { return; } scene2.camera.setView({ destination: offscreenRectangle }); const tileset = await createTileset(batchedTilesetUrl); const result = await pickFromRayMostDetailed(primitiveRay); const primitive = result.object.primitive; const position = result.position; expect(primitive).toBe(tileset); if (scene2.context.depthTexture) { const minimumHeight = import__564.Cartesian3.fromRadians(0, 0).x; const maximumHeight = minimumHeight + 20; expect(position.x).toBeGreaterThan(minimumHeight); expect(position.x).toBeLessThan(maximumHeight); expect(position.y).toEqualEpsilon(0, import__565.Math.EPSILON5); expect(position.z).toEqualEpsilon(0, import__565.Math.EPSILON5); } }); it("excludes tileset in objectsToExclude list", async function() { if (webglStub) { return; } scene2.camera.setView({ destination: offscreenRectangle }); const tileset = await createTileset(batchedTilesetUrl); const objectsToExclude = [tileset]; const result = await pickFromRayMostDetailed( primitiveRay, objectsToExclude ); expect(result).toBeUndefined(); }); it("excludes tileset whose show is false", async function() { if (webglStub) { return; } scene2.camera.setView({ destination: offscreenRectangle }); const tileset = await createTileset(batchedTilesetUrl); tileset.show = false; const result = await pickFromRayMostDetailed(primitiveRay); expect(result).toBeUndefined(); }); it("picks a primitive", async function() { if (webglStub) { return; } const rectangle = createSmallRectangle(0); scene2.camera.setView({ destination: offscreenRectangle }); const result = await pickFromRayMostDetailed(primitiveRay); const primitive = result.object.primitive; const position = result.position; expect(primitive).toBe(rectangle); if (scene2.context.depthTexture) { const expectedPosition = import__564.Cartesian3.fromRadians(0, 0); expect(position).toEqualEpsilon( expectedPosition, import__565.Math.EPSILON5 ); } }); it("returns undefined if no primitives are picked", async function() { if (webglStub) { return; } createLargeRectangle(0); scene2.camera.setView({ destination: offscreenRectangle }); const result = await pickFromRayMostDetailed(offscreenRay); expect(result).toBeUndefined(); }); it("picks the top primitive", async function() { if (webglStub) { return; } createLargeRectangle(0); const rectangle2 = createLargeRectangle(1); scene2.camera.setView({ destination: offscreenRectangle }); const result = await pickFromRayMostDetailed(primitiveRay); expect(result.object.primitive).toBe(rectangle2); }); it("excludes objects", async function() { if (webglStub) { return; } const rectangle1 = createLargeRectangle(0); const rectangle2 = createLargeRectangle(1); const rectangle3 = createLargeRectangle(2); const rectangle4 = createLargeRectangle(3); rectangle4.show = false; scene2.camera.setView({ destination: offscreenRectangle }); const result1 = await pickFromRayMostDetailed(primitiveRay, [ rectangle2, rectangle3, rectangle4 ]); expect(result1.object.primitive).toBe(rectangle1); const result2 = await pickFromRayMostDetailed(primitiveRay); expect(result2.object.primitive).toBe(rectangle3); }); it("picks primitive that doesn't write depth", async function() { if (webglStub) { return; } const collection = scene2.primitives.add(new import__564.PointPrimitiveCollection()); const point = collection.add({ position: import__564.Cartographic.fromRadians(0, 0, 100), disableDepthTestDistance: Number.POSITIVE_INFINITY }); scene2.camera.setView({ destination: offscreenRectangle }); const result = await pickFromRayMostDetailed(primitiveRay, [], 0.01); expect(result.object.primitive).toBe(point); expect(result.position).toBeUndefined(); }); it("changes width", async function() { if (webglStub) { return; } await createTileset(pointCloudTilesetUrl); const result1 = await pickFromRayMostDetailed(primitiveRay, [], 0.1); expect(result1).toBeUndefined(); const result2 = await pickFromRayMostDetailed(primitiveRay, [], 1); expect(result2).toBeDefined(); }); it("throws if ray is undefined", function() { expect(function() { scene2.pickFromRayMostDetailed(void 0); }).toThrowDeveloperError(); }); it("throws if scene camera is in 2D", function() { scene2.morphTo2D(0); expect(function() { scene2.pickFromRayMostDetailed(void 0); }).toThrowDeveloperError(); }); it("throws if scene camera is in CV", function() { scene2.morphToColumbusView(0); expect(function() { scene2.pickFromRayMostDetailed(void 0); }).toThrowDeveloperError(); }); }); describe("drillPickFromRayMostDetailed", function() { it("drill picks a primitive", async function() { if (webglStub) { return; } const rectangle = createSmallRectangle(0); scene2.camera.setView({ destination: offscreenRectangle }); const results = await drillPickFromRayMostDetailed(primitiveRay); expect(results.length).toBe(1); const primitive = results[0].object.primitive; const position = results[0].position; expect(primitive).toBe(rectangle); if (scene2.context.depthTexture) { const expectedPosition = import__564.Cartesian3.fromRadians(0, 0); expect(position).toEqualEpsilon( expectedPosition, import__565.Math.EPSILON5 ); } else { expect(position).toBeUndefined(); } }); it("drill picks multiple primitives", async function() { if (webglStub) { return; } const rectangle1 = createSmallRectangle(0); const rectangle2 = createSmallRectangle(1); scene2.camera.setView({ destination: offscreenRectangle }); const results = await drillPickFromRayMostDetailed(primitiveRay); expect(results.length).toBe(2); expect(results[0].object.primitive).toBe(rectangle2); expect(results[1].object.primitive).toBe(rectangle1); if (scene2.context.depthTexture) { const rectangleCenter1 = import__564.Cartesian3.fromRadians(0, 0, 0); const rectangleCenter2 = import__564.Cartesian3.fromRadians(0, 0, 1); expect(results[0].position).toEqualEpsilon( rectangleCenter2, import__565.Math.EPSILON5 ); expect(results[1].position).toEqualEpsilon( rectangleCenter1, import__565.Math.EPSILON5 ); } else { expect(results[0].position).toBeUndefined(); expect(results[1].position).toBeUndefined(); } }); it("does not drill pick when show is false", async function() { if (webglStub) { return; } const rectangle1 = createLargeRectangle(0); const rectangle2 = createLargeRectangle(1); rectangle2.show = false; scene2.camera.setView({ destination: offscreenRectangle }); const results = await drillPickFromRayMostDetailed(primitiveRay); expect(results.length).toEqual(1); expect(results[0].object.primitive).toEqual(rectangle1); }); it("does not drill pick when alpha is zero", async function() { if (webglStub) { return; } const rectangle1 = createLargeRectangle(0); const rectangle2 = createLargeRectangle(1); rectangle2.appearance.material.uniforms.color.alpha = 0; scene2.camera.setView({ destination: offscreenRectangle }); const results = await drillPickFromRayMostDetailed(primitiveRay); expect(results.length).toEqual(1); expect(results[0].object.primitive).toEqual(rectangle1); }); it("returns empty array if no primitives are picked", async function() { if (webglStub) { return; } createLargeRectangle(0); createLargeRectangle(1); scene2.camera.setView({ destination: offscreenRectangle }); const results = await drillPickFromRayMostDetailed(offscreenRay); expect(results.length).toEqual(0); }); it("can drill pick batched Primitives with show attribute", async function() { if (webglStub) { return; } const geometry = new import__564.RectangleGeometry({ rectangle: import__564.Rectangle.fromDegrees(-50, -50, 50, 50), granularity: import__565.Math.toRadians(20), vertexFormat: import__564.EllipsoidSurfaceAppearance.VERTEX_FORMAT, height: 0 }); const geometryWithHeight = new import__564.RectangleGeometry({ rectangle: import__564.Rectangle.fromDegrees(-50, -50, 50, 50), granularity: import__565.Math.toRadians(20), vertexFormat: import__564.EllipsoidSurfaceAppearance.VERTEX_FORMAT, height: 1 }); const instance1 = new import__564.GeometryInstance({ id: 1, geometry, attributes: { show: new import__564.ShowGeometryInstanceAttribute(true) } }); const instance2 = new import__564.GeometryInstance({ id: 2, geometry, attributes: { show: new import__564.ShowGeometryInstanceAttribute(false) } }); const instance3 = new import__564.GeometryInstance({ id: 3, geometry: geometryWithHeight, attributes: { show: new import__564.ShowGeometryInstanceAttribute(true) } }); const primitive = primitives.add( new import__564.Primitive({ geometryInstances: [instance1, instance2, instance3], asynchronous: false, appearance: new import__564.EllipsoidSurfaceAppearance() }) ); scene2.camera.setView({ destination: offscreenRectangle }); const results = await drillPickFromRayMostDetailed(primitiveRay); expect(results.length).toEqual(2); expect(results[0].object.primitive).toEqual(primitive); expect(results[0].object.id).toEqual(3); expect(results[1].object.primitive).toEqual(primitive); expect(results[1].object.id).toEqual(1); }); it("can drill pick without ID", async function() { if (webglStub) { return; } const geometry = new import__564.RectangleGeometry({ rectangle: import__564.Rectangle.fromDegrees(-50, -50, 50, 50), granularity: import__565.Math.toRadians(20), vertexFormat: import__564.EllipsoidSurfaceAppearance.VERTEX_FORMAT }); const instance1 = new import__564.GeometryInstance({ geometry, attributes: { show: new import__564.ShowGeometryInstanceAttribute(true) } }); const instance2 = new import__564.GeometryInstance({ geometry, attributes: { show: new import__564.ShowGeometryInstanceAttribute(true) } }); const primitive = primitives.add( new import__564.Primitive({ geometryInstances: [instance1, instance2], asynchronous: false, appearance: new import__564.EllipsoidSurfaceAppearance() }) ); scene2.camera.setView({ destination: offscreenRectangle }); const results = await drillPickFromRayMostDetailed(primitiveRay); expect(results.length).toEqual(1); expect(results[0].object.primitive).toEqual(primitive); }); it("can drill pick batched Primitives without show attribute", async function() { if (webglStub) { return; } const geometry = new import__564.RectangleGeometry({ rectangle: import__564.Rectangle.fromDegrees(-50, -50, 50, 50), granularity: import__565.Math.toRadians(20), vertexFormat: import__564.EllipsoidSurfaceAppearance.VERTEX_FORMAT, height: 0 }); const geometryWithHeight = new import__564.RectangleGeometry({ rectangle: import__564.Rectangle.fromDegrees(-50, -50, 50, 50), granularity: import__565.Math.toRadians(20), vertexFormat: import__564.EllipsoidSurfaceAppearance.VERTEX_FORMAT, height: 1 }); const instance1 = new import__564.GeometryInstance({ id: 1, geometry }); const instance2 = new import__564.GeometryInstance({ id: 2, geometry }); const instance3 = new import__564.GeometryInstance({ id: 3, geometry: geometryWithHeight }); const primitive = primitives.add( new import__564.Primitive({ geometryInstances: [instance1, instance2, instance3], asynchronous: false, appearance: new import__564.EllipsoidSurfaceAppearance() }) ); scene2.camera.setView({ destination: offscreenRectangle }); const results = await drillPickFromRayMostDetailed(primitiveRay); expect(results.length).toEqual(1); expect(results[0].object.primitive).toEqual(primitive); expect(results[0].object.id).toEqual(3); }); it("stops drill picking when the limit is reached.", async function() { if (webglStub) { return; } createLargeRectangle(0); const rectangle2 = createLargeRectangle(1); const rectangle3 = createLargeRectangle(2); const rectangle4 = createLargeRectangle(3); scene2.camera.setView({ destination: offscreenRectangle }); const results = await drillPickFromRayMostDetailed(primitiveRay, 3); expect(results.length).toEqual(3); expect(results[0].object.primitive).toEqual(rectangle4); expect(results[1].object.primitive).toEqual(rectangle3); expect(results[2].object.primitive).toEqual(rectangle2); }); it("excludes objects", async function() { if (webglStub) { return; } createLargeRectangle(0); const rectangle2 = createLargeRectangle(1); const rectangle3 = createLargeRectangle(2); const rectangle4 = createLargeRectangle(3); const rectangle5 = createLargeRectangle(4); scene2.camera.setView({ destination: offscreenRectangle }); const results = await drillPickFromRayMostDetailed(primitiveRay, 2, [ rectangle5, rectangle3 ]); expect(results.length).toBe(2); expect(results[0].object.primitive).toBe(rectangle4); expect(results[1].object.primitive).toBe(rectangle2); }); it("changes width", async function() { if (webglStub) { return; } await createTileset(pointCloudTilesetUrl); const result1 = await drillPickFromRayMostDetailed( primitiveRay, 1, [], 0.1 ); expect(result1.length).toBe(0); const result2 = await drillPickFromRayMostDetailed( primitiveRay, 1, [], 1 ); expect(result2.length).toBe(1); }); it("throws if ray is undefined", function() { expect(function() { scene2.drillPickFromRayMostDetailed(void 0); }).toThrowDeveloperError(); }); it("throws if scene camera is in 2D", function() { scene2.morphTo2D(0); expect(function() { scene2.drillPickFromRayMostDetailed(primitiveRay); }).toThrowDeveloperError(); }); it("throws if scene camera is in CV", function() { scene2.morphToColumbusView(0); expect(function() { scene2.drillPickFromRayMostDetailed(primitiveRay); }).toThrowDeveloperError(); }); }); describe("sampleHeightMostDetailed", function() { it("samples height from tileset", async function() { if (!scene2.sampleHeightSupported) { return; } const cartographics = [new import__564.Cartographic(0, 0)]; await createTileset(batchedTilesetUrl); const updatedCartographics = await sampleHeightMostDetailed( cartographics ); const height = updatedCartographics[0].height; expect(height).toBeGreaterThan(0); expect(height).toBeLessThan(20); }); it("samples height from the globe", async function() { if (!scene2.sampleHeightSupported) { return; } const cartographics = [ new import__564.Cartographic(0, 0), new import__564.Cartographic(1e-4, 1e-4), new import__564.Cartographic(2e-4, 2e-4) ]; const clonedCartographics = [ new import__564.Cartographic(0, 0), new import__564.Cartographic(1e-4, 1e-4), new import__564.Cartographic(2e-4, 2e-4) ]; await createGlobe2(); const updatedCartographics = await sampleHeightMostDetailed( cartographics ); expect(updatedCartographics).toBe(cartographics); expect(updatedCartographics.length).toBe(3); let previousHeight; for (let i = 0; i < 3; ++i) { const longitude = updatedCartographics[i].longitude; const latitude = updatedCartographics[i].latitude; const height = updatedCartographics[i].height; expect(longitude).toBe(clonedCartographics[i].longitude); expect(latitude).toBe(clonedCartographics[i].latitude); expect(height).toBeDefined(); expect(height).not.toBe(previousHeight); previousHeight = height; } }); it("does not sample offscreen globe tiles", async function() { if (!scene2.sampleHeightSupported) { return; } const cartographics = [new import__564.Cartographic(0, 0)]; scene2.camera.setView({ destination: offscreenRectangle }); await createGlobe2(); const updatedCartographics = await sampleHeightMostDetailed( cartographics ); expect(updatedCartographics[0].height).toBeUndefined(); }); it("samples height from multiple primitives", async function() { if (!scene2.sampleHeightSupported) { return; } createRectangle(0, smallRectangle); createRectangle(0, offscreenRectangle); const cartographics = [ import__564.Rectangle.center(smallRectangle), import__564.Rectangle.center(offscreenRectangle), new import__564.Cartographic(-2, -2) ]; scene2.camera.setView({ destination: offscreenRectangle }); const updatedCartographics = await sampleHeightMostDetailed( cartographics ); expect(updatedCartographics[0].height).toBeDefined(); expect(updatedCartographics[1].height).toBeDefined(); expect(updatedCartographics[2].height).toBeUndefined(); }); it("samples multiple heights from primitive", async function() { if (!scene2.sampleHeightSupported) { return; } createSmallRectangle(0); const cartographics = [ new import__564.Cartographic(0, 0), new import__564.Cartographic(-1e-6, -1e-6), new import__564.Cartographic(5e-7, 5e-7) ]; scene2.camera.setView({ destination: offscreenRectangle }); const updatedCartographics = await sampleHeightMostDetailed( cartographics ); let previousHeight; for (let i = 0; i < 3; ++i) { const height = updatedCartographics[i].height; expect(height).toEqualEpsilon(0, import__565.Math.EPSILON3); expect(height).not.toBe(previousHeight); previousHeight = height; } }); it("samples height from the top primitive", async function() { if (!scene2.sampleHeightSupported) { return; } createSmallRectangle(0); createSmallRectangle(1); const cartographics = [new import__564.Cartographic(0, 0)]; scene2.camera.setView({ destination: offscreenRectangle }); const updatedCartographics = await sampleHeightMostDetailed( cartographics ); expect(updatedCartographics[0].height).toEqualEpsilon( 1, import__565.Math.EPSILON3 ); }); it("excludes objects", async function() { if (!scene2.sampleHeightSupported) { return; } const rectangle1 = createRectangle(0, smallRectangle); createRectangle(0, offscreenRectangle); const rectangle3 = createRectangle(1, offscreenRectangle); const cartographics = [ import__564.Rectangle.center(smallRectangle), import__564.Rectangle.center(offscreenRectangle), new import__564.Cartographic(-2, -2) ]; scene2.camera.setView({ destination: offscreenRectangle }); const updatedCartographics = await sampleHeightMostDetailed( cartographics, [rectangle1, rectangle3] ); expect(updatedCartographics[0].height).toBeUndefined(); expect(updatedCartographics[1].height).toEqualEpsilon( 0, import__565.Math.EPSILON2 ); expect(updatedCartographics[2].height).toBeUndefined(); }); it("excludes primitive that doesn't write depth", async function() { if (!scene2.sampleHeightSupported) { return; } const rectangle = createSmallRectangle(0); const height = 100; const cartographics = [new import__564.Cartographic(0, 0, height)]; const collection = scene2.primitives.add(new import__564.PointPrimitiveCollection()); const point = collection.add({ position: import__564.Cartographic.toCartesian(cartographics[0]) }); scene2.camera.setView({ destination: offscreenRectangle }); let updatedCartographics = await sampleHeightMostDetailed( cartographics ); expect(updatedCartographics[0].height).toEqualEpsilon( height, import__565.Math.EPSILON3 ); point.disableDepthTestDistance = Number.POSITIVE_INFINITY; updatedCartographics = await sampleHeightMostDetailed(cartographics); expect(updatedCartographics[0].height).toEqualEpsilon( 0, import__565.Math.EPSILON3 ); rectangle.show = false; updatedCartographics = await sampleHeightMostDetailed(cartographics); expect(updatedCartographics[0].height).toBeUndefined(); }); it("changes width", async function() { if (!scene2.sampleHeightSupported) { return; } const cartographics1 = [new import__564.Cartographic(0, 0)]; const cartographics2 = [new import__564.Cartographic(0, 0)]; await createTileset(pointCloudTilesetUrl); const updatedCartographics1 = await sampleHeightMostDetailed( cartographics1, [], 0.1 ); expect(updatedCartographics1[0].height).toBeUndefined(); const updatedCartographics2 = await sampleHeightMostDetailed( cartographics2, [], 1 ); expect(updatedCartographics2[0].height).toBeDefined(); }); it("handles empty array", async function() { if (!scene2.sampleHeightSupported) { return; } const cartographics = []; const updatedCartographics = await sampleHeightMostDetailed( cartographics ); expect(updatedCartographics.length).toBe(0); }); it("throws if positions is undefined", function() { if (!scene2.sampleHeightSupported) { return; } expect(function() { scene2.sampleHeightMostDetailed(void 0); }).toThrowDeveloperError(); }); it("throws if scene camera is in 2D", function() { if (!scene2.sampleHeightSupported) { return; } scene2.morphTo2D(0); const cartographics = [new import__564.Cartographic(0, 0)]; expect(function() { scene2.sampleHeightMostDetailed(cartographics); }).toThrowDeveloperError(); }); it("throws if scene camera is in CV", function() { if (!scene2.sampleHeightSupported) { return; } scene2.morphToColumbusView(0); const cartographics = [new import__564.Cartographic(0, 0)]; expect(function() { scene2.sampleHeightMostDetailed(cartographics); }).toThrowDeveloperError(); }); it("throws if sampleHeight is not supported", function() { if (!scene2.sampleHeightSupported) { return; } const depthTexture = scene2.context._depthTexture; scene2.context._depthTexture = false; const cartographics = [new import__564.Cartographic(0, 0)]; expect(function() { scene2.sampleHeightMostDetailed(cartographics); }).toThrowDeveloperError(); scene2.context._depthTexture = depthTexture; }); }); describe("clampToHeightMostDetailed", function() { it("clamps to tileset", async function() { if (!scene2.clampToHeightSupported) { return; } const cartesians = [import__564.Cartesian3.fromRadians(0, 0, 1e5)]; await createTileset(batchedTilesetUrl); const updatedCartesians = await clampToHeightMostDetailed(cartesians); const minimumHeight = import__564.Cartesian3.fromRadians(0, 0).x; const maximumHeight = minimumHeight + 20; const position = updatedCartesians[0]; expect(position.x).toBeGreaterThan(minimumHeight); expect(position.x).toBeLessThan(maximumHeight); expect(position.y).toEqualEpsilon(0, import__565.Math.EPSILON5); expect(position.z).toEqualEpsilon(0, import__565.Math.EPSILON5); }); it("clamps to the globe", async function() { if (!scene2.clampToHeightSupported) { return; } const cartesians = [ import__564.Cartesian3.fromRadians(0, 0, 1e5), import__564.Cartesian3.fromRadians(1e-4, 1e-4, 1e5), import__564.Cartesian3.fromRadians(2e-4, 2e-4, 1e5) ]; const clonedCartesians = [ import__564.Cartesian3.fromRadians(0, 0, 1e5), import__564.Cartesian3.fromRadians(1e-4, 1e-4, 1e5), import__564.Cartesian3.fromRadians(2e-4, 2e-4, 1e5) ]; await createGlobe2(); const updatedCartesians = await clampToHeightMostDetailed(cartesians); expect(updatedCartesians).toBe(cartesians); expect(updatedCartesians.length).toBe(3); let previousCartesian; for (let i = 0; i < 3; ++i) { expect(updatedCartesians[i]).not.toEqual(clonedCartesians[i]); expect(updatedCartesians[i]).not.toEqual(previousCartesian); previousCartesian = updatedCartesians[i]; } }); it("does not clamp to offscreen globe tiles", async function() { if (!scene2.clampToHeightSupported) { return; } const cartesians = [import__564.Cartesian3.fromRadians(0, 0, 1e5)]; scene2.camera.setView({ destination: offscreenRectangle }); await createGlobe2(); const updatedCartesians = await clampToHeightMostDetailed(cartesians); expect(updatedCartesians[0]).toBeUndefined(); }); it("clamps to multiple primitives", async function() { if (!scene2.clampToHeightSupported) { return; } createRectangle(0, smallRectangle); createRectangle(0, offscreenRectangle); const cartesians = [ import__564.Cartographic.toCartesian(import__564.Rectangle.center(smallRectangle)), import__564.Cartographic.toCartesian(import__564.Rectangle.center(offscreenRectangle)), import__564.Cartesian3.fromRadians(-2, -2) ]; scene2.camera.setView({ destination: offscreenRectangle }); const updatedCartesians = await clampToHeightMostDetailed(cartesians); expect(updatedCartesians[0]).toBeDefined(); expect(updatedCartesians[1]).toBeDefined(); expect(updatedCartesians[2]).toBeUndefined(); }); it("clamps to primitive", async function() { if (!scene2.clampToHeightSupported) { return; } createSmallRectangle(0); const cartesians = [ import__564.Cartesian3.fromRadians(0, 0, 1e5), import__564.Cartesian3.fromRadians(-1e-6, -1e-6, 1e5), import__564.Cartesian3.fromRadians(5e-7, 5e-7, 1e5) ]; const expectedCartesians = [ import__564.Cartesian3.fromRadians(0, 0, 0), import__564.Cartesian3.fromRadians(-1e-6, -1e-6, 0), import__564.Cartesian3.fromRadians(5e-7, 5e-7, 0) ]; scene2.camera.setView({ destination: offscreenRectangle }); const updatedCartesians = await clampToHeightMostDetailed(cartesians); let previousCartesian; for (let i = 0; i < 3; ++i) { expect(updatedCartesians[i]).toEqualEpsilon( expectedCartesians[i], import__565.Math.EPSILON5 ); expect(updatedCartesians[i]).not.toEqual(previousCartesian); previousCartesian = updatedCartesians[i]; } }); it("clamps to top primitive", async function() { if (!scene2.clampToHeightSupported) { return; } createSmallRectangle(0); createSmallRectangle(1); const cartesians = [import__564.Cartesian3.fromRadians(0, 0)]; scene2.camera.setView({ destination: offscreenRectangle }); const updatedCartesians = await clampToHeightMostDetailed(cartesians); const expectedCartesian = import__564.Cartesian3.fromRadians(0, 0, 1); expect(updatedCartesians[0]).toEqualEpsilon( expectedCartesian, import__565.Math.EPSILON5 ); }); it("excludes objects", async function() { if (!scene2.clampToHeightSupported) { return; } const rectangle1 = createRectangle(0, smallRectangle); createRectangle(0, offscreenRectangle); const rectangle3 = createRectangle(1, offscreenRectangle); const cartesians = [ import__564.Cartographic.toCartesian(import__564.Rectangle.center(smallRectangle)), import__564.Cartographic.toCartesian(import__564.Rectangle.center(offscreenRectangle)), import__564.Cartesian3.fromRadians(-2, -2) ]; scene2.camera.setView({ destination: offscreenRectangle }); const updatedCartesians = await clampToHeightMostDetailed(cartesians, [ rectangle1, rectangle3 ]); const expectedCartesian = import__564.Cartographic.toCartesian( import__564.Rectangle.center(offscreenRectangle) ); expect(updatedCartesians[0]).toBeUndefined(); expect(updatedCartesians[1]).toEqualEpsilon( expectedCartesian, import__565.Math.EPSILON2 ); expect(updatedCartesians[2]).toBeUndefined(); }); it("excludes primitive that doesn't write depth", async function() { if (!scene2.clampToHeightSupported) { return; } const rectangle = createSmallRectangle(0); const height = 100; const cartesian = import__564.Cartesian3.fromRadians(0, 0, height); const cartesians1 = [import__564.Cartesian3.clone(cartesian)]; const cartesians2 = [import__564.Cartesian3.clone(cartesian)]; const cartesians3 = [import__564.Cartesian3.clone(cartesian)]; const collection = scene2.primitives.add(new import__564.PointPrimitiveCollection()); const point = collection.add({ position: cartesian }); scene2.camera.setView({ destination: offscreenRectangle }); let updatedCartesians = await clampToHeightMostDetailed(cartesians1); expect(updatedCartesians[0]).toEqualEpsilon( cartesian, import__565.Math.EPSILON3 ); point.disableDepthTestDistance = Number.POSITIVE_INFINITY; updatedCartesians = await clampToHeightMostDetailed(cartesians2); expect(updatedCartesians[0]).toEqualEpsilon( cartesian, import__565.Math.EPSILON3 ); rectangle.show = false; updatedCartesians = await clampToHeightMostDetailed(cartesians3); expect(updatedCartesians[0]).toBeUndefined(); }); it("changes width", async function() { if (!scene2.clampToHeightSupported) { return; } const cartesian = import__564.Cartesian3.fromRadians(0, 0, 100); const cartesians1 = [import__564.Cartesian3.clone(cartesian)]; const cartesians2 = [import__564.Cartesian3.clone(cartesian)]; await createTileset(pointCloudTilesetUrl); const clampedCartesians1 = await clampToHeightMostDetailed( cartesians1, [], 0.1 ); expect(clampedCartesians1[0]).toBeUndefined(); const clampedCartesians2 = await clampToHeightMostDetailed( cartesians2, [], 1 ); expect(clampedCartesians2[0]).toBeDefined(); }); it("handles empty array", async function() { if (!scene2.clampToHeightSupported) { return; } const cartesians = []; const updatedCartesians = await clampToHeightMostDetailed(cartesians); expect(updatedCartesians.length).toBe(0); }); it("throws if cartesians is undefined", function() { if (!scene2.clampToHeightSupported) { return; } expect(function() { scene2.clampToHeightMostDetailed(void 0); }).toThrowDeveloperError(); }); it("throws if scene camera is in 2D", function() { if (!scene2.clampToHeightSupported) { return; } scene2.morphTo2D(0); const cartesians = [import__564.Cartesian3.fromRadians(0, 0)]; expect(function() { scene2.clampToHeightMostDetailed(cartesians); }).toThrowDeveloperError(); }); it("throws if scene camera is in CV", function() { if (!scene2.clampToHeightSupported) { return; } scene2.morphToColumbusView(0); const cartesians = [import__564.Cartesian3.fromRadians(0, 0)]; expect(function() { scene2.clampToHeightMostDetailed(cartesians); }).toThrowDeveloperError(); }); it("throws if clampToHeight is not supported", function() { if (!scene2.clampToHeightSupported) { return; } const depthTexture = scene2.context._depthTexture; scene2.context._depthTexture = false; const cartesians = [import__564.Cartesian3.fromRadians(0, 0)]; expect(function() { scene2.clampToHeightMostDetailed(cartesians); }).toThrowDeveloperError(); scene2.context._depthTexture = depthTexture; }); }); it("calls multiple picking functions within the same frame", async function() { if (!scene2.clampToHeightSupported || !scene2.pickPositionSupported) { return; } createSmallRectangle(0); const offscreenRectanglePrimitive = createRectangle( 0, offscreenRectangle ); offscreenRectanglePrimitive.appearance.material.uniforms.color = new import__564.Color( 1, 0, 0, 1 ); scene2.camera.setView({ destination: offscreenRectangle }); scene2.renderForSpecs(); const cartographic = import__564.Cartographic.fromRadians(0, 0, 1e5); const cartesian = import__564.Cartographic.toCartesian(cartographic); const cartesians = [import__564.Cartesian3.clone(cartesian)]; const cartographics = [cartographic]; expect(scene2).toClampToHeightAndCall(function(cartesian2) { const expectedCartesian = import__564.Cartesian3.fromRadians(0, 0); expect(cartesian2).toEqualEpsilon( expectedCartesian, import__565.Math.EPSILON5 ); }, cartesian); expect(scene2).toPickPositionAndCall(function(cartesian2) { const expectedCartesian = import__564.Cartographic.toCartesian( import__564.Rectangle.center(offscreenRectangle) ); expect(cartesian2).toEqualEpsilon( expectedCartesian, import__565.Math.EPSILON5 ); }); expect(scene2).toClampToHeightAndCall(function(cartesian2) { const expectedCartesian = import__564.Cartesian3.fromRadians(0, 0); expect(cartesian2).toEqualEpsilon( expectedCartesian, import__565.Math.EPSILON5 ); }, cartesian); expect(scene2).toPickPrimitive(offscreenRectanglePrimitive); expect(scene2).toClampToHeightAndCall(function(cartesian2) { const expectedCartesian = import__564.Cartesian3.fromRadians(0, 0); expect(cartesian2).toEqualEpsilon( expectedCartesian, import__565.Math.EPSILON5 ); }, cartesian); offscreenRectanglePrimitive.appearance.material.uniforms.color = new import__564.Color( 1, 0, 0, 0.5 ); scene2.renderForSpecs(); expect(scene2).toPickPositionAndCall(function(cartesian2) { expect(cartesian2).toBeUndefined(); }); expect(scene2).toClampToHeightAndCall(function(cartesian2) { const expectedCartesian = import__564.Cartesian3.fromRadians(0, 0); expect(cartesian2).toEqualEpsilon( expectedCartesian, import__565.Math.EPSILON5 ); }, cartesian); scene2.pickTranslucentDepth = true; scene2.renderForSpecs(); expect(scene2).toPickPositionAndCall(function(cartesian2) { const expectedCartesian = import__564.Cartographic.toCartesian( import__564.Rectangle.center(offscreenRectangle) ); expect(cartesian2).toEqualEpsilon( expectedCartesian, import__565.Math.EPSILON5 ); }); const results = []; let completed = 0; scene2.clampToHeightMostDetailed(cartesians).then(function(updatedCartesians) { results.push(updatedCartesians); completed++; }); scene2.sampleHeightMostDetailed(cartographics).then(function(updatedCartographics) { results.push(updatedCartographics); completed++; }); expect(scene2).toClampToHeightAndCall(function(cartesian2) { const expectedCartesian = import__564.Cartesian3.fromRadians(0, 0); expect(cartesian2).toEqualEpsilon( expectedCartesian, import__565.Math.EPSILON5 ); }, cartesian); return pollToPromise_default(function() { scene2.render(); return completed === 2; }).then(function() { expect(results[0][0]).toBeDefined(); expect(results[1][0].height).toBeDefined(); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/PntsParserSpec.js var import__566 = __toESM(require_Cesium(), 1); describe("Scene/PntsParser", function() { it("throws without arrayBuffer", function() { expect(function() { return import__566.PntsParser.parse(); }).toThrowDeveloperError(); }); it("throws with invalid version", function() { const arrayBuffer = Cesium3DTilesTester_default.generatePointCloudTileBuffer({ version: 2 }); expect(function() { return import__566.PntsParser.parse(arrayBuffer); }).toThrowError(import__566.RuntimeError); }); it("throws if featureTableJsonByteLength is 0", function() { const arrayBuffer = Cesium3DTilesTester_default.generatePointCloudTileBuffer({ featureTableJsonByteLength: 0 }); expect(function() { return import__566.PntsParser.parse(arrayBuffer); }).toThrowError(import__566.RuntimeError); }); it("throws if the feature table does not contain POINTS_LENGTH", function() { const arrayBuffer = Cesium3DTilesTester_default.generatePointCloudTileBuffer({ featureTableJson: { POSITION: { byteOffset: 0 } } }); expect(function() { return import__566.PntsParser.parse(arrayBuffer); }).toThrowError(import__566.RuntimeError); }); it("throws if the feature table does not contain POSITION or POSITION_QUANTIZED", function() { const arrayBuffer = Cesium3DTilesTester_default.generatePointCloudTileBuffer({ featureTableJson: { POINTS_LENGTH: 1 } }); expect(function() { return import__566.PntsParser.parse(arrayBuffer); }).toThrowError(import__566.RuntimeError); }); it("throws if the positions are quantized and the feature table does not contain QUANTIZED_VOLUME_SCALE", function() { const arrayBuffer = Cesium3DTilesTester_default.generatePointCloudTileBuffer({ featureTableJson: { POINTS_LENGTH: 1, POSITION_QUANTIZED: { byteOffset: 0 }, QUANTIZED_VOLUME_OFFSET: [0, 0, 0] } }); expect(function() { return import__566.PntsParser.parse(arrayBuffer); }).toThrowError(import__566.RuntimeError); }); it("throws if the positions are quantized and the feature table does not contain QUANTIZED_VOLUME_OFFSET", function() { const arrayBuffer = Cesium3DTilesTester_default.generatePointCloudTileBuffer({ featureTableJson: { POINTS_LENGTH: 1, POSITION_QUANTIZED: { byteOffset: 0 }, QUANTIZED_VOLUME_SCALE: [1, 1, 1] } }); expect(function() { return import__566.PntsParser.parse(arrayBuffer); }).toThrowError(import__566.RuntimeError); }); it("throws if the BATCH_ID semantic is defined but BATCH_LENGTH is not", function() { const arrayBuffer = Cesium3DTilesTester_default.generatePointCloudTileBuffer({ featureTableJson: { POINTS_LENGTH: 2, POSITION: [0, 0, 0, 1, 1, 1], BATCH_ID: [0, 1] } }); expect(function() { return import__566.PntsParser.parse(arrayBuffer); }).toThrowError(import__566.RuntimeError); }); }); // packages/engine/Specs/Scene/PointCloudEyeDomeLightingSpec.js var import__567 = __toESM(require_Cesium(), 1); var import__568 = __toESM(require_Cesium(), 1); describe( "Scene/PointCloudEyeDomeLighting", function() { let scene2; const centerLongitude = -1.31968; const centerLatitude = 0.698874; const pointCloudNoColorUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudNoColor/tileset.json"; function setCamera(longitude, latitude) { const center = import__567.Cartesian3.fromRadians(longitude, latitude, 5); scene2.camera.lookAt(center, new import__567.HeadingPitchRange(0, -1.57, 5)); } beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { const camera = scene2.camera; camera.frustum = new import__567.PerspectiveFrustum(); camera.frustum.aspectRatio = scene2.drawingBufferWidth / scene2.drawingBufferHeight; camera.frustum.fov = import__568.Math.toRadians(60); setCamera(centerLongitude, centerLatitude); }); afterEach(function() { scene2.primitives.removeAll(); }); it("adds a clear command and a post-processing draw call", function() { if (!import__567.PointCloudEyeDomeLighting.isSupported(scene2.frameState.context)) { return; } return Cesium3DTilesTester_default.loadTileset(scene2, pointCloudNoColorUrl).then( function(tileset) { tileset.pointCloudShading.eyeDomeLighting = true; scene2.renderForSpecs(); const originalLength = scene2.frameState.commandList.length; tileset.pointCloudShading.attenuation = true; scene2.renderForSpecs(); const newLength = scene2.frameState.commandList.length; expect(newLength).toEqual(originalLength + 2); } ); }); it("does not change commands for pick calls", function() { if (!import__567.PointCloudEyeDomeLighting.isSupported(scene2.frameState.context)) { return; } return Cesium3DTilesTester_default.loadTileset(scene2, pointCloudNoColorUrl).then( function(tileset) { tileset.pointCloudShading.eyeDomeLighting = true; scene2.pickForSpecs(); const originalLength = scene2.frameState.commandList.length; tileset.pointCloudShading.attenuation = true; scene2.pickForSpecs(); const newLength = scene2.frameState.commandList.length; expect(newLength).toEqual(originalLength); } ); }); it("works when point cloud shader changes", function() { if (!import__567.PointCloudEyeDomeLighting.isSupported(scene2.frameState.context)) { return; } return Cesium3DTilesTester_default.loadTileset(scene2, pointCloudNoColorUrl).then( function(tileset) { tileset.pointCloudShading.attenuation = true; tileset.pointCloudShading.eyeDomeLighting = true; scene2.renderForSpecs(); tileset.pointCloudShading.eyeDomeLighting = false; scene2.renderForSpecs(); tileset.style = new import__567.Cesium3DTileStyle({ color: "color('red')" }); scene2.renderForSpecs(); scene2.context.shaderCache.destroyReleasedShaderPrograms(); tileset.pointCloudShading.eyeDomeLighting = true; scene2.renderForSpecs(); expect(scene2.frameState.commandList.length).toBe(3); } ); }); }, "WebGL" ); // packages/engine/Specs/Scene/PointCloudShadingSpec.js var import__569 = __toESM(require_Cesium(), 1); describe("Scene/PointCloudShading", function() { it("creates expected instance from raw assignment and construction", function() { let pointCloudShading = new import__569.PointCloudShading(); expect(pointCloudShading.attenuation).toEqual(false); expect(pointCloudShading.geometricErrorScale).toEqual(1); expect(pointCloudShading.maximumAttenuation).not.toBeDefined(); expect(pointCloudShading.baseResolution).not.toBeDefined(); expect(pointCloudShading.eyeDomeLighting).toEqual(true); expect(pointCloudShading.eyeDomeLightingStrength).toEqual(1); expect(pointCloudShading.eyeDomeLightingRadius).toEqual(1); expect(pointCloudShading.backFaceCulling).toEqual(false); expect(pointCloudShading.normalShading).toEqual(true); const options = { geometricErrorScale: 2, maximumAttenuation: 16, baseResolution: 0.1, eyeDomeLightingStrength: 0.1, eyeDomeLightingRadius: 2, backFaceCulling: true, normalShading: false }; pointCloudShading = new import__569.PointCloudShading(options); expect(pointCloudShading.attenuation).toEqual(false); expect(pointCloudShading.geometricErrorScale).toEqual( options.geometricErrorScale ); expect(pointCloudShading.maximumAttenuation).toEqual( options.maximumAttenuation ); expect(pointCloudShading.baseResolution).toEqual(options.baseResolution); expect(pointCloudShading.eyeDomeLighting).toEqual(true); expect(pointCloudShading.eyeDomeLightingStrength).toEqual( options.eyeDomeLightingStrength ); expect(pointCloudShading.eyeDomeLightingRadius).toEqual( options.eyeDomeLightingRadius ); expect(pointCloudShading.backFaceCulling).toEqual(options.backFaceCulling); expect(pointCloudShading.normalShading).toEqual(options.normalShading); }); it("provides a method for checking if point cloud shading is supported", function() { const scene2 = createScene_default(); const context = scene2.context; const expectedSupport = context.floatingPointTexture && context.drawBuffers && context.fragmentDepth; expect(import__569.PointCloudShading.isSupported(scene2)).toEqual(expectedSupport); scene2.destroyForSpecs(); }); }); // packages/engine/Specs/Scene/PointPrimitiveCollectionSpec.js var import__570 = __toESM(require_Cesium(), 1); var import__571 = __toESM(require_Cesium(), 1); describe( "Scene/PointPrimitiveCollection", function() { let scene2; let camera; let pointPrimitives; beforeAll(function() { scene2 = createScene_default(); camera = scene2.camera; }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { scene2.morphTo3D(0); camera.position = new import__570.Cartesian3(10, 0, 0); camera.direction = import__570.Cartesian3.negate(import__570.Cartesian3.UNIT_X, new import__570.Cartesian3()); camera.up = import__570.Cartesian3.clone(import__570.Cartesian3.UNIT_Z); pointPrimitives = new import__570.PointPrimitiveCollection(); scene2.primitives.add(pointPrimitives); }); afterEach(function() { scene2.primitives.removeAll(); }); it("constructs a default pointPrimitive", function() { const p = pointPrimitives.add(); expect(p.show).toEqual(true); expect(p.position).toEqual(import__570.Cartesian3.ZERO); expect(p.pixelSize).toEqual(10); expect(p.color.red).toEqual(1); expect(p.color.green).toEqual(1); expect(p.color.blue).toEqual(1); expect(p.color.alpha).toEqual(1); expect(p.outlineColor.red).toEqual(0); expect(p.outlineColor.green).toEqual(0); expect(p.outlineColor.blue).toEqual(0); expect(p.outlineColor.alpha).toEqual(0); expect(p.outlineWidth).toEqual(0); expect(p.scaleByDistance).not.toBeDefined(); expect(p.translucencyByDistance).not.toBeDefined(); expect(p.distanceDisplayCondition).not.toBeDefined(); expect(p.disableDepthTestDistance).toEqual(0); expect(p.id).not.toBeDefined(); }); it("can add and remove before first render.", function() { const p = pointPrimitives.add(); pointPrimitives.remove(p); scene2.renderForSpecs(); }); it("explicitly constructs a pointPrimitive", function() { const p = pointPrimitives.add({ show: false, position: new import__570.Cartesian3(1, 2, 3), pixelSize: 2, color: { red: 0.1, green: 0.2, blue: 0.3, alpha: 0.4 }, outlineColor: { red: 0.5, green: 0.6, blue: 0.7, alpha: 0.8 }, outlineWidth: 4, scaleByDistance: new import__570.NearFarScalar(1, 3, 1e6, 0), translucencyByDistance: new import__570.NearFarScalar(1, 1, 1e6, 0), distanceDisplayCondition: new import__570.DistanceDisplayCondition(10, 100), disableDepthTestDistance: 10, id: "id" }); expect(p.show).toEqual(false); expect(p.position).toEqual(new import__570.Cartesian3(1, 2, 3)); expect(p.pixelSize).toEqual(2); expect(p.color.red).toEqual(0.1); expect(p.color.green).toEqual(0.2); expect(p.color.blue).toEqual(0.3); expect(p.color.alpha).toEqual(0.4); expect(p.outlineColor.red).toEqual(0.5); expect(p.outlineColor.green).toEqual(0.6); expect(p.outlineColor.blue).toEqual(0.7); expect(p.outlineColor.alpha).toEqual(0.8); expect(p.outlineWidth).toEqual(4); expect(p.scaleByDistance).toEqual( new import__570.NearFarScalar(1, 3, 1e6, 0) ); expect(p.translucencyByDistance).toEqual( new import__570.NearFarScalar(1, 1, 1e6, 0) ); expect(p.distanceDisplayCondition).toEqual( new import__570.DistanceDisplayCondition(10, 100) ); expect(p.disableDepthTestDistance).toEqual(10); expect(p.id).toEqual("id"); }); it("sets pointPrimitive properties", function() { const p = pointPrimitives.add(); p.show = false; p.position = new import__570.Cartesian3(1, 2, 3); p.pixelSize = 2; p.color = new import__570.Color(0.1, 0.2, 0.3, 0.4); p.outlineColor = new import__570.Color(0.5, 0.6, 0.7, 0.8); p.outlineWidth = 4; p.scaleByDistance = new import__570.NearFarScalar(1e6, 3, 1e8, 0); p.translucencyByDistance = new import__570.NearFarScalar(1e6, 1, 1e8, 0); p.distanceDisplayCondition = new import__570.DistanceDisplayCondition(10, 100); p.disableDepthTestDistance = 10; expect(p.show).toEqual(false); expect(p.position).toEqual(new import__570.Cartesian3(1, 2, 3)); expect(p.pixelSize).toEqual(2); expect(p.color.red).toEqual(0.1); expect(p.color.green).toEqual(0.2); expect(p.color.blue).toEqual(0.3); expect(p.color.alpha).toEqual(0.4); expect(p.outlineColor.red).toEqual(0.5); expect(p.outlineColor.green).toEqual(0.6); expect(p.outlineColor.blue).toEqual(0.7); expect(p.outlineColor.alpha).toEqual(0.8); expect(p.outlineWidth).toEqual(4); expect(p.scaleByDistance).toEqual( new import__570.NearFarScalar(1e6, 3, 1e8, 0) ); expect(p.translucencyByDistance).toEqual( new import__570.NearFarScalar(1e6, 1, 1e8, 0) ); expect(p.distanceDisplayCondition).toEqual( new import__570.DistanceDisplayCondition(10, 100) ); expect(p.disableDepthTestDistance).toEqual(10); }); it("is not destroyed", function() { expect(pointPrimitives.isDestroyed()).toEqual(false); }); it("renders pointPrimitive in multiple passes", function() { pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.LIME }); camera.position = new import__570.Cartesian3(2, 0, 0); const frameState2 = scene2.frameState; frameState2.commandList.length = 0; pointPrimitives.blendOption = import__570.BlendOption.OPAQUE_AND_TRANSLUCENT; pointPrimitives.update(frameState2); expect(frameState2.commandList.length).toEqual(2); frameState2.commandList.length = 0; pointPrimitives.blendOption = import__570.BlendOption.OPAQUE; pointPrimitives.update(frameState2); expect(frameState2.commandList.length).toEqual(1); frameState2.commandList.length = 0; pointPrimitives.blendOption = import__570.BlendOption.TRANSLUCENT; pointPrimitives.update(frameState2); expect(frameState2.commandList.length).toEqual(1); }); it("disables pointPrimitive scaleByDistance", function() { const p = pointPrimitives.add({ scaleByDistance: new import__570.NearFarScalar(1, 3, 1e6, 0) }); p.scaleByDistance = void 0; expect(p.scaleByDistance).not.toBeDefined(); }); it("disables pointPrimitive translucencyByDistance", function() { const p = pointPrimitives.add({ translucencyByDistance: new import__570.NearFarScalar(1, 1, 1e6, 0) }); p.translucencyByDistance = void 0; expect(p.translucencyByDistance).not.toBeDefined(); }); it("renders pointPrimitive with scaleByDistance", function() { pointPrimitives.add({ position: import__570.Cartesian3.ZERO, scaleByDistance: new import__570.NearFarScalar(2, 1, 4, 0), color: import__570.Color.LIME }); camera.position = new import__570.Cartesian3(2, 0, 0); expect(scene2).toRender([0, 255, 0, 255]); camera.position = new import__570.Cartesian3(4, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); }); it("renders pointPrimitive with translucencyByDistance", function() { pointPrimitives.add({ position: import__570.Cartesian3.ZERO, translucencyByDistance: new import__570.NearFarScalar(2, 1, 4, 0), color: import__570.Color.LIME }); camera.position = new import__570.Cartesian3(2, 0, 0); expect(scene2).toRender([0, 255, 0, 255]); camera.position = new import__570.Cartesian3(4, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); }); it("does not render pointPrimitive if show is false", function() { pointPrimitives.add({ position: import__570.Cartesian3.ZERO, translucencyByDistance: new import__570.NearFarScalar(2, 1, 4, 0), color: import__570.Color.LIME }); camera.position = new import__570.Cartesian3(2, 0, 0); expect(scene2).toRender([0, 255, 0, 255]); pointPrimitives.show = false; expect(scene2).toRender([0, 0, 0, 255]); }); it("throws scaleByDistance with nearDistance === farDistance", function() { const p = pointPrimitives.add(); const scale = new import__570.NearFarScalar(2e5, 1, 2e5, 0); expect(function() { p.scaleByDistance = scale; }).toThrowDeveloperError(); }); it("throws new pointPrimitive with invalid scaleByDistance (nearDistance === farDistance)", function() { const scale = new import__570.NearFarScalar(2e5, 1, 2e5, 0); expect(function() { pointPrimitives.add({ scaleByDistance: scale }); }).toThrowDeveloperError(); }); it("throws scaleByDistance with nearDistance > farDistance", function() { const p = pointPrimitives.add(); const scale = new import__570.NearFarScalar(1e9, 1, 1e5, 1); expect(function() { p.scaleByDistance = scale; }).toThrowDeveloperError(); }); it("throws translucencyByDistance with nearDistance === farDistance", function() { const p = pointPrimitives.add(); const translucency = new import__570.NearFarScalar(2e5, 1, 2e5, 0); expect(function() { p.translucencyByDistance = translucency; }).toThrowDeveloperError(); }); it("throws new pointPrimitive with invalid translucencyByDistance (nearDistance === farDistance)", function() { const translucency = new import__570.NearFarScalar(2e5, 1, 2e5, 0); expect(function() { pointPrimitives.add({ translucencyByDistance: translucency }); }).toThrowDeveloperError(); }); it("throws translucencyByDistance with nearDistance > farDistance", function() { const p = pointPrimitives.add(); const translucency = new import__570.NearFarScalar(1e9, 1, 1e5, 1); expect(function() { p.translucencyByDistance = translucency; }).toThrowDeveloperError(); }); it("renders pointPrimitive with distanceDisplayCondition", function() { pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.LIME, distanceDisplayCondition: new import__570.DistanceDisplayCondition(10, 100) }); camera.position = new import__570.Cartesian3(200, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); camera.position = new import__570.Cartesian3(50, 0, 0); expect(scene2).toRender([0, 255, 0, 255]); camera.position = new import__570.Cartesian3(5, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); }); it("throws new pointPrimitive with invalid distanceDisplayCondition (near >= far)", function() { const dc = new import__570.DistanceDisplayCondition(100, 10); expect(function() { pointPrimitives.add({ distanceDisplayCondition: dc }); }).toThrowDeveloperError(); }); it("throws distanceDisplayCondition with near >= far", function() { const p = pointPrimitives.add(); const dc = new import__570.DistanceDisplayCondition(100, 10); expect(function() { p.distanceDisplayCondition = dc; }).toThrowDeveloperError(); }); it("renders with disableDepthTestDistance", function() { const p = pointPrimitives.add({ position: new import__570.Cartesian3(-1, 0, 0), pixelSize: 10, color: import__570.Color.LIME }); pointPrimitives.add({ position: import__570.Cartesian3.ZERO, pixelSize: 10, color: import__570.Color.BLUE }); expect(scene2).toRender([0, 0, 255, 255]); p.disableDepthTestDistance = Number.POSITIVE_INFINITY; expect(scene2).toRender([0, 255, 0, 255]); }); it("throws with new point primitive with invalid disableDepthTestDistance (< 0.0)", function() { expect(function() { pointPrimitives.add({ disableDepthTestDistance: -1 }); }).toThrowDeveloperError(); }); it("throws with disableDepthTestDistance set less than 0.0", function() { const p = pointPrimitives.add(); expect(function() { p.disableDepthTestDistance = -1; }).toThrowDeveloperError(); }); it("set a removed pointPrimitive property", function() { const p = pointPrimitives.add(); pointPrimitives.remove(p); p.show = false; expect(p.show).toEqual(false); }); it("has zero pointPrimitives when constructed", function() { expect(pointPrimitives.length).toEqual(0); }); it("adds a pointPrimitive", function() { const p = pointPrimitives.add({ position: new import__570.Cartesian3(1, 2, 3) }); expect(pointPrimitives.length).toEqual(1); expect(pointPrimitives.get(0)).toEqual(p); }); it("removes the first pointPrimitive", function() { const one = pointPrimitives.add({ position: new import__570.Cartesian3(1, 2, 3) }); const two = pointPrimitives.add({ position: new import__570.Cartesian3(4, 5, 6) }); expect(pointPrimitives.length).toEqual(2); expect(pointPrimitives.remove(one)).toEqual(true); expect(pointPrimitives.length).toEqual(1); expect(pointPrimitives.get(0)).toEqual(two); }); it("removes the last pointPrimitive", function() { const one = pointPrimitives.add({ position: new import__570.Cartesian3(1, 2, 3) }); const two = pointPrimitives.add({ position: new import__570.Cartesian3(4, 5, 6) }); expect(pointPrimitives.length).toEqual(2); expect(pointPrimitives.remove(two)).toEqual(true); expect(pointPrimitives.length).toEqual(1); expect(pointPrimitives.get(0)).toEqual(one); }); it("removes the same pointPrimitive twice", function() { const p = pointPrimitives.add({ position: new import__570.Cartesian3(1, 2, 3) }); expect(pointPrimitives.length).toEqual(1); expect(pointPrimitives.remove(p)).toEqual(true); expect(pointPrimitives.length).toEqual(0); expect(pointPrimitives.remove(p)).toEqual(false); expect(pointPrimitives.length).toEqual(0); }); it("returns false when removing undefined", function() { pointPrimitives.add({ position: new import__570.Cartesian3(1, 2, 3) }); expect(pointPrimitives.length).toEqual(1); expect(pointPrimitives.remove(void 0)).toEqual(false); expect(pointPrimitives.length).toEqual(1); }); it("adds and removes pointPrimitives", function() { const one = pointPrimitives.add({ position: new import__570.Cartesian3(1, 2, 3) }); const two = pointPrimitives.add({ position: new import__570.Cartesian3(4, 5, 6) }); expect(pointPrimitives.length).toEqual(2); expect(pointPrimitives.get(0)).toEqual(one); expect(pointPrimitives.get(1)).toEqual(two); expect(pointPrimitives.remove(two)).toEqual(true); const three = pointPrimitives.add({ position: new import__570.Cartesian3(7, 8, 9) }); expect(pointPrimitives.length).toEqual(2); expect(pointPrimitives.get(0)).toEqual(one); expect(pointPrimitives.get(1)).toEqual(three); }); it("removes all pointPrimitives", function() { pointPrimitives.add({ position: new import__570.Cartesian3(1, 2, 3) }); pointPrimitives.add({ position: new import__570.Cartesian3(4, 5, 6) }); expect(pointPrimitives.length).toEqual(2); pointPrimitives.removeAll(); expect(pointPrimitives.length).toEqual(0); }); it("can check if it contains a pointPrimitive", function() { const pointPrimitive = pointPrimitives.add(); expect(pointPrimitives.contains(pointPrimitive)).toEqual(true); }); it("returns false when checking if it contains a pointPrimitive it does not contain", function() { const pointPrimitive = pointPrimitives.add(); pointPrimitives.remove(pointPrimitive); expect(pointPrimitives.contains(pointPrimitive)).toEqual(false); }); it("does not contain undefined", function() { expect(pointPrimitives.contains(void 0)).toEqual(false); }); it("does not contain random other objects", function() { expect(pointPrimitives.contains({})).toEqual(false); expect(pointPrimitives.contains(new import__570.Cartesian2())).toEqual(false); }); it("does not render when constructed", function() { expect(scene2).toRender([0, 0, 0, 255]); }); it("modifies and removes a pointPrimitive, then renders", function() { const p1 = pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.LIME }); pointPrimitives.add({ position: new import__570.Cartesian3(-1, 0, 0), color: import__570.Color.BLUE }); expect(scene2).toRender([0, 255, 0, 255]); p1.pixelSize = 2; pointPrimitives.remove(p1); expect(scene2).toRender([0, 0, 255, 255]); }); it("renders a green pointPrimitive", function() { pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.LIME }); expect(scene2).toRender([0, 255, 0, 255]); }); it("adds and renders a pointPrimitive", function() { pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.LIME }); expect(scene2).toRender([0, 255, 0, 255]); pointPrimitives.add({ position: new import__570.Cartesian3(1, 0, 0), // Closer to camera color: import__570.Color.BLUE }); expect(scene2).toRender([0, 0, 255, 255]); }); it("removes and renders a pointPrimitive", function() { pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.LIME }); const bluePointPrimitive = pointPrimitives.add({ position: new import__570.Cartesian3(1, 0, 0), // Closer to camera color: import__570.Color.BLUE }); expect(scene2).toRender([0, 0, 255, 255]); pointPrimitives.remove(bluePointPrimitive); expect(scene2).toRender([0, 255, 0, 255]); }); it("removes all pointPrimitives and renders", function() { pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.LIME }); expect(scene2).toRender([0, 255, 0, 255]); pointPrimitives.removeAll(); expect(scene2).toRender([0, 0, 0, 255]); }); it("removes all pointPrimitives, adds a pointPrimitive, and renders", function() { pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.LIME }); expect(scene2).toRender([0, 255, 0, 255]); pointPrimitives.removeAll(); pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.BLUE }); expect(scene2).toRender([0, 0, 255, 255]); }); it("renders using pointPrimitive show property", function() { const greenPointPrimitive = pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.LIME }); const bluePointPrimitive = pointPrimitives.add({ show: false, position: import__570.Cartesian3.ZERO, color: import__570.Color.BLUE }); expect(scene2).toRender([0, 255, 0, 255]); greenPointPrimitive.show = false; bluePointPrimitive.show = true; expect(scene2).toRender([0, 0, 255, 255]); }); it("renders using pointPrimitive position property", function() { const p = pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.LIME }); expect(scene2).toRender([0, 255, 0, 255]); p.position = new import__570.Cartesian3(20, 0, 0); expect(scene2).toRender([0, 0, 0, 255]); p.position = new import__570.Cartesian3(1, 0, 0); expect(scene2).toRender([0, 255, 0, 255]); }); it("renders using pointPrimitive color property", function() { const p = pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.WHITE }); expect(scene2).toRender([255, 255, 255, 255]); p.color = new import__570.Color(1, 0, 1, 1); expect(scene2).toRender([255, 0, 255, 255]); p.color = new import__570.Color(0, 1, 0, 1); expect(scene2).toRender([0, 255, 0, 255]); }); it("renders bounding volume with debugShowBoundingVolume", function() { pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.LIME, pixelSize: 0.5 // bring bounding volume in view }); pointPrimitives.debugShowBoundingVolume = true; expect(scene2).notToRender([0, 0, 0, 255]); }); it("updates 10% of pointPrimitives", function() { for (let i = 0; i < 10; ++i) { pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.WHITE, show: i === 3 }); } expect(scene2).toRender([255, 255, 255, 255]); pointPrimitives.get(3).color = new import__570.Color(0, 1, 0, 1); expect(scene2).toRender([0, 255, 0, 255]); pointPrimitives.get(3).color = new import__570.Color(1, 0, 0, 1); expect(scene2).toRender([255, 0, 0, 255]); }); it("renders more than 64K pointPrimitives", function() { for (let i = 0; i < 64 * 1024; ++i) { pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.TRANSPARENT }); } pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.WHITE }); expect(scene2).toRender([255, 255, 255, 255]); }); it("is picked", function() { const p = pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.WHITE, id: "id" }); expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toEqual(p); expect(result.id).toEqual("id"); }); }); it("can change pick id", function() { const p = pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.WHITE, id: "id" }); expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toEqual(p); expect(result.id).toEqual("id"); }); p.id = "id2"; expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toEqual(p); expect(result.id).toEqual("id2"); }); }); it("is not picked", function() { pointPrimitives.add({ show: false, position: import__570.Cartesian3.ZERO, color: import__570.Color.WHITE }); expect(scene2).notToPick(); }); it("picks a pointPrimitive using scaleByDistance", function() { const p = pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.WHITE }); const scaleByDistance = new import__570.NearFarScalar(1, 4, 3e9, 2); p.scaleByDistance = scaleByDistance; expect(scene2).toPickPrimitive(p); scaleByDistance.nearValue = 0; scaleByDistance.farValue = 0; p.scaleByDistance = scaleByDistance; expect(scene2).notToPick(); }); it("picks a pointPrimitive using translucencyByDistance", function() { const p = pointPrimitives.add({ position: import__570.Cartesian3.ZERO, color: import__570.Color.WHITE }); const translucency = new import__570.NearFarScalar(1, 0.9, 3e9, 0.8); p.translucencyByDistance = translucency; expect(scene2).toPickPrimitive(p); translucency.nearValue = 0; translucency.farValue = 0; p.translucencyByDistance = translucency; expect(scene2).notToPick(); }); it("computes screen space position", function() { const p = pointPrimitives.add({ position: import__570.Cartesian3.ZERO }); scene2.renderForSpecs(); expect(p.computeScreenSpacePosition(scene2)).toEqualEpsilon( new import__570.Cartesian2(0.5, 0.5), import__571.Math.EPSILON1 ); }); it("stores screen space position in a result", function() { const p = pointPrimitives.add({ position: import__570.Cartesian3.ZERO }); const result = new import__570.Cartesian2(); scene2.renderForSpecs(); const actual = p.computeScreenSpacePosition(scene2, result); expect(actual).toEqual(result); expect(result).toEqualEpsilon( new import__570.Cartesian2(0.5, 0.5), import__571.Math.EPSILON1 ); }); it("throws when computing screen space position when not in a collection", function() { const p = pointPrimitives.add({ position: import__570.Cartesian3.ZERO }); pointPrimitives.remove(p); expect(function() { p.computeScreenSpacePosition(scene2); }).toThrowDeveloperError(); }); it("throws when computing screen space position without scene", function() { const p = pointPrimitives.add(); expect(function() { p.computeScreenSpacePosition(); }).toThrowDeveloperError(); }); it("computes screen space bounding box", function() { const size = 10; const p = pointPrimitives.add({ size }); const halfWidth = size * 0.5; const halfHeight = halfWidth; const bbox = import__570.PointPrimitive.getScreenSpaceBoundingBox(p, import__570.Cartesian2.ZERO); expect(bbox.x).toEqual(-halfWidth); expect(bbox.y).toEqual(-halfHeight); expect(bbox.width).toEqual(size); expect(bbox.height).toEqual(size); }); it("computes screen space bounding box with result", function() { const size = 10; const p = pointPrimitives.add({ size }); const halfWidth = size * 0.5; const halfHeight = halfWidth; const result = new import__570.BoundingRectangle(); const bbox = import__570.PointPrimitive.getScreenSpaceBoundingBox( p, import__570.Cartesian2.ZERO, result ); expect(bbox.x).toEqual(-halfWidth); expect(bbox.y).toEqual(-halfHeight); expect(bbox.width).toEqual(size); expect(bbox.height).toEqual(size); expect(bbox).toBe(result); }); it("equals another pointPrimitive", function() { const p = pointPrimitives.add({ position: new import__570.Cartesian3(1, 2, 3), color: { red: 1, green: 0, blue: 0, alpha: 1 } }); const p2 = pointPrimitives.add({ position: new import__570.Cartesian3(1, 2, 3), color: { red: 1, green: 0, blue: 0, alpha: 1 } }); expect(p.equals(p2)).toEqual(true); }); it("does not equal another pointPrimitive", function() { const p = pointPrimitives.add({ position: new import__570.Cartesian3(1, 2, 3) }); const p2 = pointPrimitives.add({ position: new import__570.Cartesian3(4, 5, 6) }); expect(p.equals(p2)).toEqual(false); }); it("does not equal undefined", function() { const pointPrimitive = pointPrimitives.add(); expect(pointPrimitive.equals(void 0)).toEqual(false); }); it("throws when accessing without an index", function() { expect(function() { pointPrimitives.get(); }).toThrowDeveloperError(); }); it("computes bounding sphere in 3D", function() { const one = pointPrimitives.add({ position: import__570.Cartesian3.fromDegrees(-50, -50) }); const two = pointPrimitives.add({ position: import__570.Cartesian3.fromDegrees(-50, 50) }); scene2.renderForSpecs(); const actual = scene2.frameState.commandList[0].boundingVolume; const positions = [one.position, two.position]; const expected = import__570.BoundingSphere.fromPoints(positions); expect(actual.center).toEqual(expected.center); expect(actual.radius).toEqual(expected.radius); }); it("computes bounding sphere in Columbus view", function() { const projection = scene2.mapProjection; const ellipsoid = projection.ellipsoid; const one = pointPrimitives.add({ position: import__570.Cartesian3.fromDegrees(-50, -50) }); const two = pointPrimitives.add({ position: import__570.Cartesian3.fromDegrees(-50, 50) }); scene2.morphToColumbusView(0); scene2.renderForSpecs(); const actual = scene2.frameState.commandList[0].boundingVolume; const projectedPositions = [ projection.project(ellipsoid.cartesianToCartographic(one.position)), projection.project(ellipsoid.cartesianToCartographic(two.position)) ]; const expected = import__570.BoundingSphere.fromPoints(projectedPositions); expected.center = new import__570.Cartesian3( 0, expected.center.x, expected.center.y ); expect(actual.center).toEqualEpsilon( expected.center, import__571.Math.EPSILON8 ); expect(actual.radius).toBeGreaterThanOrEqual(expected.radius); }); it("computes bounding sphere in 2D", function() { const projection = scene2.mapProjection; const ellipsoid = projection.ellipsoid; const one = pointPrimitives.add({ color: import__570.Color.LIME, position: import__570.Cartesian3.fromDegrees(-50, -50) }); const two = pointPrimitives.add({ color: import__570.Color.LIME, position: import__570.Cartesian3.fromDegrees(-50, 50) }); camera.setView({ destination: import__570.Rectangle.fromDegrees(-60, -60, -40, 60) }); scene2.morphTo2D(0); scene2.renderForSpecs(); scene2.renderForSpecs(); const actual = scene2.frameState.commandList[0].boundingVolume; const projectedPositions = [ projection.project(ellipsoid.cartesianToCartographic(one.position)), projection.project(ellipsoid.cartesianToCartographic(two.position)) ]; const expected = import__570.BoundingSphere.fromPoints(projectedPositions); expected.center = new import__570.Cartesian3( 0, expected.center.x, expected.center.y ); expect(actual.center).toEqualEpsilon( expected.center, import__571.Math.EPSILON8 ); expect(actual.radius).toBeGreaterThan(expected.radius); }); }, "WebGL" ); // packages/engine/Specs/Scene/PolylineCollectionSpec.js var import__572 = __toESM(require_Cesium(), 1); var import__573 = __toESM(require_Cesium(), 1); describe( "Scene/PolylineCollection", function() { let scene2; let polylines; beforeAll(function() { scene2 = createScene_default(); scene2.primitives.destroyPrimitives = false; }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { polylines = new import__572.PolylineCollection(); scene2.mode = import__572.SceneMode.SCENE3D; scene2.camera = new import__572.Camera(scene2); }); afterEach(function() { scene2.primitives.removeAll(); if (!polylines.isDestroyed()) { polylines.removeAll(); polylines.destroy(); } }); it("default constructs a polyline", function() { const p = polylines.add(); expect(p.show).toEqual(true); expect(p.positions.length).toEqual(0); expect(p.width).toEqual(1); expect(p.material.uniforms.color).toEqual(new import__572.Color(1, 1, 1, 1)); expect(p.id).not.toBeDefined(); expect(p.loop).toEqual(false); }); it("explicitly constructs a polyline", function() { const material = import__572.Material.fromType(import__572.Material.PolylineOutlineType); const p = polylines.add({ show: false, positions: [ new import__572.Cartesian3(1, 2, 3), new import__572.Cartesian3(4, 5, 6), new import__572.Cartesian3(7, 8, 9) ], loop: true, width: 2, material, id: "id" }); expect(p.show).toEqual(false); expect(p.positions[0]).toEqual(new import__572.Cartesian3(1, 2, 3)); expect(p.positions[1]).toEqual(new import__572.Cartesian3(4, 5, 6)); expect(p.positions[2]).toEqual(new import__572.Cartesian3(7, 8, 9)); expect(p.positions.length).toEqual(3); expect(p.loop).toEqual(true); expect(p.width).toEqual(2); expect(p.material.uniforms.color).toEqual(material.uniforms.color); expect(p.material.uniforms.outlineColor).toEqual( material.uniforms.outlineColor ); expect(p.material.uniforms.outlineWidth).toEqual( material.uniforms.outlineWidth ); expect(p.id).toEqual("id"); }); it("sets polyline properties", function() { const material = import__572.Material.fromType(import__572.Material.PolylineOutlineType); const p = polylines.add(); p.show = false; p.positions = [ new import__572.Cartesian3(1, 2, 3), new import__572.Cartesian3(4, 5, 6), new import__572.Cartesian3(7, 8, 9) ]; p.loop = true; p.width = 2; p.material = material; expect(p.show).toEqual(false); expect(p.positions[0]).toEqual(new import__572.Cartesian3(1, 2, 3)); expect(p.positions[1]).toEqual(new import__572.Cartesian3(4, 5, 6)); expect(p.positions[2]).toEqual(new import__572.Cartesian3(7, 8, 9)); expect(p.positions.length).toEqual(3); expect(p.loop).toEqual(true); expect(p.width).toEqual(2); expect(p.material.uniforms.color).toEqual(material.uniforms.color); expect(p.material.uniforms.outlineColor).toEqual( material.uniforms.outlineColor ); expect(p.material.uniforms.outlineWidth).toEqual( material.uniforms.outlineWidth ); }); it("constructor sets loop only when number of positions is greater than 2", function() { const p = polylines.add({ positions: [ new import__572.Cartesian3(0, 1, 2), new import__572.Cartesian3(3, 4, 5) ], loop: true }); expect(p.positions.length).toEqual(2); }); it("sets loop only when number of positions is greater than 2", function() { const p = polylines.add({ positions: [ new import__572.Cartesian3(0, 1, 2), new import__572.Cartesian3(3, 4, 5) ] }); p.loop = true; expect(p.positions.length).toEqual(2); }); it("sets removed polyline properties", function() { const p = polylines.add(); polylines.remove(p); p.show = false; expect(p.show).toEqual(false); }); it("has zero polylines when constructed", function() { expect(polylines.length).toEqual(0); }); it("adds a polyline", function() { const p = polylines.add({ positions: [ { x: 1, y: 2, z: 3 }, { x: 2, y: 3, z: 4 } ] }); expect(polylines.length).toEqual(1); expect(polylines.get(0) === p).toEqual(true); }); it("removes the first polyline", function() { const one = polylines.add({ positions: [ { x: 1, y: 2, z: 3 }, { x: 2, y: 3, z: 4 } ] }); const two = polylines.add({ positions: [ { x: 4, y: 5, z: 6 }, { x: 2, y: 3, z: 4 } ] }); expect(polylines.length).toEqual(2); expect(polylines.remove(one)).toEqual(true); expect(polylines.length).toEqual(1); expect(polylines.get(0) === two).toEqual(true); }); it("removes the last polyline", function() { const one = polylines.add({ positions: [ { x: 1, y: 2, z: 3 }, { x: 2, y: 3, z: 4 } ] }); const two = polylines.add({ positions: [ { x: 4, y: 5, z: 6 }, { x: 2, y: 3, z: 4 } ] }); expect(polylines.length).toEqual(2); expect(polylines.remove(two)).toEqual(true); expect(polylines.length).toEqual(1); expect(polylines.get(0) === one).toEqual(true); }); it("removes the same polyline twice", function() { const p = polylines.add({ positions: [ { x: 1, y: 2, z: 3 }, { x: 2, y: 3, z: 4 } ] }); expect(polylines.length).toEqual(1); expect(polylines.remove(p)).toEqual(true); expect(polylines.length).toEqual(0); expect(polylines.remove(p)).toEqual(false); expect(polylines.length).toEqual(0); }); it("returns false when removing undefined", function() { polylines.add({ positions: [ { x: 1, y: 2, z: 3 }, { x: 2, y: 3, z: 4 } ] }); expect(polylines.length).toEqual(1); expect(polylines.remove(void 0)).toEqual(false); expect(polylines.length).toEqual(1); }); it("adds and removes polylines", function() { const one = polylines.add({ positions: [ { x: 1, y: 2, z: 3 }, { x: 2, y: 3, z: 4 } ] }); const two = polylines.add({ positions: [ { x: 4, y: 5, z: 6 }, { x: 2, y: 3, z: 4 } ] }); expect(polylines.length).toEqual(2); expect(polylines.get(0) === one).toEqual(true); expect(polylines.get(1) === two).toEqual(true); expect(polylines.remove(two)).toEqual(true); const three = polylines.add({ positions: [ { x: 7, y: 8, z: 9 }, { x: 2, y: 3, z: 4 } ] }); expect(polylines.length).toEqual(2); expect(polylines.get(0) === one).toEqual(true); expect(polylines.get(1) === three).toEqual(true); }); it("removes all polylines", function() { polylines.add({ positions: [ { x: 1, y: 2, z: 3 }, { x: 2, y: 3, z: 4 } ] }); polylines.add({ positions: [ { x: 4, y: 5, z: 6 }, { x: 2, y: 3, z: 4 } ] }); expect(polylines.length).toEqual(2); polylines.removeAll(); expect(polylines.length).toEqual(0); }); it("removal of polyline from polyLinesToUpdate is deferred until scene is updated", function() { const firstPolyline = polylines.add(); const secondPolyline = polylines.add(); firstPolyline.width = 4; secondPolyline.width = 5; expect(polylines._polylinesToUpdate.length).toEqual(2); polylines.remove(secondPolyline); polylines.update(scene2.frameState); expect(polylines._polylinesToUpdate.length).toEqual(1); }); it("removal of polyline from polylinesToUpdate after polyline is made dirty multiple times", function() { const firstPolyline = polylines.add(); const secondPolyline = polylines.add(); firstPolyline.width = 4; secondPolyline.width = 5; secondPolyline.width = 7; expect(polylines._polylinesToUpdate.length).toEqual(2); polylines.remove(secondPolyline); polylines.update(scene2.frameState); expect(polylines._polylinesToUpdate.length).toEqual(1); }); it("can check if it contains a polyline", function() { const polyline = polylines.add(); expect(polylines.contains(polyline)).toEqual(true); }); it("returns false when checking if it contains a polyline it does not contain", function() { const polyline = polylines.add(); polylines.remove(polyline); expect(polylines.contains(polyline)).toEqual(false); }); it("does not contain undefined", function() { expect(polylines.contains(void 0)).toEqual(false); }); it("does not contain random other objects", function() { expect(polylines.contains({})).toEqual(false); expect(polylines.contains(new import__572.Cartesian3())).toEqual(false); }); it("does not render when constructed", function() { expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).toRender([0, 0, 0, 255]); }); it("renders polylines. one polyline with no positions", function() { const positions = []; for (let i = 0; i < 100; ++i) { positions.push({ x: 0, y: -1e6, z: 0 }); positions.push({ x: 0, y: 1e6, z: 0 }); } polylines.add({ positions }); polylines.add(); polylines.add({ positions }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); }); it("does not crash if polyline has one position", function() { polylines.add({ positions: [ { x: 1.6477456656519484e6, y: 494901887918947e-8, z: 3661524164064342e-9 } ] }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).toRender([0, 0, 0, 255]); }); it("renders polylines with duplicate positions at construction", function() { polylines.add({ positions: [ new import__572.Cartesian3(0, -1e6, 0), new import__572.Cartesian3(0, 1e6, 0), new import__572.Cartesian3(0, 1e6, 0), new import__572.Cartesian3(0, 2e6, 0) ] }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders polylines with duplicate positions after setting positions", function() { const p = polylines.add(); p.positions = [ new import__572.Cartesian3(0, -1e6, 0), new import__572.Cartesian3(0, 1e6, 0), new import__572.Cartesian3(0, 1e6, 0), new import__572.Cartesian3(0, 2e6, 0) ]; expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); }); it("does not render polyline if show is false", function() { const p = polylines.add(); p.positions = [ new import__572.Cartesian3(0, -1e6, 0), new import__572.Cartesian3(0, 1e6, 0), new import__572.Cartesian3(0, 2e6, 0) ]; scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); polylines.show = false; expect(scene2).toRender([0, 0, 0, 255]); }); it("A polyline that used to cross the IDL but now does not, triggers vertex creation (This code used to crash)", function() { scene2.mode = import__572.SceneMode.SCENE2D; const positions = []; positions.push({ x: 12163600, y: -47362500, z: 40812700 }); positions.push({ x: -50442500, y: 83936900, z: 37992500 }); const line = polylines.add({ positions }); scene2.primitives.add(polylines); scene2.render(); line.positions = positions; scene2.render(); positions[1] = { x: 19616100, y: -46499100, z: 38870500 }; line.positions = positions; scene2.render(); }); it("renders 64K vertices of same polyline", function() { const positions = []; for (let i = 0; i < import__573.Math.SIXTY_FOUR_KILOBYTES / 2; ++i) { positions.push({ x: 0, y: -1e6, z: 0 }); positions.push({ x: 0, y: 1e6, z: 0 }); } polylines.add({ positions }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); }); it("creates two vertex arrays and renders", function() { const positions = []; for (let i = 0; i < import__573.Math.SIXTY_FOUR_KILOBYTES / 2; ++i) { positions.push({ x: 0, y: -1e6, z: 0 }); positions.push({ x: 0, y: 1e6, z: 0 }); } const p1 = polylines.add({ positions }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); p1.show = false; expect(scene2).toRender([0, 0, 0, 255]); polylines.add({ positions }); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders more than 64K vertices of same polyline", function() { const positions = []; for (let i = 0; i < import__573.Math.SIXTY_FOUR_KILOBYTES; ++i) { positions.push({ x: 0, y: -1e6, z: 0 }); positions.push({ x: 0, y: 1e6, z: 0 }); } positions.push({ x: 0, y: -1e6, z: 0 }); positions.push({ x: 0, y: 1e6, z: 0 }); polylines.add({ positions }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders a polyline with no positions", function() { const positions = []; for (let i = 0; i < 100; ++i) { positions.push({ x: 0, y: -1e6, z: 0 }); positions.push({ x: 0, y: 1e6, z: 0 }); } polylines.add({ positions }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); polylines.add({ positions: [] }); scene2.primitives.removeAll(); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders an updated polyline with no positions using set positions", function() { const positions = []; for (let i = 0; i < 100; ++i) { positions.push({ x: 0, y: -1e6, z: 0 }); positions.push({ x: 0, y: 1e6, z: 0 }); } polylines.add({ positions }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); const p2 = polylines.add({ positions: [] }); expect(scene2).notToRender([0, 0, 0, 255]); p2.positions = []; expect(scene2).notToRender([0, 0, 0, 255]); p2.positions = []; expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders an updated polyline with no positions using show", function() { const positions = []; for (let i = 0; i < 100; ++i) { positions.push({ x: 0, y: -1e6, z: 0 }); positions.push({ x: 0, y: 1e6, z: 0 }); } polylines.add({ positions }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); const p2 = polylines.add({ positions: [] }); expect(scene2).notToRender([0, 0, 0, 255]); p2.show = false; expect(scene2).notToRender([0, 0, 0, 255]); p2.show = true; expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders an updated polyline with no positions using material", function() { const positions = []; for (let i = 0; i < 100; ++i) { positions.push({ x: 0, y: -1e6, z: 0 }); positions.push({ x: 0, y: 1e6, z: 0 }); } polylines.add({ positions }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); const p2 = polylines.add({ positions: [] }); expect(scene2).notToRender([0, 0, 0, 255]); p2.material = import__572.Material.fromType(import__572.Material.PolylineOutlineType); expect(scene2).notToRender([0, 0, 0, 255]); }); it("changes buffer usage after 100 iterations of not changing", function() { const positions = []; for (let i = 0; i < 100; ++i) { positions.push({ x: 0, y: -1e6, z: 0 }); positions.push({ x: 0, y: 1e6, z: 0 }); } const p = polylines.add({ positions }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); p.positions = positions; for (let j = 0; j < 101; ++j) { scene2.render(); } expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders more than 64K vertices of different polylines", function() { const positions = []; for (let i = 0; i < import__573.Math.SIXTY_FOUR_KILOBYTES; ++i) { positions.push({ x: -1e6, y: -1e6, z: 0 }); positions.push({ x: -1e6, y: 1e6, z: 0 }); } polylines.add({ positions }); polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ] }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders bounding volume with debugShowBoundingVolume", function() { polylines.debugShowBoundingVolume = true; const material = import__572.Material.fromType("Color"); material.uniforms.color = new import__572.Color(1, 1, 1, 0); const p = polylines.add({ positions: [ { x: 1, y: -1e3, z: 1 }, { x: 1, y: 1e3, z: 1 } ], material }); const bounds = import__572.BoundingSphere.fromPoints(p.positions); scene2.camera.viewBoundingSphere(bounds); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); }); it("does not render", function() { const p = polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ] }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); p.show = false; expect(scene2).toRender([0, 0, 0, 255]); }); it("modifies and removes a polyline, then renders", function() { const p = polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ] }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); polylines.remove(p); expect(scene2).toRender([0, 0, 0, 255]); }); it("renders a green polyline", function() { polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ] }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); }); it("adds and renders a polyline", function() { polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ] }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); polylines.add({ positions: [ { x: 5e5, y: -1e6, z: 0 }, { x: 5e5, y: 1e6, z: 0 } ] }); expect(scene2).notToRender([0, 0, 0, 255]); }); it("removes and renders a polyline", function() { polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ] }); const bluePolyline = polylines.add({ positions: [ { x: 5e5, y: -1e6, z: 0 }, { x: 5e5, y: 1e6, z: 0 } ] }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); polylines.remove(bluePolyline); expect(scene2).notToRender([0, 0, 0, 255]); }); it("removes all polylines and renders", function() { polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ] }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); polylines.removeAll(); expect(scene2).toRender([0, 0, 0, 255]); }); it("removes all polylines, adds a polyline, and renders", function() { polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ] }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); polylines.removeAll(); expect(scene2).toRender([0, 0, 0, 255]); polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ] }); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders using polyline positions property", function() { const p = polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ] }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); p.positions = [ { x: 0, y: -1e6, z: -2e6 }, { x: 0, y: 1e6, z: -2e6 } ]; expect(scene2).toRender([0, 0, 0, 255]); p.positions = [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ]; expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders and updates one polyline from many polylines using show property", function() { const positions = [ { x: 0, y: -1e6, z: -2e6 }, { x: 0, y: 1e6, z: -2e6 } ]; polylines.add({ positions, width: 2 }); polylines.add({ positions, width: 2 }); polylines.add({ positions, width: 2 }); const p = polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ], width: 2 }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); p.show = false; expect(scene2).toRender([0, 0, 0, 255]); p.show = true; expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders using polyline show property", function() { const p = polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ], show: true }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); p.show = false; expect(scene2).toRender([0, 0, 0, 255]); p.show = true; expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders four polylines with different widths", function() { const positions = []; for (let i = 0; i < 200; ++i) { positions.push( { x: -1e6, y: 1e6, z: 0 }, { x: -1e6, y: -1e6, z: 0 } ); } polylines.add({ positions, width: 3 }); polylines.add({ positions, width: 1 }); polylines.add({ positions, width: 2 }); polylines.add({ positions: [ { x: 0, y: -1, z: 0 }, { x: 0, y: 1, z: 0 } ], width: 7 }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders three polylines with different widths and updates one", function() { const positions = []; for (let i = 0; i < 200; ++i) { positions.push( { x: -1e6, y: 1e6, z: 0 }, { x: -1e6, y: -1e6, z: 0 } ); } polylines.add({ positions, width: 3 }); polylines.add({ positions, width: 4 }); const p2 = polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ], width: 7 }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); p2.material = import__572.Material.fromType(import__572.Material.PolylineOutlineType); expect(scene2).notToRender([0, 0, 0, 255]); p2.material = import__572.Material.fromType(import__572.Material.ColorType); expect(scene2).notToRender([0, 0, 0, 255]); }); it("does not render with width 0.0", function() { const line = polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ], width: 7 }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); line.width = 0; expect(scene2).toRender([0, 0, 0, 255]); }); it("renders with a distance display condition", function() { const near = 100; const far = 1e4; const line = polylines.add({ positions: [ { x: 10, y: -10, z: 0 }, { x: 10, y: 10, z: 0 } ], width: 7, distanceDisplayCondition: new import__572.DistanceDisplayCondition(near, far) }); scene2.primitives.add(polylines); scene2.renderForSpecs(); const boundingSphere = line._boundingVolumeWC; const center = boundingSphere.center; const radius = boundingSphere.radius; scene2.camera.lookAt( center, new import__572.HeadingPitchRange( 0, -import__573.Math.PI_OVER_TWO, radius + near - 10 ) ); expect(scene2).toRender([0, 0, 0, 255]); scene2.camera.lookAt( center, new import__572.HeadingPitchRange(0, -import__573.Math.PI_OVER_TWO, radius + near + 1) ); expect(scene2).notToRender([0, 0, 0, 255]); scene2.camera.lookAt( center, new import__572.HeadingPitchRange(0, -import__573.Math.PI_OVER_TWO, radius + far + 10) ); expect(scene2).toRender([0, 0, 0, 255]); }); it("renders with a distance display condition after creation", function() { const near = 100; const far = 1e4; const line = polylines.add({ positions: [ { x: 10, y: -10, z: 0 }, { x: 10, y: 10, z: 0 } ], width: 7 }); scene2.primitives.add(polylines); scene2.renderForSpecs(); line.distanceDisplayCondition = new import__572.DistanceDisplayCondition(near, far); const boundingSphere = line._boundingVolumeWC; const center = boundingSphere.center; const radius = boundingSphere.radius; scene2.camera.lookAt( center, new import__572.HeadingPitchRange( 0, -import__573.Math.PI_OVER_TWO, radius + near - 10 ) ); expect(scene2).toRender([0, 0, 0, 255]); scene2.camera.lookAt( center, new import__572.HeadingPitchRange(0, -import__573.Math.PI_OVER_TWO, radius + near + 1) ); expect(scene2).notToRender([0, 0, 0, 255]); scene2.camera.lookAt( center, new import__572.HeadingPitchRange(0, -import__573.Math.PI_OVER_TWO, radius + far + 10) ); expect(scene2).toRender([0, 0, 0, 255]); }); it("changes polyline position size recreates vertex arrays", function() { const positions = []; for (let i = 0; i < 20; ++i) { positions.push( { x: 0, y: 1e6, z: 0 }, { x: 0, y: -1e6, z: 0 } ); } const p = polylines.add({ positions }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); p.positions = positions; expect(scene2).notToRender([0, 0, 0, 255]); positions.push({ x: 0, y: 1e6, z: 0 }); p.positions = positions; expect(scene2).notToRender([0, 0, 0, 255]); }); it("changes polyline width property", function() { const p1 = polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ] }); const p2 = polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ] }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).notToRender([0, 0, 0, 255]); p1.width = 2; expect(scene2).notToRender([0, 0, 0, 255]); p2.width = 2; expect(scene2).notToRender([0, 0, 0, 255]); p1.width = 1; expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders with model matrix", function() { polylines.add({ positions: [ { x: 0, y: 0, z: 0 }, { x: 0, y: 1, z: 0 } ] }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(polylines); expect(scene2).toRender([0, 0, 0, 255]); polylines.modelMatrix = import__572.Matrix4.fromUniformScale( 1e6, polylines.modelMatrix ); expect(scene2).notToRender([0, 0, 0, 255]); }); it("is picked", function() { const p = polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ], id: "id" }); scene2.primitives.add(polylines); expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toEqual(p); expect(result.id).toEqual("id"); }); }); it("can change pick id", function() { const p = polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ], id: "id" }); scene2.primitives.add(polylines); expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toEqual(p); expect(result.id).toEqual("id"); }); p.id = "id2"; expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toEqual(p); expect(result.id).toEqual("id2"); }); }); it("is not picked (show === false)", function() { polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ], show: false }); scene2.primitives.add(polylines); expect(scene2).notToPick(); }); it("is not picked (alpha === 0.0)", function() { const p = polylines.add({ positions: [ { x: 0, y: -1e6, z: 0 }, { x: 0, y: 1e6, z: 0 } ] }); p.material.uniforms.color.alpha = 0; scene2.primitives.add(polylines); expect(scene2).notToPick(); }); it("does not equal undefined", function() { const polyline = polylines.add(); expect(polyline).not.toEqual(void 0); }); it("throws when accessing without an index", function() { expect(function() { polylines.get(); }).toThrowDeveloperError(); }); it("computes bounding sphere in 3D", function() { const one = polylines.add({ positions: [ { x: 1, y: 2, z: 3 }, { x: 2, y: 3, z: 4 } ] }); const two = polylines.add({ positions: [ { x: 4, y: 5, z: 6 }, { x: 2, y: 3, z: 4 } ] }); const three = polylines.add({ positions: [ { x: 7, y: 8, z: 9 }, { x: 2, y: 3, z: 4 } ] }); scene2.primitives.add(polylines); scene2.render(); const boundingVolume = scene2.frameState.commandList[0].boundingVolume; expect(one._boundingVolume).toEqual( import__572.BoundingSphere.fromPoints(one.positions) ); expect(two._boundingVolume).toEqual( import__572.BoundingSphere.fromPoints(two.positions) ); expect(three._boundingVolume).toEqual( import__572.BoundingSphere.fromPoints(three.positions) ); expect(boundingVolume).toEqual( import__572.BoundingSphere.union( import__572.BoundingSphere.union(one._boundingVolume, two._boundingVolume), three._boundingVolume ) ); }); function testBoundingSphere() { const projection = scene2.mapProjection; const ellipsoid = projection.ellipsoid; const one = polylines.add({ positions: import__572.Cartesian3.fromDegreesArray([-50, -50, 50, -50]) }); const two = polylines.add({ positions: import__572.Cartesian3.fromDegreesArray([50, 50, -50, 50]) }); scene2.primitives.add(polylines); scene2.render(); const boundingVolume = scene2.frameState.commandList[0].boundingVolume; let positions = one.positions; let projectedPositions = []; let i; for (i = 0; i < positions.length; ++i) { projectedPositions.push( projection.project(ellipsoid.cartesianToCartographic(positions[i])) ); } let bs = import__572.BoundingSphere.fromPoints(projectedPositions); bs.center = new import__572.Cartesian3(bs.center.z, bs.center.x, bs.center.y); expect(one._boundingVolume2D.center).toEqualEpsilon( bs.center, import__573.Math.EPSILON8 ); expect(one._boundingVolume2D.radius).toEqualEpsilon( bs.radius, import__573.Math.EPSILON12 ); positions = two.positions; projectedPositions = []; for (i = 0; i < positions.length; ++i) { projectedPositions.push( projection.project(ellipsoid.cartesianToCartographic(positions[i])) ); } bs = import__572.BoundingSphere.fromPoints(projectedPositions); bs.center = new import__572.Cartesian3(bs.center.z, bs.center.x, bs.center.y); expect(two._boundingVolume2D.center).toEqualEpsilon( bs.center, import__573.Math.EPSILON8 ); expect(two._boundingVolume2D.radius).toEqualEpsilon( bs.radius, import__573.Math.EPSILON12 ); const expected = import__572.BoundingSphere.union( one._boundingVolume2D, two._boundingVolume2D ); expect(boundingVolume.center).toEqualEpsilon( expected.center, import__573.Math.EPSILON8 ); expect(boundingVolume.radius).toEqualEpsilon( expected.radius, import__573.Math.EPSILON8 ); } it("computes bounding sphere in Columbus view", function() { scene2.mode = import__572.SceneMode.COLUMBUS_VIEW; testBoundingSphere(); }); it("computes bounding sphere in 2D", function() { scene2.mode = import__572.SceneMode.SCENE2D; testBoundingSphere(); }); it("computes optimized bounding volumes per material", function() { const one = polylines.add({ positions: [ { x: 1, y: 2, z: 3 }, { x: 2, y: 3, z: 4 } ] }); one.material.uniforms.color = new import__572.Color(1, 0, 0, 1); const two = polylines.add({ positions: [ { x: 2, y: 3, z: 4 }, { x: 4, y: 5, z: 6 } ] }); two.material.uniforms.color = new import__572.Color(0, 1, 0, 1); scene2.primitives.add(polylines); scene2.render(); expect(scene2.frameState.commandList[0].boundingVolume).toEqual( one._boundingVolume ); expect(scene2.frameState.commandList[1].boundingVolume).toEqual( two._boundingVolume ); }); it("isDestroyed", function() { expect(polylines.isDestroyed()).toEqual(false); polylines.destroy(); expect(polylines.isDestroyed()).toEqual(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/PolylineColorAppearanceSpec.js var import__574 = __toESM(require_Cesium(), 1); describe( "Scene/PolylineColorAppearance", function() { let scene2; let primitive; beforeAll(function() { scene2 = createScene_default(); scene2.primitives.destroyPrimitives = false; }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.primitives.removeAll(); primitive = primitive && !primitive.isDestroyed() && primitive.destroy(); }); it("constructor", function() { const a = new import__574.PolylineColorAppearance(); expect(a.material).not.toBeDefined(); expect(a.vertexShaderSource).toBeDefined(); expect(a.fragmentShaderSource).toBeDefined(); expect(a.renderState).toEqual( import__574.Appearance.getDefaultRenderState(true, false) ); expect(a.vertexFormat).toEqual(import__574.PolylineColorAppearance.VERTEX_FORMAT); expect(a.translucent).toEqual(true); expect(a.closed).toEqual(false); }); it("renders", function() { primitive = new import__574.Primitive({ geometryInstances: new import__574.GeometryInstance({ geometry: new import__574.PolylineGeometry({ positions: [ new import__574.Cartesian3(0, -1e6, 0), new import__574.Cartesian3(0, 1e6, 0) ], width: 10, vertexFormat: import__574.PolylineColorAppearance.VERTEX_FORMAT, arcType: import__574.ArcType.NONE }), attributes: { color: import__574.ColorGeometryInstanceAttribute.fromColor( new import__574.Color(1, 1, 0, 1) ) } }), appearance: new import__574.PolylineColorAppearance({ translucent: false }), asynchronous: false }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive); expect(scene2).notToRender([0, 0, 0, 255]); }); }, "WebGL" ); // packages/engine/Specs/Scene/PolylineMaterialAppearanceSpec.js var import__575 = __toESM(require_Cesium(), 1); describe( "Scene/PolylineMaterialAppearance", function() { let scene2; let primitive; beforeAll(function() { scene2 = createScene_default(); scene2.primitives.destroyPrimitives = false; }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.primitives.removeAll(); primitive = primitive && !primitive.isDestroyed() && primitive.destroy(); }); it("constructor", function() { const a = new import__575.PolylineMaterialAppearance(); expect(a.material).toBeDefined(); expect(a.material.type).toEqual(import__575.Material.ColorType); expect(a.vertexShaderSource).toBeDefined(); expect(a.fragmentShaderSource).toBeDefined(); expect(a.renderState).toEqual( import__575.Appearance.getDefaultRenderState(true, false) ); expect(a.vertexFormat).toEqual(import__575.PolylineMaterialAppearance.VERTEX_FORMAT); expect(a.translucent).toEqual(true); expect(a.closed).toEqual(false); }); it("renders", function() { primitive = new import__575.Primitive({ geometryInstances: new import__575.GeometryInstance({ geometry: new import__575.PolylineGeometry({ positions: [ new import__575.Cartesian3(0, -1e7, 0), new import__575.Cartesian3(0, 1e6, 0) ], width: 10, vertexFormat: import__575.PolylineMaterialAppearance.VERTEX_FORMAT, arcType: import__575.ArcType.NONE }) }), appearance: new import__575.PolylineMaterialAppearance({ material: import__575.Material.fromType(import__575.Material.PolylineOutlineType), translucent: false }), asynchronous: false }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive); expect(scene2).notToRender([0, 0, 0, 255]); }); }, "WebGL" ); // packages/engine/Specs/Scene/PostProcessStageCollectionSpec.js var import__576 = __toESM(require_Cesium(), 1); // Specs/ViewportPrimitive.js var import_engine28 = __toESM(require_Cesium(), 1); var ViewportPrimitive = function(fragmentShader) { this._fs = fragmentShader; this._command = void 0; }; ViewportPrimitive.prototype.update = function(frameState2) { if (!(0, import_engine28.defined)(this._command)) { this._command = frameState2.context.createViewportQuadCommand(this._fs, { renderState: import_engine28.RenderState.fromCache(), pass: import_engine28.Pass.OPAQUE }); } frameState2.commandList.push(this._command); }; ViewportPrimitive.prototype.isDestroyed = function() { return false; }; ViewportPrimitive.prototype.destroy = function() { if ((0, import_engine28.defined)(this._command)) { this._command.shaderProgram = this._command.shaderProgram && this._command.shaderProgram.destroy(); } return (0, import_engine28.destroyObject)(this); }; var ViewportPrimitive_default = ViewportPrimitive; // packages/engine/Specs/Scene/PostProcessStageCollectionSpec.js describe( "Scene/PostProcessStageCollection", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); scene2.postProcessStages.fxaa.enabled = false; }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.postProcessStages.removeAll(); scene2.postProcessStages.fxaa.enabled = false; scene2.postProcessStages.bloom.enabled = false; scene2.postProcessStages.ambientOcclusion.enabled = false; scene2.highDynamicRange = false; scene2.primitives.removeAll(); }); it("constructs", function() { const stages = new import__576.PostProcessStageCollection(); expect(stages.ready).toEqual(false); expect(stages.fxaa).toBeDefined(); expect(stages.ambientOcclusion).toBeDefined(); expect(stages.bloom).toBeDefined(); expect(stages.length).toEqual(0); expect(stages.outputTexture).not.toBeDefined(); }); it("adds stages", function() { expect(scene2).toRender([0, 0, 0, 255]); scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 1.0, 0.0, 1.0); }" }) ); expect(scene2.postProcessStages.length).toEqual(1); scene2.renderForSpecs(); expect(scene2).toRender([255, 255, 0, 255]); scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "uniform sampler2D colorTexture;\nin vec2 v_textureCoordinates;\nvoid main() {\n vec4 color = texture(colorTexture, v_textureCoordinates);\n out_FragColor = vec4(color.r, 0.0, 1.0, 1.0);\n}" }) ); expect(scene2.postProcessStages.length).toEqual(2); scene2.renderForSpecs(); expect(scene2).toRender([255, 0, 255, 255]); }); it("throws when adding the same stage", function() { const stage = new import__576.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 1.0, 0.0, 1.0); }" }); expect(function() { scene2.postProcessStages.add(stage); scene2.postProcessStages.add(stage); }).toThrowDeveloperError(); }); it("removes a single stage", function() { const stage1 = scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 1.0, 0.0, 1.0); }" }) ); scene2.renderForSpecs(); expect(scene2).toRender([255, 255, 0, 255]); scene2.postProcessStages.remove(stage1); scene2.renderForSpecs(); expect(scene2).toRender([0, 0, 0, 255]); }); it("removes stages", function() { expect(scene2).toRender([0, 0, 0, 255]); const stage1 = scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 1.0, 0.0, 1.0); }" }) ); const stage2 = scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "uniform sampler2D colorTexture;\nin vec2 v_textureCoordinates;\nvoid main() {\n vec4 color = texture(colorTexture, v_textureCoordinates);\n out_FragColor = vec4(color.r, 0.0, 1.0, 1.0);\n}" }) ); expect(scene2.postProcessStages.length).toEqual(2); scene2.renderForSpecs(); expect(scene2).toRender([255, 0, 255, 255]); scene2.postProcessStages.remove(stage1); expect(scene2.postProcessStages.length).toEqual(1); expect(scene2.postProcessStages.contains(stage1)).toEqual(false); expect(scene2.postProcessStages.contains(stage2)).toEqual(true); expect(stage1.isDestroyed()).toEqual(true); scene2.renderForSpecs(); expect(scene2).toRender([0, 0, 255, 255]); scene2.postProcessStages.remove(stage2); expect(scene2.postProcessStages.length).toEqual(0); expect(scene2.postProcessStages.contains(stage2)).toEqual(false); expect(stage2.isDestroyed()).toEqual(true); scene2.renderForSpecs(); expect(scene2).toRender([0, 0, 0, 255]); expect(scene2.postProcessStages.remove(stage1)).toEqual(false); }); it("gets stages at index", function() { const stage1 = scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 1.0, 0.0, 1.0); }" }) ); const stage2 = scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "uniform sampler2D colorTexture;\nin vec2 v_textureCoordinates;\nvoid main() {\n vec4 color = texture(colorTexture, v_textureCoordinates);\n out_FragColor = vec4(color.r, 0.0, 1.0, 1.0);\n}" }) ); expect(scene2.postProcessStages.length).toEqual(2); expect(scene2.postProcessStages.get(0)).toEqual(stage1); expect(scene2.postProcessStages.get(1)).toEqual(stage2); expect(scene2.postProcessStages.remove(stage1)).toEqual(true); expect(scene2.postProcessStages.get(0)).toEqual(stage2); }); it("throws when get index is invalid", function() { expect(function() { return scene2.postProcessStages.get(0); }).toThrowDeveloperError(); scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 1.0, 0.0, 1.0); }" }) ); expect(function() { return scene2.postProcessStages.get(-1); }).toThrowDeveloperError(); expect(function() { return scene2.postProcessStages.get(1); }).toThrowDeveloperError(); }); it("removes all", function() { expect(scene2).toRender([0, 0, 0, 255]); const stage1 = scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 1.0, 0.0, 1.0); }" }) ); const stage2 = scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "uniform sampler2D colorTexture;\nin vec2 v_textureCoordinates;\nvoid main() {\n vec4 color = texture(colorTexture, v_textureCoordinates);\n out_FragColor = vec4(color.r, 0.0, 1.0, 1.0);\n}" }) ); expect(scene2.postProcessStages.length).toEqual(2); scene2.renderForSpecs(); expect(scene2).toRender([255, 0, 255, 255]); scene2.postProcessStages.removeAll(); expect(scene2.postProcessStages.length).toEqual(0); expect(scene2.postProcessStages.contains(stage1)).toEqual(false); expect(scene2.postProcessStages.contains(stage2)).toEqual(false); expect(stage1.isDestroyed()).toEqual(true); expect(stage2.isDestroyed()).toEqual(true); scene2.renderForSpecs(); expect(scene2).toRender([0, 0, 0, 255]); expect(scene2.postProcessStages.remove(stage1)).toEqual(false); }); it("gets by stage name", function() { const stage1 = scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 1.0, 0.0, 1.0); }" }) ); const stage2 = scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "uniform sampler2D colorTexture;\nin vec2 v_textureCoordinates;\nvoid main() {\n vec4 color = texture(colorTexture, v_textureCoordinates);\n out_FragColor = vec4(color.r, 0.0, 1.0, 1.0);\n}" }) ); expect(scene2.postProcessStages.getStageByName(stage1.name)).toEqual( stage1 ); expect(scene2.postProcessStages.getStageByName(stage2.name)).toEqual( stage2 ); expect( scene2.postProcessStages.getStageByName("invalid") ).not.toBeDefined(); }); it("gets the output texture by stage name", function() { const stage1 = scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 1.0, 0.0, 1.0); }" }) ); const stage2 = scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "uniform sampler2D colorTexture;\nin vec2 v_textureCoordinates;\nvoid main() {\n vec4 color = texture(colorTexture, v_textureCoordinates);\n out_FragColor = vec4(color.r, 0.0, 1.0, 1.0);\n}" }) ); scene2.postProcessStages.fxaa.enabled = true; scene2.renderForSpecs(); expect( scene2.postProcessStages.getOutputTexture(stage1.name) ).toBeDefined(); expect( scene2.postProcessStages.getOutputTexture(stage2.name) ).toBeDefined(); expect( scene2.postProcessStages.getOutputTexture( scene2.postProcessStages.fxaa.name ) ).toBeDefined(); expect( scene2.postProcessStages.getOutputTexture( scene2.postProcessStages.fxaa.name ) ).toEqual(scene2.postProcessStages.getOutputTexture(stage1.name)); scene2.postProcessStages.remove(stage1); expect( scene2.postProcessStages.getOutputTexture(stage1.name) ).not.toBeDefined(); }); it("shows correct output when single stage is enabled then disabled", function() { const stage = scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 0.0, 1.0, 1.0); }" }) ); scene2.renderForSpecs(); expect(scene2).toRender([255, 0, 255, 255]); stage.enabled = false; scene2.renderForSpecs(); expect(scene2).toRender([0, 0, 0, 255]); }); it("shows correct output when single stage is disabled then enabled", function() { const stage = scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 0.0, 1.0, 1.0); }" }) ); stage.enabled = false; scene2.renderForSpecs(); expect(scene2).toRender([0, 0, 0, 255]); stage.enabled = true; scene2.renderForSpecs(); expect(scene2).toRender([255, 0, 255, 255]); }); it("shows correct output when additional stage is enabled then disabled", function() { scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 0.0, 1.0, 1.0); }" }) ); const stage = scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(0.0, 1.0, 1.0, 1.0); }" }) ); scene2.renderForSpecs(); expect(scene2).toRender([0, 255, 255, 255]); stage.enabled = false; scene2.renderForSpecs(); expect(scene2).toRender([255, 0, 255, 255]); }); it("shows correct output when additional stage is disabled then enabled", function() { scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 0.0, 1.0, 1.0); }" }) ); const stage = scene2.postProcessStages.add( new import__576.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(0.0, 1.0, 1.0, 1.0); }" }) ); stage.enabled = false; scene2.renderForSpecs(); expect(scene2).toRender([255, 0, 255, 255]); stage.enabled = true; scene2.renderForSpecs(); expect(scene2).toRender([0, 255, 255, 255]); }); it("uses Reinhard tonemapping", function() { if (!scene2.highDynamicRangeSupported) { return; } const fs = "void main() { \n out_FragColor = vec4(4.0, 0.0, 0.0, 1.0); \n} \n"; scene2.primitives.add(new ViewportPrimitive_default(fs)); scene2.postProcessStages.tonemapper = import__576.Tonemapper.REINHARD; expect(scene2).toRender([255, 0, 0, 255]); scene2.highDynamicRange = true; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).not.toEqual([255, 0, 0, 255]); expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); scene2.highDynamicRange = false; }); it("uses modified Reinhard tonemapping", function() { if (!scene2.highDynamicRangeSupported) { return; } const fs = "void main() { \n out_FragColor = vec4(0.5, 0.0, 0.0, 1.0); \n} \n"; scene2.primitives.add(new ViewportPrimitive_default(fs)); scene2.postProcessStages.tonemapper = import__576.Tonemapper.MODIFIED_REINHARD; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).toEqualEpsilon([127, 0, 0, 255], 5); }); scene2.highDynamicRange = true; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).not.toEqual([127, 0, 0, 255]); expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); scene2.highDynamicRange = false; }); it("uses filmic tonemapping", function() { if (!scene2.highDynamicRangeSupported) { return; } const fs = "void main() { \n out_FragColor = vec4(4.0, 0.0, 0.0, 1.0); \n} \n"; scene2.primitives.add(new ViewportPrimitive_default(fs)); scene2.postProcessStages.tonemapper = import__576.Tonemapper.FILMIC; expect(scene2).toRender([255, 0, 0, 255]); scene2.highDynamicRange = true; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).not.toEqual([255, 0, 0, 255]); expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); scene2.highDynamicRange = false; }); it("uses ACES tonemapping", function() { if (!scene2.highDynamicRangeSupported) { return; } const fs = "void main() { \n out_FragColor = vec4(4.0, 0.0, 0.0, 1.0); \n} \n"; scene2.primitives.add(new ViewportPrimitive_default(fs)); scene2.postProcessStages.tonemapper = import__576.Tonemapper.ACES; expect(scene2).toRender([255, 0, 0, 255]); scene2.highDynamicRange = true; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).not.toEqual([255, 0, 0, 255]); expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); scene2.highDynamicRange = false; }); it("destroys", function() { const stages = new import__576.PostProcessStageCollection(); const stage = stages.add( new import__576.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0); }" }) ); expect(stages.isDestroyed()).toEqual(false); stages.destroy(); expect(stages.isDestroyed()).toEqual(true); expect(stage.isDestroyed()).toEqual(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/PostProcessStageCompositeSpec.js var import__577 = __toESM(require_Cesium(), 1); describe( "Scene/PostProcessStageComposite", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); scene2.postProcessStages.fxaa.enabled = false; }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.postProcessStages.removeAll(); }); it("constructs", function() { const stage = new import__577.PostProcessStage({ fragmentShader: "uniform vec4 color; void main() { out_FragColor = color; }", uniforms: { color: import__577.Color.clone(import__577.Color.RED) } }); const uniforms = { color: { get: function() { return stage.uniforms.color; }, set: function(value) { stage.uniforms.color = value; } } }; const inputPreviousStageTexture = false; const name = "kaleidoscope"; const composite = new import__577.PostProcessStageComposite({ stages: [stage], uniforms, inputPreviousStageTexture, name }); expect(composite.ready).toEqual(false); expect(composite.name).toEqual(name); expect(composite.enabled).toEqual(true); expect(composite.uniforms).toEqual(uniforms); expect(composite.inputPreviousStageTexture).toEqual( inputPreviousStageTexture ); expect(composite.length).toEqual(1); }); it("default constructs", function() { const stage1 = new import__577.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0); }" }); const stage2 = new import__577.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 0.0, 0.0, 1.0); }" }); const composite = new import__577.PostProcessStageComposite({ stages: [stage1, stage2] }); expect(composite.ready).toEqual(false); expect(composite.name).toBeDefined(); expect(composite.enabled).toEqual(true); expect(composite.uniforms).not.toBeDefined(); expect(composite.inputPreviousStageTexture).toEqual(true); expect(composite.length).toEqual(2); }); it("throws without stages", function() { expect(function() { return new import__577.PostProcessStageComposite(); }).toThrowDeveloperError(); expect(function() { return new import__577.PostProcessStageComposite({ stages: [] }); }).toThrowDeveloperError(); }); it("gets stages", function() { const stage1 = new import__577.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0); }" }); const stage2 = new import__577.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 0.0, 0.0, 1.0); }" }); const composite = new import__577.PostProcessStageComposite({ stages: [stage1, stage2] }); expect(composite.get(0)).toEqual(stage1); expect(composite.get(1)).toEqual(stage2); }); it("throws when get index is invalid", function() { const stage1 = new import__577.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0); }" }); const stage2 = new import__577.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 0.0, 0.0, 1.0); }" }); const composite = new import__577.PostProcessStageComposite({ stages: [stage1, stage2] }); expect(function() { return composite.get(-1); }).toThrowDeveloperError(); expect(function() { return composite.get(composite.length + 1); }).toThrowDeveloperError(); }); it("renders with inputPreviousStageTexture is true", function() { const stage1 = new import__577.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0); }" }); const stage2 = new import__577.PostProcessStage({ fragmentShader: "uniform sampler2D colorTexture;\nin vec2 v_textureCoordinates;\nvoid main() {\n vec4 color = texture(colorTexture, v_textureCoordinates);\n out_FragColor = vec4(color.r, 0.0, 1.0, 1.0);\n}" }); const composite = new import__577.PostProcessStageComposite({ stages: [stage1, stage2] }); expect(scene2).toRender([0, 0, 0, 255]); scene2.postProcessStages.add(composite); scene2.renderForSpecs(); expect(scene2).toRender([255, 0, 255, 255]); }); it("renders with inputPreviousStageTexture is false", function() { const stage1 = new import__577.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0); }" }); const stage2 = new import__577.PostProcessStage({ fragmentShader: "uniform sampler2D colorTexture;\nin vec2 v_textureCoordinates;\nvoid main() {\n vec4 color = texture(colorTexture, v_textureCoordinates);\n out_FragColor = vec4(color.r, 0.0, 1.0, 1.0);\n}" }); const composite = new import__577.PostProcessStageComposite({ stages: [stage1, stage2], inputPreviousStageTexture: false }); expect(scene2).toRender([0, 0, 0, 255]); scene2.postProcessStages.add(composite); scene2.renderForSpecs(); expect(scene2).toRender([0, 0, 255, 255]); }); it("does not run a stage that requires depth textures when depth textures are not supported", function() { const s = createScene_default({ contextOptions: { requestWebgl1: true } }); s.context._depthTexture = false; if ((0, import__577.defined)(s._view.globeDepth)) { s._view.globeDepth.destroy(); s._view.globeDepth = void 0; if ((0, import__577.defined)(s._view.oit)) { s._view.oit.destroy(); s._view.oit = void 0; } } expect(s).toRender([0, 0, 0, 255]); const bgColor = 51; s.postProcessStages.add( new import__577.PostProcessStage({ fragmentShader: `void main() { out_FragColor = vec4(vec3(${bgColor / 255}), 1.0); }` }) ); const stage = s.postProcessStages.add( new import__577.PostProcessStageComposite({ stages: [ new import__577.PostProcessStage({ fragmentShader: "uniform sampler2D depthTexture; void main() { out_FragColor = vec4(1.0); }" }) ] }) ); return pollToPromise_default(function() { s.renderForSpecs(); return stage.ready; }).then(function() { expect(s).toRender([bgColor, bgColor, bgColor, 255]); }).finally(function(e) { s.destroyForSpecs(); if (e) { return Promise.reject(e); } }); }); it("destroys", function() { const stage1 = new import__577.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0); }" }); const stage2 = new import__577.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 0.0, 0.0, 1.0); }" }); const composite = new import__577.PostProcessStageComposite({ stages: [stage1, stage2] }); expect(stage1.isDestroyed()).toEqual(false); expect(stage2.isDestroyed()).toEqual(false); expect(composite.isDestroyed()).toEqual(false); composite.destroy(); expect(composite.isDestroyed()).toEqual(true); expect(stage1.isDestroyed()).toEqual(true); expect(stage2.isDestroyed()).toEqual(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/PostProcessStageLibrarySpec.js var import__579 = __toESM(require_Cesium(), 1); // packages/engine/Specs/Scene/Model/loadAndZoomToModelAsync.js var import__578 = __toESM(require_Cesium(), 1); async function loadAndZoomToModelAsync(options, scene2) { const model = await import__578.Model.fromGltfAsync(options); scene2.primitives.add(model); await pollToPromise_default( function() { scene2.renderForSpecs(); return model.ready; }, { timeout: 1e4 } ); scene2.camera.flyToBoundingSphere(model.boundingSphere, { duration: 0, offset: options.offset }); return model; } var loadAndZoomToModelAsync_default = loadAndZoomToModelAsync; // packages/engine/Specs/Scene/PostProcessStageLibrarySpec.js describe( "Scene/PostProcessStageLibrary", function() { const boxTexturedUrl = "./Data/Models/glTF-2.0/BoxTextured/glTF/BoxTextured.gltf"; let scene2; let originalBloomBrightness; beforeAll(function() { scene2 = createScene_default({ canvas: createCanvas_default(3, 3) }); originalBloomBrightness = scene2.postProcessStages.bloom.uniforms.brightness; }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.postProcessStages.removeAll(); scene2.primitives.removeAll(); scene2.postProcessStages.fxaa.enabled = false; scene2.postProcessStages.bloom.enabled = false; scene2.postProcessStages.bloom.uniforms.brightness = originalBloomBrightness; scene2.postProcessStages.ambientOcclusion.enabled = false; scene2.renderForSpecs(); }); it("black and white", function() { const fs = "void main() { \n out_FragColor = vec4(1.0, 0.0, 0.0, 1.0); \n} \n"; scene2.primitives.add(new ViewportPrimitive_default(fs)); expect(scene2).toRenderAndCall(function(rgba) { for (let i = 0; i < 3; ++i) { for (let j = 0; j < 3; ++j) { const k = i * 4 * 3 + 4 * j; expect(rgba[k]).toEqual(255); expect(rgba[k + 1]).toEqual(0); expect(rgba[k + 2]).toEqual(0); expect(rgba[k + 3]).toEqual(255); } } }); scene2.postProcessStages.add( import__579.PostProcessStageLibrary.createBlackAndWhiteStage() ); scene2.renderForSpecs(); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toEqual(rgba[0]); expect(rgba[2]).toEqual(rgba[0]); expect(rgba[3]).toEqual(255); for (let i = 0; i < 3; ++i) { for (let j = 0; j < 3; ++j) { const k = i * 4 * 3 + 4 * j; expect(rgba[k]).toEqual(rgba[0]); expect(rgba[k + 1]).toEqual(rgba[1]); expect(rgba[k + 2]).toEqual(rgba[2]); expect(rgba[k + 3]).toEqual(rgba[3]); } } }); }); it("per-feature black and white", function() { return loadAndZoomToModelAsync_default( { url: boxTexturedUrl }, scene2 ).then(function(model) { const stage = scene2.postProcessStages.add( import__579.PostProcessStageLibrary.createBlackAndWhiteStage() ); stage.selected = []; return pollToPromise_default(function() { scene2.renderForSpecs(); return stage.ready; }).then(function() { let color; expect(scene2).toRenderAndCall(function(rgba) { color = rgba; expect(rgba[1]).toEqual(rgba[0]); expect(rgba[2]).toEqual(rgba[0]); expect(rgba[3]).toEqual(255); }); stage.selected = [model]; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual(color); }); }); }); }); it("brightness", function() { const fs = "void main() { \n out_FragColor = vec4(vec3(0.25), 1.0); \n} \n"; scene2.primitives.add(new ViewportPrimitive_default(fs)); let red; let green; let blue; expect(scene2).toRenderAndCall(function(rgba) { for (let i = 0; i < 3; ++i) { for (let j = 0; j < 3; ++j) { const k = i * 4 * 3 + 4 * j; expect(rgba[k]).toEqualEpsilon(Math.floor(255 * 0.25), 1); expect(rgba[k + 1]).toEqual(rgba[k]); expect(rgba[k + 2]).toEqual(rgba[k]); expect(rgba[k + 3]).toEqual(255); } } red = rgba[0]; green = rgba[1]; blue = rgba[2]; }); scene2.postProcessStages.add( import__579.PostProcessStageLibrary.createBrightnessStage() ); scene2.renderForSpecs(); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).not.toEqual(red); expect(rgba[1]).not.toEqual(green); expect(rgba[2]).not.toEqual(blue); expect(rgba[3]).toEqual(255); for (let i = 0; i < 3; ++i) { for (let j = 0; j < 3; ++j) { const k = i * 4 * 3 + 4 * j; expect(rgba[k]).toEqual(rgba[0]); expect(rgba[k + 1]).toEqual(rgba[1]); expect(rgba[k + 2]).toEqual(rgba[2]); expect(rgba[k + 3]).toEqual(rgba[3]); } } }); }); it("night vision", function() { const fs = "void main() { \n out_FragColor = vec4(1.0, 0.0, 0.0, 1.0); \n} \n"; scene2.primitives.add(new ViewportPrimitive_default(fs)); expect(scene2).toRenderAndCall(function(rgba) { for (let i = 0; i < 3; ++i) { for (let j = 0; j < 3; ++j) { const k = i * 4 * 3 + 4 * j; expect(rgba[k]).toEqual(255); expect(rgba[k + 1]).toEqual(0); expect(rgba[k + 2]).toEqual(0); expect(rgba[k + 3]).toEqual(255); } } }); scene2.postProcessStages.add( import__579.PostProcessStageLibrary.createNightVisionStage() ); scene2.renderForSpecs(); expect(scene2).toRenderAndCall(function(rgba) { for (let i = 0; i < 3; ++i) { for (let j = 0; j < 3; ++j) { const k = i * 4 * 3 + 4 * j; expect(rgba[k]).toEqual(0); expect(rgba[k + 1]).toBeGreaterThan(0); expect(rgba[k + 2]).toEqual(0); expect(rgba[k + 3]).toEqual(255); } } }); }); it("depth view", function() { if (!scene2.context.depthTexture) { return; } const fs = "void main() { \n out_FragColor = vec4(1.0, 0.0, 0.0, 1.0); \n} \n"; scene2.primitives.add(new ViewportPrimitive_default(fs)); expect(scene2).toRenderAndCall(function(rgba) { for (let i = 0; i < 3; ++i) { for (let j = 0; j < 3; ++j) { const k = i * 4 * 3 + 4 * j; expect(rgba[k]).toEqual(255); expect(rgba[k + 1]).toEqual(0); expect(rgba[k + 2]).toEqual(0); expect(rgba[k + 3]).toEqual(255); } } }); scene2.postProcessStages.add( import__579.PostProcessStageLibrary.createDepthViewStage() ); scene2.renderForSpecs(); expect(scene2).toRenderAndCall(function(rgba) { for (let i = 0; i < 3; ++i) { for (let j = 0; j < 3; ++j) { const k = i * 4 * 3 + 4 * j; expect(rgba[k]).toEqual(255); expect(rgba[k + 1]).toEqual(255); expect(rgba[k + 2]).toEqual(255); expect(rgba[k + 3]).toEqual(255); } } }); }); it("blur", function() { const fs = "void main() { \n out_FragColor = all(equal(floor(gl_FragCoord.xy), vec2(1.0, 1.0))) ? vec4(1.0, 0.0, 0.0, 1.0) : vec4(0.0, 0.0, 1.0, 1.0); \n} \n"; scene2.primitives.add(new ViewportPrimitive_default(fs)); expect(scene2).toRenderAndCall(function(rgba) { for (let i = 0; i < 3; ++i) { for (let j = 0; j < 3; ++j) { if (i === 1 && j === 1) { continue; } const k = i * 4 * 3 + 4 * j; expect(rgba[k]).toEqual(0); expect(rgba[k + 1]).toEqual(0); expect(rgba[k + 2]).toEqual(255); expect(rgba[k + 3]).toEqual(255); } } expect(rgba[16]).toEqual(255); expect(rgba[17]).toEqual(0); expect(rgba[18]).toEqual(0); expect(rgba[19]).toEqual(255); }); scene2.postProcessStages.add(import__579.PostProcessStageLibrary.createBlurStage()); scene2.renderForSpecs(); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[16]).toBeGreaterThan(0); expect(rgba[17]).toEqual(0); expect(rgba[18]).toBeGreaterThan(0); expect(rgba[19]).toEqual(255); }); }); it("blur uniforms", function() { const blur = import__579.PostProcessStageLibrary.createBlurStage(); expect(blur.uniforms.delta).toEqual(1); expect(blur.uniforms.sigma).toEqual(2); expect(blur.uniforms.stepSize).toEqual(1); blur.uniforms.delta = 2; blur.uniforms.sigma = 3; blur.uniforms.stepSize = 2; expect(blur.uniforms.delta).toEqual(2); expect(blur.uniforms.sigma).toEqual(3); expect(blur.uniforms.stepSize).toEqual(2); }); it("depth of field", function() { if (!scene2.context.depthTexture) { return; } const origin = import__579.Cartesian3.fromDegrees(-123.0744619, 44.0503706, 100); const modelMatrix = import__579.Transforms.headingPitchRollToFixedFrame( origin, new import__579.HeadingPitchRoll() ); return loadAndZoomToModelAsync_default( { url: boxTexturedUrl, // Ensure the texture loads every time incrementallyLoadTextures: false, modelMatrix }, scene2 ).then(function() { scene2.camera.lookAt(origin, new import__579.HeadingPitchRange(0, 0, 1.5)); let originalColor; expect(scene2).toRenderAndCall(function(rgba) { originalColor = rgba; for (let i = 0; i < rgba.length; i += 4) { expect(rgba[i]).toBeGreaterThan(0); expect(rgba[i + 1]).toBeGreaterThan(0); expect(rgba[i + 2]).toBeGreaterThan(0); expect(rgba[i + 3]).toEqual(255); } }); scene2.postProcessStages.add( import__579.PostProcessStageLibrary.createDepthOfFieldStage() ); scene2.renderForSpecs(); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual(originalColor); for (let i = 0; i < rgba.length; i += 4) { expect(rgba[i]).toBeGreaterThan(0); expect(rgba[i + 1]).toBeGreaterThan(0); expect(rgba[i + 2]).toBeGreaterThan(0); expect(rgba[i + 3]).toEqual(255); } }); }); }); it("depth of field uniforms", function() { const dof = import__579.PostProcessStageLibrary.createDepthOfFieldStage(); expect(dof.uniforms.focalDistance).toEqual(5); expect(dof.uniforms.delta).toEqual(1); expect(dof.uniforms.sigma).toEqual(2); expect(dof.uniforms.stepSize).toEqual(1); dof.uniforms.focalDistance = 6; dof.uniforms.delta = 2; dof.uniforms.sigma = 3; dof.uniforms.stepSize = 2; expect(dof.uniforms.focalDistance).toEqual(6); expect(dof.uniforms.delta).toEqual(2); expect(dof.uniforms.sigma).toEqual(3); expect(dof.uniforms.stepSize).toEqual(2); }); it("ambient occlusion", function() { if (!scene2.context.depthTexture) { return; } scene2.postProcessStages.ambientOcclusion.enabled = true; scene2.postProcessStages.ambientOcclusion.uniforms.ambientOcclusionOnly = true; scene2.renderForSpecs(); expect(scene2).toRenderAndCall(function(rgba) { for (let i = 0; i < rgba.length; i += 4) { expect(rgba[i]).toEqual(255); expect(rgba[i + 1]).toEqual(255); expect(rgba[i + 2]).toEqual(255); expect(rgba[i + 3]).toEqual(255); } }); }); it("ambient occlusion uniforms", function() { const ao = import__579.PostProcessStageLibrary.createAmbientOcclusionStage(); expect(ao.uniforms.ambientOcclusionOnly).toEqual(false); expect(ao.uniforms.intensity).toEqual(3); expect(ao.uniforms.bias).toEqual(0.1); expect(ao.uniforms.lengthCap).toEqual(0.26); expect(ao.uniforms.stepSize).toEqual(1.95); expect(ao.uniforms.frustumLength).toEqual(1e3); expect(ao.uniforms.randomTexture).not.toBeDefined(); expect(ao.uniforms.delta).toEqual(1); expect(ao.uniforms.sigma).toEqual(2); expect(ao.uniforms.blurStepSize).toEqual(0.86); ao.uniforms.ambientOcclusionOnly = true; ao.uniforms.intensity = 4; ao.uniforms.bias = 0.2; ao.uniforms.lengthCap = 0.3; ao.uniforms.stepSize = 2; ao.uniforms.frustumLength = 1001; ao.uniforms.delta = 2; ao.uniforms.sigma = 3; ao.uniforms.blurStepSize = 2; expect(ao.uniforms.ambientOcclusionOnly).toEqual(true); expect(ao.uniforms.intensity).toEqual(4); expect(ao.uniforms.bias).toEqual(0.2); expect(ao.uniforms.lengthCap).toEqual(0.3); expect(ao.uniforms.stepSize).toEqual(2); expect(ao.uniforms.frustumLength).toEqual(1001); expect(ao.uniforms.delta).toEqual(2); expect(ao.uniforms.sigma).toEqual(3); expect(ao.uniforms.blurStepSize).toEqual(2); }); it("bloom", function() { const origin = import__579.Cartesian3.fromDegrees(-123.0744619, 44.0503706, 100); const modelMatrix = import__579.Transforms.headingPitchRollToFixedFrame( origin, new import__579.HeadingPitchRoll() ); return loadAndZoomToModelAsync_default( { url: boxTexturedUrl, // Ensure the texture loads every time incrementallyLoadTextures: false, modelMatrix }, scene2 ).then(function() { scene2.camera.lookAt(origin, new import__579.HeadingPitchRange(0, 0, 1.5)); let originalColor; expect(scene2).toRenderAndCall(function(rgba) { originalColor = rgba; for (let i = 0; i < rgba.length; i += 4) { expect(rgba[i]).toBeGreaterThan(0); expect(rgba[i + 1]).toBeGreaterThan(0); expect(rgba[i + 2]).toBeGreaterThan(0); expect(rgba[i + 3]).toEqual(255); } }); const bloom = scene2.postProcessStages.bloom; bloom.enabled = true; bloom.uniforms.brightness = 0.5; scene2.renderForSpecs(); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual(originalColor); for (let i = 0; i < rgba.length; i += 4) { expect(rgba[i]).toBeGreaterThan(0); expect(rgba[i + 1]).toBeGreaterThan(0); expect(rgba[i + 2]).toBeGreaterThan(0); expect(rgba[i + 3]).toEqual(255); } }); }); }); it("bloom uniforms", function() { const bloom = import__579.PostProcessStageLibrary.createBloomStage(); expect(bloom.uniforms.glowOnly).toEqual(false); expect(bloom.uniforms.contrast).toEqual(128); expect(bloom.uniforms.brightness).toEqual(-0.3); expect(bloom.uniforms.delta).toEqual(1); expect(bloom.uniforms.sigma).toEqual(2); expect(bloom.uniforms.stepSize).toEqual(1); bloom.uniforms.glowOnly = true; bloom.uniforms.contrast = 0; bloom.uniforms.brightness = 3; bloom.uniforms.delta = 2; bloom.uniforms.sigma = 3; bloom.uniforms.stepSize = 2; expect(bloom.uniforms.glowOnly).toEqual(true); expect(bloom.uniforms.contrast).toEqual(0); expect(bloom.uniforms.brightness).toEqual(3); expect(bloom.uniforms.delta).toEqual(2); expect(bloom.uniforms.sigma).toEqual(3); expect(bloom.uniforms.stepSize).toEqual(2); }); }, "WebGL" ); // packages/engine/Specs/Scene/PostProcessStageSpec.js var import__580 = __toESM(require_Cesium(), 1); describe( "Scene/PostProcessStage", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); scene2.postProcessStages.fxaa.enabled = false; }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.postProcessStages.removeAll(); scene2.primitives.removeAll(); }); it("constructs", function() { const fragmentShader = "uniform vec4 color; void main() { out_FragColor = color; }"; const uniforms = { color: import__580.Color.clone(import__580.Color.RED) }; const textureScale = 0.5; const forcePowerOfTwo = true; const sampleMode = import__580.PostProcessStageSampleMode.LINEAR; const pixelFormat = import__580.PixelFormat.RGB; const pixelDatatype = import__580.PixelDatatype.UNSIGNED_INT; const clearColor = import__580.Color.clone(import__580.Color.BLUE); const scissorRectangle = new import__580.BoundingRectangle(0, 0, 5, 5); const name = "wonka vision"; const stage = new import__580.PostProcessStage({ fragmentShader, uniforms, textureScale, forcePowerOfTwo, sampleMode, pixelFormat, pixelDatatype, clearColor, scissorRectangle, name }); expect(stage.fragmentShader).toEqual(fragmentShader); expect(stage.uniforms.color).toBeDefined(); expect(stage.textureScale).toEqual(textureScale); expect(stage.forcePowerOfTwo).toEqual(forcePowerOfTwo); expect(stage.sampleMode).toEqual(sampleMode); expect(stage.pixelFormat).toEqual(stage.pixelFormat); expect(stage.pixelDatatype).toEqual(pixelDatatype); expect(stage.clearColor).toEqual(clearColor); expect(stage.scissorRectangle).toEqual(scissorRectangle); expect(stage.name).toEqual(name); expect(stage.outputTexture).not.toBeDefined(); }); it("default constructs", function() { const fragmentShader = "void main() { out_FragColor = vec4(1.0); }"; const stage = new import__580.PostProcessStage({ fragmentShader }); expect(stage.fragmentShader).toEqual(fragmentShader); expect(stage.uniforms).not.toBeDefined(); expect(stage.textureScale).toEqual(1); expect(stage.forcePowerOfTwo).toEqual(false); expect(stage.sampleMode).toEqual(import__580.PostProcessStageSampleMode.NEAREST); expect(stage.pixelFormat).toEqual(import__580.PixelFormat.RGBA); expect(stage.pixelDatatype).toEqual(import__580.PixelDatatype.UNSIGNED_BYTE); expect(stage.clearColor).toEqual(import__580.Color.BLACK); expect(stage.scissorRectangle).toEqual(new import__580.BoundingRectangle()); expect(stage.name).toBeDefined(); expect(stage.outputTexture).not.toBeDefined(); }); it("throws without fragment shader", function() { expect(function() { return new import__580.PostProcessStage(); }).toThrowDeveloperError(); }); it("throws with invalid texture scale", function() { const fs = "void main() { out_FragColor = vec4(1.0); }"; expect(function() { return new import__580.PostProcessStage({ fragmentShader: fs, textureScale: -1 }); }).toThrowDeveloperError(); expect(function() { return new import__580.PostProcessStage({ fragmentShader: fs, textureScale: 2 }); }).toThrowDeveloperError(); }); it("throws if pixel format is not a color format", function() { expect(function() { return new import__580.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0); }", pixelFormat: import__580.PixelFormat.DEPTH_STENCIL }); }).toThrowDeveloperError(); }); it("executes", function() { expect(scene2).toRender([0, 0, 0, 255]); scene2.postProcessStages.add( new import__580.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0, 1.0, 0.0, 1.0); }" }) ); scene2.renderForSpecs(); expect(scene2).toRender([255, 255, 0, 255]); }); it("can use a texture uniform", function() { expect(scene2).toRender([0, 0, 0, 255]); const stage = scene2.postProcessStages.add( new import__580.PostProcessStage({ fragmentShader: "uniform sampler2D inputTexture; in vec2 v_textureCoordinates; void main() { out_FragColor = texture(inputTexture, v_textureCoordinates); }", uniforms: { inputTexture: "./Data/Images/Green2x2.png" } }) ); return pollToPromise_default(function() { scene2.renderForSpecs(); return stage.ready; }).then(function() { expect(scene2).toRender([0, 255, 0, 255]); stage.uniforms.inputTexture = "./Data/Images/Blue2x2.png"; return pollToPromise_default(function() { scene2.renderForSpecs(); return stage.ready; }).then(function() { expect(scene2).toRender([0, 0, 255, 255]); }); }); }); it("can use a image uniform", function() { let ready = false; const image = new Image(); image.src = "./Data/Images/Blue2x2.png"; image.onload = function() { ready = true; }; return pollToPromise_default(function() { return ready; }).then(function() { expect(scene2).toRender([0, 0, 0, 255]); const stage = scene2.postProcessStages.add( new import__580.PostProcessStage({ fragmentShader: "uniform sampler2D inputTexture; void main() { out_FragColor = texture(inputTexture, vec2(0.5)); }", uniforms: { inputTexture: image } }) ); return pollToPromise_default(function() { scene2.renderForSpecs(); return stage.ready; }).then(function() { expect(scene2).toRender([0, 0, 255, 255]); }); }); }); it("does not run a stage that requires depth textures when depth textures are not supported", function() { const s = createScene_default({ contextOptions: { requestWebgl1: true } }); s.context._depthTexture = false; if ((0, import__580.defined)(s._view.globeDepth)) { s._view.globeDepth.destroy(); s._view.globeDepth = void 0; if ((0, import__580.defined)(s._view.oit)) { s._view.oit.destroy(); s._view.oit = void 0; } } expect(s).toRender([0, 0, 0, 255]); const bgColor = 51; s.postProcessStages.add( new import__580.PostProcessStage({ fragmentShader: `void main() { out_FragColor = vec4(vec3(${bgColor / 255}), 1.0); }` }) ); const stage = s.postProcessStages.add( new import__580.PostProcessStage({ fragmentShader: "uniform sampler2D depthTexture; void main() { out_FragColor = vec4(1.0); }" }) ); return pollToPromise_default(function() { s.renderForSpecs(); return stage.ready; }).then(function() { expect(s).toRender([bgColor, bgColor, bgColor, 255]); }).finally(function(e) { s.destroyForSpecs(); if (e) { return Promise.reject(e); } }); }); it("per-feature post process stage", function() { const offset = new import__580.HeadingPitchRange(0, -import__580.Math.PI_OVER_FOUR, 2); return loadAndZoomToModelAsync_default( { url: "./Data/Models/glTF-2.0/BoxTextured/glTF/BoxTextured.gltf", offset, incrementallyLoadTextures: false }, scene2 ).then(function(model) { const fs = "uniform sampler2D colorTexture; \nin vec2 v_textureCoordinates; \nvoid main() { \n if (czm_selected(v_textureCoordinates)) { \n out_FragColor = texture(colorTexture, v_textureCoordinates); \n } else { \n out_FragColor = vec4(1.0, 0.0, 0.0, 1.0); \n } \n} \n"; const stage = scene2.postProcessStages.add( new import__580.PostProcessStage({ fragmentShader: fs }) ); stage.selected = []; return pollToPromise_default(function() { scene2.renderForSpecs(); return stage.ready; }).then(function() { expect(scene2).toRender([255, 0, 0, 255]); stage.selected = [model]; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([255, 0, 0, 255]); }); }); }); }); it("destroys", function() { const stage = new import__580.PostProcessStage({ fragmentShader: "void main() { out_FragColor = vec4(1.0); }" }); expect(stage.isDestroyed()).toEqual(false); stage.destroy(); expect(stage.isDestroyed()).toEqual(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/PrimitiveCollectionSpec.js var import__581 = __toESM(require_Cesium(), 1); describe( "Scene/PrimitiveCollection", function() { let scene2; let context; let rectangle; let primitives; beforeAll(function() { scene2 = createScene_default(); scene2.primitives.destroyPrimitives = false; context = scene2.context; rectangle = import__581.Rectangle.fromDegrees(-80, 20, -70, 30); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { primitives = new import__581.PrimitiveCollection(); }); afterEach(function() { scene2.primitives.removeAll(); primitives = primitives && !primitives.isDestroyed() && primitives.destroy(); }); function allLabelsReady(labels) { return pollToPromise_default(function() { scene2.renderForSpecs(); const backgroundBillboard = labels._backgroundBillboardCollection.get( 0 ); return (!(0, import__581.defined)(backgroundBillboard) || backgroundBillboard.ready) && labels._labelsToUpdate.length === 0; }); } function createLabels(position) { position = (0, import__581.defaultValue)(position, { x: -1, y: 0, z: 0 }); const labels = new import__581.LabelCollection(); labels.add({ position, text: "x", horizontalOrigin: import__581.HorizontalOrigin.CENTER, verticalOrigin: import__581.VerticalOrigin.CENTER }); return labels; } function createRectangle() { return new import__581.Primitive({ geometryInstances: new import__581.GeometryInstance({ geometry: new import__581.RectangleGeometry({ rectangle }), attributes: { color: new import__581.ColorGeometryInstanceAttribute(1, 1, 0, 0.5) } }), appearance: new import__581.PerInstanceColorAppearance(), releaseGeometryInstances: true, asynchronous: false }); } function verifyLabelsRender(primitives2, labels, color) { scene2.primitives.removeAll(); scene2.camera.setView({ destination: rectangle }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitives2); return allLabelsReady(labels).then(function() { if ((0, import__581.defined)(color)) { expect(scene2).toRender(color); } else { expect(scene2).notToRender([0, 0, 0, 255]); } }); } function verifyPrimitivesRender(primitives2, color) { scene2.primitives.removeAll(); scene2.camera.setView({ destination: rectangle }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitives2); if ((0, import__581.defined)(color)) { expect(scene2).toRender(color); } else { expect(scene2).notToRender([0, 0, 0, 255]); } } it("constructs with options", function() { const collection = new import__581.PrimitiveCollection({ show: false, destroyPrimitives: false }); expect(collection.show).toEqual(false); expect(collection.destroyPrimitives).toEqual(false); collection.destroy(); }); it("gets default show", function() { expect(primitives.show).toEqual(true); }); it("get throws if index is undefined", function() { expect(function() { primitives.get(void 0); }).toThrowDeveloperError(); }); it("has zero primitives when constructed", function() { expect(primitives.length).toEqual(0); }); it("adds a primitive with add()", function() { const p = createLabels(); expect(primitives.add(p)).toBe(p); expect(primitives.length).toEqual(1); }); it("add works with an index", function() { const p0 = createLabels(); const p1 = createLabels(); expect(function() { primitives.add(p0, 1); }).toThrowDeveloperError(); expect(function() { primitives.add(p0, -1); }).toThrowDeveloperError(); primitives.add(p0, 0); expect(primitives.get(0)).toBe(p0); expect(function() { primitives.add(p1, -1); }).toThrowDeveloperError(); expect(function() { primitives.add(p1, 2); }).toThrowDeveloperError(); primitives.add(p1, 0); expect(primitives.get(0)).toBe(p1); }); it("removes the first primitive", function() { const p0 = createLabels(); const p1 = createLabels(); primitives.add(p0); primitives.add(p1); expect(primitives.length).toEqual(2); expect(primitives.remove(p0)).toEqual(true); expect(primitives.length).toEqual(1); expect(primitives.get(0)).toBe(p1); expect(primitives.remove(p1)).toEqual(true); expect(primitives.length).toEqual(0); }); it("removes the last primitive", function() { const p0 = createLabels(); const p1 = createLabels(); primitives.add(p0); primitives.add(p1); expect(primitives.length).toEqual(2); expect(primitives.remove(p1)).toEqual(true); expect(primitives.length).toEqual(1); expect(primitives.get(0)).toBe(p0); expect(primitives.remove(p0)).toEqual(true); expect(primitives.length).toEqual(0); }); it("removes a primitive twice", function() { const p0 = createLabels(); primitives.add(p0); expect(primitives.remove(p0)).toEqual(true); expect(primitives.remove(p0)).toEqual(false); }); it("removes null", function() { expect(primitives.remove()).toEqual(false); }); it("removes all primitives", function() { primitives.add(createLabels()); primitives.add(createLabels()); primitives.add(createLabels()); expect(primitives.length).toEqual(3); primitives.removeAll(); expect(primitives.length).toEqual(0); }); it("contains a primitive", function() { const labels = createLabels(); primitives.add(labels); expect(primitives.contains(labels)).toEqual(true); }); it("does not contain a primitive", function() { const labels0 = createLabels(); const labels1 = createLabels(); primitives.add(labels0); expect(primitives.contains(labels1)).toEqual(false); }); it("does not contain removed primitive", function() { const labels0 = createLabels(); primitives.add(labels0); primitives.remove(labels0); expect(primitives.contains(labels0)).toEqual(false); }); it("does not contain all removed primitives", function() { const labels0 = createLabels(); primitives.add(labels0); primitives.removeAll(); expect(primitives.contains(labels0)).toEqual(false); }); it("does not contain undefined", function() { expect(primitives.contains()).toEqual(false); }); it("adds and removes a primitive in two composites", function() { const p = createLabels(); primitives.add(p); primitives.destroyPrimitives = false; const otherPrimitives = new import__581.PrimitiveCollection(); otherPrimitives.add(p); otherPrimitives.destroyPrimitives = false; expect(primitives.contains(p)).toEqual(true); expect(otherPrimitives.contains(p)).toEqual(true); expect(primitives.remove(p)).toEqual(true); expect(primitives.contains(p)).toEqual(false); expect(otherPrimitives.contains(p)).toEqual(true); expect(otherPrimitives.remove(p)).toEqual(true); expect(primitives.contains(p)).toEqual(false); expect(otherPrimitives.contains(p)).toEqual(false); expect(primitives.remove(p)).toEqual(false); expect(otherPrimitives.remove(p)).toEqual(false); p.destroy(); otherPrimitives.destroy(); }); it("does not remove from a second composite", function() { const p = createLabels(); primitives.add(p); const otherPrimitives = new import__581.PrimitiveCollection(); expect(otherPrimitives.contains(p)).toEqual(false); expect(otherPrimitives.remove(p)).toEqual(false); otherPrimitives.destroy(); }); it("gets default destroyPrimitives", function() { expect(primitives.destroyPrimitives).toEqual(true); }); it("renders a primitive added with add()", function() { const labels = createLabels(); primitives.add(labels); return verifyLabelsRender(primitives, labels); }); it("does not render", function() { primitives.show = false; const labels = createLabels(); primitives.add(labels); verifyPrimitivesRender(primitives, [0, 0, 0, 255]); }); it("renders a primitive in more than one composite", function() { const p = createLabels(); primitives.add(p); const otherPrimitives = new import__581.PrimitiveCollection(); otherPrimitives.destroyPrimitives = false; otherPrimitives.add(p); return verifyLabelsRender(primitives, p).then(function() { verifyPrimitivesRender(otherPrimitives); otherPrimitives.destroy(); }); }); it("renders child composites", function() { const children = new import__581.PrimitiveCollection(); const labels = createLabels(); children.add(labels); primitives.add(children); return verifyLabelsRender(primitives, labels); }); it("picks a primitive added with add()", function() { const labels = createLabels(); const l = labels.get(0); primitives.add(labels); return verifyLabelsRender(primitives, labels).then(function() { expect(scene2).toPickPrimitive(l); }); }); it("does not pick", function() { const labels = createLabels(); primitives.show = false; primitives.add(labels); verifyPrimitivesRender(primitives, [0, 0, 0, 255]); expect(scene2).notToPick(); }); it("picks child composites", function() { const labels = createLabels(); const l = labels.get(0); const children = new import__581.PrimitiveCollection(); children.add(labels); primitives.add(children); return verifyLabelsRender(primitives, labels).then(function() { expect(scene2).toPickPrimitive(l); }); }); it("picks a primitive added with render order (0)", function() { const p0 = createRectangle(); const p1 = createRectangle(); primitives.add(p0); primitives.add(p1); verifyPrimitivesRender(primitives); expect(scene2).toPickPrimitive(p1); }); it("picks a primitive added with render order (1)", function() { const p0 = createRectangle(); const p1 = createRectangle(); primitives.add(p1); primitives.add(p0); verifyPrimitivesRender(primitives); expect(scene2).toPickPrimitive(p0); }); it("picks a primitive added with raise (0)", function() { const p0 = createRectangle(); const p1 = createRectangle(); primitives.add(p0); primitives.add(p1); primitives.raise(p1); verifyPrimitivesRender(primitives); expect(scene2).toPickPrimitive(p1); }); it("picks a primitive added with raise (1)", function() { const p0 = createRectangle(); const p1 = createRectangle(); primitives.add(p0); primitives.add(p1); primitives.raise(p0); verifyPrimitivesRender(primitives); expect(scene2).toPickPrimitive(p0); }); it("picks a primitive added with raiseToTop (0)", function() { const p0 = createRectangle(); const p1 = createRectangle(); primitives.add(p0); primitives.add(p1); primitives.raiseToTop(p1); verifyPrimitivesRender(primitives); expect(scene2).toPickPrimitive(p1); }); it("picks a primitive added with raiseToTop (1)", function() { const p0 = createRectangle(); const p1 = createRectangle(); primitives.add(p0); primitives.add(p1); primitives.raiseToTop(p0); verifyPrimitivesRender(primitives); expect(scene2).toPickPrimitive(p0); }); it("picks a primitive added with lower (0)", function() { const p0 = createRectangle(); const p1 = createRectangle(); primitives.add(p0); primitives.add(p1); primitives.lower(p1); verifyPrimitivesRender(primitives); expect(scene2).toPickPrimitive(p0); }); it("picks a primitive added with lower (1)", function() { const p0 = createRectangle(); const p1 = createRectangle(); primitives.add(p0); primitives.add(p1); primitives.lower(p0); verifyPrimitivesRender(primitives); expect(scene2).toPickPrimitive(p1); }); it("picks a primitive added with lowerToBottom (0)", function() { const p0 = createRectangle(); const p1 = createRectangle(); primitives.add(p0); primitives.add(p1); primitives.lowerToBottom(p1); verifyPrimitivesRender(primitives); expect(scene2).toPickPrimitive(p0); }); it("picks a primitive added with lowerToBottom (1)", function() { const p0 = createRectangle(); const p1 = createRectangle(); primitives.add(p0); primitives.add(p1); primitives.lowerToBottom(p0); verifyPrimitivesRender(primitives); expect(scene2).toPickPrimitive(p1); }); it("is not destroyed when first constructed", function() { expect(primitives.isDestroyed()).toEqual(false); }); it("is destroyed after calling destroy()", function() { primitives.destroy(); expect(primitives.isDestroyed()).toEqual(true); }); it("destroys its primitives", function() { const labels = new import__581.LabelCollection(context); primitives.add(labels); expect(labels.isDestroyed()).toEqual(false); primitives.destroy(); expect(labels.isDestroyed()).toEqual(true); }); it("destroys children", function() { const labels = new import__581.LabelCollection(context); const children = new import__581.PrimitiveCollection(); children.add(labels); primitives.add(children); expect(children.isDestroyed()).toEqual(false); expect(labels.isDestroyed()).toEqual(false); primitives.destroy(); expect(children.isDestroyed()).toEqual(true); expect(labels.isDestroyed()).toEqual(true); }); it("destroys primitive on remove", function() { const labels = new import__581.LabelCollection(context); primitives.add(labels); expect(labels.isDestroyed()).toEqual(false); primitives.remove(labels); expect(labels.isDestroyed()).toEqual(true); }); it("destroys primitive on removeAll", function() { const labels = new import__581.LabelCollection(context); primitives.add(labels); expect(labels.isDestroyed()).toEqual(false); primitives.removeAll(); expect(labels.isDestroyed()).toEqual(true); }); it("does not destroy its primitives", function() { const labels = new import__581.LabelCollection(context); primitives.destroyPrimitives = false; primitives.add(labels); expect(labels.isDestroyed()).toEqual(false); primitives.destroy(); expect(labels.isDestroyed()).toEqual(false); labels.destroy(); expect(labels.isDestroyed()).toEqual(true); }); it("does not destroy primitive on remove", function() { const labels = new import__581.LabelCollection(context); primitives.destroyPrimitives = false; primitives.add(labels); expect(labels.isDestroyed()).toEqual(false); primitives.remove(labels); expect(labels.isDestroyed()).toEqual(false); labels.destroy(); expect(labels.isDestroyed()).toEqual(true); }); it("does not destroy primitive on removeAll", function() { const labels = new import__581.LabelCollection(context); primitives.destroyPrimitives = false; primitives.add(labels); expect(labels.isDestroyed()).toEqual(false); primitives.removeAll(); expect(labels.isDestroyed()).toEqual(false); labels.destroy(); expect(labels.isDestroyed()).toEqual(true); }); it("throws when add() without an primitive", function() { expect(function() { primitives.add(); }).toThrowDeveloperError(); }); it("raise throws when primitive is not in composite", function() { const p = createLabels(); expect(function() { primitives.raise(p); }).toThrowDeveloperError(); }); it("raiseToTop throws when primitive is not in composite", function() { const p = createLabels(); expect(function() { primitives.raiseToTop(p); }).toThrowDeveloperError(); }); it("lower throws when primitive is not in composite", function() { const p = createLabels(); expect(function() { primitives.lower(p); }).toThrowDeveloperError(); }); it("lowerToBottom throws when primitive is not in composite", function() { const p = createLabels(); expect(function() { primitives.lowerToBottom(p); }).toThrowDeveloperError(); }); it("fires an event on primitive added", function() { const p = createLabels(); const primitiveAdded = primitives.primitiveAdded; const onPrimitiveAddedSpy = jasmine.createSpy("event"); primitiveAdded.addEventListener(onPrimitiveAddedSpy); expect(onPrimitiveAddedSpy).not.toHaveBeenCalled(); primitives.add(p); expect(onPrimitiveAddedSpy).toHaveBeenCalledOnceWith(p); }); it("fires an event on primitive removed", function() { const p = createLabels(); const primitiveRemoved = primitives.primitiveRemoved; const onPrimitiveRemovedSpy = jasmine.createSpy("event"); primitiveRemoved.addEventListener(onPrimitiveRemovedSpy); expect(onPrimitiveRemovedSpy).not.toHaveBeenCalled(); primitives.add(p); expect(onPrimitiveRemovedSpy).not.toHaveBeenCalled(); primitives.remove(p); expect(onPrimitiveRemovedSpy).toHaveBeenCalledOnceWith(p); }); it("fires events on primitive remove all", function() { const collection = new import__581.PrimitiveCollection({ destroyPrimitives: false }); const p1 = createLabels(); const p2 = createLabels(); const primitiveRemoved = collection.primitiveRemoved; const onPrimitiveRemovedSpy = jasmine.createSpy("event"); primitiveRemoved.addEventListener(onPrimitiveRemovedSpy); expect(onPrimitiveRemovedSpy).not.toHaveBeenCalled(); collection.add(p1); collection.add(p2); expect(onPrimitiveRemovedSpy).not.toHaveBeenCalled(); collection.removeAll(); expect(onPrimitiveRemovedSpy).toHaveBeenCalledWith(p1); expect(onPrimitiveRemovedSpy).toHaveBeenCalledWith(p2); expect(onPrimitiveRemovedSpy).toHaveBeenCalledTimes(2); collection.destroy(); p1.destroy(); p2.destroy(); }); }, "WebGL" ); // packages/engine/Specs/Scene/PrimitiveCullingSpec.js var import__582 = __toESM(require_Cesium(), 1); var import__583 = __toESM(require_Cesium(), 1); describe( "Scene/PrimitiveCulling", function() { let scene2; const rectangle = import__582.Rectangle.fromDegrees(-100, 30, -93, 37); let primitive; let greenImage; beforeAll(function() { scene2 = createScene_default(); scene2.primitives.destroyPrimitives = false; return import__582.Resource.fetchImage("./Data/Images/Green.png").then(function(image) { greenImage = image; }); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { scene2.morphTo3D(0); const camera = scene2.camera; camera.frustum = new import__582.PerspectiveFrustum(); camera.frustum.aspectRatio = scene2.drawingBufferWidth / scene2.drawingBufferHeight; camera.frustum.fov = import__583.Math.toRadians(60); }); afterEach(function() { scene2.primitives.removeAll(); primitive = primitive && primitive.destroy(); }); function testCull(primitive2) { scene2.camera.setView({ destination: rectangle }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive2); expect(scene2).notToRender([0, 0, 0, 255]); if (scene2.mode !== import__582.SceneMode.SCENE2D) { scene2.camera.moveForward(1e8); expect(scene2).toRender([0, 0, 0, 255]); } } function testCullIn3D(primitive2) { scene2.mode = import__582.SceneMode.SCENE3D; testCull(primitive2); } function testCullInColumbusView(primitive2) { scene2.mode = import__582.SceneMode.COLUMBUS_VIEW; testCull(primitive2); } function testCullIn2D(primitive2) { scene2.mode = import__582.SceneMode.SCENE2D; testCull(primitive2); } function testOcclusionCull(primitive2) { scene2.mode = import__582.SceneMode.SCENE3D; scene2.camera.setView({ destination: rectangle }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive2); expect(scene2).notToRender([0, 0, 0, 255]); scene2.globe = new import__582.Globe(); expect(scene2).toRender([0, 0, 0, 255]); scene2.globe = void 0; } function createPrimitive(height) { height = (0, import__582.defaultValue)(height, 0); const primitive2 = new import__582.Primitive({ geometryInstances: new import__582.GeometryInstance({ geometry: new import__582.RectangleGeometry({ rectangle, vertexFormat: import__582.PerInstanceColorAppearance.VERTEX_FORMAT, height }), attributes: { color: import__582.ColorGeometryInstanceAttribute.fromColor(import__582.Color.RED) } }), appearance: new import__582.PerInstanceColorAppearance(), asynchronous: false }); return primitive2; } it("frustum culls polygon in 3D", function() { primitive = createPrimitive(); testCullIn3D(primitive); }); it("frustum culls polygon in Columbus view", function() { primitive = createPrimitive(); testCullInColumbusView(primitive); }); it("frustum culls polygon in 2D", function() { primitive = createPrimitive(); testCullIn2D(primitive); }); it("polygon occlusion", function() { primitive = createPrimitive(-1e6); testOcclusionCull(primitive); }); function allLabelsReady(labels) { return pollToPromise_default(function() { scene2.renderForSpecs(); const backgroundBillboard = labels._backgroundBillboardCollection.get( 0 ); return (!(0, import__582.defined)(backgroundBillboard) || backgroundBillboard.ready) && labels._labelsToUpdate.length === 0; }); } function createLabels(height) { height = (0, import__582.defaultValue)(height, 0); const labels = new import__582.LabelCollection(); const center = import__582.Cartesian3.fromDegrees(-96.5, 33.5, height); labels.modelMatrix = import__582.Transforms.eastNorthUpToFixedFrame(center); labels.add({ position: import__582.Cartesian3.ZERO, text: "X", horizontalOrigin: import__582.HorizontalOrigin.CENTER, verticalOrigin: import__582.VerticalOrigin.CENTER }); return labels; } function testLabelsCull(labels, occulude) { scene2.camera.setView({ destination: rectangle }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(labels); return allLabelsReady(labels).then(function() { expect(scene2).notToRender([0, 0, 0, 255]); if (occulude) { scene2.globe = new import__582.Globe(); expect(scene2).toRender([0, 0, 0, 255]); scene2.globe = void 0; return; } if (scene2.mode !== import__582.SceneMode.SCENE2D) { scene2.camera.moveForward(1e8); expect(scene2).toRender([0, 0, 0, 255]); } }); } it("frustum culls labels in 3D", function() { primitive = createLabels(); scene2.mode = import__582.SceneMode.SCENE3D; return testLabelsCull(primitive); }); it("frustum culls labels in Columbus view", function() { primitive = createLabels(); scene2.mode = import__582.SceneMode.COLUMBUS_VIEW; return testLabelsCull(primitive); }); it("frustum culls labels in 2D", function() { primitive = createLabels(); scene2.mode = import__582.SceneMode.SCENE2D; return testLabelsCull(primitive); }); it("label occlusion", function() { primitive = createLabels(-1e6); scene2.mode = import__582.SceneMode.SCENE3D; return testLabelsCull(primitive, true); }); function createBillboard(height) { height = (0, import__582.defaultValue)(height, 0); const billboards = new import__582.BillboardCollection(); billboards.add({ position: import__582.Cartesian3.fromDegrees(-96.5, 33.5, height), image: greenImage }); return billboards; } function testBillboardsCull(billboards, occulude) { scene2.camera.setView({ destination: rectangle }); expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(billboards); return pollToPromise_default(function() { scene2.renderForSpecs(); return billboards.get(0).ready; }).then(function() { expect(scene2).notToRender([0, 0, 0, 255]); if (occulude) { scene2.globe = new import__582.Globe(); expect(scene2).toRender([0, 0, 0, 255]); scene2.globe = void 0; return; } if (scene2.mode !== import__582.SceneMode.SCENE2D) { scene2.camera.moveForward(1e8); expect(scene2).toRender([0, 0, 0, 255]); } }); } it("frustum culls billboards in 3D", function() { primitive = createBillboard(); scene2.mode = import__582.SceneMode.SCENE3D; return testBillboardsCull(primitive); }); it("frustum culls billboards in Columbus view", function() { primitive = createBillboard(); scene2.mode = import__582.SceneMode.COLUMBUS_VIEW; return testBillboardsCull(primitive); }); it("frustum culls billboards in 2D", function() { primitive = createBillboard(); scene2.mode = import__582.SceneMode.SCENE2D; return testBillboardsCull(primitive); }); it("billboard occlusion", function() { primitive = createBillboard(-1e6); scene2.mode = import__582.SceneMode.SCENE3D; return testBillboardsCull(primitive, true); }); function createPolylines(height) { height = (0, import__582.defaultValue)(height, 0); const material = import__582.Material.fromType("Color"); material.translucent = false; const polylines = new import__582.PolylineCollection(); polylines.add({ positions: import__582.Cartesian3.fromDegreesArrayHeights([ -100, 30, height, -93, 37, height ]), material }); return polylines; } it("frustum culls polylines in 3D", function() { primitive = createPolylines(); testCullIn3D(primitive); }); it("frustum culls polylines in Columbus view", function() { primitive = createPolylines(); testCullInColumbusView(primitive); }); it("frustum culls polylines in 2D", function() { primitive = createPolylines(); testCullIn2D(primitive); }); it("polyline occlusion", function() { primitive = createPolylines(-1e6); testOcclusionCull(primitive); }); }, "WebGL" ); // packages/engine/Specs/Scene/PrimitivePipelineSpec.js var import__584 = __toESM(require_Cesium(), 1); describe( "Scene/PrimitivePipeline", function() { it("can pack and unpack geometry", function() { const boxGeometry = import__584.BoxGeometry.createGeometry( import__584.BoxGeometry.fromDimensions({ dimensions: new import__584.Cartesian3(1, 2, 3) }) ); const boxGeometry2 = import__584.BoxGeometry.createGeometry( import__584.BoxGeometry.fromDimensions({ dimensions: new import__584.Cartesian3(3, 4, 7) }) ); const geometryToPack = [boxGeometry, boxGeometry2]; const transferableObjects = []; const results = import__584.PrimitivePipeline.packCreateGeometryResults( geometryToPack, transferableObjects ); const unpackedGeometry = import__584.PrimitivePipeline.unpackCreateGeometryResults( results ); expect(transferableObjects.length).toBe(1); expect(geometryToPack).toEqual(unpackedGeometry); }); it("can pack and unpack geometry without indices", function() { const attributes = new import__584.GeometryAttributes(); attributes.position = new import__584.GeometryAttribute({ componentDatatype: import__584.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: new Float32Array([1, 2, 3, 4, 5, 6]) }); const geometry = new import__584.Geometry({ attributes, indices: void 0, primitiveType: import__584.PrimitiveType.POINTS, boundingSphere: import__584.BoundingSphere.fromVertices(attributes.position.values) }); const geometryToPack = [geometry]; const transferableObjects = []; const results = import__584.PrimitivePipeline.packCreateGeometryResults( geometryToPack, transferableObjects ); const unpackedGeometry = import__584.PrimitivePipeline.unpackCreateGeometryResults( results ); expect(transferableObjects.length).toBe(1); expect(geometryToPack).toEqual(unpackedGeometry); }); }, "WebGL" ); // packages/engine/Specs/Scene/PrimitiveSpec.js var import__585 = __toESM(require_Cesium(), 1); var import__586 = __toESM(require_Cesium(), 1); // Specs/BadGeometry.js var import_engine29 = __toESM(require_Cesium(), 1); function BadGeometry() { this._workerName = "../../Build/Specs/TestWorkers/createBadGeometry"; if (typeof window !== "undefined" && typeof window.location !== "undefined" && typeof window.location.search !== "undefined") { const parameters = (0, import_engine29.queryToObject)(window.location.search.substring(1)); if (parameters.built) { this._workerName = `../${this._workerName}`; } } } BadGeometry.createGeometry = function() { throw new import_engine29.RuntimeError("BadGeometry.createGeometry"); }; BadGeometry.packedLength = 0; BadGeometry.pack = function() { }; BadGeometry.unpack = function() { return new BadGeometry(); }; var BadGeometry_default = BadGeometry; // packages/engine/Specs/Scene/PrimitiveSpec.js describe( "Scene/Primitive", function() { let scene2; let context; let frameStateContext; let frameState2; let ellipsoid; let rectangle1; let rectangle2; let rectangleInstance1; let rectangleInstance2; let primitive; beforeAll(function() { scene2 = createScene_default(); scene2.primitives.destroyPrimitives = false; context = scene2.context; ellipsoid = import__585.Ellipsoid.WGS84; frameStateContext = createContext_default(); }); afterAll(function() { scene2.destroyForSpecs(); frameStateContext.destroyForSpecs(); }); beforeEach(function() { scene2.morphTo3D(0); const camera = scene2.camera; camera.frustum = new import__585.PerspectiveFrustum(); camera.frustum.aspectRatio = scene2.drawingBufferWidth / scene2.drawingBufferHeight; camera.frustum.fov = import__586.Math.toRadians(60); scene2.frameState.passes.render = true; scene2.frameState.passes.pick = false; frameState2 = createFrameState_default(frameStateContext); rectangle1 = import__585.Rectangle.fromDegrees(-80, 20, -70, 30); rectangle2 = import__585.Rectangle.fromDegrees(70, 20, 80, 30); let translation = import__585.Cartesian3.multiplyByScalar( import__585.Cartesian3.normalize( ellipsoid.cartographicToCartesian(import__585.Rectangle.center(rectangle1)), new import__585.Cartesian3() ), 2, new import__585.Cartesian3() ); rectangleInstance1 = new import__585.GeometryInstance({ geometry: new import__585.RectangleGeometry({ vertexFormat: import__585.PerInstanceColorAppearance.VERTEX_FORMAT, ellipsoid, rectangle: rectangle1 }), modelMatrix: import__585.Matrix4.fromTranslation(translation, new import__585.Matrix4()), id: "rectangle1", attributes: { color: new import__585.ColorGeometryInstanceAttribute(1, 1, 0, 1), show: new import__585.ShowGeometryInstanceAttribute(true) } }); translation = import__585.Cartesian3.multiplyByScalar( import__585.Cartesian3.normalize( ellipsoid.cartographicToCartesian(import__585.Rectangle.center(rectangle2)), new import__585.Cartesian3() ), 3, new import__585.Cartesian3() ); rectangleInstance2 = new import__585.GeometryInstance({ geometry: new import__585.RectangleGeometry({ vertexFormat: import__585.PerInstanceColorAppearance.VERTEX_FORMAT, ellipsoid, rectangle: rectangle2 }), modelMatrix: import__585.Matrix4.fromTranslation(translation, new import__585.Matrix4()), id: "rectangle2", attributes: { color: new import__585.ColorGeometryInstanceAttribute(0, 1, 1, 1), show: new import__585.ShowGeometryInstanceAttribute(true) } }); }); afterEach(function() { scene2.primitives.removeAll(); primitive = primitive && !primitive.isDestroyed() && primitive.destroy(); }); it("default constructs", function() { primitive = new import__585.Primitive(); expect(primitive.geometryInstances).not.toBeDefined(); expect(primitive.appearance).not.toBeDefined(); expect(primitive.depthFailAppearance).not.toBeDefined(); expect(primitive.modelMatrix).toEqual(import__585.Matrix4.IDENTITY); expect(primitive.show).toEqual(true); expect(primitive.vertexCacheOptimize).toEqual(false); expect(primitive.interleave).toEqual(false); expect(primitive.compressVertices).toEqual(true); expect(primitive.releaseGeometryInstances).toEqual(true); expect(primitive.allowPicking).toEqual(true); expect(primitive.cull).toEqual(true); expect(primitive.asynchronous).toEqual(true); expect(primitive.debugShowBoundingVolume).toEqual(false); }); it("Constructs with options", function() { const geometryInstances = {}; const appearance = {}; const depthFailAppearance = {}; const modelMatrix = import__585.Matrix4.fromUniformScale(5); primitive = new import__585.Primitive({ geometryInstances, appearance, depthFailAppearance, modelMatrix, show: false, vertexCacheOptimize: true, interleave: true, compressVertices: false, releaseGeometryInstances: false, allowPicking: false, cull: false, asynchronous: false, debugShowBoundingVolume: true }); expect(primitive.geometryInstances).toEqual(geometryInstances); expect(primitive.appearance).toEqual(appearance); expect(primitive.depthFailAppearance).toEqual(depthFailAppearance); expect(primitive.modelMatrix).toEqual(modelMatrix); expect(primitive.show).toEqual(false); expect(primitive.vertexCacheOptimize).toEqual(true); expect(primitive.interleave).toEqual(true); expect(primitive.compressVertices).toEqual(false); expect(primitive.releaseGeometryInstances).toEqual(false); expect(primitive.allowPicking).toEqual(false); expect(primitive.cull).toEqual(false); expect(primitive.asynchronous).toEqual(false); expect(primitive.debugShowBoundingVolume).toEqual(true); }); it("releases geometry instances when releaseGeometryInstances is true", function() { primitive = new import__585.Primitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], appearance: new import__585.PerInstanceColorAppearance(), releaseGeometryInstances: true, asynchronous: false }); expect(primitive.geometryInstances).toBeDefined(); scene2.primitives.add(primitive); scene2.renderForSpecs(); expect(primitive.geometryInstances).not.toBeDefined(); }); it("does not release geometry instances when releaseGeometryInstances is false", function() { primitive = new import__585.Primitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], appearance: new import__585.PerInstanceColorAppearance(), releaseGeometryInstances: false, asynchronous: false }); expect(primitive.geometryInstances).toBeDefined(); scene2.primitives.add(primitive); scene2.renderForSpecs(); expect(primitive.geometryInstances).toBeDefined(); }); it("does not render when geometryInstances is an empty array", function() { primitive = new import__585.Primitive({ geometryInstances: [], appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); frameState2.commandList.length = 0; primitive.update(frameState2); expect(frameState2.commandList.length).toEqual(0); }); it("does not render when show is false", function() { primitive = new import__585.Primitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); primitive.update(frameState2); expect(frameState2.commandList.length).toBeGreaterThan(0); frameState2.commandList.length = 0; primitive.show = false; primitive.update(frameState2); expect(frameState2.commandList.length).toEqual(0); }); it("does not render other than for the color or pick pass", function() { primitive = new import__585.Primitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); frameState2.passes.render = false; frameState2.passes.pick = false; primitive.update(frameState2); expect(frameState2.commandList.length).toEqual(0); }); it("does not render when scene3DOnly is true and the scene mode is SCENE2D", function() { primitive = new import__585.Primitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); frameState2.mode = import__585.SceneMode.SCENE2D; frameState2.scene3DOnly = true; primitive.update(frameState2); expect(frameState2.commandList.length).toEqual(0); }); it("does not render when scene3DOnly is true and the scene mode is COLUMBUS_VIEW", function() { primitive = new import__585.Primitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); frameState2.mode = import__585.SceneMode.COLUMBUS_VIEW; frameState2.scene3DOnly = true; primitive.update(frameState2); expect(frameState2.commandList.length).toEqual(0); }); it("renders in two passes for closed, translucent geometry", function() { primitive = new import__585.Primitive({ geometryInstances: new import__585.GeometryInstance({ geometry: import__585.BoxGeometry.fromDimensions({ vertexFormat: import__585.PerInstanceColorAppearance.VERTEX_FORMAT, dimensions: new import__585.Cartesian3(5e5, 5e5, 5e5) }), id: "box", attributes: { color: new import__585.ColorGeometryInstanceAttribute(1, 1, 0, 0.5) } }), appearance: new import__585.PerInstanceColorAppearance({ closed: true, translucent: true }), asynchronous: false }); const frameState3 = scene2.frameState; frameState3.commandList.length = 0; frameState3.scene3DOnly = true; scene2.primitives.add(primitive); scene2.render(); expect(frameState3.commandList.length).toEqual(2); }); function verifyPrimitiveRender(primitive2, rectangle) { scene2.primitives.removeAll(); if ((0, import__585.defined)(rectangle)) { scene2.camera.setView({ destination: rectangle }); } expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(primitive2); expect(scene2).notToRender([0, 0, 0, 255]); } it("renders in Columbus view when scene3DOnly is false", function() { scene2.frameState.scene3DOnly = false; primitive = new import__585.Primitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); scene2.morphToColumbusView(0); verifyPrimitiveRender(primitive, rectangle1); verifyPrimitiveRender(primitive, rectangle2); }); it("renders in 2D when scene3DOnly is false", function() { scene2.frameState.scene3DOnly = false; primitive = new import__585.Primitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); scene2.morphTo2D(0); verifyPrimitiveRender(primitive, rectangle1); verifyPrimitiveRender(primitive, rectangle2); }); it("renders RTC", function() { const dimensions = new import__585.Cartesian3(400, 300, 500); const positionOnEllipsoid = import__585.Cartesian3.fromDegrees(-105, 45); const boxModelMatrix = import__585.Matrix4.multiplyByTranslation( import__585.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid), new import__585.Cartesian3(0, 0, dimensions.z * 0.5), new import__585.Matrix4() ); const boxGeometry = import__585.BoxGeometry.createGeometry( import__585.BoxGeometry.fromDimensions({ vertexFormat: import__585.PerInstanceColorAppearance.VERTEX_FORMAT, dimensions }) ); const positions = boxGeometry.attributes.position.values; const newPositions = new Float32Array(positions.length); for (let i = 0; i < positions.length; ++i) { newPositions[i] = positions[i]; } boxGeometry.attributes.position.values = newPositions; boxGeometry.attributes.position.componentDatatype = import__585.ComponentDatatype.FLOAT; import__585.BoundingSphere.transform( boxGeometry.boundingSphere, boxModelMatrix, boxGeometry.boundingSphere ); const boxGeometryInstance = new import__585.GeometryInstance({ geometry: boxGeometry, attributes: { color: new import__585.ColorGeometryInstanceAttribute(1, 0, 0, 0.5) } }); const primitive2 = new import__585.Primitive({ geometryInstances: boxGeometryInstance, appearance: new import__585.PerInstanceColorAppearance({ closed: true }), asynchronous: false, allowPicking: false, rtcCenter: boxGeometry.boundingSphere.center }); const camera = scene2.camera; const testCamera = new import__585.Camera(scene2); testCamera.viewBoundingSphere(boxGeometry.boundingSphere); scene2.camera = testCamera; scene2.frameState.scene3DOnly = true; verifyPrimitiveRender(primitive2); scene2.camera = camera; }); it("renders with depth fail appearance", function() { const rect = import__585.Rectangle.fromDegrees(-1, -1, 1, 1); const translation = import__585.Cartesian3.multiplyByScalar( import__585.Cartesian3.normalize( ellipsoid.cartographicToCartesian(import__585.Rectangle.center(rect)), new import__585.Cartesian3() ), 100, new import__585.Cartesian3() ); const rectInstance = new import__585.GeometryInstance({ geometry: new import__585.RectangleGeometry({ vertexFormat: import__585.PerInstanceColorAppearance.VERTEX_FORMAT, ellipsoid, rectangle: rect }), modelMatrix: import__585.Matrix4.fromTranslation(translation, new import__585.Matrix4()), id: "rect", attributes: { color: new import__585.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); const p0 = new import__585.Primitive({ geometryInstances: rectInstance, appearance: new import__585.PerInstanceColorAppearance({ translucent: false }), asynchronous: false }); const rectInstance2 = new import__585.GeometryInstance({ geometry: new import__585.RectangleGeometry({ vertexFormat: import__585.PerInstanceColorAppearance.VERTEX_FORMAT, ellipsoid, rectangle: rect }), id: "rect2", attributes: { color: new import__585.ColorGeometryInstanceAttribute(1, 0, 0, 1), depthFailColor: new import__585.ColorGeometryInstanceAttribute( 1, 0, 1, 1 ) } }); const p1 = new import__585.Primitive({ geometryInstances: rectInstance2, appearance: new import__585.PerInstanceColorAppearance({ translucent: false }), depthFailAppearance: new import__585.PerInstanceColorAppearance({ translucent: false }), asynchronous: false }); scene2.primitives.add(p0); scene2.primitives.add(p1); scene2.camera.setView({ destination: rect }); scene2.renderForSpecs(); expect(scene2).toRender([255, 0, 255, 255]); }); it("pick with depth fail appearance", function() { const rect = import__585.Rectangle.fromDegrees(-1, -1, 1, 1); const translation = import__585.Cartesian3.multiplyByScalar( import__585.Cartesian3.normalize( ellipsoid.cartographicToCartesian(import__585.Rectangle.center(rect)), new import__585.Cartesian3() ), 100, new import__585.Cartesian3() ); const rectInstance = new import__585.GeometryInstance({ geometry: new import__585.RectangleGeometry({ vertexFormat: import__585.PerInstanceColorAppearance.VERTEX_FORMAT, ellipsoid, rectangle: rect }), modelMatrix: import__585.Matrix4.fromTranslation(translation, new import__585.Matrix4()), id: "rect", attributes: { color: new import__585.ColorGeometryInstanceAttribute(1, 1, 0, 1) } }); const p0 = new import__585.Primitive({ geometryInstances: rectInstance, appearance: new import__585.PerInstanceColorAppearance({ translucent: false }), asynchronous: false }); const rectInstance2 = new import__585.GeometryInstance({ geometry: new import__585.RectangleGeometry({ vertexFormat: import__585.PerInstanceColorAppearance.VERTEX_FORMAT, ellipsoid, rectangle: rect }), id: "rect2", attributes: { color: new import__585.ColorGeometryInstanceAttribute(1, 0, 0, 1), depthFailColor: new import__585.ColorGeometryInstanceAttribute( 1, 0, 1, 1 ) } }); const p1 = new import__585.Primitive({ geometryInstances: rectInstance2, appearance: new import__585.PerInstanceColorAppearance({ translucent: false }), depthFailAppearance: new import__585.PerInstanceColorAppearance({ translucent: false }), asynchronous: false }); scene2.primitives.add(p0); scene2.primitives.add(p1); scene2.camera.setView({ destination: rect }); scene2.renderForSpecs(); expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toEqual(p1); expect(result.id).toEqual("rect2"); }); }); it("RTC throws with more than one instance", function() { expect(function() { return new import__585.Primitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], appearance: new import__585.PerInstanceColorAppearance({ closed: true }), asynchronous: false, allowPicking: false, rtcCenter: import__585.Cartesian3.ZERO }); }).toThrowDeveloperError(); }); it("RTC throws if the scene is not 3D only", function() { scene2.frameState.scene3DOnly = false; const primitive2 = new import__585.Primitive({ geometryInstances: rectangleInstance1, appearance: new import__585.PerInstanceColorAppearance({ closed: true }), asynchronous: false, allowPicking: false, rtcCenter: import__585.Cartesian3.ZERO }); expect(function() { verifyPrimitiveRender(primitive2); }).toThrowDeveloperError(); }); it("updates model matrix for one instance in 3D", function() { primitive = new import__585.Primitive({ geometryInstances: rectangleInstance1, appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); primitive.update(frameState2); const commands = frameState2.commandList; expect(commands.length).toEqual(1); expect(commands[0].modelMatrix).toEqual(primitive.modelMatrix); const modelMatrix = import__585.Matrix4.fromUniformScale(10); primitive.modelMatrix = modelMatrix; commands.length = 0; primitive.update(frameState2); expect(commands.length).toEqual(1); expect(commands[0].modelMatrix).toEqual(modelMatrix); }); it("updates model matrix for more than one instance in 3D with equal model matrices in 3D only scene", function() { let modelMatrix = import__585.Matrix4.fromUniformScale(2); rectangleInstance1.modelMatrix = modelMatrix; rectangleInstance2.modelMatrix = modelMatrix; primitive = new import__585.Primitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); frameState2.scene3DOnly = true; const commands = frameState2.commandList; commands.length = 0; primitive.update(frameState2); expect(commands.length).toEqual(1); expect(commands[0].modelMatrix).toEqual(modelMatrix); modelMatrix = import__585.Matrix4.fromUniformScale(10); primitive.modelMatrix = modelMatrix; commands.length = 0; primitive.update(frameState2); expect(commands.length).toEqual(1); expect(commands[0].modelMatrix).toEqual(modelMatrix); }); it("computes model matrix when given one for a single instance and for the primitive in 3D only", function() { const instanceModelMatrix = import__585.Matrix4.fromUniformScale(2); const dimensions = new import__585.Cartesian3(4e5, 3e5, 5e5); const positionOnEllipsoid = import__585.Cartesian3.fromDegrees(-105, 45); const primitiveModelMatrix = import__585.Matrix4.multiplyByTranslation( import__585.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid), new import__585.Cartesian3(0, 0, dimensions.z * 0.5), new import__585.Matrix4() ); const boxGeometry = import__585.BoxGeometry.fromDimensions({ vertexFormat: import__585.PerInstanceColorAppearance.VERTEX_FORMAT, dimensions }); const boxGeometryInstance = new import__585.GeometryInstance({ geometry: boxGeometry, modelMatrix: instanceModelMatrix, attributes: { color: new import__585.ColorGeometryInstanceAttribute(1, 0, 0, 1) } }); primitive = new import__585.Primitive({ geometryInstances: boxGeometryInstance, modelMatrix: primitiveModelMatrix, appearance: new import__585.PerInstanceColorAppearance({ translucent: false, closed: true }), asynchronous: false }); const expectedModelMatrix = import__585.Matrix4.multiplyTransformation( primitiveModelMatrix, instanceModelMatrix, new import__585.Matrix4() ); frameState2.scene3DOnly = true; const commands = frameState2.commandList; commands.length = 0; primitive.update(frameState2); expect(commands.length).toEqual(1); expect(commands[0].modelMatrix).toEqual(expectedModelMatrix); }); it("update model matrix throws in Columbus view", function() { primitive = new import__585.Primitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); frameState2.mode = import__585.SceneMode.COLUMBUS_VIEW; frameState2.scene3DOnly = false; const commands = frameState2.commandList; commands.length = 0; primitive.update(frameState2); expect(commands.length).toEqual(1); expect(commands[0].modelMatrix).toEqual(import__585.Matrix4.IDENTITY); const modelMatrix = import__585.Matrix4.fromUniformScale(10); primitive.modelMatrix = modelMatrix; commands.length = 0; expect(function() { primitive.update(frameState2); }).toThrowDeveloperError(); }); it("update model matrix throws in 2D", function() { primitive = new import__585.Primitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); frameState2.mode = import__585.SceneMode.SCENE2D; frameState2.scene3DOnly = false; const commands = frameState2.commandList; primitive.update(frameState2); expect(commands.length).toEqual(1); expect(commands[0].modelMatrix).toEqual(import__585.Matrix4.IDENTITY); const modelMatrix = import__585.Matrix4.fromUniformScale(10); primitive.modelMatrix = modelMatrix; commands.length = 0; expect(function() { primitive.update(frameState2); }).toThrowDeveloperError(); }); it("renders bounding volume with debugShowBoundingVolume", function() { primitive = new import__585.Primitive({ geometryInstances: rectangleInstance1, appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false, debugShowBoundingVolume: true }); scene2.primitives.add(primitive); scene2.camera.setView({ destination: rectangle1 }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).not.toEqual(0); expect(rgba[1]).toBeGreaterThanOrEqual(0); expect(rgba[2]).toBeGreaterThanOrEqual(0); expect(rgba[3]).toEqual(255); }); }); it("transforms to world coordinates", function() { primitive = new import__585.Primitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); verifyPrimitiveRender(primitive, rectangle1); verifyPrimitiveRender(primitive, rectangle2); expect(primitive.modelMatrix).toEqual(import__585.Matrix4.IDENTITY); }); it("does not transform to world coordinates", function() { rectangleInstance2.modelMatrix = import__585.Matrix4.clone( rectangleInstance1.modelMatrix ); primitive = new import__585.Primitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); scene2.frameState.scene3DOnly = true; verifyPrimitiveRender(primitive, rectangle1); verifyPrimitiveRender(primitive, rectangle2); expect(primitive.modelMatrix).not.toEqual(import__585.Matrix4.IDENTITY); scene2.frameState.scene3DOnly = true; }); it("get common per instance attributes", function() { rectangleInstance2.attributes.not_used = new import__585.GeometryInstanceAttribute({ componentDatatype: import__585.ComponentDatatype.FLOAT, componentsPerAttribute: 1, value: [0.5] }); primitive = new import__585.Primitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); scene2.primitives.add(primitive); scene2.renderForSpecs(); let attributes = primitive.getGeometryInstanceAttributes("rectangle1"); expect(attributes.color).toBeDefined(); expect(attributes.show).toBeDefined(); attributes = primitive.getGeometryInstanceAttributes("rectangle2"); expect(attributes.color).toBeDefined(); expect(attributes.show).toBeDefined(); expect(attributes.not_used).not.toBeDefined(); }); it("modify color instance attribute", function() { primitive = new import__585.Primitive({ geometryInstances: rectangleInstance1, appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); scene2.camera.setView({ destination: rectangle1 }); scene2.primitives.add(primitive); let pixels; expect(scene2).toRenderAndCall(function(rgba) { pixels = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); }); const attributes = primitive.getGeometryInstanceAttributes("rectangle1"); expect(attributes.color).toBeDefined(); attributes.color = [255, 255, 255, 255]; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).not.toEqual(pixels); }); }); it("modify show instance attribute", function() { primitive = new import__585.Primitive({ geometryInstances: rectangleInstance1, appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); scene2.primitives.add(primitive); scene2.camera.setView({ destination: rectangle1 }); expect(scene2).notToRender([0, 0, 0, 255]); const attributes = primitive.getGeometryInstanceAttributes("rectangle1"); expect(attributes.show).toBeDefined(); attributes.show = [0]; expect(scene2).toRender([0, 0, 0, 255]); }); it("get bounding sphere from per instance attribute", function() { primitive = new import__585.Primitive({ geometryInstances: rectangleInstance1, appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); verifyPrimitiveRender(primitive, rectangle1); const attributes = primitive.getGeometryInstanceAttributes("rectangle1"); expect(attributes.boundingSphere).toBeDefined(); }); it("renders with distance display condition per instance attribute", function() { if (!context.floatingPointTexture) { return; } const near = 1e4; const far = 1e6; const rect = import__585.Rectangle.fromDegrees(-1, -1, 1, 1); const translation = import__585.Cartesian3.multiplyByScalar( import__585.Cartesian3.normalize( ellipsoid.cartographicToCartesian(import__585.Rectangle.center(rect)), new import__585.Cartesian3() ), 2, new import__585.Cartesian3() ); const rectInstance = new import__585.GeometryInstance({ geometry: new import__585.RectangleGeometry({ vertexFormat: import__585.PerInstanceColorAppearance.VERTEX_FORMAT, ellipsoid, rectangle: rect }), modelMatrix: import__585.Matrix4.fromTranslation(translation, new import__585.Matrix4()), id: "rect", attributes: { color: new import__585.ColorGeometryInstanceAttribute(1, 1, 0, 1), distanceDisplayCondition: new import__585.DistanceDisplayConditionGeometryInstanceAttribute( near, far ) } }); primitive = new import__585.Primitive({ geometryInstances: rectInstance, appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); scene2.primitives.add(primitive); scene2.camera.setView({ destination: rect }); scene2.renderForSpecs(); const boundingSphere = primitive.getGeometryInstanceAttributes("rect").boundingSphere; const center = boundingSphere.center; const radius = boundingSphere.radius; scene2.camera.lookAt( center, new import__585.HeadingPitchRange(0, -import__586.Math.PI_OVER_TWO, radius) ); expect(scene2).toRender([0, 0, 0, 255]); scene2.camera.lookAt( center, new import__585.HeadingPitchRange(0, -import__586.Math.PI_OVER_TWO, radius + near + 1) ); expect(scene2).notToRender([0, 0, 0, 255]); scene2.camera.lookAt( center, new import__585.HeadingPitchRange(0, -import__586.Math.PI_OVER_TWO, radius + far + 1) ); expect(scene2).toRender([0, 0, 0, 255]); }); it("primitive with display condition properly transforms boundingSphere", function() { const near = 1e4; const far = 1e6; const translation = new import__585.Cartesian3(10, 20, 30); const cylinder = new import__585.GeometryInstance({ id: "cylinder", vertexFormat: import__585.PerInstanceColorAppearance.VERTEX_FORMAT, geometry: new import__585.CylinderGeometry({ length: 10, topRadius: 10, bottomRadius: 10 }), attributes: { color: new import__585.ColorGeometryInstanceAttribute(1, 1, 0, 1), show: new import__585.ShowGeometryInstanceAttribute(true), distanceDisplayCondition: new import__585.DistanceDisplayConditionGeometryInstanceAttribute( near, far ) } }); primitive = new import__585.Primitive({ geometryInstances: cylinder, appearance: new import__585.PerInstanceColorAppearance(), modelMatrix: import__585.Matrix4.fromTranslation(translation, new import__585.Matrix4()), asynchronous: false }); scene2.primitives.add(primitive); scene2.frameState.scene3DOnly = true; scene2.renderForSpecs(); const boundingSphere = primitive.getGeometryInstanceAttributes("cylinder").boundingSphere; const center = boundingSphere.center; expect(center).toEqual(translation); }); it("primitive without display condition properly transforms boundingSphere", function() { const translation = new import__585.Cartesian3(10, 20, 30); const cylinder = new import__585.GeometryInstance({ id: "cylinder", vertexFormat: import__585.PerInstanceColorAppearance.VERTEX_FORMAT, geometry: new import__585.CylinderGeometry({ length: 10, topRadius: 10, bottomRadius: 10 }), attributes: { color: new import__585.ColorGeometryInstanceAttribute(1, 1, 0, 1), show: new import__585.ShowGeometryInstanceAttribute(true) } }); primitive = new import__585.Primitive({ geometryInstances: cylinder, appearance: new import__585.PerInstanceColorAppearance(), modelMatrix: import__585.Matrix4.fromTranslation(translation, new import__585.Matrix4()), asynchronous: false }); scene2.primitives.add(primitive); scene2.frameState.scene3DOnly = true; scene2.renderForSpecs(); const boundingSphere = primitive.getGeometryInstanceAttributes("cylinder").boundingSphere; const center = boundingSphere.center; expect(center).toEqual(translation); }); it("getGeometryInstanceAttributes returns same object each time", function() { primitive = new import__585.Primitive({ geometryInstances: rectangleInstance1, appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); verifyPrimitiveRender(primitive, rectangle1); const attributes = primitive.getGeometryInstanceAttributes("rectangle1"); const attributes2 = primitive.getGeometryInstanceAttributes("rectangle1"); expect(attributes).toBe(attributes2); }); it("picking", function() { primitive = new import__585.Primitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); verifyPrimitiveRender(primitive, rectangle1); expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toEqual(primitive); expect(result.id).toEqual("rectangle1"); }); verifyPrimitiveRender(primitive, rectangle2); expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toEqual(primitive); expect(result.id).toEqual("rectangle2"); }); }); it("does not pick when allowPicking is false", function() { primitive = new import__585.Primitive({ geometryInstances: [rectangleInstance1], appearance: new import__585.PerInstanceColorAppearance(), allowPicking: false, asynchronous: false }); verifyPrimitiveRender(primitive, rectangle1); expect(scene2).notToPick(); }); it("does not cull when cull is false", function() { primitive = new import__585.Primitive({ geometryInstances: rectangleInstance1, appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false, cull: false }); frameState2.commandList.length = 0; primitive.update(frameState2); expect(frameState2.commandList[0].cull).toEqual(false); }); it("update throws when geometry primitive types are different", function() { primitive = new import__585.Primitive({ geometryInstances: [ new import__585.GeometryInstance({ geometry: new import__585.Geometry({ attributes: { position: new import__585.GeometryAttribute({ componentDatatype: import__585.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: new Float32Array([1, 2, 3, 4]) }) }, primitiveType: import__585.PrimitiveType.LINES }) }), new import__585.GeometryInstance({ geometry: new import__585.Geometry({ attributes: { position: new import__585.GeometryAttribute({ componentDatatype: import__585.ComponentDatatype.FLOAT, componentsPerAttribute: 3, values: new Float32Array([1, 2, 3, 4, 5, 6]) }) }, primitiveType: import__585.PrimitiveType.TRIANGLES }) }) ], appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); expect(function() { primitive.update(frameState2); }).toThrowDeveloperError(); }); it("failed geometry throws on next update", async function() { primitive = new import__585.Primitive({ geometryInstances: [ new import__585.GeometryInstance({ geometry: new BadGeometry_default() }) ], appearance: new import__585.MaterialAppearance({ materialSupport: import__585.MaterialAppearance.MaterialSupport.ALL }), compressVertices: false }); scene2.frameState.afterRender.length = 0; scene2.primitives.add(primitive); await pollToPromise_default(function() { for (let i = 0; i < frameState2.afterRender.length; ++i) { frameState2.afterRender[i](); return true; } primitive.update(frameState2); return false; }); expect(function() { scene2.render(); }).toThrow(); }); it("internally invalid asynchronous geometry becomes ready", async function() { primitive = new import__585.Primitive({ geometryInstances: [ new import__585.GeometryInstance({ geometry: import__585.PolygonGeometry.fromPositions({ positions: [] }) }) ], appearance: new import__585.MaterialAppearance({ materialSupport: import__585.MaterialAppearance.MaterialSupport.ALL }), compressVertices: false }); scene2.frameState.afterRender.length = 0; await pollToPromise_default(function() { for (let i = 0; i < frameState2.afterRender.length; ++i) { frameState2.afterRender[i](); return true; } primitive.update(frameState2); return false; }); expect(primitive.ready).toBe(true); }); it("internally invalid synchronous geometry resolves promise and sets ready", function() { primitive = new import__585.Primitive({ geometryInstances: [ new import__585.GeometryInstance({ geometry: import__585.PolygonGeometry.fromPositions({ positions: [] }) }) ], appearance: new import__585.MaterialAppearance({ materialSupport: import__585.MaterialAppearance.MaterialSupport.ALL }), asynchronous: false, compressVertices: false }); scene2.frameState.afterRender.length = 0; return pollToPromise_default(function() { if (scene2.frameState.afterRender.length > 0) { scene2.frameState.afterRender[0](); return true; } primitive.update(scene2.frameState); return false; }).then(function() { expect(primitive.ready).toBe(true); }); }); it("can mix valid and invalid geometry", function() { const instances = []; instances.push(rectangleInstance1); instances.push( new import__585.GeometryInstance({ geometry: import__585.PolygonGeometry.fromPositions({ positions: [] }), attributes: { color: new import__585.ColorGeometryInstanceAttribute(1, 0, 1, 1) }, id: "invalid" }) ); instances.push(rectangleInstance2); primitive = new import__585.Primitive({ geometryInstances: instances, appearance: new import__585.PerInstanceColorAppearance({ flat: true }) }); return pollToPromise_default(function() { primitive.update(frameState2); if (frameState2.afterRender.length > 0) { frameState2.afterRender[0](); } return primitive.ready; }).then(function() { expect( primitive.getGeometryInstanceAttributes("rectangle1").boundingSphere ).toBeDefined(); expect( primitive.getGeometryInstanceAttributes("rectangle2").boundingSphere ).toBeDefined(); expect( primitive.getGeometryInstanceAttributes("invalid").boundingSphere ).not.toBeDefined(); }); }); it("shader validation", function() { if (!!window.webglStub) { return; } primitive = new import__585.Primitive({ geometryInstances: [rectangleInstance1, rectangleInstance2], appearance: new import__585.MaterialAppearance({ materialSupport: import__585.MaterialAppearance.MaterialSupport.ALL }), asynchronous: false, compressVertices: false }); expect(function() { primitive.update(frameState2); }).toThrowDeveloperError(); }); it("setting per instance attribute throws when value is undefined", function() { primitive = new import__585.Primitive({ geometryInstances: rectangleInstance1, appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); primitive.update(frameState2); const attributes = primitive.getGeometryInstanceAttributes("rectangle1"); expect(function() { attributes.color = void 0; }).toThrowDeveloperError(); }); it("can disable picking when asynchronous", function() { primitive = new import__585.Primitive({ geometryInstances: rectangleInstance1, appearance: new import__585.PerInstanceColorAppearance(), asynchronous: true, allowPicking: false }); frameState2.afterRender.length = 0; scene2.primitives.add(primitive); return pollToPromise_default(function() { if (frameState2.afterRender.length > 0) { frameState2.afterRender[0](); } scene2.render(); return primitive.ready; }).then(function() { const attributes = primitive.getGeometryInstanceAttributes( "rectangle1" ); expect(function() { attributes.color = void 0; }).toThrowDeveloperError(); }); }); it("getGeometryInstanceAttributes throws without id", function() { primitive = new import__585.Primitive({ geometryInstances: rectangleInstance1, appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); scene2.primitives.add(primitive); scene2.renderForSpecs(); expect(function() { primitive.getGeometryInstanceAttributes(); }).toThrowDeveloperError(); }); it("getGeometryInstanceAttributes throws if update was not called", function() { primitive = new import__585.Primitive({ geometryInstances: rectangleInstance1, appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); expect(function() { primitive.getGeometryInstanceAttributes("rectangle1"); }).toThrowDeveloperError(); }); it("getGeometryInstanceAttributes returns undefined if id does not exist", function() { primitive = new import__585.Primitive({ geometryInstances: rectangleInstance1, appearance: new import__585.PerInstanceColorAppearance(), asynchronous: false }); scene2.primitives.add(primitive); scene2.renderForSpecs(); expect( primitive.getGeometryInstanceAttributes("unknown") ).not.toBeDefined(); }); it("isDestroyed", function() { primitive = new import__585.Primitive(); expect(primitive.isDestroyed()).toEqual(false); primitive.destroy(); expect(primitive.isDestroyed()).toEqual(true); }); it("renders when using asynchronous pipeline", function() { primitive = new import__585.Primitive({ geometryInstances: rectangleInstance1, appearance: new import__585.PerInstanceColorAppearance({ flat: true }) }); const frameState3 = scene2.frameState; return pollToPromise_default(function() { primitive.update(frameState3); for (let i = 0; i < frameState3.afterRender.length; ++i) { frameState3.afterRender[i](); } return primitive.ready; }).then(function() { verifyPrimitiveRender(primitive, rectangle1); }); }); it("destroy before asynchronous pipeline is complete", function() { primitive = new import__585.Primitive({ geometryInstances: rectangleInstance1, appearance: new import__585.PerInstanceColorAppearance() }); primitive.update(frameState2); primitive.destroy(); expect(primitive.isDestroyed()).toEqual(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/PropertyAttributePropertySpec.js var import__587 = __toESM(require_Cesium(), 1); describe("Scene/PropertyAttributeProperty", function() { let classProperty; let extras; let extensions; let propertyAttributeProperty; beforeAll(function() { classProperty = import__587.MetadataClassProperty.fromJson({ id: "intensity", property: { type: "SCALAR", componentType: "FLOAT32" } }); extras = { description: "Extra" }; extensions = { EXT_other_extension: {} }; const property = { attribute: "_INTENSITY", extensions, extras }; propertyAttributeProperty = new import__587.PropertyAttributeProperty({ property, classProperty }); }); it("creates property attribute property", function() { expect(propertyAttributeProperty.attribute).toBe("_INTENSITY"); expect(propertyAttributeProperty.hasValueTransform).toBe(false); expect(propertyAttributeProperty.offset).toBe(0); expect(propertyAttributeProperty.scale).toBe(1); expect(propertyAttributeProperty.extras).toBe(extras); expect(propertyAttributeProperty.extensions).toBe(extensions); expect(propertyAttributeProperty.classProperty).toBe(classProperty); }); it("constructor throws without property", function() { expect(function() { return new import__587.PropertyAttributeProperty({ property: void 0, classProperty }); }).toThrowDeveloperError(); }); it("constructor throws without classProperty", function() { expect(function() { return new import__587.PropertyAttributeProperty({ property: {}, classProperty: void 0 }); }).toThrowDeveloperError(); }); it("creates property with value transform from class definition", function() { const classProperty2 = import__587.MetadataClassProperty.fromJson({ id: "transformed", property: { type: "SCALAR", componentType: "UINT8", normalized: true, offset: 1, scale: 2 } }); propertyAttributeProperty = new import__587.PropertyAttributeProperty({ property: { attribute: "_TRANSFORMED" }, classProperty: classProperty2 }); expect(propertyAttributeProperty.attribute).toBe("_TRANSFORMED"); expect(propertyAttributeProperty.hasValueTransform).toBe(true); expect(propertyAttributeProperty.offset).toBe(1); expect(propertyAttributeProperty.scale).toBe(2); }); it("creates property with value transform override", function() { const classProperty2 = import__587.MetadataClassProperty.fromJson({ id: "transformed", property: { type: "SCALAR", componentType: "UINT8", normalized: true, offset: 1, scale: 2 } }); propertyAttributeProperty = new import__587.PropertyAttributeProperty({ property: { attribute: "_TRANSFORMED", offset: 2, scale: 4 }, classProperty: classProperty2 }); expect(propertyAttributeProperty.attribute).toBe("_TRANSFORMED"); expect(propertyAttributeProperty.hasValueTransform).toBe(true); expect(propertyAttributeProperty.offset).toBe(2); expect(propertyAttributeProperty.scale).toBe(4); }); it("unpacks property and scale for vectors and matrices", function() { let classProperty2 = import__587.MetadataClassProperty.fromJson({ id: "transformed", property: { type: "VEC2", componentType: "UINT8", normalized: true, offset: [1, 2], scale: [2, 4] } }); propertyAttributeProperty = new import__587.PropertyAttributeProperty({ property: { attribute: "_TRANSFORMED" }, classProperty: classProperty2 }); expect(propertyAttributeProperty.attribute).toBe("_TRANSFORMED"); expect(propertyAttributeProperty.hasValueTransform).toBe(true); expect(propertyAttributeProperty.offset).toEqual(new import__587.Cartesian2(1, 2)); expect(propertyAttributeProperty.scale).toEqual(new import__587.Cartesian2(2, 4)); classProperty2 = import__587.MetadataClassProperty.fromJson({ id: "transformed", property: { type: "MAT2", componentType: "UINT8", normalized: true, offset: [1, 2, 2, 1], scale: [2, 4, 4, 1] } }); propertyAttributeProperty = new import__587.PropertyAttributeProperty({ property: { attribute: "_TRANSFORMED" }, classProperty: classProperty2 }); expect(propertyAttributeProperty.attribute).toBe("_TRANSFORMED"); expect(propertyAttributeProperty.hasValueTransform).toBe(true); expect(propertyAttributeProperty.offset).toEqual(new import__587.Matrix2(1, 2, 2, 1)); expect(propertyAttributeProperty.scale).toEqual(new import__587.Matrix2(2, 4, 4, 1)); }); }); // packages/engine/Specs/Scene/PropertyAttributeSpec.js var import__588 = __toESM(require_Cesium(), 1); describe("Scene/PropertyAttribute", function() { let classDefinition; let extras; let extensions; let propertyAttribute; beforeAll(function() { classDefinition = import__588.MetadataClass.fromJson({ id: "points", class: { properties: { color: { type: "VEC3", componentType: "UINT8", array: true, count: 3 }, intensity: { type: "SCALAR", componentType: "UINT8" }, pointSize: { type: "SCALAR", componentTYpe: "FLOAT32" } } } }); extras = { description: "Extra" }; extensions = { EXT_other_extension: {} }; const propertyAttributeJson = { class: "points", extras, extensions, properties: { color: { attribute: "_COLOR" }, intensity: { attribute: "_INTENSITY" }, pointSize: { attribute: "_POINT_SIZE" } } }; propertyAttribute = new import__588.PropertyAttribute({ propertyAttribute: propertyAttributeJson, class: classDefinition }); }); it("creates property attribute", function() { expect(propertyAttribute.class).toBe(classDefinition); expect(propertyAttribute.extras).toBe(extras); expect(propertyAttribute.extensions).toBe(extensions); }); it("constructor throws without class", function() { expect(function() { return new import__588.PropertyAttribute({ class: void 0, propertyAttribute: {} }); }).toThrowDeveloperError(); }); it("constructor throws without propertyAttribute", function() { expect(function() { return new import__588.PropertyAttribute({ class: classDefinition, propertyAttribute: void 0 }); }).toThrowDeveloperError(); }); it("getProperty returns property attribute property", function() { expect(propertyAttribute.getProperty("color").attribute).toBe("_COLOR"); expect(propertyAttribute.getProperty("intensity").attribute).toBe( "_INTENSITY" ); expect(propertyAttribute.getProperty("pointSize").attribute).toBe( "_POINT_SIZE" ); }); it("getProperty returns undefined if the property doesn't exist", function() { expect(propertyAttribute.getProperty("other")).toBeUndefined(); }); it("getProperty throws if propertyId is undefined", function() { expect(function() { propertyAttribute.getProperty(void 0); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/PropertyTableSpec.js var import__589 = __toESM(require_Cesium(), 1); describe("Scene/PropertyTable", function() { if (!MetadataTester_default.isSupported()) { return; } const properties = { name: { type: "STRING", semantic: "NAME" }, height: { type: "SCALAR", componentType: "FLOAT32", semantic: "HEIGHT" } }; const propertyValues = { name: ["Building A", "Building B", "Building C"], height: [10, 20, 30] }; const extras = { description: "Extra" }; const extensions = { EXT_other_extension: {} }; function createPropertyTable() { return MetadataTester_default.createPropertyTable({ properties, propertyValues, extras, extensions }); } it("creates property table with default values", function() { const propertyTable = new import__589.PropertyTable({ count: 3 }); expect(propertyTable.count).toBe(3); expect(propertyTable.class).toBeUndefined(); expect(propertyTable.extras).toBeUndefined(); expect(propertyTable.extensions).toBeUndefined(); }); it("creates property table", function() { const propertyTable = createPropertyTable(); expect(propertyTable.count).toBe(3); expect(propertyTable.class).toBeDefined(); expect(propertyTable.getPropertyIds().length).toBe(2); expect(propertyTable.getProperty(0, "name")).toBe("Building A"); expect(propertyTable.getProperty(1, "name")).toBe("Building B"); expect(propertyTable.getProperty(2, "name")).toBe("Building C"); expect(propertyTable.getProperty(0, "height")).toBe(10); expect(propertyTable.getProperty(1, "height")).toBe(20); expect(propertyTable.getProperty(2, "height")).toBe(30); expect(propertyTable.extras).toBe(extras); expect(propertyTable.extensions).toBe(extensions); }); it("constructor throws without count", function() { expect(function() { return new import__589.PropertyTable({}); }).toThrowDeveloperError(); }); it("hasProperty throws without index", function() { const propertyTable = createPropertyTable(); expect(function() { propertyTable.hasProperty(void 0, "name"); }).toThrowDeveloperError(); }); it("hasProperty throws without propertyId", function() { const propertyTable = createPropertyTable(); expect(function() { propertyTable.hasProperty(0, void 0); }).toThrowDeveloperError(); }); it("hasProperty returns true if the feature has this property", function() { const propertyTable = createPropertyTable(); expect(propertyTable.hasProperty(0, "name")).toBe(true); }); it("hasProperty returns false if the feature does not have this property", function() { const propertyTable = createPropertyTable(); expect(propertyTable.hasProperty(0, "numberOfPoints")).toBe(false); }); it("hasPropertyBySemantic throws without index", function() { const propertyTable = createPropertyTable(); expect(function() { propertyTable.hasPropertyBySemantic(void 0, "NAME"); }).toThrowDeveloperError(); }); it("hasPropertyBySemantic throws without semantic", function() { const propertyTable = createPropertyTable(); expect(function() { propertyTable.hasPropertyBySemantic(0, void 0); }).toThrowDeveloperError(); }); it("hasPropertyBySemantic returns true if the feature has a property with the given semantic", function() { const propertyTable = createPropertyTable(); expect(propertyTable.hasPropertyBySemantic(0, "NAME")).toBe(true); }); it("hasPropertyBySemantic returns false if the feature does not a property with the given semantic", function() { const propertyTable = createPropertyTable(); expect(propertyTable.hasPropertyBySemantic(0, "ID")).toBe(false); }); it("propertyExists throws without propertyId", function() { const propertyTable = createPropertyTable(); expect(function() { propertyTable.propertyExists(void 0); }).toThrowDeveloperError(); }); it("propertyExists returns true if the property exists", function() { const propertyTable = createPropertyTable(); expect(propertyTable.propertyExists("name")).toBe(true); }); it("propertyExists returns false if the property does not exist", function() { const propertyTable = createPropertyTable(); expect(propertyTable.propertyExists("numberOfPoints")).toBe(false); }); it("propertyExistsBySemantic throws without semantic", function() { const propertyTable = createPropertyTable(); expect(function() { propertyTable.propertyExistsBySemantic(void 0); }).toThrowDeveloperError(); }); it("propertyExistsBySemantic returns true if the property exists", function() { const propertyTable = createPropertyTable(); expect(propertyTable.propertyExistsBySemantic("NAME")).toBe(true); }); it("propertyExistsBySemantic returns false if the property does not exist", function() { const propertyTable = createPropertyTable(); expect(propertyTable.propertyExistsBySemantic("ID")).toBe(false); }); it("getPropertyIds returns array of property IDs", function() { const propertyTable = createPropertyTable(); const propertyIds = propertyTable.getPropertyIds([]); propertyIds.sort(); expect(propertyIds).toEqual(["height", "name"]); }); it("getProperty returns undefined if a property does not exist", function() { const propertyTable = createPropertyTable(); expect(propertyTable.getProperty(0, "numberOfPoints")).not.toBeDefined(); }); it("getProperty returns the property value", function() { const propertyTable = createPropertyTable(); expect(propertyTable.getProperty(0, "name")).toEqual("Building A"); expect(propertyTable.getProperty(0, "height")).toEqual(10); }); it("setProperty creates properties if they don't exist", function() { const propertyTable = createPropertyTable(); expect(propertyTable._jsonMetadataTable).not.toBeDefined(); propertyTable.setProperty(0, "numberOfPoints", 10); expect(propertyTable._jsonMetadataTable).toBeDefined(); expect(propertyTable.getProperty(0, "numberOfPoints")).toBe(10); }); it("setProperty sets property value", function() { const propertyTable = createPropertyTable(); expect(propertyTable.getProperty(0, "name")).toBe("Building A"); propertyTable.setProperty(0, "name", "Building New"); expect(propertyTable.getProperty(0, "name")).toBe("Building New"); }); it("getPropertyBySemantic returns undefined when there's no property with the given semantic", function() { const propertyTable = createPropertyTable(); expect(propertyTable.getPropertyBySemantic(0, "ID")).not.toBeDefined(); }); it("getPropertyBySemantic returns the property value", function() { const propertyTable = createPropertyTable(); expect(propertyTable.getPropertyBySemantic(0, "NAME")).toEqual( "Building A" ); }); it("getPropertyBySemantic returns undefined if there is no metadataTable", function() { const propertyTable = new import__589.PropertyTable({ count: 3 }); expect(propertyTable.getPropertyBySemantic(0, "NAME")).not.toBeDefined(); }); it("setPropertyBySemantic sets property value", function() { const propertyTable = createPropertyTable(); expect(propertyTable.getPropertyBySemantic(0, "NAME")).toEqual( "Building A" ); expect(propertyTable.setPropertyBySemantic(0, "NAME", "Building New")).toBe( true ); }); it("setPropertyBySemantic returns false if the semantic does not exist", function() { const propertyTable = createPropertyTable(); expect(propertyTable.setPropertyBySemantic(0, "ID", 10)).toBe(false); }); it("setPropertyBySemantic returns false if there is no metadata table", function() { const propertyTable = new import__589.PropertyTable({ count: 3 }); expect(propertyTable.setPropertyBySemantic(0, "NAME")).toBe(false); }); it("getPropertyTypedArray returns typed array", function() { const propertyTable = createPropertyTable(); const expectedTypedArray = new Float32Array([10, 20, 30]); expect(propertyTable.getPropertyTypedArray("height")).toEqual( expectedTypedArray ); }); it("getPropertyTypedArray returns undefined if property does not exist", function() { const propertyTable = createPropertyTable(); expect(propertyTable.getPropertyTypedArray("volume")).toBeUndefined(); }); it("getPropertyTypedArray throws if propertyId is undefined", function() { const propertyTable = createPropertyTable(); expect(function() { propertyTable.getPropertyTypedArray(void 0); }).toThrowDeveloperError(); }); it("getPropertyTypedArrayBySemantic returns typed array", function() { const propertyTable = createPropertyTable(); const expectedTypedArray = new Float32Array([10, 20, 30]); expect(propertyTable.getPropertyTypedArrayBySemantic("HEIGHT")).toEqual( expectedTypedArray ); }); it("getPropertyTypedArrayBySemantic returns undefined if semantic does not exist", function() { const propertyTable = createPropertyTable(); expect(propertyTable.getPropertyTypedArrayBySemantic("ID")).toBeUndefined(); }); it("getPropertyTypedArrayBySemantic throws if semantic is undefined", function() { const propertyTable = createPropertyTable(); expect(function() { propertyTable.getPropertyTypedArrayBySemantic(void 0); }).toThrowDeveloperError(); }); describe("batch table compatibility", function() { const schemaJson = { classes: { box: { properties: { itemId: { type: "SCALAR", componentType: "UINT8" }, itemCount: { type: "SCALAR", componentType: "UINT16" } } } } }; const schema = import__589.MetadataSchema.fromJson(schemaJson); const propertyTableJson = { count: 3, class: "box", properties: { itemId: { bufferView: 0 }, itemCount: { bufferView: 1 } } }; const bufferViews = { 0: new Uint8Array([25, 32, 57]), 1: new Uint8Array([25, 0, 5, 1, 50, 0]) }; const jsonProperties = { priority: [2, 1, 0], uri: ["tree.las", "building.gltf", "map.tif"] }; const count = 3; const hierarchyExtension = { classes: [ { name: "Wheels", length: 2, instances: { tireLocation: ["front", "back"] } }, { name: "Car", length: 1, instances: { color: ["blue"], type: ["sedan"], year: ["2020"] } } ], instancesLength: 3, classIds: [0, 0, 1], parentIds: [2, 2, 2], parentCounts: [1, 1, 0] }; let batchTable; let batchTableJsonOnly; let hierarchy; let metadataTable; beforeEach(function() { const jsonTable = new import__589.JsonMetadataTable({ count, properties: jsonProperties }); hierarchy = new import__589.BatchTableHierarchy({ extension: hierarchyExtension }); metadataTable = new import__589.MetadataTable({ count, properties: propertyTableJson.properties, class: schema.classes.box, bufferViews }); batchTable = new import__589.PropertyTable({ count, metadataTable, jsonMetadataTable: jsonTable, batchTableHierarchy: hierarchy }); batchTableJsonOnly = new import__589.PropertyTable({ count, jsonMetadataTable: jsonTable }); }); it("computes byteLength correctly", function() { const expectedByteLength = metadataTable.byteLength + hierarchy.byteLength; expect(batchTable.byteLength).toBe(expectedByteLength); expect(batchTableJsonOnly.byteLength).toBe(0); }); it("getPropertyIds combines binary, json and hierarchy IDs", function() { const results = batchTable.getPropertyIds(0); expect(results.sort()).toEqual([ "color", "itemCount", "itemId", "priority", "tireLocation", "type", "uri", "year" ]); }); it("hasProperty uses structural metadata", function() { expect(batchTable.hasProperty(0, "itemId")).toBe(true); expect(batchTable.hasProperty(0, "itemCount")).toBe(true); }); it("hasProperty uses JSON metadata", function() { expect(batchTable.hasProperty(0, "priority")).toBe(true); expect(batchTable.hasProperty(0, "uri")).toBe(true); }); it("hasProperty uses batch table hierarchy", function() { expect(batchTable.hasProperty(0, "tireLocation")).toBe(true); expect(batchTable.hasProperty(0, "color")).toBe(true); expect(batchTable.hasProperty(0, "type")).toBe(true); expect(batchTable.hasProperty(0, "year")).toBe(true); expect(batchTable.hasProperty(1, "tireLocation")).toBe(true); expect(batchTable.hasProperty(1, "color")).toBe(true); expect(batchTable.hasProperty(1, "type")).toBe(true); expect(batchTable.hasProperty(1, "year")).toBe(true); expect(batchTable.hasProperty(2, "tireLocation")).toBe(false); expect(batchTable.hasProperty(2, "color")).toBe(true); expect(batchTable.hasProperty(2, "type")).toBe(true); expect(batchTable.hasProperty(2, "year")).toBe(true); }); it("hasProperty returns false for unknown property", function() { expect(batchTable.hasProperty(0, "widgets")).toBe(false); }); it("hasPropertyBySemantic returns false when there is no metadata table", function() { expect(batchTableJsonOnly.hasPropertyBySemantic(0, "NAME")).toBe(false); }); it("propertyExists uses structural metadata", function() { expect(batchTable.propertyExists("itemId")).toBe(true); expect(batchTable.propertyExists("itemCount")).toBe(true); }); it("propertyExists uses JSON metadata", function() { expect(batchTable.propertyExists("priority")).toBe(true); expect(batchTable.propertyExists("uri")).toBe(true); }); it("propertyExists uses batch table hierarchy", function() { expect(batchTable.propertyExists("tireLocation")).toBe(true); expect(batchTable.propertyExists("color")).toBe(true); expect(batchTable.propertyExists("type")).toBe(true); expect(batchTable.propertyExists("year")).toBe(true); }); it("propertyExists returns false for unknown property", function() { expect(batchTable.propertyExists("widgets")).toBe(false); }); it("propertyExistsBySemantic returns false when there is no metadata table", function() { expect(batchTableJsonOnly.propertyExistsBySemantic("NAME")).toBe(false); }); it("getProperty uses structural metadata", function() { expect(batchTable.getProperty(0, "itemId")).toBe(25); expect(batchTable.getProperty(0, "itemCount")).toBe(25); expect(batchTable.getProperty(1, "itemId")).toBe(32); expect(batchTable.getProperty(1, "itemCount")).toBe(261); expect(batchTable.getProperty(2, "itemId")).toBe(57); expect(batchTable.getProperty(2, "itemCount")).toBe(50); }); it("getProperty uses JSON metadata", function() { expect(batchTable.getProperty(0, "priority")).toBe(2); expect(batchTable.getProperty(1, "priority")).toBe(1); expect(batchTable.getProperty(2, "priority")).toBe(0); expect(batchTable.getProperty(0, "uri")).toBe("tree.las"); expect(batchTable.getProperty(1, "uri")).toBe("building.gltf"); expect(batchTable.getProperty(2, "uri")).toBe("map.tif"); }); it("getProperty uses batch table hierarchy", function() { expect(batchTable.getProperty(0, "tireLocation")).toBe("front"); expect(batchTable.getProperty(0, "color")).toBe("blue"); expect(batchTable.getProperty(0, "type")).toBe("sedan"); expect(batchTable.getProperty(0, "year")).toBe("2020"); expect(batchTable.getProperty(1, "tireLocation")).toBe("back"); expect(batchTable.getProperty(1, "color")).toBe("blue"); expect(batchTable.getProperty(1, "type")).toBe("sedan"); expect(batchTable.getProperty(1, "year")).toBe("2020"); expect(batchTable.getProperty(2, "tireLocation")).not.toBeDefined(); expect(batchTable.getProperty(2, "color")).toBe("blue"); expect(batchTable.getProperty(2, "type")).toBe("sedan"); expect(batchTable.getProperty(2, "year")).toBe("2020"); }); it("getProperty returns undefined for unknown propertyId", function() { expect(batchTable.getProperty(0, "widgets")).not.toBeDefined(); }); it("setProperty uses structural metadata", function() { expect(batchTable.getProperty(0, "itemCount")).toBe(25); batchTable.setProperty(0, "itemCount", 24); expect(batchTable.getProperty(0, "itemCount")).toBe(24); }); it("setProperty uses JSON metadata", function() { expect(batchTable.getProperty(0, "uri")).toBe("tree.las"); batchTable.setProperty(0, "uri", "tree_final.las"); expect(batchTable.getProperty(0, "uri")).toBe("tree_final.las"); }); it("setProperty uses batch table hierarchy", function() { expect(batchTable.getProperty(0, "tireLocation")).toBe("front"); expect(batchTable.getProperty(0, "color")).toBe("blue"); expect(batchTable.getProperty(2, "tireLocation")).not.toBeDefined(); expect(batchTable.getProperty(2, "color")).toBe("blue"); batchTable.setProperty(0, "tireLocation", "back"); batchTable.setProperty(2, "color", "navy"); expect(batchTable.getProperty(0, "tireLocation")).toBe("back"); expect(batchTable.getProperty(0, "color")).toBe("navy"); expect(batchTable.getProperty(2, "tireLocation")).not.toBeDefined(); expect(batchTable.getProperty(2, "color")).toBe("navy"); }); it("setProperty creates a new property for unknown propertyId", function() { expect(batchTable.getProperty(0, "widgets")).not.toBeDefined(); batchTable.setProperty(0, "widgets", 5); expect(batchTable.getProperty(0, "widgets")).toBe(5); }); it("getPropertyTypedArray returns undefined for JSON and hierarchy properties", function() { expect(batchTable.getPropertyTypedArray("itemId")).toBeDefined(); expect(batchTable.getPropertyTypedArray("priority")).not.toBeDefined(); expect( batchTable.getPropertyTypedArray("tireLocation") ).not.toBeDefined(); }); it("getPropertyTypedArray returns undefined when there is no metadata table", function() { expect( batchTableJsonOnly.getPropertyTypedArray("priority") ).not.toBeDefined(); }); it("getPropertyTypedArrayBySemantic returns undefined when there is no metadata table", function() { expect( batchTableJsonOnly.getPropertyTypedArrayBySemantic("PRIORITY") ).not.toBeDefined(); }); it("isClass throws without featureId", function() { expect(function() { return batchTable.isClass(void 0, "Wheels"); }).toThrowDeveloperError(); }); it("isClass throws for out-of-bounds featureId", function() { expect(function() { return batchTable.isClass(-1, "Wheels"); }).toThrowDeveloperError(); expect(function() { return batchTable.isClass(10, "Wheels"); }).toThrowDeveloperError(); }); it("isClass throws without className", function() { expect(function() { return batchTable.isClass(0, void 0); }).toThrowDeveloperError(); }); it("isClass works for batch table hierarchy", function() { expect(batchTable.isClass(0, "Wheels")).toBe(true); expect(batchTable.isClass(0, "Car")).toBe(true); expect(batchTable.isClass(0, "Wings")).toBe(false); }); it("isClass returns false without batch table hierarchy", function() { expect(batchTableJsonOnly.isClass(0, "Wheels")).toBe(false); }); it("isExactClass throws without featureId", function() { expect(function() { return batchTable.isExactClass(void 0, "Wheels"); }).toThrowDeveloperError(); }); it("isExactClass throws for out-of-bounds featureId", function() { expect(function() { return batchTable.isExactClass(-1, "Wheels"); }).toThrowDeveloperError(); expect(function() { return batchTable.isExactClass(10, "Wheels"); }).toThrowDeveloperError(); }); it("isExactClass throws without className", function() { expect(function() { return batchTable.isExactClass(0, void 0); }).toThrowDeveloperError(); }); it("isExactClass works for batch table hierarchy", function() { expect(batchTable.isExactClass(0, "Wheels")).toBe(true); expect(batchTable.isExactClass(0, "Car")).toBe(false); expect(batchTable.isExactClass(0, "Wings")).toBe(false); expect(batchTable.isExactClass(2, "Wheels")).toBe(false); expect(batchTable.isExactClass(2, "Car")).toBe(true); }); it("isExactClass returns false without batch table hierarchy", function() { expect(batchTableJsonOnly.isExactClass(0, "Wheels")).toBe(false); }); it("getExactClassName throws without featureId", function() { expect(function() { return batchTable.getExactClassName(void 0); }).toThrowDeveloperError(); }); it("getExactClassName throws for out-of-bounds featureId", function() { expect(function() { return batchTable.getExactClassName(-1); }).toThrowDeveloperError(); expect(function() { return batchTable.getExactClassName(10); }).toThrowDeveloperError(); }); it("getExactClassName works for batch table hierarchy", function() { expect(batchTable.getExactClassName(0)).toBe("Wheels"); expect(batchTable.getExactClassName(2)).toBe("Car"); }); it("getExactClassName returns undefined without batch table hierarchy", function() { expect(batchTableJsonOnly.getExactClassName(0)).toBe(void 0); }); }); }); // packages/engine/Specs/Scene/PropertyTexturePropertySpec.js var import__590 = __toESM(require_Cesium(), 1); describe( "Scene/PropertyTextureProperty", function() { let classProperty; let context; let texture; let extras; let extensions; let propertyTextureProperty; beforeAll(function() { classProperty = import__590.MetadataClassProperty.fromJson({ id: "color", property: { array: true, type: "SCALAR", componentType: "UINT8", count: 3 } }); context = createContext_default(); texture = new import__590.Texture({ context, pixelFormat: import__590.PixelFormat.RGBA, pixelDatatype: import__590.PixelDatatype.UNSIGNED_BYTE, source: { arrayBufferView: new Uint8Array([1, 2, 3, 4]), width: 1, height: 1 } }); extras = { description: "Extra" }; extensions = { KHR_texture_transform: { offset: [0.5, 0.5], scale: [0.1, 0.2], texCoord: 1 } }; const property = { channels: [0, 1, 2], index: 0, texCoord: 0, extensions, extras }; propertyTextureProperty = new import__590.PropertyTextureProperty({ property, classProperty, textures: { 0: texture } }); }); afterAll(function() { texture.destroy(); context.destroyForSpecs(); }); function makeProperty(options) { const classProperty2 = import__590.MetadataClassProperty.fromJson({ id: "propertyId", property: options.property }); return new import__590.PropertyTextureProperty({ property: { channels: options.channels, index: 0, texCoord: 0 }, classProperty: classProperty2, textures: { 0: texture } }); } it("creates property texture property", function() { expect(propertyTextureProperty.extras).toBe(extras); expect(propertyTextureProperty.extensions).toBe(extensions); expect(propertyTextureProperty.classProperty).toBe(classProperty); const expectedTransform = new import__590.Matrix3( 0.1, 0, 0.5, 0, 0.2, 0.5, 0, 0, 1 ); const modelTextureReader = propertyTextureProperty.textureReader; expect(modelTextureReader.texture).toBe(texture); expect(modelTextureReader.texCoord).toBe(1); expect(modelTextureReader.transform).toEqual(expectedTransform); expect(modelTextureReader.channels).toBe("rgb"); }); it("creates property texture property with default channels", function() { const property = makeProperty({ property: { type: "SCALAR", componentType: "UINT8", normalized: true } }); expect(property.textureReader.channels).toBe("r"); }); it("constructor throws without property", function() { expect(function() { return new import__590.PropertyTextureProperty({ property: void 0, classProperty, textures: {} }); }).toThrowDeveloperError(); }); it("constructor throws without classProperty", function() { expect(function() { return new import__590.PropertyTextureProperty({ property: {}, classProperty: void 0, textures: {} }); }).toThrowDeveloperError(); }); it("constructor throws without textures", function() { expect(function() { return new import__590.PropertyTextureProperty({ property: {}, classProperty, textures: void 0 }); }).toThrowDeveloperError(); }); it("isGpuCompatible returns true for UINT8-based properties", function() { const properties = [ makeProperty({ channels: [0], property: { type: "SCALAR", componentType: "UINT8", normalized: true } }), makeProperty({ channels: [0, 1], property: { type: "VEC2", componentType: "UINT8" } }), makeProperty({ channels: [0, 1, 2, 3], property: { array: true, count: 4, type: "SCALAR", componentType: "UINT8", normalized: true } }) ]; for (let i = 0; i < properties.length; i++) { expect(properties[i].isGpuCompatible()).toBe(true); } }); it("isGpuCompatible returns false for other types", function() { const properties = [ makeProperty({ channels: [0], property: { type: "SCALAR", componentType: "INT8" } }), makeProperty({ channels: [0, 1], property: { type: "VEC2", componentType: "UINT16" } }), makeProperty({ channels: [0, 1, 2, 3], property: { array: true, type: "SCALAR", componentType: "UINT8", normalized: true } }), makeProperty({ channels: [0, 1, 2, 3], property: { type: "STRING" } }), makeProperty({ channels: [0, 1, 2, 3], property: { type: "MAT2", componentType: "UINT8" } }) ]; for (let i = 0; i < properties.length; i++) { expect(properties[i].isGpuCompatible()).toBe(false); } }); it("getGlslType returns floating point types for normalized UINT8 properties", function() { const properties = [ makeProperty({ channels: [0], property: { type: "SCALAR", componentType: "UINT8", normalized: true } }), makeProperty({ channels: [0, 1], property: { type: "VEC2", componentType: "UINT8", normalized: true } }), makeProperty({ channels: [0, 1, 2], property: { array: true, count: 3, type: "SCALAR", componentType: "UINT8", normalized: true } }) ]; const expectedTypes = ["float", "vec2", "vec3"]; for (let i = 0; i < properties.length; i++) { expect(properties[i].getGlslType()).toBe(expectedTypes[i]); } }); it("getGlslType returns integer types for non-normalized UINT8 properties", function() { const properties = [ makeProperty({ channels: [0], property: { type: "SCALAR", componentType: "UINT8" } }), makeProperty({ channels: [0, 1], property: { type: "VEC2", componentType: "UINT8" } }), makeProperty({ channels: [0, 1, 2], property: { array: true, count: 3, type: "SCALAR", componentType: "UINT8" } }) ]; const expectedTypes = ["int", "ivec2", "ivec3"]; for (let i = 0; i < properties.length; i++) { expect(properties[i].getGlslType()).toBe(expectedTypes[i]); } }); it("unpackInShader passes through normalized values unchanged", function() { const properties = [ makeProperty({ channels: [0], property: { type: "SCALAR", componentType: "UINT8", normalized: true } }), makeProperty({ channels: [0, 1], property: { type: "VEC2", componentType: "UINT8", normalized: true } }), makeProperty({ channels: [0, 1, 2], property: { array: true, count: 3, type: "SCALAR", componentType: "UINT8", normalized: true } }) ]; for (let i = 0; i < properties.length; i++) { expect(properties[i].unpackInShader("x")).toBe("x"); } }); it("unpackInShader un-normalizes integer values", function() { const properties = [ makeProperty({ channels: [0], property: { type: "SCALAR", componentType: "UINT8" } }), makeProperty({ channels: [0, 1], property: { type: "VEC2", componentType: "UINT8" } }), makeProperty({ channels: [0, 1, 2], property: { array: true, count: 3, type: "SCALAR", componentType: "UINT8" } }) ]; const expectedTypes = ["int", "ivec2", "ivec3"]; for (let i = 0; i < properties.length; i++) { const expected = `${expectedTypes[i]}(255.0 * x)`; expect(properties[i].unpackInShader("x")).toEqual(expected); } }); }, "WebGL" ); // packages/engine/Specs/Scene/PropertyTextureSpec.js var import__591 = __toESM(require_Cesium(), 1); describe( "Scene/PropertyTexture", function() { let classDefinition; let context; let texture0; let texture1; let extras; let extensions; let propertyTexture; beforeAll(function() { classDefinition = import__591.MetadataClass.fromJson({ id: "map", class: { properties: { color: { type: "VEC3", componentType: "UINT8" }, intensity: { type: "SCALAR", componentType: "UINT8" }, ortho: { type: "SCALAR", componentType: "UINT8", normalized: true } } } }); context = createContext_default(); texture0 = new import__591.Texture({ context, pixelFormat: import__591.PixelFormat.RGBA, pixelDatatype: import__591.PixelDatatype.UNSIGNED_BYTE, source: { arrayBufferView: new Uint8Array([1, 2, 3, 4]), width: 1, height: 1 } }); texture1 = new import__591.Texture({ context, pixelFormat: import__591.PixelFormat.LUMINANCE, pixelDatatype: import__591.PixelDatatype.UNSIGNED_BYTE, source: { arrayBufferView: new Uint8Array([5]), width: 1, height: 1 } }); extras = { description: "Extra" }; extensions = { EXT_other_extension: {} }; const propertyTextureJson = { class: "map", extras, extensions, properties: { color: { channels: [0, 1, 2], index: 0, texCoord: 0 }, intensity: { channels: [3], index: 0, texCoord: 0 }, ortho: { channels: [0], index: 1, texCoord: 0 } } }; propertyTexture = new import__591.PropertyTexture({ propertyTexture: propertyTextureJson, class: classDefinition, textures: { 0: texture0, 1: texture1 } }); }); afterAll(function() { texture0.destroy(); texture1.destroy(); context.destroyForSpecs(); }); it("creates property texture", function() { expect(propertyTexture.class).toBe(classDefinition); expect(propertyTexture.extras).toBe(extras); expect(propertyTexture.extensions).toBe(extensions); }); it("constructor throws without propertyTexture", function() { expect(function() { return new import__591.PropertyTexture({ class: classDefinition, textures: {} }); }).toThrowDeveloperError(); }); it("constructor throws without class", function() { expect(function() { return new import__591.PropertyTexture({ propertyTexture: {}, textures: {} }); }).toThrowDeveloperError(); }); it("constructor throws without textures", function() { expect(function() { return new import__591.PropertyTexture({ propertyTexture: {}, class: classDefinition }); }).toThrowDeveloperError(); }); it("getProperty returns property texture property", function() { expect(propertyTexture.getProperty("color")).toBeDefined(); expect(propertyTexture.getProperty("intensity")).toBeDefined(); expect(propertyTexture.getProperty("ortho")).toBeDefined(); }); it("getProperty returns undefined if the property doesn't exist", function() { expect(propertyTexture.getProperty("other")).toBeUndefined(); }); it("getProperty throws if propertyId is undefined", function() { expect(function() { propertyTexture.getProperty(void 0); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Scene/QuadtreePrimitiveSpec.js var import__592 = __toESM(require_Cesium(), 1); describe("Scene/QuadtreePrimitive", function() { describe("selectTilesForRendering", function() { let scene2; let camera; let frameState2; let quadtree; let mockTerrain; let tileProvider; let imageryLayerCollection; let surfaceShaderSet; let processor; let rootTiles; beforeEach(function() { scene2 = { mapProjection: new import__592.GeographicProjection(), drawingBufferWidth: 1e3, drawingBufferHeight: 1e3 }; camera = new import__592.Camera(scene2); frameState2 = { frameNumber: 0, passes: { render: true }, camera, fog: { enabled: false }, context: { drawingBufferWidth: scene2.drawingBufferWidth, drawingBufferHeight: scene2.drawingBufferHeight }, mode: import__592.SceneMode.SCENE3D, commandList: [], cullingVolume: jasmine.createSpyObj("CullingVolume", [ "computeVisibility" ]), afterRender: [], pixelRatio: 1, verticalExaggeration: 1, verticalExaggerationRelativeHeight: 0, globeTranslucencyState: new import__592.GlobeTranslucencyState() }; frameState2.cullingVolume.computeVisibility.and.returnValue( import__592.Intersect.INTERSECTING ); imageryLayerCollection = new import__592.ImageryLayerCollection(); surfaceShaderSet = jasmine.createSpyObj("SurfaceShaderSet", [ "getShaderProgram" ]); mockTerrain = new MockTerrainProvider_default(); tileProvider = new import__592.GlobeSurfaceTileProvider({ terrainProvider: mockTerrain, imageryLayers: imageryLayerCollection, surfaceShaderSet }); quadtree = new import__592.QuadtreePrimitive({ tileProvider }); processor = new TerrainTileProcessor_default( frameState2, mockTerrain, imageryLayerCollection ); quadtree.render(frameState2); rootTiles = quadtree._levelZeroTiles; processor.mockWebGL(); }); function process(quadtreePrimitive, callback) { return new Promise((resolve) => { function next() { ++frameState2.frameNumber; quadtree.beginFrame(frameState2); quadtree.render(frameState2); quadtree.endFrame(frameState2); if (callback()) { setTimeout(next, 0); } else { resolve(); } } next(); }); } it("must be constructed with a tileProvider", function() { expect(function() { return new import__592.QuadtreePrimitive(); }).toThrowDeveloperError(); expect(function() { return new import__592.QuadtreePrimitive({}); }).toThrowDeveloperError(); }); it("selects nothing when the root tiles are not yet ready", function() { quadtree.render(frameState2); expect(quadtree._tilesToRender.length).toBe(0); }); it("selects root tiles once they are ready", function() { mockTerrain.requestTileGeometryWillSucceed(rootTiles[0]).requestTileGeometryWillSucceed(rootTiles[1]).createMeshWillSucceed(rootTiles[0]).createMeshWillSucceed(rootTiles[1]); return processor.process(rootTiles).then(function() { quadtree.render(frameState2); expect(quadtree._tilesToRender.length).toBeGreaterThan(0); expect( quadtree._tilesToRender.filter(function(tile) { return tile.level === 0; }).length ).toBe(quadtree._tilesToRender.length); }); }); it("selects deeper tiles once they are renderable", function() { mockTerrain.requestTileGeometryWillSucceed(rootTiles[0]).requestTileGeometryWillSucceed(rootTiles[1]).createMeshWillSucceed(rootTiles[0]).createMeshWillSucceed(rootTiles[1]); rootTiles[0].children.forEach(function(tile) { mockTerrain.requestTileGeometryWillSucceed(tile).createMeshWillSucceed(tile); expect(tile.renderable).toBe(false); }); return processor.process(rootTiles).then(function() { quadtree.render(frameState2); expect(quadtree._tilesToRender.length).toBeGreaterThan(0); expect( quadtree._tilesToRender.filter(function(tile) { return tile.level === 0; }).length ).toBe(quadtree._tilesToRender.length); return processor.process(rootTiles[0].children); }).then(function() { quadtree.render(frameState2); expect(quadtree._tilesToRender).toContain( rootTiles[0].southwestChild ); expect(quadtree._tilesToRender).toContain( rootTiles[0].southeastChild ); expect(quadtree._tilesToRender).toContain( rootTiles[0].northwestChild ); expect(quadtree._tilesToRender).toContain( rootTiles[0].northeastChild ); }); }); it("skips loading levels when tiles are known to be available", function() { rootTiles.forEach(function(tile) { mockTerrain.willBeAvailable(tile).requestTileGeometryWillSucceed(tile).createMeshWillSucceed(tile); tile.children.forEach(function(tile2) { mockTerrain.willBeAvailable(tile2).requestTileGeometryWillSucceed(tile2).createMeshWillSucceed(tile2); tile2.children.forEach(function(tile3) { mockTerrain.willBeAvailable(tile3).requestTileGeometryWillSucceed(tile3).createMeshWillSucceed(tile3); }); }); }); quadtree.preloadAncestors = false; const lookAtTile = rootTiles[0].southwestChild.northeastChild; setCameraPosition( quadtree, frameState2, import__592.Rectangle.center(lookAtTile.rectangle), lookAtTile.level ); spyOn(mockTerrain, "requestTileGeometry").and.callThrough(); return process(quadtree, function() { expect(quadtree._tilesToRender).not.toContain(lookAtTile.parent); const lookAtTileRendered = quadtree._tilesToRender.indexOf(lookAtTile) >= 0; const continueProcessing = !lookAtTileRendered; return continueProcessing; }).then(function() { expect(quadtree._tilesToRender).toContain(lookAtTile); expect(lookAtTile.data.fill).toBeUndefined(); expect(lookAtTile.data.vertexArray).toBeDefined(); const parent = lookAtTile.parent; mockTerrain.requestTileGeometry.calls.allArgs().forEach(function(call) { expect(call.slice(0, 3)).not.toEqual([ parent.x, parent.y, parent.level ]); }); }); }); it("does not skip loading levels if availability is unknown", function() { rootTiles.forEach(function(tile) { mockTerrain.requestTileGeometryWillSucceed(tile).createMeshWillSucceed(tile); tile.children.forEach(function(tile2) { mockTerrain.willBeAvailable(tile2).requestTileGeometryWillSucceed(tile2).createMeshWillSucceed(tile2); tile2.children.forEach(function(tile3) { mockTerrain.willBeUnknownAvailability(tile3).requestTileGeometryWillSucceed(tile3).createMeshWillSucceed(tile3); }); }); }); quadtree.preloadAncestors = false; const lookAtTile = rootTiles[0].southwestChild.northeastChild; setCameraPosition( quadtree, frameState2, import__592.Rectangle.center(lookAtTile.rectangle), lookAtTile.level ); spyOn(mockTerrain, "requestTileGeometry").and.callThrough(); return process(quadtree, function() { expect(quadtree._tilesToRender).not.toContain(lookAtTile.parent); const lookAtTileRendered = quadtree._tilesToRender.indexOf(lookAtTile) >= 0; const continueProcessing = !lookAtTileRendered; return continueProcessing; }).then(function() { expect(quadtree._tilesToRender).toContain(lookAtTile); expect(lookAtTile.data.fill).toBeUndefined(); expect(lookAtTile.data.vertexArray).toBeDefined(); const parent = lookAtTile.parent; const allArgs = mockTerrain.requestTileGeometry.calls.allArgs(); const parentArgsIndex = allArgs.indexOf( allArgs.filter(function(call) { return call[0] === parent.x && call[1] === parent.y && call[2] === parent.level; })[0] ); const lookAtArgsIndex = allArgs.indexOf( allArgs.filter(function(call) { return call[0] === lookAtTile.x && call[1] === lookAtTile.y && call[2] === lookAtTile.level; })[0] ); expect(parentArgsIndex).toBeLessThan(lookAtArgsIndex); }); }); it("loads and renders intermediate tiles according to loadingDescendantLimit", function() { rootTiles.forEach(function(tile) { mockTerrain.willBeAvailable(tile).requestTileGeometryWillSucceed(tile).createMeshWillSucceed(tile); tile.children.forEach(function(tile2) { mockTerrain.willBeAvailable(tile2).requestTileGeometryWillSucceed(tile2).createMeshWillSucceed(tile2); tile2.children.forEach(function(tile3) { mockTerrain.willBeAvailable(tile3).requestTileGeometryWillSucceed(tile3).createMeshWillSucceed(tile3); }); }); }); quadtree.preloadAncestors = false; quadtree.loadingDescendantLimit = 1; const lookAtTile = rootTiles[0].southwestChild.northeastChild; setCameraPosition( quadtree, frameState2, import__592.Rectangle.center(lookAtTile.rectangle), lookAtTile.level ); spyOn(mockTerrain, "requestTileGeometry").and.callThrough(); return process(quadtree, function() { const lookAtTileParentRendered = quadtree._tilesToRender.indexOf(lookAtTile.parent) >= 0; const continueProcessing = !lookAtTileParentRendered; return continueProcessing; }).then(function() { expect(quadtree._tilesToRender).toContain(lookAtTile.parent); expect(lookAtTile.parent.data.fill).toBeUndefined(); expect(lookAtTile.parent.data.vertexArray).toBeDefined(); return process(quadtree, function() { const lookAtTileRendered = quadtree._tilesToRender.indexOf(lookAtTile) >= 0; const continueProcessing = !lookAtTileRendered; return continueProcessing; }); }).then(function() { expect(quadtree._tilesToRender).toContain(lookAtTile); expect(lookAtTile.data.fill).toBeUndefined(); expect(lookAtTile.data.vertexArray).toBeDefined(); }); }); it("continues rendering more detailed tiles when camera zooms out and an appropriate ancestor is not yet renderable", function() { rootTiles.forEach(function(tile) { mockTerrain.willBeAvailable(tile).requestTileGeometryWillSucceed(tile).createMeshWillSucceed(tile); tile.children.forEach(function(tile2) { mockTerrain.willBeAvailable(tile2).requestTileGeometryWillSucceed(tile2).createMeshWillSucceed(tile2); tile2.children.forEach(function(tile3) { mockTerrain.willBeAvailable(tile3).requestTileGeometryWillSucceed(tile3).createMeshWillSucceed(tile3); }); }); }); quadtree.preloadAncestors = false; const lookAtTile = rootTiles[0].southwestChild.northeastChild; setCameraPosition( quadtree, frameState2, import__592.Rectangle.center(lookAtTile.rectangle), lookAtTile.level ); spyOn(mockTerrain, "requestTileGeometry").and.callThrough(); return process(quadtree, function() { expect(quadtree._tilesToRender).not.toContain(lookAtTile.parent); const lookAtTileRendered = quadtree._tilesToRender.indexOf(lookAtTile) >= 0; const continueProcessing = !lookAtTileRendered; return continueProcessing; }).then(function() { setCameraPosition( quadtree, frameState2, import__592.Rectangle.center(lookAtTile.rectangle), lookAtTile.parent.level ); quadtree.beginFrame(frameState2); quadtree.render(frameState2); quadtree.endFrame(frameState2); expect(quadtree._tilesToRender).toContain(lookAtTile); expect(quadtree._tilesToRender).not.toContain(lookAtTile.parent); return process(quadtree, function() { const parentRendered = quadtree._tilesToRender.indexOf(lookAtTile.parent) >= 0; const continueProcessing = !parentRendered; return continueProcessing; }); }).then(function() { expect(quadtree._tilesToRender).not.toContain(lookAtTile); expect(quadtree._tilesToRender).toContain(lookAtTile.parent); }); }); it("renders a fill for a newly-visible tile", function() { rootTiles.forEach(function(tile) { mockTerrain.willBeAvailable(tile).requestTileGeometryWillSucceed(tile).createMeshWillSucceed(tile); tile.children.forEach(function(tile2) { mockTerrain.willBeAvailable(tile2).requestTileGeometryWillSucceed(tile2).createMeshWillSucceed(tile2); tile2.children.forEach(function(tile3) { mockTerrain.willBeAvailable(tile3).requestTileGeometryWillSucceed(tile3).createMeshWillSucceed(tile3); }); }); }); quadtree.preloadAncestors = false; const visibleTile = rootTiles[0].southwestChild.northeastChild; const notVisibleTile = rootTiles[0].southwestChild.northwestChild; frameState2.cullingVolume.computeVisibility.and.callFake(function(boundingVolume) { if (!(0, import__592.defined)(visibleTile.data)) { return import__592.Intersect.INTERSECTING; } if (boundingVolume === visibleTile.data.tileBoundingRegion.boundingVolume) { return import__592.Intersect.INTERSECTING; } else if (boundingVolume === notVisibleTile.data.tileBoundingRegion.boundingVolume) { return import__592.Intersect.OUTSIDE; } return import__592.Intersect.INTERSECTING; }); setCameraPosition( quadtree, frameState2, import__592.Rectangle.center(visibleTile.rectangle), visibleTile.level ); spyOn(mockTerrain, "requestTileGeometry").and.callThrough(); return process(quadtree, function() { const visibleTileRendered = quadtree._tilesToRender.indexOf(visibleTile) >= 0; const continueProcessing = !visibleTileRendered; return continueProcessing; }).then(function() { expect(quadtree._tilesToRender).not.toContain(notVisibleTile); frameState2.cullingVolume.computeVisibility.and.returnValue( import__592.Intersect.INTERSECTING ); quadtree.beginFrame(frameState2); quadtree.render(frameState2); quadtree.endFrame(frameState2); expect(quadtree._tilesToRender).toContain(visibleTile); expect(quadtree._tilesToRender).toContain(notVisibleTile); expect(notVisibleTile.data.fill).toBeDefined(); expect(notVisibleTile.data.vertexArray).toBeUndefined(); }); }); }); describe( "with mock tile provider", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); scene2.render(); }); afterAll(function() { scene2.destroyForSpecs(); }); function createSpyTileProvider() { const result = jasmine.createSpyObj("tileProvider", [ "getQuadtree", "setQuadtree", "getReady", "getTilingScheme", "getErrorEvent", "initialize", "updateImagery", "beginUpdate", "endUpdate", "getLevelMaximumGeometricError", "loadTile", "computeTileVisibility", "showTileThisFrame", "computeDistanceToTile", "canRefine", "isDestroyed", "destroy" ]); Object.defineProperties(result, { quadtree: { get: result.getQuadtree, set: result.setQuadtree }, tilingScheme: { get: result.getTilingScheme }, errorEvent: { get: result.getErrorEvent } }); const tilingScheme = new import__592.GeographicTilingScheme(); result.getTilingScheme.and.returnValue(tilingScheme); result.canRefine.and.callFake(function(tile) { return tile.renderable; }); return result; } it("calls initialize, beginUpdate, loadTile, and endUpdate", function() { const tileProvider = createSpyTileProvider(); tileProvider.getReady.and.returnValue(true); const quadtree = new import__592.QuadtreePrimitive({ tileProvider }); quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); expect(tileProvider.initialize).toHaveBeenCalled(); expect(tileProvider.beginUpdate).toHaveBeenCalled(); expect(tileProvider.loadTile).toHaveBeenCalled(); expect(tileProvider.endUpdate).toHaveBeenCalled(); }); it("shows the root tiles when they are ready and visible", function() { const tileProvider = createSpyTileProvider(); tileProvider.getReady.and.returnValue(true); tileProvider.computeTileVisibility.and.returnValue(import__592.Visibility.FULL); tileProvider.loadTile.and.callFake(function(frameState2, tile) { tile.renderable = true; }); const quadtree = new import__592.QuadtreePrimitive({ tileProvider }); quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); expect(tileProvider.showTileThisFrame).toHaveBeenCalled(); }); it("stops loading a tile that moves to the DONE state", function() { const tileProvider = createSpyTileProvider(); tileProvider.getReady.and.returnValue(true); tileProvider.computeTileVisibility.and.returnValue(import__592.Visibility.FULL); let calls = 0; tileProvider.loadTile.and.callFake(function(frameState2, tile) { ++calls; tile.state = import__592.QuadtreeTileLoadState.DONE; }); const quadtree = new import__592.QuadtreePrimitive({ tileProvider }); quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); expect(calls).toBe(2); quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); expect(calls).toBe(2); }); it("tileLoadProgressEvent is raised when tile loaded and when new children discovered", function() { const eventHelper = new import__592.EventHelper(); const tileProvider = createSpyTileProvider(); tileProvider.getReady.and.returnValue(true); tileProvider.computeTileVisibility.and.returnValue(import__592.Visibility.FULL); const quadtree = new import__592.QuadtreePrimitive({ tileProvider }); const progressEventSpy = jasmine.createSpy("progressEventSpy"); eventHelper.add(quadtree.tileLoadProgressEvent, progressEventSpy); quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); quadtree.update(scene2.frameState); scene2.renderForSpecs(); expect(progressEventSpy.calls.mostRecent().args[0]).toEqual(2); quadtree._levelZeroTiles[0].state = import__592.QuadtreeTileLoadState.DONE; quadtree._levelZeroTiles[1].state = import__592.QuadtreeTileLoadState.LOADING; quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); quadtree.update(scene2.frameState); scene2.renderForSpecs(); expect(progressEventSpy.calls.mostRecent().args[0]).toEqual(1); quadtree._levelZeroTiles[1].state = import__592.QuadtreeTileLoadState.DONE; quadtree._levelZeroTiles[1].renderable = true; quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); quadtree.update(scene2.frameState); scene2.renderForSpecs(); expect(progressEventSpy.calls.mostRecent().args[0]).toEqual(4); }); it("forEachLoadedTile does not enumerate tiles in the START state", function() { const tileProvider = createSpyTileProvider(); tileProvider.getReady.and.returnValue(true); tileProvider.computeTileVisibility.and.returnValue(import__592.Visibility.FULL); tileProvider.computeDistanceToTile.and.returnValue(1e-15); tileProvider.loadTile.and.callFake(function(frameState2, tile) { tile.state = import__592.QuadtreeTileLoadState.DONE; tile.renderable = true; }); const quadtree = new import__592.QuadtreePrimitive({ tileProvider }); quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); tileProvider.loadTile.and.callFake(function(frameState2, tile) { tile.state = import__592.QuadtreeTileLoadState.START; }); quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); quadtree.forEachLoadedTile(function(tile) { expect(tile.state).not.toBe(import__592.QuadtreeTileLoadState.START); }); }); it("add and remove callbacks to tiles", function() { const tileProvider = createSpyTileProvider(); tileProvider.getReady.and.returnValue(true); tileProvider.computeTileVisibility.and.returnValue(import__592.Visibility.FULL); tileProvider.computeDistanceToTile.and.returnValue(1e-15); tileProvider.loadTile.and.callFake(function(frameState2, tile) { tile.state = import__592.QuadtreeTileLoadState.DONE; tile.renderable = true; tile.data = { pick: function() { return void 0; } }; }); const quadtree = new import__592.QuadtreePrimitive({ tileProvider }); const removeFunc = quadtree.updateHeight( import__592.Cartographic.fromDegrees(-72, 40), function(position) { } ); quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); ++scene2.frameState.frameNumber; quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); let addedCallback = false; quadtree.forEachLoadedTile(function(tile) { addedCallback = addedCallback || tile.customData.length > 0; }); expect(addedCallback).toEqual(true); removeFunc(); ++scene2.frameState.frameNumber; quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); let removedCallback = true; quadtree.forEachLoadedTile(function(tile) { removedCallback = removedCallback && tile.customData.length === 0; }); expect(removedCallback).toEqual(true); }); it("updates heights", function() { const tileProvider = createSpyTileProvider(); tileProvider.getReady.and.returnValue(true); tileProvider.computeTileVisibility.and.returnValue(import__592.Visibility.FULL); tileProvider.computeDistanceToTile.and.returnValue(1e-15); tileProvider.terrainProvider = { getTileDataAvailable: function() { return true; } }; const position = import__592.Cartesian3.clone(import__592.Cartesian3.ZERO); const updatedPosition = import__592.Cartesian3.clone(import__592.Cartesian3.UNIT_X); let currentPosition = position; tileProvider.loadTile.and.callFake(function(frameState2, tile) { tile.state = import__592.QuadtreeTileLoadState.DONE; tile.renderable = true; tile.data = { pick: function() { return currentPosition; }, mesh: {} }; }); const quadtree = new import__592.QuadtreePrimitive({ tileProvider }); quadtree.updateHeight(import__592.Cartographic.fromDegrees(-72, 40), function(p) { import__592.Cartesian3.clone(p, position); }); quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); expect(position).toEqual(import__592.Cartesian3.ZERO); currentPosition = updatedPosition; quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); expect(position).toEqual(updatedPosition); }); it("gives correct priority to tile loads", function() { const tileProvider = createSpyTileProvider(); tileProvider.getReady.and.returnValue(true); tileProvider.computeTileVisibility.and.returnValue(import__592.Visibility.FULL); const quadtree = new import__592.QuadtreePrimitive({ tileProvider }); quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); expect(quadtree._tileLoadQueueHigh.length).toBe(2); expect(quadtree._tileLoadQueueHigh).toContain( quadtree._levelZeroTiles[0] ); expect(quadtree._tileLoadQueueHigh).toContain( quadtree._levelZeroTiles[1] ); expect(quadtree._tileLoadQueueMedium.length).toBe(0); expect(quadtree._tileLoadQueueLow.length).toBe(0); quadtree._levelZeroTiles[0].renderable = true; quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); expect(quadtree._tileLoadQueueHigh.length).toBe(5); expect(quadtree._tileLoadQueueHigh).toContain( quadtree._levelZeroTiles[1] ); expect(quadtree._tileLoadQueueHigh).toContain( quadtree._levelZeroTiles[0].children[0] ); expect(quadtree._tileLoadQueueHigh).toContain( quadtree._levelZeroTiles[0].children[1] ); expect(quadtree._tileLoadQueueHigh).toContain( quadtree._levelZeroTiles[0].children[2] ); expect(quadtree._tileLoadQueueHigh).toContain( quadtree._levelZeroTiles[0].children[3] ); expect(quadtree._tileLoadQueueMedium.length).toBe(0); expect(quadtree._tileLoadQueueLow.length).toBe(1); expect(quadtree._tileLoadQueueLow).toContain( quadtree._levelZeroTiles[0] ); quadtree._levelZeroTiles[0].children[0].renderable = true; quadtree._levelZeroTiles[0].children[1].renderable = true; quadtree._levelZeroTiles[0].children[2].renderable = true; quadtree._levelZeroTiles[0].children[3].renderable = true; quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); expect(quadtree._tileLoadQueueHigh.length).toBe(17); expect(quadtree._tileLoadQueueHigh).toContain( quadtree._levelZeroTiles[1] ); expect(quadtree._tileLoadQueueHigh).toContain( quadtree._levelZeroTiles[0].children[0].children[0] ); expect(quadtree._tileLoadQueueHigh).toContain( quadtree._levelZeroTiles[0].children[0].children[1] ); expect(quadtree._tileLoadQueueHigh).toContain( quadtree._levelZeroTiles[0].children[0].children[2] ); expect(quadtree._tileLoadQueueHigh).toContain( quadtree._levelZeroTiles[0].children[0].children[3] ); expect(quadtree._tileLoadQueueMedium.length).toBe(0); expect(quadtree._tileLoadQueueLow.length).toBe(5); expect(quadtree._tileLoadQueueLow).toContain( quadtree._levelZeroTiles[0] ); expect(quadtree._tileLoadQueueLow).toContain( quadtree._levelZeroTiles[0].children[0] ); expect(quadtree._tileLoadQueueLow).toContain( quadtree._levelZeroTiles[0].children[1] ); expect(quadtree._tileLoadQueueLow).toContain( quadtree._levelZeroTiles[0].children[2] ); expect(quadtree._tileLoadQueueLow).toContain( quadtree._levelZeroTiles[0].children[3] ); quadtree._levelZeroTiles[0].children[0].upsampledFromParent = true; quadtree._levelZeroTiles[0].children[1].upsampledFromParent = true; quadtree._levelZeroTiles[0].children[2].upsampledFromParent = true; quadtree._levelZeroTiles[0].children[3].upsampledFromParent = true; quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); expect(quadtree._tileLoadQueueHigh.length).toBe(1); expect(quadtree._tileLoadQueueHigh).toContain( quadtree._levelZeroTiles[1] ); expect(quadtree._tileLoadQueueMedium.length).toBe(1); expect(quadtree._tileLoadQueueMedium).toContain( quadtree._levelZeroTiles[0] ); expect(quadtree._tileLoadQueueLow.length).toBe(0); }); it("renders tiles in approximate near-to-far order", function() { const tileProvider = createSpyTileProvider(); tileProvider.getReady.and.returnValue(true); tileProvider.computeTileVisibility.and.returnValue(import__592.Visibility.FULL); const quadtree = new import__592.QuadtreePrimitive({ tileProvider }); tileProvider.loadTile.and.callFake(function(frameState2, tile) { if (tile.level <= 1) { tile.state = import__592.QuadtreeTileLoadState.DONE; tile.renderable = true; } }); scene2.camera.setView({ destination: import__592.Cartesian3.fromDegrees(1, 1, 15e3) }); scene2.camera.update(scene2.mode); return pollToPromise_default(function() { quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); return quadtree._tilesToRender.filter(function(tile) { return tile.level === 1; }).length === 8; }).then(function() { quadtree.update(scene2.frameState); quadtree.beginFrame(scene2.frameState); quadtree.render(scene2.frameState); quadtree.endFrame(scene2.frameState); const west = quadtree._levelZeroTiles.filter(function(tile) { return tile.x === 0; })[0]; const east = quadtree._levelZeroTiles.filter(function(tile) { return tile.x === 1; })[0]; expect(quadtree._tilesToRender[0]).toBe(east.northwestChild); expect( quadtree._tilesToRender[1] === east.southwestChild || quadtree._tilesToRender[1] === east.northeastChild ).toBe(true); expect( quadtree._tilesToRender[2] === east.southwestChild || quadtree._tilesToRender[2] === east.northeastChild ).toBe(true); expect(quadtree._tilesToRender[3]).toBe(east.southeastChild); expect(quadtree._tilesToRender[4]).toBe(west.northeastChild); expect( quadtree._tilesToRender[5] === west.northwestChild || quadtree._tilesToRender[5] === west.southeastChild ).toBe(true); expect( quadtree._tilesToRender[6] === west.northwestChild || quadtree._tilesToRender[6] === west.southeastChild ).toBe(true); expect(quadtree._tilesToRender[7]).toBe(west.southwestChild); }); }); }, "WebGL" ); function setCameraPosition(quadtree, frameState2, position, level) { const camera = frameState2.camera; const geometricError = quadtree.tileProvider.getLevelMaximumGeometricError( level ); const sse = quadtree.maximumScreenSpaceError * 0.8; const sseDenominator = camera.frustum.sseDenominator; const height = frameState2.context.drawingBufferHeight; const distance = geometricError * height / (sse * sseDenominator); const cartesian = import__592.Ellipsoid.WGS84.cartographicToCartesian(position); camera.lookAt(cartesian, new import__592.Cartesian3(0, 0, distance)); } }); // packages/engine/Specs/Scene/QuadtreeTileSpec.js var import__593 = __toESM(require_Cesium(), 1); var import__594 = __toESM(require_Cesium(), 1); describe("Scene/QuadtreeTile", function() { it("throws without a options", function() { expect(function() { return new import__593.QuadtreeTile(); }).toThrowDeveloperError(); }); it("throws without options.rectangle", function() { expect(function() { return new import__593.QuadtreeTile({ x: 0, y: 0 }); }).toThrowDeveloperError(); }); it("throws without options.level", function() { expect(function() { return new import__593.QuadtreeTile({ rectangle: new import__593.Rectangle( -import__594.Math.PI_OVER_FOUR, 0, import__594.Math.PI_OVER_FOUR, import__594.Math.PI_OVER_FOUR ), x: 0, y: 0 }); }).toThrowDeveloperError(); }); it("throws with negative x or y properties", function() { expect(function() { return new import__593.QuadtreeTile({ x: -1, y: -1, level: 1 }); }).toThrowDeveloperError(); }); it("creates rectangle on construction", function() { const desc = { tilingScheme: new import__593.WebMercatorTilingScheme(), x: 0, y: 0, level: 0 }; const tile = new import__593.QuadtreeTile(desc); const rectangle = desc.tilingScheme.tileXYToRectangle( desc.x, desc.y, desc.level ); expect(tile.rectangle).toEqual(rectangle); }); it("throws if constructed improperly", function() { expect(function() { return new import__593.QuadtreeTile(); }).toThrowDeveloperError(); expect(function() { return new import__593.QuadtreeTile({ y: 0, level: 0, tilingScheme: { tileXYToRectangle: function() { return void 0; } } }); }).toThrowDeveloperError(); expect(function() { return new import__593.QuadtreeTile({ x: 0, level: 0, tilingScheme: { tileXYToRectangle: function() { return void 0; } } }); }).toThrowDeveloperError(); expect(function() { return new import__593.QuadtreeTile({ x: 0, y: 0, tilingScheme: { tileXYToRectangle: function() { return void 0; } } }); }).toThrowDeveloperError(); expect(function() { return new import__593.QuadtreeTile({ x: 0, y: 0, level: 0 }); }).toThrowDeveloperError(); }); it("can get tiles around a root tile", function() { const tilingScheme = new import__593.GeographicTilingScheme({ numberOfLevelZeroTilesX: 3, numberOfLevelZeroTilesY: 3 }); const levelZeroTiles = import__593.QuadtreeTile.createLevelZeroTiles(tilingScheme); const L0X0Y0 = levelZeroTiles.filter(function(tile) { return tile.x === 0 && tile.y === 0; })[0]; const L0X1Y0 = levelZeroTiles.filter(function(tile) { return tile.x === 1 && tile.y === 0; })[0]; const L0X2Y0 = levelZeroTiles.filter(function(tile) { return tile.x === 2 && tile.y === 0; })[0]; const L0X0Y1 = levelZeroTiles.filter(function(tile) { return tile.x === 0 && tile.y === 1; })[0]; const L0X1Y1 = levelZeroTiles.filter(function(tile) { return tile.x === 1 && tile.y === 1; })[0]; const L0X2Y1 = levelZeroTiles.filter(function(tile) { return tile.x === 2 && tile.y === 1; })[0]; const L0X0Y2 = levelZeroTiles.filter(function(tile) { return tile.x === 0 && tile.y === 2; })[0]; const L0X1Y2 = levelZeroTiles.filter(function(tile) { return tile.x === 1 && tile.y === 2; })[0]; const L0X2Y2 = levelZeroTiles.filter(function(tile) { return tile.x === 2 && tile.y === 2; })[0]; expect(L0X0Y0.findTileToWest(levelZeroTiles)).toBe(L0X2Y0); expect(L0X0Y0.findTileToEast(levelZeroTiles)).toBe(L0X1Y0); expect(L0X0Y0.findTileToNorth(levelZeroTiles)).toBeUndefined(); expect(L0X0Y0.findTileToSouth(levelZeroTiles)).toBe(L0X0Y1); expect(L0X1Y0.findTileToWest(levelZeroTiles)).toBe(L0X0Y0); expect(L0X1Y0.findTileToEast(levelZeroTiles)).toBe(L0X2Y0); expect(L0X1Y0.findTileToNorth(levelZeroTiles)).toBeUndefined(); expect(L0X1Y0.findTileToSouth(levelZeroTiles)).toBe(L0X1Y1); expect(L0X2Y0.findTileToWest(levelZeroTiles)).toBe(L0X1Y0); expect(L0X2Y0.findTileToEast(levelZeroTiles)).toBe(L0X0Y0); expect(L0X2Y0.findTileToNorth(levelZeroTiles)).toBeUndefined(); expect(L0X2Y0.findTileToSouth(levelZeroTiles)).toBe(L0X2Y1); expect(L0X0Y1.findTileToWest(levelZeroTiles)).toBe(L0X2Y1); expect(L0X0Y1.findTileToEast(levelZeroTiles)).toBe(L0X1Y1); expect(L0X0Y1.findTileToNorth(levelZeroTiles)).toBe(L0X0Y0); expect(L0X0Y1.findTileToSouth(levelZeroTiles)).toBe(L0X0Y2); expect(L0X1Y1.findTileToWest(levelZeroTiles)).toBe(L0X0Y1); expect(L0X1Y1.findTileToEast(levelZeroTiles)).toBe(L0X2Y1); expect(L0X1Y1.findTileToNorth(levelZeroTiles)).toBe(L0X1Y0); expect(L0X1Y1.findTileToSouth(levelZeroTiles)).toBe(L0X1Y2); expect(L0X2Y1.findTileToWest(levelZeroTiles)).toBe(L0X1Y1); expect(L0X2Y1.findTileToEast(levelZeroTiles)).toBe(L0X0Y1); expect(L0X2Y1.findTileToNorth(levelZeroTiles)).toBe(L0X2Y0); expect(L0X2Y1.findTileToSouth(levelZeroTiles)).toBe(L0X2Y2); expect(L0X0Y2.findTileToWest(levelZeroTiles)).toBe(L0X2Y2); expect(L0X0Y2.findTileToEast(levelZeroTiles)).toBe(L0X1Y2); expect(L0X0Y2.findTileToNorth(levelZeroTiles)).toBe(L0X0Y1); expect(L0X0Y2.findTileToSouth(levelZeroTiles)).toBeUndefined(); expect(L0X1Y2.findTileToWest(levelZeroTiles)).toBe(L0X0Y2); expect(L0X1Y2.findTileToEast(levelZeroTiles)).toBe(L0X2Y2); expect(L0X1Y2.findTileToNorth(levelZeroTiles)).toBe(L0X1Y1); expect(L0X1Y2.findTileToSouth(levelZeroTiles)).toBeUndefined(); expect(L0X2Y2.findTileToWest(levelZeroTiles)).toBe(L0X1Y2); expect(L0X2Y2.findTileToEast(levelZeroTiles)).toBe(L0X0Y2); expect(L0X2Y2.findTileToNorth(levelZeroTiles)).toBe(L0X2Y1); expect(L0X2Y2.findTileToSouth(levelZeroTiles)).toBeUndefined(); }); it("can get tiles around a tile when they share a common parent", function() { const tilingScheme = new import__593.GeographicTilingScheme({ numberOfLevelZeroTilesX: 2, numberOfLevelZeroTilesY: 1 }); const levelZeroTiles = import__593.QuadtreeTile.createLevelZeroTiles(tilingScheme); const parent = levelZeroTiles[1]; const sw = parent.southwestChild; const se = parent.southeastChild; const nw = parent.northwestChild; const ne = parent.northeastChild; expect(sw.findTileToEast(levelZeroTiles)).toBe(se); expect(sw.findTileToNorth(levelZeroTiles)).toBe(nw); expect(se.findTileToWest(levelZeroTiles)).toBe(sw); expect(se.findTileToNorth(levelZeroTiles)).toBe(ne); expect(nw.findTileToEast(levelZeroTiles)).toBe(ne); expect(nw.findTileToSouth(levelZeroTiles)).toBe(sw); expect(ne.findTileToWest(levelZeroTiles)).toBe(nw); expect(ne.findTileToSouth(levelZeroTiles)).toBe(se); }); it("can get tiles around a tile when they do not share a common parent", function() { const tilingScheme = new import__593.GeographicTilingScheme({ numberOfLevelZeroTilesX: 2, numberOfLevelZeroTilesY: 2 }); const levelZeroTiles = import__593.QuadtreeTile.createLevelZeroTiles(tilingScheme); const northwest = levelZeroTiles[0]; const nwse = northwest.southeastChild; const nwne = northwest.northeastChild; const nwsw = northwest.southwestChild; const northeast = levelZeroTiles[1]; const nesw = northeast.southwestChild; const nenw = northeast.northwestChild; const nese = northeast.southeastChild; const southwest = levelZeroTiles[2]; const swne = southwest.northeastChild; const swnw = southwest.northwestChild; const swse = southwest.southeastChild; const southeast = levelZeroTiles[3]; const senw = southeast.northwestChild; const sene = southeast.northeastChild; const sesw = southeast.southwestChild; expect(nwse.findTileToEast(levelZeroTiles)).toBe(nesw); expect(nwse.findTileToSouth(levelZeroTiles)).toBe(swne); expect(nwne.findTileToEast(levelZeroTiles)).toBe(nenw); expect(nwsw.findTileToSouth(levelZeroTiles)).toBe(swnw); expect(nesw.findTileToWest(levelZeroTiles)).toBe(nwse); expect(nesw.findTileToSouth(levelZeroTiles)).toBe(senw); expect(nenw.findTileToWest(levelZeroTiles)).toBe(nwne); expect(nese.findTileToSouth(levelZeroTiles)).toBe(sene); expect(swne.findTileToEast(levelZeroTiles)).toBe(senw); expect(swne.findTileToNorth(levelZeroTiles)).toBe(nwse); expect(swnw.findTileToNorth(levelZeroTiles)).toBe(nwsw); expect(swse.findTileToEast(levelZeroTiles)).toBe(sesw); expect(senw.findTileToWest(levelZeroTiles)).toBe(swne); expect(senw.findTileToNorth(levelZeroTiles)).toBe(nesw); expect(sene.findTileToNorth(levelZeroTiles)).toBe(nese); expect(sesw.findTileToWest(levelZeroTiles)).toBe(swse); }); it("can get adjacent tiles wrapping around the anti-meridian", function() { const tilingScheme = new import__593.GeographicTilingScheme({ numberOfLevelZeroTilesX: 2, numberOfLevelZeroTilesY: 1 }); const levelZeroTiles = import__593.QuadtreeTile.createLevelZeroTiles(tilingScheme); const west = levelZeroTiles[0]; const wsw = west.southwestChild; const wnw = west.northwestChild; const east = levelZeroTiles[1]; const ene = east.northeastChild; const ese = east.southeastChild; expect(wsw.findTileToWest(levelZeroTiles)).toBe(ese); expect(wnw.findTileToWest(levelZeroTiles)).toBe(ene); expect(ene.findTileToEast(levelZeroTiles)).toBe(wnw); expect(ese.findTileToEast(levelZeroTiles)).toBe(wsw); }); it("returns undefined when asked for adjacent tiles north of the north pole or south of the south pole", function() { const tilingScheme = new import__593.GeographicTilingScheme({ numberOfLevelZeroTilesX: 2, numberOfLevelZeroTilesY: 1 }); const levelZeroTiles = import__593.QuadtreeTile.createLevelZeroTiles(tilingScheme); const west = levelZeroTiles[0]; const wnw = west.northwestChild; const wsw = west.southwestChild; expect(wnw.findTileToNorth(levelZeroTiles)).toBeUndefined(); expect(wsw.findTileToSouth(levelZeroTiles)).toBeUndefined(); }); describe("createLevelZeroTiles", function() { let tilingScheme1x1; let tilingScheme2x2; let tilingScheme2x1; let tilingScheme1x2; beforeEach(function() { tilingScheme1x1 = new import__593.GeographicTilingScheme({ numberOfLevelZeroTilesX: 1, numberOfLevelZeroTilesY: 1 }); tilingScheme2x2 = new import__593.GeographicTilingScheme({ numberOfLevelZeroTilesX: 2, numberOfLevelZeroTilesY: 2 }); tilingScheme2x1 = new import__593.GeographicTilingScheme({ numberOfLevelZeroTilesX: 2, numberOfLevelZeroTilesY: 1 }); tilingScheme1x2 = new import__593.GeographicTilingScheme({ numberOfLevelZeroTilesX: 1, numberOfLevelZeroTilesY: 2 }); }); it("requires tilingScheme", function() { expect(function() { return import__593.QuadtreeTile.createLevelZeroTiles(void 0); }).toThrowDeveloperError(); }); it("creates expected number of tiles", function() { let tiles = import__593.QuadtreeTile.createLevelZeroTiles(tilingScheme1x1); expect(tiles.length).toBe(1); tiles = import__593.QuadtreeTile.createLevelZeroTiles(tilingScheme2x2); expect(tiles.length).toBe(4); tiles = import__593.QuadtreeTile.createLevelZeroTiles(tilingScheme2x1); expect(tiles.length).toBe(2); tiles = import__593.QuadtreeTile.createLevelZeroTiles(tilingScheme1x2); expect(tiles.length).toBe(2); }); it("created tiles are associated with specified tiling scheme", function() { const tiles = import__593.QuadtreeTile.createLevelZeroTiles(tilingScheme2x2); for (let i = 0; i < tiles.length; ++i) { expect(tiles[i].tilingScheme).toBe(tilingScheme2x2); } }); it("created tiles are ordered from the northwest and proceeding east and then south", function() { const tiles = import__593.QuadtreeTile.createLevelZeroTiles(tilingScheme2x2); const northwest = tiles[0]; const northeast = tiles[1]; const southwest = tiles[2]; const southeast = tiles[3]; expect(northeast.rectangle.west).toBeGreaterThan( northwest.rectangle.west ); expect(southeast.rectangle.west).toBeGreaterThan( southwest.rectangle.west ); expect(northeast.rectangle.south).toBeGreaterThan( southeast.rectangle.south ); expect(northwest.rectangle.south).toBeGreaterThan( southwest.rectangle.south ); }); }); }); // packages/engine/Specs/Scene/ResourceCacheKeySpec.js var import__595 = __toESM(require_Cesium(), 1); describe("ResourceCacheKey", function() { const schemaUri = "https://example.com/schema.json"; const schemaResource = new import__595.Resource({ url: schemaUri }); const gltfUri = "https://example.com/parent.gltf"; const gltfResource = new import__595.Resource({ url: gltfUri }); const baseUri = "https://example.com/resources/"; const baseResource = new import__595.Resource({ url: baseUri }); const schemaJson = {}; const bufferUri = "https://example.com/external.bin"; const bufferResource = new import__595.Resource({ url: bufferUri }); const bufferId = 0; const meshoptGltfEmbeddedBuffer = { buffers: [ { byteLength: 100 } ], bufferViews: [ { buffer: 0, byteOffset: 0, byteLength: 100, extensions: { EXT_meshopt_compression: { buffer: 1, byteOffset: 25, byteLength: 50 } } } ] }; const gltfEmbeddedBuffer = { buffers: [ { byteLength: 100 } ], bufferViews: [ { buffer: 0, byteOffset: 0, byteLength: 100 } ] }; const gltfExternalBuffer = { buffers: [ { uri: "external.bin", byteLength: 100 } ], bufferViews: [ { buffer: 0, byteOffset: 0, byteLength: 100 } ] }; const gltfUncompressed = { buffers: [ { uri: "external.bin", byteLength: 100 } ], bufferViews: [ { buffer: 0, byteOffset: 0, byteLength: 40 }, { buffer: 0, byteOffset: 40, byteLength: 40 }, { buffer: 0, byteOffset: 80, byteLength: 20 } ], accessors: [ { componentType: 5126, count: 24, max: [0.5, 0.5, 0.5], min: [-0.5, -0.5, -0.5], type: "VEC3", bufferView: 0, byteOffset: 0 }, { componentType: 5126, count: 24, type: "VEC3", bufferView: 1, byteOffset: 0 }, { componentType: 5123, count: 36, type: "SCALAR", bufferView: 2, byteOffset: 0 } ], meshes: [ { primitives: [ { attributes: { POSITION: 0, NORMAL: 1 }, indices: 2 } ] } ] }; const gltfDraco = { buffers: [ { uri: "external.bin", byteLength: 100 } ], bufferViews: [ { buffer: 0, byteOffset: 0, byteLength: 100 } ], accessors: [ { componentType: 5126, count: 24, max: [0.5, 0.5, 0.5], min: [-0.5, -0.5, -0.5], type: "VEC3" }, { componentType: 5126, count: 24, type: "VEC3" }, { componentType: 5123, count: 36, type: "SCALAR" } ], meshes: [ { primitives: [ { attributes: { POSITION: 0, NORMAL: 1 }, indices: 2, extensions: { KHR_draco_mesh_compression: { bufferView: 0, attributes: { POSITION: 0, NORMAL: 1 } } } } ] } ] }; const gltfWithTextures = { buffers: [ { uri: "external.bin", byteLength: 100 } ], bufferViews: [ { buffer: 0, byteOffset: 0, byteLength: 100 } ], images: [ { uri: "image.png" }, { mimeType: "image/jpeg", bufferView: 0 }, { uri: "image.webp" }, { uri: "image.ktx2" } ], textures: [ { // Intentionally omitting sampler from this texture source: 0 }, { sampler: 0, source: 1 }, { source: 0, extensions: { EXT_texture_webp: { source: 2 } } }, { source: 0, extensions: { KHR_texture_basisu: { source: 3 } } } ], samplers: [ { magFilter: 9728, minFilter: 9984, wrapS: 33071, wrapT: 33648 } ] }; const mockFrameState = { context: { id: "01234" } }; it("getSchemaCacheKey works for external schemas", function() { const cacheKey = import__595.ResourceCacheKey.getSchemaCacheKey({ resource: schemaResource }); expect(cacheKey).toBe(`external-schema:${schemaUri}`); }); it("getSchemaCacheKey works for JSON schemas", function() { const cacheKey = import__595.ResourceCacheKey.getSchemaCacheKey({ schema: schemaJson }); expect(cacheKey).toBe(`embedded-schema:${JSON.stringify(schemaJson)}`); }); it("getSchemaCacheKey throws if neither options.schema nor options.resource are defined", function() { expect(function() { import__595.ResourceCacheKey.getSchemaCacheKey({}); }).toThrowDeveloperError(); }); it("getSchemaCacheKey throws if both options.schema and options.resource are defined", function() { expect(function() { import__595.ResourceCacheKey.getSchemaCacheKey({ schema: schemaJson, resource: schemaResource }); }).toThrowDeveloperError(); }); it("getExternalBufferCacheKey works", function() { const cacheKey = import__595.ResourceCacheKey.getExternalBufferCacheKey({ resource: bufferResource }); expect(cacheKey).toBe(`external-buffer:${bufferUri}`); }); it("getExternalBufferCacheKey throws if resource is undefined", function() { expect(function() { import__595.ResourceCacheKey.getExternalBufferCacheKey({}); }).toThrowDeveloperError(); }); it("getEmbeddedBufferCacheKey works", function() { const cacheKey = import__595.ResourceCacheKey.getEmbeddedBufferCacheKey({ parentResource: gltfResource, bufferId }); expect(cacheKey).toBe(`embedded-buffer:${gltfUri}-buffer-id-0`); }); it("getEmbeddedBufferCacheKey throws if parentResource is undefined", function() { expect(function() { import__595.ResourceCacheKey.getExternalBufferCacheKey({ bufferId }); }).toThrowDeveloperError(); }); it("getEmbeddedBufferCacheKey throws if bufferId is undefined", function() { expect(function() { import__595.ResourceCacheKey.getExternalBufferCacheKey({ parentResource: gltfResource }); }).toThrowDeveloperError(); }); it("getGltfCacheKey works", function() { const cacheKey = import__595.ResourceCacheKey.getGltfCacheKey({ gltfResource }); expect(cacheKey).toBe(`gltf:${gltfUri}`); }); it("getGltfCacheKey throws if gltfResource is undefined", function() { expect(function() { import__595.ResourceCacheKey.getGltfCacheKey({}); }).toThrowDeveloperError(); }); it("getBufferViewCacheKey works with embedded buffer", function() { const cacheKey = import__595.ResourceCacheKey.getBufferViewCacheKey({ gltf: gltfEmbeddedBuffer, bufferViewId: 0, gltfResource, baseResource }); expect(cacheKey).toBe(`buffer-view:${gltfUri}-buffer-id-0-range-0-100`); }); it("getBufferViewCacheKey works with external buffer", function() { const cacheKey = import__595.ResourceCacheKey.getBufferViewCacheKey({ gltf: gltfExternalBuffer, bufferViewId: 0, gltfResource, baseResource }); expect(cacheKey).toBe( "buffer-view:https://example.com/resources/external.bin-range-0-100" ); }); it("getBufferViewCacheKey works with meshopt", function() { const cacheKey = import__595.ResourceCacheKey.getBufferViewCacheKey({ gltf: meshoptGltfEmbeddedBuffer, bufferViewId: 0, gltfResource, baseResource }); expect(cacheKey).toBe(`buffer-view:${gltfUri}-buffer-id-1-range-25-75`); }); it("getBufferViewCacheKey throws if gltf is undefined", function() { expect(function() { import__595.ResourceCacheKey.getBufferViewCacheKey({ gltf: void 0, bufferViewId: 0, gltfResource, baseResource }); }).toThrowDeveloperError(); }); it("getBufferViewCacheKey throws if bufferViewId is undefined", function() { expect(function() { import__595.ResourceCacheKey.getBufferViewCacheKey({ gltf: gltfEmbeddedBuffer, bufferViewId: void 0, gltfResource, baseResource }); }).toThrowDeveloperError(); }); it("getBufferViewCacheKey throws if gltfResource is undefined", function() { expect(function() { import__595.ResourceCacheKey.getBufferViewCacheKey({ gltf: gltfEmbeddedBuffer, bufferViewId: 0, gltfResource: void 0, baseResource }); }).toThrowDeveloperError(); }); it("getBufferViewCacheKey throws if baseResource is undefined", function() { expect(function() { import__595.ResourceCacheKey.getBufferViewCacheKey({ gltf: gltfEmbeddedBuffer, bufferViewId: 0, gltfResource, baseResource: void 0 }); }).toThrowDeveloperError(); }); it("getDracoCacheKey works", function() { const draco = gltfDraco.meshes[0].primitives[0].extensions.KHR_draco_mesh_compression; const cacheKey = import__595.ResourceCacheKey.getDracoCacheKey({ gltf: gltfDraco, draco, gltfResource, baseResource }); expect(cacheKey).toBe( "draco:https://example.com/resources/external.bin-range-0-100" ); }); it("getDracoCacheKey throws if gltf is undefined", function() { const draco = gltfDraco.meshes[0].primitives[0].extensions.KHR_draco_mesh_compression; expect(function() { import__595.ResourceCacheKey.getBufferViewCacheKey({ gltf: void 0, draco, gltfResource, baseResource }); }).toThrowDeveloperError(); }); it("getDracoCacheKey throws if draco is undefined", function() { expect(function() { import__595.ResourceCacheKey.getBufferViewCacheKey({ gltf: gltfDraco, draco: void 0, gltfResource, baseResource }); }).toThrowDeveloperError(); }); it("getDracoCacheKey throws if gltfResource is undefined", function() { const draco = gltfDraco.meshes[0].primitives[0].extensions.KHR_draco_mesh_compression; expect(function() { import__595.ResourceCacheKey.getBufferViewCacheKey({ gltf: gltfDraco, draco, gltfResource: void 0, baseResource }); }).toThrowDeveloperError(); }); it("getDracoCacheKey throws if baseResource is undefined", function() { const draco = gltfDraco.meshes[0].primitives[0].extensions.KHR_draco_mesh_compression; expect(function() { import__595.ResourceCacheKey.getBufferViewCacheKey({ gltf: gltfDraco, draco, gltfResource, baseResource: void 0 }); }).toThrowDeveloperError(); }); it("getVertexBufferCacheKey works from buffer view", function() { const cacheKey = import__595.ResourceCacheKey.getVertexBufferCacheKey({ gltf: gltfUncompressed, gltfResource, baseResource, frameState: mockFrameState, bufferViewId: 0, loadBuffer: true }); expect(cacheKey).toBe( "vertex-buffer:https://example.com/resources/external.bin-range-0-40-buffer-context-01234" ); }); it("getVertexBufferCacheKey works from draco", function() { const draco = gltfDraco.meshes[0].primitives[0].extensions.KHR_draco_mesh_compression; const cacheKey = import__595.ResourceCacheKey.getVertexBufferCacheKey({ gltf: gltfDraco, gltfResource, baseResource, frameState: mockFrameState, draco, attributeSemantic: "POSITION", loadBuffer: true }); expect(cacheKey).toBe( "vertex-buffer:https://example.com/resources/external.bin-range-0-100-draco-POSITION-buffer-context-01234" ); }); it("getVertexBufferCacheKey works with dequantize", function() { const cacheKey = import__595.ResourceCacheKey.getVertexBufferCacheKey({ gltf: gltfUncompressed, gltfResource, baseResource, frameState: mockFrameState, bufferViewId: 0, dequantize: true, loadBuffer: true }); expect(cacheKey).toBe( "vertex-buffer:https://example.com/resources/external.bin-range-0-40-dequantize-buffer-context-01234" ); }); it("getVertexBufferCacheKey works with loadTypedArray", function() { const cacheKey = import__595.ResourceCacheKey.getVertexBufferCacheKey({ gltf: gltfUncompressed, gltfResource, baseResource, frameState: mockFrameState, bufferViewId: 0, loadTypedArray: true }); expect(cacheKey).toBe( "vertex-buffer:https://example.com/resources/external.bin-range-0-40-typed-array" ); }); it("getVertexBufferCacheKey works with loadBuffer and loadTypedArray", function() { const cacheKey = import__595.ResourceCacheKey.getVertexBufferCacheKey({ gltf: gltfUncompressed, gltfResource, baseResource, frameState: mockFrameState, bufferViewId: 0, loadBuffer: true, loadTypedArray: true }); expect(cacheKey).toBe( "vertex-buffer:https://example.com/resources/external.bin-range-0-40-buffer-context-01234-typed-array" ); }); it("getVertexBufferCacheKey throws if gltf is undefined", function() { expect(function() { import__595.ResourceCacheKey.getVertexBufferCacheKey({ gltf: void 0, gltfResource, baseResource, frameState: mockFrameState, bufferViewId: 0 }); }).toThrowDeveloperError(); }); it("getVertexBufferCacheKey throws if gltfResource is undefined", function() { expect(function() { import__595.ResourceCacheKey.getVertexBufferCacheKey({ gltf: gltfUncompressed, gltfResource: void 0, baseResource, frameState: mockFrameState, bufferViewId: 0 }); }).toThrowDeveloperError(); }); it("getVertexBufferCacheKey throws if baseResource is undefined", function() { expect(function() { import__595.ResourceCacheKey.getVertexBufferCacheKey({ gltf: gltfUncompressed, gltfResource, baseResource: void 0, frameState: mockFrameState, bufferViewId: 0 }); }).toThrowDeveloperError(); }); it("getVertexBufferCacheKey throws if frameState is undefined", function() { expect(function() { import__595.ResourceCacheKey.getVertexBufferCacheKey({ gltf: gltfUncompressed, gltfResource, baseResource, frameState: void 0, bufferViewId: 0 }); }).toThrowDeveloperError(); }); it("getVertexBufferCacheKey throws if both bufferViewId and draco are undefined", function() { expect(function() { import__595.ResourceCacheKey.getVertexBufferCacheKey({ gltf: gltfUncompressed, gltfResource, baseResource, frameState: mockFrameState }); }).toThrowDeveloperError(); }); it("getVertexBufferCacheKey throws if both bufferViewId and draco are defined", function() { const draco = gltfDraco.meshes[0].primitives[0].extensions.KHR_draco_mesh_compression; expect(function() { import__595.ResourceCacheKey.getVertexBufferCacheKey({ gltf: gltfDraco, gltfResource, baseResource, frameState: mockFrameState, bufferViewId: 0, draco, attributeSemantic: "POSITION" }); }).toThrowDeveloperError(); }); it("getVertexBufferCacheKey throws if both draco is defined and attributeSemantic is undefined", function() { const draco = gltfDraco.meshes[0].primitives[0].extensions.KHR_draco_mesh_compression; expect(function() { import__595.ResourceCacheKey.getVertexBufferCacheKey({ gltf: gltfDraco, gltfResource, baseResource, frameState: mockFrameState, draco, attributeSemantic: void 0 }); }).toThrowDeveloperError(); }); it("getIndexBufferCacheKey throws if both loadBuffer and loadTypedArray are false", function() { expect(function() { import__595.ResourceCacheKey.getVertexBufferCacheKey({ gltf: gltfUncompressed, gltfResource, baseResource, frameState: mockFrameState, bufferViewId: 0, loadBuffer: false, loadTypedArray: false }); }).toThrowDeveloperError(); }); it("getIndexBufferCacheKey works from buffer view", function() { const cacheKey = import__595.ResourceCacheKey.getIndexBufferCacheKey({ gltf: gltfUncompressed, accessorId: 2, gltfResource, baseResource, frameState: mockFrameState, loadBuffer: true }); expect(cacheKey).toBe( "index-buffer:https://example.com/resources/external.bin-accessor-80-5123-SCALAR-36-buffer-context-01234" ); }); it("getIndexBufferCacheKey works from draco", function() { const draco = gltfDraco.meshes[0].primitives[0].extensions.KHR_draco_mesh_compression; const cacheKey = import__595.ResourceCacheKey.getIndexBufferCacheKey({ gltf: gltfDraco, accessorId: 2, gltfResource, baseResource, frameState: mockFrameState, draco, loadBuffer: true }); expect(cacheKey).toBe( "index-buffer:https://example.com/resources/external.bin-range-0-100-draco-buffer-context-01234" ); }); it("getIndexBufferCacheKey works with loadTypedArray", function() { const cacheKey = import__595.ResourceCacheKey.getIndexBufferCacheKey({ gltf: gltfUncompressed, accessorId: 2, gltfResource, baseResource, frameState: mockFrameState, loadTypedArray: true }); expect(cacheKey).toBe( "index-buffer:https://example.com/resources/external.bin-accessor-80-5123-SCALAR-36-typed-array" ); }); it("getIndexBufferCacheKey works with loadBuffer and loadTypedArray", function() { const cacheKey = import__595.ResourceCacheKey.getIndexBufferCacheKey({ gltf: gltfUncompressed, accessorId: 2, gltfResource, baseResource, frameState: mockFrameState, loadBuffer: true, loadTypedArray: true }); expect(cacheKey).toBe( "index-buffer:https://example.com/resources/external.bin-accessor-80-5123-SCALAR-36-buffer-context-01234-typed-array" ); }); it("getIndexBufferCacheKey throws if gltf is undefined", function() { expect(function() { import__595.ResourceCacheKey.getIndexBufferCacheKey({ gltf: void 0, accessorId: 2, gltfResource, baseResource, frameState: mockFrameState, loadBuffer: true }); }).toThrowDeveloperError(); }); it("getIndexBufferCacheKey throws if gltfResource is undefined", function() { expect(function() { import__595.ResourceCacheKey.getIndexBufferCacheKey({ gltf: gltfUncompressed, accessorId: 2, gltfResource: void 0, baseResource, frameState: mockFrameState, loadBuffer: true }); }).toThrowDeveloperError(); }); it("getIndexBufferCacheKey throws if baseResource is undefined", function() { expect(function() { import__595.ResourceCacheKey.getIndexBufferCacheKey({ gltf: gltfUncompressed, accessorId: 2, gltfResource, baseResource: void 0, frameState: mockFrameState, loadBuffer: true }); }).toThrowDeveloperError(); }); it("getIndexBufferCacheKey throws if frameState is undefined", function() { expect(function() { import__595.ResourceCacheKey.getIndexBufferCacheKey({ gltf: gltfUncompressed, accessorId: 2, gltfResource, baseResource, frameState: void 0, loadBuffer: true }); }).toThrowDeveloperError(); }); it("getIndexBufferCacheKey throws if both loadBuffer and loadTypedArray are false", function() { expect(function() { import__595.ResourceCacheKey.getIndexBufferCacheKey({ gltf: gltfUncompressed, accessorId: 2, gltfResource, baseResource, frameState: mockFrameState, loadBuffer: false, loadTypedArray: false }); }).toThrowDeveloperError(); }); it("getImageCacheKey works from uri", function() { const cacheKey = import__595.ResourceCacheKey.getImageCacheKey({ gltf: gltfWithTextures, imageId: 0, gltfResource, baseResource }); expect(cacheKey).toBe("image:https://example.com/resources/image.png"); }); it("getImageCacheKey works from buffer view", function() { const cacheKey = import__595.ResourceCacheKey.getImageCacheKey({ gltf: gltfWithTextures, imageId: 1, gltfResource, baseResource }); expect(cacheKey).toBe( "image:https://example.com/resources/external.bin-range-0-100" ); }); it("getImageCacheKey throws if gltf is undefined", function() { expect(function() { import__595.ResourceCacheKey.getImageCacheKey({ gltf: void 0, imageId: 0, gltfResource, baseResource }); }).toThrowDeveloperError(); }); it("getImageCacheKey throws if imageId is undefined", function() { expect(function() { import__595.ResourceCacheKey.getImageCacheKey({ gltf: gltfWithTextures, imageId: void 0, gltfResource, baseResource }); }).toThrowDeveloperError(); }); it("getImageCacheKey throws if gltfResource is undefined", function() { expect(function() { import__595.ResourceCacheKey.getImageCacheKey({ gltf: gltfWithTextures, imageId: 0, gltfResource: void 0, baseResource }); }).toThrowDeveloperError(); }); it("getImageCacheKey throws if baseResource is undefined", function() { expect(function() { import__595.ResourceCacheKey.getImageCacheKey({ gltf: gltfWithTextures, imageId: 0, gltfResource, baseResource: void 0 }); }).toThrowDeveloperError(); }); it("getTextureCacheKey works with default sampler", function() { const cacheKey = import__595.ResourceCacheKey.getTextureCacheKey({ gltf: gltfWithTextures, textureInfo: { index: 0, texCoord: 0 }, gltfResource, baseResource, supportedImageFormats: new import__595.SupportedImageFormats(), frameState: mockFrameState }); expect(cacheKey).toBe( "texture:https://example.com/resources/image.png-sampler-10497-10497-9729-9729-context-01234" ); }); it("getTextureCacheKey works with explicit sampler", function() { const cacheKey = import__595.ResourceCacheKey.getTextureCacheKey({ gltf: gltfWithTextures, textureInfo: { index: 1, texCoord: 0 }, gltfResource, baseResource, supportedImageFormats: new import__595.SupportedImageFormats(), frameState: mockFrameState }); expect(cacheKey).toBe( "texture:https://example.com/resources/external.bin-range-0-100-sampler-33071-33648-9984-9728-context-01234" ); }); it("getTextureCacheKey works with EXT_texture_webp extension", function() { const cacheKey = import__595.ResourceCacheKey.getTextureCacheKey({ gltf: gltfWithTextures, textureInfo: { index: 2, texCoord: 0 }, gltfResource, baseResource, supportedImageFormats: new import__595.SupportedImageFormats({ webp: true }), frameState: mockFrameState }); expect(cacheKey).toBe( "texture:https://example.com/resources/image.webp-sampler-10497-10497-9729-9729-context-01234" ); }); it("getTextureCacheKey ignores EXT_texture_webp extension if WebP is not supported", function() { const cacheKey = import__595.ResourceCacheKey.getTextureCacheKey({ gltf: gltfWithTextures, textureInfo: { index: 2, texCoord: 0 }, gltfResource, baseResource, supportedImageFormats: new import__595.SupportedImageFormats(), frameState: mockFrameState }); expect(cacheKey).toBe( "texture:https://example.com/resources/image.png-sampler-10497-10497-9729-9729-context-01234" ); }); it("getTextureCacheKey works with KHR_texture_basisu extension", function() { const cacheKey = import__595.ResourceCacheKey.getTextureCacheKey({ gltf: gltfWithTextures, textureInfo: { index: 3, texCoord: 0 }, gltfResource, baseResource, supportedImageFormats: new import__595.SupportedImageFormats({ basis: true }), frameState: mockFrameState }); expect(cacheKey).toBe( "texture:https://example.com/resources/image.ktx2-sampler-10497-10497-9729-9729-context-01234" ); }); it("getTextureCacheKey ignores KHR_texture_basisu extension if Basis is not supported", function() { const cacheKey = import__595.ResourceCacheKey.getTextureCacheKey({ gltf: gltfWithTextures, textureInfo: { index: 3, texCoord: 0 }, gltfResource, baseResource, supportedImageFormats: new import__595.SupportedImageFormats(), frameState: mockFrameState }); expect(cacheKey).toBe( "texture:https://example.com/resources/image.png-sampler-10497-10497-9729-9729-context-01234" ); }); it("getTextureCacheKey throws if gltf is undefined", function() { expect(function() { import__595.ResourceCacheKey.getTextureCacheKey({ gltf: void 0, textureInfo: { index: 0, texCoord: 0 }, gltfResource, baseResource, supportedImageFormats: new import__595.SupportedImageFormats(), frameState: mockFrameState }); }).toThrowDeveloperError(); }); it("getTextureCacheKey throws if textureInfo is undefined", function() { expect(function() { import__595.ResourceCacheKey.getTextureCacheKey({ gltf: gltfWithTextures, textureInfo: void 0, gltfResource, baseResource, supportedImageFormats: new import__595.SupportedImageFormats(), frameState: mockFrameState }); }).toThrowDeveloperError(); }); it("getTextureCacheKey throws if gltfResource is undefined", function() { expect(function() { import__595.ResourceCacheKey.getTextureCacheKey({ gltf: gltfWithTextures, textureInfo: { index: 0, texCoord: 0 }, gltfResource: void 0, baseResource, supportedImageFormats: new import__595.SupportedImageFormats(), frameState: mockFrameState }); }).toThrowDeveloperError(); }); it("getTextureCacheKey throws if baseResource is undefined", function() { expect(function() { import__595.ResourceCacheKey.getTextureCacheKey({ gltf: gltfWithTextures, textureInfo: { index: 0, texCoord: 0 }, gltfResource, baseResource: void 0, supportedImageFormats: new import__595.SupportedImageFormats(), frameState: mockFrameState }); }).toThrowDeveloperError(); }); it("getTextureCacheKey throws if supportedImageFormats is undefined", function() { expect(function() { import__595.ResourceCacheKey.getTextureCacheKey({ gltf: gltfWithTextures, textureInfo: { index: 0, texCoord: 0 }, gltfResource, baseResource, supportedImageFormats: void 0, frameState: mockFrameState }); }).toThrowDeveloperError(); }); it("getTextureCacheKey throws if frameState is undefined", function() { expect(function() { import__595.ResourceCacheKey.getTextureCacheKey({ gltf: gltfWithTextures, textureInfo: { index: 0, texCoord: 0 }, gltfResource, baseResource, supportedImageFormats: new import__595.SupportedImageFormats(), frameState: void 0 }); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/ResourceCacheSpec.js var import__596 = __toESM(require_Cesium(), 1); describe("ResourceCache", function() { const schemaResource = new import__596.Resource({ url: "https://example.com/schema.json" }); const schemaJson = {}; const bufferParentResource = new import__596.Resource({ url: "https://example.com/model.glb" }); const bufferResource = new import__596.Resource({ url: "https://example.com/external.bin" }); const gltfUri = "https://example.com/model.glb"; const gltfResource = new import__596.Resource({ url: gltfUri }); const image = new Image(); image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII="; const positions = new Float32Array([-1, -1, -1, 1, 1, 1, 0, 1, 0]); const normals = new Float32Array([-1, 0, 0, 1, 0, 0, 0, 1, 0]); const indices = new Uint16Array([0, 1, 2]); const bufferTypedArray = concatTypedArrays_default([positions, normals, indices]); const gltfDraco = { buffers: [ { uri: "external.bin", byteLength: 8 } ], bufferViews: [ { buffer: 0, byteOffset: 4, byteLength: 4 } ], accessors: [ { componentType: 5126, count: 3, max: [-1, -1, -1], min: [1, 1, 1], type: "VEC3" }, { componentType: 5126, count: 3, type: "VEC3" }, { componentType: 5123, count: 3, type: "SCALAR" } ], meshes: [ { primitives: [ { attributes: { POSITION: 0, NORMAL: 1 }, indices: 2, extensions: { KHR_draco_mesh_compression: { bufferView: 0, attributes: { POSITION: 0, NORMAL: 1 } } } } ] } ] }; const dracoExtension = gltfDraco.meshes[0].primitives[0].extensions.KHR_draco_mesh_compression; const gltfUncompressed = { buffers: [ { uri: "external.bin", byteLength: 78 } ], bufferViews: [ { buffer: 0, byteOffset: 0, byteLength: 36 }, { buffer: 0, byteOffset: 36, byteLength: 36 }, { buffer: 0, byteOffset: 72, byteLength: 6 } ], accessors: [ { componentType: 5126, count: 3, max: [-1, -1, -1], min: [1, 1, 1], type: "VEC3", bufferView: 0, byteOffset: 0 }, { componentType: 5126, count: 3, type: "VEC3", bufferView: 1, byteOffset: 0 }, { componentType: 5123, count: 3, type: "SCALAR", bufferView: 2, byteOffset: 0 } ], meshes: [ { primitives: [ { attributes: { POSITION: 0, NORMAL: 1 }, indices: 2 } ] } ] }; const gltfWithTextures = { images: [ { uri: "image.png" } ], textures: [ { source: 0 } ], materials: [ { emissiveTexture: { index: 0 }, occlusionTexture: { index: 1 } } ] }; const mockFrameState = { context: { id: "01234" } }; const mockFrameState2 = { context: { id: "56789" } }; let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { import__596.ResourceCache.clearForSpecs(); }); it("adds resource", function() { const cacheKey = import__596.ResourceCacheKey.getSchemaCacheKey({ resource: schemaResource }); const resourceLoader = new import__596.MetadataSchemaLoader({ resource: schemaResource, cacheKey }); import__596.ResourceCache.add(resourceLoader); const cacheEntry = import__596.ResourceCache.cacheEntries[cacheKey]; expect(cacheEntry.referenceCount).toBe(1); expect(cacheEntry.resourceLoader).toBe(resourceLoader); }); it("add throws if resourceLoader is undefined", function() { expect(() => import__596.ResourceCache.add()).toThrowDeveloperError(); }); it("add throws if resourceLoader's cacheKey is undefined", function() { const resourceLoader = new import__596.MetadataSchemaLoader({ resource: schemaResource }); expect(() => import__596.ResourceCache.add(resourceLoader)).toThrowDeveloperError(); }); it("add throws if a resource with this cacheKey is already in the cache", function() { const cacheKey = import__596.ResourceCacheKey.getSchemaCacheKey({ resource: schemaResource }); const resourceLoader = new import__596.MetadataSchemaLoader({ resource: schemaResource, cacheKey }); import__596.ResourceCache.add(resourceLoader); expect(() => import__596.ResourceCache.add(resourceLoader)).toThrowDeveloperError(); }); it("destroys resource when reference count reaches 0", function() { const destroy = spyOn( import__596.MetadataSchemaLoader.prototype, "destroy" ).and.callThrough(); const cacheKey = import__596.ResourceCacheKey.getSchemaCacheKey({ resource: schemaResource }); const resourceLoader = new import__596.MetadataSchemaLoader({ resource: schemaResource, cacheKey }); import__596.ResourceCache.add(resourceLoader); import__596.ResourceCache.get(cacheKey); const cacheEntry = import__596.ResourceCache.cacheEntries[cacheKey]; expect(cacheEntry.referenceCount).toBe(2); import__596.ResourceCache.unload(resourceLoader); expect(cacheEntry.referenceCount).toBe(1); expect(destroy).not.toHaveBeenCalled(); import__596.ResourceCache.unload(resourceLoader); expect(cacheEntry.referenceCount).toBe(0); expect(destroy).toHaveBeenCalled(); expect(import__596.ResourceCache.cacheEntries[cacheKey]).toBeUndefined(); }); it("unload throws if resourceLoader is undefined", function() { expect(function() { import__596.ResourceCache.unload(); }).toThrowDeveloperError(); }); it("unload throws if resourceLoader is not in the cache", function() { const cacheKey = import__596.ResourceCacheKey.getSchemaCacheKey({ resource: schemaResource }); const resourceLoader = new import__596.MetadataSchemaLoader({ resource: schemaResource, cacheKey }); expect(function() { import__596.ResourceCache.unload(resourceLoader); }).toThrowDeveloperError(); }); it("unload throws if resourceLoader has already been unloaded from the cache", function() { const cacheKey = import__596.ResourceCacheKey.getSchemaCacheKey({ resource: schemaResource }); const resourceLoader = new import__596.MetadataSchemaLoader({ resource: schemaResource, cacheKey }); import__596.ResourceCache.add(resourceLoader); import__596.ResourceCache.unload(resourceLoader); expect(function() { import__596.ResourceCache.unload(resourceLoader); }).toThrowDeveloperError(); }); it("gets resource", function() { const cacheKey = import__596.ResourceCacheKey.getSchemaCacheKey({ resource: schemaResource }); const resourceLoader = new import__596.MetadataSchemaLoader({ resource: schemaResource, cacheKey }); import__596.ResourceCache.add(resourceLoader); const cacheEntry = import__596.ResourceCache.cacheEntries[cacheKey]; import__596.ResourceCache.get(cacheKey); expect(cacheEntry.referenceCount).toBe(2); import__596.ResourceCache.get(cacheKey); expect(cacheEntry.referenceCount).toBe(3); }); it("get returns undefined if there is no resource with this cache key", function() { const cacheKey = import__596.ResourceCacheKey.getSchemaCacheKey({ resource: schemaResource }); expect(import__596.ResourceCache.get(cacheKey)).toBeUndefined(); }); it("gets schema loader", function() { const expectedCacheKey = import__596.ResourceCacheKey.getSchemaCacheKey({ schema: schemaJson }); const schemaLoader = import__596.ResourceCache.getSchemaLoader({ schema: schemaJson }); const cacheEntry = import__596.ResourceCache.cacheEntries[expectedCacheKey]; expect(schemaLoader.cacheKey).toBe(expectedCacheKey); expect(cacheEntry.referenceCount).toBe(1); expect(schemaLoader).toBeInstanceOf(import__596.MetadataSchemaLoader); expect( import__596.ResourceCache.getSchemaLoader({ schema: schemaJson }) ).toBe(schemaLoader); expect(cacheEntry.referenceCount).toBe(2); }); it("gets embedded buffer loader", function() { const expectedCacheKey = import__596.ResourceCacheKey.getEmbeddedBufferCacheKey({ parentResource: bufferParentResource, bufferId: 0 }); const bufferLoader = import__596.ResourceCache.getEmbeddedBufferLoader({ parentResource: bufferParentResource, bufferId: 0, typedArray: bufferTypedArray }); const cacheEntry = import__596.ResourceCache.cacheEntries[expectedCacheKey]; expect(bufferLoader.cacheKey).toBe(expectedCacheKey); expect(cacheEntry.referenceCount).toBe(1); expect(bufferLoader).toBeInstanceOf(import__596.BufferLoader); expect( import__596.ResourceCache.getEmbeddedBufferLoader({ parentResource: bufferParentResource, bufferId: 0, typedArray: bufferTypedArray }) ).toBe(bufferLoader); expect(cacheEntry.referenceCount).toBe(2); }); it("getEmbeddedBufferLoader throws if parentResource is undefined", function() { expect( () => import__596.ResourceCache.getEmbeddedBufferLoader({ bufferId: 0, typedArray: bufferTypedArray }) ).toThrowDeveloperError(); }); it("getEmbeddedBufferLoader throws if bufferId is undefined", function() { expect( () => import__596.ResourceCache.getEmbeddedBufferLoader({ parentResource: bufferParentResource, typedArray: bufferTypedArray }) ).toThrowDeveloperError(); }); it("getEmbeddedBufferLoader throws if typedArray is undefined", function() { expect( () => import__596.ResourceCache.getEmbeddedBufferLoader({ parentResource: bufferParentResource, bufferId: 0 }) ).toThrowDeveloperError(); }); it("gets external buffer loader", function() { const expectedCacheKey = import__596.ResourceCacheKey.getExternalBufferCacheKey({ resource: bufferResource }); const bufferLoader = import__596.ResourceCache.getExternalBufferLoader({ resource: bufferResource }); const cacheEntry = import__596.ResourceCache.cacheEntries[expectedCacheKey]; expect(bufferLoader.cacheKey).toBe(expectedCacheKey); expect(cacheEntry.referenceCount).toBe(1); expect(bufferLoader).toBeInstanceOf(import__596.BufferLoader); expect( import__596.ResourceCache.getExternalBufferLoader({ resource: bufferResource }) ).toBe(bufferLoader); expect(cacheEntry.referenceCount).toBe(2); }); it("getExternalBufferLoader throws if resource is undefined", function() { expect( () => import__596.ResourceCache.getExternalBufferLoader({ resource: void 0 }) ).toThrowDeveloperError(); }); it("gets glTF loader", function() { const expectedCacheKey = import__596.ResourceCacheKey.getGltfCacheKey({ gltfResource }); const gltfJsonLoader = import__596.ResourceCache.getGltfJsonLoader({ gltfResource, baseResource: gltfResource }); const cacheEntry = import__596.ResourceCache.cacheEntries[expectedCacheKey]; expect(gltfJsonLoader.cacheKey).toBe(expectedCacheKey); expect(cacheEntry.referenceCount).toBe(1); expect(gltfJsonLoader).toBeInstanceOf(import__596.GltfJsonLoader); expect( import__596.ResourceCache.getGltfJsonLoader({ gltfResource, baseResource: gltfResource }) ).toBe(gltfJsonLoader); expect(cacheEntry.referenceCount).toBe(2); }); it("getGltfJsonLoader throws if gltfResource is undefined", function() { expect( () => import__596.ResourceCache.getGltfJsonLoader({ gltfResource: void 0, baseResource: gltfResource }) ).toThrowDeveloperError(); }); it("loadGltfJson throws if gltfResource is undefined", function() { expect( () => import__596.ResourceCache.getGltfJsonLoader({ gltfResource, baseResource: void 0 }) ).toThrowDeveloperError(); }); it("gets buffer view loader", function() { const expectedCacheKey = import__596.ResourceCacheKey.getBufferViewCacheKey({ gltf: gltfUncompressed, bufferViewId: 0, gltfResource, baseResource: gltfResource }); const bufferViewLoader = import__596.ResourceCache.getBufferViewLoader({ gltf: gltfUncompressed, bufferViewId: 0, gltfResource, baseResource: gltfResource }); const cacheEntry = import__596.ResourceCache.cacheEntries[expectedCacheKey]; expect(bufferViewLoader.cacheKey).toBe(expectedCacheKey); expect(cacheEntry.referenceCount).toBe(1); expect(bufferViewLoader).toBeInstanceOf(import__596.GltfBufferViewLoader); expect( import__596.ResourceCache.getBufferViewLoader({ gltf: gltfUncompressed, bufferViewId: 0, gltfResource, baseResource: gltfResource }) ).toBe(bufferViewLoader); expect(cacheEntry.referenceCount).toBe(2); }); it("getBufferViewLoader throws if gltf is undefined", function() { expect( () => import__596.ResourceCache.getBufferViewLoader({ gltf: void 0, bufferViewId: 0, gltfResource, baseResource: gltfResource }) ).toThrowDeveloperError(); }); it("getBufferViewLoader throws if bufferViewId is undefined", function() { expect( () => import__596.ResourceCache.getBufferViewLoader({ gltf: gltfUncompressed, bufferViewId: void 0, gltfResource, baseResource: gltfResource }) ).toThrowDeveloperError(); }); it("getBufferViewLoader throws if gltfResource is undefined", function() { expect( () => import__596.ResourceCache.getBufferViewLoader({ gltf: gltfUncompressed, bufferViewId: 0, gltfResource: void 0, baseResource: gltfResource }) ).toThrowDeveloperError(); }); it("getBufferViewLoader throws if baseResource is undefined", function() { expect( () => import__596.ResourceCache.getBufferViewLoader({ gltf: gltfUncompressed, bufferViewId: 0, gltfResource, baseResource: void 0 }) ).toThrowDeveloperError(); }); it("gets draco loader", function() { const expectedCacheKey = import__596.ResourceCacheKey.getDracoCacheKey({ gltf: gltfDraco, draco: dracoExtension, gltfResource, baseResource: gltfResource }); const dracoLoader = import__596.ResourceCache.getDracoLoader({ gltf: gltfDraco, draco: dracoExtension, gltfResource, baseResource: gltfResource }); const cacheEntry = import__596.ResourceCache.cacheEntries[expectedCacheKey]; expect(dracoLoader.cacheKey).toBe(expectedCacheKey); expect(cacheEntry.referenceCount).toBe(1); expect(dracoLoader).toBeInstanceOf(import__596.GltfDracoLoader); expect( import__596.ResourceCache.getDracoLoader({ gltf: gltfDraco, draco: dracoExtension, gltfResource, baseResource: gltfResource }) ).toBe(dracoLoader); expect(cacheEntry.referenceCount).toBe(2); }); it("getDracoLoader throws if gltf is undefined", function() { expect( () => import__596.ResourceCache.getDracoLoader({ gltf: void 0, draco: dracoExtension, gltfResource, baseResource: gltfResource }) ).toThrowDeveloperError(); }); it("getDracoLoader throws if draco is undefined", function() { expect( () => import__596.ResourceCache.getDracoLoader({ gltf: gltfDraco, draco: void 0, gltfResource, baseResource: gltfResource }) ).toThrowDeveloperError(); }); it("getDracoLoader throws if gltfResource is undefined", function() { expect( () => import__596.ResourceCache.getDracoLoader({ gltf: gltfDraco, draco: dracoExtension, gltfResource: void 0, baseResource: gltfResource }) ).toThrowDeveloperError(); }); it("getDracoLoader throws if baseResource is undefined", function() { expect( () => import__596.ResourceCache.getDracoLoader({ gltf: gltfDraco, draco: dracoExtension, gltfResource, baseResource: void 0 }) ).toThrowDeveloperError(); }); it("gets vertex buffer loader for buffer view", function() { const expectedCacheKey = import__596.ResourceCacheKey.getVertexBufferCacheKey({ gltf: gltfUncompressed, gltfResource, baseResource: gltfResource, frameState: mockFrameState, bufferViewId: 0, loadBuffer: true }); const vertexBufferLoader = import__596.ResourceCache.getVertexBufferLoader({ gltf: gltfUncompressed, gltfResource, baseResource: gltfResource, frameState: mockFrameState, bufferViewId: 0, accessorId: 0, loadBuffer: true }); const cacheEntry = import__596.ResourceCache.cacheEntries[expectedCacheKey]; expect(vertexBufferLoader.cacheKey).toBe(expectedCacheKey); expect(cacheEntry.referenceCount).toBe(1); expect(vertexBufferLoader).toBeInstanceOf(import__596.GltfVertexBufferLoader); expect( import__596.ResourceCache.getVertexBufferLoader({ gltf: gltfUncompressed, gltfResource, baseResource: gltfResource, frameState: mockFrameState, bufferViewId: 0, loadBuffer: true }) ).toBe(vertexBufferLoader); expect(cacheEntry.referenceCount).toBe(2); }); it("gets vertex buffer loader for draco", function() { const expectedCacheKey = import__596.ResourceCacheKey.getVertexBufferCacheKey({ gltf: gltfDraco, gltfResource, baseResource: gltfResource, frameState: mockFrameState, draco: dracoExtension, attributeSemantic: "POSITION", loadBuffer: true }); const vertexBufferLoader = import__596.ResourceCache.getVertexBufferLoader({ gltf: gltfDraco, gltfResource, baseResource: gltfResource, frameState: mockFrameState, draco: dracoExtension, attributeSemantic: "POSITION", accessorId: 0, loadBuffer: true }); const cacheEntry = import__596.ResourceCache.cacheEntries[expectedCacheKey]; expect(vertexBufferLoader.cacheKey).toBe(expectedCacheKey); expect(cacheEntry.referenceCount).toBe(1); expect(vertexBufferLoader).toBeInstanceOf(import__596.GltfVertexBufferLoader); expect( import__596.ResourceCache.getVertexBufferLoader({ gltf: gltfDraco, gltfResource, baseResource: gltfResource, frameState: mockFrameState, draco: dracoExtension, attributeSemantic: "POSITION", accessorId: 0, loadBuffer: true }) ).toBe(vertexBufferLoader); expect(cacheEntry.referenceCount).toBe(2); }); it("gets vertex buffer loaders on different contexts", function() { const vertexBufferLoader1 = import__596.ResourceCache.getVertexBufferLoader({ gltf: gltfUncompressed, gltfResource, baseResource: gltfResource, frameState: mockFrameState, bufferViewId: 0, accessorId: 0, loadBuffer: true }); const vertexBufferLoader2 = import__596.ResourceCache.getVertexBufferLoader({ gltf: gltfUncompressed, gltfResource, baseResource: gltfResource, frameState: mockFrameState2, bufferViewId: 0, accessorId: 0, loadBuffer: true }); expect(vertexBufferLoader1).toBeDefined(); expect(vertexBufferLoader2).toBeDefined(); expect(vertexBufferLoader1).not.toBe(vertexBufferLoader2); }); it("getVertexBufferLoader throws if gltf is undefined", function() { expect( () => import__596.ResourceCache.getVertexBufferLoader({ gltf: void 0, gltfResource, baseResource: gltfResource, frameState: mockFrameState, bufferViewId: 0, loadBuffer: true }) ).toThrowDeveloperError(); }); it("getVertexBufferLoader throws if gltfResource is undefined", function() { expect( () => import__596.ResourceCache.getVertexBufferLoader({ gltf: gltfUncompressed, gltfResource: void 0, baseResource: gltfResource, frameState: mockFrameState, bufferViewId: 0, loadBuffer: true }) ).toThrowDeveloperError(); }); it("getVertexBufferLoader throws if baseResource is undefined", function() { expect( () => import__596.ResourceCache.getVertexBufferLoader({ gltf: gltfUncompressed, gltfResource, baseResource: void 0, frameState: mockFrameState, bufferViewId: 0, loadBuffer: true }) ).toThrowDeveloperError(); }); it("getVertexBufferLoader throws if frameState is undefined", function() { expect( () => import__596.ResourceCache.getVertexBufferLoader({ gltf: gltfUncompressed, gltfResource, baseResource: gltfResource, frameState: void 0, bufferViewId: 0, loadBuffer: true }) ).toThrowDeveloperError(); }); it("getVertexBufferLoader throws if bufferViewId and draco are both defined", function() { expect( () => import__596.ResourceCache.getVertexBufferLoader({ gltf: gltfDraco, gltfResource, baseResource: gltfResource, frameState: mockFrameState, bufferViewId: 0, draco: dracoExtension, attributeSemantic: "POSITION", accessorId: 0, loadBuffer: true }) ).toThrowDeveloperError(); }); it("getVertexBufferLoader throws if bufferViewId and draco are both undefined", function() { expect( () => import__596.ResourceCache.getVertexBufferLoader({ gltf: gltfDraco, gltfResource, baseResource: gltfResource, frameState: mockFrameState, loadBuffer: true }) ).toThrowDeveloperError(); }); it("getVertexBufferLoader throws if draco is defined and attributeSemantic is not defined", function() { expect( () => import__596.ResourceCache.getVertexBufferLoader({ gltf: gltfDraco, gltfResource, baseResource: gltfResource, frameState: mockFrameState, draco: dracoExtension, attributeSemantic: void 0, accessorId: 0, loadBuffer: true }) ).toThrowDeveloperError(); }); it("getVertexBufferLoader throws if draco is defined and accessorId is not defined", function() { expect( () => import__596.ResourceCache.getVertexBufferLoader({ gltf: gltfDraco, gltfResource, baseResource: gltfResource, frameState: mockFrameState, draco: dracoExtension, attributeSemantic: "POSITION", accessorId: void 0, loadBuffer: true }) ).toThrowDeveloperError(); }); it("getVertexBufferLoader throws if both loadBuffer and loadTypedArray are false", function() { expect( () => import__596.ResourceCache.getVertexBufferLoader({ gltf: gltfUncompressed, gltfResource, baseResource: gltfResource, frameState: mockFrameState, bufferViewId: 0, loadBuffer: false, loadTypedArray: false }) ).toThrowDeveloperError(); }); it("gets index buffer loader for accessor as buffer", function() { const expectedCacheKey = import__596.ResourceCacheKey.getIndexBufferCacheKey({ gltf: gltfUncompressed, accessorId: 2, gltfResource, baseResource: gltfResource, frameState: mockFrameState, loadBuffer: true }); const indexBufferLoader = import__596.ResourceCache.getIndexBufferLoader({ gltf: gltfUncompressed, accessorId: 2, gltfResource, baseResource: gltfResource, frameState: mockFrameState, loadBuffer: true }); const cacheEntry = import__596.ResourceCache.cacheEntries[expectedCacheKey]; expect(indexBufferLoader.cacheKey).toBe(expectedCacheKey); expect(cacheEntry.referenceCount).toBe(1); expect(indexBufferLoader).toBeInstanceOf(import__596.GltfIndexBufferLoader); expect( import__596.ResourceCache.getIndexBufferLoader({ gltf: gltfUncompressed, accessorId: 2, gltfResource, baseResource: gltfResource, frameState: mockFrameState, loadBuffer: true }) ).toBe(indexBufferLoader); expect(cacheEntry.referenceCount).toBe(2); }); it("loads index buffer from draco", function() { const expectedCacheKey = import__596.ResourceCacheKey.getIndexBufferCacheKey({ gltf: gltfDraco, accessorId: 2, gltfResource, baseResource: gltfResource, frameState: mockFrameState, draco: dracoExtension, loadBuffer: true }); const indexBufferLoader = import__596.ResourceCache.getIndexBufferLoader({ gltf: gltfDraco, accessorId: 2, gltfResource, baseResource: gltfResource, frameState: mockFrameState, draco: dracoExtension, loadBuffer: true }); const cacheEntry = import__596.ResourceCache.cacheEntries[expectedCacheKey]; expect(indexBufferLoader.cacheKey).toBe(expectedCacheKey); expect(cacheEntry.referenceCount).toBe(1); expect(indexBufferLoader).toBeInstanceOf(import__596.GltfIndexBufferLoader); expect( import__596.ResourceCache.getIndexBufferLoader({ gltf: gltfDraco, accessorId: 2, gltfResource, baseResource: gltfResource, frameState: mockFrameState, draco: dracoExtension, loadBuffer: true }) ).toBe(indexBufferLoader); expect(cacheEntry.referenceCount).toBe(2); }); it("gets index buffer loaders on different contexts", function() { const indexBufferLoader1 = import__596.ResourceCache.getIndexBufferLoader({ gltf: gltfUncompressed, accessorId: 2, gltfResource, baseResource: gltfResource, frameState: mockFrameState, loadBuffer: true }); const indexBufferLoader2 = import__596.ResourceCache.getIndexBufferLoader({ gltf: gltfUncompressed, accessorId: 2, gltfResource, baseResource: gltfResource, frameState: mockFrameState2, loadBuffer: true }); expect(indexBufferLoader1).toBeDefined(); expect(indexBufferLoader2).toBeDefined(); expect(indexBufferLoader1).not.toBe(indexBufferLoader2); }); it("getIndexBufferLoader throws if gltf is undefined", function() { expect( () => import__596.ResourceCache.getIndexBufferLoader({ gltf: void 0, accessorId: 2, gltfResource, baseResource: gltfResource, frameState: mockFrameState, loadBuffer: true }) ).toThrowDeveloperError(); }); it("getIndexBufferLoader throws if accessorId is undefined", function() { expect( () => import__596.ResourceCache.getIndexBufferLoader({ gltf: gltfUncompressed, accessorId: void 0, gltfResource, baseResource: gltfResource, frameState: mockFrameState, loadBuffer: true }) ).toThrowDeveloperError(); }); it("getIndexBufferLoader throws if gltfResource is undefined", function() { expect( () => import__596.ResourceCache.getIndexBufferLoader({ gltf: gltfUncompressed, accessorId: 2, gltfResource: void 0, baseResource: gltfResource, frameState: mockFrameState, loadBuffer: true }) ).toThrowDeveloperError(); }); it("getIndexBufferLoader throws if baseResource is undefined", function() { expect( () => import__596.ResourceCache.getIndexBufferLoader({ gltf: gltfUncompressed, accessorId: 2, gltfResource, baseResource: void 0, frameState: mockFrameState, loadBuffer: true }) ).toThrowDeveloperError(); }); it("getIndexBufferLoader throws if frameState is undefined", function() { expect( () => import__596.ResourceCache.getIndexBufferLoader({ gltf: gltfUncompressed, accessorId: 2, gltfResource, baseResource: gltfResource, frameState: void 0, loadBuffer: true }) ).toThrowDeveloperError(); }); it("getIndexBufferLoader throws if both loadBuffer and loadTypedArray are false", function() { expect( () => import__596.ResourceCache.getIndexBufferLoader({ gltf: gltfUncompressed, accessorId: 2, gltfResource, baseResource: gltfResource, frameState: mockFrameState, loadBuffer: false, loadTypedArray: false }) ).toThrowDeveloperError(); }); it("gets image loader", function() { const expectedCacheKey = import__596.ResourceCacheKey.getImageCacheKey({ gltf: gltfWithTextures, imageId: 0, gltfResource, baseResource: gltfResource }); const imageLoader = import__596.ResourceCache.getImageLoader({ gltf: gltfWithTextures, imageId: 0, gltfResource, baseResource: gltfResource }); const cacheEntry = import__596.ResourceCache.cacheEntries[expectedCacheKey]; expect(imageLoader.cacheKey).toBe(expectedCacheKey); expect(cacheEntry.referenceCount).toBe(1); expect(imageLoader).toBeInstanceOf(import__596.GltfImageLoader); expect( import__596.ResourceCache.getImageLoader({ gltf: gltfWithTextures, imageId: 0, gltfResource, baseResource: gltfResource }) ).toBe(imageLoader); expect(cacheEntry.referenceCount).toBe(2); }); it("getImageLoader throws if gltf is undefined", function() { expect( () => import__596.ResourceCache.getImageLoader({ gltf: void 0, imageId: 0, gltfResource, baseResource: gltfResource }) ).toThrowDeveloperError(); }); it("getImageLoader throws if imageId is undefined", function() { expect( () => import__596.ResourceCache.getImageLoader({ gltf: gltfWithTextures, imageId: void 0, gltfResource, baseResource: gltfResource }) ).toThrowDeveloperError(); }); it("getImageLoader throws if gltfResource is undefined", function() { expect( () => import__596.ResourceCache.getImageLoader({ gltf: gltfWithTextures, imageId: 0, gltfResource: void 0, baseResource: gltfResource }) ).toThrowDeveloperError(); }); it("getImageLoader throws if baseResource is undefined", function() { expect( () => import__596.ResourceCache.getImageLoader({ gltf: gltfWithTextures, imageId: 0, gltfResource, baseResource: void 0 }) ).toThrowDeveloperError(); }); it("gets texture loader", function() { const expectedCacheKey = import__596.ResourceCacheKey.getTextureCacheKey({ gltf: gltfWithTextures, textureInfo: gltfWithTextures.materials[0].emissiveTexture, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__596.SupportedImageFormats(), frameState: mockFrameState }); const textureLoader = import__596.ResourceCache.getTextureLoader({ gltf: gltfWithTextures, textureInfo: gltfWithTextures.materials[0].emissiveTexture, gltfResource, baseResource: gltfResource, frameState: mockFrameState, supportedImageFormats: new import__596.SupportedImageFormats() }); const cacheEntry = import__596.ResourceCache.cacheEntries[expectedCacheKey]; expect(textureLoader.cacheKey).toBe(expectedCacheKey); expect(cacheEntry.referenceCount).toBe(1); expect(textureLoader).toBeInstanceOf(import__596.GltfTextureLoader); expect( import__596.ResourceCache.getTextureLoader({ gltf: gltfWithTextures, textureInfo: gltfWithTextures.materials[0].emissiveTexture, gltfResource, baseResource: gltfResource, frameState: mockFrameState, supportedImageFormats: new import__596.SupportedImageFormats() }) ).toBe(textureLoader); expect(cacheEntry.referenceCount).toBe(2); }); it("get texture loaders in different contexts", function() { const textureLoader1 = import__596.ResourceCache.getTextureLoader({ gltf: gltfWithTextures, textureInfo: gltfWithTextures.materials[0].emissiveTexture, gltfResource, baseResource: gltfResource, frameState: mockFrameState, supportedImageFormats: new import__596.SupportedImageFormats() }); const textureLoader2 = import__596.ResourceCache.getTextureLoader({ gltf: gltfWithTextures, textureInfo: gltfWithTextures.materials[0].emissiveTexture, gltfResource, baseResource: gltfResource, frameState: mockFrameState2, supportedImageFormats: new import__596.SupportedImageFormats() }); expect(textureLoader1).toBeDefined(); expect(textureLoader2).toBeDefined(); expect(textureLoader1).not.toBe(textureLoader2); }); it("getTextureLoader throws if gltf is undefined", function() { expect( () => import__596.ResourceCache.getTextureLoader({ gltf: void 0, textureInfo: gltfWithTextures.materials[0].emissiveTexture, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__596.SupportedImageFormats(), frameState: mockFrameState }) ).toThrowDeveloperError(); }); it("getTextureLoader throws if textureInfo is undefined", function() { expect( () => import__596.ResourceCache.getTextureLoader({ gltf: gltfWithTextures, textureInfo: void 0, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__596.SupportedImageFormats(), frameState: mockFrameState }) ).toThrowDeveloperError(); }); it("getTextureLoader throws if gltfResource is undefined", function() { expect( () => import__596.ResourceCache.getTextureLoader({ gltf: gltfWithTextures, textureInfo: gltfWithTextures.materials[0].emissiveTexture, gltfResource: void 0, baseResource: gltfResource, supportedImageFormats: new import__596.SupportedImageFormats(), frameState: mockFrameState }) ).toThrowDeveloperError(); }); it("getTextureLoader throws if baseResource is undefined", function() { expect( () => import__596.ResourceCache.getTextureLoader({ gltf: gltfWithTextures, textureInfo: gltfWithTextures.materials[0].emissiveTexture, gltfResource, baseResource: void 0, supportedImageFormats: new import__596.SupportedImageFormats(), frameState: mockFrameState }) ).toThrowDeveloperError(); }); it("getTextureLoader throws if supportedImageFormats is undefined", function() { expect( () => import__596.ResourceCache.getTextureLoader({ gltf: gltfWithTextures, textureInfo: gltfWithTextures.materials[0].emissiveTexture, gltfResource, baseResource: gltfResource, supportedImageFormats: void 0, frameState: mockFrameState }) ).toThrowDeveloperError(); }); it("getTextureLoader throws if frameState is undefined", function() { expect( () => import__596.ResourceCache.getTextureLoader({ gltf: gltfWithTextures, textureInfo: gltfWithTextures.materials[0].emissiveTexture, gltfResource, baseResource: gltfResource, supportedImageFormats: new import__596.SupportedImageFormats(), frameState: void 0 }) ).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/ResourceCacheStatisticsSpec.js var import__597 = __toESM(require_Cesium(), 1); describe("Scene/ResourceCacheStatistics", function() { it("constructs", function() { const statistics = new import__597.ResourceCacheStatistics(); expect(statistics.geometryByteLength).toBe(0); expect(statistics.texturesByteLength).toBe(0); expect(statistics._geometrySizes).toEqual({}); expect(statistics._textureSizes).toEqual({}); }); function mockLoader(cacheKey, data) { return (0, import__597.combine)(data, { cacheKey }); } it("clears", function() { const statistics = new import__597.ResourceCacheStatistics(); const geometryLoader = mockLoader("vertices", { buffer: { sizeInBytes: 100 } }); const textureLoader = mockLoader("texture", { texture: { sizeInBytes: 300 } }); statistics.addGeometryLoader(geometryLoader); statistics.addTextureLoader(textureLoader); expect(statistics.geometryByteLength).not.toBe(0); expect(statistics.texturesByteLength).not.toBe(0); expect(statistics._geometrySizes).not.toEqual({}); expect(statistics._textureSizes).not.toEqual({}); statistics.clear(); expect(statistics.geometryByteLength).toBe(0); expect(statistics.texturesByteLength).toBe(0); expect(statistics._geometrySizes).toEqual({}); expect(statistics._textureSizes).toEqual({}); }); it("addGeometryLoader throws for undefined loader", function() { const statistics = new import__597.ResourceCacheStatistics(); expect(function() { statistics.addGeometryLoader(void 0); }).toThrowDeveloperError(); }); it("addGeometryLoader counts geometry memory", function() { const statistics = new import__597.ResourceCacheStatistics(); const geometryLoader = mockLoader("vertices", { buffer: { sizeInBytes: 100 } }); statistics.addGeometryLoader(geometryLoader); expect(statistics.geometryByteLength).toBe(100); expect(statistics.texturesByteLength).toBe(0); expect(statistics._geometrySizes).toEqual({ vertices: 100 }); expect(statistics._textureSizes).toEqual({}); }); it("addGeometryLoader counts buffers with typed arrays", function() { const statistics = new import__597.ResourceCacheStatistics(); const geometryLoader = mockLoader("vertices", { buffer: { sizeInBytes: 100 }, typedArray: new Uint8Array(100) }); statistics.addGeometryLoader(geometryLoader); expect(statistics.geometryByteLength).toBe(200); expect(statistics.texturesByteLength).toBe(0); expect(statistics._geometrySizes).toEqual({ vertices: 200 }); expect(statistics._textureSizes).toEqual({}); }); it("addGeometryLoader does not double count memory", function() { const statistics = new import__597.ResourceCacheStatistics(); const geometryLoader = mockLoader("vertices", { buffer: { sizeInBytes: 100 }, typedArray: new Uint8Array(100) }); statistics.addGeometryLoader(geometryLoader); statistics.addGeometryLoader(geometryLoader); expect(statistics.geometryByteLength).toBe(200); expect(statistics.texturesByteLength).toBe(0); expect(statistics._geometrySizes).toEqual({ vertices: 200 }); expect(statistics._textureSizes).toEqual({}); }); it("addTextureLoader throws for undefined loader", function() { const statistics = new import__597.ResourceCacheStatistics(); expect(function() { statistics.addTextureLoader(void 0); }).toThrowDeveloperError(); }); it("addTextureLoader counts texture memory", function() { const statistics = new import__597.ResourceCacheStatistics(); const textureLoader = mockLoader("texture", { texture: { sizeInBytes: 100 } }); statistics.addTextureLoader(textureLoader); expect(statistics.geometryByteLength).toBe(0); expect(statistics.texturesByteLength).toBe(100); expect(statistics._geometrySizes).toEqual({}); expect(statistics._textureSizes).toEqual({ texture: 100 }); }); it("addTextureLoader does not double count memory", function() { const statistics = new import__597.ResourceCacheStatistics(); const textureLoader = mockLoader("texture", { texture: { sizeInBytes: 100 } }); statistics.addTextureLoader(textureLoader); statistics.addTextureLoader(textureLoader); expect(statistics.geometryByteLength).toBe(0); expect(statistics.texturesByteLength).toBe(100); expect(statistics._geometrySizes).toEqual({}); expect(statistics._textureSizes).toEqual({ texture: 100 }); }); it("removeLoader throws for undefined loader", function() { const statistics = new import__597.ResourceCacheStatistics(); expect(function() { statistics.removeLoader(void 0); }).toThrowDeveloperError(); }); it("removeLoader correctly updates memory for buffers", function() { const geometryLoader = mockLoader("vertices", { buffer: { sizeInBytes: 100 } }); const geometryLoader2 = mockLoader("indices", { buffer: { sizeInBytes: 200 } }); const textureLoader = mockLoader("texture", { texture: { sizeInBytes: 300 } }); const statistics = new import__597.ResourceCacheStatistics(); statistics.addGeometryLoader(geometryLoader); statistics.addGeometryLoader(geometryLoader2); statistics.addTextureLoader(textureLoader); expect(statistics.geometryByteLength).toBe(300); expect(statistics.texturesByteLength).toBe(300); expect(statistics._geometrySizes).toEqual({ vertices: 100, indices: 200 }); statistics.removeLoader(geometryLoader2); expect(statistics.geometryByteLength).toBe(100); expect(statistics.texturesByteLength).toBe(300); expect(statistics._geometrySizes).toEqual({ vertices: 100 }); expect(statistics._textureSizes).toEqual({ texture: 300 }); }); it("removeLoader correctly updates memory for textures", function() { const geometryLoader = mockLoader("vertices", { buffer: { sizeInBytes: 100 } }); const textureLoader = mockLoader("texture", { texture: { sizeInBytes: 300 } }); const textureLoader2 = mockLoader("texture2", { texture: { sizeInBytes: 500 } }); const statistics = new import__597.ResourceCacheStatistics(); statistics.addGeometryLoader(geometryLoader); statistics.addTextureLoader(textureLoader); statistics.addTextureLoader(textureLoader2); expect(statistics.geometryByteLength).toBe(100); expect(statistics.texturesByteLength).toBe(800); expect(statistics._geometrySizes).toEqual({ vertices: 100 }); expect(statistics._textureSizes).toEqual({ texture: 300, texture2: 500 }); statistics.removeLoader(textureLoader2); expect(statistics.geometryByteLength).toBe(100); expect(statistics.texturesByteLength).toBe(300); expect(statistics._geometrySizes).toEqual({ vertices: 100 }); expect(statistics._textureSizes).toEqual({ texture: 300 }); }); it("removeLoader gracefully handles loader without tracked resources", function() { const statistics = new import__597.ResourceCacheStatistics(); const textureLoader = mockLoader("texture", { texture: { sizeInBytes: 300 } }); expect(function() { statistics.removeLoader(textureLoader); }).not.toThrowDeveloperError(); expect(statistics.geometryByteLength).toBe(0); expect(statistics.texturesByteLength).toBe(0); expect(statistics._geometrySizes).toEqual({}); expect(statistics._textureSizes).toEqual({}); }); }); // packages/engine/Specs/Scene/ResourceLoaderSpec.js var import__598 = __toESM(require_Cesium(), 1); describe("Scene/ResourceLoader", function() { it("throws when using ResourceLoader directly", function() { const resourceLoader = new import__598.ResourceLoader(); expect(function() { return resourceLoader.cacheKey; }).toThrowDeveloperError(); expect(function() { resourceLoader.load(); }).toThrowDeveloperError(); }); it("getError from error message", function() { const resourceLoader = new import__598.ResourceLoader(); const errorMessage = "Resource failed"; const runtimeError = resourceLoader.getError(errorMessage); expect(runtimeError.message).toBe(errorMessage); }); it("getError from error message and error", function() { const resourceLoader = new import__598.ResourceLoader(); const errorMessage = "Resource failed"; const error = new Error("404 Not Found"); const runtimeError = resourceLoader.getError(errorMessage, error); expect(runtimeError.message).toBe("Resource failed\n404 Not Found"); }); it("getError throws if errorMessage is undefined", function() { const resourceLoader = new import__598.ResourceLoader(); expect(function() { resourceLoader.getError(); }).toThrowDeveloperError(); }); it("destroys", function() { const resourceLoader = new import__598.ResourceLoader(); expect(resourceLoader.isDestroyed()).toBe(false); resourceLoader.destroy(); expect(resourceLoader.isDestroyed()).toBe(true); }); }); // packages/engine/Specs/Scene/SceneSpec.js var import__599 = __toESM(require_Cesium(), 1); var import__600 = __toESM(require_Cesium(), 1); // Specs/render.js var import_engine30 = __toESM(require_Cesium(), 1); function executeCommands(frameState2, commands) { let commandsExecuted = 0; const cullingVolume = frameState2.cullingVolume; let occluder; if (frameState2.mode === import_engine30.SceneMode.SCENE3D) { occluder = frameState2.occluder; } const length2 = commands.length; for (let i = 0; i < length2; ++i) { const command = commands[i]; const boundingVolume = command.boundingVolume; if ((0, import_engine30.defined)(boundingVolume)) { if (cullingVolume.computeVisibility(boundingVolume) === import_engine30.Intersect.OUTSIDE || (0, import_engine30.defined)(occluder) && !occluder.isBoundingSphereVisible(boundingVolume)) { continue; } } command.execute(frameState2.context); commandsExecuted++; } return commandsExecuted; } function render(frameState2, primitive) { frameState2.commandList.length = 0; primitive.update(frameState2); let i; const renderCommands = new Array(import_engine30.Pass.NUMBER_OF_PASSES); for (i = 0; i < import_engine30.Pass.NUMBER_OF_PASSES; ++i) { renderCommands[i] = []; } const commands = frameState2.commandList; const length2 = commands.length; for (i = 0; i < length2; i++) { const command = commands[i]; const pass = (0, import_engine30.defined)(command.pass) ? command.pass : import_engine30.Pass.OPAQUE; renderCommands[pass].push(command); } let commandsExecuted = 0; for (i = 0; i < import_engine30.Pass.NUMBER_OF_PASSES; ++i) { commandsExecuted += executeCommands(frameState2, renderCommands[i]); } return commandsExecuted; } var render_default = render; // packages/engine/Specs/Scene/SceneSpec.js describe( "Scene/Scene", function() { let scene2; beforeAll(function() { return import__599.GroundPrimitive.initializeTerrainHeights(); }); beforeEach(function() { scene2 = createScene_default(); }); afterEach(function() { scene2.destroyForSpecs(); }); function getSimpleShaderProgram() { return import__599.ShaderProgram.fromCache({ context: scene2.context, vertexShaderSource: new import__599.ShaderSource({ sources: ["void main() { gl_Position = vec4(1.0); }"] }), fragmentShaderSource: new import__599.ShaderSource({ sources: ["void main() { out_FragColor = vec4(1.0); }"] }) }); } function returnTileJson(path) { import__599.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { import__599.Resource._DefaultImplementations.loadWithXhr( path, responseType, method, data, headers, deferred ); }; } function returnQuantizedMeshTileJson() { return returnTileJson( "Data/CesiumTerrainTileJson/QuantizedMesh.tile.json" ); } function createRectangle(rectangle, height) { return new import__599.Primitive({ geometryInstances: new import__599.GeometryInstance({ geometry: new import__599.RectangleGeometry({ rectangle, vertexFormat: import__599.EllipsoidSurfaceAppearance.VERTEX_FORMAT, height }) }), appearance: new import__599.EllipsoidSurfaceAppearance({ aboveGround: false }), asynchronous: false }); } describe("constructor", () => { it("has expected defaults", function() { expect(scene2.canvas).toBeInstanceOf(HTMLCanvasElement); expect(scene2.primitives).toBeInstanceOf(import__599.PrimitiveCollection); expect(scene2.camera).toBeInstanceOf(import__599.Camera); expect(scene2.screenSpaceCameraController).toBeInstanceOf( import__599.ScreenSpaceCameraController ); expect(scene2.mapProjection).toBeInstanceOf(import__599.GeographicProjection); expect(scene2.frameState).toBeInstanceOf(import__599.FrameState); expect(scene2.tweens).toBeInstanceOf(import__599.TweenCollection); const contextAttributes = scene2.context._gl.getContextAttributes(); expect(contextAttributes.alpha).toEqual(false); expect(contextAttributes.stencil).toEqual(true); expect(contextAttributes.premultipliedAlpha).toEqual(true); expect(contextAttributes.preserveDrawingBuffer).toEqual(false); expect(scene2._depthPlane._ellipsoidOffset).toEqual(0); }); it("respects default log depth buffer override", () => { const previous = import__599.Scene.defaultLogDepthBuffer; import__599.Scene.defaultLogDepthBuffer = false; const newScene = createScene_default(); expect(newScene._logDepthBuffer).toEqual(false); import__599.Scene.defaultLogDepthBuffer = previous; }); it("sets options", function() { const webglOptions = { alpha: true, depth: false, stencil: true, antialias: false, premultipliedAlpha: false, preserveDrawingBuffer: true }; const mapProjection = new import__599.WebMercatorProjection(); const s = createScene_default({ contextOptions: { webgl: webglOptions }, mapProjection, depthPlaneEllipsoidOffset: Number.POSITIVE_INFINITY }); const contextAttributes = s.context._gl.getContextAttributes(); expect(contextAttributes.alpha).toEqual(webglOptions.alpha); expect(contextAttributes.depth).toEqual(webglOptions.depth); expect(contextAttributes.stencil).toEqual(webglOptions.stencil); expect(contextAttributes.antialias).toEqual(webglOptions.antialias); expect(contextAttributes.premultipliedAlpha).toEqual( webglOptions.premultipliedAlpha ); expect(contextAttributes.preserveDrawingBuffer).toEqual( webglOptions.preserveDrawingBuffer ); expect(s.mapProjection).toEqual(mapProjection); expect(s._depthPlane._ellipsoidOffset).toEqual( Number.POSITIVE_INFINITY ); s.destroyForSpecs(); }); it("throws without options", function() { expect(function() { return new import__599.Scene(); }).toThrowDeveloperError(); }); it("throws without options.canvas", function() { expect(function() { return new import__599.Scene({}); }).toThrowDeveloperError(); }); it("draws background color", function() { expect(scene2).toRender([0, 0, 0, 255]); scene2.backgroundColor = import__599.Color.BLUE; expect(scene2).toRender([0, 0, 255, 255]); }); }); it("calls afterRender functions", function() { const spyListener = jasmine.createSpy("listener"); const primitive = { update: function(frameState2) { frameState2.afterRender.push(spyListener); }, destroy: function() { }, isDestroyed: () => false }; scene2.primitives.add(primitive); scene2.renderForSpecs(); expect(spyListener).toHaveBeenCalled(); }); function CommandMockPrimitive(command) { this.update = function(frameState2) { frameState2.commandList.push(command); }; this.destroy = function() { }; this.isDestroyed = function() { return false; }; } it("debugCommandFilter filters commands", function() { const c = new import__599.DrawCommand({ shaderProgram: getSimpleShaderProgram(), renderState: new import__599.RenderState(), pass: import__599.Pass.OPAQUE }); c.execute = function() { }; spyOn(c, "execute"); scene2.primitives.add(new CommandMockPrimitive(c)); scene2.debugCommandFilter = function(command) { return command !== c; }; scene2.renderForSpecs(); expect(c.execute).not.toHaveBeenCalled(); }); it("debugCommandFilter does not filter commands", function() { const originalLogDepth = scene2.logarithmicDepthBuffer; scene2.logarithmicDepthBuffer = false; const c = new import__599.DrawCommand({ shaderProgram: getSimpleShaderProgram(), renderState: new import__599.RenderState(), pass: import__599.Pass.OPAQUE }); c.execute = function() { }; spyOn(c, "execute"); scene2.primitives.add(new CommandMockPrimitive(c)); expect(scene2.debugCommandFilter).toBeUndefined(); scene2.renderForSpecs(); expect(c.execute).toHaveBeenCalled(); scene2.logarithmicDepthBuffer = originalLogDepth; }); it("debugShowBoundingVolume draws a bounding sphere", function() { const originalLogDepth = scene2.logarithmicDepthBuffer; scene2.logarithmicDepthBuffer = false; const radius = 10; const center = import__599.Cartesian3.add( scene2.camera.position, scene2.camera.direction, new import__599.Cartesian3() ); const c = new import__599.DrawCommand({ shaderProgram: getSimpleShaderProgram(), renderState: new import__599.RenderState(), pass: import__599.Pass.OPAQUE, debugShowBoundingVolume: true, boundingVolume: new import__599.BoundingSphere(center, radius) }); c.execute = function() { }; scene2.primitives.add(new CommandMockPrimitive(c)); scene2.depthTestAgainstTerrain = true; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).not.toEqual(0); }); scene2.logarithmicDepthBuffer = originalLogDepth; }); it("debugShowCommands tints commands", function() { const originalLogDepth = scene2.logarithmicDepthBuffer; scene2.logarithmicDepthBuffer = false; const c = new import__599.DrawCommand({ shaderProgram: getSimpleShaderProgram(), renderState: new import__599.RenderState(), pass: import__599.Pass.OPAQUE }); c.execute = function() { }; const originalShallowClone = import__599.DrawCommand.shallowClone; spyOn(import__599.DrawCommand, "shallowClone").and.callFake(function(command, result) { result = originalShallowClone(command, result); result.execute = function() { result.uniformMap.debugShowCommandsColor(); }; return result; }); scene2.primitives.add(new CommandMockPrimitive(c)); scene2.debugShowCommands = true; scene2.renderForSpecs(); expect(c._debugColor).toBeDefined(); scene2.debugShowCommands = false; scene2.logarithmicDepthBuffer = originalLogDepth; }); it("debugShowFramesPerSecond", function() { scene2.debugShowFramesPerSecond = true; scene2.renderForSpecs(); expect(scene2._performanceDisplay).toBeDefined(); scene2.debugShowFramesPerSecond = false; }); it("opaque/translucent render order (1)", function() { const rectangle = import__599.Rectangle.fromDegrees(-100, 30, -90, 40); const rectanglePrimitive1 = createRectangle(rectangle); rectanglePrimitive1.appearance.material.uniforms.color = new import__599.Color( 1, 0, 0, 1 ); const rectanglePrimitive2 = createRectangle(rectangle, 1e3); rectanglePrimitive2.appearance.material.uniforms.color = new import__599.Color( 0, 1, 0, 0.5 ); const primitives = scene2.primitives; primitives.add(rectanglePrimitive1); primitives.add(rectanglePrimitive2); scene2.camera.setView({ destination: rectangle }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).not.toEqual(0); expect(rgba[1]).not.toEqual(0); expect(rgba[2]).toEqual(0); }); primitives.raiseToTop(rectanglePrimitive1); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).not.toEqual(0); expect(rgba[1]).not.toEqual(0); expect(rgba[2]).toEqual(0); }); }); it("opaque/translucent render order (2)", function() { const rectangle = import__599.Rectangle.fromDegrees(-100, 30, -90, 40); const rectanglePrimitive1 = createRectangle(rectangle, 1e3); rectanglePrimitive1.appearance.material.uniforms.color = new import__599.Color( 1, 0, 0, 1 ); const rectanglePrimitive2 = createRectangle(rectangle); rectanglePrimitive2.appearance.material.uniforms.color = new import__599.Color( 0, 1, 0, 0.5 ); const primitives = scene2.primitives; primitives.add(rectanglePrimitive1); primitives.add(rectanglePrimitive2); scene2.camera.setView({ destination: rectangle }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).not.toEqual(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); }); primitives.raiseToTop(rectanglePrimitive1); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).not.toEqual(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); }); }); it("renders with OIT and without FXAA", function() { const rectangle = import__599.Rectangle.fromDegrees(-100, 30, -90, 40); const rectanglePrimitive = createRectangle(rectangle, 1e3); rectanglePrimitive.appearance.material.uniforms.color = new import__599.Color( 1, 0, 0, 0.5 ); const primitives = scene2.primitives; primitives.add(rectanglePrimitive); scene2.camera.setView({ destination: rectangle }); scene2.postProcessStages.fxaa.enabled = false; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).not.toEqual(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); }); }); it("renders with forced FXAA", function() { const context = scene2.context; if (context.depthTexture) { const framebuffer2 = new import__599.Framebuffer({ context, colorTextures: [ new import__599.Texture({ context, width: 1, height: 1, pixelFormat: import__599.PixelFormat.RGBA, pixelDatatype: import__599.PixelDatatype.UNSIGNED_BYTE }) ], depthTexture: new import__599.Texture({ context, width: 1, height: 1, pixelFormat: import__599.PixelFormat.DEPTH_COMPONENT, pixelDatatype: import__599.PixelDatatype.UNSIGNED_SHORT }) }); const status = framebuffer2.status; framebuffer2.destroy(); if (status !== import__599.WebGLConstants.FRAMEBUFFER_COMPLETE) { return; } } if ((0, import__599.defined)(scene2._oit)) { scene2._oit._translucentMRTSupport = false; scene2._oit._translucentMultipassSupport = false; } scene2.postProcessStages.fxaa.enabled = false; const rectangle = import__599.Rectangle.fromDegrees(-100, 30, -90, 40); const rectanglePrimitive = createRectangle(rectangle, 1e3); rectanglePrimitive.appearance.material.uniforms.color = new import__599.Color( 1, 0, 0, 1 ); const primitives = scene2.primitives; primitives.add(rectanglePrimitive); scene2.camera.setView({ destination: rectangle }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).not.toEqual(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); }); }); it("setting a globe", function() { const ellipsoid = import__599.Ellipsoid.UNIT_SPHERE; const globe2 = new import__599.Globe(ellipsoid); scene2.globe = globe2; expect(scene2.globe).toBe(globe2); }); it("sets verticalExaggeration and verticalExaggerationRelativeHeight", function() { expect(scene2.verticalExaggeration).toEqual(1); expect(scene2.verticalExaggerationRelativeHeight).toEqual(0); scene2.verticalExaggeration = 2; scene2.verticalExaggerationRelativeHeight = 1e5; expect(scene2.verticalExaggeration).toEqual(2); expect(scene2.verticalExaggerationRelativeHeight).toEqual(1e5); }); it("destroys primitive on set globe", function() { const globe2 = new import__599.Globe(import__599.Ellipsoid.UNIT_SPHERE); scene2.globe = globe2; expect(globe2.isDestroyed()).toEqual(false); scene2.globe = void 0; expect(globe2.isDestroyed()).toEqual(true); }); describe("render tests", function() { let s; beforeEach(function() { s = createScene_default(); }); afterEach(function() { s.destroyForSpecs(); }); it("renders a globe", function() { s.globe = new import__599.Globe(import__599.Ellipsoid.UNIT_SPHERE); s.camera.position = new import__599.Cartesian3(1.02, 0, 0); s.camera.up = import__599.Cartesian3.clone(import__599.Cartesian3.UNIT_Z); s.camera.direction = import__599.Cartesian3.negate( import__599.Cartesian3.normalize(s.camera.position, new import__599.Cartesian3()), new import__599.Cartesian3() ); return expect(s).toRenderAndCall(function() { render_default(s.frameState, s.globe); const pixel = s._context.readPixels(); const blankPixel = [0, 0, 0, 0]; expect(pixel).not.toEqual(blankPixel); }); }); it("renders sky atmosphere without a globe", function() { s.globe = new import__599.Globe(import__599.Ellipsoid.UNIT_SPHERE); s.globe.show = false; s.camera.position = new import__599.Cartesian3(1.02, 0, 0); s.camera.up = import__599.Cartesian3.clone(import__599.Cartesian3.UNIT_Z); s.camera.direction = import__599.Cartesian3.negate( import__599.Cartesian3.normalize(s.camera.position, new import__599.Cartesian3()), new import__599.Cartesian3() ); return expect(s).toRenderAndCall(function() { render_default(s.frameState, s.globe); const pixel = s._context.readPixels(); const blankPixel = [0, 0, 0, 0]; expect(pixel).not.toEqual(blankPixel); }); }); it("renders a globe with an ElevationContour", function() { s.globe = new import__599.Globe(import__599.Ellipsoid.UNIT_SPHERE); s.globe.material = import__599.Material.fromType("ElevationContour"); s.camera.position = new import__599.Cartesian3(1.02, 0, 0); s.camera.up = import__599.Cartesian3.clone(import__599.Cartesian3.UNIT_Z); s.camera.direction = import__599.Cartesian3.negate( import__599.Cartesian3.normalize(s.camera.position, new import__599.Cartesian3()), new import__599.Cartesian3() ); return expect(s).toRenderAndCall(function() { render_default(s.frameState, s.globe); const pixel = s._context.readPixels(); const blankPixel = [0, 0, 0, 0]; expect(pixel).not.toEqual(blankPixel); }); }); it("renders a globe with a SlopeRamp", function() { s.globe = new import__599.Globe(import__599.Ellipsoid.UNIT_SPHERE); s.globe.material = import__599.Material.fromType("SlopeRamp"); s.camera.position = new import__599.Cartesian3(1.02, 0, 0); s.camera.up = import__599.Cartesian3.clone(import__599.Cartesian3.UNIT_Z); s.camera.direction = import__599.Cartesian3.negate( import__599.Cartesian3.normalize(s.camera.position, new import__599.Cartesian3()), new import__599.Cartesian3() ); return expect(s).toRenderAndCall(function() { render_default(s.frameState, s.globe); const pixel = s._context.readPixels(); const blankPixel = [0, 0, 0, 0]; expect(pixel).not.toEqual(blankPixel); }); }); it("renders a globe with AspectRamp", function() { s.globe = new import__599.Globe(import__599.Ellipsoid.UNIT_SPHERE); s.globe.material = import__599.Material.fromType("AspectRamp"); s.camera.position = new import__599.Cartesian3(1.02, 0, 0); s.camera.up = import__599.Cartesian3.clone(import__599.Cartesian3.UNIT_Z); s.camera.direction = import__599.Cartesian3.negate( import__599.Cartesian3.normalize(s.camera.position, new import__599.Cartesian3()), new import__599.Cartesian3() ); return expect(s).toRenderAndCall(function() { render_default(s.frameState, s.globe); const pixel = s._context.readPixels(); const blankPixel = [0, 0, 0, 0]; expect(pixel).not.toEqual(blankPixel); }); }); it("renders a globe with a ElevationRamp", function() { s.globe = new import__599.Globe(import__599.Ellipsoid.UNIT_SPHERE); s.globe.material = import__599.Material.fromType("ElevationRamp"); s.camera.position = new import__599.Cartesian3(1.02, 0, 0); s.camera.up = import__599.Cartesian3.clone(import__599.Cartesian3.UNIT_Z); s.camera.direction = import__599.Cartesian3.negate( import__599.Cartesian3.normalize(s.camera.position, new import__599.Cartesian3()), new import__599.Cartesian3() ); return expect(s).toRenderAndCall(function() { render_default(s.frameState, s.globe); const pixel = s._context.readPixels(); const blankPixel = [0, 0, 0, 0]; expect(pixel).not.toEqual(blankPixel); }); }); it("renders a globe with an ElevationBand", function() { s.globe = new import__599.Globe(import__599.Ellipsoid.UNIT_SPHERE); s.globe.material = import__599.Material.fromType("ElevationBand"); s.camera.position = new import__599.Cartesian3(1.02, 0, 0); s.camera.up = import__599.Cartesian3.clone(import__599.Cartesian3.UNIT_Z); s.camera.direction = import__599.Cartesian3.negate( import__599.Cartesian3.normalize(s.camera.position, new import__599.Cartesian3()), new import__599.Cartesian3() ); return expect(s).toRenderAndCall(function() { render_default(s.frameState, s.globe); const pixel = s._context.readPixels(); const blankPixel = [0, 0, 0, 0]; expect(pixel).not.toEqual(blankPixel); }); }); }); it("renders with multipass OIT if MRT is available", function() { if (!scene2.context.drawBuffers || !(0, import__599.defined)(scene2._oit)) { return; } scene2._oit._translucentMRTSupport = false; scene2._oit._translucentMultipassSupport = true; const rectangle = import__599.Rectangle.fromDegrees(-100, 30, -90, 40); const rectanglePrimitive = createRectangle(rectangle, 1e3); rectanglePrimitive.appearance.material.uniforms.color = new import__599.Color( 1, 0, 0, 0.5 ); const primitives = scene2.primitives; primitives.add(rectanglePrimitive); scene2.camera.setView({ destination: rectangle }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).not.toEqual(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); }); }); it("renders with alpha blending if floating point textures are available", function() { if (!scene2.context.floatingPointTexture || !(0, import__599.defined)(scene2._oit)) { return; } scene2._oit._translucentMRTSupport = false; scene2._oit._translucentMultipassSupport = false; const rectangle = import__599.Rectangle.fromDegrees(-100, 30, -90, 40); const rectanglePrimitive = createRectangle(rectangle, 1e3); rectanglePrimitive.appearance.material.uniforms.color = new import__599.Color( 1, 0, 0, 0.5 ); const primitives = scene2.primitives; primitives.add(rectanglePrimitive); scene2.camera.setView({ destination: rectangle }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).not.toEqual(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); }); }); it("renders map twice when in 2D", function() { scene2.morphTo2D(0); const rectangle = import__599.Rectangle.fromDegrees(-180, -90, 180, 90); const rectanglePrimitive1 = createRectangle(rectangle, 0); rectanglePrimitive1.appearance.material.uniforms.color = new import__599.Color( 1, 0, 0, 1 ); const primitives = scene2.primitives; primitives.add(rectanglePrimitive1); scene2.camera.setView({ destination: new import__599.Cartesian3( import__599.Ellipsoid.WGS84.maximumRadius * Math.PI + 1e4, 0, 10 ), convert: false }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).not.toEqual(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); }); }); it("renders map when the camera is on the IDL in 2D", function() { const s = createScene_default({ canvas: createCanvas_default(5, 5) }); s.morphTo2D(0); const rectangle = import__599.Rectangle.fromDegrees(-180, -90, 180, 90); const rectanglePrimitive1 = createRectangle(rectangle, 0); rectanglePrimitive1.appearance.material.uniforms.color = new import__599.Color( 1, 0, 0, 1 ); const primitives = s.primitives; primitives.add(rectanglePrimitive1); s.camera.setView({ destination: new import__599.Cartesian3( import__599.Ellipsoid.WGS84.maximumRadius * Math.PI, 0, 10 ), convert: false }); expect(s).toRenderAndCall(function(rgba) { expect(rgba[0]).not.toEqual(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); }); s.destroyForSpecs(); }); it("renders with HDR when available", function() { if (!scene2.highDynamicRangeSupported) { return; } scene2.highDynamicRange = true; const rectangle = import__599.Rectangle.fromDegrees(-100, 30, -90, 40); const rectanglePrimitive = createRectangle(rectangle, 1e3); rectanglePrimitive.appearance.material.uniforms.color = new import__599.Color( 10, 0, 0, 1 ); const primitives = scene2.primitives; primitives.add(rectanglePrimitive); scene2.camera.setView({ destination: rectangle }); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[0]).toBeLessThanOrEqual(255); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); }); }); it("copies the globe depth", function() { if (!scene2.context.depthTexture) { return; } const rectangle = import__599.Rectangle.fromDegrees(-100, 30, -90, 40); const rectanglePrimitive = createRectangle(rectangle, 1e3); rectanglePrimitive.appearance.material.uniforms.color = new import__599.Color( 1, 0, 0, 0.5 ); const primitives = scene2.primitives; primitives.add(rectanglePrimitive); scene2.camera.setView({ destination: rectangle }); const uniformState = scene2.context.uniformState; expect(scene2).toRenderAndCall(function(rgba) { expect(uniformState.globeDepthTexture).toBeDefined(); }); }); it("pickPosition", function() { if (!scene2.pickPositionSupported) { return; } const rectangle = import__599.Rectangle.fromDegrees(-1e-4, -1e-4, 1e-4, 1e-4); scene2.camera.setView({ destination: rectangle }); const canvas = scene2.canvas; const windowPosition = new import__599.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); expect(scene2).toRenderAndCall(function() { const position = scene2.pickPosition(windowPosition); expect(position).not.toBeDefined(); const rectanglePrimitive = createRectangle(rectangle); rectanglePrimitive.appearance.material.uniforms.color = new import__599.Color( 1, 0, 0, 1 ); const primitives = scene2.primitives; primitives.add(rectanglePrimitive); }); expect(scene2).toRenderAndCall(function() { const position = scene2.pickPosition(windowPosition); expect(position.x).toBeGreaterThan(import__599.Ellipsoid.WGS84.minimumRadius); expect(position.y).toEqualEpsilon(0, import__600.Math.EPSILON5); expect(position.z).toEqualEpsilon(0, import__600.Math.EPSILON5); }); }); it("pickPosition in CV", function() { if (!scene2.pickPositionSupported) { return; } scene2.morphToColumbusView(0); const rectangle = import__599.Rectangle.fromDegrees(-1e-4, -1e-4, 1e-4, 1e-4); scene2.camera.setView({ destination: rectangle }); const canvas = scene2.canvas; const windowPosition = new import__599.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); expect(scene2).toRenderAndCall(function() { const position = scene2.pickPosition(windowPosition); expect(position).not.toBeDefined(); const rectanglePrimitive = createRectangle(rectangle); rectanglePrimitive.appearance.material.uniforms.color = new import__599.Color( 1, 0, 0, 1 ); const primitives = scene2.primitives; primitives.add(rectanglePrimitive); }); expect(scene2).toRenderAndCall(function() { const position = scene2.pickPosition(windowPosition); expect(position.x).toBeGreaterThan(import__599.Ellipsoid.WGS84.minimumRadius); expect(position.y).toEqualEpsilon(0, import__600.Math.EPSILON5); expect(position.z).toEqualEpsilon(0, import__600.Math.EPSILON5); }); }); it("pickPosition in 2D", function() { if (!scene2.pickPositionSupported) { return; } scene2.morphTo2D(0); const rectangle = import__599.Rectangle.fromDegrees(-1e-4, -1e-4, 1e-4, 1e-4); scene2.camera.setView({ destination: rectangle }); const canvas = scene2.canvas; const windowPosition = new import__599.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); expect(scene2).toRenderAndCall(function() { const position = scene2.pickPosition(windowPosition); expect(position).not.toBeDefined(); const rectanglePrimitive = createRectangle(rectangle); rectanglePrimitive.appearance.material.uniforms.color = new import__599.Color( 1, 0, 0, 1 ); const primitives = scene2.primitives; primitives.add(rectanglePrimitive); }); expect(scene2).toRenderAndCall(function() { const position = scene2.pickPosition(windowPosition); expect(position.x).toBeGreaterThan(import__599.Ellipsoid.WGS84.minimumRadius); expect(position.y).toEqualEpsilon(0, import__600.Math.EPSILON5); expect(position.z).toEqualEpsilon(0, import__600.Math.EPSILON5); }); }); it("pickPosition returns undefined when useDepthPicking is false", function() { if (!scene2.pickPositionSupported) { return; } const rectangle = import__599.Rectangle.fromDegrees(-100, 30, -90, 40); scene2.camera.setView({ destination: rectangle }); const canvas = scene2.canvas; const windowPosition = new import__599.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const rectanglePrimitive = createRectangle(rectangle); rectanglePrimitive.appearance.material.uniforms.color = new import__599.Color( 1, 0, 0, 1 ); const primitives = scene2.primitives; primitives.add(rectanglePrimitive); scene2.useDepthPicking = false; expect(scene2).toRenderAndCall(function() { const position = scene2.pickPosition(windowPosition); expect(position).not.toBeDefined(); }); scene2.useDepthPicking = true; expect(scene2).toRenderAndCall(function() { const position = scene2.pickPosition(windowPosition); expect(position).toBeDefined(); }); }); it("pickPosition picks translucent geometry when pickTranslucentDepth is true", function() { if (!scene2.pickPositionSupported) { return; } const rectangle = import__599.Rectangle.fromDegrees(-100, 30, -90, 40); scene2.camera.setView({ destination: rectangle }); const canvas = scene2.canvas; const windowPosition = new import__599.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const rectanglePrimitive = scene2.primitives.add( createRectangle(rectangle) ); rectanglePrimitive.appearance.material.uniforms.color = new import__599.Color( 1, 0, 0, 0.5 ); scene2.useDepthPicking = true; scene2.pickTranslucentDepth = false; expect(scene2).toRenderAndCall(function() { const position = scene2.pickPosition(windowPosition); expect(position).not.toBeDefined(); }); scene2.pickTranslucentDepth = true; expect(scene2).toRenderAndCall(function() { const position = scene2.pickPosition(windowPosition); expect(position).toBeDefined(); }); }); it("pickPosition caches results per frame", function() { if (!scene2.pickPositionSupported) { return; } const rectangle = import__599.Rectangle.fromDegrees(-100, 30, -90, 40); scene2.camera.setView({ destination: rectangle }); const canvas = scene2.canvas; const windowPosition = new import__599.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); spyOn( import__599.SceneTransforms, "transformWindowToDrawingBuffer" ).and.callThrough(); expect(scene2).toRenderAndCall(function() { scene2.pickPosition(windowPosition); expect( import__599.SceneTransforms.transformWindowToDrawingBuffer ).toHaveBeenCalled(); scene2.pickPosition(windowPosition); expect( import__599.SceneTransforms.transformWindowToDrawingBuffer.calls.count() ).toEqual(1); const rectanglePrimitive = createRectangle(rectangle); rectanglePrimitive.appearance.material.uniforms.color = new import__599.Color( 1, 0, 0, 1 ); const primitives = scene2.primitives; primitives.add(rectanglePrimitive); }); expect(scene2).toRenderAndCall(function() { scene2.pickPosition(windowPosition); expect( import__599.SceneTransforms.transformWindowToDrawingBuffer.calls.count() ).toEqual(2); scene2.pickPosition(windowPosition); expect( import__599.SceneTransforms.transformWindowToDrawingBuffer.calls.count() ).toEqual(2); }); }); it("pickPosition throws without windowPosition", function() { expect(function() { scene2.pickPosition(); }).toThrowDeveloperError(); }); it("isDestroyed", function() { const s = createScene_default(); expect(s.isDestroyed()).toEqual(false); s.destroyForSpecs(); expect(s.isDestroyed()).toEqual(true); }); it("raises renderError when render throws", function() { const s = createScene_default({ rethrowRenderErrors: false }); const spyListener = jasmine.createSpy("listener"); s.renderError.addEventListener(spyListener); const error = "foo"; s.primitives.update = function() { throw error; }; s.render(); expect(spyListener).toHaveBeenCalledWith(s, error); s.destroyForSpecs(); }); it("a render error is rethrown if rethrowRenderErrors is true", function() { scene2.rethrowRenderErrors = true; const spyListener = jasmine.createSpy("listener"); scene2.renderError.addEventListener(spyListener); const error = new import__599.RuntimeError("error"); scene2.primitives.update = function() { throw error; }; expect(function() { scene2.render(); }).toThrowError(import__599.RuntimeError); expect(spyListener).toHaveBeenCalledWith(scene2, error); }); it("always raises preUpdate event prior to updating", function() { const spyListener = jasmine.createSpy("listener"); scene2.preUpdate.addEventListener(spyListener); scene2.render(); expect(spyListener.calls.count()).toBe(1); scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; scene2.render(); expect(spyListener.calls.count()).toBe(2); }); it("always raises postUpdate event after updating", function() { const spyListener = jasmine.createSpy("listener"); scene2.postUpdate.addEventListener(spyListener); scene2.render(); expect(spyListener.calls.count()).toBe(1); scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; scene2.render(); expect(spyListener.calls.count()).toBe(2); }); it("raises the preRender event prior to rendering only if the scene renders", function() { const spyListener = jasmine.createSpy("listener"); scene2.preRender.addEventListener(spyListener); scene2.render(); expect(spyListener.calls.count()).toBe(1); scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; scene2.render(); expect(spyListener.calls.count()).toBe(1); }); it("raises the postRender event after rendering if the scene rendered", function() { const spyListener = jasmine.createSpy("listener"); scene2.postRender.addEventListener(spyListener); scene2.render(); expect(spyListener.calls.count()).toBe(1); scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; scene2.render(); expect(spyListener.calls.count()).toBe(1); }); it("raises the cameraMoveStart event after moving the camera", function() { scene2.render(); const spyListener = jasmine.createSpy("listener"); scene2.camera.moveStart.addEventListener(spyListener); scene2._cameraStartFired = false; scene2.camera.moveLeft(); scene2.render(); expect(spyListener.calls.count()).toBe(1); }); it("raises the cameraMoveEvent event when the camera stops moving", function() { scene2.render(); const spyListener = jasmine.createSpy("listener"); scene2.camera.moveEnd.addEventListener(spyListener); scene2.cameraEventWaitTime = -1; scene2.camera.moveLeft(); scene2.render(); scene2.render(); expect(spyListener.calls.count()).toBe(1); }); it("raises the camera changed event on direction changed", function() { const spyListener = jasmine.createSpy("listener"); scene2.camera.changed.addEventListener(spyListener); scene2.initializeFrame(); scene2.render(); scene2.camera.lookLeft( scene2.camera.frustum.fov * (scene2.camera.percentageChanged + 0.1) ); scene2.initializeFrame(); scene2.render(); expect(spyListener.calls.count()).toBe(1); const args = spyListener.calls.allArgs(); expect(args.length).toEqual(1); expect(args[0].length).toEqual(1); expect(args[0][0]).toBeGreaterThan(scene2.camera.percentageChanged); }); it("raises the camera changed event on heading changed when looking up", function() { const spyListener = jasmine.createSpy("listener"); scene2.camera.lookUp(0.785398); scene2.camera.changed.addEventListener(spyListener); scene2.initializeFrame(); scene2.render(); scene2.camera.twistLeft( import__600.Math.PI * (scene2.camera.percentageChanged + 0.1) ); scene2.initializeFrame(); scene2.render(); expect(spyListener.calls.count()).toBe(1); const args = spyListener.calls.allArgs(); expect(args.length).toEqual(1); expect(args[0].length).toEqual(1); expect(args[0][0]).toBeGreaterThan(scene2.camera.percentageChanged); }); it("raises the camera changed event on roll changed", function() { const spyListener = jasmine.createSpy("listener"); scene2.camera.changed.addEventListener(spyListener); scene2.initializeFrame(); scene2.render(); scene2.camera.twistLeft( import__600.Math.PI * (scene2.camera.percentageChanged + 0.1) ); scene2.initializeFrame(); scene2.render(); expect(spyListener.calls.count()).toBe(1); const args = spyListener.calls.allArgs(); expect(args.length).toEqual(1); expect(args[0].length).toEqual(1); expect(args[0][0]).toBeGreaterThan(scene2.camera.percentageChanged); }); it("raises the camera changed event on position changed", function() { const spyListener = jasmine.createSpy("listener"); scene2.camera.changed.addEventListener(spyListener); scene2.initializeFrame(); scene2.render(); scene2.camera.moveUp( scene2.camera.positionCartographic.height * (scene2.camera.percentageChanged + 0.1) ); scene2.initializeFrame(); scene2.render(); expect(spyListener.calls.count()).toBe(1); const args = spyListener.calls.allArgs(); expect(args.length).toEqual(1); expect(args[0].length).toEqual(1); expect(args[0][0]).toBeGreaterThan(scene2.camera.percentageChanged); }); it("raises the camera changed event in 2D", function() { scene2.morphTo2D(0); const spyListener = jasmine.createSpy("listener"); scene2.camera.changed.addEventListener(spyListener); scene2.initializeFrame(); scene2.render(); scene2.camera.moveLeft( scene2.camera.positionCartographic.height * (scene2.camera.percentageChanged + 0.1) ); scene2.initializeFrame(); scene2.render(); expect(spyListener.calls.count()).toBe(1); const args = spyListener.calls.allArgs(); expect(args.length).toEqual(1); expect(args[0].length).toEqual(1); expect(args[0][0]).toBeGreaterThan(scene2.camera.percentageChanged); }); it("get maximumAliasedLineWidth", function() { expect(scene2.maximumAliasedLineWidth).toBeGreaterThanOrEqual(1); }); it("get maximumCubeMapSize", function() { expect(scene2.maximumCubeMapSize).toBeGreaterThanOrEqual(16); }); it("does not throw with debugShowCommands", function() { if (!scene2.context.drawBuffers) { return; } scene2.debugShowCommands = true; const rectangle = import__599.Rectangle.fromDegrees(-100, 30, -90, 40); const rectanglePrimitive = createRectangle(rectangle, 1e3); rectanglePrimitive.appearance.material.uniforms.color = new import__599.Color( 1, 0, 0, 0.5 ); const primitives = scene2.primitives; primitives.add(rectanglePrimitive); scene2.camera.setView({ destination: rectangle }); expect(function() { scene2.renderForSpecs(); }).not.toThrowError(import__599.RuntimeError); }); it("does not throw with debugShowFrustums", function() { if (!scene2.context.drawBuffers) { return; } scene2.debugShowFrustums = true; const rectangle = import__599.Rectangle.fromDegrees(-100, 30, -90, 40); const rectanglePrimitive = createRectangle(rectangle, 1e3); rectanglePrimitive.appearance.material.uniforms.color = new import__599.Color( 1, 0, 0, 0.5 ); const primitives = scene2.primitives; primitives.add(rectanglePrimitive); scene2.camera.setView({ destination: rectangle }); expect(function() { scene2.renderForSpecs(); }).not.toThrowError(import__599.RuntimeError); }); it("throws when minimumDisableDepthTestDistance is set less than 0.0", function() { expect(function() { scene2.minimumDisableDepthTestDistance = -1; }).toThrowDeveloperError(); }); it("converts to canvas coordinates", function() { const mockPosition = new import__599.Cartesian3(); spyOn(import__599.SceneTransforms, "wgs84ToWindowCoordinates"); scene2.cartesianToCanvasCoordinates(mockPosition); expect(import__599.SceneTransforms.wgs84ToWindowCoordinates).toHaveBeenCalledWith( scene2, mockPosition, void 0 ); }); it("converts to canvas coordinates and return it in a variable", function() { const result = new import__599.Cartesian2(); const mockPosition = new import__599.Cartesian3(); spyOn(import__599.SceneTransforms, "wgs84ToWindowCoordinates"); scene2.cartesianToCanvasCoordinates(mockPosition, result); expect(import__599.SceneTransforms.wgs84ToWindowCoordinates).toHaveBeenCalledWith( scene2, mockPosition, result ); }); it("Gets imageryLayers", function() { const globe2 = scene2.globe = new import__599.Globe(import__599.Ellipsoid.UNIT_SPHERE); expect(scene2.imageryLayers).toBe(globe2.imageryLayers); scene2.globe = void 0; expect(scene2.imageryLayers).toBeUndefined(); }); it("Gets terrainProvider", function() { const globe2 = scene2.globe = new import__599.Globe(import__599.Ellipsoid.UNIT_SPHERE); expect(scene2.terrainProvider).toBe(globe2.terrainProvider); scene2.globe = void 0; expect(scene2.terrainProvider).toBeUndefined(); }); it("Sets terrainProvider", async function() { returnQuantizedMeshTileJson(); const globe2 = scene2.globe = new import__599.Globe(import__599.Ellipsoid.UNIT_SPHERE); scene2.terrainProvider = await import__599.CesiumTerrainProvider.fromUrl( "//terrain/tiles" ); expect(scene2.terrainProvider).toBe(globe2.terrainProvider); scene2.globe = void 0; const newProvider = await import__599.CesiumTerrainProvider.fromUrl( "//newTerrain/tiles" ); expect(function() { scene2.terrainProvider = newProvider; }).not.toThrow(); import__599.Resource._Implementations.loadWithXhr = import__599.Resource._DefaultImplementations.loadWithXhr; }); it("setTerrain updates terrain provider", async function() { returnQuantizedMeshTileJson(); const globe2 = scene2.globe = new import__599.Globe(import__599.Ellipsoid.UNIT_SPHERE); const promise = import__599.CesiumTerrainProvider.fromUrl("//terrain/tiles"); scene2.setTerrain(new import__599.Terrain(promise)); const originalProvider = scene2.terrainProvider; let terrainWasChanged = false; scene2.terrainProviderChanged.addEventListener((terrainProvider) => { expect(terrainProvider).not.toBe(originalProvider); expect(scene2.terrainProvider).toBe(terrainProvider); expect(scene2.terrainProvider).toBe(globe2.terrainProvider); terrainWasChanged = true; }); await promise; expect(terrainWasChanged).toBeTrue(); import__599.Resource._Implementations.loadWithXhr = import__599.Resource._DefaultImplementations.loadWithXhr; }); it("setTerrain handles destroy", async function() { const scene3 = createScene_default(); returnQuantizedMeshTileJson(); scene3.globe = new import__599.Globe(import__599.Ellipsoid.UNIT_SPHERE); const promise = import__599.CesiumTerrainProvider.fromUrl("//newTerrain/tiles"); scene3.setTerrain(new import__599.Terrain(promise)); scene3.destroyForSpecs(); await expectAsync(promise).toBeResolved(); expect(scene3.isDestroyed()).toBeTrue(); import__599.Resource._Implementations.loadWithXhr = import__599.Resource._DefaultImplementations.loadWithXhr; }); it("Gets terrainProviderChanged", function() { const globe2 = scene2.globe = new import__599.Globe(import__599.Ellipsoid.UNIT_SPHERE); expect(scene2.terrainProviderChanged).toBe(globe2.terrainProviderChanged); scene2.globe = void 0; expect(scene2.terrainProviderChanged).toBeUndefined(); }); it("Sets material", function() { const globe2 = scene2.globe = new import__599.Globe(import__599.Ellipsoid.UNIT_SPHERE); const material = import__599.Material.fromType("ElevationContour"); globe2.material = material; expect(globe2.material).toBe(material); globe2.material = void 0; expect(globe2.material).toBeUndefined(); }); const scratchTime = new import__599.JulianDate(); it("doesn't render scene if requestRenderMode is enabled", function() { scene2.renderForSpecs(); const lastFrameNumber = scene2.frameState.frameNumber; scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; scene2.renderForSpecs(); expect(scene2.frameState.frameNumber).toEqual(lastFrameNumber); }); it("requestRender causes a new frame to be rendered in requestRenderMode", function() { scene2.renderForSpecs(); const lastFrameNumber = scene2.frameState.frameNumber; expect(scene2._renderRequested).toBe(false); scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; scene2.requestRender(); expect(scene2._renderRequested).toBe(true); scene2.renderForSpecs(); expect(scene2.frameState.frameNumber).not.toEqual(lastFrameNumber); }); it("moving the camera causes a new frame to be rendered in requestRenderMode", function() { scene2.renderForSpecs(); const lastFrameNumber = scene2.frameState.frameNumber; expect(scene2._renderRequested).toBe(false); scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; scene2.camera.moveLeft(); scene2.renderForSpecs(); expect(scene2.frameState.frameNumber).not.toEqual(lastFrameNumber); }); it("changing the camera frustum does not cause continuous rendering in requestRenderMode", function() { scene2.renderForSpecs(); let lastFrameNumber = scene2.frameState.frameNumber; expect(scene2._renderRequested).toBe(false); scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; scene2.camera.frustum.near *= 1.1; scene2.renderForSpecs(); expect(scene2.frameState.frameNumber).not.toEqual(lastFrameNumber); lastFrameNumber = scene2.frameState.frameNumber; scene2.renderForSpecs(); expect(scene2.frameState.frameNumber).toEqual(lastFrameNumber); }); it("successful completed requests causes a new frame to be rendered in requestRenderMode", function() { scene2.renderForSpecs(); const lastFrameNumber = scene2.frameState.frameNumber; expect(scene2._renderRequested).toBe(false); scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; import__599.RequestScheduler.requestCompletedEvent.raiseEvent(); scene2.renderForSpecs(); expect(scene2._renderRequested).toBe(true); scene2.renderForSpecs(); expect(scene2.frameState.frameNumber).not.toEqual(lastFrameNumber); }); it("data returning from a web worker causes a new frame to be rendered in requestRenderMode", function() { scene2.renderForSpecs(); const lastFrameNumber = scene2.frameState.frameNumber; expect(scene2._renderRequested).toBe(false); scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; import__599.TaskProcessor.taskCompletedEvent.raiseEvent(); scene2.renderForSpecs(); expect(scene2._renderRequested).toBe(true); scene2.renderForSpecs(); expect(scene2.frameState.frameNumber).not.toEqual(lastFrameNumber); }); it("Executing an after render function causes a new frame to be rendered in requestRenderMode", function() { scene2.renderForSpecs(); const lastFrameNumber = scene2.frameState.frameNumber; expect(scene2._renderRequested).toBe(false); scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; let functionCalled = false; scene2._frameState.afterRender.push(function() { functionCalled = true; return true; }); scene2.renderForSpecs(); expect(functionCalled).toBe(true); expect(scene2._renderRequested).toBe(true); scene2.renderForSpecs(); expect(scene2.frameState.frameNumber).not.toEqual(lastFrameNumber); }); it("Globe tile loading triggers a new frame to be rendered in requestRenderMode", function() { scene2.renderForSpecs(); let lastFrameNumber = scene2.frameState.frameNumber; expect(scene2._renderRequested).toBe(false); scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; const ellipsoid = import__599.Ellipsoid.UNIT_SPHERE; const globe2 = new import__599.Globe(ellipsoid); scene2.globe = globe2; scene2.requestRender(); Object.defineProperty(globe2, "tilesLoaded", { value: false }); scene2.renderForSpecs(); lastFrameNumber = scene2.frameState.frameNumber; expect(scene2._renderRequested).toBe(true); scene2.renderForSpecs(); expect(scene2.frameState.frameNumber).not.toEqual(lastFrameNumber); }); it("Globe imagery updates triggers a new frame to be rendered in requestRenderMode", function() { scene2.renderForSpecs(); const lastFrameNumber = scene2.frameState.frameNumber; expect(scene2._renderRequested).toBe(false); scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; const ellipsoid = import__599.Ellipsoid.UNIT_SPHERE; const globe2 = new import__599.Globe(ellipsoid); scene2.globe = globe2; globe2.imageryLayersUpdatedEvent.raiseEvent(); scene2.renderForSpecs(); expect(scene2._renderRequested).toBe(true); scene2.renderForSpecs(); expect(scene2.frameState.frameNumber).not.toEqual(lastFrameNumber); }); it("Globe changing terrain providers triggers a new frame to be rendered in requestRenderMode", function() { scene2.renderForSpecs(); const lastFrameNumber = scene2.frameState.frameNumber; expect(scene2._renderRequested).toBe(false); scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; const ellipsoid = import__599.Ellipsoid.UNIT_SPHERE; const globe2 = new import__599.Globe(ellipsoid); scene2.globe = globe2; globe2.terrainProviderChanged.raiseEvent(); scene2.renderForSpecs(); expect(scene2._renderRequested).toBe(true); scene2.renderForSpecs(); expect(scene2.frameState.frameNumber).not.toEqual(lastFrameNumber); }); it("scene morphing causes a new frame to be rendered in requestRenderMode", function() { scene2.renderForSpecs(); let lastFrameNumber = scene2.frameState.frameNumber; let lastRenderTime = import__599.JulianDate.clone(scene2.lastRenderTime, scratchTime); expect(lastRenderTime).toBeDefined(); expect(scene2._renderRequested).toBe(false); scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; scene2.morphTo2D(1); scene2.renderForSpecs( import__599.JulianDate.addSeconds(lastRenderTime, 0.5, new import__599.JulianDate()) ); expect(scene2.frameState.frameNumber).not.toEqual(lastFrameNumber); scene2.completeMorph(); scene2.renderForSpecs(); lastFrameNumber = scene2.frameState.frameNumber; scene2.renderForSpecs(); expect(scene2.frameState.frameNumber).toEqual(lastFrameNumber); lastFrameNumber = scene2.frameState.frameNumber; lastRenderTime = import__599.JulianDate.clone(scene2.lastRenderTime, scratchTime); scene2.morphToColumbusView(1); scene2.renderForSpecs( import__599.JulianDate.addSeconds(lastRenderTime, 0.5, new import__599.JulianDate()) ); expect(scene2.frameState.frameNumber).not.toEqual(lastFrameNumber); scene2.completeMorph(); scene2.renderForSpecs(); lastFrameNumber = scene2.frameState.frameNumber; scene2.renderForSpecs(); expect(scene2.frameState.frameNumber).toEqual(lastFrameNumber); lastFrameNumber = scene2.frameState.frameNumber; lastRenderTime = import__599.JulianDate.clone(scene2.lastRenderTime, scratchTime); scene2.morphTo3D(1); scene2.renderForSpecs( import__599.JulianDate.addSeconds(lastRenderTime, 0.5, new import__599.JulianDate()) ); expect(scene2.frameState.frameNumber).not.toEqual(lastFrameNumber); scene2.completeMorph(); scene2.renderForSpecs(); lastFrameNumber = scene2.frameState.frameNumber; scene2.renderForSpecs(); expect(scene2.frameState.frameNumber).toEqual(lastFrameNumber); }); it("time change exceeding maximumRenderTimeChange causes a new frame to be rendered in requestRenderMode", function() { scene2.renderForSpecs(); const lastFrameNumber = scene2.frameState.frameNumber; const lastRenderTime = import__599.JulianDate.clone( scene2.lastRenderTime, scratchTime ); expect(lastRenderTime).toBeDefined(); expect(scene2._renderRequested).toBe(false); scene2.requestRenderMode = true; scene2.renderForSpecs(lastRenderTime); expect(scene2.frameState.frameNumber).toEqual(lastFrameNumber); scene2.maximumRenderTimeChange = 100; scene2.renderForSpecs( import__599.JulianDate.addSeconds(lastRenderTime, 50, new import__599.JulianDate()) ); expect(scene2.frameState.frameNumber).toEqual(lastFrameNumber); scene2.renderForSpecs( import__599.JulianDate.addSeconds(lastRenderTime, 150, new import__599.JulianDate()) ); expect(scene2.frameState.frameNumber).not.toEqual(lastFrameNumber); }); it("undefined maximumRenderTimeChange will not cause a new frame to be rendered in requestRenderMode", function() { scene2.renderForSpecs(); const lastFrameNumber = scene2.frameState.frameNumber; const lastRenderTime = import__599.JulianDate.clone( scene2.lastRenderTime, scratchTime ); expect(lastRenderTime).toBeDefined(); expect(scene2._renderRequested).toBe(false); scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; const farFuture = import__599.JulianDate.addDays( lastRenderTime, 1e4, new import__599.JulianDate() ); scene2.renderForSpecs(); scene2.renderForSpecs(farFuture); expect(scene2.frameState.frameNumber).toEqual(lastFrameNumber); }); it("forceRender renders a scene regardless of whether a render was requested", function() { scene2.renderForSpecs(); const lastFrameNumber = scene2.frameState.frameNumber; expect(scene2._renderRequested).toBe(false); scene2.requestRenderMode = true; scene2.maximumRenderTimeChange = void 0; scene2.forceRender(); expect(scene2.frameState.frameNumber).not.toEqual(lastFrameNumber); }); function getFrustumCommandsLength(scene3, pass) { let commandsLength = 0; const frustumCommandsList = scene3.frustumCommandsList; const frustumsLength = frustumCommandsList.length; for (let i = 0; i < frustumsLength; ++i) { const frustumCommands = frustumCommandsList[i]; for (let j = 0; j < import__599.Pass.NUMBER_OF_PASSES; ++j) { if (!(0, import__599.defined)(pass) || j === pass) { commandsLength += frustumCommands.indices[j]; } } } return commandsLength; } it("occludes primitive", function() { scene2.globe = new import__599.Globe(import__599.Ellipsoid.WGS84); const rectangle = import__599.Rectangle.fromDegrees(-100, 30, -90, 40); const rectanglePrimitive = createRectangle(rectangle, 10); scene2.primitives.add(rectanglePrimitive); scene2.camera.setView({ destination: new import__599.Cartesian3( -588536.1057451078, -10512475371849751e-9, 6737159100747835e-9 ), orientation: new import__599.HeadingPitchRoll( 6.283185307179586, -1.5688261558859757, 0 ) }); scene2.renderForSpecs(); expect(getFrustumCommandsLength(scene2)).toBe(1); scene2.camera.setView({ destination: new import__599.Cartesian3( -5754647167415793e-9, 14907694100240812e-9, -483807.2406259497 ), orientation: new import__599.HeadingPitchRoll( 6.283185307179586, -1.5698869547885104, 0 ) }); scene2.renderForSpecs(); expect(getFrustumCommandsLength(scene2)).toBe(0); scene2.globe.show = false; scene2.renderForSpecs(); expect(getFrustumCommandsLength(scene2)).toBe(1); }); it("does not occlude if DrawCommand.occlude is false", function() { scene2.globe = new import__599.Globe(import__599.Ellipsoid.WGS84); const rectangle = import__599.Rectangle.fromDegrees(-100, 30, -90, 40); const rectanglePrimitive = createRectangle(rectangle, 10); scene2.primitives.add(rectanglePrimitive); scene2.renderForSpecs(); rectanglePrimitive._colorCommands[0].occlude = false; scene2.camera.setView({ destination: new import__599.Cartesian3( -5754647167415793e-9, 14907694100240812e-9, -483807.2406259497 ), orientation: new import__599.HeadingPitchRoll( 6.283185307179586, -1.5698869547885104, 0 ) }); scene2.renderForSpecs(); expect(getFrustumCommandsLength(scene2)).toBe(1); }); it("sets light", function() { const uniformState = scene2.context.uniformState; const lightDirectionWC = uniformState._lightDirectionWC; const sunDirectionWC = uniformState._sunDirectionWC; const lightColor = uniformState._lightColor; const lightColorHdr = uniformState._lightColorHdr; scene2.renderForSpecs(); expect(lightDirectionWC).toEqual(sunDirectionWC); expect(lightColor).toEqual(new import__599.Cartesian3(1, 1, 1)); expect(lightColorHdr).toEqual(new import__599.Cartesian3(2, 2, 2)); scene2.light = new import__599.DirectionalLight({ direction: new import__599.Cartesian3(1, 0, 0), color: import__599.Color.RED, intensity: 2 }); scene2.renderForSpecs(); expect(lightDirectionWC).toEqual(new import__599.Cartesian3(-1, 0, 0)); expect(lightColor).toEqual(new import__599.Cartesian3(1, 0, 0)); expect(lightColorHdr).toEqual(new import__599.Cartesian3(2, 0, 0)); scene2.light = new import__599.SunLight({ color: import__599.Color.BLUE, intensity: 0.5 }); scene2.renderForSpecs(); expect(lightDirectionWC).toEqual(sunDirectionWC); expect(lightColor).toEqual(new import__599.Cartesian3(0, 0, 0.5)); expect(lightColorHdr).toEqual(new import__599.Cartesian3(0, 0, 0.5)); scene2.light = void 0; scene2.renderForSpecs(); expect(lightDirectionWC).toEqual(sunDirectionWC); expect(lightColor).toEqual(new import__599.Cartesian3(1, 1, 1)); expect(lightColorHdr).toEqual(new import__599.Cartesian3(2, 2, 2)); }); function updateGlobeUntilDone(scene3) { return pollToPromise_default(function() { scene3.renderForSpecs(); return scene3.globe.tilesLoaded; }); } it("detects when camera is underground", async function() { const globe2 = new import__599.Globe(); scene2.globe = globe2; scene2.camera.setView({ destination: new import__599.Rectangle(1e-4, 1e-4, 3e-3, 3e-3) }); await updateGlobeUntilDone(scene2); expect(scene2.cameraUnderground).toBe(false); scene2.camera.setView({ destination: new import__599.Cartesian3( -746658.0557573901, -5.6441910002196245e6, 2863585099969967e-9 ), orientation: new import__599.HeadingPitchRoll( 0.3019699121236403, 0.07316306869231592, 7089903642230055e-19 ) }); await updateGlobeUntilDone(scene2); expect(scene2.cameraUnderground).toBe(true); }); it("detects that camera is above ground if globe is undefined", function() { scene2.renderForSpecs(); expect(scene2.cameraUnderground).toBe(false); }); it("detects that camera is above ground if scene mode is 2D", function() { const globe2 = new import__599.Globe(); scene2.globe = globe2; scene2.morphTo2D(0); expect(scene2.cameraUnderground).toBe(false); }); it("detects that camera is above ground if scene mode is morphing", function() { const globe2 = new import__599.Globe(); scene2.globe = globe2; scene2.morphTo2D(1); expect(scene2.cameraUnderground).toBe(false); }); it("detects that camera is underground in Columbus View", async function() { const globe2 = new import__599.Globe(); scene2.globe = globe2; scene2.camera.setView({ destination: new import__599.Cartesian3( -4643042379120885e-9, 4314056579506199e-9, -451828.8968118975 ), orientation: new import__599.HeadingPitchRoll( 6.283185307179586, -0.7855491933100796, 6.283185307179586 ) }); scene2.morphToColumbusView(0); await updateGlobeUntilDone(scene2); scene2.renderForSpecs(); expect(scene2.cameraUnderground).toBe(true); }); it("does not occlude primitives when camera is underground", async function() { const globe2 = new import__599.Globe(); scene2.globe = globe2; const center = import__599.Cartesian3.fromRadians( 2.3929070618374535, -0.07149851443375346, -25e3, globe2.ellipsoid ); const radius = 10; const command = new import__599.DrawCommand({ shaderProgram: getSimpleShaderProgram(), renderState: new import__599.RenderState(), pass: import__599.Pass.OPAQUE, boundingVolume: new import__599.BoundingSphere(center, radius) }); scene2.primitives.add(new CommandMockPrimitive(command)); spyOn(import__599.DrawCommand.prototype, "execute"); await updateGlobeUntilDone(scene2); expect(getFrustumCommandsLength(scene2, import__599.Pass.OPAQUE)).toBe(0); scene2.camera.setView({ destination: new import__599.Cartesian3( -4643042379120885e-9, 4314056579506199e-9, -451828.8968118975 ), orientation: new import__599.HeadingPitchRoll( 6.283185307179586, -0.7855491933100796, 6.283185307179586 ) }); await updateGlobeUntilDone(scene2); scene2.renderForSpecs(); expect(getFrustumCommandsLength(scene2, import__599.Pass.OPAQUE)).toBe(1); }); it("does not occlude primitives when the globe is translucent", function() { const globe2 = new import__599.Globe(); scene2.globe = globe2; const center = import__599.Cartesian3.fromRadians( 2.3929070618374535, -0.07149851443375346, -25e3, globe2.ellipsoid ); const radius = 10; const command = new import__599.DrawCommand({ shaderProgram: getSimpleShaderProgram(), renderState: new import__599.RenderState(), pass: import__599.Pass.OPAQUE, boundingVolume: new import__599.BoundingSphere(center, radius) }); scene2.primitives.add(new CommandMockPrimitive(command)); spyOn(import__599.DrawCommand.prototype, "execute"); scene2.renderForSpecs(); expect(getFrustumCommandsLength(scene2, import__599.Pass.OPAQUE)).toBe(0); scene2.globe.translucency.enabled = true; scene2.globe.translucency.frontFaceAlpha = 0.5; scene2.renderForSpecs(); expect(getFrustumCommandsLength(scene2, import__599.Pass.OPAQUE)).toBe(1); }); it("does not render environment when camera is underground and translucency is disabled", async function() { const globe2 = new import__599.Globe(); scene2.globe = globe2; scene2.sun = new import__599.Sun(); scene2.camera.setView({ destination: new import__599.Cartesian3( 2.8384779315700866e6, -4939120816857662e-9, 1.9780944576285738e6 ), orientation: new import__599.HeadingPitchRoll( 5.955798516387474, -1.0556025616093283, 0.39098563693868016 ) }); await updateGlobeUntilDone(scene2); const time2 = import__599.JulianDate.fromIso8601( "2020-04-25T03:07:26.04924034334544558Z" ); globe2.translucency.enabled = true; globe2.translucency.frontFaceAlpha = 0.5; scene2.renderForSpecs(time2); expect(scene2.environmentState.isSunVisible).toBe(true); globe2.translucency.enabled = false; scene2.renderForSpecs(time2); expect(scene2.environmentState.isSunVisible).toBe(false); }); it("renders globe with translucency", async function() { const globe2 = new import__599.Globe(); scene2.globe = globe2; scene2.camera.setView({ destination: new import__599.Cartesian3( 2.7646813022502237e6, -20999839371941473e-9, 14894754464869803e-9 ), orientation: new import__599.HeadingPitchRoll( 6.283185307179586, -1.5687983447998315, 0 ) }); await updateGlobeUntilDone(scene2); let opaqueColor; expect(scene2).toRenderAndCall(function(rgba) { opaqueColor = rgba; }); globe2.translucency.enabled = true; globe2.translucency.frontFaceAlpha = 0.5; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual(opaqueColor); }); }); it("renders ground primitive on translucent globe", async function() { const globe2 = new import__599.Globe(); scene2.globe = globe2; globe2.baseColor = import__599.Color.BLACK; globe2.translucency.enabled = true; globe2.translucency.frontFaceAlpha = 0.5; scene2.camera.setView({ destination: new import__599.Cartesian3( -557278.4840232887, -6744284200717078e-9, 2794079461722868e-9 ), orientation: new import__599.HeadingPitchRoll( 6.283185307179586, -1.5687983448015541, 0 ) }); const redRectangleInstance = new import__599.GeometryInstance({ geometry: new import__599.RectangleGeometry({ rectangle: import__599.Rectangle.fromDegrees(-110, 20, -80, 25), vertexFormat: import__599.PerInstanceColorAppearance.VERTEX_FORMAT }), attributes: { color: import__599.ColorGeometryInstanceAttribute.fromColor( new import__599.Color(1, 0, 0, 0.5) ) } }); scene2.primitives.add( new import__599.GroundPrimitive({ geometryInstances: [redRectangleInstance], appearance: new import__599.PerInstanceColorAppearance({ closed: true }), asynchronous: false }) ); await updateGlobeUntilDone(scene2); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); }); }); it("picks ground primitive on translucent globe", async function() { const globe2 = new import__599.Globe(); scene2.globe = globe2; globe2.baseColor = import__599.Color.BLACK; globe2.translucency.enabled = true; globe2.translucency.frontFaceAlpha = 0.5; scene2.camera.setView({ destination: new import__599.Cartesian3( -557278.4840232887, -6744284200717078e-9, 2794079461722868e-9 ), orientation: new import__599.HeadingPitchRoll( 6.283185307179586, -1.5687983448015541, 0 ) }); const redRectangleInstance = new import__599.GeometryInstance({ geometry: new import__599.RectangleGeometry({ rectangle: import__599.Rectangle.fromDegrees(-110, 20, -80, 25), vertexFormat: import__599.PerInstanceColorAppearance.VERTEX_FORMAT }), attributes: { color: import__599.ColorGeometryInstanceAttribute.fromColor( new import__599.Color(1, 0, 0, 0.5) ) } }); const primitive = scene2.primitives.add( new import__599.GroundPrimitive({ geometryInstances: [redRectangleInstance], appearance: new import__599.PerInstanceColorAppearance({ closed: true }), asynchronous: false }) ); await updateGlobeUntilDone(scene2); expect(scene2).toPickPrimitive(primitive); }); it("updates frameState.atmosphere", function() { const frameState2 = scene2.frameState; expect(frameState2.atmosphere).toBeUndefined(); const originalAtmosphere = scene2.atmosphere; scene2.renderForSpecs(); expect(frameState2.atmosphere).toBe(originalAtmosphere); const anotherAtmosphere = new import__599.Atmosphere(); scene2.atmosphere = anotherAtmosphere; scene2.renderForSpecs(); expect(frameState2.atmosphere).toBe(anotherAtmosphere); }); function TilesetMockPrimitive() { this.update = function() { }; this.destroy = function() { }; this.show = true; this.isDestroyed = function() { return false; }; this.isCesium3DTileset = true; this.enableCollision = false; this.getHeight = function() { return void 0; }; this.updateHeight = function() { return function() { }; }; } it("subscribes to globe height updates when tileset is added", function() { const mockTileset = new TilesetMockPrimitive(); mockTileset.enableCollision = true; spyOn(mockTileset, "updateHeight"); scene2.primitives.add(mockTileset); scene2.renderForSpecs(); expect(mockTileset.updateHeight).toHaveBeenCalled(); }); }, "WebGL" ); // packages/engine/Specs/Scene/SceneTransformsSpec.js var import__601 = __toESM(require_Cesium(), 1); var import__602 = __toESM(require_Cesium(), 1); describe( "Scene/SceneTransforms", function() { let scene2; let defaultCamera; beforeAll(function() { scene2 = createScene_default(); defaultCamera = import__601.Camera.clone(scene2.camera); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { scene2.mode = import__601.SceneMode.SCENE3D; scene2.camera.position = defaultCamera.position.clone(); scene2.camera.direction = defaultCamera.direction.clone(); scene2.camera.up = defaultCamera.up.clone(); scene2.camera.right = defaultCamera.right.clone(); scene2.camera._transform = defaultCamera.transform.clone(); scene2.camera.frustum = defaultCamera.frustum.clone(); }); it("throws an exception without scene", function() { const position = import__601.Cartesian3.fromDegrees(0, 0); expect(function() { import__601.SceneTransforms.wgs84ToWindowCoordinates(void 0, position); }).toThrowDeveloperError(); }); it("throws an exception without position", function() { expect(function() { import__601.SceneTransforms.wgs84ToWindowCoordinates(scene2); }).toThrowDeveloperError(); }); it("returns correct window position in 3D", function() { const ellipsoid = import__601.Ellipsoid.WGS84; const positionCartographic = ellipsoid.cartesianToCartographic( scene2.camera.position ); positionCartographic.height = 0; const position = ellipsoid.cartographicToCartesian(positionCartographic); scene2.renderForSpecs(); const windowCoordinates = import__601.SceneTransforms.wgs84ToWindowCoordinates( scene2, position ); expect(windowCoordinates.x).toEqualEpsilon(0.5, import__602.Math.EPSILON2); expect(windowCoordinates.y).toEqualEpsilon(0.5, import__602.Math.EPSILON2); }); it("returns correct drawing buffer position in 3D", function() { const ellipsoid = import__601.Ellipsoid.WGS84; const positionCartographic = ellipsoid.cartesianToCartographic( scene2.camera.position ); positionCartographic.height = 0; const position = ellipsoid.cartographicToCartesian(positionCartographic); scene2.renderForSpecs(); const drawingBufferCoordinates = import__601.SceneTransforms.wgs84ToDrawingBufferCoordinates( scene2, position ); expect(drawingBufferCoordinates.x).toEqualEpsilon( 0.5, import__602.Math.EPSILON2 ); expect(drawingBufferCoordinates.y).toEqualEpsilon( 0.5, import__602.Math.EPSILON2 ); }); it("returns undefined for window position behind camera in 3D", function() { const ellipsoid = import__601.Ellipsoid.WGS84; const positionCartographic = ellipsoid.cartesianToCartographic( scene2.camera.position ); positionCartographic.height *= 1.1; const position = ellipsoid.cartographicToCartesian(positionCartographic); scene2.renderForSpecs(); const windowCoordinates = import__601.SceneTransforms.wgs84ToWindowCoordinates( scene2, position ); expect(windowCoordinates).not.toBeDefined(); }); it("returns undefined for drawing buffer position behind camera in 3D", function() { const ellipsoid = import__601.Ellipsoid.WGS84; const positionCartographic = ellipsoid.cartesianToCartographic( scene2.camera.position ); positionCartographic.height *= 1.1; const position = ellipsoid.cartographicToCartesian(positionCartographic); scene2.renderForSpecs(); const drawingBufferCoordinates = import__601.SceneTransforms.wgs84ToDrawingBufferCoordinates( scene2, position ); expect(drawingBufferCoordinates).not.toBeDefined(); }); it("returns correct window position in ColumbusView", function() { scene2.morphToColumbusView(0); scene2.renderForSpecs(); const actualWindowCoordinates = new import__601.Cartesian2(0.5, 0.5); const position = scene2.camera.pickEllipsoid(actualWindowCoordinates); const windowCoordinates = import__601.SceneTransforms.wgs84ToWindowCoordinates( scene2, position ); expect(windowCoordinates).toEqualEpsilon( actualWindowCoordinates, import__602.Math.EPSILON2 ); }); it("returns correct drawing buffer position in ColumbusView", function() { scene2.morphToColumbusView(0); scene2.renderForSpecs(); const actualDrawingBufferCoordinates = new import__601.Cartesian2(0.5, 0.5); const position = scene2.camera.pickEllipsoid( actualDrawingBufferCoordinates ); const drawingBufferCoordinates = import__601.SceneTransforms.wgs84ToDrawingBufferCoordinates( scene2, position ); expect(drawingBufferCoordinates).toEqualEpsilon( actualDrawingBufferCoordinates, import__602.Math.EPSILON2 ); }); it("returns undefined for window position behind camera in ColumbusView", function() { scene2.morphToColumbusView(0); scene2.renderForSpecs(); const position = new import__601.Cartesian3(); import__601.Cartesian3.normalize(scene2.camera.position, position); import__601.Cartesian3.add(position, scene2.camera.direction, position); import__601.Cartesian3.multiplyByScalar( scene2.camera.direction, -1, scene2.camera.direction ); const windowCoordinates = import__601.SceneTransforms.wgs84ToWindowCoordinates( scene2, position ); expect(windowCoordinates).not.toBeDefined(); }); it("returns undefined for drawing buffer position behind camera in ColumbusView", function() { scene2.morphToColumbusView(0); scene2.renderForSpecs(); const position = new import__601.Cartesian3(); import__601.Cartesian3.normalize(scene2.camera.position, position); import__601.Cartesian3.add(position, scene2.camera.direction, position); import__601.Cartesian3.multiplyByScalar( scene2.camera.direction, -1, scene2.camera.direction ); const drawingBufferCoordinates = import__601.SceneTransforms.wgs84ToDrawingBufferCoordinates( scene2, position ); expect(drawingBufferCoordinates).not.toBeDefined(); }); it("returns correct window position in 2D", function() { scene2.camera.setView({ destination: import__601.Rectangle.fromDegrees( -1e-6, -1e-6, 1e-6, 1e-6 ) }); scene2.morphTo2D(0); scene2.renderForSpecs(); const position = import__601.Cartesian3.fromDegrees(0, 0); const windowCoordinates = import__601.SceneTransforms.wgs84ToWindowCoordinates( scene2, position ); expect(windowCoordinates.x).toBeGreaterThan(0); expect(windowCoordinates.y).toBeGreaterThan(0); expect(windowCoordinates.x).toBeLessThan(1); expect(windowCoordinates.y).toBeLessThan(1); }); it("returns correct window position in 3D with orthographic frustum", function() { const frustum = new import__601.OrthographicFrustum(); frustum.aspectRatio = 1; frustum.width = 20; scene2.camera.frustum = frustum; scene2.renderForSpecs(); scene2.camera.setView({ destination: import__601.Rectangle.fromDegrees( -1e-6, -1e-6, 1e-6, 1e-6 ) }); const position = import__601.Cartesian3.fromDegrees(0, 0); const windowCoordinates = import__601.SceneTransforms.wgs84ToWindowCoordinates( scene2, position ); expect(windowCoordinates.x).toBeGreaterThan(0); expect(windowCoordinates.y).toBeGreaterThan(0); expect(windowCoordinates.x).toBeLessThan(1); expect(windowCoordinates.y).toBeLessThan(1); }); it("returns correct drawing buffer position in 2D", function() { scene2.camera.setView({ destination: import__601.Rectangle.fromDegrees( -1e-6, -1e-6, 1e-6, 1e-6 ) }); scene2.morphTo2D(0); scene2.renderForSpecs(); const position = import__601.Cartesian3.fromDegrees(0, 0); const drawingBufferCoordinates = import__601.SceneTransforms.wgs84ToDrawingBufferCoordinates( scene2, position ); expect(drawingBufferCoordinates.x).toBeGreaterThan(0); expect(drawingBufferCoordinates.y).toBeGreaterThan(0); expect(drawingBufferCoordinates.x).toBeLessThan(1); expect(drawingBufferCoordinates.y).toBeLessThan(1); }); it("should not error when zoomed out and in 2D", function() { const scene3 = createScene_default(); scene3.camera.setView({ destination: import__601.Cartesian3.fromDegrees(75, 15, 3e7) }); scene3.morphTo2D(0); scene3.renderForSpecs(); const position = import__601.Cartesian3.fromDegrees(-80, 25); const windowCoordinates = import__601.SceneTransforms.wgs84ToWindowCoordinates( scene3, position ); expect(windowCoordinates).toBeDefined(); scene3.destroyForSpecs(); }); }, "WebGL" ); // packages/engine/Specs/Scene/ScreenSpaceCameraControllerSpec.js var import__603 = __toESM(require_Cesium(), 1); var import__604 = __toESM(require_Cesium(), 1); describe("Scene/ScreenSpaceCameraController", function() { let usePointerEvents; let scene2; let canvas; let camera; let controller; function MockScene2(canvas2, camera2, ellipsoid) { this.canvas = canvas2; this.camera = camera2; this.globe = void 0; this.verticalExaggeration = 1; this.verticalExaggerationRelativeHeight = 0; this.mapProjection = new import__603.GeographicProjection(ellipsoid); this.screenSpaceCameraController = void 0; this.cameraUnderground = false; this.globeHeight = 0; } function MockGlobe(ellipsoid) { this.ellipsoid = ellipsoid; this.getHeight = function(cartographic) { return 0; }; this.pickWorldCoordinates = function() { return new import__603.Cartesian3(0, 0, 1); }; this._surface = { tileProvider: {}, _tileLoadQueueHigh: [], _tileLoadQueueMedium: [], _tileLoadQueueLow: [], _debug: { tilesWaitingForChildren: 0 } }; this.show = true; } beforeAll(function() { usePointerEvents = import__603.FeatureDetection.supportsPointerEvents(); canvas = createCanvas_default(1024, 768); }); afterAll(function() { document.body.removeChild(canvas); }); beforeEach(function() { const maxRadii = import__603.Ellipsoid.WGS84.maximumRadius; const offset = import__603.Cartesian3.multiplyByScalar( import__603.Cartesian3.normalize(new import__603.Cartesian3(0, -2, 1), new import__603.Cartesian3()), 2.5 * maxRadii, new import__603.Cartesian3() ); camera = createCamera_default({ canvas, offset, near: 1, far: 5e8 }); scene2 = new MockScene2(canvas, camera, import__603.Ellipsoid.WGS84); controller = new import__603.ScreenSpaceCameraController(scene2); scene2.screenSpaceCameraController = controller; camera._scene = scene2; }); afterEach(function() { scene2.mapMode2D = import__603.MapMode2D.INFINITE_SCROLL; controller = controller && !controller.isDestroyed() && controller.destroy(); }); const MouseButtons = { LEFT: 0, MIDDLE: 1, RIGHT: 2 }; function simulateMouseDown(options) { if (usePointerEvents) { DomEventSimulator_default.firePointerDown( canvas, (0, import__603.combine)(options, { pointerType: "mouse" }) ); } else { DomEventSimulator_default.fireMouseDown(canvas, options); } } function simulateMouseUp(options) { if (usePointerEvents) { DomEventSimulator_default.firePointerUp( canvas, (0, import__603.combine)(options, { pointerType: "mouse" }) ); } else { DomEventSimulator_default.fireMouseUp(document, options); } } function simulateMouseMove(options) { if (usePointerEvents) { DomEventSimulator_default.firePointerMove( canvas, (0, import__603.combine)(options, { pointerType: "mouse" }) ); } else { DomEventSimulator_default.fireMouseMove(document, options); } } function simulateMouseWheel(wheelDelta) { if ("onwheel" in document) { DomEventSimulator_default.fireWheel( canvas, (0, import__603.combine)({ deltaY: -wheelDelta }) ); } else if (document.onmousewheel !== void 0) { DomEventSimulator_default.fireMouseWheel( canvas, (0, import__603.combine)({ wheelDelta }) ); } } function moveMouse(button, startPosition, endPosition, shiftKey) { const canvasRect = canvas.getBoundingClientRect(); const options = { button, clientX: startPosition.x + canvasRect.left, clientY: startPosition.y + canvasRect.top, shiftKey }; simulateMouseDown(options); options.clientX = endPosition.x + canvasRect.left; options.clientY = endPosition.y + canvasRect.top; simulateMouseMove(options); simulateMouseUp(options); } function setUp2D() { scene2.mode = import__603.SceneMode.SCENE2D; const ellipsoid = import__603.Ellipsoid.WGS84; scene2.mapProjection = new import__603.GeographicProjection(ellipsoid); scene2.frameState = { mode: scene2.mode, mapProjection: scene2.mapProjection }; scene2.cameraUnderground = false; const maxRadii = ellipsoid.maximumRadius; const frustum = new import__603.OrthographicOffCenterFrustum(); frustum.right = maxRadii * Math.PI; frustum.left = -frustum.right; frustum.top = frustum.right * (canvas.clientHeight / canvas.clientWidth); frustum.bottom = -frustum.top; frustum.near = 0.01 * maxRadii; frustum.far = 60 * maxRadii; camera.frustum = frustum; camera.position = new import__603.Cartesian3(0, 0, maxRadii); camera.direction = import__603.Cartesian3.negate(import__603.Cartesian3.UNIT_Z, new import__603.Cartesian3()); camera.up = import__603.Cartesian3.clone(import__603.Cartesian3.UNIT_Y); camera.right = import__603.Cartesian3.clone(import__603.Cartesian3.UNIT_X); } function setUpCV() { scene2.mode = import__603.SceneMode.COLUMBUS_VIEW; const ellipsoid = import__603.Ellipsoid.WGS84; scene2.mapProjection = new import__603.GeographicProjection(ellipsoid); scene2.frameState = { mode: scene2.mode, mapProjection: scene2.mapProjection }; scene2.cameraUnderground = false; controller.enableCollisionDetection = true; const maxRadii = ellipsoid.maximumRadius; camera.position = new import__603.Cartesian3(0, 0, maxRadii); camera.direction = import__603.Cartesian3.negate(import__603.Cartesian3.UNIT_Z, new import__603.Cartesian3()); camera.up = import__603.Cartesian3.clone(import__603.Cartesian3.UNIT_Y); camera.right = import__603.Cartesian3.clone(import__603.Cartesian3.UNIT_X); } function setUpCVUnderground() { scene2.mode = import__603.SceneMode.COLUMBUS_VIEW; const ellipsoid = import__603.Ellipsoid.WGS84; scene2.globe = new MockGlobe(ellipsoid); scene2.mapProjection = new import__603.GeographicProjection(ellipsoid); scene2.frameState = { mode: scene2.mode, mapProjection: scene2.mapProjection }; scene2.cameraUnderground = true; controller.enableCollisionDetection = false; camera.position = new import__603.Cartesian3(0, 0, -100); camera.direction = import__603.Cartesian3.clone(import__603.Cartesian3.UNIT_Z); camera.up = import__603.Cartesian3.clone(import__603.Cartesian3.UNIT_Y); camera.right = import__603.Cartesian3.cross( camera.direction, camera.up, new import__603.Cartesian3() ); } function setUp3D() { scene2.mode = import__603.SceneMode.SCENE3D; const ellipsoid = import__603.Ellipsoid.WGS84; scene2.mapProjection = new import__603.GeographicProjection(ellipsoid); scene2.frameState = { mode: scene2.mode, mapProjection: scene2.mapProjection }; scene2.cameraUnderground = false; controller.enableCollisionDetection = true; } function setUp3DUnderground() { setUp3D(); scene2.globe = new MockGlobe(scene2.mapProjection.ellipsoid); scene2.cameraUnderground = true; controller.enableCollisionDetection = false; camera.setView({ destination: import__603.Camera.DEFAULT_VIEW_RECTANGLE }); const positionCart = import__603.Ellipsoid.WGS84.cartesianToCartographic( camera.position ); positionCart.height = -100; camera.position = import__603.Ellipsoid.WGS84.cartographicToCartesian(positionCart); } it("constructor throws without a scene", function() { expect(function() { return new import__603.ScreenSpaceCameraController(); }).toThrowDeveloperError(); }); function updateController() { camera.update(scene2.mode); controller.update(); } it("translate right in 2D", function() { setUp2D(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 4, canvas.clientHeight / 2 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(position.x).toBeLessThan(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toEqual(camera.position.z); }); it("translate left in 2D", function() { setUp2D(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 4, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(position.x).toBeGreaterThan(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toEqual(camera.position.z); }); it("translate up in 2D", function() { setUp2D(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(position.y).toBeGreaterThan(camera.position.y); expect(position.x).toEqual(camera.position.x); expect(position.z).toEqual(camera.position.z); }); it("translate down in 2D", function() { setUp2D(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(position.y).toBeLessThan(camera.position.y); expect(position.x).toEqual(camera.position.x); expect(position.z).toEqual(camera.position.z); }); it("translate in rotated 2D", function() { setUp2D(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); camera.up = import__603.Cartesian3.negate(import__603.Cartesian3.UNIT_X, new import__603.Cartesian3()); camera.right = import__603.Cartesian3.clone(import__603.Cartesian3.UNIT_Y); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(position.x).toBeGreaterThan(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toEqual(camera.position.z); }); it("zoom in 2D", function() { setUp2D(); const position = import__603.Cartesian3.clone(camera.position); const frustumDiff = camera.frustum.right - camera.frustum.left; const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(position.x).toEqual(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toEqual(camera.position.z); expect(frustumDiff).toBeGreaterThan( camera.frustum.right - camera.frustum.left ); }); it("zoom out in 2D", function() { setUp2D(); const frustum = camera.frustum; frustum.right = 1e3; frustum.left = -frustum.right; frustum.top = frustum.right * (canvas.clientHeight / canvas.clientWidth); frustum.bottom = -frustum.top; const position = import__603.Cartesian3.clone(camera.position); const frustumDiff = frustum.right - frustum.left; const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(position.x).toEqual(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toEqual(camera.position.z); expect(frustumDiff).toBeLessThan( camera.frustum.right - camera.frustum.left ); }); it("zoom in 2D with wheel", function() { setUp2D(); const position = import__603.Cartesian3.clone(camera.position); const frustumDiff = camera.frustum.right - camera.frustum.left; simulateMouseWheel(120); updateController(); expect(position.x).toEqual(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toEqual(camera.position.z); expect(frustumDiff).toBeGreaterThan( camera.frustum.right - camera.frustum.left ); }); it("zoom out in 2D with wheel", function() { setUp2D(); const frustum = camera.frustum; frustum.right = 1e3; frustum.left = -frustum.right; frustum.top = frustum.right * (canvas.clientHeight / canvas.clientWidth); frustum.bottom = -frustum.top; const position = import__603.Cartesian3.clone(camera.position); const frustumDiff = frustum.right - frustum.left; simulateMouseWheel(-120); updateController(); expect(position.x).toEqual(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toEqual(camera.position.z); expect(frustumDiff).toBeLessThan( camera.frustum.right - camera.frustum.left ); }); it("zoom with max zoom rate in 2D", function() { setUp2D(); const position = import__603.Cartesian3.clone(camera.position); const factor = 1e6; camera.frustum.right *= factor; camera.frustum.left *= factor; camera.frustum.top *= factor; camera.frustum.bottom *= factor; const frustumDiff = camera.frustum.right - camera.frustum.left; const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(position.x).toEqual(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toEqual(camera.position.z); expect(frustumDiff).toBeGreaterThan( camera.frustum.right - camera.frustum.left ); }); it("zoom with no mouse movement has no effect on the camera", function() { setUp2D(); const position = import__603.Cartesian3.clone(camera.position); const frustumDiff = camera.frustum.right - camera.frustum.left; const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(position.x).toEqual(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toEqual(camera.position.z); expect(frustumDiff).toEqual(camera.frustum.right - camera.frustum.left); }); it("zoom in does not affect camera close to the surface", function() { setUp2D(); const frustum = camera.frustum; const ratio = frustum.top / frustum.right; frustum.right = (controller.minimumZoomDistance + 1) * 0.5; frustum.left = -frustum.right; frustum.top = ratio * frustum.right; frustum.bottom = -frustum.top; const position = import__603.Cartesian3.clone(camera.position); const frustumDiff = camera.frustum.right - camera.frustum.left; const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(position.x).toEqual(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toEqual(camera.position.z); expect(frustumDiff).toEqual(camera.frustum.right - camera.frustum.left); }); it("zooms out with maximum distance in 2D", function() { setUp2D(); const frustum = camera.frustum; frustum.near = 1; frustum.far = 2; frustum.left = -2; frustum.right = 2; frustum.top = 1; frustum.bottom = -1; const maxZoom = 10; controller.minimumZoomDistance = 0; controller.maximumZoomDistance = maxZoom; const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight ); const endPosition = new import__603.Cartesian2(canvas.clientWidth / 2, 0); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(camera.frustum.right).toEqualEpsilon( maxZoom * 0.5, import__604.Math.EPSILON10 ); expect(camera.frustum.left).toEqual(-camera.frustum.right); expect(camera.frustum.top).toEqualEpsilon( maxZoom * 0.25, import__604.Math.EPSILON10 ); expect(camera.frustum.bottom).toEqual(-camera.frustum.top); }); it("rotate counter-clockwise in 2D", function() { setUp2D(); scene2.mapMode2D = import__603.MapMode2D.ROTATE; const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 4, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); moveMouse(MouseButtons.MIDDLE, startPosition, endPosition); updateController(); expect(position.x).toEqual(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toEqual(camera.position.z); expect(camera.direction).toEqualEpsilon( import__603.Cartesian3.negate(import__603.Cartesian3.UNIT_Z, new import__603.Cartesian3()), import__604.Math.EPSILON15 ); expect(camera.up).toEqualEpsilon( import__603.Cartesian3.negate(import__603.Cartesian3.UNIT_X, new import__603.Cartesian3()), import__604.Math.EPSILON15 ); expect(camera.right).toEqualEpsilon( import__603.Cartesian3.UNIT_Y, import__604.Math.EPSILON15 ); }); it("rotate clockwise in 2D", function() { setUp2D(); scene2.mapMode2D = import__603.MapMode2D.ROTATE; const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 4, canvas.clientHeight / 2 ); moveMouse(MouseButtons.MIDDLE, startPosition, endPosition); updateController(); expect(position.x).toEqual(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toEqual(camera.position.z); expect(camera.direction).toEqualEpsilon( import__603.Cartesian3.negate(import__603.Cartesian3.UNIT_Z, new import__603.Cartesian3()), import__604.Math.EPSILON15 ); expect(camera.up).toEqualEpsilon(import__603.Cartesian3.UNIT_X, import__604.Math.EPSILON15); expect(camera.right).toEqualEpsilon( import__603.Cartesian3.negate(import__603.Cartesian3.UNIT_Y, new import__603.Cartesian3()), import__604.Math.EPSILON15 ); }); it("rotates counter-clockwise with mouse position at bottom of the screen", function() { setUp2D(); scene2.mapMode2D = import__603.MapMode2D.ROTATE; const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( 3 * canvas.clientWidth / 4, 3 * canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 4, 3 * canvas.clientHeight / 4 ); moveMouse(MouseButtons.MIDDLE, startPosition, endPosition); updateController(); expect(position.x).toEqual(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toEqual(camera.position.z); expect(camera.direction).toEqualEpsilon( import__603.Cartesian3.negate(import__603.Cartesian3.UNIT_Z, new import__603.Cartesian3()), import__604.Math.EPSILON15 ); expect(camera.up).toEqualEpsilon( import__603.Cartesian3.negate(import__603.Cartesian3.UNIT_X, new import__603.Cartesian3()), import__604.Math.EPSILON15 ); expect(camera.right).toEqualEpsilon( import__603.Cartesian3.UNIT_Y, import__604.Math.EPSILON15 ); }); it("translate right in Columbus view", function() { setUpCV(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 4, canvas.clientHeight / 2 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(position.x).toBeLessThan(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toEqual(camera.position.z); }); it("translate left in Columbus view", function() { setUpCV(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 4, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(position.x).toBeGreaterThan(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toEqual(camera.position.z); }); it("translate up in Columbus view", function() { setUpCV(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(position.y).toBeGreaterThan(camera.position.y); expect(position.x).toEqual(camera.position.x); expect(position.z).toEqual(camera.position.z); }); it("translate down in Columbus view", function() { setUpCV(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(position.y).toBeLessThan(camera.position.y); expect(position.x).toEqual(camera.position.x); expect(position.z).toEqual(camera.position.z); }); it("translates in Columbus view when camera is underground", function() { setUpCVUnderground(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(position.x).toEqual(camera.position.x); expect(position.y).not.toEqual(camera.position.y); expect(position.z).toEqual(camera.position.z); }); it("looks in Columbus view", function() { setUpCV(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition, true); updateController(); expect(camera.position).toEqual(position); expect( import__603.Cartesian3.cross(camera.direction, camera.up, new import__603.Cartesian3()) ).toEqualEpsilon(camera.right, import__604.Math.EPSILON12); expect( import__603.Cartesian3.cross(camera.up, camera.right, new import__603.Cartesian3()) ).toEqualEpsilon(camera.direction, import__604.Math.EPSILON12); expect( import__603.Cartesian3.cross(camera.right, camera.direction, new import__603.Cartesian3()) ).toEqualEpsilon(camera.up, import__604.Math.EPSILON12); }); it("zoom in Columbus view", function() { setUpCV(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(position.x).toEqual(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toBeGreaterThan(camera.position.z); }); it("zoom out in Columbus view", function() { setUpCV(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(position.x).toEqual(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toBeLessThan(camera.position.z); }); it("zoom in Columbus view with wheel", function() { setUpCV(); const position = import__603.Cartesian3.clone(camera.position); simulateMouseWheel(120); updateController(); expect(position.x).toEqual(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toBeGreaterThan(camera.position.z); }); it("zoom out in Columbus view with wheel", function() { setUpCV(); const position = import__603.Cartesian3.clone(camera.position); simulateMouseWheel(-120); updateController(); expect(position.x).toEqual(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toBeLessThan(camera.position.z); }); it("zoom in Columbus view when camera is underground", function() { setUpCVUnderground(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(position.z).toBeLessThan(camera.position.z); }); it("rotates in Columbus view", function() { setUpCV(); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( 3 * canvas.clientWidth / 8, 3 * canvas.clientHeight / 8 ); camera.position.y = -100; moveMouse(MouseButtons.MIDDLE, startPosition, endPosition); updateController(); expect( import__603.Cartesian3.dot( import__603.Cartesian3.normalize(camera.position, new import__603.Cartesian3()), import__603.Cartesian3.UNIT_Z ) ).toBeGreaterThan(0); expect(import__603.Cartesian3.dot(camera.direction, import__603.Cartesian3.UNIT_Z)).toBeLessThan( 0 ); expect(import__603.Cartesian3.dot(camera.up, import__603.Cartesian3.UNIT_Z)).toBeGreaterThan(0); expect(import__603.Cartesian3.dot(camera.right, import__603.Cartesian3.UNIT_Z)).toBeLessThan( import__604.Math.EPSILON6 ); }); it("rotates in Columbus view with camera transform set", function() { setUpCV(); const origin = import__603.Cartesian3.fromDegrees(-72, 40); camera.lookAtTransform( import__603.Transforms.eastNorthUpToFixedFrame(origin), new import__603.Cartesian3(1, 0, 0) ); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2(0, 0); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 4, canvas.clientHeight / 4 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(camera.position).not.toEqual(position); expect(camera.direction).toEqualEpsilon( import__603.Cartesian3.normalize( import__603.Cartesian3.negate(camera.position, new import__603.Cartesian3()), new import__603.Cartesian3() ), import__604.Math.EPSILON14 ); expect( import__603.Cartesian3.cross(camera.direction, camera.up, new import__603.Cartesian3()) ).toEqualEpsilon(camera.right, import__604.Math.EPSILON14); expect( import__603.Cartesian3.cross(camera.right, camera.direction, new import__603.Cartesian3()) ).toEqualEpsilon(camera.up, import__604.Math.EPSILON14); }); it("rotates in Columbus view when camera is underground", function() { setUpCVUnderground(); camera.position.y = -100; const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( 3 * canvas.clientWidth / 8, 3 * canvas.clientHeight / 8 ); moveMouse(MouseButtons.MIDDLE, startPosition, endPosition); updateController(); expect(camera.position).not.toEqual(position); }); it("zooms in Columbus view with camera transform set", function() { setUpCV(); const origin = import__603.Cartesian3.fromDegrees(-72, 40); camera._transform = import__603.Transforms.eastNorthUpToFixedFrame(origin); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(position.x).toEqual(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toBeGreaterThan(camera.position.z); }); it("zoom in Columbus view with camera transform set and with wheel", function() { setUpCV(); const origin = import__603.Cartesian3.fromDegrees(-72, 40); camera._transform = import__603.Transforms.eastNorthUpToFixedFrame(origin); const position = import__603.Cartesian3.clone(camera.position); simulateMouseWheel(120); updateController(); expect(position.x).toEqual(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toBeGreaterThan(camera.position.z); }); it("adds an animation to correct position or zoom in Columbus view", function() { setUpCV(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2(0, canvas.clientHeight / 2); const endPosition = new import__603.Cartesian2( 4 * canvas.clientWidth, canvas.clientHeight / 2 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(position.x).toBeGreaterThan(camera.position.x); expect(position.y).toEqual(camera.position.y); expect(position.z).toEqual(camera.position.z); expect(controller._tweens.length).toEqual(1); }); it("pans in 3D", function() { setUp3D(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( 3 * canvas.clientWidth / 8, 3 * canvas.clientHeight / 8 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(camera.position).not.toEqual(position); expect(camera.direction).toEqualEpsilon( import__603.Cartesian3.normalize( import__603.Cartesian3.negate(camera.position, new import__603.Cartesian3()), new import__603.Cartesian3() ), import__604.Math.EPSILON12 ); expect( import__603.Cartesian3.cross(camera.direction, camera.up, new import__603.Cartesian3()) ).toEqualEpsilon(camera.right, import__604.Math.EPSILON12); expect( import__603.Cartesian3.cross(camera.right, camera.direction, new import__603.Cartesian3()) ).toEqualEpsilon(camera.up, import__604.Math.EPSILON12); }); it("pans in 3D with constrained axis", function() { setUp3D(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( 3 * canvas.clientWidth / 8, canvas.clientHeight / 2 ); camera.constrainedAxis = import__603.Cartesian3.clone(import__603.Cartesian3.UNIT_Z); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(camera.position).not.toEqual(position); expect(camera.direction).toEqualEpsilon( import__603.Cartesian3.normalize( import__603.Cartesian3.negate(camera.position, new import__603.Cartesian3()), new import__603.Cartesian3() ), import__604.Math.EPSILON14 ); expect( import__603.Cartesian3.cross(camera.direction, camera.up, new import__603.Cartesian3()) ).toEqualEpsilon(camera.right, import__604.Math.EPSILON14); expect( import__603.Cartesian3.cross(camera.right, camera.direction, new import__603.Cartesian3()) ).toEqualEpsilon(camera.up, import__604.Math.EPSILON14); }); it("strafes in 3D when camera is underground", function() { setUp3DUnderground(); const position = import__603.Cartesian3.clone(camera.position); const direction = import__603.Cartesian3.clone(camera.direction); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( 3 * canvas.clientWidth / 8, 3 * canvas.clientHeight / 8 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(camera.position).not.toEqual(position); expect(camera.direction).toEqual(direction); }); it("rotates in 3D", function() { setUp3D(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2(0, 0); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 4, canvas.clientHeight / 4 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(camera.position).not.toEqual(position); expect(camera.direction).toEqualEpsilon( import__603.Cartesian3.normalize( import__603.Cartesian3.negate(camera.position, new import__603.Cartesian3()), new import__603.Cartesian3() ), import__604.Math.EPSILON15 ); expect( import__603.Cartesian3.cross(camera.direction, camera.up, new import__603.Cartesian3()) ).toEqualEpsilon(camera.right, import__604.Math.EPSILON15); expect( import__603.Cartesian3.cross(camera.right, camera.direction, new import__603.Cartesian3()) ).toEqualEpsilon(camera.up, import__604.Math.EPSILON15); }); it("rotates with constrained axis", function() { setUp3D(); const axis = import__603.Cartesian3.clone(import__603.Cartesian3.UNIT_Z); camera.constrainedAxis = axis; const startPosition = new import__603.Cartesian2(0, 0); const endPosition = new import__603.Cartesian2(0, canvas.clientHeight); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(camera.position.z).toEqualEpsilon( import__603.Cartesian3.magnitude(camera.position), import__604.Math.EPSILON1 ); expect(camera.direction).toEqualEpsilon( import__603.Cartesian3.negate(axis, new import__603.Cartesian3()), import__604.Math.EPSILON4 ); expect(import__603.Cartesian3.dot(camera.up, axis)).toBeLessThan(import__604.Math.EPSILON2); expect(camera.right).toEqualEpsilon( import__603.Cartesian3.cross(camera.direction, camera.up, new import__603.Cartesian3()), import__604.Math.EPSILON4 ); }); it("zoom in 3D", function() { setUp3D(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(import__603.Cartesian3.magnitude(position)).toBeGreaterThan( import__603.Cartesian3.magnitude(camera.position) ); }); it("zooms in on an object in 3D", function() { setUp3D(); scene2.globe = new MockGlobe(scene2.mapProjection.ellipsoid); updateController(); const origin = import__603.Cartesian3.fromDegrees(-72, 40, 1); camera.setView({ destination: origin }); updateController(); scene2.pickPositionSupported = true; scene2.pickPositionWorldCoordinates = () => import__603.Cartesian3.fromDegrees(-72, 40, -10); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2(0, 0); const endPosition = new import__603.Cartesian2(0, canvas.clientHeight / 2); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(import__603.Cartesian3.magnitude(position)).toBeGreaterThan( import__603.Cartesian3.magnitude(camera.position) ); }); it("zooms in on an object in 3D when transform is set", function() { setUp3D(); scene2.globe = new MockGlobe(scene2.mapProjection.ellipsoid); updateController(); const origin = import__603.Cartesian3.fromDegrees(-72, 40, 1); camera.lookAtTransform(import__603.Transforms.eastNorthUpToFixedFrame(origin), { heading: 0, pitch: 0, range: 10 }); updateController(); scene2.pickPositionSupported = true; scene2.pickPositionWorldCoordinates = () => import__603.Cartesian3.fromDegrees(-72, 40, -10); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2(0, 0); const endPosition = new import__603.Cartesian2(0, canvas.clientHeight / 2); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(import__603.Cartesian3.magnitude(position)).toBeGreaterThan( import__603.Cartesian3.magnitude(camera.position) ); }); it("zoom in 3D to point 0,0", function() { setUp3D(); scene2.globe = new MockGlobe(scene2.mapProjection.ellipsoid); updateController(); camera.setView({ destination: import__603.Cartesian3.fromDegrees(-72, 40, 1) }); updateController(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2(0, 0); const endPosition = new import__603.Cartesian2(0, canvas.clientHeight / 2); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(import__603.Cartesian3.magnitude(position)).toBeGreaterThan( import__603.Cartesian3.magnitude(camera.position) ); }); it("zoom out in 3D", function() { setUp3D(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(import__603.Cartesian3.magnitude(position)).toBeLessThan( import__603.Cartesian3.magnitude(camera.position) ); }); it("zooms out to maximum height in 3D", function() { setUp3D(); const positionCart = import__603.Ellipsoid.WGS84.cartesianToCartographic( camera.position ); positionCart.height = 0; camera.position = import__603.Ellipsoid.WGS84.cartographicToCartesian(positionCart); const maxDist = 100; controller.minimumZoomDistance = 0; controller.maximumZoomDistance = maxDist; const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight * 50 ); const endPosition = new import__603.Cartesian2(canvas.clientWidth / 2, 0); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); const height = import__603.Ellipsoid.WGS84.cartesianToCartographic(camera.position).height; expect(height).toEqualEpsilon(maxDist, import__604.Math.EPSILON2); }); it("zoom in 3D with wheel", function() { setUp3D(); const position = import__603.Cartesian3.clone(camera.position); const heading = camera.heading; const pitch = camera.pitch; const roll = camera.roll; simulateMouseWheel(120); updateController(); expect(import__603.Cartesian3.magnitude(position)).toBeGreaterThan( import__603.Cartesian3.magnitude(camera.position) ); expect(camera.heading).toBeCloseTo(heading, 10); expect(camera.pitch).toBeCloseTo(pitch, 10); expect(camera.roll).toBeCloseTo(roll, 10); }); it("zoom out in 3D with wheel", function() { setUp3D(); const position = import__603.Cartesian3.clone(camera.position); const heading = camera.heading; const pitch = camera.pitch; const roll = camera.roll; simulateMouseWheel(-120); updateController(); expect(import__603.Cartesian3.magnitude(position)).toBeLessThan( import__603.Cartesian3.magnitude(camera.position) ); expect(camera.heading).toBeCloseTo(heading, 10); expect(camera.pitch).toBeCloseTo(pitch, 10); expect(camera.roll).toBeCloseTo(roll, 10); }); it("zoom in 3D with orthographic projection", function() { setUp3D(); const frustum = new import__603.OrthographicFrustum(); frustum.aspectRatio = 1; frustum.width = 20; camera.frustum = frustum; expect(frustum.projectionMatrix).toBeDefined(); camera.setView({ destination: import__603.Camera.DEFAULT_VIEW_RECTANGLE }); const position = import__603.Cartesian3.clone(camera.position); const frustumWidth = camera.frustum.width; const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(import__603.Cartesian3.magnitude(position)).toBeGreaterThan( import__603.Cartesian3.magnitude(camera.position) ); expect(frustumWidth).toBeGreaterThan(camera.frustum.width); }); it("zoom out in 3D with orthographic projection", function() { setUp3D(); const frustum = new import__603.OrthographicFrustum(); frustum.aspectRatio = 1; frustum.width = 20; camera.frustum = frustum; expect(frustum.projectionMatrix).toBeDefined(); camera.setView({ destination: import__603.Camera.DEFAULT_VIEW_RECTANGLE }); const position = import__603.Cartesian3.clone(camera.position); const frustumWidth = camera.frustum.width; const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(import__603.Cartesian3.magnitude(position)).toBeLessThan( import__603.Cartesian3.magnitude(camera.position) ); expect(frustumWidth).toBeLessThan(camera.frustum.width); }); it("zoom in 3D when camera is underground", function() { setUp3DUnderground(); const position = import__603.Cartesian3.clone(camera.position); const direction = import__603.Cartesian3.clone(camera.direction); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); const vector = import__603.Cartesian3.subtract( camera.position, position, new import__603.Cartesian3() ); const normalizedVector = import__603.Cartesian3.normalize(vector, vector); expect(normalizedVector).toEqualEpsilon(direction, import__604.Math.EPSILON2); expect(camera.direction).toEqualEpsilon(direction, import__604.Math.EPSILON6); }); it("tilts in 3D", function() { setUp3D(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); moveMouse(MouseButtons.MIDDLE, startPosition, endPosition); updateController(); expect(camera.position).not.toEqual(position); expect(camera.direction).not.toEqualEpsilon( import__603.Cartesian3.normalize( import__603.Cartesian3.negate(camera.position, new import__603.Cartesian3()), new import__603.Cartesian3() ), import__604.Math.EPSILON14 ); expect( import__603.Cartesian3.cross(camera.direction, camera.up, new import__603.Cartesian3()) ).toEqualEpsilon(camera.right, import__604.Math.EPSILON14); expect( import__603.Cartesian3.cross(camera.right, camera.direction, new import__603.Cartesian3()) ).toEqualEpsilon(camera.up, import__604.Math.EPSILON14); const ray = new import__603.Ray(camera.positionWC, camera.directionWC); const intersection = import__603.IntersectionTests.rayEllipsoid( ray, scene2.mapProjection.ellipsoid ); expect(intersection).toBeDefined(); }); it("does not tilt in the wrong direction", function() { setUp3D(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, 3 * canvas.clientHeight / 4 ); moveMouse(MouseButtons.MIDDLE, startPosition, endPosition); updateController(); expect(camera.position).toEqualEpsilon(position, import__604.Math.EPSILON8); expect(camera.direction).toEqualEpsilon( import__603.Cartesian3.normalize( import__603.Cartesian3.negate(camera.position, new import__603.Cartesian3()), new import__603.Cartesian3() ), import__604.Math.EPSILON15 ); expect( import__603.Cartesian3.cross(camera.direction, camera.up, new import__603.Cartesian3()) ).toEqualEpsilon(camera.right, import__604.Math.EPSILON14); expect( import__603.Cartesian3.cross(camera.right, camera.direction, new import__603.Cartesian3()) ).toEqualEpsilon(camera.up, import__604.Math.EPSILON15); }); it("tilts at the minimum zoom distance", function() { setUp3D(); const positionCart = import__603.Ellipsoid.WGS84.cartesianToCartographic( camera.position ); positionCart.height = controller.minimumZoomDistance; camera.position = import__603.Ellipsoid.WGS84.cartographicToCartesian(positionCart); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight ); const endPosition = new import__603.Cartesian2(canvas.clientWidth / 2, 0); moveMouse(MouseButtons.MIDDLE, startPosition, endPosition); updateController(); const height = import__603.Ellipsoid.WGS84.cartesianToCartographic(camera.position).height; expect(height).toBeLessThan(controller.minimumZoomDistance + 10); expect( import__603.Cartesian3.cross(camera.direction, camera.up, new import__603.Cartesian3()) ).toEqualEpsilon(camera.right, import__604.Math.EPSILON14); expect( import__603.Cartesian3.cross(camera.right, camera.direction, new import__603.Cartesian3()) ).toEqualEpsilon(camera.up, import__604.Math.EPSILON14); }); it("tilts in 3D when camera is underground", function() { setUp3DUnderground(); const position = import__603.Cartesian3.clone(camera.position); const direction = import__603.Cartesian3.clone(camera.direction); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); moveMouse(MouseButtons.MIDDLE, startPosition, endPosition); updateController(); expect(camera.position).not.toEqual(position); expect(camera.direction).not.toEqual(direction); }); it("looks in 3D", function() { setUp3D(); const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition, true); updateController(); expect(camera.position).toEqual(position); expect(camera.direction).not.toEqual( import__603.Cartesian3.normalize( import__603.Cartesian3.negate(camera.position, new import__603.Cartesian3()), new import__603.Cartesian3() ) ); expect( import__603.Cartesian3.cross(camera.direction, camera.up, new import__603.Cartesian3()) ).toEqualEpsilon(camera.right, import__604.Math.EPSILON12); expect( import__603.Cartesian3.cross(camera.up, camera.right, new import__603.Cartesian3()) ).toEqualEpsilon(camera.direction, import__604.Math.EPSILON12); expect( import__603.Cartesian3.cross(camera.right, camera.direction, new import__603.Cartesian3()) ).toEqualEpsilon(camera.up, import__604.Math.EPSILON12); }); it("pans with constrained axis other than z-axis", function() { setUp3D(); camera.position = new import__603.Cartesian3( 0, 2 * import__603.Ellipsoid.WGS84.maximumRadius, 0 ); camera.direction = import__603.Cartesian3.normalize( import__603.Cartesian3.negate(camera.position, new import__603.Cartesian3()), new import__603.Cartesian3() ); camera.up = import__603.Cartesian3.clone(import__603.Cartesian3.UNIT_X); camera.right = import__603.Cartesian3.cross( camera.direction, camera.up, new import__603.Cartesian3() ); const axis = import__603.Cartesian3.clone(import__603.Cartesian3.UNIT_X); camera.constrainedAxis = axis; const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(import__603.Cartesian3.dot(camera.position, axis)).toBeGreaterThan(0); expect(camera.direction).toEqualEpsilon( import__603.Cartesian3.normalize( import__603.Cartesian3.negate(camera.position, new import__603.Cartesian3()), new import__603.Cartesian3() ), import__604.Math.EPSILON14 ); expect(camera.right).toEqualEpsilon( import__603.Cartesian3.normalize( import__603.Cartesian3.cross(axis, camera.position, new import__603.Cartesian3()), new import__603.Cartesian3() ), import__604.Math.EPSILON14 ); expect(camera.up).toEqualEpsilon( import__603.Cartesian3.cross(camera.right, camera.direction, new import__603.Cartesian3()), import__604.Math.EPSILON14 ); }); it("pans with constrained axis and is tilted", function() { setUp3D(); camera.position = new import__603.Cartesian3( 0, 2 * import__603.Ellipsoid.WGS84.maximumRadius, 0 ); camera.direction = import__603.Cartesian3.negate( import__603.Cartesian3.normalize(camera.position, new import__603.Cartesian3()), new import__603.Cartesian3() ); camera.up = import__603.Cartesian3.clone(import__603.Cartesian3.UNIT_X); camera.right = import__603.Cartesian3.cross( camera.direction, camera.up, new import__603.Cartesian3() ); const axis = import__603.Cartesian3.clone(import__603.Cartesian3.UNIT_Z); camera.constrainedAxis = axis; const startPosition = new import__603.Cartesian2( canvas.clientWidth * 0.5, canvas.clientHeight * 0.25 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth * 0.5, canvas.clientHeight * 0.75 ); moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(import__603.Cartesian3.dot(camera.position, axis)).toBeLessThan( import__604.Math.EPSILON2 ); expect(camera.direction).toEqualEpsilon( import__603.Cartesian3.negate( import__603.Cartesian3.normalize(camera.position, new import__603.Cartesian3()), new import__603.Cartesian3() ), import__604.Math.EPSILON12 ); expect(camera.right).toEqualEpsilon(axis, import__604.Math.EPSILON12); expect(camera.up).toEqualEpsilon( import__603.Cartesian3.cross(camera.right, camera.direction, new import__603.Cartesian3()), import__604.Math.EPSILON12 ); }); it("controller does not modify the camera after re-enabling motion", function() { setUp3D(); const position = import__603.Cartesian3.clone(camera.position); const direction = import__603.Cartesian3.clone(camera.direction); const up = import__603.Cartesian3.clone(camera.up); const right = import__603.Cartesian3.clone(camera.right); const startPosition = new import__603.Cartesian2(0, 0); const endPosition = new import__603.Cartesian2(canvas.clientWidth, canvas.clientHeight); controller.enableRotate = false; moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(camera.position).toEqualEpsilon(position, import__604.Math.EPSILON7); expect(camera.direction).toEqualEpsilon(direction, import__604.Math.EPSILON7); expect(camera.up).toEqualEpsilon(up, import__604.Math.EPSILON7); expect(camera.right).toEqualEpsilon(right, import__604.Math.EPSILON7); controller.enableRotate = true; updateController(); expect(camera.position).toEqualEpsilon(position, import__604.Math.EPSILON7); expect(camera.direction).toEqualEpsilon(direction, import__604.Math.EPSILON7); expect(camera.up).toEqualEpsilon(up, import__604.Math.EPSILON7); expect(camera.right).toEqualEpsilon(right, import__604.Math.EPSILON7); }); it("can set input type to undefined", function() { setUp3D(); controller.zoomEventTypes = void 0; const position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(camera.position).toEqual(position); }); it("can change default input", function() { setUp3D(); controller.translateEventTypes = void 0; controller.rotateEventTypes = void 0; controller.tiltEventTypes = void 0; controller.lookEventTypes = void 0; let position = import__603.Cartesian3.clone(camera.position); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); controller.zoomEventTypes = import__603.CameraEventType.LEFT_DRAG; moveMouse(MouseButtons.LEFT, startPosition, endPosition); updateController(); expect(import__603.Cartesian3.magnitude(camera.position)).toBeLessThan( import__603.Cartesian3.magnitude(position) ); position = import__603.Cartesian3.clone(camera.position); controller.zoomEventTypes = { eventType: import__603.CameraEventType.LEFT_DRAG, modifier: import__603.KeyboardEventModifier.SHIFT }; moveMouse(MouseButtons.LEFT, endPosition, startPosition, true); updateController(); expect(import__603.Cartesian3.magnitude(camera.position)).toBeGreaterThan( import__603.Cartesian3.magnitude(position) ); position = import__603.Cartesian3.clone(camera.position); controller.zoomEventTypes = [ import__603.CameraEventType.MIDDLE_DRAG, { eventType: import__603.CameraEventType.LEFT_DRAG, modifier: import__603.KeyboardEventModifier.SHIFT } ]; moveMouse(MouseButtons.MIDDLE, startPosition, endPosition); updateController(); expect(import__603.Cartesian3.magnitude(camera.position)).toBeLessThan( import__603.Cartesian3.magnitude(position) ); position = import__603.Cartesian3.clone(camera.position); moveMouse(MouseButtons.LEFT, endPosition, startPosition, true); updateController(); expect(import__603.Cartesian3.magnitude(camera.position)).toBeGreaterThan( import__603.Cartesian3.magnitude(position) ); }); it("camera does not go below the terrain in 3D", function() { setUp3D(); scene2.globe = new MockGlobe(scene2.mapProjection.ellipsoid); updateController(); camera.setView({ destination: import__603.Cartesian3.fromDegrees(-72, 40, -10) }); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(camera.positionCartographic.height).toEqualEpsilon( controller.minimumZoomDistance, import__604.Math.EPSILON5 ); }); it("camera does not go below the terrain in CV", function() { setUpCV(); scene2.globe = new MockGlobe(scene2.mapProjection.ellipsoid); updateController(); camera.setView({ destination: import__603.Cartesian3.fromDegrees(-72, 40, -10) }); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(camera.position.z).toEqualEpsilon( controller.minimumZoomDistance, import__604.Math.EPSILON7 ); }); it("camera does go below the terrain in 3D when collision detection is disabled", function() { setUp3D(); scene2.globe = new MockGlobe(scene2.mapProjection.ellipsoid); controller.enableCollisionDetection = false; updateController(); camera.setView({ destination: import__603.Cartesian3.fromDegrees(-72, 40, -10) }); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(camera.positionCartographic.height).toBeLessThan( controller.minimumZoomDistance ); }); it("camera does go below the terrain in CV when collision detection is disabled", function() { setUpCV(); scene2.globe = new MockGlobe(scene2.mapProjection.ellipsoid); controller.enableCollisionDetection = false; updateController(); camera.setView({ destination: import__603.Cartesian3.fromDegrees(-72, 40, -10) }); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(camera.position.z).toBeLessThan(controller.minimumZoomDistance); }); it("camera does not go below the terrain in 3D with the transform set", function() { setUp3D(); scene2.globe = new MockGlobe(scene2.mapProjection.ellipsoid); updateController(); camera.lookAt( import__603.Cartesian3.fromDegrees(-72, 40, 1), new import__603.Cartesian3(1, 1, -10) ); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(camera.positionCartographic.height).toBeGreaterThanOrEqual( controller.minimumZoomDistance ); }); it("camera does not go below the terrain in CV with the transform set", function() { setUpCV(); scene2.globe = new MockGlobe(scene2.mapProjection.ellipsoid); updateController(); camera.lookAt( import__603.Cartesian3.fromDegrees(-72, 40, 1), new import__603.Cartesian3(1, 1, -10) ); const startPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 4 ); const endPosition = new import__603.Cartesian2( canvas.clientWidth / 2, canvas.clientHeight / 2 ); moveMouse(MouseButtons.RIGHT, startPosition, endPosition); updateController(); expect(camera.positionWC.x).toEqualEpsilon( controller.minimumZoomDistance, import__604.Math.EPSILON8 ); }); it("is destroyed", function() { expect(controller.isDestroyed()).toEqual(false); controller.destroy(); expect(controller.isDestroyed()).toEqual(true); }); }); // packages/engine/Specs/Scene/ShadowMapSpec.js var import__605 = __toESM(require_Cesium(), 1); var import__606 = __toESM(require_Cesium(), 1); describe( "Scene/ShadowMap", function() { let scene2; let sunShadowMap; const backgroundColor = [0, 0, 0, 255]; const longitude = -1.31968; const latitude = 0.4101524; const height = 0; const boxHeight = 4; const floorHeight = -1; const boxUrl = "./Data/Models/glTF-2.0/Box/glTF/Box.gltf"; const boxTranslucentUrl = "./Data/Models/glTF-2.0/BoxInterleavedTranslucent/glTF/BoxInterleavedTranslucent.gltf"; const boxNoNormalsUrl = "./Data/Models/glTF-2.0/BoxNoNormals/glTF/BoxNoNormals.gltf"; const boxCutoutUrl = "./Data/Models/glTF-2.0/BoxCutout/glTF/BoxCutout.gltf"; const boxInvertedUrl = "./Data/Models/glTF-2.0/BoxInverted/glTF/BoxInverted.gltf"; let box; let boxTranslucent; let boxPointLights; let boxCutout; let boxNoNormals; let room; let floor; let floorTranslucent; let primitiveBox; let primitiveBoxRTC; let primitiveBoxTranslucent; let primitiveFloor; let primitiveFloorRTC; beforeAll(function() { scene2 = createScene_default(); scene2.frameState.scene3DOnly = true; import__605.Color.unpack(backgroundColor, 0, scene2.backgroundColor); sunShadowMap = scene2.shadowMap; const boxOrigin = new import__605.Cartesian3.fromRadians( longitude, latitude, boxHeight ); const boxTransform = import__605.Transforms.headingPitchRollToFixedFrame( boxOrigin, new import__605.HeadingPitchRoll() ); const boxScale = 0.5; const boxScaleCartesian = new import__605.Cartesian3(boxScale, boxScale, boxScale); const boxTransformNoNormals = new import__605.Matrix4(); import__605.Matrix4.setScale(boxTransform, boxScaleCartesian, boxTransformNoNormals); const floorOrigin = new import__605.Cartesian3.fromRadians( longitude, latitude, floorHeight ); const floorTransform = import__605.Transforms.headingPitchRollToFixedFrame( floorOrigin, new import__605.HeadingPitchRoll() ); const roomOrigin = new import__605.Cartesian3.fromRadians( longitude, latitude, height ); const roomTransform = import__605.Transforms.headingPitchRollToFixedFrame( roomOrigin, new import__605.HeadingPitchRoll() ); const modelPromises = []; modelPromises.push( loadModel({ url: boxUrl, modelMatrix: boxTransform, scale: boxScale, show: false }).then(function(model) { box = model; }) ); modelPromises.push( loadModel({ url: boxTranslucentUrl, modelMatrix: boxTransform, scale: boxScale, show: false }).then(function(model) { boxTranslucent = model; }) ); modelPromises.push( loadModel({ url: boxUrl, modelMatrix: boxTransform, scale: 0.2, show: false }).then(function(model) { boxPointLights = model; }) ); modelPromises.push( loadModel({ url: boxCutoutUrl, modelMatrix: boxTransform, scale: boxScale, incrementallyLoadTextures: false, show: false }).then(function(model) { boxCutout = model; }) ); modelPromises.push( loadModel({ gltf: boxNoNormalsUrl, modelMatrix: boxTransformNoNormals, show: false }).then(function(model) { boxNoNormals = model; }) ); modelPromises.push( loadModel({ url: boxUrl, modelMatrix: floorTransform, scale: 2, show: false }).then(function(model) { floor = model; }) ); modelPromises.push( loadModel({ url: boxTranslucentUrl, modelMatrix: floorTransform, scale: 2, show: false }).then(function(model) { floorTranslucent = model; }) ); modelPromises.push( loadModel({ url: boxInvertedUrl, modelMatrix: roomTransform, scale: 8, show: false }).then(function(model) { room = model; }) ); primitiveBox = createPrimitive(boxTransform, 0.5, import__605.Color.RED); primitiveBoxRTC = createPrimitiveRTC(boxTransform, 0.5, import__605.Color.RED); primitiveBoxTranslucent = createPrimitive( boxTransform, 0.5, import__605.Color.RED.withAlpha(0.5) ); primitiveFloor = createPrimitive(floorTransform, 2, import__605.Color.RED); primitiveFloorRTC = createPrimitiveRTC(floorTransform, 2, import__605.Color.RED); return Promise.all(modelPromises); }); function createPrimitive(transform, size, color) { return scene2.primitives.add( new import__605.Primitive({ geometryInstances: new import__605.GeometryInstance({ geometry: import__605.BoxGeometry.fromDimensions({ dimensions: new import__605.Cartesian3(size, size, size), vertexFormat: import__605.PerInstanceColorAppearance.VERTEX_FORMAT }), modelMatrix: transform, attributes: { color: import__605.ColorGeometryInstanceAttribute.fromColor(color) } }), appearance: new import__605.PerInstanceColorAppearance({ translucent: false, closed: true }), asynchronous: false, show: false, shadows: import__605.ShadowMode.ENABLED }) ); } function createPrimitiveRTC(transform, size, color) { const boxGeometry = import__605.BoxGeometry.createGeometry( import__605.BoxGeometry.fromDimensions({ vertexFormat: import__605.PerInstanceColorAppearance.VERTEX_FORMAT, dimensions: new import__605.Cartesian3(size, size, size) }) ); const positions = boxGeometry.attributes.position.values; const newPositions = new Float32Array(positions.length); for (let i = 0; i < positions.length; ++i) { newPositions[i] = positions[i]; } boxGeometry.attributes.position.values = newPositions; boxGeometry.attributes.position.componentDatatype = import__605.ComponentDatatype.FLOAT; import__605.BoundingSphere.transform( boxGeometry.boundingSphere, transform, boxGeometry.boundingSphere ); const boxGeometryInstance = new import__605.GeometryInstance({ geometry: boxGeometry, attributes: { color: import__605.ColorGeometryInstanceAttribute.fromColor(color) } }); return scene2.primitives.add( new import__605.Primitive({ geometryInstances: boxGeometryInstance, appearance: new import__605.PerInstanceColorAppearance({ translucent: false, closed: true }), asynchronous: false, rtcCenter: boxGeometry.boundingSphere.center, show: false, shadows: import__605.ShadowMode.ENABLED }) ); } async function loadModel(options) { const model = scene2.primitives.add(await import__605.Model.fromGltfAsync(options)); await pollToPromise_default( function() { scene2.render(); return model.ready; }, { timeout: 1e4 } ); return model; } function loadGlobe() { return pollToPromise_default(function() { scene2.render(); const globe2 = scene2.globe; return globe2._surface._tileLoadQueueHigh.length === 0 && globe2._surface._tileLoadQueueMedium.length === 0 && globe2._surface._tileLoadQueueLow.length === 0 && globe2._surface._debug.tilesWaitingForChildren === 0; }); } afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { const length2 = scene2.primitives.length; for (let i = 0; i < length2; ++i) { scene2.primitives.get(i).show = false; } scene2.globe = void 0; scene2.shadowMap = scene2.shadowMap && scene2.shadowMap.destroy(); }); function createCascadedShadowMap() { const center = new import__605.Cartesian3.fromRadians(longitude, latitude, height); scene2.camera.lookAt( center, new import__605.HeadingPitchRange(0, import__606.Math.toRadians(-70), 5) ); const lightCamera = new import__605.Camera(scene2); lightCamera.lookAt(center, new import__605.Cartesian3(0, 0, 1)); scene2.shadowMap = new import__605.ShadowMap({ context: scene2.context, lightCamera }); } function createSingleCascadeShadowMap() { const center = new import__605.Cartesian3.fromRadians(longitude, latitude, height); scene2.camera.lookAt( center, new import__605.HeadingPitchRange(0, import__606.Math.toRadians(-70), 5) ); const lightCamera = new import__605.Camera(scene2); lightCamera.lookAt(center, new import__605.Cartesian3(0, 0, 1)); scene2.shadowMap = new import__605.ShadowMap({ context: scene2.context, lightCamera, numberOfCascades: 1 }); } function createShadowMapForDirectionalLight() { const center = new import__605.Cartesian3.fromRadians(longitude, latitude, height); scene2.camera.lookAt( center, new import__605.HeadingPitchRange(0, import__606.Math.toRadians(-70), 5) ); const frustum = new import__605.OrthographicOffCenterFrustum(); frustum.left = -50; frustum.right = 50; frustum.bottom = -50; frustum.top = 50; frustum.near = 1; frustum.far = 1e3; const lightCamera = new import__605.Camera(scene2); lightCamera.frustum = frustum; lightCamera.lookAt(center, new import__605.Cartesian3(0, 0, 20)); scene2.shadowMap = new import__605.ShadowMap({ context: scene2.context, lightCamera, cascadesEnabled: false }); } function createShadowMapForSpotLight() { const center = new import__605.Cartesian3.fromRadians(longitude, latitude, height); scene2.camera.lookAt( center, new import__605.HeadingPitchRange(0, import__606.Math.toRadians(-70), 5) ); const lightCamera = new import__605.Camera(scene2); lightCamera.frustum.fov = import__606.Math.PI_OVER_TWO; lightCamera.frustum.aspectRatio = 1; lightCamera.frustum.near = 1; lightCamera.frustum.far = 1e3; lightCamera.lookAt(center, new import__605.Cartesian3(0, 0, 20)); scene2.shadowMap = new import__605.ShadowMap({ context: scene2.context, lightCamera, cascadesEnabled: false }); } function createShadowMapForPointLight() { const center = new import__605.Cartesian3.fromRadians(longitude, latitude, height); scene2.camera.lookAt( center, new import__605.HeadingPitchRange(0, import__606.Math.toRadians(-70), 5) ); const lightCamera = new import__605.Camera(scene2); lightCamera.position = center; scene2.shadowMap = new import__605.ShadowMap({ context: scene2.context, lightCamera, isPointLight: true }); } function renderAndExpect(rgba, time2) { expect({ scene: scene2, time: time2, primeShadowMap: true }).toRender(rgba); } function renderAndReadPixels() { let color; expect({ scene: scene2, primeShadowMap: true }).toRenderAndCall(function(rgba) { color = rgba; }); return color; } function renderAndCall(expectationCallback, time2, customScene) { expect({ scene: (0, import__605.defined)(customScene) ? customScene : scene2, time: time2, primeShadowMap: true }).toRenderAndCall(function(rgba) { expectationCallback(rgba); }); } function verifyShadows(caster, receiver) { caster.shadows = import__605.ShadowMode.ENABLED; receiver.shadows = import__605.ShadowMode.ENABLED; scene2.shadowMap.enabled = false; let unshadowedColor; renderAndCall(function(rgba) { unshadowedColor = rgba; expect(unshadowedColor).not.toEqual(backgroundColor); }); scene2.shadowMap.enabled = true; let shadowedColor; renderAndCall(function(rgba) { shadowedColor = rgba; expect(rgba).not.toEqual(backgroundColor); expect(rgba).not.toEqual(unshadowedColor); }); caster.shadows = import__605.ShadowMode.DISABLED; renderAndExpect(unshadowedColor); caster.shadows = import__605.ShadowMode.ENABLED; renderAndExpect(shadowedColor); receiver.shadows = import__605.ShadowMode.DISABLED; renderAndExpect(unshadowedColor); receiver.shadows = import__605.ShadowMode.ENABLED; renderAndExpect(shadowedColor); scene2.camera.moveRight(0.5); renderAndExpect(unshadowedColor); } it("sets default shadow map properties", function() { scene2.shadowMap = new import__605.ShadowMap({ context: scene2.context, lightCamera: new import__605.Camera(scene2) }); expect(scene2.shadowMap.enabled).toBe(true); expect(scene2.shadowMap.softShadows).toBe(false); expect(scene2.shadowMap.isPointLight).toBe(false); expect(scene2.shadowMap._isSpotLight).toBe(false); expect(scene2.shadowMap._cascadesEnabled).toBe(true); expect(scene2.shadowMap._numberOfCascades).toBe(4); expect(scene2.shadowMap._normalOffset).toBe(true); }); it("throws without options.context", function() { expect(function() { scene2.shadowMap = new import__605.ShadowMap({ lightCamera: new import__605.Camera(scene2) }); }).toThrowDeveloperError(); }); it("throws without options.lightCamera", function() { expect(function() { scene2.shadowMap = new import__605.ShadowMap({ context: scene2.context }); }).toThrowDeveloperError(); }); it("throws when options.numberOfCascades is not one or four", function() { expect(function() { scene2.shadowMap = new import__605.ShadowMap({ context: scene2.context, lightCamera: new import__605.Camera(scene2), numberOfCascades: 3 }); }).toThrowDeveloperError(); }); it("Model casts shadows onto another model", function() { box.show = true; floor.show = true; createCascadedShadowMap(); verifyShadows(box, floor); }); it("translucent Model casts shadows onto another model", function() { boxTranslucent.show = true; floor.show = true; createCascadedShadowMap(); verifyShadows(boxTranslucent, floor); }); it("Model without normals casts shadows onto another model", function() { boxNoNormals.show = true; floor.show = true; createCascadedShadowMap(); verifyShadows(boxNoNormals, floor); }); it("Model with cutout texture casts shadows onto another model", function() { boxCutout.show = true; floor.show = true; createCascadedShadowMap(); scene2.shadowMap.enabled = false; let unshadowedColor; renderAndCall(function(rgba) { unshadowedColor = rgba; expect(rgba).not.toEqual(backgroundColor); }); scene2.shadowMap.enabled = true; renderAndExpect(unshadowedColor); scene2.camera.moveRight(0.2); renderAndCall(function(rgba) { expect(rgba).not.toEqual(backgroundColor); expect(rgba).not.toEqual(unshadowedColor); }); scene2.camera.moveRight(0.3); renderAndExpect(unshadowedColor); }); it("primitive casts shadows onto another primitive", function() { primitiveBox.show = true; primitiveFloor.show = true; createCascadedShadowMap(); verifyShadows(primitiveBox, primitiveFloor); }); it("RTC primitive casts shadows onto another RTC primitive", function() { primitiveBoxRTC.show = true; primitiveFloorRTC.show = true; createCascadedShadowMap(); verifyShadows(primitiveBoxRTC, primitiveFloorRTC); }); it("translucent primitive casts shadows onto another primitive", function() { primitiveBoxTranslucent.show = true; primitiveFloor.show = true; createCascadedShadowMap(); verifyShadows(primitiveBoxTranslucent, primitiveFloor); }); it("Model casts shadow onto globe", function() { box.show = true; scene2.globe = new import__605.Globe(); scene2.camera.frustum._sseDenominator = 5e-3; createCascadedShadowMap(); return loadGlobe().then(function() { verifyShadows(box, scene2.globe); }); }); it("globe casts shadow onto globe", function() { scene2.globe = new import__605.Globe(); scene2.camera.frustum._sseDenominator = 0.01; const center = new import__605.Cartesian3.fromRadians(longitude, latitude, height); scene2.camera.lookAt( center, new import__605.HeadingPitchRange(0, import__606.Math.toRadians(-70), 5) ); const lightCamera = new import__605.Camera(scene2); lightCamera.lookAt(center, new import__605.Cartesian3(1, 0, 0.1)); scene2.shadowMap = new import__605.ShadowMap({ context: scene2.context, lightCamera }); spyOn( import__605.EllipsoidTerrainProvider.prototype, "requestTileGeometry" ).and.callFake(function() { const width = 16; const height2 = 16; const buffer = new Uint8Array(width * height2); for (let i = 0; i < buffer.length; ++i) { const row = i % width; if (row > 6 && row < 10) { buffer[i] = 1; } } return new import__605.HeightmapTerrainData({ buffer, width, height: height2 }); }); return loadGlobe().then(function() { scene2.shadowMap.enabled = false; let unshadowedColor; renderAndCall(function(rgba) { unshadowedColor = rgba; expect(rgba).not.toEqual(backgroundColor); }); scene2.shadowMap.enabled = true; scene2.globe.shadows = import__605.ShadowMode.DISABLED; renderAndExpect(unshadowedColor); scene2.globe.shadows = import__605.ShadowMode.ENABLED; renderAndCall(function(rgba) { expect(rgba).not.toEqual(backgroundColor); expect(rgba).not.toEqual(unshadowedColor); }); }); }); it("changes light direction", function() { box.show = true; floor.show = true; const center = new import__605.Cartesian3.fromRadians(longitude, latitude, height); scene2.camera.lookAt( center, new import__605.HeadingPitchRange(0, import__606.Math.toRadians(-70), 5) ); const lightCamera = new import__605.Camera(scene2); lightCamera.lookAt(center, new import__605.Cartesian3(0, 0, 1)); scene2.shadowMap = new import__605.ShadowMap({ context: scene2.context, lightCamera }); const shadowedColor = renderAndReadPixels(); scene2.camera.moveLeft(0.5); renderAndCall(function(rgba) { expect(rgba).not.toEqual(backgroundColor); expect(rgba).not.toEqual(shadowedColor); }); lightCamera.lookAt(center, new import__605.Cartesian3(0.1, 0, 1)); renderAndExpect(shadowedColor); }); it("sun shadow map works", function() { box.show = true; floor.show = true; const startTime = new import__605.JulianDate(2457561211806e-6); const endTime = new import__605.JulianDate(2457561276389e-6); const center = new import__605.Cartesian3.fromRadians(longitude, latitude, height); scene2.camera.lookAt( center, new import__605.HeadingPitchRange(0, import__606.Math.toRadians(-90), 2) ); scene2.shadowMap = sunShadowMap; scene2.shadowMap.enabled = false; let unshadowedColor; renderAndCall(function(rgba) { unshadowedColor = rgba; expect(rgba).not.toEqual(backgroundColor); }, startTime); let shadowedColor; scene2.shadowMap.enabled = true; renderAndCall(function(rgba) { shadowedColor = rgba; expect(rgba).not.toEqual(backgroundColor); expect(rgba).not.toEqual(unshadowedColor); const shadowedRed = rgba[0]; const unshadowedRed = unshadowedColor[0]; expect(shadowedRed).toBeLessThan(unshadowedRed); }, startTime); renderAndCall(function(rgba) { expect(rgba).not.toEqual(backgroundColor); expect(rgba).not.toEqual(shadowedColor); expect(rgba).not.toEqual(unshadowedColor); const red = rgba[0]; const unshadowedRed = unshadowedColor[0]; const shadowedRed = shadowedColor[0]; expect(red).toBeGreaterThan(shadowedRed); expect(red).toBeLessThan(unshadowedRed); }, endTime); scene2.shadowMap = void 0; }); it("uses scene's light source", function() { const originalLight = scene2.light; box.show = true; floor.show = true; const lightDirectionAbove = new import__605.Cartesian3( -0.22562675028973597, 0.8893549458095356, -0.3976686433675793 ); const lightDirectionAngle = new import__605.Cartesian3( 0.14370705890272903, 0.9062077731227641, -0.3976628636840613 ); const center = new import__605.Cartesian3.fromRadians(longitude, latitude, height); scene2.camera.lookAt( center, new import__605.HeadingPitchRange(0, import__606.Math.toRadians(-90), 2) ); scene2.light = new import__605.DirectionalLight({ direction: lightDirectionAbove }); scene2.shadowMap = sunShadowMap; scene2.shadowMap.enabled = false; let unshadowedColor; renderAndCall(function(rgba) { unshadowedColor = rgba; expect(rgba).not.toEqual(backgroundColor); }); scene2.shadowMap.enabled = true; let shadowedColor; renderAndCall(function(rgba) { shadowedColor = rgba; expect(rgba).not.toEqual(backgroundColor); expect(rgba).not.toEqual(unshadowedColor); const shadowedRed = rgba[0]; const unshadowedRed = unshadowedColor[0]; expect(shadowedRed).toBeLessThan(unshadowedRed); }); scene2.light = new import__605.DirectionalLight({ direction: lightDirectionAngle }); renderAndCall(function(rgba) { expect(rgba).not.toEqual(backgroundColor); expect(rgba).not.toEqual(shadowedColor); expect(rgba).not.toEqual(unshadowedColor); const red = rgba[0]; const unshadowedRed = unshadowedColor[0]; const shadowedRed = shadowedColor[0]; expect(red).toBeGreaterThan(shadowedRed); expect(red).toBeLessThan(unshadowedRed); }); scene2.shadowMap = void 0; scene2.light = originalLight; }); it("single cascade shadow map", function() { box.show = true; floor.show = true; createSingleCascadeShadowMap(); verifyShadows(box, floor); }); it("directional shadow map", function() { box.show = true; floor.show = true; createShadowMapForDirectionalLight(); verifyShadows(box, floor); }); it("spot light shadow map", function() { box.show = true; floor.show = true; createShadowMapForSpotLight(); verifyShadows(box, floor); }); it("point light shadows", function() { boxPointLights.show = true; room.show = true; createShadowMapForPointLight(); const longitudeSpacing = 3419296208325038e-22; const latitudeSpacing = 315782e-12; const heightSpacing = 2; const origins = [ import__605.Cartesian3.fromRadians(longitude, latitude + latitudeSpacing, height), import__605.Cartesian3.fromRadians(longitude, latitude - latitudeSpacing, height), import__605.Cartesian3.fromRadians(longitude + longitudeSpacing, latitude, height), import__605.Cartesian3.fromRadians(longitude - longitudeSpacing, latitude, height), import__605.Cartesian3.fromRadians(longitude, latitude, height - heightSpacing), import__605.Cartesian3.fromRadians(longitude, latitude, height + heightSpacing) ]; const offsets = [ new import__605.HeadingPitchRange(0, 0, 0.1), new import__605.HeadingPitchRange(import__606.Math.PI, 0, 0.1), new import__605.HeadingPitchRange(import__606.Math.PI_OVER_TWO, 0, 0.1), new import__605.HeadingPitchRange(import__606.Math.THREE_PI_OVER_TWO, 0, 0.1), new import__605.HeadingPitchRange(0, -import__606.Math.PI_OVER_TWO, 0.1), new import__605.HeadingPitchRange(0, import__606.Math.PI_OVER_TWO, 0.1) ]; for (let i = 0; i < 6; ++i) { boxPointLights.modelMatrix = import__605.Transforms.headingPitchRollToFixedFrame( origins[i], new import__605.HeadingPitchRoll() ); scene2.render(); scene2.camera.lookAt(origins[i], offsets[i]); scene2.camera.moveForward(0.5); scene2.shadowMap.enabled = false; let unshadowedColor; renderAndCall(function(rgba) { unshadowedColor = rgba; expect(rgba).not.toEqual(backgroundColor); }); scene2.shadowMap.enabled = true; renderAndCall(function(rgba) { expect(rgba).not.toEqual(backgroundColor); expect(rgba).not.toEqual(unshadowedColor); }); const radius = scene2.shadowMap._pointLightRadius; scene2.shadowMap._pointLightRadius = 3; renderAndExpect(unshadowedColor); scene2.shadowMap._pointLightRadius = radius; scene2.camera.moveRight(0.5); renderAndExpect(unshadowedColor); } }); it("changes size", function() { box.show = true; floor.show = true; createCascadedShadowMap(); const shadowedColor = renderAndReadPixels(); scene2.shadowMap.size = 256; renderAndExpect(shadowedColor); expect(scene2.shadowMap._shadowMapTexture.width).toBe(512); expect(scene2.shadowMap._shadowMapTexture.height).toBe(512); expect(scene2.shadowMap.size).toBe(256); }); it("enable debugCascadeColors", function() { box.show = true; floor.show = true; createCascadedShadowMap(); const startTime = new import__605.JulianDate(2457561211806e-6); const shadowedColor = renderAndReadPixels(); scene2.shadowMap.debugCascadeColors = true; expect(scene2.shadowMap.dirty).toBe(true); renderAndCall(function(rgba) { expect(rgba).not.toEqual(backgroundColor); expect(rgba).not.toEqual(shadowedColor); }, startTime); }); it("enable soft shadows", function() { box.show = true; floor.show = true; createCascadedShadowMap(); scene2.shadowMap.enabled = false; const unshadowedColor = renderAndReadPixels(); scene2.shadowMap.enabled = true; expect(scene2.shadowMap.dirty).toBe(true); const shadowedColor = renderAndReadPixels(); scene2.shadowMap.softShadows = true; scene2.shadowMap.size = 256; scene2.camera.moveRight(0.25); renderAndCall(function(rgba) { expect(rgba).not.toEqual(backgroundColor); expect(rgba).not.toEqual(unshadowedColor); expect(rgba).not.toEqual(shadowedColor); }); }); it("changes darkness", function() { box.show = true; floor.show = true; createCascadedShadowMap(); scene2.shadowMap.enabled = false; const unshadowedColor = renderAndReadPixels(); scene2.shadowMap.enabled = true; const shadowedColor = renderAndReadPixels(); scene2.shadowMap.darkness = 0.5; renderAndCall(function(rgba) { expect(rgba).not.toEqual(backgroundColor); expect(rgba).not.toEqual(unshadowedColor); expect(rgba).not.toEqual(shadowedColor); }); }); it("disables shadow fading", function() { box.show = true; floor.show = true; const center = new import__605.Cartesian3.fromRadians(longitude, latitude, height); scene2.camera.lookAt( center, new import__605.HeadingPitchRange(0, import__606.Math.toRadians(-70), 5) ); const lightCamera = new import__605.Camera(scene2); lightCamera.lookAt(center, new import__605.Cartesian3(0, 0, 1)); scene2.shadowMap = new import__605.ShadowMap({ context: scene2.context, lightCamera }); const shadowedColor = renderAndReadPixels(); lightCamera.lookAt(center, new import__605.Cartesian3(1, 0, 0.01)); const horizonShadowedColor = renderAndReadPixels(); scene2.shadowMap.fadingEnabled = false; renderAndCall(function(rgba) { expect(horizonShadowedColor).not.toEqual(shadowedColor); expect(rgba).not.toEqual(horizonShadowedColor); }); }); function depthFramebufferSupported(scene3) { const framebuffer2 = new import__605.Framebuffer({ context: scene3.context, depthStencilTexture: new import__605.Texture({ context: scene3.context, width: 1, height: 1, pixelFormat: import__605.PixelFormat.DEPTH_STENCIL, pixelDatatype: import__605.PixelDatatype.UNSIGNED_INT_24_8 }) }); return framebuffer2.status === import__605.WebGLConstants.FRAMEBUFFER_COMPLETE; } it("defaults to color texture if depth texture extension is not supported", function() { box.show = true; floor.show = true; const sceneWithWebgl1 = createScene_default({ contextOptions: { requestWebgl1: true } }); const lightCamera = new import__605.Camera(scene2); sceneWithWebgl1.shadowMap = new import__605.ShadowMap({ context: sceneWithWebgl1.context, lightCamera }); renderAndCall( function(rgba) { if (sceneWithWebgl1.context.depthTexture) { if (depthFramebufferSupported(sceneWithWebgl1)) { expect(sceneWithWebgl1.shadowMap._usesDepthTexture).toBe(true); expect( sceneWithWebgl1.shadowMap._shadowMapTexture.pixelFormat ).toEqual(import__605.PixelFormat.DEPTH_STENCIL); } else { expect(sceneWithWebgl1.shadowMap._usesDepthTexture).toBe(false); expect( sceneWithWebgl1.shadowMap._shadowMapTexture.pixelFormat ).toEqual(import__605.PixelFormat.RGBA); } } }, void 0, sceneWithWebgl1 ); sceneWithWebgl1.shadowMap = sceneWithWebgl1.shadowMap && sceneWithWebgl1.shadowMap.destroy(); sceneWithWebgl1.context._depthTexture = false; sceneWithWebgl1.shadowMap = new import__605.ShadowMap({ context: sceneWithWebgl1.context, lightCamera }); renderAndCall( function(rgba) { expect(sceneWithWebgl1.shadowMap._usesDepthTexture).toBe(false); expect( sceneWithWebgl1.shadowMap._shadowMapTexture.pixelFormat ).toEqual(import__605.PixelFormat.RGBA); }, void 0, sceneWithWebgl1 ); sceneWithWebgl1.destroyForSpecs(); }); it("does not render shadows when the camera is far away from any shadow receivers", function() { box.show = true; floor.show = true; createCascadedShadowMap(); renderAndCall(function(rgba) { expect(scene2.shadowMap.outOfView).toBe(false); }); const center = new import__605.Cartesian3.fromRadians(longitude, latitude, 2e5); scene2.camera.lookAt( center, new import__605.HeadingPitchRange(0, import__606.Math.toRadians(-70), 5) ); renderAndCall(function(rgba) { expect(scene2.shadowMap.outOfView).toBe(true); }); }); it("does not render shadows when the light direction is below the horizon", function() { box.show = true; floor.show = true; const center = new import__605.Cartesian3.fromRadians(longitude, latitude, height); scene2.camera.lookAt( center, new import__605.HeadingPitchRange(0, import__606.Math.toRadians(-70), 5) ); const lightCamera = new import__605.Camera(scene2); lightCamera.lookAt(center, new import__605.Cartesian3(0, 0, 1)); scene2.shadowMap = new import__605.ShadowMap({ context: scene2.context, lightCamera }); renderAndCall(function(rgba) { expect(scene2.shadowMap.outOfView).toBe(false); }); lightCamera.lookAt(center, new import__605.Cartesian3(0, 0, -1)); renderAndCall(function(rgba) { expect(scene2.shadowMap.outOfView).toBe(true); }); }); it("enable debugShow for cascaded shadow map", function() { createCascadedShadowMap(); scene2.shadowMap.debugShow = true; scene2.shadowMap.debugFreezeFrame = true; renderAndCall(function(rgba) { expect(scene2.frameState.commandList.length).toBe(13); }); scene2.shadowMap.debugShow = false; renderAndCall(function(rgba) { expect(scene2.frameState.commandList.length).toBe(0); }); }); it("enable debugShow for fixed shadow map", function() { createShadowMapForDirectionalLight(); scene2.shadowMap.debugShow = true; renderAndCall(function(rgba) { expect(scene2.frameState.commandList.length).toBe(3); }); scene2.shadowMap.debugShow = false; renderAndCall(function(rgba) { expect(scene2.frameState.commandList.length).toBe(0); }); }); it("enable debugShow for point light shadow map", function() { createShadowMapForPointLight(); scene2.shadowMap.debugShow = true; renderAndCall(function(rgba) { expect(scene2.frameState.commandList.length).toBe(2); }); scene2.shadowMap.debugShow = false; renderAndCall(function(rgba) { expect(scene2.frameState.commandList.length).toBe(0); }); }); it("enable fitNearFar", function() { box.show = true; floor.show = true; createShadowMapForDirectionalLight(); scene2.shadowMap._fitNearFar = true; let shadowNearFit; let shadowFarFit; renderAndCall(function(rgba) { shadowNearFit = scene2.shadowMap._sceneCamera.frustum.near; shadowFarFit = scene2.shadowMap._sceneCamera.frustum.far; }); scene2.shadowMap._fitNearFar = false; renderAndCall(function(rgba) { const shadowNear = scene2.shadowMap._sceneCamera.frustum.near; const shadowFar = scene2.shadowMap._sceneCamera.frustum.far; expect(shadowNear).toBeLessThan(shadowNearFit); expect(shadowFar).toBeGreaterThan(shadowFarFit); }); }); it("set normalOffset", function() { createCascadedShadowMap(); const shadowMap = scene2.shadowMap; shadowMap.normalOffset = false; expect(shadowMap._normalOffset).toBe(false); expect(shadowMap._terrainBias.normalOffset).toBe(false); expect(shadowMap._primitiveBias.normalOffset).toBe(false); expect(shadowMap._pointBias.normalOffset).toBe(false); }); it("set maximumDistance", function() { box.show = true; floor.show = true; createCascadedShadowMap(); scene2.shadowMap.enabled = false; let unshadowedColor; renderAndCall(function(rgba) { expect(rgba).not.toEqual(backgroundColor); unshadowedColor = rgba; }); scene2.shadowMap.enabled = true; let shadowedColor; renderAndCall(function(rgba) { expect(rgba).not.toEqual(backgroundColor); expect(rgba).not.toEqual(unshadowedColor); }); scene2.shadowMap.maximumDistance = 6; renderAndCall(function(rgba) { expect(rgba).not.toEqual(backgroundColor); expect(rgba).not.toEqual(unshadowedColor); expect(rgba).not.toEqual(shadowedColor); }); scene2.shadowMap.maximumDistance = 3; renderAndExpect(unshadowedColor); }); it("shadows are disabled during the pick pass", function() { const spy = spyOn(import__605.Context.prototype, "draw").and.callThrough(); boxTranslucent.show = true; floorTranslucent.show = true; createCascadedShadowMap(); renderAndCall(function(rgba) { const count = spy.calls.count(); for (let i = 0; i < count; ++i) { const drawCommand = spy.calls.argsFor(i)[0]; const owner = drawCommand.owner; if ((0, import__605.defined)(owner) && owner instanceof import__605.Model) { expect( drawCommand.shaderProgram._fragmentShaderText.indexOf( "czm_shadow" ) !== -1 ).toBe(true); } } }); spy.calls.reset(); expect(scene2).toPickAndCall(function(result) { const count = spy.calls.count(); for (let i = 0; i < count; ++i) { const drawCommand = spy.calls.argsFor(i)[0]; const owner = drawCommand.owner; if ((0, import__605.defined)(owner) && owner instanceof import__605.Model) { expect( drawCommand.shaderProgram._fragmentShaderText.indexOf( "czm_shadow" ) !== -1 ).toBe(false); } } }); }); it("Model updates derived commands when the shadow map is dirty", function() { const spy1 = spyOn( import__605.ShadowMap, "createReceiveDerivedCommand" ).and.callThrough(); const spy2 = spyOn( import__605.ShadowMap, "createCastDerivedCommand" ).and.callThrough(); box.show = true; floor.show = true; createCascadedShadowMap(); scene2.shadowMap.enabled = false; let unshadowedColor; renderAndCall(function(rgba) { unshadowedColor = rgba; expect(rgba).not.toEqual(backgroundColor); }); scene2.shadowMap.enabled = true; let shadowedColor; renderAndCall(function(rgba) { shadowedColor = rgba; expect(rgba).not.toEqual(backgroundColor); expect(rgba).not.toEqual(unshadowedColor); }); floor.show = false; scene2.shadowMap.debugCascadeColors = true; let i; for (i = 0; i < 6; ++i) { scene2.render(); } const startTime = new import__605.JulianDate(2457561211806e-6); floor.show = true; renderAndCall(function(rgba) { expect(rgba).not.toEqual(backgroundColor); expect(rgba).not.toEqual(unshadowedColor); expect(rgba).not.toEqual(shadowedColor); }, startTime); for (i = 0; i < 6; ++i) { scene2.render(); } expect(spy1.calls.count()).toBeLessThanOrEqual(8); expect(spy2.calls.count()).toEqual(4); box.show = false; floor.show = false; }); it("does not receive shadows if fromLightSource is false", function() { box.show = true; floorTranslucent.show = true; createCascadedShadowMap(); scene2.shadowMap.fromLightSource = false; scene2.shadowMap.enabled = false; let unshadowedColor; renderAndCall(function(rgba) { unshadowedColor = rgba; expect(rgba).not.toEqual(backgroundColor); }); scene2.shadowMap.enabled = true; renderAndCall(function(rgba) { expect(rgba).not.toEqual(backgroundColor); expect(rgba).toEqual(unshadowedColor); }); }); it("tweaking shadow bias parameters works", function() { box.show = true; floor.show = true; createCascadedShadowMap(); scene2.shadowMap.enabled = false; let unshadowedColor; renderAndCall(function(rgba) { unshadowedColor = rgba; expect(rgba).not.toEqual(backgroundColor); }); scene2.shadowMap.enabled = true; let shadowedColor; renderAndCall(function(rgba) { shadowedColor = rgba; expect(rgba).not.toEqual(backgroundColor); expect(rgba).not.toEqual(unshadowedColor); }); scene2.shadowMap._primitiveBias.polygonOffsetFactor = 1.2; scene2.shadowMap._primitiveBias.polygonOffsetFactor = 4.1; scene2.shadowMap._primitiveBias.normalOffsetScale = 2.1; scene2.shadowMap._primitiveBias.normalShadingSmooth = 0.4; scene2.shadowMap.debugCreateRenderStates(); scene2.shadowMap.dirty = true; renderAndExpect(shadowedColor); scene2.shadowMap._primitiveBias.normalOffset = false; scene2.shadowMap._primitiveBias.normalShading = false; scene2.shadowMap._primitiveBias.polygonOffset = false; scene2.shadowMap.debugCreateRenderStates(); scene2.shadowMap.dirty = true; renderAndExpect(shadowedColor); }); it("destroys", function() { box.show = true; floor.show = true; createCascadedShadowMap(); expect(scene2.shadowMap.isDestroyed()).toEqual(false); scene2.shadowMap.destroy(); expect(scene2.shadowMap.isDestroyed()).toEqual(true); scene2.shadowMap = void 0; }); }, "WebGL" ); // packages/engine/Specs/Scene/ShadowVolumeAppearanceSpec.js var import__607 = __toESM(require_Cesium(), 1); var import__608 = __toESM(require_Cesium(), 1); describe("Scene/ShadowVolumeAppearance", function() { const testVs = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin float batchId;\nvoid main() {\n vec4 position = czm_computePosition();\n gl_Position = czm_depthClamp(czm_modelViewProjectionRelativeToEye * position);\n}\n"; const unitSphereEllipsoid = import__607.Ellipsoid.UNIT_SPHERE; const projection = new import__607.WebMercatorProjection(unitSphereEllipsoid); const largeTestRectangle = import__607.Rectangle.fromDegrees(-45, -45, 45, 45); const smallTestRectangle = import__607.Rectangle.fromDegrees(-0.1, -0.1, 0.1, 0.1); const largeRectangleAttributes = import__607.ShadowVolumeAppearance.getSphericalExtentGeometryInstanceAttributes( largeTestRectangle, [0, 0, 0, 1, 1, 0], unitSphereEllipsoid, projection ); const smallRectangleAttributes = import__607.ShadowVolumeAppearance.getPlanarTextureCoordinateAttributes( smallTestRectangle, [0, 0, 0, 1, 1, 0], unitSphereEllipsoid, projection ); const perInstanceColorMaterialAppearance = new import__607.PerInstanceColorAppearance(); const flatPerInstanceColorMaterialAppearance = new import__607.PerInstanceColorAppearance( { flat: true } ); const textureMaterialAppearance = new import__607.MaterialAppearance({ material: new import__607.Material({ fabric: { type: "BumpMap", uniforms: { image: "../images/Cesium_Logo_Color.jpg", channel: "r" } } }) }); const flatTextureMaterialAppearance = new import__607.MaterialAppearance({ material: import__607.Material.fromType(import__607.Material.ImageType, { image: "../Data/images/Red16x16.png" }), flat: true }); const eastMostCartographic = new import__607.Cartographic(); const longitudeExtentsEncodeScratch = { high: 0, low: 0 }; eastMostCartographic.longitude = import__608.Math.PI; eastMostCartographic.latitude = 0; eastMostCartographic.height = 0; const eastMostCartesian = projection.project(eastMostCartographic); let encoded = import__607.EncodedCartesian3.encode( eastMostCartesian.x, longitudeExtentsEncodeScratch ); const eastMostYhighDefine = `EAST_MOST_X_HIGH ${encoded.high.toFixed( `${encoded.high}`.length + 1 )}`; const eastMostYlowDefine = `EAST_MOST_X_LOW ${encoded.low.toFixed( `${encoded.low}`.length + 1 )}`; const westMostCartographic = new import__607.Cartographic(); westMostCartographic.longitude = -import__608.Math.PI; westMostCartographic.latitude = 0; westMostCartographic.height = 0; const westMostCartesian = projection.project(westMostCartographic); encoded = import__607.EncodedCartesian3.encode( westMostCartesian.x, longitudeExtentsEncodeScratch ); const westMostYhighDefine = `WEST_MOST_X_HIGH ${encoded.high.toFixed( `${encoded.high}`.length + 1 )}`; const westMostYlowDefine = `WEST_MOST_X_LOW ${encoded.low.toFixed( `${encoded.low}`.length + 1 )}`; it("provides attributes for computing texture coordinates from Spherical extents", function() { const attributes = largeRectangleAttributes; const sphericalExtents = attributes.sphericalExtents; expect(sphericalExtents.componentDatatype).toEqual(import__607.ComponentDatatype.FLOAT); expect(sphericalExtents.componentsPerAttribute).toEqual(4); expect(sphericalExtents.normalize).toEqual(false); let value = sphericalExtents.value; expect(value[0]).toEqualEpsilon( -import__608.Math.PI_OVER_FOUR, import__608.Math.EPSILON4 ); expect(value[1]).toEqualEpsilon( -import__608.Math.PI_OVER_FOUR, import__608.Math.EPSILON4 ); expect(value[2]).toEqualEpsilon( 1 / import__608.Math.PI_OVER_TWO, import__608.Math.EPSILON4 ); expect(value[3]).toEqualEpsilon( 1 / import__608.Math.PI_OVER_TWO, import__608.Math.EPSILON4 ); const longitudeRotation = attributes.longitudeRotation; expect(longitudeRotation.componentDatatype).toEqual( import__607.ComponentDatatype.FLOAT ); expect(longitudeRotation.componentsPerAttribute).toEqual(1); expect(longitudeRotation.normalize).toEqual(false); value = longitudeRotation.value; expect(value[0]).toEqualEpsilon(0, import__608.Math.EPSILON4); }); function checkGeometryInstanceAttributeVec3(attribute) { expect(attribute.componentDatatype).toEqual(import__607.ComponentDatatype.FLOAT); expect(attribute.componentsPerAttribute).toEqual(3); expect(attribute.normalize).toEqual(false); } it("provides attributes for computing texture coordinates using planes in 3D", function() { const attributes = smallRectangleAttributes; const southWest_LOW = attributes.southWest_LOW; const southWest_HIGH = attributes.southWest_HIGH; const eastward = attributes.eastward; const northward = attributes.northward; checkGeometryInstanceAttributeVec3(southWest_LOW); checkGeometryInstanceAttributeVec3(southWest_HIGH); checkGeometryInstanceAttributeVec3(eastward); checkGeometryInstanceAttributeVec3(northward); expect(southWest_HIGH.value[0]).toEqualEpsilon(0, import__608.Math.EPSILON7); expect(southWest_HIGH.value[1]).toEqualEpsilon(0, import__608.Math.EPSILON7); expect(southWest_HIGH.value[2]).toEqualEpsilon(0, import__608.Math.EPSILON7); expect(southWest_LOW.value[0]).toBeGreaterThan( Math.cos(import__608.Math.toRadians(0.2)) ); const smallRectangleCenter = import__607.Cartographic.toCartesian( import__607.Rectangle.center(smallTestRectangle), unitSphereEllipsoid ); const enuMatrix = import__607.Transforms.eastNorthUpToFixedFrame( smallRectangleCenter, unitSphereEllipsoid ); const inverseEnu = import__607.Matrix4.inverse(enuMatrix, new import__607.Matrix4()); let eastwardENU = import__607.Matrix4.multiplyByPointAsVector( inverseEnu, import__607.Cartesian3.fromArray(eastward.value), new import__607.Cartesian3() ); eastwardENU = import__607.Cartesian3.normalize(eastwardENU, eastwardENU); expect( import__607.Cartesian3.equalsEpsilon( eastwardENU, import__607.Cartesian3.UNIT_X, import__608.Math.EPSILON7 ) ).toBe(true); let northwardENU = import__607.Matrix4.multiplyByPointAsVector( inverseEnu, import__607.Cartesian3.fromArray(northward.value), new import__607.Cartesian3() ); northwardENU = import__607.Cartesian3.normalize(northwardENU, northwardENU); expect( import__607.Cartesian3.equalsEpsilon( northwardENU, import__607.Cartesian3.UNIT_Y, import__608.Math.EPSILON7 ) ).toBe(true); }); it("provides attributes for computing planes in 2D and Columbus View", function() { const planes2D_HIGH = largeRectangleAttributes.planes2D_HIGH; const planes2D_LOW = largeRectangleAttributes.planes2D_LOW; expect(planes2D_HIGH.componentDatatype).toEqual(import__607.ComponentDatatype.FLOAT); expect(planes2D_HIGH.componentsPerAttribute).toEqual(4); expect(planes2D_HIGH.normalize).toEqual(false); let highValue = planes2D_HIGH.value; expect(highValue[0]).toEqualEpsilon(0, import__608.Math.EPSILON7); expect(highValue[1]).toEqualEpsilon(0, import__608.Math.EPSILON7); expect(highValue[2]).toEqualEpsilon(0, import__608.Math.EPSILON7); expect(highValue[3]).toEqualEpsilon(0, import__608.Math.EPSILON7); expect(planes2D_LOW.componentDatatype).toEqual(import__607.ComponentDatatype.FLOAT); expect(planes2D_LOW.componentsPerAttribute).toEqual(4); expect(planes2D_LOW.normalize).toEqual(false); let cartographic = import__607.Cartographic.fromDegrees(-45, -45, 0); let southwestCartesian = projection.project(cartographic); let lowValue = planes2D_LOW.value; expect(lowValue[0]).toEqualEpsilon( southwestCartesian.x, import__608.Math.EPSILON7 ); expect(lowValue[1]).toEqualEpsilon( southwestCartesian.y, import__608.Math.EPSILON7 ); expect(lowValue[2]).toEqualEpsilon( -southwestCartesian.y, import__608.Math.EPSILON7 ); expect(lowValue[3]).toEqualEpsilon( -southwestCartesian.x, import__608.Math.EPSILON7 ); highValue = smallRectangleAttributes.planes2D_HIGH.value; expect(highValue[0]).toEqualEpsilon(0, import__608.Math.EPSILON7); expect(highValue[1]).toEqualEpsilon(0, import__608.Math.EPSILON7); expect(highValue[2]).toEqualEpsilon(0, import__608.Math.EPSILON7); expect(highValue[3]).toEqualEpsilon(0, import__608.Math.EPSILON7); cartographic = import__607.Cartographic.fromDegrees(-0.1, -0.1, 0); southwestCartesian = projection.project(cartographic); lowValue = smallRectangleAttributes.planes2D_LOW.value; expect(lowValue[0]).toEqualEpsilon( southwestCartesian.x, import__608.Math.EPSILON7 ); expect(lowValue[1]).toEqualEpsilon( southwestCartesian.y, import__608.Math.EPSILON7 ); expect(lowValue[2]).toEqualEpsilon( -southwestCartesian.y, import__608.Math.EPSILON7 ); expect(lowValue[3]).toEqualEpsilon( -southwestCartesian.x, import__608.Math.EPSILON7 ); }); it("provides attributes for rotating texture coordinates", function() { const attributes = import__607.ShadowVolumeAppearance.getPlanarTextureCoordinateAttributes( smallTestRectangle, [1, 0, 0, 0, 1, 1], unitSphereEllipsoid, projection, 0 ); const uMaxVmax = attributes.uMaxVmax; const uvMinAndExtents = attributes.uvMinAndExtents; expect(uMaxVmax.componentDatatype).toEqual(import__607.ComponentDatatype.FLOAT); expect(uMaxVmax.componentsPerAttribute).toEqual(4); expect(uMaxVmax.normalize).toEqual(false); expect(uvMinAndExtents.componentDatatype).toEqual(import__607.ComponentDatatype.FLOAT); expect(uvMinAndExtents.componentsPerAttribute).toEqual(4); expect(uvMinAndExtents.normalize).toEqual(false); let value = uMaxVmax.value; expect(value[0]).toEqual(0); expect(value[1]).toEqual(0); expect(value[2]).toEqual(1); expect(value[3]).toEqual(1); value = uvMinAndExtents.value; expect(value[0]).toEqual(1); expect(value[1]).toEqual(0); expect(value[2]).toEqual(1); expect(value[3]).toEqual(1); }); it("checks for spherical extent attributes", function() { expect( import__607.ShadowVolumeAppearance.hasAttributesForSphericalExtents( smallRectangleAttributes ) ).toBe(false); expect( import__607.ShadowVolumeAppearance.hasAttributesForSphericalExtents( largeRectangleAttributes ) ).toBe(true); }); it("checks for planar texture coordinate attributes", function() { expect( import__607.ShadowVolumeAppearance.hasAttributesForTextureCoordinatePlanes( smallRectangleAttributes ) ).toBe(true); expect( import__607.ShadowVolumeAppearance.hasAttributesForTextureCoordinatePlanes( largeRectangleAttributes ) ).toBe(false); }); it("checks if a rectangle should use spherical texture coordinates", function() { expect( import__607.ShadowVolumeAppearance.shouldUseSphericalCoordinates(smallTestRectangle) ).toBe(false); expect( import__607.ShadowVolumeAppearance.shouldUseSphericalCoordinates(largeTestRectangle) ).toBe(true); }); it("creates vertex shaders for color", function() { const sphericalTexturedAppearance = new import__607.ShadowVolumeAppearance( true, false, textureMaterialAppearance ); let shaderSource = sphericalTexturedAppearance.createVertexShader( [], testVs, false, projection ); let defines = shaderSource.defines; expect(defines.length).toEqual(2); expect(defines.indexOf("TEXTURE_COORDINATES")).not.toEqual(-1); expect(defines.indexOf("SPHERICAL")).not.toEqual(-1); shaderSource = sphericalTexturedAppearance.createVertexShader( [], testVs, true, projection ); defines = shaderSource.defines; expect(defines.length).toEqual(6); expect(defines.indexOf("TEXTURE_COORDINATES")).not.toEqual(-1); expect(defines.indexOf("COLUMBUS_VIEW_2D")).not.toEqual(-1); expect(defines.indexOf(eastMostYhighDefine)).not.toEqual(-1); expect(defines.indexOf(eastMostYlowDefine)).not.toEqual(-1); expect(defines.indexOf(westMostYhighDefine)).not.toEqual(-1); expect(defines.indexOf(westMostYlowDefine)).not.toEqual(-1); const sphericalUnculledColorAppearance = new import__607.ShadowVolumeAppearance( false, false, perInstanceColorMaterialAppearance ); shaderSource = sphericalUnculledColorAppearance.createVertexShader( [], testVs, false, projection ); defines = shaderSource.defines; expect(defines.length).toEqual(1); expect(defines.indexOf("PER_INSTANCE_COLOR")).not.toEqual(-1); shaderSource = sphericalUnculledColorAppearance.createVertexShader( [], testVs, true, projection ); defines = shaderSource.defines; expect(defines.length).toEqual(5); expect(defines.indexOf(eastMostYhighDefine)).not.toEqual(-1); expect(defines.indexOf(eastMostYlowDefine)).not.toEqual(-1); expect(defines.indexOf(westMostYhighDefine)).not.toEqual(-1); expect(defines.indexOf(westMostYlowDefine)).not.toEqual(-1); expect(defines.indexOf("PER_INSTANCE_COLOR")).not.toEqual(-1); const planarTexturedAppearance = new import__607.ShadowVolumeAppearance( false, true, textureMaterialAppearance ); shaderSource = planarTexturedAppearance.createVertexShader( [], testVs, false, projection ); defines = shaderSource.defines; expect(defines.indexOf("TEXTURE_COORDINATES")).not.toEqual(-1); expect(defines.length).toEqual(1); shaderSource = planarTexturedAppearance.createVertexShader( [], testVs, true, projection ); defines = shaderSource.defines; expect(defines.indexOf("TEXTURE_COORDINATES")).not.toEqual(-1); expect(defines.indexOf("COLUMBUS_VIEW_2D")).not.toEqual(-1); expect(defines.indexOf(eastMostYhighDefine)).not.toEqual(-1); expect(defines.indexOf(eastMostYlowDefine)).not.toEqual(-1); expect(defines.indexOf(westMostYhighDefine)).not.toEqual(-1); expect(defines.indexOf(westMostYlowDefine)).not.toEqual(-1); expect(defines.length).toEqual(6); }); it("creates vertex shaders for pick", function() { const sphericalTexturedAppearance = new import__607.ShadowVolumeAppearance( true, false, textureMaterialAppearance ); let shaderSource = sphericalTexturedAppearance.createPickVertexShader( [], testVs, false, projection ); let defines = shaderSource.defines; expect(defines.length).toEqual(2); expect(defines.indexOf("TEXTURE_COORDINATES")).not.toEqual(-1); expect(defines.indexOf("SPHERICAL")).not.toEqual(-1); shaderSource = sphericalTexturedAppearance.createPickVertexShader( [], testVs, true, projection ); defines = shaderSource.defines; expect(defines.length).toEqual(6); expect(defines.indexOf("TEXTURE_COORDINATES")).not.toEqual(-1); expect(defines.indexOf("COLUMBUS_VIEW_2D")).not.toEqual(-1); expect(defines.indexOf(eastMostYhighDefine)).not.toEqual(-1); expect(defines.indexOf(eastMostYlowDefine)).not.toEqual(-1); expect(defines.indexOf(westMostYhighDefine)).not.toEqual(-1); expect(defines.indexOf(westMostYlowDefine)).not.toEqual(-1); const sphericalUnculledColorAppearance = new import__607.ShadowVolumeAppearance( false, false, perInstanceColorMaterialAppearance ); shaderSource = sphericalUnculledColorAppearance.createPickVertexShader( [], testVs, false, projection ); defines = shaderSource.defines; expect(defines.length).toEqual(0); shaderSource = sphericalUnculledColorAppearance.createPickVertexShader( [], testVs, true, projection ); defines = shaderSource.defines; expect(defines.indexOf(eastMostYhighDefine)).not.toEqual(-1); expect(defines.indexOf(eastMostYlowDefine)).not.toEqual(-1); expect(defines.indexOf(westMostYhighDefine)).not.toEqual(-1); expect(defines.indexOf(westMostYlowDefine)).not.toEqual(-1); expect(defines.length).toEqual(4); const planarTexturedAppearance = new import__607.ShadowVolumeAppearance( false, true, textureMaterialAppearance ); shaderSource = planarTexturedAppearance.createPickVertexShader( [], testVs, false, projection ); defines = shaderSource.defines; expect(defines.length).toEqual(0); shaderSource = planarTexturedAppearance.createPickVertexShader( [], testVs, true, projection ); defines = shaderSource.defines; expect(defines.indexOf(eastMostYhighDefine)).not.toEqual(-1); expect(defines.indexOf(eastMostYlowDefine)).not.toEqual(-1); expect(defines.indexOf(westMostYhighDefine)).not.toEqual(-1); expect(defines.indexOf(westMostYlowDefine)).not.toEqual(-1); expect(defines.length).toEqual(4); }); it("creates fragment shaders for color and pick", function() { const sphericalTexturedAppearance = new import__607.ShadowVolumeAppearance( true, false, textureMaterialAppearance ); let shaderSource = sphericalTexturedAppearance.createFragmentShader(false); let defines = shaderSource.defines; expect(defines.indexOf("SPHERICAL")).not.toEqual(-1); expect(defines.indexOf("REQUIRES_EC")).not.toEqual(-1); expect(defines.indexOf("REQUIRES_WC")).not.toEqual(-1); expect(defines.indexOf("TEXTURE_COORDINATES")).not.toEqual(-1); expect(defines.indexOf("CULL_FRAGMENTS")).not.toEqual(-1); expect(defines.indexOf("NORMAL_EC")).not.toEqual(-1); expect(defines.indexOf("USES_NORMAL_EC")).not.toEqual(-1); expect(defines.indexOf("USES_POSITION_TO_EYE_EC")).not.toEqual(-1); expect(defines.indexOf("USES_TANGENT_TO_EYE")).not.toEqual(-1); expect(defines.indexOf("USES_ST")).not.toEqual(-1); expect(defines.length).toEqual(10); shaderSource = sphericalTexturedAppearance.createFragmentShader(true); defines = shaderSource.defines; expect(defines.indexOf("REQUIRES_EC")).not.toEqual(-1); expect(defines.indexOf("REQUIRES_WC")).not.toEqual(-1); expect(defines.indexOf("TEXTURE_COORDINATES")).not.toEqual(-1); expect(defines.indexOf("CULL_FRAGMENTS")).not.toEqual(-1); expect(defines.indexOf("NORMAL_EC")).not.toEqual(-1); expect(defines.indexOf("USES_NORMAL_EC")).not.toEqual(-1); expect(defines.indexOf("USES_POSITION_TO_EYE_EC")).not.toEqual(-1); expect(defines.indexOf("USES_TANGENT_TO_EYE")).not.toEqual(-1); expect(defines.indexOf("USES_ST")).not.toEqual(-1); expect(defines.length).toEqual(9); const planarColorAppearance = new import__607.ShadowVolumeAppearance( true, true, perInstanceColorMaterialAppearance ); shaderSource = planarColorAppearance.createFragmentShader(false); defines = shaderSource.defines; expect(defines.indexOf("PER_INSTANCE_COLOR")).not.toEqual(-1); expect(defines.indexOf("REQUIRES_EC")).not.toEqual(-1); expect(defines.indexOf("REQUIRES_WC")).not.toEqual(-1); expect(defines.indexOf("TEXTURE_COORDINATES")).not.toEqual(-1); expect(defines.indexOf("CULL_FRAGMENTS")).not.toEqual(-1); expect(defines.indexOf("NORMAL_EC")).not.toEqual(-1); expect(defines.length).toEqual(6); shaderSource = planarColorAppearance.createPickFragmentShader(true); defines = shaderSource.defines; expect(defines.indexOf("REQUIRES_EC")).not.toEqual(-1); expect(defines.indexOf("REQUIRES_WC")).not.toEqual(-1); expect(defines.indexOf("TEXTURE_COORDINATES")).not.toEqual(-1); expect(defines.indexOf("CULL_FRAGMENTS")).not.toEqual(-1); expect(defines.indexOf("PICK")).not.toEqual(-1); expect(defines.length).toEqual(5); const flatSphericalTexturedAppearance = new import__607.ShadowVolumeAppearance( true, false, flatTextureMaterialAppearance ); shaderSource = flatSphericalTexturedAppearance.createFragmentShader(false); defines = shaderSource.defines; expect(defines.indexOf("SPHERICAL")).not.toEqual(-1); expect(defines.indexOf("REQUIRES_EC")).not.toEqual(-1); expect(defines.indexOf("REQUIRES_WC")).not.toEqual(-1); expect(defines.indexOf("TEXTURE_COORDINATES")).not.toEqual(-1); expect(defines.indexOf("CULL_FRAGMENTS")).not.toEqual(-1); expect(defines.indexOf("NORMAL_EC")).not.toEqual(-1); expect(defines.indexOf("USES_NORMAL_EC")).not.toEqual(-1); expect(defines.indexOf("USES_POSITION_TO_EYE_EC")).not.toEqual(-1); expect(defines.indexOf("USES_ST")).not.toEqual(-1); expect(defines.indexOf("FLAT")).not.toEqual(-1); expect(defines.length).toEqual(10); const flatSphericalColorAppearance = new import__607.ShadowVolumeAppearance( false, false, flatPerInstanceColorMaterialAppearance ); shaderSource = flatSphericalColorAppearance.createFragmentShader(false); defines = shaderSource.defines; expect(defines.indexOf("SPHERICAL")).not.toEqual(-1); expect(defines.indexOf("PER_INSTANCE_COLOR")).not.toEqual(-1); expect(defines.indexOf("FLAT")).not.toEqual(-1); expect(defines.length).toEqual(3); }); }); // packages/engine/Specs/Scene/SingleTileImageryProviderSpec.js var import__609 = __toESM(require_Cesium(), 1); describe("Scene/SingleTileImageryProvider", function() { afterEach(function() { import__609.Resource._Implementations.createImage = import__609.Resource._DefaultImplementations.createImage; }); it("conforms to ImageryProvider interface", function() { expect(import__609.SingleTileImageryProvider).toConformToInterface(import__609.ImageryProvider); }); it("constructor throws without url", async function() { expect(() => new import__609.SingleTileImageryProvider()).toThrowDeveloperError(); }); it("constructor throws without tile height and tile width", async function() { expect( () => new import__609.SingleTileImageryProvider({ url: "Data/Images/Red16x16.png", tileWidth: 16 }) ).toThrowDeveloperError(); expect( () => new import__609.SingleTileImageryProvider({ url: "Data/Images/Red16x16.png", tileHeight: 16 }) ).toThrowDeveloperError(); }); it("fromUrl throws without url", async function() { await expectAsync( import__609.SingleTileImageryProvider.fromUrl() ).toBeRejectedWithDeveloperError(); }); it("fromUrl resolves to created provider", async function() { const provider = await import__609.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); expect(provider).toBeInstanceOf(import__609.SingleTileImageryProvider); }); it("fromUrl with Resource resolves to created provider", async function() { const resource = new import__609.Resource({ url: "Data/Images/Red16x16.png" }); const provider = await import__609.SingleTileImageryProvider.fromUrl(resource); expect(provider).toBeInstanceOf(import__609.SingleTileImageryProvider); }); it("fromUrl throws on failed request", async function() { await expectAsync( import__609.SingleTileImageryProvider.fromUrl("invalid.image.url") ).toBeRejectedWithError( import__609.RuntimeError, "Failed to load image invalid.image.url" ); }); it("returns valid value for hasAlphaChannel", async function() { const provider = await import__609.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); expect(typeof provider.hasAlphaChannel).toBe("boolean"); }); it("properties are gettable", async function() { const url = "Data/Images/Red16x16.png"; const rectangle = new import__609.Rectangle(0.1, 0.2, 0.3, 0.4); const credit = "hi"; const provider = await import__609.SingleTileImageryProvider.fromUrl(url, { rectangle, credit }); expect(provider.url).toEqual(url); expect(provider.rectangle).toEqual(rectangle); expect(provider.hasAlphaChannel).toEqual(true); expect(provider.tilingScheme).toBeInstanceOf(import__609.GeographicTilingScheme); expect(provider.tilingScheme.rectangle).toEqual(rectangle); expect(provider.tileWidth).toEqual(16); expect(provider.tileHeight).toEqual(16); expect(provider.maximumLevel).toEqual(0); expect(provider.tileDiscardPolicy).toBeUndefined(); }); it("can use a custom ellipsoid", async function() { const ellipsoid = new import__609.Ellipsoid(1, 2, 3); const provider = await import__609.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png", { ellipsoid } ); expect(provider.tilingScheme.ellipsoid).toEqual(ellipsoid); }); it("requests the single image immediately upon construction", async function() { const imageUrl = "Data/Images/Red16x16.png"; spyOn(import__609.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const url = request.url; expect(url).toEqual(imageUrl); import__609.Resource._DefaultImplementations.createImage( request, crossOrigin, deferred ); }); const provider = await import__609.SingleTileImageryProvider.fromUrl(imageUrl); expect(import__609.Resource._Implementations.createImage).toHaveBeenCalled(); const image = await Promise.resolve(provider.requestImage(0, 0, 0)); expect(image).toBeImageOrImageBitmap(); }); it("lazy loads image when constructed with tile height and tile width", async function() { const imageUrl = "Data/Images/Red16x16.png"; spyOn(import__609.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const url = request.url; expect(url).toEqual(imageUrl); import__609.Resource._DefaultImplementations.createImage( request, crossOrigin, deferred ); }); const provider = new import__609.SingleTileImageryProvider({ url: imageUrl, tileHeight: 16, tileWidth: 16 }); expect(import__609.Resource._Implementations.createImage).not.toHaveBeenCalled(); const image = await Promise.resolve(provider.requestImage(0, 0, 0)); expect(image).toBeImageOrImageBitmap(); expect(import__609.Resource._Implementations.createImage).toHaveBeenCalled(); }); it("turns the supplied credit into a logo", async function() { const provider = await import__609.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png" ); expect(provider.credit).toBeUndefined(); const providerWithCredit = await import__609.SingleTileImageryProvider.fromUrl( "Data/Images/Red16x16.png", { credit: "Thanks to our awesome made up source of this imagery!" } ); expect(providerWithCredit.credit).toBeDefined(); }); it("raises error event when image cannot be loaded", function() { const provider = new import__609.SingleTileImageryProvider({ url: "made/up/url", tileHeight: 16, tileWidth: 16 }); const layer = new import__609.ImageryLayer(provider); let tries = 0; provider.errorEvent.addEventListener(function(error) { expect(error.timesRetried).toEqual(tries); ++tries; if (tries < 3) { error.retry = true; } }); import__609.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { if (tries === 2) { import__609.Resource._DefaultImplementations.createImage( new import__609.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); } else { setTimeout(function() { deferred.reject(); }, 1); } }; const imagery = new import__609.Imagery(layer, 0, 0, 0); imagery.addReference(); layer._requestImagery(imagery); return pollToPromise_default(function() { return imagery.state === import__609.ImageryState.RECEIVED; }).then(function() { expect(imagery.image).toBeImageOrImageBitmap(); expect(tries).toEqual(2); imagery.releaseReference(); }); }); }); // packages/engine/Specs/Scene/SkyAtmosphereSpec.js var import__610 = __toESM(require_Cesium(), 1); var import__611 = __toESM(require_Cesium(), 1); describe( "Scene/SkyAtmosphere", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { scene2.mode = import__610.SceneMode.SCENE3D; }); it("draws sky with camera in atmosphere", function() { const s = new import__610.SkyAtmosphere(); expect(scene2).toRender([0, 0, 0, 255]); scene2.render(); const command = s.update(scene2.frameState); expect(command).toBeDefined(); command.execute(scene2.context); s.destroy(); }); it("draws sky with camera in space", function() { const s = new import__610.SkyAtmosphere(); expect(scene2).toRender([0, 0, 0, 255]); scene2.render(); const command = s.update(scene2.frameState); expect(command).toBeDefined(); command.execute(scene2.context); s.destroy(); }); it("draws sky with dynamic lighting (scene light source)", function() { const s = new import__610.SkyAtmosphere(); s.setDynamicLighting(import__610.DynamicAtmosphereLightingType.SCENE_LIGHT); expect(scene2).toRender([0, 0, 0, 255]); scene2.render(); const command = s.update(scene2.frameState); expect(command).toBeDefined(); expect(s._radiiAndDynamicAtmosphereColor.z).toBe(1); command.execute(scene2.context); s.destroy(); }); it("draws sky with dynamic lighting (sunlight)", function() { const s = new import__610.SkyAtmosphere(); s.setDynamicLighting(import__610.DynamicAtmosphereLightingType.SUNLIGHT); expect(scene2).toRender([0, 0, 0, 255]); scene2.render(); const command = s.update(scene2.frameState); expect(command).toBeDefined(); expect(s._radiiAndDynamicAtmosphereColor.z).toBe(2); command.execute(scene2.context); s.destroy(); }); it("draws sky with dynamic lighting off", function() { const s = new import__610.SkyAtmosphere(); s.setDynamicLighting(import__610.DynamicAtmosphereLightingType.NONE); expect(scene2).toRender([0, 0, 0, 255]); scene2.render(); const command = s.update(scene2.frameState); expect(command).toBeDefined(); expect(s._radiiAndDynamicAtmosphereColor.z).toBe(0); command.execute(scene2.context); s.destroy(); }); it("draws sky with color correction active", function() { const oldSkyAtmosphere = scene2.skyAtmosphere; const s = new import__610.SkyAtmosphere(); scene2.skyAtmosphere = s; scene2.environmentState.isReadyForAtmosphere = true; scene2.camera.setView({ destination: import__610.Cartesian3.fromDegrees(-75.5847, 40.0397, 1e3), orientation: { heading: -import__611.Math.PI_OVER_TWO, pitch: 0.2, roll: 0 } }); let color; expect(scene2).toRenderAndCall(function(rgba) { color = rgba; expect(color).not.toEqual([0, 0, 0, 255]); }); s.hueShift = 0.5; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).not.toEqual(color); }); scene2.skyAtmosphere = oldSkyAtmosphere; }); it("does not render when show is false", function() { const s = new import__610.SkyAtmosphere(); s.show = false; expect(scene2).toRender([0, 0, 0, 255]); scene2.render(); const command = s.update(scene2.frameState); expect(command).not.toBeDefined(); }); it("does not render in 2D", function() { const s = new import__610.SkyAtmosphere(); expect(scene2).toRender([0, 0, 0, 255]); scene2.mode = import__610.SceneMode.SCENE2D; scene2.render(); const command = s.update(scene2.frameState); expect(command).not.toBeDefined(); }); it("does not render without a color pass", function() { const s = new import__610.SkyAtmosphere(); scene2.frameState.passes.render = false; const command = s.update(scene2.frameState); expect(command).not.toBeDefined(); }); it("gets ellipsoid", function() { const s = new import__610.SkyAtmosphere(import__610.Ellipsoid.UNIT_SPHERE); expect(s.ellipsoid).toEqual(import__610.Ellipsoid.UNIT_SPHERE); }); it("isDestroyed", function() { const s = new import__610.SkyAtmosphere(); expect(s.isDestroyed()).toEqual(false); s.destroy(); expect(s.isDestroyed()).toEqual(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/SkyBoxSpec.js var import__612 = __toESM(require_Cesium(), 1); describe( "Scene/SkyBox", function() { let scene2; let skyBox; let loadedImage; beforeAll(function() { scene2 = createScene_default(); return import__612.Resource.fetchImage("./Data/Images/Blue.png").then(function(image) { loadedImage = image; }); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { scene2.mode = import__612.SceneMode.SCENE3D; }); afterEach(function() { skyBox = skyBox && skyBox.destroy(); scene2.skyBox = void 0; }); it("draws a sky box from Images", function() { skyBox = new import__612.SkyBox({ sources: { positiveX: loadedImage, negativeX: loadedImage, positiveY: loadedImage, negativeY: loadedImage, positiveZ: loadedImage, negativeZ: loadedImage } }); expect(scene2).toRender([0, 0, 0, 255]); scene2.skyBox = skyBox; expect(scene2).toRender([0, 0, 255, 255]); }); it("does not render when show is false", function() { skyBox = new import__612.SkyBox({ sources: { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" }, show: false }); expect(scene2).toRender([0, 0, 0, 255]); scene2.skyBox = skyBox; expect(scene2).toRender([0, 0, 0, 255]); }); it("does not render in 2D", function() { skyBox = new import__612.SkyBox({ sources: { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" } }); scene2.mode = import__612.SceneMode.SCENE2D; expect(scene2).toRender([0, 0, 0, 255]); scene2.skyBox = skyBox; expect(scene2).toRender([0, 0, 0, 255]); }); it("does not render without a render pass", function() { skyBox = new import__612.SkyBox({ sources: { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" } }); scene2.frameState.passes.render = false; scene2.skyBox = skyBox; const command = skyBox.update(scene2.frameState); expect(command).not.toBeDefined(); }); it("gets constructor options", function() { skyBox = new import__612.SkyBox({ sources: { positiveX: "positiveX.png", negativeX: "negativeX.png", positiveY: "positiveY.png", negativeY: "negativeY.png", positiveZ: "positiveZ.png", negativeZ: "negativeZ.png" }, show: false }); expect(skyBox.sources.positiveX).toEqual("positiveX.png"); expect(skyBox.sources.negativeX).toEqual("negativeX.png"); expect(skyBox.sources.positiveY).toEqual("positiveY.png"); expect(skyBox.sources.negativeY).toEqual("negativeY.png"); expect(skyBox.sources.positiveZ).toEqual("positiveZ.png"); expect(skyBox.sources.negativeZ).toEqual("negativeZ.png"); expect(skyBox.show).toEqual(false); }); it("isDestroyed", function() { skyBox = new import__612.SkyBox({ sources: { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" } }); expect(skyBox.isDestroyed()).toEqual(false); skyBox.destroy(); expect(skyBox.isDestroyed()).toEqual(true); skyBox = void 0; }); it("throws when constructed without positiveX", function() { skyBox = new import__612.SkyBox({ sources: { negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" } }); scene2.skyBox = skyBox; expect(function() { return scene2.render(); }).toThrowDeveloperError(); }); it("throws when constructed without negativeX", function() { skyBox = new import__612.SkyBox({ sources: { positiveX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" } }); scene2.skyBox = skyBox; expect(function() { return scene2.render(); }).toThrowDeveloperError(); }); it("throws when constructed without positiveY", function() { skyBox = new import__612.SkyBox({ sources: { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" } }); scene2.skyBox = skyBox; expect(function() { return scene2.render(); }).toThrowDeveloperError(); }); it("throws when constructed without negativeY", function() { skyBox = new import__612.SkyBox({ sources: { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" } }); scene2.skyBox = skyBox; expect(function() { return scene2.render(); }).toThrowDeveloperError(); }); it("throws when constructed without positiveZ", function() { skyBox = new import__612.SkyBox({ sources: { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" } }); scene2.skyBox = skyBox; expect(function() { return scene2.render(); }).toThrowDeveloperError(); }); it("throws when constructed without negativeZ", function() { skyBox = new import__612.SkyBox({ sources: { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png" } }); scene2.skyBox = skyBox; expect(function() { return scene2.render(); }).toThrowDeveloperError(); }); it("throws when constructed when positiveX is a different type", function() { skyBox = new import__612.SkyBox({ sources: { positiveX: loadedImage, negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" } }); scene2.skyBox = skyBox; expect(function() { return scene2.render(); }).toThrowDeveloperError(); }); it("throws when constructed when negativeX is a different type", function() { skyBox = new import__612.SkyBox({ sources: { positiveX: "./Data/Images/Blue.png", negativeX: loadedImage, positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" } }); scene2.skyBox = skyBox; expect(function() { return scene2.render(); }).toThrowDeveloperError(); }); it("throws when constructed when positiveY is a different type", function() { skyBox = new import__612.SkyBox({ sources: { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", positiveY: loadedImage, negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" } }); scene2.skyBox = skyBox; expect(function() { return scene2.render(); }).toThrowDeveloperError(); }); it("throws when constructed when negativeY is a different type", function() { skyBox = new import__612.SkyBox({ sources: { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: loadedImage, positiveZ: "./Data/Images/Blue.png", negativeZ: "./Data/Images/Blue.png" } }); scene2.skyBox = skyBox; expect(function() { return scene2.render(); }).toThrowDeveloperError(); }); it("throws when constructed when positiveZ is a different type", function() { skyBox = new import__612.SkyBox({ sources: { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: loadedImage, negativeZ: "./Data/Images/Blue.png" } }); scene2.skyBox = skyBox; expect(function() { return scene2.render(); }).toThrowDeveloperError(); }); it("throws when constructed when negativeZ is a different type", function() { skyBox = new import__612.SkyBox({ sources: { positiveX: "./Data/Images/Blue.png", negativeX: "./Data/Images/Blue.png", positiveY: "./Data/Images/Blue.png", negativeY: "./Data/Images/Blue.png", positiveZ: "./Data/Images/Blue.png", negativeZ: loadedImage } }); scene2.skyBox = skyBox; expect(function() { return scene2.render(); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Scene/SpatialNodeSpec.js var import__613 = __toESM(require_Cesium(), 1); describe("Scene/SpatialNode", function() { function getBasicBoxShape() { const shape = new import__613.VoxelBoxShape(); const modelMatrix = import__613.Matrix4.IDENTITY.clone(); const minBounds = import__613.VoxelBoxShape.DefaultMinBounds.clone(); const maxBounds = import__613.VoxelBoxShape.DefaultMaxBounds.clone(); shape.update(modelMatrix, minBounds, maxBounds); return shape; } it("constructs", function() { const shape = getBasicBoxShape(); const level = 2; const x = 1; const y = 2; const z = 3; const parent = void 0; const dimensions = new import__613.Cartesian3(2, 3, 4); const node = new import__613.SpatialNode(level, x, y, z, parent, shape, dimensions); expect(node.level).toEqual(2); expect(node.screenSpaceError).toEqual(0); }); it("returns coordinates of child", function() { const shape = getBasicBoxShape(); const level = 2; const x = 1; const y = 2; const z = 3; const parent = void 0; const dimensions = new import__613.Cartesian3(2, 3, 4); const node = new import__613.SpatialNode(level, x, y, z, parent, shape, dimensions); expect(node.children).toBeUndefined(); node.constructChildNodes(shape, dimensions); expect(node.children.length).toBe(8); const expectedChildCoordinates = [ [3, 2, 4, 6], [3, 3, 4, 6], [3, 2, 5, 6], [3, 3, 5, 6], [3, 2, 4, 7], [3, 3, 4, 7], [3, 2, 5, 7], [3, 3, 5, 7] ]; const actualChildCoordinates = node.children.map((child) => [ child.level, child.x, child.y, child.z ]); expect(actualChildCoordinates).toEqual(expectedChildCoordinates); }); it("computes screen space error", function() { const shape = getBasicBoxShape(); const level = 0; const x = 0; const y = 0; const z = 0; const parent = void 0; const dimensions = new import__613.Cartesian3(2, 3, 4); const node = new import__613.SpatialNode(level, x, y, z, parent, shape, dimensions); const cameraPosition = new import__613.Cartesian3(0, 0, 2); node.computeScreenSpaceError(cameraPosition, 1); expect(node.screenSpaceError).toEqual(1); }); it("adds a keyframe node", function() { const shape = getBasicBoxShape(); const parent = void 0; const dimensions = new import__613.Cartesian3(2, 3, 4); const node = new import__613.SpatialNode(0, 0, 0, 0, parent, shape, dimensions); const numberOfStartingKeyframes = node.keyframeNodes.length; node.createKeyframeNode(0); expect(node.keyframeNodes.length - numberOfStartingKeyframes).toEqual(1); }); }); // packages/engine/Specs/Scene/SphereEmitterSpec.js var import__614 = __toESM(require_Cesium(), 1); describe("Scene/SphereEmitter", function() { let emitter; it("default constructor", function() { emitter = new import__614.SphereEmitter(); expect(emitter.radius).toEqual(1); }); it("constructor", function() { emitter = new import__614.SphereEmitter(5); expect(emitter.radius).toEqual(5); }); it("constructor throws with invalid radius", function() { expect(function() { emitter = new import__614.SphereEmitter(0); }).toThrowDeveloperError(); expect(function() { emitter = new import__614.SphereEmitter(-1); }).toThrowDeveloperError(); }); it("radius setter", function() { emitter = new import__614.SphereEmitter(); emitter.radius = 5; expect(emitter.radius).toEqual(5); }); it("radius setter throws with invalid value", function() { emitter = new import__614.SphereEmitter(); expect(function() { emitter.radius = void 0; }).toThrowDeveloperError(); expect(function() { emitter.radius = 0; }).toThrowDeveloperError(); expect(function() { emitter.radius = -1; }).toThrowDeveloperError(); }); it("emits", function() { emitter = new import__614.SphereEmitter(5); const particle = new import__614.Particle(); for (let i = 0; i < 1e3; ++i) { emitter.emit(particle); expect(import__614.Cartesian3.magnitude(particle.position)).toBeLessThanOrEqual( emitter.radius ); expect(particle.velocity).toEqual( import__614.Cartesian3.normalize(particle.position, new import__614.Cartesian3()) ); } }); }); // packages/engine/Specs/Scene/StructuralMetadataSpec.js var import__615 = __toESM(require_Cesium(), 1); describe("Scene/StructuralMetadata", function() { const propertyTablesSchema = { classes: { building: { properties: { name: { type: "STRING" }, height: { type: "SCALAR", componentType: "FLOAT64" } } }, tree: { properties: { species: { type: "STRING" } } } } }; const propertyTexturesSchema = { classes: { map: { properties: { color: { type: "SCALAR", componentType: "UINT8", array: true, count: 3 }, intensity: { type: "SCALAR", componentType: "UINT8" } } }, ortho: { properties: { vegetation: { type: "SCALAR", componentType: "UINT8", normalized: true } } } } }; const propertyAttributesSchema = { classes: { points: { properties: { color: { type: "VEC3", componentType: "UINT8", array: true, count: 3 }, intensity: { type: "SCALAR", componentType: "UINT8" }, pointSize: { type: "SCALAR", componentTYpe: "FLOAT32" } } } } }; it("creates structural metadata with default values", function() { const metadata = new import__615.StructuralMetadata({ schema: import__615.MetadataSchema.fromJson(propertyTablesSchema) }); expect(metadata.schema).toBeDefined(); expect(metadata.statistics).toBeUndefined(); expect(metadata.extras).toBeUndefined(); expect(metadata.extensions).toBeUndefined(); }); it("creates structural metadata", function() { const mockPropertyTables = [ { id: 0, name: "Buildings", byteLength: 8 }, { id: 1, name: "Trees", byteLength: 16 } ]; const metadata = new import__615.StructuralMetadata({ schema: import__615.MetadataSchema.fromJson(propertyTablesSchema), propertyTables: mockPropertyTables }); expect(metadata.propertyTableCount).toEqual(2); const buildingClass = metadata.schema.classes.building; const treeClass = metadata.schema.classes.tree; expect(buildingClass.id).toBe("building"); expect(treeClass.id).toBe("tree"); const buildingsTable = metadata.getPropertyTable(0); const treesTable = metadata.getPropertyTable(1); expect(buildingsTable).toBe(mockPropertyTables[0]); expect(treesTable).toBe(mockPropertyTables[1]); expect(metadata.propertyTablesByteLength).toBe(24); }); it("creates structural metadata with property textures", function() { const schema = import__615.MetadataSchema.fromJson(propertyTexturesSchema); const mapClass = schema.classes.map; const orthoClass = schema.classes.ortho; const mockTextures = [ { id: 0, name: "Map Texture", class: mapClass }, { id: 1, name: "Ortho Texture", class: orthoClass } ]; const metadata = new import__615.StructuralMetadata({ schema, propertyTextures: mockTextures }); expect(mapClass.id).toBe("map"); expect(orthoClass.id).toBe("ortho"); const mapTexture = metadata.getPropertyTexture(0); const orthoTexture = metadata.getPropertyTexture(1); expect(mapTexture.id).toBe(0); expect(mapTexture.name).toBe("Map Texture"); expect(mapTexture.class).toBe(mapClass); expect(orthoTexture.id).toBe(1); expect(orthoTexture.name).toBe("Ortho Texture"); expect(orthoTexture.class).toBe(orthoClass); expect(metadata.propertyTablesByteLength).toBe(0); }); it("creates structural metadata with property attributes", function() { const schema = import__615.MetadataSchema.fromJson(propertyAttributesSchema); const pointsClass = schema.classes.points; const propertyAttributes = [ new import__615.PropertyAttribute({ class: pointsClass, name: "Points", id: 0, propertyAttribute: { properties: { color: { attribute: "_COLOR" }, intensity: { attribute: "_INTENSITY" }, pointSize: { attribute: "_POINT_SIZE" } } } }) ]; const metadata = new import__615.StructuralMetadata({ schema, propertyAttributes }); expect(pointsClass.id).toBe("points"); const propertyAttribute = metadata.getPropertyAttribute(0); expect(propertyAttribute).toBe(propertyAttributes[0]); expect(propertyAttribute.id).toBe(0); expect(propertyAttribute.name).toBe("Points"); expect(propertyAttribute.class).toBe(pointsClass); expect(propertyAttribute.getProperty("color").attribute).toBe("_COLOR"); expect(propertyAttribute.getProperty("intensity").attribute).toBe( "_INTENSITY" ); expect(propertyAttribute.getProperty("pointSize").attribute).toBe( "_POINT_SIZE" ); expect(metadata.propertyTablesByteLength).toBe(0); }); it("creates structural metadata with extras", function() { const extras = { date: "2021-04-14" }; const metadata = new import__615.StructuralMetadata({ extras, schema: import__615.MetadataSchema.fromJson(propertyTablesSchema) }); expect(metadata.extras).toBe(extras); }); it("creates structural metadata with extensions", function() { const extensions = { "3DTILES_extension": {} }; const metadata = new import__615.StructuralMetadata({ extensions, schema: import__615.MetadataSchema.fromJson(propertyTablesSchema) }); expect(metadata.extensions).toBe(extensions); }); it("creates structural metadata with statistics", function() { const statistics = { classes: { tree: { count: 100, properties: { height: { min: 10, max: 20 } } } } }; const metadata = new import__615.StructuralMetadata({ statistics, schema: import__615.MetadataSchema.fromJson(propertyTablesSchema) }); expect(metadata.statistics).toBe(statistics); }); it("getPropertyTable throws without propertyTableId", function() { const metadata = new import__615.StructuralMetadata({ extension: {}, schema: import__615.MetadataSchema.fromJson(propertyTablesSchema) }); expect(function() { metadata.getPropertyTable(); }).toThrowDeveloperError(); }); it("getPropertyTexture throws without propertyTextureId", function() { const metadata = new import__615.StructuralMetadata({ extension: {}, schema: import__615.MetadataSchema.fromJson(propertyTexturesSchema) }); expect(function() { metadata.getPropertyTexture(); }).toThrowDeveloperError(); }); it("getPropertyAttribute throws without propertyAttributeId", function() { const metadata = new import__615.StructuralMetadata({ extension: {}, schema: import__615.MetadataSchema.fromJson(propertyAttributesSchema) }); expect(function() { metadata.getPropertyAttribute(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/StyleExpressionSpec.js var import__616 = __toESM(require_Cesium(), 1); describe("Scene/StyleExpression", function() { function MockFeature() { } MockFeature.prototype.getPropertyInherited = function(name) { return void 0; }; it("throws", function() { const expression = new import__616.StyleExpression(); const feature = new MockFeature(); expect(function() { return expression.evaluate(feature); }).toThrowDeveloperError(); expect(function() { return expression.evaluateColor(feature); }).toThrowDeveloperError(); expect(function() { return expression.getShaderFunction("getColor()", {}, {}, "vec4"); }).toThrowDeveloperError(); expect(function() { return expression.getVariables(""); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/SunLightSpec.js var import__617 = __toESM(require_Cesium(), 1); describe("Scene/SunLight", function() { it("constructs with default options", function() { const light = new import__617.SunLight(); expect(light.color).toEqual(import__617.Color.WHITE); expect(light.intensity).toBe(2); }); it("constructs with all options", function() { const light = new import__617.SunLight({ color: import__617.Color.RED, intensity: 2 }); expect(light.color).toEqual(import__617.Color.RED); expect(light.color).not.toBe(import__617.Color.RED); expect(light.intensity).toBe(2); }); }); // packages/engine/Specs/Scene/SunSpec.js var import__618 = __toESM(require_Cesium(), 1); var import__619 = __toESM(require_Cesium(), 1); describe( "Scene/Sun", function() { let scene2; const backgroundColor = [255, 0, 0, 255]; beforeAll(function() { scene2 = createScene_default(); scene2.backgroundColor = import__618.Color.unpack(backgroundColor); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { scene2.mode = import__618.SceneMode.SCENE3D; }); afterEach(function() { scene2.sun = void 0; }); function viewSun(camera, uniformState) { const sunPosition = uniformState.sunPositionWC; const bounds = new import__618.BoundingSphere(sunPosition, import__619.Math.SOLAR_RADIUS); camera.viewBoundingSphere(bounds); } it("draws in 3D", function() { expect(scene2).toRender(backgroundColor); scene2.sun = new import__618.Sun(); scene2.sun.glowFactor = 100; scene2.render(); viewSun(scene2.camera, scene2.context.uniformState); expect(scene2).notToRender(backgroundColor); }); it("draws in Columbus view", function() { expect(scene2).toRender(backgroundColor); scene2.mode = import__618.SceneMode.COLUMBUS_VIEW; scene2.sun = new import__618.Sun(); scene2.render(); viewSun(scene2.camera, scene2.context.uniformState); expect(scene2).notToRender(backgroundColor); }); it("does not render when show is false", function() { expect(scene2).toRender(backgroundColor); scene2.sun = new import__618.Sun(); scene2.render(); scene2.sun.show = false; viewSun(scene2.camera, scene2.context.uniformState); expect(scene2).toRender(backgroundColor); }); it("does not render in 2D", function() { expect(scene2).toRender(backgroundColor); scene2.mode = import__618.SceneMode.SCENE2D; scene2.sun = new import__618.Sun(); scene2.render(); viewSun(scene2.camera, scene2.context.uniformState); expect(scene2).toRender(backgroundColor); }); it("does not render without a render pass", function() { scene2.sun = new import__618.Sun(); scene2.render(); viewSun(scene2.camera, scene2.context.uniformState); scene2.frameState.passes.render = false; const command = scene2.sun.update(scene2.frameState, scene2.view.passState); expect(command).not.toBeDefined(); }); it("can set glow factor", function() { const sun = scene2.sun = new import__618.Sun(); sun.glowFactor = 0; expect(sun.glowFactor).toEqual(0); sun.glowFactor = 2; expect(sun.glowFactor).toEqual(2); }); it("draws without lens flare", function() { expect(scene2).toRender(backgroundColor); scene2.sun = new import__618.Sun(); scene2.sun.glowFactor = 0; scene2.renderForSpecs(); viewSun(scene2.camera, scene2.context.uniformState); expect(scene2).notToRender(backgroundColor); }); it("isDestroyed", function() { const sun = new import__618.Sun(); expect(sun.isDestroyed()).toEqual(false); sun.destroy(); expect(sun.isDestroyed()).toEqual(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/SupportedImageFormatsSpec.js var import__620 = __toESM(require_Cesium(), 1); describe("Scene/SupportedImageFormats", function() { it("constructs with options", function() { const supportedImageFormats = new import__620.SupportedImageFormats({ webp: true, basis: false }); expect(supportedImageFormats.webp).toBe(true); expect(supportedImageFormats.basis).toBe(false); }); it("constructs with default values", function() { const supportedImageFormats = new import__620.SupportedImageFormats({}); expect(supportedImageFormats.webp).toBe(false); expect(supportedImageFormats.basis).toBe(false); }); }); // packages/engine/Specs/Scene/TerrainFillMeshSpec.js var import__621 = __toESM(require_Cesium(), 1); var import__622 = __toESM(require_Cesium(), 1); describe("Scene/TerrainFillMesh", function() { let processor; let scene2; let camera; let frameState2; let imageryLayerCollection; let surfaceShaderSet; let mockTerrain; let tileProvider; let quadtree; let rootTiles; let center; let west; let south; let east; let north; let southwest; let southeast; let northwest; let northeast; beforeEach(function() { scene2 = { mapProjection: new import__621.GeographicProjection(), drawingBufferWidth: 1e3, drawingBufferHeight: 1e3 }; camera = new import__621.Camera(scene2); frameState2 = { frameNumber: 0, passes: { render: true }, camera, fog: { enabled: false }, context: { drawingBufferWidth: scene2.drawingBufferWidth, drawingBufferHeight: scene2.drawingBufferHeight }, mode: import__621.SceneMode.SCENE3D, commandList: [], cullingVolume: jasmine.createSpyObj("CullingVolume", [ "computeVisibility" ]), afterRender: [] }; frameState2.cullingVolume.computeVisibility.and.returnValue( import__621.Intersect.INTERSECTING ); imageryLayerCollection = new import__621.ImageryLayerCollection(); surfaceShaderSet = jasmine.createSpyObj("SurfaceShaderSet", [ "getShaderProgram" ]); mockTerrain = new MockTerrainProvider_default(); tileProvider = new import__621.GlobeSurfaceTileProvider({ terrainProvider: mockTerrain, imageryLayers: imageryLayerCollection, surfaceShaderSet }); quadtree = new import__621.QuadtreePrimitive({ tileProvider }); processor = new TerrainTileProcessor_default( frameState2, mockTerrain, imageryLayerCollection ); processor.mockWebGL(); quadtree.render(frameState2); rootTiles = quadtree._levelZeroTiles; center = rootTiles[0].northeastChild.southwestChild.northeastChild.southwestChild; west = center.findTileToWest(rootTiles); south = center.findTileToSouth(rootTiles); east = center.findTileToEast(rootTiles); north = center.findTileToNorth(rootTiles); southwest = west.findTileToSouth(rootTiles); southeast = east.findTileToSouth(rootTiles); northwest = west.findTileToNorth(rootTiles); northeast = east.findTileToNorth(rootTiles); mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 3, height: 3, createdByUpsampling: false, buffer: new Float32Array([ 15, 16, 17, 22, 23, 24, 29, 30, 31 ]) }), west ).createMeshWillSucceed(west); mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 3, height: 3, createdByUpsampling: false, buffer: new Float32Array([ 31, 32, 33, 38, 39, 40, 45, 46, 47 ]) }), south ).createMeshWillSucceed(south); mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 3, height: 3, createdByUpsampling: false, buffer: new Float32Array([ 19, 20, 21, 26, 27, 28, 33, 34, 35 ]) }), east ).createMeshWillSucceed(east); mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 3, height: 3, createdByUpsampling: false, buffer: new Float32Array([ 3, 4, 5, 10, 11, 12, 17, 18, 19 ]) }), north ).createMeshWillSucceed(north); mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 3, height: 3, createdByUpsampling: false, buffer: new Float32Array([ 29, 30, 31, 36, 37, 38, 43, 44, 45 ]) }), southwest ).createMeshWillSucceed(southwest); mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 3, height: 3, createdByUpsampling: false, buffer: new Float32Array([ 33, 34, 35, 40, 41, 42, 47, 48, 49 ]) }), southeast ).createMeshWillSucceed(southeast); mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 3, height: 3, createdByUpsampling: false, buffer: new Float32Array([ 1, 2, 3, 8, 9, 10, 15, 16, 17 ]) }), northwest ).createMeshWillSucceed(northwest); mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 3, height: 3, createdByUpsampling: false, buffer: new Float32Array([ 5, 6, 7, 12, 13, 14, 19, 20, 21 ]) }), northeast ).createMeshWillSucceed(northeast); }); describe("updateFillTiles", function() { it("does nothing if no rendered tiles are provided", function() { expect(function() { import__621.TerrainFillMesh.updateFillTiles(tileProvider, [], frameState2); }).not.toThrow(); }); it("propagates edges and corners to an unloaded tile", function() { const tiles = [ center, west, south, east, north, southwest, southeast, northwest, northeast ]; tiles.forEach(mockTerrain.createMeshWillSucceed.bind(mockTerrain)); return processor.process(tiles).then(function() { tiles.forEach(markRendered); import__621.TerrainFillMesh.updateFillTiles(tileProvider, tiles, frameState2); const fill = center.data.fill; expect(fill).toBeDefined(); expect(fill.westTiles).toEqual([west]); expect(fill.westMeshes).toEqual([west.data.mesh]); expect(fill.southTiles).toEqual([south]); expect(fill.southMeshes).toEqual([south.data.mesh]); expect(fill.eastTiles).toEqual([east]); expect(fill.eastMeshes).toEqual([east.data.mesh]); expect(fill.northTiles).toEqual([north]); expect(fill.northMeshes).toEqual([north.data.mesh]); expect(fill.southwestTile).toEqual(southwest); expect(fill.southwestMesh).toEqual(southwest.data.mesh); expect(fill.southeastTile).toEqual(southeast); expect(fill.southeastMesh).toEqual(southeast.data.mesh); expect(fill.northwestTile).toEqual(northwest); expect(fill.northwestMesh).toEqual(northwest.data.mesh); expect(fill.northeastTile).toEqual(northeast); expect(fill.northeastMesh).toEqual(northeast.data.mesh); }); }); it("propagates fill tile edges to an unloaded tile", function() { const centerSW = center.southwestChild; const centerSE = center.southeastChild; const centerNW = center.northwestChild; const centerNE = center.northeastChild; const tiles = [ centerSW, centerSE, centerNW, centerNE, west, south, east, north, southwest, southeast, northwest, northeast ]; tiles.forEach(mockTerrain.createMeshWillSucceed.bind(mockTerrain)); return processor.process(tiles).then(function() { tiles.forEach(markRendered); import__621.TerrainFillMesh.updateFillTiles(tileProvider, tiles, frameState2); const sw = centerSW.data.fill; const se = centerSE.data.fill; const nw = centerNW.data.fill; const ne = centerNE.data.fill; expect(sw).toBeDefined(); expect(sw.westTiles).toEqual([west]); expect(sw.westMeshes).toEqual([west.data.mesh]); expect(sw.southTiles).toEqual([south]); expect(sw.southMeshes).toEqual([south.data.mesh]); expect(sw.southwestTile).toEqual(southwest); expect(sw.southwestMesh).toEqual(southwest.data.mesh); expect(sw.southeastTile).toBeUndefined(); expect(sw.southeastMesh).toBeUndefined(); expect(sw.northwestTile).toBeUndefined(); expect(sw.northwestMesh).toBeUndefined(); expect(se).toBeDefined(); expect(se.eastTiles).toEqual([east]); expect(se.eastMeshes).toEqual([east.data.mesh]); expect(se.southTiles).toEqual([south]); expect(se.southMeshes).toEqual([south.data.mesh]); expect(se.southeastTile).toEqual(southeast); expect(se.southeastMesh).toEqual(southeast.data.mesh); expect(se.southwestTile).toBeUndefined(); expect(se.southwestMesh).toBeUndefined(); expect(se.northeastTile).toBeUndefined(); expect(se.northeastMesh).toBeUndefined(); expect(nw).toBeDefined(); expect(nw.westTiles).toEqual([west]); expect(nw.westMeshes).toEqual([west.data.mesh]); expect(nw.northTiles).toEqual([north]); expect(nw.northMeshes).toEqual([north.data.mesh]); expect(nw.northwestTile).toEqual(northwest); expect(nw.northwestMesh).toEqual(northwest.data.mesh); expect(nw.southwestTile).toBeUndefined(); expect(nw.southwestMesh).toBeUndefined(); expect(nw.northeastTile).toBeUndefined(); expect(nw.northeastMesh).toBeUndefined(); expect(ne).toBeDefined(); expect(ne.eastTiles).toEqual([east]); expect(ne.eastMeshes).toEqual([east.data.mesh]); expect(ne.northTiles).toEqual([north]); expect(ne.northMeshes).toEqual([north.data.mesh]); expect(ne.northeastTile).toEqual(northeast); expect(ne.northeastMesh).toEqual(northeast.data.mesh); expect(ne.southeastTile).toBeUndefined(); expect(ne.southeastMesh).toBeUndefined(); expect(ne.northwestTile).toBeUndefined(); expect(ne.northwestMesh).toBeUndefined(); expect( sw.eastTiles[0] === centerSE || se.westTiles[0] === centerSW ).toBe(true); expect( nw.eastTiles[0] === centerNE || ne.westTiles[0] === centerNW ).toBe(true); expect( sw.northTiles[0] === centerNW || nw.southTiles[0] === centerSW ).toBe(true); expect( se.northTiles[0] === centerNE || ne.southTiles[0] === centerSE ).toBe(true); expect( sw.northeastTile === centerNE || ne.southwestTile === centerSW ).toBe(true); expect( nw.southeastTile === centerSE || se.northwestTile === centerNW ).toBe(true); }); }); it("does not touch disconnected tiles", function() { const disconnected = center.southwestChild.northeastChild; const tiles = [ disconnected, west, south, east, north, southwest, southeast, northwest, northeast ]; tiles.forEach(mockTerrain.createMeshWillSucceed.bind(mockTerrain)); return processor.process(tiles).then(function() { tiles.forEach(markRendered); import__621.TerrainFillMesh.updateFillTiles(tileProvider, tiles, frameState2); expect(disconnected.data.fill).toBeUndefined(); }); }); it("propagates multiple adjacent source tiles to a destination edge", function() { const tiles = [center, west, south, east, north]; [west, south, east, north].forEach(function(tile) { tile.children.forEach(function(child) { mockTerrain.willBeUnavailable(child); mockTerrain.upsampleWillSucceed(child); tiles.push(child); }); }); return processor.process(tiles).then(function() { tiles.forEach(markRendered); import__621.TerrainFillMesh.updateFillTiles(tileProvider, tiles, frameState2); const fill = center.data.fill; expect(fill).toBeDefined(); expect(fill.westTiles).toEqual([ west.northeastChild, west.southeastChild ]); expect(fill.southTiles).toEqual([ south.northwestChild, south.northeastChild ]); expect(fill.eastTiles).toEqual([ east.southwestChild, east.northwestChild ]); expect(fill.northTiles).toEqual([ north.southeastChild, north.southwestChild ]); }); }); it("adjusts existing fill tiles when adjacent tiles are loaded", function() { const tiles = [center, west, south, north]; tiles.forEach(mockTerrain.createMeshWillSucceed.bind(mockTerrain)); return processor.process(tiles).then(function() { tiles.forEach(markRendered); import__621.TerrainFillMesh.updateFillTiles(tileProvider, tiles, frameState2); const fill = center.data.fill; expect(fill).toBeDefined(); expect(fill.westTiles).toEqual([west]); expect(fill.westMeshes).toEqual([west.data.mesh]); expect(fill.southTiles).toEqual([south]); expect(fill.southMeshes).toEqual([south.data.mesh]); expect(fill.eastTiles).toEqual([]); expect(fill.eastMeshes).toEqual([]); expect(fill.northTiles).toEqual([north]); expect(fill.northMeshes).toEqual([north.data.mesh]); fill.update(tileProvider, frameState2); expectVertexCount(fill, 8); tiles.push(east); return processor.process(tiles); }).then(function() { tiles.forEach(markRendered); import__621.TerrainFillMesh.updateFillTiles(tileProvider, tiles, frameState2); const fill = center.data.fill; expect(fill).toBeDefined(); expect(fill.westTiles).toEqual([west]); expect(fill.westMeshes).toEqual([west.data.mesh]); expect(fill.southTiles).toEqual([south]); expect(fill.southMeshes).toEqual([south.data.mesh]); expect(fill.eastTiles).toEqual([east]); expect(fill.eastMeshes).toEqual([east.data.mesh]); expect(fill.northTiles).toEqual([north]); expect(fill.northMeshes).toEqual([north.data.mesh]); fill.update(tileProvider, frameState2); expectVertexCount(fill, 9); expectVertex(fill, 1, 0.5, 26); }); }); it("adjusts existing fill tiles when an adjacent fill tile changes", function() { const dontLoad = [east, south, southeast]; dontLoad.forEach( mockTerrain.requestTileGeometryWillDefer.bind(mockTerrain) ); const tiles = [ center, west, south, east, north, southwest, southeast, northwest, northeast ]; return processor.process(tiles).then(function() { tiles.forEach(markRendered); import__621.TerrainFillMesh.updateFillTiles(tileProvider, tiles, frameState2); center.data.fill.update(tileProvider, frameState2); south.data.fill.update(tileProvider, frameState2); east.data.fill.update(tileProvider, frameState2); southeast.data.fill.update(tileProvider, frameState2); expectVertexCount(center.data.fill, 7); expectVertex(center.data.fill, 0, 0, 31); expectVertex(center.data.fill, 0, 0.5, 24); expectVertex(center.data.fill, 0, 1, 17); expectVertex(center.data.fill, 0.5, 1, 18); expectVertex(center.data.fill, 1, 1, 19); expectVertexCount(south.data.fill, 6); expectVertex(south.data.fill, 0, 1, 31); expectVertex(south.data.fill, 0, 0.5, 38); expectVertex(south.data.fill, 0, 0, 45); expectVertexCount(east.data.fill, 6); expectVertex(east.data.fill, 0, 1, 19); expectVertex(east.data.fill, 0.5, 1, 20); expectVertex(east.data.fill, 1, 1, 21); expectVertexCount(southeast.data.fill, 5); expect(getHeight(center.data.fill, 1, 0)).toBe( getHeight(southeast.data.fill, 0, 1) ); expect(getHeight(center.data.fill, 1, 0)).toBe( getHeight(south.data.fill, 1, 1) ); expect(getHeight(center.data.fill, 1, 0)).toBe( getHeight(east.data.fill, 0, 0) ); expect(getHeight(center.data.fill, 1, 1)).toBe( getHeight(east.data.fill, 0, 1) ); expect(getHeight(east.data.fill, 1, 0)).toBe( getHeight(southeast.data.fill, 1, 1) ); expect(getHeight(south.data.fill, 1, 0)).toBe( getHeight(southeast.data.fill, 0, 0) ); mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 3, height: 3, createdByUpsampling: false, buffer: new Float32Array([ 31, 32, 33, 38, 39, 40, 45, 46, 47 ]) }), south ).createMeshWillSucceed(south); return processor.process(tiles); }).then(function() { tiles.forEach(markRendered); import__621.TerrainFillMesh.updateFillTiles(tileProvider, tiles, frameState2); center.data.fill.update(tileProvider, frameState2); east.data.fill.update(tileProvider, frameState2); southeast.data.fill.update(tileProvider, frameState2); expect(south.data.fill).toBeUndefined(); expectVertexCount(center.data.fill, 8); expectVertex(center.data.fill, 0, 0, 31); expectVertex(center.data.fill, 0, 0.5, 24); expectVertex(center.data.fill, 0, 1, 17); expectVertex(center.data.fill, 0.5, 1, 18); expectVertex(center.data.fill, 1, 1, 19); expectVertex(center.data.fill, 1, 0, 33); expectVertexCount(east.data.fill, 6); expectVertex(east.data.fill, 0, 1, 19); expectVertex(east.data.fill, 0.5, 1, 20); expectVertex(east.data.fill, 1, 1, 21); expectVertex(east.data.fill, 0, 0, 33); expectVertexCount(southeast.data.fill, 6); expectVertex(southeast.data.fill, 0, 0, 47); expectVertex(southeast.data.fill, 0, 0.5, 40); expectVertex(southeast.data.fill, 0, 1, 33); expect(getHeight(east.data.fill, 1, 0)).toBe( getHeight(southeast.data.fill, 1, 1) ); }); }); function markRendered(tile) { quadtree._lastSelectionFrameNumber = frameState2.frameNumber; tile._lastSelectionResultFrame = frameState2.frameNumber; tile._lastSelectionResult = import__621.TileSelectionResult.RENDERED; let parent = tile.parent; while (parent) { if (parent._lastSelectionResultFrame !== frameState2.frameNumber) { parent._lastSelectionResultFrame = frameState2.frameNumber; parent._lastSelectionResult = import__621.TileSelectionResult.REFINED; } parent = parent.parent; } } }); describe("update", function() { it("puts a middle height at the four corners and center when there are no adjacent tiles", function() { return processor.process([center]).then(function() { center.data.tileBoundingRegion = new import__621.TileBoundingRegion({ rectangle: center.rectangle, minimumHeight: 1, maximumHeight: 3, computeBoundingVolumes: false }); const fill = center.data.fill = new import__621.TerrainFillMesh(center); fill.update(tileProvider, frameState2); expectVertexCount(fill, 5); expectVertex(fill, 0, 0, 2); expectVertex(fill, 0, 1, 2); expectVertex(fill, 1, 0, 2); expectVertex(fill, 1, 1, 2); expectVertex(fill, 0.5, 0.5, 2); }); }); it("puts zero height at the four corners and center when there are no adjacent tiles and no bounding region", function() { return processor.process([center]).then(function() { const fill = center.data.fill = new import__621.TerrainFillMesh(center); fill.update(tileProvider, frameState2); expectVertexCount(fill, 5); expectVertex(fill, 0, 0, 0); expectVertex(fill, 0, 1, 0); expectVertex(fill, 1, 0, 0); expectVertex(fill, 1, 1, 0); expectVertex(fill, 0.5, 0.5, 0); }); }); it("uses adjacent edge heights", function() { return processor.process([center, west, south, east, north]).then(function() { const fill = center.data.fill = new import__621.TerrainFillMesh(center); fill.westTiles.push(west); fill.westMeshes.push(west.data.mesh); fill.southTiles.push(south); fill.southMeshes.push(south.data.mesh); fill.eastTiles.push(east); fill.eastMeshes.push(east.data.mesh); fill.northTiles.push(north); fill.northMeshes.push(north.data.mesh); fill.update(tileProvider, frameState2); expectVertexCount(fill, 9); expectVertex(fill, 0, 0, 31); expectVertex(fill, 0.5, 0, 32); expectVertex(fill, 1, 0, 33); expectVertex(fill, 0, 0.5, 24); expectVertex(fill, 0.5, 0.5, (33 + 17) / 2); expectVertex(fill, 1, 0.5, 26); expectVertex(fill, 0, 1, 17); expectVertex(fill, 0.5, 1, 18); expectVertex(fill, 1, 1, 19); }); }); it("uses adjacent corner heights if adjacent edges are not available", function() { return processor.process([center, southwest, southeast, northwest, northeast]).then(function() { const fill = center.data.fill = new import__621.TerrainFillMesh(center); fill.southwestTile = southwest; fill.southwestMesh = southwest.data.mesh; fill.southeastTile = southeast; fill.southeastMesh = southeast.data.mesh; fill.northwestTile = northwest; fill.northwestMesh = northwest.data.mesh; fill.northeastTile = northeast; fill.northeastMesh = northeast.data.mesh; fill.update(tileProvider, frameState2); expectVertexCount(fill, 5); expectVertex(fill, 0, 0, 31); expectVertex(fill, 1, 0, 33); expectVertex(fill, 0, 1, 17); expectVertex(fill, 1, 1, 19); expectVertex(fill, 0.5, 0.5, (17 + 33) / 2); }); }); it("finds a suitable corner vertex in a less detailed tile", function() { const sw = center.southwestChild; const se = center.southeastChild; const nw = center.northwestChild; const ne = center.northeastChild; return processor.process([sw, se, nw, ne, west, south, east, north]).then(function() { const fillSW = sw.data.fill = new import__621.TerrainFillMesh(sw); const fillSE = se.data.fill = new import__621.TerrainFillMesh(se); const fillNW = nw.data.fill = new import__621.TerrainFillMesh(nw); const fillNE = ne.data.fill = new import__621.TerrainFillMesh(ne); fillSW.westTiles.push(west); fillSW.westMeshes.push(west.data.mesh); fillSW.southTiles.push(south); fillSW.southMeshes.push(south.data.mesh); fillSE.eastTiles.push(east); fillSE.eastMeshes.push(east.data.mesh); fillSE.southTiles.push(south); fillSE.southMeshes.push(south.data.mesh); fillNW.westTiles.push(west); fillNW.westMeshes.push(west.data.mesh); fillNW.northTiles.push(north); fillNW.northMeshes.push(north.data.mesh); fillNE.eastTiles.push(east); fillNE.eastMeshes.push(east.data.mesh); fillNE.northTiles.push(north); fillNE.northMeshes.push(north.data.mesh); fillSW.update(tileProvider, frameState2); fillSE.update(tileProvider, frameState2); fillNW.update(tileProvider, frameState2); fillNE.update(tileProvider, frameState2); expectVertexCount(fillSW, 5); expectVertex(fillSW, 0, 0, 31); expectVertex(fillSW, 1, 0, 32); expectVertex(fillSW, 0, 1, 24); expectVertex(fillSW, 1, 1, (24 + 32) / 2); expectVertex(fillSW, 0.5, 0.5, (24 + 32) / 2); expectVertexCount(fillSE, 5); expectVertex(fillSE, 0, 0, 32); expectVertex(fillSE, 1, 0, 33); expectVertex(fillSE, 0, 1, (32 + 26) / 2); expectVertex(fillSE, 1, 1, 26); expectVertex(fillSE, 0.5, 0.5, (26 + 33) / 2); expectVertexCount(fillNW, 5); expectVertex(fillNW, 0, 0, 24); expectVertex(fillNW, 1, 0, (18 + 24) / 2); expectVertex(fillNW, 0, 1, 17); expectVertex(fillNW, 1, 1, 18); expectVertex(fillNW, 0.5, 0.5, (17 + 24) / 2); expectVertexCount(fillNE, 5); expectVertex(fillNE, 0, 0, (18 + 26) / 2); expectVertex(fillNE, 1, 0, 26); expectVertex(fillNE, 0, 1, 18); expectVertex(fillNE, 1, 1, 19); expectVertex(fillNE, 0.5, 0.5, (18 + 26) / 2); }); }); it("interpolates a suitable corner vertex from a less detailed tile", function() { const sw = center.southwestChild.southwestChild; const se = center.southeastChild.southeastChild; const nw = center.northwestChild.northwestChild; const ne = center.northeastChild.northeastChild; return processor.process([sw, se, nw, ne, west, south, east, north]).then(function() { const fillSW = sw.data.fill = new import__621.TerrainFillMesh(sw); const fillSE = se.data.fill = new import__621.TerrainFillMesh(se); const fillNW = nw.data.fill = new import__621.TerrainFillMesh(nw); const fillNE = ne.data.fill = new import__621.TerrainFillMesh(ne); fillSW.westTiles.push(west); fillSW.westMeshes.push(west.data.mesh); fillSW.southTiles.push(south); fillSW.southMeshes.push(south.data.mesh); fillSE.eastTiles.push(east); fillSE.eastMeshes.push(east.data.mesh); fillSE.southTiles.push(south); fillSE.southMeshes.push(south.data.mesh); fillNW.westTiles.push(west); fillNW.westMeshes.push(west.data.mesh); fillNW.northTiles.push(north); fillNW.northMeshes.push(north.data.mesh); fillNE.eastTiles.push(east); fillNE.eastMeshes.push(east.data.mesh); fillNE.northTiles.push(north); fillNE.northMeshes.push(north.data.mesh); fillSW.update(tileProvider, frameState2); fillSE.update(tileProvider, frameState2); fillNW.update(tileProvider, frameState2); fillNE.update(tileProvider, frameState2); expectVertexCount(fillSW, 5); expectVertex(fillSW, 0, 0, 31); expectVertex(fillSW, 1, 0, (31 + 32) / 2); expectVertex(fillSW, 0, 1, (31 + 24) / 2); expectVertex( fillSW, 1, 1, ((31 + 32) / 2 + (31 + 24) / 2) / 2 ); expectVertex( fillSW, 0.5, 0.5, ((31 + 32) / 2 + (31 + 24) / 2) / 2 ); expectVertexCount(fillSE, 5); expectVertex(fillSE, 0, 0, (32 + 33) / 2); expectVertex(fillSE, 1, 0, 33); expectVertex( fillSE, 0, 1, ((32 + 33) / 2 + (33 + 26) / 2) / 2 ); expectVertex(fillSE, 1, 1, (33 + 26) / 2); expectVertex(fillSE, 0.5, 0.5, (33 + (33 + 26) / 2) / 2); expectVertexCount(fillNW, 5); expectVertex(fillNW, 0, 0, (17 + 24) / 2); expectVertex( fillNW, 1, 0, ((17 + 18) / 2 + (17 + 24) / 2) / 2 ); expectVertex(fillNW, 0, 1, 17); expectVertex(fillNW, 1, 1, (17 + 18) / 2); expectVertex(fillNW, 0.5, 0.5, (17 + (17 + 24) / 2) / 2); expectVertexCount(fillNE, 5); expectVertex( fillNE, 0, 0, ((19 + 26) / 2 + (18 + 19) / 2) / 2 ); expectVertex(fillNE, 1, 0, (19 + 26) / 2); expectVertex(fillNE, 0, 1, (18 + 19) / 2); expectVertex(fillNE, 1, 1, 19); expectVertex( fillNE, 0.5, 0.5, ((18 + 19) / 2 + (19 + 26) / 2) / 2 ); }); }); it("uses the height of the closest vertex when an edge does not include the corner", function() { const westN = west.northeastChild.southeastChild; const westS = west.southeastChild.northeastChild; const eastN = east.northwestChild.southwestChild; const eastS = east.southwestChild.northwestChild; const northW = north.southwestChild.southeastChild; const northE = north.southeastChild.southwestChild; const southW = south.northwestChild.northeastChild; const southE = south.northeastChild.northwestChild; mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 2, height: 2, createdByUpsampling: false, buffer: new Float32Array([1, 1, 1.5, 1.5]) }), westN ).createMeshWillSucceed(westN); mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 2, height: 2, createdByUpsampling: false, buffer: new Float32Array([1.5, 1.5, 2, 2]) }), westS ).createMeshWillSucceed(westS); mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 2, height: 2, createdByUpsampling: false, buffer: new Float32Array([3, 3, 3.5, 3.5]) }), eastN ).createMeshWillSucceed(eastN); mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 2, height: 2, createdByUpsampling: false, buffer: new Float32Array([3.5, 3.5, 4, 4]) }), eastS ).createMeshWillSucceed(eastS); mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 2, height: 2, createdByUpsampling: false, buffer: new Float32Array([5, 5.5, 5, 5.5]) }), northW ).createMeshWillSucceed(northW); mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 2, height: 2, createdByUpsampling: false, buffer: new Float32Array([5.5, 6, 6.5, 6]) }), northE ).createMeshWillSucceed(northE); mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 2, height: 2, createdByUpsampling: false, buffer: new Float32Array([7, 7.5, 7, 7.5]) }), southW ).createMeshWillSucceed(southW); mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 2, height: 2, createdByUpsampling: false, buffer: new Float32Array([7.5, 8, 7.5, 8]) }), southE ).createMeshWillSucceed(southE); return processor.process([ center, westN, westS, eastN, eastS, northE, northW, southE, southW ]).then(function() { const fill = center.data.fill = new import__621.TerrainFillMesh(center); fill.westTiles.push(westN, westS); fill.westMeshes.push(westN.data.mesh, westS.data.mesh); fill.eastTiles.push(eastS, eastN); fill.eastMeshes.push(eastS.data.mesh, eastN.data.mesh); fill.northTiles.push(northE, northW); fill.northMeshes.push(northE.data.mesh, northW.data.mesh); fill.southTiles.push(southW, southE); fill.southMeshes.push(southW.data.mesh, southE.data.mesh); fill.update(tileProvider, frameState2); expectVertexCount(fill, 17); expectVertex(fill, 0, 0, (2 + 7) / 2); expectVertex(fill, 0, 0.25, 2); expectVertex(fill, 0, 0.5, 1.5); expectVertex(fill, 0, 0.75, 1); expectVertex(fill, 0, 1, (1 + 5) / 2); expectVertex(fill, 1, 0, (4 + 8) / 2); expectVertex(fill, 1, 0.25, 4); expectVertex(fill, 1, 0.5, 3.5); expectVertex(fill, 1, 0.75, 3); expectVertex(fill, 1, 1, (3 + 6) / 2); }); }); describe("correctly transforms texture coordinates across the anti-meridian", function() { let westernHemisphere; let easternHemisphere; beforeEach(function() { westernHemisphere = rootTiles[0].southwestChild.northwestChild.southwestChild.northwestChild; easternHemisphere = rootTiles[1].southeastChild.northeastChild.southeastChild.northeastChild; expect(rootTiles.length).toBe(2); expect(westernHemisphere.x).toBe(0); expect(easternHemisphere.x).toBe(31); }); it("western hemisphere to eastern hemisphere", function() { mockTerrain.requestTileGeometryWillDefer(easternHemisphere); mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 3, height: 3, createdByUpsampling: false, buffer: new Float32Array([ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]) }), westernHemisphere ).createMeshWillSucceed(westernHemisphere); return processor.process([westernHemisphere, easternHemisphere]).then(function() { const fill = easternHemisphere.data.fill = new import__621.TerrainFillMesh( easternHemisphere ); fill.eastTiles.push(westernHemisphere); fill.eastMeshes.push(westernHemisphere.data.mesh); fill.update(tileProvider, frameState2); expectVertexCount(fill, 6); expectVertex(fill, 1, 0, 7); expectVertex(fill, 1, 0.5, 4); expectVertex(fill, 1, 1, 1); }); }); it("eastern hemisphere to western hemisphere", function() { mockTerrain.requestTileGeometryWillSucceedWith( new import__621.HeightmapTerrainData({ width: 3, height: 3, createdByUpsampling: false, buffer: new Float32Array([ 10, 11, 12, 13, 14, 15, 16, 17, 18 ]) }), easternHemisphere ).createMeshWillSucceed(easternHemisphere); mockTerrain.requestTileGeometryWillDefer(westernHemisphere); return processor.process([westernHemisphere, easternHemisphere]).then(function() { const fill = westernHemisphere.data.fill = new import__621.TerrainFillMesh( westernHemisphere ); fill.westTiles.push(easternHemisphere); fill.westMeshes.push(easternHemisphere.data.mesh); fill.update(tileProvider, frameState2); expectVertexCount(fill, 6); expectVertex(fill, 0, 0, 18); expectVertex(fill, 0, 0.5, 15); expectVertex(fill, 0, 1, 12); }); }); }); }); const textureCoordinateScratch = new import__621.Cartesian2(); const positionScratch = new import__621.Cartesian3(); const expectedPositionScratch = new import__621.Cartesian3(); function getHeight(fill, u, v) { const mesh = fill.mesh; const rectangle = fill.tile.rectangle; const encoding = mesh.encoding; const vertices = mesh.vertices; const stride = encoding.stride; const count = mesh.vertices.length / stride; for (let i = 0; i < count; ++i) { const tc = encoding.decodeTextureCoordinates( vertices, i, textureCoordinateScratch ); const vertexHeight = encoding.decodeHeight(vertices, i); const vertexPosition = encoding.decodePosition( vertices, i, positionScratch ); if (Math.abs(u - tc.x) < 1e-5 && Math.abs(v - tc.y) < import__622.Math.EPSILON5) { const longitude = import__622.Math.lerp(rectangle.west, rectangle.east, u); const latitude = import__622.Math.lerp(rectangle.south, rectangle.north, v); const expectedPosition = import__621.Cartesian3.fromRadians( longitude, latitude, vertexHeight, void 0, expectedPositionScratch ); expect(vertexPosition).toEqualEpsilon(expectedPosition, 1); return vertexHeight; } } fail(`Vertex with u=${u}, v=${v} does not exist.`); } function expectVertex(fill, u, v, height) { const vertexHeight = getHeight(fill, u, v); expect(vertexHeight).toEqualEpsilon(height, import__622.Math.EPSILON5); } function expectVertexCount(fill, count) { expect(fill.mesh.vertices.length).toBe(count * fill.mesh.encoding.stride); } }); // packages/engine/Specs/Scene/TerrainSpec.js var import__623 = __toESM(require_Cesium(), 1); describe("Scene/Terrain", function() { it("constructor throws without terrain promise", function() { expect(() => new import__623.Terrain()).toThrowDeveloperError(); }); it("does not throw on error", function() { expect(() => { const terrain = new import__623.Terrain(Promise.reject(new Error("Fail"))); }).not.toThrow(); }); it("readyEvent handles terrain promise success", async function() { let resolve; const promise = new Promise((r) => { resolve = r; }); const terrain = new import__623.Terrain(promise); const terrainProvider = new import__623.EllipsoidTerrainProvider(); let wasCalled = false; terrain.readyEvent.addEventListener((provider) => { expect(provider).toBe(terrainProvider); wasCalled = true; }); resolve(terrainProvider); await promise; expect(wasCalled).toBeTrue(); expect(terrain.provider).toBe(terrainProvider); }); it("errorEvent handles terrain promise failure", async function() { let reject; const promise = new Promise((resolve, r) => { reject = r; }); const terrain = new import__623.Terrain(promise); const error = new Error("Fail"); let wasCalled = false; terrain.errorEvent.addEventListener((e) => { expect(e).toBe(error); wasCalled = true; }); reject(error); await expectAsync(promise).toBeRejected(); expect(wasCalled).toBeTrue(); }); }); // packages/engine/Specs/Scene/TextureAtlasSpec.js var import__624 = __toESM(require_Cesium(), 1); describe( "Scene/TextureAtlas", function() { let scene2; let atlas; let greenImage; let tallGreenImage; let blueImage; let bigRedImage; let bigBlueImage; let bigGreenImage; let greenGuid; let tallGreenGuid; let blueGuid; let bigRedGuid; let bigBlueGuid; let bigGreenGuid; beforeAll(function() { scene2 = createScene_default(); return Promise.all([ import__624.Resource.fetchImage("./Data/Images/Green.png").then(function(image) { greenImage = image; greenGuid = (0, import__624.createGuid)(); }), import__624.Resource.fetchImage("./Data/Images/Green1x4.png").then(function(image) { tallGreenImage = image; tallGreenGuid = (0, import__624.createGuid)(); }), import__624.Resource.fetchImage("./Data/Images/Blue.png").then(function(image) { blueImage = image; blueGuid = (0, import__624.createGuid)(); }), import__624.Resource.fetchImage("./Data/Images/Red16x16.png").then(function(image) { bigRedImage = image; bigRedGuid = (0, import__624.createGuid)(); }), import__624.Resource.fetchImage("./Data/Images/Blue10x10.png").then(function(image) { bigBlueImage = image; bigBlueGuid = (0, import__624.createGuid)(); }), import__624.Resource.fetchImage("./Data/Images/Green4x4.png").then(function(image) { bigGreenImage = image; bigGreenGuid = (0, import__624.createGuid)(); }) ]); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { atlas = atlas && atlas.destroy(); }); function expectToRender(texture, textureCoordinates, expected) { const x = textureCoordinates.x + textureCoordinates.width / 2; const y = textureCoordinates.y + textureCoordinates.height / 2; const fs = `${"uniform sampler2D u_texture;void main() { out_FragColor = texture(u_texture, vec2("}${x}, ${y}));}`; const uniformMap = { u_texture: function() { return texture; } }; expect({ context: scene2.context, fragmentShader: fs, uniformMap }).contextToRender(expected); } it("creates a single image atlas", function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 0, initialSize: new import__624.Cartesian2(1, 1) }); return atlas.addImage(greenGuid, greenImage).then(function(index) { expect(index).toEqual(0); expect(atlas.numberOfImages).toEqual(1); expect(atlas.borderWidthInPixels).toEqual(0); const texture = atlas.texture; const atlasWidth = 2; const atlasHeight = 2; expect(texture.pixelFormat).toEqual(import__624.PixelFormat.RGBA); expect(texture.width).toEqual(atlasWidth); expect(texture.height).toEqual(atlasHeight); const coords = atlas.textureCoordinates[index]; expect(coords.x).toEqual(0 / atlasWidth); expect(coords.y).toEqual(0 / atlasHeight); expect(coords.width).toEqual(1 / atlasWidth); expect(coords.height).toEqual(1 / atlasHeight); }); }); it("renders a single image atlas", function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 0, initialSize: new import__624.Cartesian2(1, 1) }); return atlas.addImage(greenGuid, greenImage).then(function(index) { const texture = atlas.texture; const coords = atlas.textureCoordinates[index]; expectToRender(texture, coords, [0, 255, 0, 255]); }); }); it("creates a single image atlas with default values", function() { atlas = new import__624.TextureAtlas({ context: scene2.context }); return atlas.addImage(greenGuid, greenImage).then(function(index) { expect(index).toEqual(0); expect(atlas.numberOfImages).toEqual(1); expect(atlas.borderWidthInPixels).toEqual(1); const texture = atlas.texture; const atlasWidth = 16; const atlasHeight = 16; expect(texture.pixelFormat).toEqual(import__624.PixelFormat.RGBA); expect(texture.width).toEqual(atlasWidth); expect(texture.height).toEqual(atlasHeight); const coords = atlas.textureCoordinates[index]; expect(coords.x).toEqual(1 / atlasWidth); expect(coords.y).toEqual(1 / atlasHeight); expect(coords.width).toEqual(1 / atlasWidth); expect(coords.height).toEqual(1 / atlasHeight); }); }); it("renders a single image atlas with default values", function() { atlas = new import__624.TextureAtlas({ context: scene2.context }); return atlas.addImage(greenGuid, greenImage).then(function(index) { const texture = atlas.texture; const coords = atlas.textureCoordinates[index]; expectToRender(texture, coords, [0, 255, 0, 255]); }); }); it("creates a single image atlas with non-square initialSize", function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 0, initialSize: new import__624.Cartesian2(1, 5) }); return atlas.addImage(tallGreenGuid, tallGreenImage).then(function(index) { expect(index).toEqual(0); expect(atlas.numberOfImages).toEqual(1); const texture = atlas.texture; const atlasWidth = 2; const atlasHeight = 8; expect(texture.width).toEqual(atlasWidth); expect(texture.height).toEqual(atlasHeight); const coords = atlas.textureCoordinates[index]; expect(coords.x).toEqual(0 / atlasWidth); expect(coords.y).toEqual(0 / atlasHeight); expect(coords.width).toEqual(1 / atlasWidth); expect(coords.height).toEqual(4 / atlasHeight); }); }); it("renders a single image atlas with non-square initialSize", function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 0, initialSize: new import__624.Cartesian2(1, 5) }); return atlas.addImage(tallGreenGuid, tallGreenImage).then(function(index) { const texture = atlas.texture; const coords = atlas.textureCoordinates[index]; expectToRender(texture, coords, [0, 255, 0, 255]); }); }); it("creates a two image atlas", async function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 0, initialSize: new import__624.Cartesian2(2, 2) }); const greenIndex = await atlas.addImage(greenGuid, greenImage); const blueIndex = await atlas.addImage(blueGuid, blueImage); expect(atlas.numberOfImages).toEqual(2); const texture = atlas.texture; const atlasWidth = 2; const atlasHeight = 2; expect(texture.width).toEqual(atlasWidth); expect(texture.height).toEqual(atlasHeight); const greenCoords = atlas.textureCoordinates[greenIndex]; expect(greenCoords.x).toEqual(0 / atlasWidth); expect(greenCoords.y).toEqual(0 / atlasHeight); expect(greenCoords.width).toEqual(1 / atlasWidth); expect(greenCoords.height).toEqual(1 / atlasHeight); const blueCoords = atlas.textureCoordinates[blueIndex]; expect(blueCoords.x).toEqual(1 / atlasWidth); expect(blueCoords.y).toEqual(0 / atlasHeight); expect(blueCoords.width).toEqual(1 / atlasWidth); expect(blueCoords.height).toEqual(1 / atlasHeight); }); it("renders a two image atlas", async function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 0, initialSize: new import__624.Cartesian2(2, 2) }); const greenIndex = await atlas.addImage(greenGuid, greenImage); const blueIndex = await atlas.addImage(blueGuid, blueImage); const texture = atlas.texture; const greenCoords = atlas.textureCoordinates[greenIndex]; expectToRender(texture, greenCoords, [0, 255, 0, 255]); const blueCoords = atlas.textureCoordinates[blueIndex]; expectToRender(texture, blueCoords, [0, 0, 255, 255]); }); it("renders a four image atlas", async function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 0 }); const greenIndex = await atlas.addImage(greenGuid, greenImage); const blueIndex = await atlas.addImage(blueGuid, blueImage); const bigRedIndex = await atlas.addImage(bigRedGuid, bigRedImage); const bigBlueIndex = await atlas.addImage(bigBlueGuid, bigBlueImage); expect(atlas.numberOfImages).toEqual(4); const texture = atlas.texture; const c0 = atlas.textureCoordinates[greenIndex]; const c1 = atlas.textureCoordinates[blueIndex]; const c2 = atlas.textureCoordinates[bigRedIndex]; const c3 = atlas.textureCoordinates[bigBlueIndex]; expectToRender(texture, c0, [0, 255, 0, 255]); expectToRender(texture, c1, [0, 0, 255, 255]); expectToRender(texture, c2, [255, 0, 0, 255]); expectToRender(texture, c3, [0, 0, 255, 255]); }); it("creates a four image atlas with non-zero borderWidthInPixels", async function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 2 }); const greenIndex = await atlas.addImage(greenGuid, greenImage); const blueIndex = await atlas.addImage(blueGuid, blueImage); const bigRedIndex = await atlas.addImage(bigRedGuid, bigRedImage); const bigBlueIndex = await atlas.addImage(bigBlueGuid, bigBlueImage); expect(atlas.borderWidthInPixels).toEqual(2); expect(atlas.numberOfImages).toEqual(4); const texture = atlas.texture; const c0 = atlas.textureCoordinates[greenIndex]; const c1 = atlas.textureCoordinates[blueIndex]; const c2 = atlas.textureCoordinates[bigRedIndex]; const c3 = atlas.textureCoordinates[bigBlueIndex]; const atlasWidth = 68; const atlasHeight = 68; expect(texture.width).toEqual(atlasWidth); expect(texture.height).toEqual(atlasHeight); expect(c0.x).toEqualEpsilon(2 / atlasWidth, import__624.Math.EPSILON16); expect(c0.y).toEqualEpsilon(2 / atlasHeight, import__624.Math.EPSILON16); expect(c0.width).toEqualEpsilon( greenImage.width / atlasWidth, import__624.Math.EPSILON16 ); expect(c0.height).toEqualEpsilon( greenImage.height / atlasHeight, import__624.Math.EPSILON16 ); expect(c1.x).toEqualEpsilon( (greenImage.width + 2 * atlas.borderWidthInPixels) / atlasWidth, import__624.Math.EPSILON16 ); expect(c1.y).toEqualEpsilon(2 / atlasHeight, import__624.Math.EPSILON16); expect(c1.width).toEqualEpsilon( blueImage.width / atlasWidth, import__624.Math.EPSILON16 ); expect(c1.height).toEqualEpsilon( blueImage.width / atlasHeight, import__624.Math.EPSILON16 ); expect(c2.x).toEqualEpsilon(2 / atlasWidth, import__624.Math.EPSILON16); expect(c2.y).toEqualEpsilon( (bigRedImage.height + atlas.borderWidthInPixels) / atlasHeight, import__624.Math.EPSILON16 ); expect(c2.width).toEqualEpsilon( bigRedImage.width / atlasWidth, import__624.Math.EPSILON16 ); expect(c2.height).toEqualEpsilon( bigRedImage.height / atlasHeight, import__624.Math.EPSILON16 ); expect(c3.x).toEqualEpsilon(2 / atlasWidth, import__624.Math.EPSILON16); expect(c3.y).toEqualEpsilon( (greenImage.height + 2 * atlas.borderWidthInPixels) / atlasHeight, import__624.Math.EPSILON16 ); expect(c3.width).toEqualEpsilon( bigBlueImage.width / atlasWidth, import__624.Math.EPSILON16 ); expect(c3.height).toEqualEpsilon( bigBlueImage.height / atlasHeight, import__624.Math.EPSILON16 ); }); it("renders a four image atlas with non-zero borderWidthInPixels", async function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 2 }); const greenIndex = await atlas.addImage(greenGuid, greenImage); const blueIndex = await atlas.addImage(blueGuid, blueImage); const bigRedIndex = await atlas.addImage(bigRedGuid, bigRedImage); const bigBlueIndex = await atlas.addImage(bigBlueGuid, bigBlueImage); expect(atlas.numberOfImages).toEqual(4); const texture = atlas.texture; const c0 = atlas.textureCoordinates[greenIndex]; const c1 = atlas.textureCoordinates[blueIndex]; const c2 = atlas.textureCoordinates[bigRedIndex]; const c3 = atlas.textureCoordinates[bigBlueIndex]; expectToRender(texture, c0, [0, 255, 0, 255]); expectToRender(texture, c1, [0, 0, 255, 255]); expectToRender(texture, c2, [255, 0, 0, 255]); expectToRender(texture, c3, [0, 0, 255, 255]); }); it("creates an atlas that dynamically resizes", function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 0, initialSize: new import__624.Cartesian2(1, 1) }); return atlas.addImage(blueGuid, blueImage).then(function(blueIndex) { expect(atlas.numberOfImages).toEqual(1); const texture = atlas.texture; const coordinates = atlas.textureCoordinates; const atlasWidth = 2; const atlasHeight = 2; expect(texture.width).toEqual(atlasWidth); expect(texture.height).toEqual(atlasHeight); expect(coordinates[blueIndex].x).toEqual(0 / atlasWidth); expect(coordinates[blueIndex].y).toEqual(0 / atlasHeight); expect(coordinates[blueIndex].width).toEqual(1 / atlasWidth); expect(coordinates[blueIndex].height).toEqual(1 / atlasHeight); return atlas.addImage(bigGreenGuid, bigGreenImage).then(function(greenIndex) { expect(atlas.numberOfImages).toEqual(2); const texture2 = atlas.texture; const coordinates2 = atlas.textureCoordinates; const atlasWidth2 = 12; const atlasHeight2 = 12; expect(texture2.width).toEqual(atlasWidth2); expect(texture2.height).toEqual(atlasHeight2); expect(coordinates2[blueIndex].x).toEqual(0 / atlasWidth2); expect(coordinates2[blueIndex].y).toEqual(0 / atlasHeight2); expect(coordinates2[blueIndex].width).toEqual(1 / atlasWidth2); expect(coordinates2[blueIndex].height).toEqual(1 / atlasHeight2); expect(coordinates2[greenIndex].x).toEqual(0 / atlasWidth2); expect(coordinates2[greenIndex].y).toEqual(2 / atlasHeight2); expect(coordinates2[greenIndex].width).toEqual(4 / atlasWidth2); expect(coordinates2[greenIndex].height).toEqual(4 / atlasHeight2); }); }); }); it("renders an atlas that dynamically resizes", function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 0, initialSize: new import__624.Cartesian2(1, 1) }); return atlas.addImage(blueGuid, blueImage).then(function(blueIndex) { expect(atlas.numberOfImages).toEqual(1); const texture = atlas.texture; const coordinates = atlas.textureCoordinates; const blueCoords = coordinates[blueIndex]; expectToRender(texture, blueCoords, [0, 0, 255, 255]); return atlas.addImage(bigGreenGuid, bigGreenImage).then(function(greenIndex) { expect(atlas.numberOfImages).toEqual(2); const texture2 = atlas.texture; const coordinates2 = atlas.textureCoordinates; const blueCoords2 = coordinates2[blueIndex]; expectToRender(texture2, blueCoords2, [0, 0, 255, 255]); const greenCoords = coordinates2[greenIndex]; expectToRender(texture2, greenCoords, [0, 255, 0, 255]); }); }); }); it("creates an atlas with smaller initialSize than first image", function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 0, initialSize: new import__624.Cartesian2(1, 1) }); return atlas.addImage(bigRedGuid, bigRedImage).then(function(index) { expect(atlas.numberOfImages).toEqual(1); const texture = atlas.texture; const coordinates = atlas.textureCoordinates; const atlasWidth = 32; const atlasHeight = 32; expect(texture.width).toEqual(atlasWidth); expect(texture.height).toEqual(atlasHeight); expect(coordinates[index].x).toEqual(0 / atlasWidth); expect(coordinates[index].y).toEqual(0 / atlasHeight); expect(coordinates[index].width).toEqual(16 / atlasWidth); expect(coordinates[index].height).toEqual(16 / atlasHeight); }); }); it("renders an atlas with smaller initialSize than first image", function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 0, initialSize: new import__624.Cartesian2(1, 1) }); return atlas.addImage(bigRedGuid, bigRedImage).then(function(index) { const texture = atlas.texture; const coords = atlas.textureCoordinates[index]; expectToRender(texture, coords, [255, 0, 0, 255]); }); }); it("creates a two image atlas with non-zero borderWidthInPixels that resizes", async function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 2, initialSize: new import__624.Cartesian2(2, 2) }); const greenIndex = await atlas.addImage(greenGuid, greenImage); const blueIndex = await atlas.addImage(blueGuid, blueImage); const texture = atlas.texture; const coordinates = atlas.textureCoordinates; const atlasWidth = 10; const atlasHeight = 10; expect(atlas.borderWidthInPixels).toEqual(2); expect(atlas.numberOfImages).toEqual(2); expect(texture.width).toEqual(atlasWidth); expect(texture.height).toEqual(atlasHeight); expect(coordinates[greenIndex].x).toEqual( atlas.borderWidthInPixels / atlasWidth ); expect(coordinates[greenIndex].y).toEqual( atlas.borderWidthInPixels / atlasHeight ); expect(coordinates[greenIndex].width).toEqual(1 / atlasWidth); expect(coordinates[greenIndex].height).toEqual(1 / atlasHeight); expect(coordinates[blueIndex].x).toEqual(5 / atlasWidth); expect(coordinates[blueIndex].y).toEqual(2 / atlasHeight); expect(coordinates[blueIndex].width).toEqual(1 / atlasWidth); expect(coordinates[blueIndex].height).toEqual(1 / atlasHeight); }); it("renders a two image atlas with non-zero borderWidthInPixels that resizes", async function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 2, initialSize: new import__624.Cartesian2(2, 2) }); const greenIndex = await atlas.addImage(greenGuid, greenImage); const blueIndex = await atlas.addImage(blueGuid, blueImage); const texture = atlas.texture; const coordinates = atlas.textureCoordinates; const greenCoords = coordinates[greenIndex]; const blueCoords = coordinates[blueIndex]; expectToRender(texture, greenCoords, [0, 255, 0, 255]); expectToRender(texture, blueCoords, [0, 0, 255, 255]); }); it("creates an atlas with non-square initialSize that resizes", function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 0, initialSize: new import__624.Cartesian2(1, 1) }); return atlas.addImage(tallGreenGuid, tallGreenImage).then(function(index) { expect(atlas.numberOfImages).toEqual(1); const texture = atlas.texture; const coordinates = atlas.textureCoordinates; const atlasWidth = 2; const atlasHeight = 8; expect(texture.width).toEqual(atlasWidth); expect(texture.height).toEqual(atlasHeight); expect(coordinates[index].x).toEqual(0 / atlasWidth); expect(coordinates[index].y).toEqual(0 / atlasHeight); expect(coordinates[index].width).toEqual( tallGreenImage.width / atlasWidth ); expect(coordinates[index].height).toEqual( tallGreenImage.height / atlasHeight ); }); }); it("renders an atlas with non-square initialSize that resizes", function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 0, initialSize: new import__624.Cartesian2(1, 1) }); return atlas.addImage(tallGreenGuid, tallGreenImage).then(function(index) { const texture = atlas.texture; const coords = atlas.textureCoordinates[index]; expectToRender(texture, coords, [0, 255, 0, 255]); }); }); it("renders an atlas that dynamically resizes twice", async function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 0, initialSize: new import__624.Cartesian2(1, 1) }); const blueIndex = await atlas.addImage(blueGuid, blueImage); const bigGreenIndex = await atlas.addImage(bigGreenGuid, bigGreenImage); const bigRedIndex = await atlas.addImage(bigRedGuid, bigRedImage); const texture = atlas.texture; const blueCoordinates = atlas.textureCoordinates[blueIndex]; const bigGreenCoordinates = atlas.textureCoordinates[bigGreenIndex]; const bigRedCoordinates = atlas.textureCoordinates[bigRedIndex]; expectToRender(texture, blueCoordinates, [0, 0, 255, 255]); expectToRender(texture, bigGreenCoordinates, [0, 255, 0, 255]); expectToRender(texture, bigRedCoordinates, [255, 0, 0, 255]); }); it("promise resolves to index after calling addImage with Image", function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 0, initialSize: new import__624.Cartesian2(4, 4) }); return atlas.addImage(blueGuid, blueImage).then(function(blueIndex) { expect(blueIndex).toEqual(0); return atlas.addImage(greenGuid, greenImage).then(function(greenIndex) { expect(greenIndex).toEqual(1); return atlas.addImage(blueGuid, blueImage).then(function(index) { expect(index).toEqual(blueIndex); expect(atlas.numberOfImages).toEqual(2); const texture = atlas.texture; const coordinates = atlas.textureCoordinates; const blueCoordinates = coordinates[blueIndex]; const greenCoordinates = coordinates[greenIndex]; expectToRender(texture, blueCoordinates, [0, 0, 255, 255]); expectToRender(texture, greenCoordinates, [0, 255, 0, 255]); }); }); }); }); it("creates an atlas with subregions", async function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 0, initialSize: new import__624.Cartesian2(1, 1) }); await atlas.addImage(greenGuid, greenImage); const index1 = await atlas.addSubRegion( greenGuid, new import__624.BoundingRectangle(0, 0, 0.5, 0.5) ); const index2 = await atlas.addSubRegion( greenGuid, new import__624.BoundingRectangle(0, 0.5, 0.5, 0.5) ); const index3 = await atlas.addSubRegion( greenGuid, new import__624.BoundingRectangle(0.5, 0, 0.5, 0.5) ); const index4 = await atlas.addSubRegion( greenGuid, new import__624.BoundingRectangle(0.5, 0.5, 0.5, 0.5) ); expect(atlas.numberOfImages).toEqual(5); const coordinates = atlas.textureCoordinates; const atlasWidth = 2; const atlasHeight = 2; expect(coordinates[index1].x).toEqual(0 / atlasWidth); expect(coordinates[index1].y).toEqual(0 / atlasHeight); expect(coordinates[index1].width).toEqual(0.5 / atlasWidth); expect(coordinates[index1].height).toEqual(0.5 / atlasHeight); expect(coordinates[index2].x).toEqual(0 / atlasWidth); expect(coordinates[index2].y).toEqual(0.5 / atlasHeight); expect(coordinates[index2].width).toEqual(0.5 / atlasWidth); expect(coordinates[index2].height).toEqual(0.5 / atlasHeight); expect(coordinates[index3].x).toEqual(0.5 / atlasWidth); expect(coordinates[index3].y).toEqual(0 / atlasHeight); expect(coordinates[index3].width).toEqual(0.5 / atlasWidth); expect(coordinates[index3].height).toEqual(0.5 / atlasHeight); expect(coordinates[index4].x).toEqual(0.5 / atlasWidth); expect(coordinates[index4].y).toEqual(0.5 / atlasHeight); expect(coordinates[index4].width).toEqual(0.5 / atlasWidth); expect(coordinates[index4].height).toEqual(0.5 / atlasHeight); expect(atlas.getImageIndex(greenGuid)).toEqual(index4); }); it("creates an atlas that resizes with subregions", async function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: 0, initialSize: new import__624.Cartesian2(1, 1) }); await atlas.addImage(greenGuid, greenImage); const index1 = await atlas.addSubRegion( greenGuid, new import__624.BoundingRectangle(0, 0, 0.5, 0.5) ); const index2 = await atlas.addSubRegion( greenGuid, new import__624.BoundingRectangle(0, 0.5, 0.5, 0.5) ); const index3 = await atlas.addSubRegion( greenGuid, new import__624.BoundingRectangle(0.5, 0, 0.5, 0.5) ); const index4 = await atlas.addSubRegion( greenGuid, new import__624.BoundingRectangle(0.5, 0.5, 0.5, 0.5) ); expect(atlas.numberOfImages).toEqual(5); const blueIndex = await atlas.addImage(blueGuid, blueImage); expect(atlas.numberOfImages).toEqual(6); const coordinates = atlas.textureCoordinates; const atlasWidth = 2; const atlasHeight = 2; expect(coordinates[index1].x).toEqual(0 / atlasWidth); expect(coordinates[index1].y).toEqual(0 / atlasHeight); expect(coordinates[index1].width).toEqual(0.5 / atlasWidth); expect(coordinates[index1].height).toEqual(0.5 / atlasHeight); expect(coordinates[index2].x).toEqual(0 / atlasWidth); expect(coordinates[index2].y).toEqual(0.5 / atlasHeight); expect(coordinates[index2].width).toEqual(0.5 / atlasWidth); expect(coordinates[index2].height).toEqual(0.5 / atlasHeight); expect(coordinates[index3].x).toEqual(0.5 / atlasWidth); expect(coordinates[index3].y).toEqual(0 / atlasHeight); expect(coordinates[index3].width).toEqual(0.5 / atlasWidth); expect(coordinates[index3].height).toEqual(0.5 / atlasHeight); expect(coordinates[index4].x).toEqual(0.5 / atlasWidth); expect(coordinates[index4].y).toEqual(0.5 / atlasHeight); expect(coordinates[index4].width).toEqual(0.5 / atlasWidth); expect(coordinates[index4].height).toEqual(0.5 / atlasHeight); expect(coordinates[blueIndex].x).toEqual(1 / atlasWidth); expect(coordinates[blueIndex].y).toEqual(0 / atlasHeight); expect(coordinates[blueIndex].width).toEqual(1 / atlasWidth); expect(coordinates[blueIndex].height).toEqual(1 / atlasHeight); }); it("creates a two image atlas using a url and a function", async function() { atlas = new import__624.TextureAtlas({ context: scene2.context, pixelFormat: import__624.PixelFormat.RGBA, borderWidthInPixels: 0 }); const greenUrl = "./Data/Images/Green.png"; const greenIndex = await atlas.addImage(greenUrl, greenUrl); const blueIndex = await atlas.addImage("Blue Image", blueImage); expect(atlas.numberOfImages).toEqual(2); const texture = atlas.texture; const coordinates = atlas.textureCoordinates; const blueCoordinates = coordinates[blueIndex]; const greenCoordinates = coordinates[greenIndex]; expectToRender(texture, blueCoordinates, [0, 0, 255, 255]); expectToRender(texture, greenCoordinates, [0, 255, 0, 255]); const index = await atlas.addImage("Blue Image", blueImage); expect(index).toEqual(blueIndex); }); it("GUID changes when atlas is modified", function() { atlas = new import__624.TextureAtlas({ context: scene2.context }); const guid1 = atlas.guid; return atlas.addImage(greenGuid, greenImage).then(function(index) { const guid2 = atlas.guid; expect(guid1).not.toEqual(guid2); return atlas.addSubRegion(greenGuid, new import__624.BoundingRectangle(0, 0, 0.5, 0.5)).then(function(index2) { const guid3 = atlas.guid; expect(guid2).not.toEqual(guid3); }); }); }); it("throws with a negative borderWidthInPixels", function() { expect(function() { atlas = new import__624.TextureAtlas({ context: scene2.context, borderWidthInPixels: -1 }); }).toThrowDeveloperError(); }); it("throws with a initialSize less than one", function() { expect(function() { atlas = new import__624.TextureAtlas({ context: scene2.context, initialSize: new import__624.Cartesian2(0, 0) }); }).toThrowDeveloperError(); }); it("throws without context", function() { expect(function() { return new import__624.TextureAtlas({}); }).toThrowDeveloperError(); }); it("addImage throws without id", function() { atlas = new import__624.TextureAtlas({ context: scene2.context }); expect(function() { atlas.addImage(void 0, blueImage); }).toThrowDeveloperError(); }); it("addImage throws without image", function() { atlas = new import__624.TextureAtlas({ context: scene2.context }); expect(function() { atlas.addImage("./Data/Images/Green.png", void 0); }).toThrowDeveloperError(); }); it("addSubRegion throws without id", function() { atlas = new import__624.TextureAtlas({ context: scene2.context }); expect(function() { atlas.addSubRegion(void 0, new import__624.BoundingRectangle()); }).toThrowDeveloperError(); }); it("addSubRegion throws without subregion", function() { atlas = new import__624.TextureAtlas({ context: scene2.context }); expect(function() { atlas.addSubRegion("asdf", void 0); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Scene/TileBoundingRegionSpec.js var import__625 = __toESM(require_Cesium(), 1); var import__626 = __toESM(require_Cesium(), 1); describe("Scene/TileBoundingRegion", function() { const boundingVolumeRegion = [0, 0, 1, 1, 0, 1]; const regionBox = boundingVolumeRegion.slice(0, 4); const rectangle = new import__625.Rectangle( regionBox[0], regionBox[1], regionBox[2], regionBox[3] ); const tileBoundingRegion = new import__625.TileBoundingRegion({ maximumHeight: boundingVolumeRegion[5], minimumHeight: boundingVolumeRegion[4], rectangle }); let frameState2; let camera; beforeEach(function() { frameState2 = createFrameState_default(); camera = frameState2.camera; }); it("throws when options.rectangle is undefined", function() { expect(function() { return new import__625.TileBoundingRegion(); }).toThrowDeveloperError(); }); it("can be instantiated with rectangle and heights", function() { const minimumHeight = boundingVolumeRegion[4]; const maximumHeight = boundingVolumeRegion[5]; const tbr = new import__625.TileBoundingRegion({ maximumHeight, minimumHeight, rectangle }); expect(tbr).toBeDefined(); expect(tbr.boundingVolume).toBeDefined(); expect(tbr.boundingSphere).toBeDefined(); expect(tbr.rectangle).toEqual(rectangle); expect(tbr.minimumHeight).toEqual(minimumHeight); expect(tbr.maximumHeight).toEqual(maximumHeight); }); it("can be instantiated with only a rectangle", function() { const tbr = new import__625.TileBoundingRegion({ rectangle }); expect(tbr).toBeDefined(); expect(tbr.boundingVolume).toBeDefined(); expect(tbr.boundingSphere).toBeDefined(); expect(tbr.rectangle).toEqual(rectangle); expect(tbr.minimumHeight).toBeDefined(); expect(tbr.maximumHeight).toBeDefined(); }); it("can be instantiated from a zero-area rectangle", function() { const zeroAreaRectangle = new import__625.Rectangle(0, 0, 0, 0); const tbr = new import__625.TileBoundingRegion({ rectangle: zeroAreaRectangle }); expect(tbr).toBeDefined(); expect(tbr.boundingVolume).toBeDefined(); expect(tbr.boundingSphere).toBeDefined(); expect(tbr.rectangle).toEqual(zeroAreaRectangle); expect(tbr.minimumHeight).toBeDefined(); expect(tbr.maximumHeight).toBeDefined(); }); it("distanceToCamera throws when frameState is undefined", function() { expect(function() { return tileBoundingRegion.distanceToCamera(); }).toThrowDeveloperError(); }); it("distance to camera is 0 when camera is inside bounding region", function() { camera.position = import__625.Cartesian3.fromRadians( regionBox[0] + import__626.Math.EPSILON6, regionBox[1], 0 ); expect(tileBoundingRegion.distanceToCamera(frameState2)).toEqual(0); }); it("distance to camera is correct when camera is outside bounding region", function() { camera.position = import__625.Cartesian3.fromRadians(regionBox[0], regionBox[1], 2); expect(tileBoundingRegion.distanceToCamera(frameState2)).toEqualEpsilon( 1, import__626.Math.EPSILON6 ); }); it("distanceToCamera", function() { const offset = 1e-4; const west = -1e-3; const south = -1e-3; const east = 1e-3; const north = 1e-3; const tile = new import__625.TileBoundingRegion({ rectangle: new import__625.Rectangle(west, south, east, north), minimumHeight: 0, maximumHeight: 10 }); camera.position = import__625.Cartesian3.fromRadians(0, 0, 20); expect(tile.distanceToCamera(frameState2)).toEqualEpsilon( 10, import__626.Math.EPSILON3 ); camera.position = import__625.Cartesian3.fromRadians(0, 0, 5); expect(tile.distanceToCamera(frameState2)).toEqual(0); camera.position = import__625.Cartesian3.fromRadians( west - offset, south - offset, 0 ); const southwestPosition = import__625.Cartesian3.fromRadians(west, south); let expectedDistance = import__625.Cartesian3.distance( camera.position, southwestPosition ); expect(tile.distanceToCamera(frameState2)).toEqualEpsilon( expectedDistance, import__626.Math.EPSILON1 ); camera.position = import__625.Cartesian3.fromRadians( east + offset, north + offset, 0 ); const northeastPosition = import__625.Cartesian3.fromRadians(east, north); expectedDistance = import__625.Cartesian3.distance(camera.position, northeastPosition); expect(tile.distanceToCamera(frameState2)).toEqualEpsilon( expectedDistance, import__626.Math.EPSILON1 ); }); it("distanceToCamera close to south plane at the northern hemisphere", function() { const ellipsoid = import__625.Ellipsoid.WGS84; const tilingScheme = new import__625.GeographicTilingScheme({ ellipsoid }); const rectangle2 = tilingScheme.tileXYToRectangle(5, 0, 2); const cameraPositionCartographic = new import__625.Cartographic( (rectangle2.west + rectangle2.east) * 0.5, rectangle2.south, 0 ); cameraPositionCartographic.south -= import__626.Math.EPSILON8; const tile = new import__625.TileBoundingRegion({ rectangle: rectangle2, minimumHeight: 0, maximumHeight: 10 }); camera.position = ellipsoid.cartographicToCartesian( cameraPositionCartographic, new import__625.Cartesian3() ); expect(tile.distanceToCamera(frameState2)).toBeLessThan( import__626.Math.EPSILON8 * ellipsoid.maximumRadius ); }); it("distanceToCamera close to north plane at the southern hemisphere", function() { const ellipsoid = import__625.Ellipsoid.WGS84; const tilingScheme = new import__625.GeographicTilingScheme({ ellipsoid }); const rectangle2 = tilingScheme.tileXYToRectangle(4, 3, 2); const cameraPositionCartographic = new import__625.Cartographic( (rectangle2.west + rectangle2.east) * 0.5, rectangle2.north, 0 ); cameraPositionCartographic.north += import__626.Math.EPSILON8; const tile = new import__625.TileBoundingRegion({ rectangle: rectangle2, minimumHeight: 0, maximumHeight: 10 }); camera.position = ellipsoid.cartographicToCartesian( cameraPositionCartographic, new import__625.Cartesian3() ); expect(tile.distanceToCamera(frameState2)).toBeLessThan( import__626.Math.EPSILON8 * ellipsoid.maximumRadius ); }); it("distanceToCamera in 2D", function() { frameState2.mode = import__625.SceneMode.SCENE2D; const offset = 1e-4; const west = -1e-3; const south = -1e-3; const east = 1e-3; const north = 1e-3; const tile = new import__625.TileBoundingRegion({ rectangle: new import__625.Rectangle(west, south, east, north), minimumHeight: 0, maximumHeight: 10 }); camera.position = import__625.Cartesian3.fromRadians(0, 0, 0); expect(tile.distanceToCamera(frameState2)).toEqual(import__625.Ellipsoid.WGS84.radii.x); const southwest3D = new import__625.Cartographic(west, south, 0); const southwest2D = frameState2.mapProjection.project(southwest3D); const position3D = new import__625.Cartographic(west - offset, south - offset, 0); const position2D = frameState2.mapProjection.project(position3D); const distance2D = import__625.Cartesian2.distance(southwest2D, position2D); const height = import__625.Ellipsoid.WGS84.radii.x; const expectedDistance = Math.sqrt( distance2D * distance2D + height * height ); camera.position = import__625.Cartesian3.fromRadians( position3D.longitude, position3D.latitude ); expect(tile.distanceToCamera(frameState2)).toEqualEpsilon( expectedDistance, 10 ); }); it("createDebugVolume throws when color is undefined", function() { expect(function() { return tileBoundingRegion.createDebugVolume(); }).toThrowDeveloperError(); }); it("can create a debug volume", function() { const debugVolume = tileBoundingRegion.createDebugVolume(import__625.Color.BLUE); expect(debugVolume).toBeDefined(); }); it("intersectPlane throws when plane is undefined", function() { expect(function() { return tileBoundingRegion.intersectPlane(); }).toThrowDeveloperError(); }); it("intersects plane", function() { const normal = new import__625.Cartesian3(); import__625.Cartesian3.normalize(import__625.Cartesian3.fromRadians(0, 0, 1), normal); const distanceFromCenter = import__625.Cartesian3.distance( new import__625.Cartesian3(0, 0, 0), import__625.Cartesian3.fromRadians(0, 0, 0) ); const plane = new import__625.Plane(normal, -distanceFromCenter); expect(tileBoundingRegion.intersectPlane(plane)).toEqual( import__625.Intersect.INTERSECTING ); }); }); // packages/engine/Specs/Scene/TileBoundingS2CellSpec.js var import__627 = __toESM(require_Cesium(), 1); var import__628 = __toESM(require_Cesium(), 1); describe("Scene/TileBoundingS2Cell", function() { const s2Cell = import__627.S2Cell.fromToken("1"); const s2Options = { token: "1", minimumHeight: 0, maximumHeight: 1e5 }; const tileS2Cell = new import__627.TileBoundingS2Cell(s2Options); let frameState2; let camera; beforeEach(function() { frameState2 = createFrameState_default(); camera = frameState2.camera; }); it("throws when options.token is undefined", function() { expect(function() { return new import__627.TileBoundingS2Cell(); }).toThrowDeveloperError(); }); it("can be instantiated with S2 cell", function() { const tS2Cell = new import__627.TileBoundingS2Cell({ token: "1" }); expect(tS2Cell).toBeDefined(); expect(tS2Cell.boundingVolume).toBeDefined(); expect(tS2Cell.boundingSphere).toBeDefined(); expect(tS2Cell.s2Cell).toBeDefined(); expect(tS2Cell.center).toBeDefined(); expect(tS2Cell.minimumHeight).toBeDefined(); expect(tS2Cell.maximumHeight).toBeDefined(); }); it("can be instantiated with S2 cell and heights", function() { const tS2Cell = new import__627.TileBoundingS2Cell(s2Options); expect(tS2Cell).toBeDefined(); expect(tS2Cell.boundingVolume).toBeDefined(); expect(tS2Cell.boundingSphere).toBeDefined(); expect(tS2Cell.s2Cell).toBeDefined(); expect(tS2Cell.center).toBeDefined(); expect(tS2Cell.minimumHeight).toBeDefined(); expect(tS2Cell.maximumHeight).toBeDefined(); }); it("distanceToCamera throws when frameState is undefined", function() { expect(function() { return tileS2Cell.distanceToCamera(); }).toThrowDeveloperError(); }); it("distance to camera is 0 when camera is inside bounding volume", function() { camera.position = s2Cell.getCenter(); expect(tileS2Cell.distanceToCamera(frameState2)).toEqual(0); }); const edgeOneScratch = new import__627.Cartesian3(); const edgeTwoScratch = new import__627.Cartesian3(); const faceCenterScratch = new import__627.Cartesian3(); const topPlaneScratch = new import__627.Plane(import__627.Cartesian3.UNIT_X, 0, 0); const sidePlane0Scratch = new import__627.Plane(import__627.Cartesian3.UNIT_X, 0, 0); it("distanceToCamera works when camera is facing only one plane", function() { const testDistance = 100; const topPlane = import__627.Plane.clone( tileS2Cell._boundingPlanes[0], topPlaneScratch ); topPlane.distance -= testDistance; camera.position = import__627.Plane.projectPointOntoPlane(topPlane, tileS2Cell.center); expect(tileS2Cell.distanceToCamera(frameState2)).toEqualEpsilon( testDistance, import__628.Math.EPSILON7 ); const sidePlane0 = import__627.Plane.clone( tileS2Cell._boundingPlanes[2], sidePlane0Scratch ); const edgeOne = import__627.Cartesian3.midpoint( tileS2Cell._vertices[0], tileS2Cell._vertices[1], edgeOneScratch ); const edgeTwo = import__627.Cartesian3.midpoint( tileS2Cell._vertices[4], tileS2Cell._vertices[5], edgeTwoScratch ); const faceCenter = import__627.Cartesian3.midpoint(edgeOne, edgeTwo, faceCenterScratch); sidePlane0.distance -= testDistance; camera.position = import__627.Plane.projectPointOntoPlane(sidePlane0, faceCenter); expect(tileS2Cell.distanceToCamera(frameState2)).toEqualEpsilon( testDistance, import__628.Math.EPSILON7 ); }); const edgeMidpointScratch = new import__627.Cartesian3(); it("distanceToCamera works when camera is facing two planes", function() { const testDistance = 5; camera.position = import__627.Cartesian3.midpoint( tileS2Cell._vertices[0], tileS2Cell._vertices[1], edgeMidpointScratch ); camera.position.z -= testDistance; expect(tileS2Cell.distanceToCamera(frameState2)).toEqualEpsilon( testDistance, import__628.Math.EPSILON7 ); camera.position = import__627.Cartesian3.midpoint( tileS2Cell._vertices[0], tileS2Cell._vertices[4], edgeMidpointScratch ); camera.position.x -= 1; camera.position.z -= 1; expect(tileS2Cell.distanceToCamera(frameState2)).toEqualEpsilon( Math.SQRT2, import__628.Math.EPSILON7 ); camera.position = import__627.Cartesian3.midpoint( tileS2Cell._vertices[5], tileS2Cell._vertices[6], edgeMidpointScratch ); camera.position.x -= 1e4; camera.position.y -= 1; expect(tileS2Cell.distanceToCamera(frameState2)).toEqualEpsilon( 1e4, import__628.Math.EPSILON7 ); }); const vertex2Scratch = new import__627.Cartesian3(); it("distanceToCamera works when camera is facing three planes", function() { camera.position = import__627.Cartesian3.clone(tileS2Cell._vertices[2], vertex2Scratch); camera.position.x += 1; camera.position.y += 1; camera.position.z += 1; expect(tileS2Cell.distanceToCamera(frameState2)).toEqualEpsilon( Math.sqrt(3), import__628.Math.EPSILON7 ); }); it("distanceToCamera works when camera is facing more than three planes", function() { camera.position = new import__627.Cartesian3(-import__627.Ellipsoid.WGS84.maximumRadius, 0, 0); expect(tileS2Cell.distanceToCamera(frameState2)).toEqualEpsilon( import__627.Ellipsoid.WGS84.maximumRadius + tileS2Cell._boundingPlanes[1].distance, import__628.Math.EPSILON7 ); }); it("can create a debug volume", function() { const debugVolume = tileS2Cell.createDebugVolume(import__627.Color.BLUE); expect(debugVolume).toBeDefined(); }); it("createDebugVolume throws when color is undefined", function() { expect(function() { return tileS2Cell.createDebugVolume(); }).toThrowDeveloperError(); }); it("intersectPlane throws when plane is undefined", function() { expect(function() { return tileS2Cell.intersectPlane(); }).toThrowDeveloperError(); }); it("intersects plane", function() { expect(tileS2Cell.intersectPlane(import__627.Plane.ORIGIN_ZX_PLANE)).toEqual( import__627.Intersect.INTERSECTING ); const outsidePlane = import__627.Plane.clone(import__627.Plane.ORIGIN_YZ_PLANE); outsidePlane.distance -= 2 * import__627.Ellipsoid.WGS84.maximumRadius; expect(tileS2Cell.intersectPlane(outsidePlane)).toEqual(import__627.Intersect.OUTSIDE); expect(tileS2Cell.intersectPlane(import__627.Plane.ORIGIN_YZ_PLANE)).toEqual( import__627.Intersect.INSIDE ); }); }); // packages/engine/Specs/Scene/TileBoundingSphereSpec.js var import__629 = __toESM(require_Cesium(), 1); var import__630 = __toESM(require_Cesium(), 1); describe("Scene/TileBoundingSphere", function() { const tileBoundingSphere = new import__629.TileBoundingSphere( new import__629.Cartesian3(0, 0, 0), 1 ); const frameState2 = createFrameState_default(); it("can be instantiated with center and radius", function() { const center = new import__629.Cartesian3(0, 0, 0); const radius = 1; const tbs = new import__629.TileBoundingSphere(center, radius); expect(tbs).toBeDefined(); expect(tbs.boundingVolume).toBeDefined(); expect(tbs.boundingSphere).toBeDefined(); expect(tbs.center).toEqual(center); expect(tbs.radius).toEqual(radius); }); it("createDebugVolume throws when color is undefined", function() { expect(function() { return tileBoundingSphere.createDebugVolume(); }).toThrowDeveloperError(); }); it("can create a debug volume", function() { const debugVolume = tileBoundingSphere.createDebugVolume(import__629.Color.BLUE); expect(debugVolume).toBeDefined(); }); it("distanceToCamera throws when frameState is undefined", function() { expect(function() { return tileBoundingSphere.distanceToCamera(); }).toThrowDeveloperError(); }); it("distance to camera is 0 when camera is inside bounding sphere", function() { frameState2.camera.position = new import__629.Cartesian3(0, 0, 0); expect(tileBoundingSphere.distanceToCamera(frameState2)).toEqual(0); }); it("distance to camera is correct when camera is outside bounding region", function() { frameState2.camera.position = new import__629.Cartesian3(0, 2, 0); expect(tileBoundingSphere.distanceToCamera(frameState2)).toEqual(1); }); it("intersectPlane throws when plane is undefined", function() { expect(function() { return tileBoundingSphere.intersectPlane(); }).toThrowDeveloperError(); }); it("intersects plane", function() { const normal = new import__629.Cartesian3(0, 0, 1); const plane = new import__629.Plane(normal, import__630.Math.EPSILON6); expect(tileBoundingSphere.intersectPlane(plane)).toEqual( import__629.Intersect.INTERSECTING ); }); }); // packages/engine/Specs/Scene/TileBoundingVolumeSpec.js var import__631 = __toESM(require_Cesium(), 1); describe("Scene/TileBoundingVolume", function() { it("throws", function() { const boundingVolume = new import__631.TileBoundingVolume(); expect(function() { boundingVolume.createDebugVolume(); }).toThrowDeveloperError(); expect(function() { boundingVolume.distanceToCamera(); }).toThrowDeveloperError(); expect(function() { boundingVolume.intersectPlane(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/TileCoordinatesImageryProviderSpec.js var import__632 = __toESM(require_Cesium(), 1); describe("Scene/TileCoordinatesImageryProvider", function() { it("conforms to ImageryProvider interface", function() { expect(import__632.TileCoordinatesImageryProvider).toConformToInterface( import__632.ImageryProvider ); }); it("returns valid value for hasAlphaChannel", function() { const provider = new import__632.TileCoordinatesImageryProvider(); expect(typeof provider.hasAlphaChannel).toBe("boolean"); }); it("can use a custom ellipsoid", function() { const ellipsoid = new import__632.Ellipsoid(1, 2, 3); const provider = new import__632.TileCoordinatesImageryProvider({ ellipsoid }); expect(provider.tilingScheme.ellipsoid).toEqual(ellipsoid); }); it("can provide a root tile", function() { const provider = new import__632.TileCoordinatesImageryProvider(); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__632.GeographicTilingScheme); expect(provider.tileDiscardPolicy).toBeUndefined(); expect(provider.rectangle).toEqual(new import__632.GeographicTilingScheme().rectangle); return Promise.resolve(provider.requestImage(0, 0, 0)).then(function(image) { expect(image).toBeDefined(); }); }); it("uses alternate tiling scheme if provided", function() { const tilingScheme = new import__632.WebMercatorTilingScheme(); const provider = new import__632.TileCoordinatesImageryProvider({ tilingScheme }); expect(provider.tilingScheme).toBe(tilingScheme); }); it("uses tile width and height if provided", function() { const provider = new import__632.TileCoordinatesImageryProvider({ tileWidth: 123, tileHeight: 456 }); expect(provider.tileWidth).toEqual(123); expect(provider.tileHeight).toEqual(456); }); }); // packages/engine/Specs/Scene/TileImagerySpec.js var import__633 = __toESM(require_Cesium(), 1); describe("Scene/TileImagery", function() { it("does not use ancestor ready imagery that needs to be reprojected", function() { const imageryLayer = { _calculateTextureTranslationAndScale: function() { } }; const grandparentImagery = { imageryLayer, level: 0, x: 0, y: 0, state: import__633.ImageryState.READY, texture: {}, textureWebMercator: {}, addReference: function() { } }; const parentImagery = { imageryLayer, parent: grandparentImagery, level: 1, x: 0, y: 0, state: import__633.ImageryState.READY, texture: void 0, textureWebMercator: {}, processStateMachine: function() { ++this.processStateMachineCalls; }, processStateMachineCalls: 0, addReference: function() { } }; const thisImagery = { imageryLayer, parent: parentImagery, level: 2, x: 0, y: 0, state: import__633.ImageryState.FAILED, processStateMachine: function() { }, addReference: function() { } }; const tileImagery = new import__633.TileImagery(thisImagery, void 0, false); tileImagery.processStateMachine({}, {}); expect(tileImagery.readyImagery).toBe(grandparentImagery); expect(parentImagery.processStateMachineCalls).toBe(1); }); }); // packages/engine/Specs/Scene/TileMapServiceImageryProviderSpec.js var import__634 = __toESM(require_Cesium(), 1); var import__635 = __toESM(require_Cesium(), 1); describe("Scene/TileMapServiceImageryProvider", function() { const validSampleXmlString = ' NE2_HR_LC_SR_W_DR_recolored.tif EPSG:4326 '; function patchRequestScheduler(xmlResponseString) { import__634.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { setTimeout(function() { const parser = new DOMParser(); const xml = parser.parseFromString(xmlResponseString, "text/xml"); deferred.resolve(xml); }, 1); }; } function patchRequestSchedulerToRejectRequest() { import__634.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { setTimeout(function() { deferred.reject(new import__634.RequestErrorEvent(404)); }, 1); }; } beforeEach(function() { import__634.RequestScheduler.clearForSpecs(); }); afterEach(function() { import__634.Resource._Implementations.createImage = import__634.Resource._DefaultImplementations.createImage; import__634.Resource._Implementations.loadWithXhr = import__634.Resource._DefaultImplementations.loadWithXhr; }); it("return a UrlTemplateImageryProvider", function() { const provider = new import__634.TileMapServiceImageryProvider({ url: "made/up/tms/server/" }); expect(provider).toBeInstanceOf(import__634.UrlTemplateImageryProvider); }); it("fromUrl throws without url", async function() { await expectAsync( import__634.TileMapServiceImageryProvider.fromUrl() ).toBeRejectedWithDeveloperError(); }); it("fromUrl resolves to created provider", async function() { patchRequestScheduler(validSampleXmlString); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/tms/server/" ); expect(provider).toBeInstanceOf(import__634.TileMapServiceImageryProvider); }); it("fromUrl resolves to created provider with Resource", async function() { patchRequestScheduler(validSampleXmlString); const resource = new import__634.Resource({ url: "made/up/tms/server/" }); const provider = await import__634.TileMapServiceImageryProvider.fromUrl(resource); expect(provider).toBeInstanceOf(import__634.TileMapServiceImageryProvider); }); it("fromUrl throws on unsupported profile attribute", async function() { const xmlString = ' <Abstract/> <SRS>EPSG:4326</SRS> <BoundingBox minx="-10.0" miny="-123.0" maxx="11.0" maxy="-110.0"/> <Origin x="-90.0" y="-180.0"/> <TileFormat width="256" height="256" mime-type="image/png" extension="png"/> <TileSets profile="foobar"> <TileSet href="2" units-per-pixel="39135.75848201024200" order="2"/> <TileSet href="3" units-per-pixel="19567.87924100512100" order="3"/> </TileSets></TileMap>'; patchRequestScheduler(xmlString); await expectAsync( import__634.TileMapServiceImageryProvider.fromUrl("made/up/tms/server") ).toBeRejectedWithError( import__634.RuntimeError, new RegExp( "made/up/tms/server/tilemapresource.xml specifies an unsupported profile attribute, foobar." ) ); }); it("fromUrl throws on invalid xml", async function() { const xmlString = '<TileMap version="1.0.0" tilemapservice="http://tms.osgeo.org/1.0.0"> <Title/> <Abstract/> <SRS>EPSG:4326</SRS> <Origin x="-90.0" y="-180.0"/> <TileFormat width="256" height="256" mime-type="image/png" extension="png"/> <TileSets profile="foobar"> <TileSet href="2" units-per-pixel="39135.75848201024200" order="2"/> <TileSet href="3" units-per-pixel="19567.87924100512100" order="3"/> </TileSets></TileMap>'; patchRequestScheduler(xmlString); await expectAsync( import__634.TileMapServiceImageryProvider.fromUrl("made/up/tms/server") ).toBeRejectedWithError( import__634.RuntimeError, new RegExp("Unable to find expected tilesets or bbox attributes") ); }); it("returns valid value for hasAlphaChannel", async function() { patchRequestScheduler(validSampleXmlString); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/tms/server/" ); expect(typeof provider.hasAlphaChannel).toBe("boolean"); }); it("supports a slash at the end of the URL", async function() { patchRequestScheduler(validSampleXmlString); const baseUrl = "made/up/tms/server/"; const provider = await import__634.TileMapServiceImageryProvider.fromUrl(baseUrl); spyOn(import__634.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toStartWith((0, import__634.getAbsoluteUri)(baseUrl)); import__634.Resource._DefaultImplementations.createImage( new import__634.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); const image = await provider.requestImage(0, 0, 0); expect(import__634.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); it("supports no slash at the end of the URL", async function() { patchRequestScheduler(validSampleXmlString); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "http://made/up/tms/server" ); spyOn(import__634.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toContain("made/up/tms/server/"); import__634.Resource._DefaultImplementations.createImage( new import__634.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); const image = await provider.requestImage(0, 0, 0); expect(import__634.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); it("supports a query string at the end of the URL", async function() { patchRequestScheduler(validSampleXmlString); const baseUrl = "made/up/tms/server/"; const provider = await import__634.TileMapServiceImageryProvider.fromUrl( `${baseUrl}?a=some&b=query` ); spyOn(import__634.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toStartWith((0, import__634.getAbsoluteUri)(baseUrl)); expect(request.url).toContain("?a=some&b=query"); import__634.Resource._DefaultImplementations.createImage( new import__634.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); const image = await provider.requestImage(0, 0, 0); expect(import__634.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); it("requestImage returns a promise for an image and loads it for cross-origin use", async function() { patchRequestScheduler(validSampleXmlString); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/tms/server/" ); let url = (0, import__634.getAbsoluteUri)("made/up/tms/server/{z}/{x}/{reverseY}.jpg"); url = url.replace(/%7B/g, "{").replace(/%7D/g, "}"); expect(provider.url).toEqual(url); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); spyOn(import__634.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { import__634.Resource._DefaultImplementations.createImage( new import__634.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); const image = await provider.requestImage(0, 0, 0); expect(import__634.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); it("when no credit is supplied, the provider has no logo", async function() { patchRequestScheduler(validSampleXmlString); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/tms/server/" ); expect(provider.credit).toBeUndefined(); }); it("turns the supplied credit into a logo", async function() { patchRequestScheduler(validSampleXmlString); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/gms/server", { credit: "Thanks to our awesome made up source of this imagery!" } ); expect(provider.credit).toBeDefined(); }); it("resource request takes a query string", async function() { spyOn(import__634.Resource._Implementations, "loadWithXhr").and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(/\?query=1$/.test(url)).toEqual(true); deferred.reject(new import__634.RequestErrorEvent(404)); }); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "http://server.invalid?query=1" ); }); it("rectangle passed to constructor does not affect tile numbering", async function() { patchRequestScheduler(validSampleXmlString); const rectangle = new import__634.Rectangle(0.1, 0.2, 0.3, 0.4); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/tms/server", { rectangle } ); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toEqual(2); expect(provider.tilingScheme).toBeInstanceOf(import__634.GeographicTilingScheme); expect(provider.rectangle.west).toEqualEpsilon( rectangle.west, import__635.Math.EPSILON14 ); expect(provider.rectangle.east).toEqualEpsilon( rectangle.east, import__635.Math.EPSILON14 ); expect(provider.rectangle.north).toEqualEpsilon( rectangle.north, import__635.Math.EPSILON14 ); expect(provider.rectangle.south).toEqualEpsilon( rectangle.south, import__635.Math.EPSILON14 ); expect(provider.tileDiscardPolicy).toBeUndefined(); spyOn(import__634.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toContain("/0/0/0"); import__634.Resource._DefaultImplementations.createImage( new import__634.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); const image = await provider.requestImage(0, 0, 0); expect(import__634.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); it("uses maximumLevel passed to constructor", async function() { patchRequestScheduler(validSampleXmlString); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/tms/server", { maximumLevel: 5 } ); expect(provider.maximumLevel).toEqual(5); }); it("raises error event when image cannot be loaded", async function() { patchRequestScheduler(validSampleXmlString); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/tms/server" ); const layer = new import__634.ImageryLayer(provider); let tries = 0; provider.errorEvent.addEventListener(function(error) { expect(error.timesRetried).toEqual(tries); ++tries; if (tries < 3) { error.retry = true; } setTimeout(function() { import__634.RequestScheduler.update(); }, 1); }); import__634.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { if (tries === 2) { import__634.Resource._DefaultImplementations.createImage( new import__634.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); } else { setTimeout(function() { deferred.reject(); }, 1); } }; const imagery = new import__634.Imagery(layer, 0, 0, 0); imagery.addReference(); layer._requestImagery(imagery); import__634.RequestScheduler.update(); return pollToPromise_default(function() { return imagery.state === import__634.ImageryState.RECEIVED; }).then(function() { expect(imagery.image).toBeImageOrImageBitmap(); expect(tries).toEqual(2); imagery.releaseReference(); }); }); it("keeps the rectangle within the bounds allowed by the tiling scheme no matter what the tilemapresource.xml says.", async function() { const xmlString = "<TileMap version='1.0.0' tilemapservice='http://tms.osgeo.org/1.0.0'> <Title>dnb_land_ocean_ice.2012.54000x27000_geo.tif EPSG:900913 "; patchRequestScheduler(xmlString); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/tms/server" ); expect(provider.rectangle.west).toEqualEpsilon( import__635.Math.toRadians(-180), import__635.Math.EPSILON14 ); expect(provider.rectangle.west).toBeGreaterThanOrEqual( provider.tilingScheme.rectangle.west ); expect(provider.rectangle.east).toEqualEpsilon( import__635.Math.toRadians(180), import__635.Math.EPSILON14 ); expect(provider.rectangle.east).toBeLessThanOrEqual( provider.tilingScheme.rectangle.east ); expect(provider.rectangle.south).toEqualEpsilon( -import__634.WebMercatorProjection.MaximumLatitude, import__635.Math.EPSILON14 ); expect(provider.rectangle.south).toBeGreaterThanOrEqual( provider.tilingScheme.rectangle.south ); expect(provider.rectangle.north).toEqualEpsilon( import__634.WebMercatorProjection.MaximumLatitude, import__635.Math.EPSILON14 ); expect(provider.rectangle.north).toBeLessThanOrEqual( provider.tilingScheme.rectangle.north ); }); it("uses a minimum level if the tilemapresource.xml specifies one and it is reasonable", async function() { const xmlString = " dnb_land_ocean_ice.2012.54000x27000_geo.tif EPSG:900913 "; patchRequestScheduler(xmlString); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/tms/server" ); expect(provider.maximumLevel).toBe(8); expect(provider.minimumLevel).toBe(7); }); it("ignores the minimum level in the tilemapresource.xml if it is unreasonable", async function() { const xmlString = " dnb_land_ocean_ice.2012.54000x27000_geo.tif EPSG:900913 "; patchRequestScheduler(xmlString); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/tms/server" ); expect(provider.maximumLevel).toBe(8); expect(provider.minimumLevel).toBe(0); }); it("handles XML with casing differences", async function() { const xmlString = " dnb_land_ocean_ice.2012.54000x27000_geo.tif EPSG:900913 "; patchRequestScheduler(xmlString); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/tms/server" ); expect(provider.maximumLevel).toBe(8); expect(provider.minimumLevel).toBe(7); }); it("supports the global-mercator profile with a non-flipped, mercator bounding box", async function() { const xmlString = ' <Abstract/> <SRS>EPSG:900913</SRS> <BoundingBox minx="-11877789.66764229300000" miny="1707163.75952051670000" maxx="-4696205.45407573510000" maxy="7952627.07365330120000"/> <Origin x="-20037508.34278924400000" y="-20037508.34278924400000"/> <TileFormat width="256" height="256" mime-type="image/png" extension="png"/> <TileSets profile="global-mercator"> <TileSet href="2" units-per-pixel="39135.75848201024200" order="2"/> <TileSet href="3" units-per-pixel="19567.87924100512100" order="3"/> </TileSets></TileMap>'; patchRequestScheduler(xmlString); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/tms/server" ); expect(provider.tilingScheme).toBeInstanceOf(import__634.WebMercatorTilingScheme); expect(provider.tilingScheme.projection).toBeInstanceOf( import__634.WebMercatorProjection ); const projection = provider.tilingScheme.projection; const expectedSW = projection.unproject( new import__634.Cartesian2(-11877789667642293e-9, 1.7071637595205167e6) ); const expectedNE = projection.unproject( new import__634.Cartesian2(-4696205454075735e-9, 7952627073653301e-9) ); expect(provider.rectangle.west).toEqual(expectedSW.longitude); expect(provider.rectangle.south).toEqual(expectedSW.latitude); expect(provider.rectangle.east).toBeCloseTo( expectedNE.longitude, import__635.Math.EPSILON14 ); expect(provider.rectangle.north).toEqual(expectedNE.latitude); }); it("supports the global-geodetic profile with a non-flipped, geographic bounding box", async function() { const xmlString = '<TileMap version="1.0.0" tilemapservice="http://tms.osgeo.org/1.0.0"> <Title/> <Abstract/> <SRS>EPSG:4326</SRS> <BoundingBox minx="-123.0" miny="-10.0" maxx="-110.0" maxy="11.0"/> <Origin x="-180.0" y="-90.0"/> <TileFormat width="256" height="256" mime-type="image/png" extension="png"/> <TileSets profile="global-geodetic"> <TileSet href="2" units-per-pixel="39135.75848201024200" order="2"/> <TileSet href="3" units-per-pixel="19567.87924100512100" order="3"/> </TileSets></TileMap>'; patchRequestScheduler(xmlString); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/tms/server" ); expect(provider.tilingScheme).toBeInstanceOf(import__634.GeographicTilingScheme); expect(provider.tilingScheme.projection).toBeInstanceOf( import__634.GeographicProjection ); const expectedSW = import__634.Cartographic.fromDegrees(-123, -10); const expectedNE = import__634.Cartographic.fromDegrees(-110, 11); expect(provider.rectangle.west).toBeCloseTo( expectedSW.longitude, import__635.Math.EPSILON14 ); expect(provider.rectangle.south).toEqual(expectedSW.latitude); expect(provider.rectangle.east).toBeCloseTo( expectedNE.longitude, import__635.Math.EPSILON14 ); expect(provider.rectangle.north).toEqual(expectedNE.latitude); }); it("supports the old mercator profile with a flipped, geographic bounding box", async function() { const xmlString = '<TileMap version="1.0.0" tilemapservice="http://tms.osgeo.org/1.0.0"> <Title/> <Abstract/> <SRS>EPSG:900913</SRS> <BoundingBox minx="-10.0" miny="-123.0" maxx="11.0" maxy="-110.0"/> <Origin x="-90.0" y="-180.0"/> <TileFormat width="256" height="256" mime-type="image/png" extension="png"/> <TileSets profile="mercator"> <TileSet href="2" units-per-pixel="39135.75848201024200" order="2"/> <TileSet href="3" units-per-pixel="19567.87924100512100" order="3"/> </TileSets></TileMap>'; patchRequestScheduler(xmlString); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/tms/server", { flipXY: true } ); expect(provider.tilingScheme).toBeInstanceOf(import__634.WebMercatorTilingScheme); expect(provider.tilingScheme.projection).toBeInstanceOf( import__634.WebMercatorProjection ); const expectedSW = import__634.Cartographic.fromDegrees(-123, -10); const expectedNE = import__634.Cartographic.fromDegrees(-110, 11); expect(provider.rectangle.west).toBeCloseTo( expectedSW.longitude, import__635.Math.EPSILON14 ); expect(provider.rectangle.south).toEqual(expectedSW.latitude); expect(provider.rectangle.east).toBeCloseTo( expectedNE.longitude, import__635.Math.EPSILON14 ); expect(provider.rectangle.north).toEqual(expectedNE.latitude); }); it("supports the old geodetic profile with a flipped, geographic bounding box", async function() { const xmlString = '<TileMap version="1.0.0" tilemapservice="http://tms.osgeo.org/1.0.0"> <Title/> <Abstract/> <SRS>EPSG:4326</SRS> <BoundingBox minx="-10.0" miny="-123.0" maxx="11.0" maxy="-110.0"/> <Origin x="-90.0" y="-180.0"/> <TileFormat width="256" height="256" mime-type="image/png" extension="png"/> <TileSets profile="geodetic"> <TileSet href="2" units-per-pixel="39135.75848201024200" order="2"/> <TileSet href="3" units-per-pixel="19567.87924100512100" order="3"/> </TileSets></TileMap>'; patchRequestScheduler(xmlString); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/tms/server", { flipXY: true } ); expect(provider.tilingScheme).toBeInstanceOf(import__634.GeographicTilingScheme); expect(provider.tilingScheme.projection).toBeInstanceOf( import__634.GeographicProjection ); const expectedSW = import__634.Cartographic.fromDegrees(-123, -10); const expectedNE = import__634.Cartographic.fromDegrees(-110, 11); expect(provider.rectangle.west).toBeCloseTo( expectedSW.longitude, import__635.Math.EPSILON14 ); expect(provider.rectangle.south).toEqual(expectedSW.latitude); expect(provider.rectangle.east).toBeCloseTo( expectedNE.longitude, import__635.Math.EPSILON14 ); expect(provider.rectangle.north).toEqual(expectedNE.latitude); }); it("forces minimum detail level to zero if the tilemapresource.xml request fails and the constructor minimum level is too high", async function() { patchRequestSchedulerToRejectRequest(); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/tms/server", { minimumLevel: 10 } ); expect(provider.minimumLevel).toBe(0); }); it("allows the constructor minimum detail level if the tilemapresource.xml request fails but the constructor rectangle is small enough", async function() { patchRequestSchedulerToRejectRequest(); const provider = await import__634.TileMapServiceImageryProvider.fromUrl( "made/up/tms/server", { // a high minimum detail level minimumLevel: 12, // and a very small rectangle rectangle: new import__634.Rectangle( import__635.Math.toRadians(131.020889), import__635.Math.toRadians(-25.35473), import__635.Math.toRadians(131.054363), import__635.Math.toRadians(-25.335803) ) } ); expect(provider.minimumLevel).toBe(12); expect(provider.rectangle.width).toBeLessThan(1e-3); expect(provider.rectangle.height).toBeLessThan(1e-3); }); }); // packages/engine/Specs/Scene/TileMetadataSpec.js var import__636 = __toESM(require_Cesium(), 1); describe("Scene/TileMetadata", function() { const tileClassWithNoProperties = import__636.MetadataClass.fromJson({ id: "tile", class: {} }); const tileClass = import__636.MetadataClass.fromJson({ id: "tile", class: { properties: { color: { type: "SCALAR", componentType: "FLOAT32", array: true, count: 8, semantic: "COLOR" }, isSquare: { description: "Is a square tile, rather than a rectangular partial tile", type: "BOOLEAN" } } } }); const tileExtension = { class: "tile", properties: { color: [1, 0.5, 0], isSquare: true } }; let tileMetadata; beforeEach(function() { tileMetadata = new import__636.TileMetadata({ tile: tileExtension, class: tileClass }); }); it("throws without tile", function() { expect(function() { tileMetadata = new import__636.TileMetadata({ tile: void 0, class: tileClass }); }).toThrowDeveloperError(); }); it("throws without class", function() { expect(function() { tileMetadata = new import__636.TileMetadata({ tile: {}, class: void 0 }); }).toThrowDeveloperError(); }); it("creates tile metadata with default values", function() { const metadata = new import__636.TileMetadata({ tile: {}, class: tileClassWithNoProperties }); expect(metadata.extras).toBeUndefined(); expect(metadata.extensions).toBeUndefined(); }); it("creates tile metadata", function() { const properties = { color: [0, 0, 1], isSquare: false }; const extras = { version: "0.0" }; const extensions = { "3DTILES_extension": {} }; tileMetadata = new import__636.TileMetadata({ tile: { class: "tile", properties, extras, extensions }, class: tileClass }); expect(tileMetadata.class).toBe(tileClass); expect(tileMetadata.getProperty("color")).toEqual(properties.color); expect(tileMetadata.getProperty("isSquare")).toEqual(properties.isSquare); expect(tileMetadata.extras).toBe(extras); expect(tileMetadata.extensions).toBe(extensions); }); it("hasProperty returns true if the tile has this property", function() { expect(tileMetadata.hasProperty("color")).toBe(true); }); it("hasProperty returns false if the tile does not have this property", function() { expect(tileMetadata.hasProperty("numberOfPoints")).toBe(false); }); it("hasPropertyBySemantic returns true if the tile has a property with the given semantic", function() { expect(tileMetadata.hasPropertyBySemantic("COLOR")).toBe(true); }); it("hasPropertyBySemantic returns false if the tile does not have a property with the given semantic", function() { expect(tileMetadata.hasProperty("NUMBER_OF_POINTS")).toBe(false); }); it("getPropertyIds returns array of property IDs", function() { const propertyIds = tileMetadata.getPropertyIds([]); propertyIds.sort(); expect(propertyIds).toEqual(["color", "isSquare"]); }); it("getProperty returns throws if a property does not exist", function() { expect(function() { return tileMetadata.getProperty("height"); }).toThrowDeveloperError(); }); it("getProperty returns the property value", function() { expect(tileMetadata.getProperty("color")).toEqual([1, 0.5, 0]); expect(tileMetadata.getProperty("isSquare")).toBe(true); }); it("setProperty returns false if property doesn't exist", function() { expect(tileMetadata.setProperty("numberOfPoints", 10)).toBe(false); }); it("setProperty sets property value", function() { expect(tileMetadata.getProperty("isSquare")).toBe(true); expect(tileMetadata.setProperty("isSquare", false)).toBe(true); expect(tileMetadata.getProperty("isSquare")).toBe(false); }); it("getPropertyBySemantic returns undefined when there's no property with the given semantic", function() { expect( tileMetadata.getPropertyBySemantic("HORIZON_OCCLUSION_POINT") ).not.toBeDefined(); }); it("getPropertyBySemantic returns the property value", function() { expect(tileMetadata.getPropertyBySemantic("COLOR")).toEqual([ 1, 0.5, 0 ]); }); it("setPropertyBySemantic sets property value", function() { expect(tileMetadata.getPropertyBySemantic("COLOR")).toEqual([ 1, 0.5, 0 ]); expect(tileMetadata.setPropertyBySemantic("COLOR", [0, 0, 0])).toBe( true ); expect(tileMetadata.getPropertyBySemantic("COLOR")).toEqual([ 0, 0, 0 ]); }); it("setPropertyBySemantic returns false if the semantic doesn't exist", function() { expect(tileMetadata.setPropertyBySemantic("NAME", "Test Tile")).toBe(false); }); }); // packages/engine/Specs/Scene/TileOrientedBoundingBoxSpec.js var import__637 = __toESM(require_Cesium(), 1); var import__638 = __toESM(require_Cesium(), 1); describe("Scene/TileOrientedBoundingBox", function() { const center = new import__637.Cartesian3(0, 0, 0); const halfAxes = import__637.Matrix3.fromScale( new import__637.Cartesian3(0.5, 0.5, 0.5), new import__637.Matrix3() ); const tileBoundingVolume = new import__637.TileOrientedBoundingBox(center, halfAxes); const frameState2 = createFrameState_default(); it("can be instantiated with center and half-axes", function() { expect(tileBoundingVolume.boundingVolume.center).toEqual(center); expect(tileBoundingVolume.boundingVolume.halfAxes).toEqual(halfAxes); expect(tileBoundingVolume.boundingSphere.center).toEqual(center); expect(tileBoundingVolume.boundingSphere.radius).toBeGreaterThan(0.5); expect(tileBoundingVolume.boundingSphere.radius).toBeLessThan(1); }); it("createDebugVolume throws when color is undefined", function() { expect(function() { return tileBoundingVolume.createDebugVolume(); }).toThrowDeveloperError(); }); it("can create debug volume", function() { expect(tileBoundingVolume.createDebugVolume(import__637.Color.BLUE)).toBeDefined(); }); it("distanceToCamera throws when frameState is undefined", function() { expect(function() { return tileBoundingVolume.distanceToCamera(); }).toThrowDeveloperError(); }); it("has distance 0 to camera if camera is inside", function() { frameState2.camera.position = new import__637.Cartesian3(0, 0, 0); expect(tileBoundingVolume.distanceToCamera(frameState2)).toEqual(0); frameState2.camera.position = new import__637.Cartesian3(-0.5, -0.5, -0.5); expect(tileBoundingVolume.distanceToCamera(frameState2)).toEqual(0); frameState2.camera.position = new import__637.Cartesian3(0.5, 0.5, 0.5); expect(tileBoundingVolume.distanceToCamera(frameState2)).toEqual(0); }); it("has correct distance to camera if camera is slightly outside box", function() { const eps6 = import__638.Math.EPSILON6; frameState2.camera.position = new import__637.Cartesian3(0.5 + eps6, 0.5, 0.5); expect(tileBoundingVolume.distanceToCamera(frameState2)).not.toEqual(0); frameState2.camera.position = new import__637.Cartesian3(-0.5, -0.5, -0.5 - eps6); expect(tileBoundingVolume.distanceToCamera(frameState2)).not.toEqual(0); frameState2.camera.position = new import__637.Cartesian3(100.5, 100.5, 100.5); expect(tileBoundingVolume.distanceToCamera(frameState2)).toEqual( Math.sqrt(3e4) ); }); it("has correct distance to camera for large distances", function() { frameState2.camera.position = new import__637.Cartesian3( 2170456713380141e-9, -3635123519646463e-8, 2840332827058654e-8 ); expect(tileBoundingVolume.distanceToCamera(frameState2)).toEqualEpsilon( 4618302905370139e-8, import__638.Math.EPSILON6 ); }); it("intersectPlane throws when plane is undefined", function() { expect(function() { return tileBoundingVolume.intersectPlane(); }).toThrowDeveloperError(); }); it("intersects plane", function() { let plane = new import__637.Plane(import__637.Cartesian3.UNIT_X, 0); expect(tileBoundingVolume.intersectPlane(plane)).toEqual( import__637.Intersect.INTERSECTING ); plane = new import__637.Plane(import__637.Cartesian3.UNIT_X, 0.5 - import__638.Math.EPSILON6); expect(tileBoundingVolume.intersectPlane(plane)).toEqual( import__637.Intersect.INTERSECTING ); plane = new import__637.Plane(import__637.Cartesian3.UNIT_X, -0.5 + import__638.Math.EPSILON6); expect(tileBoundingVolume.intersectPlane(plane)).toEqual( import__637.Intersect.INTERSECTING ); }); it("does not intersect plane", function() { const eps6 = import__638.Math.EPSILON6; let plane = new import__637.Plane(import__637.Cartesian3.UNIT_X, 0.5 + eps6); expect(tileBoundingVolume.intersectPlane(plane)).toEqual(import__637.Intersect.INSIDE); plane = new import__637.Plane(import__637.Cartesian3.UNIT_Y, 0.5 + eps6); expect(tileBoundingVolume.intersectPlane(plane)).toEqual(import__637.Intersect.INSIDE); plane = new import__637.Plane(import__637.Cartesian3.UNIT_Z, 0.5 + eps6); expect(tileBoundingVolume.intersectPlane(plane)).toEqual(import__637.Intersect.INSIDE); plane = new import__637.Plane(import__637.Cartesian3.UNIT_X, -0.5 - eps6); expect(tileBoundingVolume.intersectPlane(plane)).toEqual(import__637.Intersect.OUTSIDE); plane = new import__637.Plane(import__637.Cartesian3.UNIT_Y, -0.5 - eps6); expect(tileBoundingVolume.intersectPlane(plane)).toEqual(import__637.Intersect.OUTSIDE); plane = new import__637.Plane(import__637.Cartesian3.UNIT_Z, -0.5 - eps6); expect(tileBoundingVolume.intersectPlane(plane)).toEqual(import__637.Intersect.OUTSIDE); }); }); // packages/engine/Specs/Scene/TileReplacementQueueSpec.js var import__639 = __toESM(require_Cesium(), 1); describe("Scene/TileReplacementQueue", function() { function Tile(num, loadedState, upsampledState) { this._num = num; this.state = import__639.QuadtreeTileLoadState.LOADING; this.data = {}; this.data.imagery = []; if ((0, import__639.defined)(loadedState)) { this.data.loadedTerrain = { state: loadedState }; } if ((0, import__639.defined)(upsampledState)) { this.data.upsampledTerrain = { state: upsampledState }; } this.eligibleForUnloading = true; } Tile.prototype.freeResources = function() { }; let queue; let one; let two; let three; let four; let notEligibleForUnloading; beforeEach(function() { const tilingScheme = new import__639.GeographicTilingScheme(); queue = new import__639.TileReplacementQueue(); one = new import__639.QuadtreeTile({ tilingScheme, level: 0, x: 0, y: 0 }); two = new import__639.QuadtreeTile({ tilingScheme, level: 0, x: 1, y: 0 }); three = new import__639.QuadtreeTile({ tilingScheme, level: 1, x: 0, y: 0 }); four = new import__639.QuadtreeTile({ tilingScheme, level: 1, x: 2, y: 1 }); notEligibleForUnloading = new import__639.QuadtreeTile({ tilingScheme, level: 1, x: 2, y: 1 }); notEligibleForUnloading.data = { eligibleForUnloading: false }; }); describe("markStartOfRenderFrame", function() { it("prevents tiles added afterward from being trimmed.", function() { queue.markTileRendered(one); queue.markTileRendered(two); queue.markStartOfRenderFrame(); queue.markTileRendered(three); queue.trimTiles(0); expect(queue.count).toEqual(1); expect(queue.head).toEqual(three); }); it("prevents all tiles from being trimmed if called on an empty queue.", function() { queue.markStartOfRenderFrame(); queue.markTileRendered(one); queue.markTileRendered(two); queue.markTileRendered(three); queue.trimTiles(0); expect(queue.count).toEqual(3); }); it("adjusts properly when last tile in previous frame is moved to the head.", function() { queue.markTileRendered(one); queue.markTileRendered(two); queue.markTileRendered(three); queue.markStartOfRenderFrame(); queue.markTileRendered(three); queue.trimTiles(0); expect(queue.count).toEqual(1); expect(queue.head).toEqual(three); }); it("adjusts properly when all tiles are moved to the head.", function() { queue.markTileRendered(one); queue.markTileRendered(two); queue.markTileRendered(three); queue.markStartOfRenderFrame(); queue.markTileRendered(one); queue.markTileRendered(two); queue.markTileRendered(three); queue.trimTiles(0); expect(queue.count).toEqual(3); expect(queue.head).toEqual(three); expect(queue.tail).toEqual(one); }); }); describe("trimTiles", function() { it("does not remove a tile that is not eligible for unloading.", function() { queue.markTileRendered(one); queue.markTileRendered(two); queue.markTileRendered(notEligibleForUnloading); queue.markTileRendered(three); queue.markStartOfRenderFrame(); queue.trimTiles(0); expect(queue.count).toEqual(1); expect(queue.head).toEqual(notEligibleForUnloading); }); it("does not remove a transitioning tile at the end of the last render frame.", function() { queue.markTileRendered(one); queue.markTileRendered(two); queue.markTileRendered(three); queue.markTileRendered(notEligibleForUnloading); queue.markStartOfRenderFrame(); queue.trimTiles(0); expect(queue.count).toEqual(1); expect(queue.head).toEqual(notEligibleForUnloading); }); it("removes two tiles not used last render frame.", function() { queue.markTileRendered(notEligibleForUnloading); queue.markTileRendered(one); queue.markTileRendered(two); queue.markStartOfRenderFrame(); queue.markTileRendered(three); queue.markTileRendered(four); queue.trimTiles(0); expect(queue.count).toEqual(3); }); }); }); // packages/engine/Specs/Scene/Tileset3DTileContentSpec.js var import__640 = __toESM(require_Cesium(), 1); describe( "Scene/Tileset3DTileContent", function() { let scene2; const centerLongitude = -1.31968; const centerLatitude = 0.698874; const tilesetOfTilesetsUrl = "./Data/Cesium3DTiles/Tilesets/TilesetOfTilesets/tileset.json"; beforeAll(function() { scene2 = createScene_default(); const center = import__640.Cartesian3.fromRadians(centerLongitude, centerLatitude); scene2.camera.lookAt(center, new import__640.HeadingPitchRange(0, -1.57, 100)); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.primitives.removeAll(); }); it("becomes ready", async function() { const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, tilesetOfTilesetsUrl ); expect(tileset.root.contentReady).toBeTrue(); expect(tileset.root.content).toBeDefined(); }); it("destroys", function() { return Cesium3DTilesTester_default.tileDestroys(scene2, tilesetOfTilesetsUrl); }); it("gets properties", function() { return Cesium3DTilesTester_default.loadTileset(scene2, tilesetOfTilesetsUrl).then( function(tileset) { const tile = tileset.root; const content = tile.content; expect(content.featuresLength).toBe(0); expect(content.pointsLength).toBe(0); expect(content.trianglesLength).toBe(0); expect(content.geometryByteLength).toBe(0); expect(content.texturesByteLength).toBe(0); expect(content.batchTableByteLength).toBe(0); expect(content.innerContents).toBeUndefined(); expect(content.tileset).toBe(tileset); expect(content.tile).toBe(tile); expect(content.url).toBeDefined(); expect(content.batchTable).toBeUndefined(); expect(content.hasProperty(0, "name")).toBe(false); expect(content.getFeature(0)).toBeUndefined(); } ); }); describe("metadata", function() { let metadataClass; let groupMetadata; let contentMetadataClass; let contentMetadata; beforeAll(function() { metadataClass = import__640.MetadataClass.fromJson({ id: "test", class: { properties: { name: { type: "STRING" }, height: { type: "SCALAR", componentType: "FLOAT32" } } } }); groupMetadata = new import__640.GroupMetadata({ id: "testGroup", group: { properties: { name: "Test Group", height: 35.6 } }, class: metadataClass }); contentMetadataClass = import__640.MetadataClass.fromJson({ id: "contentTest", class: { properties: { author: { type: "STRING" }, color: { type: "VEC3", componentType: "UINT8" } } } }); contentMetadata = new import__640.ContentMetadata({ content: { properties: { author: "Test Author", color: [255, 0, 0] } }, class: contentMetadataClass }); }); it("assigns group metadata", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetOfTilesetsUrl ).then(function(tileset) { const content = tileset.root.content; content.group = new import__640.Cesium3DContentGroup({ metadata: groupMetadata }); expect(content.group.metadata).toBe(groupMetadata); }); }); it("assigns metadata", function() { return Cesium3DTilesTester_default.loadTileset( scene2, tilesetOfTilesetsUrl ).then(function(tileset) { const content = tileset.root.content; content.metadata = contentMetadata; expect(content.metadata).toBe(contentMetadata); }); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/TilesetMetadataSpec.js var import__641 = __toESM(require_Cesium(), 1); describe("Scene/TilesetMetadata", function() { it("creates tileset metadata with default values", function() { const tilesetMetadata = new import__641.TilesetMetadata({ tileset: {}, class: {} }); expect(tilesetMetadata.extras).toBeUndefined(); }); it("creates tileset metadata", function() { const cityClass = import__641.MetadataClass.fromJson({ id: "city", class: { properties: { neighborhoods: { type: "STRING", array: true } } } }); const extras = { other: 0 }; const extensions = { EXT_other_extension: {} }; const properties = { neighborhoods: ["A", "B", "C"] }; const tilesetMetadata = new import__641.TilesetMetadata({ class: cityClass, tileset: { extras, extensions, properties } }); expect(tilesetMetadata.class).toBe(cityClass); expect(tilesetMetadata.extras).toBe(extras); expect(tilesetMetadata.extensions).toBe(extensions); expect(tilesetMetadata.getProperty("neighborhoods")).toEqual( properties.neighborhoods ); }); it("constructor throws without tileset", function() { expect(function() { return new import__641.TilesetMetadata({ class: {} }); }).toThrowDeveloperError(); }); it("constructor throws without class", function() { expect(function() { return new import__641.TilesetMetadata({ tileset: {} }); }).toThrowDeveloperError(); }); it("hasProperty returns false when there's no properties", function() { const tilesetMetadata = new import__641.TilesetMetadata({ tileset: {}, class: {} }); expect(tilesetMetadata.hasProperty("height")).toBe(false); }); it("hasProperty returns false when there's no property with the given property ID", function() { const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" } } } }); const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: { properties: { height: 10 } } }); expect(tilesetMetadata.hasProperty("color")).toBe(false); }); it("hasProperty returns true when there's a property with the given property ID", function() { const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" } } } }); const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: { properties: { height: 10 } } }); expect(tilesetMetadata.hasProperty("height")).toBe(true); }); it("hasProperty returns true when the class has a default value for a missing property", function() { const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32", required: false, default: 10 } } } }); const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: {} }); expect(tilesetMetadata.hasProperty("height")).toBe(true); }); it("hasProperty throws without propertyId", function() { const tilesetMetadata = new import__641.TilesetMetadata({ tileset: {}, class: {} }); expect(function() { tilesetMetadata.hasProperty(); }).toThrowDeveloperError(); }); it("hasPropertyBySemantic returns false when there's no properties", function() { const tilesetMetadata = new import__641.TilesetMetadata({ tileset: {}, class: {} }); expect(tilesetMetadata.hasPropertyBySemantic("HEIGHT")).toBe(false); }); it("hasPropertyBySemantic returns false when there's no property with the given semantic", function() { const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" } } } }); const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: { properties: { height: 10 } } }); expect(tilesetMetadata.hasPropertyBySemantic("HEIGHT")).toBe(false); }); it("hasPropertyBySemantic returns true when there's a property with the given semantic", function() { const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "HEIGHT" } } } }); const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: { properties: { height: 10 } } }); expect(tilesetMetadata.hasPropertyBySemantic("HEIGHT")).toBe(true); }); it("hasPropertyBySemantic returns true when the class has a default value for a missing property", function() { const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "HEIGHT", required: false, default: 10 } } } }); const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: {} }); expect(tilesetMetadata.hasPropertyBySemantic("HEIGHT")).toBe(true); }); it("hasPropertyBySemantic throws without semantic", function() { const tilesetMetadata = new import__641.TilesetMetadata({ tileset: {}, class: {} }); expect(function() { tilesetMetadata.hasPropertyBySemantic(void 0); }).toThrowDeveloperError(); }); it("getPropertyIds returns empty array when there are no properties", function() { const tilesetMetadata = new import__641.TilesetMetadata({ tileset: {}, class: {} }); expect(tilesetMetadata.getPropertyIds().length).toBe(0); }); it("getPropertyIds returns array of property IDs", function() { const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" }, color: { type: "STRING" } } } }); const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: { properties: { height: 10, color: "RED" } } }); expect(tilesetMetadata.getPropertyIds().sort()).toEqual([ "color", "height" ]); }); it("getPropertyIds includes properties with default values", function() { const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32", required: false, default: 10 }, color: { type: "STRING" } } } }); const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: { properties: { color: "RED" } } }); expect(tilesetMetadata.getPropertyIds().sort()).toEqual([ "color", "height" ]); }); it("getPropertyIds uses results argument", function() { const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" }, color: { type: "STRING" } } } }); const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: { properties: { height: 10, color: "RED" } } }); const results = []; const returnedResults = tilesetMetadata.getPropertyIds(results); expect(results).toBe(returnedResults); expect(results.sort()).toEqual(["color", "height"]); }); it("getProperty returns undefined when there's no property with the given property ID", function() { const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" } } } }); const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: { properties: { height: 10 } } }); expect(function() { return tilesetMetadata.getProperty("color"); }).toThrowDeveloperError(); }); it("getProperty returns the property value", function() { const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { position: { type: "VEC3", componentType: "FLOAT32" } } } }); const position = [0, 0, 0]; const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: { properties: { position } } }); const value = tilesetMetadata.getProperty("position"); expect(value).toEqual(import__641.Cartesian3.unpack(position)); }); it("getProperty returns the default value when the property is missing", function() { const position = [0, 0, 0]; const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { position: { type: "VEC3", componentType: "FLOAT32", required: false, default: position } } } }); const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: {} }); const value = tilesetMetadata.getProperty("position"); expect(value).toEqual(import__641.Cartesian3.unpack(position)); }); it("getProperty throws without propertyId", function() { const tilesetMetadata = new import__641.TilesetMetadata({ tileset: {}, class: {} }); expect(function() { tilesetMetadata.getProperty(); }).toThrowDeveloperError(); }); it("setProperty returns false if property doesn't exist", function() { const tilesetMetadata = new import__641.TilesetMetadata({ tileset: {}, class: {} }); const position = [0, 0, 0]; expect(tilesetMetadata.setProperty("position", position)).toBe(false); }); it("setProperty sets property value", function() { const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { position: { type: "VEC3", componentType: "FLOAT32" } } } }); const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: { properties: { position: [0, 0, 0] } } }); const position = new import__641.Cartesian3(1, 1, 1); expect(tilesetMetadata.setProperty("position", position)).toBe(true); expect(tilesetMetadata.getProperty("position")).toEqual(position); expect(tilesetMetadata.getProperty("position")).not.toBe(position); }); it("setProperty throws without propertyId", function() { const tilesetMetadata = new import__641.TilesetMetadata({ tileset: {}, class: {} }); expect(function() { tilesetMetadata.setProperty(); }).toThrowDeveloperError(); }); it("setProperty throws without value", function() { const tilesetMetadata = new import__641.TilesetMetadata({ tileset: {}, class: {} }); expect(function() { tilesetMetadata.setProperty("color"); }).toThrowDeveloperError(); }); it("getPropertyBySemantic returns undefined when there's no class", function() { const tilesetMetadata = new import__641.TilesetMetadata({ tileset: {}, class: {} }); expect(tilesetMetadata.getPropertyBySemantic("_HEIGHT")).toBeUndefined(); }); it("getPropertyBySemantic returns undefined when there's no property with the given semantic", function() { const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" } } } }); const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: { properties: { height: 10 } } }); expect(tilesetMetadata.getPropertyBySemantic("_HEIGHT")).toBeUndefined(); }); it("getPropertyBySemantic returns the property value", function() { const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "_HEIGHT" } } } }); const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: { properties: { height: 10 } } }); expect(tilesetMetadata.getPropertyBySemantic("_HEIGHT")).toBe(10); }); it("getPropertyBySemantic throws without semantic", function() { const tilesetMetadata = new import__641.TilesetMetadata({ tileset: {}, class: {} }); expect(function() { tilesetMetadata.getPropertyBySemantic(); }).toThrowDeveloperError(); }); it("setPropertyBySemantic sets property value", function() { const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "_HEIGHT" } } } }); const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: { properties: { height: 10 } } }); expect(tilesetMetadata.setPropertyBySemantic("_HEIGHT", 20)).toBe(true); expect(tilesetMetadata.getProperty("height")).toBe(20); }); it("setPropertyBySemantic returns false if semantic does not exist", function() { const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" } } } }); const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: { properties: { height: 10 } } }); expect(tilesetMetadata.setPropertyBySemantic("_HEIGHT", 20)).toBe(false); }); it("setPropertyBySemantic throws without semantic", function() { const tilesetMetadata = new import__641.TilesetMetadata({ tileset: {}, class: {} }); expect(function() { tilesetMetadata.setPropertyBySemantic(); }).toThrowDeveloperError(); }); it("setPropertyBySemantic throws without value", function() { const buildingClass = import__641.MetadataClass.fromJson({ id: "building", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32", semantic: "_HEIGHT" } } } }); const tilesetMetadata = new import__641.TilesetMetadata({ class: buildingClass, tileset: { properties: { height: 10 } } }); expect(function() { tilesetMetadata.setPropertyBySemantic("_HEIGHT"); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/TimeDynamicImagerySpec.js var import__642 = __toESM(require_Cesium(), 1); describe("Scene/TimeDynamicImagery", function() { const clock = new import__642.Clock({ clockStep: import__642.ClockStep.TICK_DEPENDENT, shouldAnimate: true }); const times = import__642.TimeIntervalCollection.fromIso8601({ iso8601: "2017-04-26/2017-04-30/P1D", dataCallback: function(interval, index) { return { Time: import__642.JulianDate.toIso8601(interval.start) }; } }); beforeEach(function() { import__642.RequestScheduler.clearForSpecs(); clock.currentTime = import__642.JulianDate.fromIso8601("2017-04-26"); }); it("clock is required", function() { expect(function() { return new import__642.TimeDynamicImagery({ times, requestImageFunction: function() { }, reloadFunction: function() { } }); }).toThrowDeveloperError(); }); it("times is required", function() { expect(function() { return new import__642.TimeDynamicImagery({ clock, requestImageFunction: function() { }, reloadFunction: function() { } }); }).toThrowDeveloperError(); }); it("requestImageFunction is required", function() { expect(function() { return new import__642.TimeDynamicImagery({ clock, times, reloadFunction: function() { } }); }).toThrowDeveloperError(); }); it("reloadFunction is required", function() { expect(function() { return new import__642.TimeDynamicImagery({ clock, times, requestImageFunction: function() { } }); }).toThrowDeveloperError(); }); it("initialization", function() { const options = { clock, times, requestImageFunction: function() { }, reloadFunction: function() { } }; const timeDynamicImagery = new import__642.TimeDynamicImagery(options); expect(timeDynamicImagery._tileCache).toEqual({}); expect(timeDynamicImagery._tilesRequestedForInterval).toEqual([]); expect(timeDynamicImagery._clock).toBe(options.clock); expect(timeDynamicImagery._times).toBe(options.times); expect(timeDynamicImagery._requestImageFunction).toBe( options.requestImageFunction ); expect(timeDynamicImagery._reloadFunction).toBe(options.reloadFunction); expect(timeDynamicImagery._currentIntervalIndex).toEqual(0); }); it("changing clock causes reload", function() { const options = { clock, times, requestImageFunction: function() { }, reloadFunction: jasmine.createSpy() }; const timeDynamicImagery = new import__642.TimeDynamicImagery(options); timeDynamicImagery.clock = new import__642.Clock(); expect(options.reloadFunction).toHaveBeenCalled(); }); it("changing times causes reload", function() { const options = { clock, times, requestImageFunction: function() { }, reloadFunction: jasmine.createSpy() }; const timeDynamicImagery = new import__642.TimeDynamicImagery(options); timeDynamicImagery.times = new import__642.TimeIntervalCollection(); expect(options.reloadFunction).toHaveBeenCalled(); }); it("clock.tick() causes reload", function() { const options = { clock, times, requestImageFunction: jasmine.createSpy(), reloadFunction: jasmine.createSpy() }; const timeDynamicImagery = new import__642.TimeDynamicImagery(options); const request = new import__642.Request(); timeDynamicImagery.checkApproachingInterval(0, 1, 2, request); clock.currentTime = import__642.JulianDate.fromIso8601("2017-04-26T23:59:59Z"); clock.tick(); expect(options.requestImageFunction).not.toHaveBeenCalled(); expect(options.reloadFunction).toHaveBeenCalled(); }); it("clock.tick() causes preload", function() { const options = { clock, times, requestImageFunction: jasmine.createSpy().and.returnValue(Promise.resolve()), reloadFunction: jasmine.createSpy() }; const timeDynamicImagery = new import__642.TimeDynamicImagery(options); options.reloadFunction.calls.reset(); const request = new import__642.Request({ throttle: false, throttleByServer: true, type: import__642.RequestType.IMAGERY }); timeDynamicImagery.checkApproachingInterval(0, 1, 2, request); clock.currentTime = import__642.JulianDate.fromIso8601("2017-04-26T23:59:56Z"); clock.tick(); expect(options.requestImageFunction).toHaveBeenCalledWith( 0, 1, 2, request, times.get(1) ); expect(timeDynamicImagery._tileCache[1]["0-1-2"]).toBeDefined(); expect(options.reloadFunction).not.toHaveBeenCalled(); }); it("checkApproachingInterval causes preload", function() { const options = { clock, times, requestImageFunction: jasmine.createSpy().and.returnValue(Promise.resolve()), reloadFunction: jasmine.createSpy() }; const timeDynamicImagery = new import__642.TimeDynamicImagery(options); options.reloadFunction.calls.reset(); const request = new import__642.Request({ throttle: false, throttleByServer: true, type: import__642.RequestType.IMAGERY }); clock.currentTime = import__642.JulianDate.fromIso8601("2017-04-26T23:59:56Z"); timeDynamicImagery.checkApproachingInterval(0, 1, 2, request); expect(options.requestImageFunction).toHaveBeenCalledWith( 0, 1, 2, request, times.get(1) ); expect(timeDynamicImagery._tileCache[1]["0-1-2"]).toBeDefined(); expect(options.reloadFunction).not.toHaveBeenCalled(); }); it("checkApproachingInterval limits number of requests", function() { const options = { clock, times, requestImageFunction: jasmine.createSpy().and.returnValue(Promise.resolve()), reloadFunction: jasmine.createSpy() }; const timeDynamicImagery = new import__642.TimeDynamicImagery(options); const request = new import__642.Request({ throttle: true, throttleByServer: true, type: import__642.RequestType.IMAGERY }); let count = 0; for (let level = 0; level < 15; ++level) { for (let x = 0; x < level + 1; ++x) { for (let y = 0; y < level + 1; ++y) { timeDynamicImagery.checkApproachingInterval(x, y, level, request); ++count; if (count === 512) { count = 256; } expect(timeDynamicImagery._tilesRequestedForInterval.length).toEqual( count ); expect( timeDynamicImagery._tilesRequestedForInterval[count - 1].key ).toEqual(`${x}-${y}-${level}`); } } } }); }); // packages/engine/Specs/Scene/TimeDynamicPointCloudSpec.js var import__643 = __toESM(require_Cesium(), 1); describe( "Scene/TimeDynamicPointCloud", function() { let scene2; const center = new import__643.Cartesian3( 1.2150128828876738e6, -4736313051199594e-9, 408160522126042e-8 ); const clock = new import__643.Clock({ clockStep: import__643.ClockStep.TICK_DEPENDENT, shouldAnimate: true }); const dates = [ import__643.JulianDate.fromIso8601("2018-07-19T15:18:00Z"), import__643.JulianDate.fromIso8601("2018-07-19T15:18:00.5Z"), import__643.JulianDate.fromIso8601("2018-07-19T15:18:01Z"), import__643.JulianDate.fromIso8601("2018-07-19T15:18:01.5Z"), import__643.JulianDate.fromIso8601("2018-07-19T15:18:02Z"), import__643.JulianDate.fromIso8601("2018-07-19T15:18:02.5Z") ]; const transforms = [ import__643.Matrix4.fromColumnMajorArray([ 0.968635634376879, 0.24848542777253735, 0, 0, -0.15986460794399626, 0.6231776137472074, 0.7655670897127491, 0, 0.190232265775849, -0.7415555636019701, 0.6433560687121489, 0, 1.2150128828876738e6, -4736313051199594e-9, 408160522126042e-8, 1 ]), import__643.Matrix4.fromColumnMajorArray([ 0.968634888916237, 0.24848833367832227, 0, 0, -0.1598664774761181, 0.6231771341505793, 0.7655670897127493, 0, 0.19023449044168372, -0.7415549929018358, 0.6433560687121489, 0, 1.2150270918213597e6, -4736309406139632e-9, 408160522126042e-8, 1 ]), import__643.Matrix4.fromColumnMajorArray([ 0.9686341434468771, 0.24849123958187078, 0, 0, -0.1598683470068011, 0.6231766545483426, 0.7655670897127493, 0, 0.19023671510580634, -0.7415544221950274, 0.6433560687121489, 0, 1.2150413007441103e6, -4736305761037043e-9, 408160522126042e-8, 1 ]), import__643.Matrix4.fromColumnMajorArray([ 0.9686333979687994, 0.24849414548318288, 0, 0, -0.15987021653604533, 0.6231761749404972, 0.7655670897127491, 0, 0.19023893976821685, -0.7415538514815451, 0.6433560687121489, 0, 1.2150555096559257e6, -4736302115891827e-9, 408160522126042e-8, 1 ]), import__643.Matrix4.fromColumnMajorArray([ 0.9686326524820043, 0.2484970513822586, 0, 0, -0.15987208606385075, 0.6231756953270434, 0.7655670897127492, 0, 0.19024116442891523, -0.7415532807613887, 0.6433560687121489, 0, 1.2150697185568055e6, -4736298470703985e-9, 408160522126042e-8, 1 ]) ]; function createIntervals(useTransforms, useDraco) { let folderName; if (useTransforms) { folderName = "Data/Cesium3DTiles/PointCloud/PointCloudTimeDynamicWithTransform/"; } else if (useDraco) { folderName = "Data/Cesium3DTiles/PointCloud/PointCloudTimeDynamicDraco/"; } else { folderName = "Data/Cesium3DTiles/PointCloud/PointCloudTimeDynamic/"; } const uris = []; for (let i = 0; i < 5; ++i) { uris.push(`${folderName + i}.pnts`); } function dataCallback(interval, index) { return { uri: uris[index], transform: useTransforms ? transforms[index] : void 0 }; } return import__643.TimeIntervalCollection.fromJulianDateArray({ julianDates: dates, dataCallback }); } function createTimeDynamicPointCloud(options) { options = (0, import__643.defaultValue)(options, {}); const useTransforms = (0, import__643.defaultValue)(options.useTransforms, false); const useDraco = (0, import__643.defaultValue)(options.useDraco, false); options.intervals = createIntervals(useTransforms, useDraco); options.clock = clock; if (!(0, import__643.defined)(options.style)) { options.style = new import__643.Cesium3DTileStyle({ color: 'color("red")', pointSize: 10 }); } return scene2.primitives.add(new import__643.TimeDynamicPointCloud(options)); } function zoomTo(center2) { scene2.camera.lookAt(center2, new import__643.HeadingPitchRange(0, -1.57, 5)); } function loadFrame(pointCloud, index) { index = (0, import__643.defaultValue)(index, 0); goToFrame(index); return pollToPromise_default(function() { scene2.renderForSpecs(); const frame = pointCloud._frames[index]; const ready = (0, import__643.defined)(frame) && frame.ready; if (ready) { scene2.renderForSpecs(); } return ready; }); } function getLoadFrameFunction(pointCloud, index) { return function() { return loadFrame(pointCloud, index); }; } function loadFrames(pointCloud, indexes) { const length2 = indexes.length; let promise = getLoadFrameFunction(pointCloud, indexes[0])(); for (let i = 1; i < length2; ++i) { promise = promise.then(getLoadFrameFunction(pointCloud, indexes[i])); } return promise.then(function() { goToFrame(indexes[0]); }); } function loadAllFrames(pointCloud) { return loadFrames(pointCloud, [0, 1, 2, 3, 4]); } function goToFrame(index) { clock.currentTime = dates[index]; clock.multiplier = 0; } function initializeScene() { scene2.morphTo3D(0); zoomTo(center); goToFrame(0); } beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { initializeScene(); }); afterEach(function() { scene2.primitives.removeAll(); }); it("throws if options.clock is undefined", function() { const intervals = createIntervals(); expect(function() { return new import__643.TimeDynamicPointCloud({ intervals }); }).toThrowDeveloperError(); }); it("throws if options.intervals is undefined", function() { expect(function() { return new import__643.TimeDynamicPointCloud({ clock }); }).toThrowDeveloperError(); }); it("renders in 3D", function() { const pointCloud = createTimeDynamicPointCloud(); return loadFrame(pointCloud).then(function() { scene2.morphTo3D(0); expect(scene2).toRender([255, 0, 0, 255]); goToFrame(1); expect(scene2).toRender([255, 0, 0, 255]); scene2.camera.moveRight(10); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("renders in 2D", function() { const pointCloud = createTimeDynamicPointCloud(); return loadFrame(pointCloud).then(function() { scene2.morphTo2D(0); expect(scene2).toRender([255, 0, 0, 255]); goToFrame(1); expect(scene2).toRender([255, 0, 0, 255]); scene2.camera.moveRight(10); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("renders in CV", function() { const pointCloud = createTimeDynamicPointCloud(); return loadFrame(pointCloud).then(function() { scene2.morphToColumbusView(0); expect(scene2).toRender([255, 0, 0, 255]); goToFrame(1); expect(scene2).toRender([255, 0, 0, 255]); scene2.camera.moveRight(10); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("gets bounding sphere of the rendered frame", function() { const pointCloud = createTimeDynamicPointCloud({ useTransforms: true }); expect(pointCloud.boundingSphere).toBeUndefined(); return loadAllFrames(pointCloud).then(function() { const boundingSphereFrame0 = pointCloud.boundingSphere; expect(boundingSphereFrame0).toBeDefined(); goToFrame(1); scene2.renderForSpecs(); const boundingSphereFrame1 = pointCloud.boundingSphere; expect(boundingSphereFrame1).toBeDefined(); expect( import__643.BoundingSphere.equals(boundingSphereFrame0, boundingSphereFrame1) ).toBe(false); }); }); it("sets show", function() { const pointCloud = createTimeDynamicPointCloud(); return loadFrame(pointCloud).then(function() { expect(scene2).toRender([255, 0, 0, 255]); pointCloud.show = false; expect(scene2).toRender([0, 0, 0, 255]); }); }); it("sets model matrix", function() { const translation = new import__643.Cartesian3(1e4, 2e3, 100); const modelMatrix = import__643.Matrix4.fromTranslation(translation); const newCenter = import__643.Cartesian3.add(center, translation, new import__643.Cartesian3()); const pointCloud = createTimeDynamicPointCloud({ modelMatrix }); return loadFrame(pointCloud).then(function() { expect(scene2).toRender([0, 0, 0, 255]); zoomTo(newCenter); expect(scene2).toRender([255, 0, 0, 255]); pointCloud.modelMatrix = import__643.Matrix4.IDENTITY; expect(scene2).toRender([0, 0, 0, 255]); zoomTo(center); expect(scene2).toRender([255, 0, 0, 255]); }); }); it("sets shadows", function() { const pointCloud = createTimeDynamicPointCloud({ shadows: import__643.ShadowMode.DISABLED }); return loadFrame(pointCloud).then(function() { scene2.renderForSpecs(); expect(scene2.frameState.commandList[0].castShadows).toBe(false); expect(scene2.frameState.commandList[0].receiveShadows).toBe(false); pointCloud.shadows = import__643.ShadowMode.ENABLED; scene2.renderForSpecs(); expect(scene2.frameState.commandList[0].castShadows).toBe(true); expect(scene2.frameState.commandList[0].receiveShadows).toBe(true); }); }); it("honors maximumMemoryUsage by unloading all frames not currently being loaded or rendered", function() { const pointCloud = createTimeDynamicPointCloud(); return loadAllFrames(pointCloud).then(function() { const singleFrameMemoryUsage = 33e3; const frames = pointCloud._frames; const framesLength = frames.length; expect(pointCloud.totalMemoryUsageInBytes).toBe( singleFrameMemoryUsage * framesLength ); pointCloud.maximumMemoryUsage = 0; scene2.renderForSpecs(); expect(pointCloud.totalMemoryUsageInBytes).toBe(singleFrameMemoryUsage); expect(frames[0].ready).toBe(true); for (let i = 1; i < length; ++i) { expect(frames[i]).toBeUndefined(); } goToFrame(1); scene2.renderForSpecs(); expect(pointCloud.totalMemoryUsageInBytes).toBe(singleFrameMemoryUsage); expect(frames[0].ready).toBe(true); expect(frames[1].ready).toBe(false); return loadFrame(pointCloud, 1).then(function() { expect(pointCloud.totalMemoryUsageInBytes).toBe( singleFrameMemoryUsage ); expect(frames[0]).toBeUndefined(); expect(frames[1].ready).toBe(true); }); }); }); it("enables attenuation and eye dome lighting", function() { const oldScene = scene2; scene2 = createScene_default({ canvas: createCanvas_default(100, 100) }); initializeScene(); const pointCloud = createTimeDynamicPointCloud({ shading: { attenuation: true, eyeDomeLighting: false }, style: new import__643.Cesium3DTileStyle() }); return loadFrame(pointCloud).then(function() { let attenuationPixelCount; expect(scene2).toRenderPixelCountAndCall(function(pixelCount) { attenuationPixelCount = pixelCount; }); pointCloud.shading.attenuation = false; expect(scene2).toRenderPixelCountAndCall(function(pixelCount) { expect(pixelCount).toBeLessThan(attenuationPixelCount); }); scene2.destroyForSpecs(); scene2 = oldScene; }); }); it("enabled eye dome lighting", function() { if (!import__643.PointCloudEyeDomeLighting.isSupported(scene2.frameState.context)) { return; } const pointCloud = createTimeDynamicPointCloud(); return loadFrame(pointCloud).then(function() { expect(scene2.frameState.commandList.length).toBe(1); pointCloud.shading.attenuation = true; pointCloud.shading.eyeDomeLighting = true; scene2.renderForSpecs(); expect(scene2.frameState.commandList.length).toBe(3); }); }); it("sets style", function() { const pointCloud = createTimeDynamicPointCloud({ style: new import__643.Cesium3DTileStyle({ color: 'color("blue")', pointSize: 10 }) }); return loadAllFrames(pointCloud).then(function() { expect(scene2).toRender([0, 0, 255, 255]); pointCloud.style = new import__643.Cesium3DTileStyle({ color: 'color("lime")', pointSize: 10 }); expect(scene2).toRender([0, 255, 0, 255]); goToFrame(1); expect(scene2).toRender([0, 255, 0, 255]); }); }); it("make style dirty", function() { const pointCloud = createTimeDynamicPointCloud({ style: new import__643.Cesium3DTileStyle({ color: 'color("blue")', pointSize: 10 }) }); return loadAllFrames(pointCloud).then(function() { expect(scene2).toRender([0, 0, 255, 255]); pointCloud.style.color = 'color("lime")'; pointCloud.makeStyleDirty(); expect(scene2).toRender([0, 255, 0, 255]); goToFrame(1); expect(scene2).toRender([0, 255, 0, 255]); }); }); it("sets clipping planes", function() { const modelMatrix = new import__643.Transforms.headingPitchRollToFixedFrame( center, new import__643.HeadingPitchRoll(0, 0, 0) ); const clippingPlanesX = new import__643.ClippingPlaneCollection({ modelMatrix, planes: [new import__643.ClippingPlane(import__643.Cartesian3.UNIT_X, 0)] }); const clippingPlanesY = new import__643.ClippingPlaneCollection({ modelMatrix, planes: [new import__643.ClippingPlane(import__643.Cartesian3.UNIT_Y, 0)] }); const pointCloud = createTimeDynamicPointCloud({ clippingPlanes: clippingPlanesX }); return loadAllFrames(pointCloud).then(function() { scene2.camera.moveRight(0.1); goToFrame(0); expect(scene2).toRender([255, 0, 0, 255]); goToFrame(1); expect(scene2).toRender([255, 0, 0, 255]); scene2.camera.moveLeft(0.2); goToFrame(0); expect(scene2).toRender([0, 0, 0, 255]); goToFrame(1); expect(scene2).toRender([0, 0, 0, 255]); pointCloud.clippingPlanes.enabled = false; goToFrame(0); expect(scene2).toRender([255, 0, 0, 255]); goToFrame(1); expect(scene2).toRender([255, 0, 0, 255]); pointCloud.clippingPlanes = clippingPlanesY; scene2.camera.moveRight(0.2); scene2.camera.moveUp(0.1); goToFrame(0); expect(scene2).toRender([255, 0, 0, 255]); goToFrame(1); expect(scene2).toRender([255, 0, 0, 255]); scene2.camera.moveDown(0.2); goToFrame(0); expect(scene2).toRender([0, 0, 0, 255]); goToFrame(1); expect(scene2).toRender([0, 0, 0, 255]); }); }); it("works with frame transforms", function() { const pointCloud = createTimeDynamicPointCloud({ useTransforms: true }); return loadAllFrames(pointCloud).then(function() { goToFrame(0); expect(scene2).toRender([255, 0, 0, 255]); goToFrame(1); expect(scene2).toRender([0, 0, 0, 255]); scene2.camera.moveRight(10); expect(scene2).toRender([255, 0, 0, 255]); }); }); it("does not render during morph", function() { const pointCloud = createTimeDynamicPointCloud(); return loadFrame(pointCloud).then(function() { scene2.renderForSpecs(); expect(scene2.frameState.commandList.length).toBeGreaterThan(0); scene2.morphToColumbusView(1); scene2.renderForSpecs(); expect(scene2.frameState.commandList.length).toBe(0); }); }); it("renders frames using Draco compression", function() { const pointCloud = createTimeDynamicPointCloud({ useDraco: true }); return loadFrame(pointCloud).then(function() { expect(scene2).toRender([255, 0, 0, 255]); }); }); it("picks", function() { const pointCloud = createTimeDynamicPointCloud(); return loadFrame(pointCloud).then(function() { pointCloud.show = false; expect(scene2).toPickPrimitive(void 0); pointCloud.show = true; expect(scene2).toPickPrimitive(pointCloud); }); }); it("does not render if current time is out of range", function() { const pointCloud = createTimeDynamicPointCloud(); return loadFrame(pointCloud).then(function() { clock.currentTime = import__643.JulianDate.addSeconds( dates[0], -10, new import__643.JulianDate() ); scene2.renderForSpecs(); expect(scene2.frameState.commandList.length).toBe(0); clock.currentTime = dates[0]; scene2.renderForSpecs(); expect(scene2.frameState.commandList.length).toBe(1); clock.currentTime = import__643.JulianDate.addSeconds( dates[5], 10, new import__643.JulianDate() ); scene2.renderForSpecs(); expect(scene2.frameState.commandList.length).toBe(0); }); }); it("prefetches different frame when clock multiplier changes", function() { const pointCloud = createTimeDynamicPointCloud(); spyOn(pointCloud, "_getAverageLoadTime").and.returnValue(0.5); return loadFrame(pointCloud).then(function() { expect(pointCloud._frames[1]).toBeUndefined(); clock.multiplier = 1; scene2.renderForSpecs(); expect(pointCloud._frames[1]).toBeDefined(); clock.multiplier = 4; scene2.renderForSpecs(); expect(pointCloud._frames[2]).toBeUndefined(); expect(pointCloud._frames[3]).toBeUndefined(); expect(pointCloud._frames[4]).toBeDefined(); }); }); it("renders last rendered frame while new frame loads", function() { const pointCloud = createTimeDynamicPointCloud(); return loadFrame(pointCloud).then(function() { const commandList = scene2.frameState.commandList; const firstFrameCommand = commandList[0]; goToFrame(4); return pollToPromise_default(function() { scene2.renderForSpecs(); const frame = pointCloud._frames[4]; const ready = (0, import__643.defined)(frame) && frame.ready; if (!ready) { expect(commandList[0]).toBe(firstFrameCommand); } return ready; }).then(function() { scene2.renderForSpecs(); expect(commandList[0]).toBeDefined(); expect(commandList[0]).not.toBe(firstFrameCommand); }); }); }); it("skips frames based on average load time and clock multiplier", function() { const pointCloud = createTimeDynamicPointCloud(); spyOn(pointCloud, "_getAverageLoadTime").and.returnValue(2); scene2.renderForSpecs(); clock.multiplier = 0.6; scene2.renderForSpecs(); clock.tick(); scene2.renderForSpecs(); clock.tick(); scene2.renderForSpecs(); clock.tick(); scene2.renderForSpecs(); clock.tick(); scene2.renderForSpecs(); const frames = pointCloud._frames; expect(frames[0]).toBeDefined(); expect(frames[1]).toBeUndefined(); expect(frames[2]).toBeDefined(); expect(frames[3]).toBeUndefined(); expect(frames[4]).toBeDefined(); }); it("does not skip frames if clock multiplier is sufficiently slow", function() { const pointCloud = createTimeDynamicPointCloud(); spyOn(pointCloud, "_getAverageLoadTime").and.returnValue(0.5); scene2.renderForSpecs(); clock.multiplier = 0.6; scene2.renderForSpecs(); clock.tick(); scene2.renderForSpecs(); clock.tick(); scene2.renderForSpecs(); clock.tick(); scene2.renderForSpecs(); clock.tick(); scene2.renderForSpecs(); const frames = pointCloud._frames; expect(frames[0]).toBeDefined(); expect(frames[1]).toBeDefined(); expect(frames[2]).toBeDefined(); expect(frames[3]).toBeDefined(); expect(frames[4]).toBeDefined(); }); it("renders loaded frames between the previous frame and next frame", function() { const pointCloud = createTimeDynamicPointCloud(); spyOn(pointCloud, "_getAverageLoadTime").and.returnValue(3.4); const frames = pointCloud._frames; return loadFrames(pointCloud, [0, 2]).then(function() { clock.multiplier = 0.6; scene2.renderForSpecs(); expect(pointCloud._lastRenderedFrame).toBe(frames[0]); clock.tick(); scene2.renderForSpecs(); expect(pointCloud._lastRenderedFrame).toBe(frames[0]); clock.tick(); scene2.renderForSpecs(); expect(pointCloud._lastRenderedFrame).toBe(frames[2]); clock.tick(); scene2.renderForSpecs(); expect(pointCloud._lastRenderedFrame).toBe(frames[2]); }); }); it("works with negative clock multiplier", function() { const pointCloud = createTimeDynamicPointCloud(); spyOn(pointCloud, "_getAverageLoadTime").and.returnValue(2); goToFrame(4); scene2.renderForSpecs(); clock.multiplier = -0.6; scene2.renderForSpecs(); clock.tick(); scene2.renderForSpecs(); clock.tick(); scene2.renderForSpecs(); clock.tick(); scene2.renderForSpecs(); clock.tick(); scene2.renderForSpecs(); const frames = pointCloud._frames; expect(frames[0]).toBeUndefined(); expect(frames[1]).toBeDefined(); expect(frames[2]).toBeUndefined(); expect(frames[3]).toBeUndefined(); expect(frames[4]).toBeDefined(); }); it("frames not loaded in sequential updates do not impact average load time", function() { const pointCloud = createTimeDynamicPointCloud(); expect(pointCloud._runningAverage).toBe(0); return loadFrame(pointCloud).then(function() { expect(pointCloud._frames[0].sequential).toBe(true); expect(pointCloud._runningLength).toBe(1); expect(pointCloud._runningAverage).toBeGreaterThan(0); goToFrame(2); scene2.renderForSpecs(); return loadFrame(pointCloud, 1).then(function() { const twoFrameAverage = pointCloud._runningAverage; expect(pointCloud._frames[1].sequential).toBe(true); expect(pointCloud._runningLength).toBe(2); expect(pointCloud._runningAverage).toBeGreaterThan(0); return loadFrame(pointCloud, 2).then(function() { expect(pointCloud._frames[2].sequential).toBe(false); expect(pointCloud._runningLength).toBe(2); expect(pointCloud._runningAverage).toBe(twoFrameAverage); }); }); }); }); it("frame failed event is raised from request failure", function() { const pointCloud = createTimeDynamicPointCloud(); let frameRejectedCount = 0; spyOn(import__643.Resource._Implementations, "loadWithXhr").and.callFake(function(request, responseType, method, data, headers, deferred, overrideMimeType) { if (request.toString().includes("PointCloudTimeDynamic")) { deferred.reject("404"); deferred.promise.catch(function() { frameRejectedCount++; }); } }); const spyUpdate = jasmine.createSpy("listener"); pointCloud.frameFailed.addEventListener(spyUpdate); let i; for (i = 0; i < 5; ++i) { goToFrame(i); scene2.renderForSpecs(); } return pollToPromise_default(function() { scene2.renderForSpecs(); return frameRejectedCount === 5; }).then(function() { expect(spyUpdate.calls.count()).toEqual(5); for (i = 0; i < 5; ++i) { const arg = spyUpdate.calls.argsFor(i)[0]; expect(arg).toBeDefined(); expect(arg.uri).toContain(`${i}.pnts`); expect(arg.message).toBe("404"); } }); }); it("failed frame event is raised from Draco failure", function() { const pointCloud = createTimeDynamicPointCloud({ useDraco: true }); return loadFrame(pointCloud).then(function() { const decoder = import__643.DracoLoader._getDecoderTaskProcessor(); let frameFailed = false; spyOn(decoder, "scheduleTask").and.callFake(function() { return Promise.reject({ message: "my error" }); }); pointCloud.frameFailed.addEventListener((error) => { frameFailed = true; expect(error).toBeDefined(); expect(error.uri).toContain("1.pnts"); expect(error.message).toBe("my error"); }); goToFrame(1); scene2.renderForSpecs(); return pollToPromise_default(function() { scene2.renderForSpecs(); return frameFailed; }); }); }); it("raises frame changed event", function() { const pointCloud = createTimeDynamicPointCloud(); const spyFrameChanged = jasmine.createSpy("listener"); pointCloud.frameChanged.addEventListener(spyFrameChanged); return loadAllFrames(pointCloud).then(function() { expect(spyFrameChanged.calls.count()).toBe(5); goToFrame(2); scene2.renderForSpecs(); expect(spyFrameChanged.calls.count()).toBe(6); clock.currentTime = import__643.JulianDate.addSeconds( dates[0], -10, new import__643.JulianDate() ); scene2.renderForSpecs(); expect(spyFrameChanged.calls.count()).toBe(6); goToFrame(0); scene2.renderForSpecs(); expect(spyFrameChanged.calls.count()).toBe(7); expect(spyFrameChanged.calls.argsFor(0)[0]).toBe(pointCloud); }); }); it("destroys", function() { const pointCloud = createTimeDynamicPointCloud(); return loadAllFrames(pointCloud).then(function() { expect(pointCloud.isDestroyed()).toEqual(false); scene2.primitives.remove(pointCloud); expect(pointCloud.isDestroyed()).toEqual(true); expect(pointCloud.totalMemoryUsageInBytes).toBe(0); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/TranslucentTileClassificationSpec.js var import__644 = __toESM(require_Cesium(), 1); describe( "Scene/TranslucentTileClassification", function() { let scene2; let context; let passState; let globeDepthFramebuffer; let ellipsoid; const positions = import__644.Cartesian3.fromDegreesArray([0.01, 0, 0.03, 0]); const lookPosition = import__644.Cartesian3.fromDegrees(0.02, 0); const lookOffset = new import__644.Cartesian3(0, 0, 10); let translucentPrimitive; let groundPolylinePrimitive; beforeAll(function() { scene2 = createScene_default(); scene2.postProcessStages.fxaa.enabled = false; scene2.render(); context = scene2.context; passState = scene2._defaultView.passState; if ((0, import__644.defined)(scene2._defaultView.globeDepth)) { globeDepthFramebuffer = scene2._defaultView.globeDepth.framebuffer; } ellipsoid = import__644.Ellipsoid.WGS84; return import__644.GroundPolylinePrimitive.initializeTerrainHeights(); }); afterAll(function() { scene2.destroyForSpecs(); import__644.ApproximateTerrainHeights._initPromise = void 0; import__644.ApproximateTerrainHeights._terrainHeights = void 0; }); function SpecPrimitive(primitive, pass) { this._primitive = primitive; this._depthForTranslucentClassification = pass === import__644.Pass.TRANSLUCENT; this._pass = pass; this.commands = []; } SpecPrimitive.prototype.update = function(frameState2) { const commandList = frameState2.commandList; const startLength = commandList.length; this._primitive.update(frameState2); this.commands = []; for (let i = startLength; i < commandList.length; ++i) { const command = commandList[i]; command.pass = this._pass; command.depthForTranslucentClassification = this._depthForTranslucentClassification; this.commands.push(command); } }; SpecPrimitive.prototype.isDestroyed = function() { return false; }; SpecPrimitive.prototype.destroy = function() { this._primitive.destroy(); return (0, import__644.destroyObject)(this); }; beforeEach(function() { scene2.morphTo3D(0); scene2.render(); scene2.camera.lookAt(lookPosition, lookOffset); const renderState = import__644.RenderState.fromCache({ stencilTest: import__644.StencilConstants.setCesium3DTileBit(), stencilMask: import__644.StencilConstants.CESIUM_3D_TILE_MASK, depthTest: { enabled: true } }); let primitive = new import__644.Primitive({ geometryInstances: new import__644.GeometryInstance({ geometry: new import__644.RectangleGeometry({ ellipsoid, rectangle: import__644.Rectangle.fromDegrees(-0.1, -0.1, 0.1, 0.1), height: 1 }), attributes: { color: import__644.ColorGeometryInstanceAttribute.fromColor( new import__644.Color(0, 0, 1, 0.5) ) } }), appearance: new import__644.PerInstanceColorAppearance({ translucent: true, flat: true, renderState }), asynchronous: false }); translucentPrimitive = new SpecPrimitive(primitive, import__644.Pass.TRANSLUCENT); scene2.primitives.add(translucentPrimitive); primitive = new import__644.GroundPolylinePrimitive({ geometryInstances: new import__644.GeometryInstance({ geometry: new import__644.GroundPolylineGeometry({ positions, granularity: 0, width: 1, loop: false, ellipsoid }) }), asynchronous: false, classificationType: import__644.ClassificationType.CESIUM_3D_TILE }); groundPolylinePrimitive = new SpecPrimitive( primitive, import__644.Pass.CESIUM_3D_TILE_CLASSIFICATION ); scene2.groundPrimitives.add(groundPolylinePrimitive); }); afterEach(function() { scene2.primitives.removeAll(); scene2.groundPrimitives.removeAll(); translucentPrimitive = translucentPrimitive && !translucentPrimitive.isDestroyed() && translucentPrimitive.destroy(); groundPolylinePrimitive = groundPolylinePrimitive && !groundPolylinePrimitive.isDestroyed() && groundPolylinePrimitive.destroy(); }); it("checks for support in the context on construction", function() { let translucentTileClassification = new import__644.TranslucentTileClassification({ depthTexture: true }); expect(translucentTileClassification.isSupported()).toBe(true); translucentTileClassification.destroy(); translucentTileClassification = new import__644.TranslucentTileClassification({ depthTexture: false }); expect(translucentTileClassification.isSupported()).toBe(false); translucentTileClassification.destroy(); }); function expectResources(translucentTileClassification, toBeDefined) { expect( (0, import__644.defined)( translucentTileClassification._drawClassificationFBO.framebuffer ) ).toBe(toBeDefined); expect((0, import__644.defined)(translucentTileClassification._packFBO.framebuffer)).toBe( toBeDefined ); expect( (0, import__644.defined)(translucentTileClassification._opaqueDepthStencilTexture) ).toBe(toBeDefined); expect( (0, import__644.defined)( translucentTileClassification._drawClassificationFBO.getColorTexture() ) ).toBe(toBeDefined); expect( (0, import__644.defined)(translucentTileClassification._translucentDepthStencilTexture) ).toBe(toBeDefined); expect( (0, import__644.defined)(translucentTileClassification._packFBO.getColorTexture()) ).toBe(toBeDefined); expect((0, import__644.defined)(translucentTileClassification._packDepthCommand)).toBe( toBeDefined ); expect((0, import__644.defined)(translucentTileClassification._accumulateCommand)).toBe( toBeDefined ); expect((0, import__644.defined)(translucentTileClassification._compositeCommand)).toBe( toBeDefined ); expect((0, import__644.defined)(translucentTileClassification._copyCommand)).toBe( toBeDefined ); } it("does not create resources if unsupported", function() { const translucentTileClassification = new import__644.TranslucentTileClassification({ depthTexture: false }); expectResources(translucentTileClassification, false); translucentTileClassification.executeTranslucentCommands( scene2, executeCommand, passState, translucentPrimitive.commands, void 0 ); expectResources(translucentTileClassification, false); translucentTileClassification.destroy(); }); it("creates resources on demand", function() { const translucentTileClassification = new import__644.TranslucentTileClassification( context ); if (!translucentTileClassification.isSupported()) { return; } scene2.render(); expectResources(translucentTileClassification, false); translucentTileClassification.executeTranslucentCommands( scene2, executeCommand, passState, [], globeDepthFramebuffer.depthStencilTexture ); expectResources(translucentTileClassification, false); translucentTileClassification.executeTranslucentCommands( scene2, executeCommand, passState, translucentPrimitive.commands, globeDepthFramebuffer.depthStencilTexture ); expectResources(translucentTileClassification, true); translucentTileClassification.destroy(); }); function readPixels(fbo) { return context.readPixels({ framebuffer: fbo }); } function executeCommand(command, scene3, context2, passState2) { command.execute(context2, passState2); } it("draws translucent commands into a buffer for depth", function() { const translucentTileClassification = new import__644.TranslucentTileClassification( context ); if (!translucentTileClassification.isSupported()) { return; } scene2.render(); const packedDepthFBO = translucentTileClassification._packFBO.framebuffer; translucentTileClassification.executeTranslucentCommands( scene2, executeCommand, passState, translucentPrimitive.commands, globeDepthFramebuffer.depthStencilTexture ); expect(translucentTileClassification.hasTranslucentDepth).toBe(true); const postTranslucentPixels = readPixels(packedDepthFBO); expect(postTranslucentPixels).not.toEqual([0, 0, 0, 0]); translucentTileClassification.destroy(); }); it("draws classification commands into a buffer", function() { const translucentTileClassification = new import__644.TranslucentTileClassification( context ); if (!translucentTileClassification.isSupported()) { return; } scene2.render(); translucentTileClassification.executeTranslucentCommands( scene2, executeCommand, passState, translucentPrimitive.commands, globeDepthFramebuffer.depthStencilTexture ); const drawClassificationFBO = translucentTileClassification._drawClassificationFBO.framebuffer; const preClassifyPixels = readPixels(drawClassificationFBO); const frustumCommands = { commands: [], indices: [] }; frustumCommands.commands[import__644.Pass.CESIUM_3D_TILE_CLASSIFICATION] = groundPolylinePrimitive.commands; frustumCommands.indices[import__644.Pass.CESIUM_3D_TILE_CLASSIFICATION] = [1]; translucentTileClassification.executeClassificationCommands( scene2, executeCommand, passState, frustumCommands ); const postClassifyPixels = readPixels(drawClassificationFBO); expect(postClassifyPixels).not.toEqual(preClassifyPixels); translucentTileClassification.destroy(); }); it("draws classification commands into a separate accumulation buffer for multifrustum", function() { const translucentTileClassification = new import__644.TranslucentTileClassification( context ); if (!translucentTileClassification.isSupported()) { return; } scene2.render(); translucentTileClassification.executeTranslucentCommands( scene2, executeCommand, passState, translucentPrimitive.commands, globeDepthFramebuffer.depthStencilTexture ); const accumulationFBO = translucentTileClassification._accumulationFBO.framebuffer; const drawClassificationFBO = translucentTileClassification._drawClassificationFBO.framebuffer; const frustumCommands = { commands: [], indices: [] }; frustumCommands.commands[import__644.Pass.CESIUM_3D_TILE_CLASSIFICATION] = groundPolylinePrimitive.commands; frustumCommands.indices[import__644.Pass.CESIUM_3D_TILE_CLASSIFICATION] = [1]; translucentTileClassification.executeClassificationCommands( scene2, executeCommand, passState, frustumCommands ); expect(readPixels(accumulationFBO)).toEqual([0, 0, 0, 0]); translucentTileClassification.executeTranslucentCommands( scene2, executeCommand, passState, translucentPrimitive.commands, globeDepthFramebuffer.depthStencilTexture ); translucentTileClassification.executeClassificationCommands( scene2, executeCommand, passState, frustumCommands ); const secondFrustumAccumulation = accumulationFBO; const accumulationPixels = readPixels(secondFrustumAccumulation); const classificationPixels = readPixels(drawClassificationFBO); const expectedPixels = [ // Multiply by two to account for premultiplied alpha classificationPixels[0] * 2, classificationPixels[1] * 2, classificationPixels[2] * 2, classificationPixels[3] ]; expect(accumulationPixels).not.toEqual([0, 0, 0, 0]); expect(accumulationPixels).toEqualEpsilon(expectedPixels, 1); translucentTileClassification.destroy(); }); it("does not draw classification commands if there is no translucent depth", function() { const translucentTileClassification = new import__644.TranslucentTileClassification( context ); if (!translucentTileClassification.isSupported()) { return; } scene2.render(); const drawClassificationFBO = translucentTileClassification._drawClassificationFBO.framebuffer; translucentTileClassification.executeTranslucentCommands( scene2, executeCommand, passState, [], globeDepthFramebuffer.depthStencilTexture ); const preClassifyPixels = readPixels(drawClassificationFBO); const frustumCommands = { commands: [], indices: [] }; frustumCommands.commands[import__644.Pass.CESIUM_3D_TILE_CLASSIFICATION] = groundPolylinePrimitive.commands; frustumCommands.indices[import__644.Pass.CESIUM_3D_TILE_CLASSIFICATION] = [1]; translucentTileClassification.executeClassificationCommands( scene2, executeCommand, passState, frustumCommands ); const postClassifyPixels = readPixels(drawClassificationFBO); expect(postClassifyPixels).toEqual(preClassifyPixels); translucentTileClassification.destroy(); }); it("composites classification into a buffer", function() { const translucentTileClassification = new import__644.TranslucentTileClassification( context ); if (!translucentTileClassification.isSupported()) { return; } const colorTexture = new import__644.Texture({ context, width: 1, height: 1, pixelFormat: import__644.PixelFormat.RGBA, pixelDatatype: import__644.PixelDatatype.UNSIGNED_BYTE }); const targetColorFBO = new import__644.Framebuffer({ context, colorTextures: [colorTexture] }); scene2.render(); translucentTileClassification.executeTranslucentCommands( scene2, executeCommand, passState, translucentPrimitive.commands, globeDepthFramebuffer.depthStencilTexture ); const frustumCommands = { commands: [], indices: [] }; frustumCommands.commands[import__644.Pass.CESIUM_3D_TILE_CLASSIFICATION] = groundPolylinePrimitive.commands; frustumCommands.indices[import__644.Pass.CESIUM_3D_TILE_CLASSIFICATION] = [1]; translucentTileClassification.executeClassificationCommands( scene2, executeCommand, passState, frustumCommands ); const preCompositePixels = readPixels(targetColorFBO); const pixelsToComposite = readPixels( translucentTileClassification._drawClassificationFBO.framebuffer ); const framebuffer2 = passState.framebuffer; passState.framebuffer = targetColorFBO; translucentTileClassification.execute(scene2, passState); passState.framebuffer = framebuffer2; const postCompositePixels = readPixels(targetColorFBO); expect(postCompositePixels).not.toEqual(preCompositePixels); const red = Math.round(pixelsToComposite[0]) + preCompositePixels[0]; const green = Math.round(pixelsToComposite[1]) + preCompositePixels[1]; const blue = Math.round(pixelsToComposite[2]) + preCompositePixels[2]; const alpha = pixelsToComposite[3] + preCompositePixels[3]; expect(postCompositePixels[0]).toEqual(red); expect(postCompositePixels[1]).toEqual(green); expect(postCompositePixels[2]).toEqual(blue); expect(postCompositePixels[3]).toEqual(alpha); translucentTileClassification.destroy(); targetColorFBO.destroy(); }); it("composites from an accumulation texture when there are multiple frustums", function() { const translucentTileClassification = new import__644.TranslucentTileClassification( context ); if (!translucentTileClassification.isSupported()) { return; } const clearCommandRed = new import__644.ClearCommand({ color: new import__644.Color(1, 0, 0, 1) }); const clearCommandGreen = new import__644.ClearCommand({ color: new import__644.Color(0, 1, 0, 1) }); const colorTexture = new import__644.Texture({ context, width: 1, height: 1, pixelFormat: import__644.PixelFormat.RGBA, pixelDatatype: import__644.PixelDatatype.UNSIGNED_BYTE }); const targetColorFBO = new import__644.Framebuffer({ context, colorTextures: [colorTexture] }); scene2.render(); translucentTileClassification.executeTranslucentCommands( scene2, executeCommand, passState, translucentPrimitive.commands, globeDepthFramebuffer.depthStencilTexture ); const frustumCommands = { commands: [], indices: [] }; frustumCommands.commands[import__644.Pass.CESIUM_3D_TILE_CLASSIFICATION] = groundPolylinePrimitive.commands; frustumCommands.indices[import__644.Pass.CESIUM_3D_TILE_CLASSIFICATION] = [1]; translucentTileClassification.executeClassificationCommands( scene2, executeCommand, passState, frustumCommands ); translucentTileClassification.executeTranslucentCommands( scene2, executeCommand, passState, translucentPrimitive.commands, globeDepthFramebuffer.depthStencilTexture ); translucentTileClassification.executeClassificationCommands( scene2, executeCommand, passState, frustumCommands ); const framebuffer2 = passState.framebuffer; passState.framebuffer = translucentTileClassification._drawClassificationFBO.framebuffer; clearCommandRed.execute(context, passState); passState.framebuffer = translucentTileClassification._accumulationFBO.framebuffer; clearCommandGreen.execute(context, passState); passState.framebuffer = targetColorFBO; translucentTileClassification.execute(scene2, passState); passState.framebuffer = framebuffer2; const postCompositePixels = readPixels(targetColorFBO); expect(postCompositePixels).toEqual([0, 255, 0, 255]); translucentTileClassification.destroy(); targetColorFBO.destroy(); }); it("does not composite classification if there is no translucent depth", function() { const translucentTileClassification = new import__644.TranslucentTileClassification( context ); if (!translucentTileClassification.isSupported()) { return; } const colorTexture = new import__644.Texture({ context, width: 1, height: 1, pixelFormat: import__644.PixelFormat.RGBA, pixelDatatype: import__644.PixelDatatype.UNSIGNED_BYTE }); const targetColorFBO = new import__644.Framebuffer({ context, colorTextures: [colorTexture] }); scene2.render(); translucentTileClassification.executeTranslucentCommands( scene2, executeCommand, passState, [], globeDepthFramebuffer.depthStencilTexture ); const frustumCommands = { commands: [], indices: [] }; frustumCommands.commands[import__644.Pass.CESIUM_3D_TILE_CLASSIFICATION] = groundPolylinePrimitive.commands; frustumCommands.indices[import__644.Pass.CESIUM_3D_TILE_CLASSIFICATION] = [1]; translucentTileClassification.executeClassificationCommands( scene2, executeCommand, passState, frustumCommands ); const preCompositePixels = readPixels(targetColorFBO); const framebuffer2 = passState.framebuffer; passState.framebuffer = targetColorFBO; translucentTileClassification.execute(scene2, passState); passState.framebuffer = framebuffer2; const postCompositePixels = readPixels(targetColorFBO); expect(postCompositePixels).toEqual(preCompositePixels); translucentTileClassification.destroy(); targetColorFBO.destroy(); }); it("clears the classification buffer", function() { const translucentTileClassification = new import__644.TranslucentTileClassification( context ); if (!translucentTileClassification.isSupported()) { return; } scene2.render(); translucentTileClassification.executeTranslucentCommands( scene2, executeCommand, passState, translucentPrimitive.commands, globeDepthFramebuffer.depthStencilTexture ); const drawClassificationFBO = translucentTileClassification._drawClassificationFBO.framebuffer; const preClassifyPixels = readPixels(drawClassificationFBO); const frustumCommands = { commands: [], indices: [] }; frustumCommands.commands[import__644.Pass.CESIUM_3D_TILE_CLASSIFICATION] = groundPolylinePrimitive.commands; frustumCommands.indices[import__644.Pass.CESIUM_3D_TILE_CLASSIFICATION] = [1]; translucentTileClassification.executeClassificationCommands( scene2, executeCommand, passState, frustumCommands ); const postClassifyPixels = readPixels(drawClassificationFBO); expect(postClassifyPixels).not.toEqual(preClassifyPixels); translucentTileClassification.execute(scene2, passState); const postClearPixels = readPixels(drawClassificationFBO); expect(postClearPixels).not.toEqual(postClassifyPixels); expect(postClearPixels).toEqual(preClassifyPixels); translucentTileClassification.destroy(); }); it("does not clear the classification buffer if there is no translucent depth", function() { const translucentTileClassification = new import__644.TranslucentTileClassification( context ); if (!translucentTileClassification.isSupported()) { return; } spyOn(translucentTileClassification._clearColorCommand, "execute"); translucentTileClassification.execute(scene2, passState); expect( translucentTileClassification._clearColorCommand.execute ).not.toHaveBeenCalled(); translucentTileClassification.destroy(); }); }, "WebGL" ); // packages/engine/Specs/Scene/TweenCollectionSpec.js var import__645 = __toESM(require_Cesium(), 1); describe( "Scene/TweenCollection", function() { it("add() adds a tween", function() { const startObject = { value: 0 }; const stopObject = { value: 1 }; function update(value) { } function complete() { } function cancel() { } const tweens = new import__645.TweenCollection(); const tween = tweens.add({ startObject, stopObject, duration: 1, delay: 0.5, easingFunction: import__645.EasingFunction.QUADRATIC_IN, update, complete, cancel }); expect(tween.startObject).toEqual(startObject); expect(tween.stopObject).toEqual(stopObject); expect(tween.duration).toEqual(1); expect(tween.delay).toEqual(0.5); expect(tween.easingFunction).toEqual(import__645.EasingFunction.QUADRATIC_IN); expect(tween.update).toBe(update); expect(tween.complete).toBe(complete); expect(tween.cancel).toBe(cancel); }); it("add() adds a tween with defaults", function() { const startObject = { value: 0 }; const stopObject = { value: 1 }; const tweens = new import__645.TweenCollection(); const tween = tweens.add({ startObject, stopObject, duration: 1 }); expect(tween.startObject).toEqual(startObject); expect(tween.stopObject).toEqual(stopObject); expect(tween.duration).toEqual(1); expect(tween.delay).toEqual(0); expect(tween.easingFunction).toEqual(import__645.EasingFunction.LINEAR_NONE); expect(tween.update).not.toBeDefined(); expect(tween.complete).not.toBeDefined(); expect(tween.cancel).not.toBeDefined(); }); it("add() adds with a duration of zero", function() { const complete = jasmine.createSpy("complete"); const tweens = new import__645.TweenCollection(); tweens.add({ startObject: {}, stopObject: {}, duration: 0, complete }); expect(tweens.length).toEqual(0); expect(complete).toHaveBeenCalled(); }); it("add() throws without startObject", function() { const tweens = new import__645.TweenCollection(); expect(function() { tweens.add({ stopObject: {}, duration: 1 }); }).toThrowDeveloperError(); }); it("add() throws without stopObject", function() { const tweens = new import__645.TweenCollection(); expect(function() { tweens.add({ startObject: {}, duration: 1 }); }).toThrowDeveloperError(); }); it("add() throws without duration", function() { const tweens = new import__645.TweenCollection(); expect(function() { tweens.add({ startObject: {}, stopObject: {} }); }).toThrowDeveloperError(); }); it("add() throws with negative duration", function() { const tweens = new import__645.TweenCollection(); expect(function() { tweens.add({ startObject: {}, stopObject: {}, duration: -1 }); }).toThrowDeveloperError(); }); it("cancelTween() cancels a tween", function() { const cancel = jasmine.createSpy("cancel"); const tweens = new import__645.TweenCollection(); const tween = tweens.add({ startObject: {}, stopObject: {}, duration: 1, cancel }); expect(tweens.length).toEqual(1); tween.cancelTween(); expect(cancel).toHaveBeenCalled(); expect(tweens.length).toEqual(0); }); it("remove() removes a tween", function() { const cancel = jasmine.createSpy("cancel"); const tweens = new import__645.TweenCollection(); const tween = tweens.add({ startObject: {}, stopObject: {}, duration: 1, cancel }); expect(tweens.length).toEqual(1); expect(tweens.contains(tween)).toEqual(true); let b = tweens.remove(tween); expect(b).toEqual(true); expect(tweens.length).toEqual(0); expect(tweens.contains(tween)).toEqual(false); expect(cancel).toHaveBeenCalled(); b = tweens.remove(tween); expect(b).toEqual(false); }); it("removeAll() removes a tween", function() { const cancel = jasmine.createSpy("cancel"); const tweens = new import__645.TweenCollection(); tweens.add({ startObject: {}, stopObject: {}, duration: 1, cancel }); tweens.add({ startObject: {}, stopObject: {}, duration: 1, cancel }); expect(tweens.length).toEqual(2); tweens.removeAll(); expect(tweens.length).toEqual(0); expect(cancel.calls.count()).toEqual(2); }); it("contains() throws without an index", function() { const tweens = new import__645.TweenCollection(); expect(function() { return tweens.get(); }).toThrowDeveloperError(); }); it("get() returns a tween", function() { const tweens = new import__645.TweenCollection(); const tween = tweens.add({ startObject: {}, stopObject: {}, duration: 1 }); const anotherTween = tweens.add({ startObject: {}, stopObject: {}, duration: 1 }); expect(tweens.get(0)).toBe(tween); expect(tweens.get(1)).toBe(anotherTween); }); it("update() animates a tween", function() { const update = jasmine.createSpy("update"); const complete = jasmine.createSpy("complete"); const startObject = { value: 0 }; const stopObject = { value: 1 }; const tweens = new import__645.TweenCollection(); tweens.add({ startObject, stopObject, duration: 1, update, complete }); expect(tweens.length).toEqual(1); tweens.update(0); expect(update).toHaveBeenCalledWith({ value: 0 }); expect(startObject.value).toEqual(0); tweens.update(0.5); expect(update).toHaveBeenCalledWith({ value: 0.5 }); expect(startObject.value).toEqual(0.5); tweens.update(1); expect(update).toHaveBeenCalledWith({ value: 1 }); expect(startObject.value).toEqual(1); expect(complete).toHaveBeenCalled(); expect(tweens.length).toEqual(0); }); it("update() animations a tween created with addProperty()", function() { const tweens = new import__645.TweenCollection(); const object = { property: 0 }; tweens.addProperty({ object, property: "property", startValue: 0, stopValue: 1, duration: 1 }); tweens.update(0); tweens.update(0.5); expect(object.property).toEqual(0.5); }); it("addProperty() throws without an object", function() { const tweens = new import__645.TweenCollection(); expect(function() { return tweens.addProperty({ property: "property", startValue: 0, stopValue: 1 }); }).toThrowDeveloperError(); }); it("addProperty() throws without a property", function() { const tweens = new import__645.TweenCollection(); const object = { property: 0 }; expect(function() { return tweens.addProperty({ object, startValue: 0, stopValue: 1 }); }).toThrowDeveloperError(); }); it("addProperty() throws when object does not contain property", function() { const tweens = new import__645.TweenCollection(); const object = { property: 0 }; expect(function() { return tweens.addProperty({ object, property: "another-property", startValue: 0, stopValue: 1 }); }).toThrowDeveloperError(); }); it("addProperty() throws without a startValue", function() { const tweens = new import__645.TweenCollection(); const object = { property: 0 }; expect(function() { return tweens.addProperty({ object, property: "property", stopValue: 1 }); }).toThrowDeveloperError(); }); it("addProperty() throws without a stopValue", function() { const tweens = new import__645.TweenCollection(); const object = { property: 0 }; expect(function() { return tweens.addProperty({ object, property: "property", startValue: 0 }); }).toThrowDeveloperError(); }); it("update() animations a tween created with addAlpha()", function() { const tweens = new import__645.TweenCollection(); const material = { uniforms: { lightColor: new import__645.Color(), darkColor: new import__645.Color() } }; tweens.addAlpha({ material, duration: 1 }); tweens.update(0); tweens.update(0.5); expect(material.uniforms.lightColor.alpha).toEqual(0.5); expect(material.uniforms.darkColor.alpha).toEqual(0.5); }); it("addAlpha() throws without a material", function() { const tweens = new import__645.TweenCollection(); expect(function() { return tweens.addAlpha({}); }).toThrowDeveloperError(); }); it("addAlpha() throws without a material with color uniforms", function() { const tweens = new import__645.TweenCollection(); const material = { uniforms: {} }; expect(function() { return tweens.addAlpha({ material }); }).toThrowDeveloperError(); }); it("update() animations a tween created with addOffsetIncrement()", function() { const tweens = new import__645.TweenCollection(); const material = { uniforms: { offset: 0 } }; tweens.addOffsetIncrement({ material, duration: 1 }); tweens.update(0); tweens.update(0.5); expect(material.uniforms.offset).toEqual(0.5); }); it("addOffsetIncrement() throws without a material", function() { const tweens = new import__645.TweenCollection(); expect(function() { return tweens.addOffsetIncrement({}); }).toThrowDeveloperError(); }); it("addOffsetIncrement() throws without a material with an offset uniform", function() { const tweens = new import__645.TweenCollection(); const material = { uniforms: {} }; expect(function() { return tweens.addOffsetIncrement({ material }); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Scene/UrlTemplateImageryProviderSpec.js var import__646 = __toESM(require_Cesium(), 1); var import__647 = __toESM(require_Cesium(), 1); describe("Scene/UrlTemplateImageryProvider", function() { beforeEach(function() { import__646.RequestScheduler.clearForSpecs(); }); afterEach(function() { import__646.Resource._Implementations.createImage = import__646.Resource._DefaultImplementations.createImage; }); it("conforms to ImageryProvider interface", function() { expect(import__646.UrlTemplateImageryProvider).toConformToInterface(import__646.ImageryProvider); }); it("requires the url to be specified", function() { function createWithoutUrl() { return new import__646.UrlTemplateImageryProvider({}); } expect(createWithoutUrl).toThrowDeveloperError(); }); it("returns valid value for hasAlphaChannel", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "made/up/tms/server/" }); expect(typeof provider.hasAlphaChannel).toBe("boolean"); }); it("requestImage returns a promise for an image and loads it for cross-origin use", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "made/up/tms/server/{Z}/{X}/{reverseY}" }); expect(provider.url).toEqual("made/up/tms/server/{Z}/{X}/{reverseY}"); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.minimumLevel).toBe(0); expect(provider.tilingScheme).toBeInstanceOf(import__646.WebMercatorTilingScheme); expect(provider.rectangle).toEqual(new import__646.WebMercatorTilingScheme().rectangle); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("when no credit is supplied, the provider has no logo", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "made/up/tms/server" }); expect(provider.credit).toBeUndefined(); }); it("turns the supplied credit into a logo", function() { const providerWithCredit = new import__646.UrlTemplateImageryProvider({ url: "made/up/gms/server", credit: "Thanks to our awesome made up source of this imagery!" }); expect(providerWithCredit.credit).toBeDefined(); }); it("rectangle passed to constructor does not affect tile numbering", function() { const rectangle = new import__646.Rectangle(0.1, 0.2, 0.3, 0.4); const provider = new import__646.UrlTemplateImageryProvider({ url: "made/up/tms/server/{z}/{x}/{reverseY}", rectangle }); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.minimumLevel).toBe(0); expect(provider.tilingScheme).toBeInstanceOf(import__646.WebMercatorTilingScheme); expect(provider.rectangle).toEqualEpsilon(rectangle, import__647.Math.EPSILON14); expect(provider.tileDiscardPolicy).toBeUndefined(); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toContain("/0/0/0"); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("uses minimumLevel and maximumLevel passed to constructor", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "made/up/tms/server", minimumLevel: 1, maximumLevel: 5 }); expect(provider.minimumLevel).toEqual(1); expect(provider.maximumLevel).toEqual(5); }); it("raises error event when image cannot be loaded", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "made/up/tms/server" }); const layer = new import__646.ImageryLayer(provider); let tries = 0; provider.errorEvent.addEventListener(function(error) { expect(error.timesRetried).toEqual(tries); ++tries; if (tries < 3) { error.retry = true; } setTimeout(function() { import__646.RequestScheduler.update(); }, 1); }); import__646.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { if (tries === 2) { import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); } else { setTimeout(function() { deferred.reject(); }, 1); } }; const imagery = new import__646.Imagery(layer, 0, 0, 0); imagery.addReference(); layer._requestImagery(imagery); import__646.RequestScheduler.update(); return pollToPromise_default(function() { return imagery.state === import__646.ImageryState.RECEIVED; }).then(function() { expect(imagery.image).toBeImageOrImageBitmap(); expect(tries).toEqual(2); imagery.releaseReference(); }); }); it("evaluation of pattern X Y reverseX reverseY Z reverseZ", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "made/up/tms/server/{z}/{reverseZ}/{reverseY}/{y}/{reverseX}/{x}.PNG", tilingScheme: new import__646.GeographicTilingScheme(), maximumLevel: 6 }); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toEqual("made/up/tms/server/2/3/2/1/4/3.PNG"); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(3, 1, 2).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("evaluation of schema zero padding for X Y Z as 0000", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "made/up/tms/server/{z}/{reverseZ}/{reverseY}/{y}/{reverseX}/{x}.PNG", urlSchemeZeroPadding: { "{x}": "0000", "{y}": "0000", "{z}": "0000" }, tilingScheme: new import__646.GeographicTilingScheme(), maximumLevel: 6 }); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toEqual( "made/up/tms/server/0002/3/2/0001/4/0003.PNG" ); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(3, 1, 2).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("evaluation of schema zero padding for reverseX reverseY reverseZ as 0000", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "made/up/tms/server/{z}/{reverseZ}/{reverseY}/{y}/{reverseX}/{x}.PNG", urlSchemeZeroPadding: { "{reverseX}": "0000", "{reverseY}": "0000", "{reverseZ}": "0000" }, tilingScheme: new import__646.GeographicTilingScheme(), maximumLevel: 6 }); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toEqual( "made/up/tms/server/2/0003/0002/1/0004/3.PNG" ); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(3, 1, 2).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("evaluation of schema zero padding for x y z as 0000 and large x and y", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "made/up/tms/server/{z}/{reverseZ}/{reverseY}/{y}/{reverseX}/{x}.PNG", urlSchemeZeroPadding: { "{x}": "0000", "{y}": "0000", "{z}": "0000" }, tilingScheme: new import__646.GeographicTilingScheme(), maximumLevel: 6 }); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toEqual( "made/up/tms/server/0005/0/21/0010/51/0012.PNG" ); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(12, 10, 5).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("evaluates pattern northDegrees", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "{northDegrees}", tilingScheme: new import__646.GeographicTilingScheme() }); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toEqualEpsilon(45, import__647.Math.EPSILON11); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(3, 1, 2).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("evaluates pattern southDegrees", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "{southDegrees}", tilingScheme: new import__646.GeographicTilingScheme() }); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toEqualEpsilon(0, import__647.Math.EPSILON11); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(3, 1, 2).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("evaluates pattern eastDegrees", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "{eastDegrees}", tilingScheme: new import__646.GeographicTilingScheme() }); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toEqualEpsilon(0, import__647.Math.EPSILON11); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(3, 1, 2).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("evaluates pattern westDegrees", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "{westDegrees}", tilingScheme: new import__646.GeographicTilingScheme() }); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toEqualEpsilon(-45, import__647.Math.EPSILON11); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(3, 1, 2).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("evaluates pattern northProjected", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "{northProjected}", tilingScheme: new import__646.WebMercatorTilingScheme() }); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toEqualEpsilon( Math.PI * import__646.Ellipsoid.WGS84.maximumRadius / 2, import__647.Math.EPSILON11 ); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(3, 1, 2).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("evaluates pattern southProjected", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "{southProjected}" }); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toEqualEpsilon( Math.PI * import__646.Ellipsoid.WGS84.maximumRadius / 2, import__647.Math.EPSILON11 ); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(3, 0, 2).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("evaluates pattern eastProjected", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "{eastProjected}" }); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toEqualEpsilon( -Math.PI * import__646.Ellipsoid.WGS84.maximumRadius / 2, import__647.Math.EPSILON11 ); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 1, 2).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("evaluates pattern westProjected", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "{westProjected}" }); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toEqualEpsilon( -Math.PI * import__646.Ellipsoid.WGS84.maximumRadius / 2, import__647.Math.EPSILON11 ); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(1, 1, 2).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("evaluates multiple coordinate patterns", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "{westDegrees} {westProjected} {southProjected} {southDegrees} {eastProjected} {eastDegrees} {northDegrees} {northProjected}" }); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toEqual( `-90 ${-Math.PI * import__646.Ellipsoid.WGS84.maximumRadius / 2} 0 0 0 0 ${import__647.Math.toDegrees( import__646.WebMercatorProjection.mercatorAngleToGeodeticLatitude(Math.PI / 2) )} ${Math.PI * import__646.Ellipsoid.WGS84.maximumRadius / 2}` ); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(1, 1, 2).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("evaluates pattern s", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "{s}" }); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(["a", "b", "c"].indexOf(request.url)).toBeGreaterThanOrEqual(0); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(3, 1, 2).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("uses custom subdomain string", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "{s}", subdomains: "123" }); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(["1", "2", "3"].indexOf(request.url)).toBeGreaterThanOrEqual(0); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(3, 1, 2).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("uses custom subdomain array", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "{s}", subdomains: ["foo", "bar"] }); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(["foo", "bar"].indexOf(request.url)).toBeGreaterThanOrEqual(0); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(3, 1, 2).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("uses custom tags", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "made/up/tms/server/{custom1}/{custom2}/{z}/{y}/{x}.PNG", tilingScheme: new import__646.GeographicTilingScheme(), maximumLevel: 6, customTags: { custom1: function() { return "foo"; }, custom2: function() { return "bar"; } } }); spyOn(import__646.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { expect(request.url).toEqual("made/up/tms/server/foo/bar/2/1/3.PNG"); import__646.Resource._DefaultImplementations.createImage( new import__646.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(3, 1, 2).then(function(image) { expect(import__646.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); describe("pickFeatures", function() { it("returns undefined when enablePickFeatures is false", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "foo/bar", pickFeaturesUrl: "foo/bar", getFeatureInfoFormats: [ new import__646.GetFeatureInfoFormat("json", "application/json"), new import__646.GetFeatureInfoFormat("xml", "text/xml") ], enablePickFeatures: false }); expect(provider.pickFeatures(0, 0, 0, 0, 0)).toBeUndefined(); }); it("does not return undefined when enablePickFeatures is subsequently set to true", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "foo/bar", pickFeaturesUrl: "foo/bar", getFeatureInfoFormats: [ new import__646.GetFeatureInfoFormat("json", "application/json"), new import__646.GetFeatureInfoFormat("xml", "text/xml") ], enablePickFeatures: false }); provider.enablePickFeatures = true; expect(provider.pickFeatures(0, 0, 0, 0, 0)).not.toBeUndefined(); }); it("returns undefined when enablePickFeatures is initialized as true and set to false", function() { const provider = new import__646.UrlTemplateImageryProvider({ url: "foo/bar", pickFeaturesUrl: "foo/bar", getFeatureInfoFormats: [ new import__646.GetFeatureInfoFormat("json", "application/json"), new import__646.GetFeatureInfoFormat("xml", "text/xml") ], enablePickFeatures: true }); provider.enablePickFeatures = false; expect(provider.pickFeatures(0, 0, 0, 0, 0)).toBeUndefined(); }); }); }); // packages/engine/Specs/Scene/Vector3DTileClampedPolylinesSpec.js var import__648 = __toESM(require_Cesium(), 1); describe( "Scene/Vector3DTileClampedPolylines", function() { let scene2; let rectangle; let polylines; const ellipsoid = import__648.Ellipsoid.WGS84; let depthRectanglePrimitive; const vectorPolylines = "./Data/Cesium3DTiles/Vector/VectorTilePolylines/tileset.json"; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); function MockGlobePrimitive(primitive) { this._primitive = primitive; this.pass = import__648.Pass.GLOBE; } MockGlobePrimitive.prototype.update = function(frameState2) { const commandList = frameState2.commandList; const startLength = commandList.length; this._primitive.update(frameState2); for (let i = startLength; i < commandList.length; ++i) { const command = commandList[i]; command.pass = this.pass; } }; MockGlobePrimitive.prototype.isDestroyed = function() { return false; }; MockGlobePrimitive.prototype.destroy = function() { this._primitive.destroy(); return (0, import__648.destroyObject)(this); }; beforeEach(function() { rectangle = import__648.Rectangle.fromDegrees(-40, -40, 40, 40); const depthpolylineColorAttribute = import__648.ColorGeometryInstanceAttribute.fromColor( new import__648.Color(0, 0, 1, 1) ); const primitive = new import__648.Primitive({ geometryInstances: new import__648.GeometryInstance({ geometry: new import__648.RectangleGeometry({ ellipsoid, rectangle }), id: "depth rectangle", attributes: { color: depthpolylineColorAttribute } }), appearance: new import__648.PerInstanceColorAppearance({ translucent: false, flat: true }), asynchronous: false }); depthRectanglePrimitive = new MockGlobePrimitive(primitive); }); afterEach(function() { scene2.primitives.removeAll(); polylines = polylines && !polylines.isDestroyed() && polylines.destroy(); }); xit("renders clamped polylines", function() { scene2.camera.lookAt( import__648.Cartesian3.fromDegrees(0, 0, 1.5), new import__648.Cartesian3(0, 0, 1) ); return Cesium3DTilesTester_default.loadTileset(scene2, vectorPolylines, { classificationType: import__648.ClassificationType.TERRAIN }).then(function(tileset) { scene2.primitives.add(depthRectanglePrimitive); tileset.show = false; expect(scene2).toRender([0, 0, 255, 255]); tileset.show = true; expect(scene2).toRender([255, 255, 255, 255]); }); }); xit("picks a clamped polyline", function() { scene2.camera.lookAt( import__648.Cartesian3.fromDegrees(0, 0, 1.5), new import__648.Cartesian3(0, 0, 1) ); return Cesium3DTilesTester_default.loadTileset(scene2, vectorPolylines, { classificationType: import__648.ClassificationType.TERRAIN }).then(function(tileset) { scene2.primitives.add(depthRectanglePrimitive); tileset.show = false; expect(scene2).toPickPrimitive(depthRectanglePrimitive._primitive); tileset.show = true; expect(scene2).toPickPrimitive(tileset); }); }); it("isDestroyed", function() { polylines = new import__648.Vector3DTileClampedPolylines({ rectangle: new import__648.Rectangle() }); expect(polylines.isDestroyed()).toEqual(false); polylines.destroy(); expect(polylines.isDestroyed()).toEqual(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/Vector3DTileContentSpec.js var import__649 = __toESM(require_Cesium(), 1); describe( "Scene/Vector3DTileContent", () => { let scene2; let camera; let ellipsoid; let globeMockPrimitive; let tilesetMockPrimitive; let globePrimitive; let tilesetPrimitive; let depthColor; const whitePixel = [255, 255, 255, 255]; const blackPixel = [0, 0, 0, 255]; function MockPrimitive(primitive, pass) { this._primitive = primitive; this._pass = pass; this.show = true; } MockPrimitive.prototype.update = function(frameState2) { if (!this.show) { return; } const commandList = frameState2.commandList; const startLength = commandList.length; this._primitive.update(frameState2); for (let i = startLength; i < commandList.length; ++i) { const command = commandList[i]; command.pass = this._pass; } }; MockPrimitive.prototype.isDestroyed = function() { return false; }; MockPrimitive.prototype.destroy = function() { return (0, import__649.destroyObject)(this); }; function createPrimitive(rectangle, pass) { let renderState; if (pass === import__649.Pass.CESIUM_3D_TILE) { renderState = import__649.RenderState.fromCache({ stencilTest: import__649.StencilConstants.setCesium3DTileBit(), stencilMask: import__649.StencilConstants.CESIUM_3D_TILE_MASK, depthTest: { enabled: true } }); } const depthColorAttribute = import__649.ColorGeometryInstanceAttribute.fromColor( new import__649.Color(1, 0, 0, 1) ); depthColor = depthColorAttribute.value; return new import__649.Primitive({ geometryInstances: new import__649.GeometryInstance({ geometry: new import__649.RectangleGeometry({ ellipsoid, rectangle }), id: "depth rectangle", attributes: { color: depthColorAttribute } }), appearance: new import__649.PerInstanceColorAppearance({ translucent: false, flat: true, renderState }), asynchronous: false }); } const tilesetRectangle = import__649.Rectangle.fromDegrees(-0.01, -0.01, 0.01, 0.01); const vectorTilePolygonsWithBatchTableTileset = "./Data/Cesium3DTiles/Vector/VectorTilePolygonsWithBatchTable/tileset.json"; function subdivideRectangle(rectangle) { const center = import__649.Rectangle.center(rectangle); const ulRect = new import__649.Rectangle( tilesetRectangle.west, center.latitude, center.longitude, tilesetRectangle.north ); const urRect = new import__649.Rectangle( center.longitude, center.longitude, tilesetRectangle.east, tilesetRectangle.north ); const lrRect = new import__649.Rectangle( center.longitude, tilesetRectangle.south, tilesetRectangle.east, center.latitude ); const llRect = new import__649.Rectangle( tilesetRectangle.west, tilesetRectangle.south, center.longitude, center.latitude ); return [ulRect, urRect, lrRect, llRect]; } beforeAll(() => { scene2 = createScene_default(); camera = scene2.camera; ellipsoid = import__649.Ellipsoid.WGS84; const rectangle = import__649.Rectangle.fromDegrees(-40, -40, 40, 40); globePrimitive = createPrimitive(rectangle, import__649.Pass.GLOBE); tilesetPrimitive = createPrimitive(rectangle, import__649.Pass.CESIUM_3D_TILE); }); afterAll(() => { tilesetPrimitive.destroy(); globePrimitive.destroy(); scene2.destroyForSpecs(); }); beforeEach(() => { globeMockPrimitive = new MockPrimitive(globePrimitive, import__649.Pass.GLOBE); tilesetMockPrimitive = new MockPrimitive( tilesetPrimitive, import__649.Pass.CESIUM_3D_TILE ); scene2.primitives.add(globeMockPrimitive); scene2.camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(tilesetRectangle)), new import__649.Cartesian3(0, 0, 0.01) ); }); afterEach(() => { scene2.primitives.removeAll(); globeMockPrimitive = globeMockPrimitive && !globeMockPrimitive.isDestroyed() && globeMockPrimitive.destroy(); tilesetMockPrimitive = tilesetMockPrimitive && !tilesetMockPrimitive.isDestroyed() && tilesetMockPrimitive.destroy(); }); describe("points", () => { const vectorTilePointsTileset = "./Data/Cesium3DTiles/Vector/VectorTilePoints/tileset.json"; const vectorTilePointsBatchedChildrenTileset = "./Data/Cesium3DTiles/Vector/VectorTilePointsBatchedChildren/tileset.json"; const vectorTilePointsBatchedChildrenWithBatchTableTileset = "./Data/Cesium3DTiles/Vector/VectorTilePointsBatchedChildrenWithBatchTable/tileset.json"; const vectorTilePointsWithBatchTableTileset = "./Data/Cesium3DTiles/Vector/VectorTilePointsWithBatchTable/tileset.json"; const vectorTilePointsWithBatchIdsTileset = "./Data/Cesium3DTiles/Vector/VectorTilePointsWithBatchIds/tileset.json"; it("renders points", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePointsTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); }); }); it("picks points", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePointsTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTilePointFeature); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTilePointFeature); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTilePointFeature); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTilePointFeature); }); }); }); it("styles points for show", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePointsTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); tileset.style = new import__649.Cesium3DTileStyle({ show: "true" }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); tileset.style = void 0; camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); }); }); it("styles points for color", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePointsTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); return new Promise((resolve) => { tileset.style = new import__649.Cesium3DTileStyle({ color: `color("black")` }); scene2.renderForSpecs(); window.requestAnimationFrame(() => { resolve(); }); }).then(() => { camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(blackPixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(blackPixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(blackPixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(blackPixel); tileset.style = void 0; camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); }); }); }); it("renders batched points with batch ids", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePointsWithBatchIdsTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); }); }); it("picks batched points with batch ids", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePointsWithBatchIdsTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTilePointFeature); expect(result._batchId).toEqual(0); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTilePointFeature); expect(result._batchId).toEqual(1); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTilePointFeature); expect(result._batchId).toEqual(3); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTilePointFeature); expect(result._batchId).toEqual(2); }); }); }); it("renders batched points with batch table", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePointsWithBatchTableTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); }); }); it("picks batched points with batch table", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePointsWithBatchTableTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTilePointFeature); expect(result.getProperty("name")).toEqual("upper left"); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTilePointFeature); expect(result.getProperty("name")).toEqual("upper right"); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTilePointFeature); expect(result.getProperty("name")).toEqual("lower right"); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTilePointFeature); expect(result.getProperty("name")).toEqual("lower left"); }); }); }); it("renders batched points with children", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePointsBatchedChildrenTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); }); }); it("renders batched polygons with children with batch table", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePointsBatchedChildrenWithBatchTableTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); }); }); }); describe("polygons", () => { const vectorTilePolygonsTileset = "./Data/Cesium3DTiles/Vector/VectorTilePolygons/tileset.json"; const vectorTilePolygonsWithBatchIdsTileset = "./Data/Cesium3DTiles/Vector/VectorTilePolygonsWithBatchIds/tileset.json"; const vectorTilePolygonsBatchedChildrenTileset = "./Data/Cesium3DTiles/Vector/VectorTilePolygonsBatchedChildren/tileset.json"; const vectorTilePolygonsBatchedChildrenWithBatchTable = "./Data/Cesium3DTiles/Vector/VectorTilePolygonsBatchedChildrenWithBatchTable/tileset.json"; it("renders polygons", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolygonsTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); }); }); it("picks polygons", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolygonsTileset ).then((tileset) => { camera.lookAt( ellipsoid.cartographicToCartesian( import__649.Rectangle.center(tilesetRectangle) ), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); }); }); }); it("styles polygons for show", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolygonsTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); tileset.style = new import__649.Cesium3DTileStyle({ show: "false" }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender([255, 0, 0, 255]); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender([255, 0, 0, 255]); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender([255, 0, 0, 255]); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender([255, 0, 0, 255]); tileset.style = new import__649.Cesium3DTileStyle({ show: "true" }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); tileset.style = void 0; camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); }); }); it("styles polygons for color", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolygonsTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); tileset.style = new import__649.Cesium3DTileStyle({ color: `color("black")` }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(blackPixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(blackPixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(blackPixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(blackPixel); tileset.style = void 0; camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); }); }); it("renders polygons on 3D Tiles", () => { scene2.primitives.add(tilesetMockPrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolygonsTileset, { classificationType: import__649.ClassificationType.CESIUM_3D_TILE } ).then((tileset) => { camera.lookAt( ellipsoid.cartographicToCartesian( import__649.Rectangle.center(tilesetRectangle) ), new import__649.Cartesian3(0, 0, 5) ); globeMockPrimitive.show = false; tilesetMockPrimitive.show = true; expect(scene2).toRender(whitePixel); globeMockPrimitive.show = true; tilesetMockPrimitive.show = false; expect(scene2).toRender(depthColor); }); }); it("renders polygons on terrain", () => { scene2.primitives.add(tilesetMockPrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolygonsTileset, { classificationType: import__649.ClassificationType.TERRAIN } ).then((tileset) => { camera.lookAt( ellipsoid.cartographicToCartesian( import__649.Rectangle.center(tilesetRectangle) ), new import__649.Cartesian3(0, 0, 5) ); globeMockPrimitive.show = false; tilesetMockPrimitive.show = true; expect(scene2).toRender(depthColor); globeMockPrimitive.show = true; tilesetMockPrimitive.show = false; expect(scene2).toRender(whitePixel); }); }); it("renders polygons on 3D Tiles and terrain", () => { scene2.primitives.add(tilesetMockPrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolygonsTileset, { classificationType: import__649.ClassificationType.BOTH } ).then((tileset) => { camera.lookAt( ellipsoid.cartographicToCartesian( import__649.Rectangle.center(tilesetRectangle) ), new import__649.Cartesian3(0, 0, 5) ); globeMockPrimitive.show = false; tilesetMockPrimitive.show = true; expect(scene2).toRender(whitePixel); globeMockPrimitive.show = true; tilesetMockPrimitive.show = false; expect(scene2).toRender(whitePixel); }); }); it("renders batched polygons with batch ids", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolygonsWithBatchIdsTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); }); }); it("picks batched polygons with batch ids", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolygonsWithBatchIdsTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result._batchId).toEqual(0); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result._batchId).toEqual(1); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result._batchId).toEqual(3); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result._batchId).toEqual(2); }); }); }); it("renders batched polygons with batch table", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolygonsWithBatchTableTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); }); }); it("picks batched polygons with batch table", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolygonsWithBatchTableTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result.getProperty("name")).toEqual("upper left"); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result.getProperty("name")).toEqual("upper right"); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result.getProperty("name")).toEqual("lower right"); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result.getProperty("name")).toEqual("lower left"); }); }); }); it("renders batched polygons with children", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolygonsBatchedChildrenTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); }); }); it("renders batched polygons with children with batch table", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolygonsBatchedChildrenWithBatchTable ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); }); }); }); describe("polylines", () => { const vectorTilePolylinesTileset = "./Data/Cesium3DTiles/Vector/VectorTilePolylines/tileset.json"; const vectorTilePolylinesBatchedChildrenTileset = "./Data/Cesium3DTiles/Vector/VectorTilePolylinesBatchedChildren/tileset.json"; const vectorTilePolylinesBatchedChildrenWithBatchTableTileset = "./Data/Cesium3DTiles/Vector/VectorTilePolylinesBatchedChildrenWithBatchTable/tileset.json"; const vectorTilePolylinesWithBatchTableTileset = "./Data/Cesium3DTiles/Vector/VectorTilePolylinesWithBatchTable/tileset.json"; const vectorTilePolylinesWithBatchIdsTileset = "./Data/Cesium3DTiles/Vector/VectorTilePolylinesWithBatchIds/tileset.json"; it("renders polylines", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); const nwCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.northwest(ulRect) ); const neCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.northeast(urRect) ); const seCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.southeast(lrRect) ); const swCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.southwest(llRect) ); camera.lookAt(nwCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(neCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(seCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(swCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); }); }); it("picks polylines", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.northwest(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.northeast(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.southeast(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.southwest(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); }); }); }); it("styles polylines for show", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); const nwCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.northwest(ulRect) ); const neCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.northeast(urRect) ); const seCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.southeast(lrRect) ); const swCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.southwest(llRect) ); tileset.style = new import__649.Cesium3DTileStyle({ show: "false" }); camera.lookAt(nwCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRender([255, 0, 0, 255]); camera.lookAt(neCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRender([255, 0, 0, 255]); camera.lookAt(seCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRender([255, 0, 0, 255]); camera.lookAt(swCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRender([255, 0, 0, 255]); tileset.style = new import__649.Cesium3DTileStyle({ show: "true" }); camera.lookAt(nwCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(neCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(seCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(swCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); tileset.style = void 0; camera.lookAt(nwCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(neCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(seCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(swCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); }); }); it("styles polylines for color", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); const nwCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.northwest(ulRect) ); const neCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.northeast(urRect) ); const seCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.southeast(lrRect) ); const swCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.southwest(llRect) ); tileset.style = new import__649.Cesium3DTileStyle({ color: `color("black")` }); camera.lookAt(nwCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRender(blackPixel); camera.lookAt(neCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRender(blackPixel); camera.lookAt(seCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRender(blackPixel); camera.lookAt(swCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRender(blackPixel); tileset.style = void 0; camera.lookAt(nwCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(neCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(seCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(swCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); }); }); it("renders polylines on 3D Tiles", () => { scene2.primitives.add(tilesetMockPrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesTileset, { classificationType: import__649.ClassificationType.CESIUM_3D_TILE } ).then((tileset) => { camera.lookAt( ellipsoid.cartographicToCartesian( import__649.Rectangle.northeast(tilesetRectangle) ), new import__649.Cartesian3(0, 0, 5) ); globeMockPrimitive.show = false; tilesetMockPrimitive.show = true; expect(scene2).toRender(whitePixel); globeMockPrimitive.show = true; tilesetMockPrimitive.show = false; expect(scene2).toRender(depthColor); }); }); it("renders polylines on terrain", () => { scene2.primitives.add(tilesetMockPrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesTileset, { classificationType: import__649.ClassificationType.TERRAIN } ).then((tileset) => { camera.lookAt( ellipsoid.cartographicToCartesian( import__649.Rectangle.northeast(tilesetRectangle) ), new import__649.Cartesian3(0, 0, 5) ); globeMockPrimitive.show = false; tilesetMockPrimitive.show = true; expect(scene2).toRender(depthColor); globeMockPrimitive.show = true; tilesetMockPrimitive.show = false; expect(scene2).toRender(whitePixel); }); }); it("renders polylines on 3D Tiles and terrain", () => { scene2.primitives.add(tilesetMockPrimitive); return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesTileset, { classificationType: import__649.ClassificationType.BOTH } ).then((tileset) => { camera.lookAt( ellipsoid.cartographicToCartesian( import__649.Rectangle.northeast(tilesetRectangle) ), new import__649.Cartesian3(0, 0, 5) ); globeMockPrimitive.show = false; tilesetMockPrimitive.show = true; expect(scene2).toRender(whitePixel); globeMockPrimitive.show = true; tilesetMockPrimitive.show = false; expect(scene2).toRender(whitePixel); }); }); it("renders polylines with batch ids", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesWithBatchIdsTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); const nwCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.northwest(ulRect) ); const neCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.northeast(urRect) ); const seCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.southeast(lrRect) ); const swCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.southwest(llRect) ); camera.lookAt(nwCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(neCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(seCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(swCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); }); }); it("picks polylines with batch ids", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesWithBatchIdsTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.northwest(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result._batchId).toEqual(0); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.northeast(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result._batchId).toEqual(1); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.southeast(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result._batchId).toEqual(3); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.southwest(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result._batchId).toEqual(2); }); }); }); it("renders polylines with batch table", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesWithBatchTableTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); const nwCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.northwest(ulRect) ); const neCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.northeast(urRect) ); const seCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.southeast(lrRect) ); const swCorner = ellipsoid.cartographicToCartesian( import__649.Rectangle.southwest(llRect) ); camera.lookAt(nwCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(neCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(seCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt(swCorner, new import__649.Cartesian3(0, 0, 5)); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); }); }); it("picks polylines with batch table", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesWithBatchTableTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.northwest(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result.getProperty("name")).toEqual("upper left"); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.northeast(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result.getProperty("name")).toEqual("upper right"); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.southeast(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result.getProperty("name")).toEqual("lower right"); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.southwest(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result.getProperty("name")).toEqual("lower left"); }); }); }); it("renders batched polylines with children", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesBatchedChildrenTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.northwest(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.northeast(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.southeast(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.southwest(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); }); }); it("renders batched polylines with children with batch table", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesBatchedChildrenWithBatchTableTileset ).then((tileset) => { const [ulRect, urRect, lrRect, llRect] = subdivideRectangle( tilesetRectangle ); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.northwest(ulRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.northeast(urRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.southeast(lrRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.southwest(llRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); }); }); describe("getPolylinePositions", () => { it("gets polyline positions", function() { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesWithBatchIdsTileset, { vectorKeepDecodedPositions: true } ).then(function(tileset) { const content = tileset.root.content; const polylinePositions = content.getPolylinePositions(0); expect(polylinePositions.length).toBe(60); expect(polylinePositions[0]).toEqualEpsilon( 6378136806372941e-9, import__649.Math.EPSILON7 ); expect(polylinePositions[1]).toEqualEpsilon( -1113.194885441724, import__649.Math.EPSILON7 ); expect(polylinePositions[2]).toEqualEpsilon( 1105.675261474196, import__649.Math.EPSILON7 ); }); }); it("gets polyline positions for individual polylines in a batch", function() { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesBatchedChildrenTileset, { vectorKeepDecodedPositions: true } ).then(function(tileset) { const content = tileset.root.children[0].content; expect(content.getPolylinePositions(0).length).toBe(60); expect(content.getPolylinePositions(1).length).toBe(60); expect(content.getPolylinePositions(2).length).toBe(60); expect(content.getPolylinePositions(3).length).toBe(60); }); }); it("gets polyline positions for clamped polylines", function() { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesWithBatchIdsTileset, { vectorKeepDecodedPositions: true, classificationType: import__649.ClassificationType.TERRAIN } ).then(function(tileset) { const content = tileset.root.content; const polylinePositions = content.getPolylinePositions(0); expect(polylinePositions.length).toBe(54); expect(polylinePositions[0]).toEqualEpsilon( 6378136806372941e-9, import__649.Math.EPSILON7 ); expect(polylinePositions[1]).toEqualEpsilon( -1113.194885441724, import__649.Math.EPSILON7 ); expect(polylinePositions[2]).toEqualEpsilon( 1105.675261474196, import__649.Math.EPSILON7 ); }); }); it("getPolylinePositions returns undefined if there are no positions associated with the given batchId", function() { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesWithBatchIdsTileset, { vectorKeepDecodedPositions: true } ).then(function(tileset) { const content = tileset.root.content; const polylinePositions = content.getPolylinePositions(1); expect(polylinePositions).toBeUndefined(); }); }); it("getPolylinePositions returns undefined if there are no polylines", function() { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolygonsWithBatchTableTileset, { vectorKeepDecodedPositions: true } ).then(function(tileset) { const content = tileset.root.content; const polylinePositions = content.getPolylinePositions(0); expect(polylinePositions).toBeUndefined(); }); }); it("getPolylinePositions returns undefined if tileset.vectorKeepDecodedPositions is false", function() { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolylinesWithBatchIdsTileset, { vectorKeepDecodedPositions: false } ).then(function(tileset) { const content = tileset.root.content; const polylinePositions = content.getPolylinePositions(0); expect(polylinePositions).toBeUndefined(); }); }); }); }); describe("combined", () => { const vectorTileCombinedTileset = "./Data/Cesium3DTiles/Vector/VectorTileCombined/tileset.json"; const vectorTileCombinedWithBatchIdsTileset = "./Data/Cesium3DTiles/Vector/VectorTileCombinedWithBatchIds/tileset.json"; const combinedTilesetRectangle = import__649.Rectangle.fromDegrees( -0.02, -0.01, 0.02, 0.01 ); const width = combinedTilesetRectangle.width; const step = width / 3; const west = combinedTilesetRectangle.west; const north = combinedTilesetRectangle.north; const south = combinedTilesetRectangle.south; const polygonRect = new import__649.Rectangle(west, south, west + step, north); const polylineRect = new import__649.Rectangle( west + step, south, west + step * 2, north ); const pointRect = new import__649.Rectangle( west + step * 2, south, west + step * 3, north ); it("renders", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTileCombinedTileset ).then((tileset) => { camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(polygonRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian( import__649.Rectangle.southeast(polylineRect) ), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(pointRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); }); }); it("picks", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTileCombinedTileset ).then((tileset) => { camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(polygonRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); }); camera.lookAt( ellipsoid.cartographicToCartesian( import__649.Rectangle.southeast(polylineRect) ), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(pointRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTilePointFeature); }); }); }); it("renders with batch ids", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTileCombinedWithBatchIdsTileset ).then((tileset) => { camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(polygonRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); camera.lookAt( ellipsoid.cartographicToCartesian( import__649.Rectangle.southeast(polylineRect) ), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRenderAndCall((rgba) => { expect(rgba[0]).toBeCloseTo(255, -1); expect(rgba[1]).toBeCloseTo(255, -1); expect(rgba[2]).toBeCloseTo(255, -1); expect(rgba[3]).toEqual(255); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(pointRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toRender(whitePixel); }); }); it("picks with batch ids", () => { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTileCombinedWithBatchIdsTileset ).then((tileset) => { camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(polygonRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result._batchId).toEqual(2); }); camera.lookAt( ellipsoid.cartographicToCartesian( import__649.Rectangle.southeast(polylineRect) ), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTileFeature); expect(result._batchId).toEqual(1); }); camera.lookAt( ellipsoid.cartographicToCartesian(import__649.Rectangle.center(pointRect)), new import__649.Cartesian3(0, 0, 5) ); expect(scene2).toPickAndCall((result) => { expect(result).toBeDefined(); expect(result).toBeInstanceOf(import__649.Cesium3DTilePointFeature); expect(result._batchId).toEqual(0); }); }); }); }); it("throws when calling getFeature with invalid index", function() { return Cesium3DTilesTester_default.loadTileset( scene2, vectorTilePolygonsWithBatchTableTileset ).then(function(tileset) { const content = tileset.root.content; expect(function() { content.getFeature(-1); }).toThrowDeveloperError(); expect(function() { content.getFeature(1e3); }).toThrowDeveloperError(); expect(function() { content.getFeature(); }).toThrowDeveloperError(); }); }); it("throws with invalid version", async function() { const arrayBuffer = Cesium3DTilesTester_default.generateVectorTileBuffer({ version: 2 }); await expectAsync( Cesium3DTilesTester_default.createContentForMockTile(arrayBuffer, "vctr") ).toBeRejectedWithError( import__649.RuntimeError, "Only Vector tile version 1 is supported. Version 2 is not." ); }); it("throws with empty feature table", async function() { const arrayBuffer = Cesium3DTilesTester_default.generateVectorTileBuffer({ defineFeatureTable: false }); await expectAsync( Cesium3DTilesTester_default.createContentForMockTile(arrayBuffer, "vctr") ).toBeRejectedWithError( import__649.RuntimeError, "Feature table must have a byte length greater than zero" ); }); it("throws without region", async function() { const arrayBuffer = Cesium3DTilesTester_default.generateVectorTileBuffer({ defineRegion: false, polygonsLength: 1 }); await expectAsync( Cesium3DTilesTester_default.createContentForMockTile(arrayBuffer, "vctr") ).toBeRejectedWithError( import__649.RuntimeError, "Feature table global property: REGION must be defined" ); }); it("throws without all batch ids", async function() { const arrayBuffer = Cesium3DTilesTester_default.generateVectorTileBuffer({ polygonsLength: 1, pointsLength: 1, polylinesLength: 1, polygonBatchIds: [1], pointBatchIds: [0] }); await expectAsync( Cesium3DTilesTester_default.createContentForMockTile(arrayBuffer, "vctr") ).toBeRejectedWithError( import__649.RuntimeError, "If one group of batch ids is defined, then all batch ids must be defined" ); }); it("destroys", async function() { const tileset = await import__649.Cesium3DTileset.fromUrl( vectorTilePolygonsWithBatchTableTileset ); expect(tileset.isDestroyed()).toEqual(false); tileset.destroy(); expect(tileset.isDestroyed()).toEqual(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/Vector3DTileGeometrySpec.js var import__650 = __toESM(require_Cesium(), 1); describe( "Scene/Vector3DTileGeometry", function() { createWebglVersionHelper(createGeometrySpecs); function createGeometrySpecs(contextOptions) { let scene2; let rectangle; let geometry; let globePrimitive; let tilesetPrimitive; let reusableGlobePrimitive; let reusableTilesetPrimitive; const ellipsoid = import__650.Ellipsoid.WGS84; const mockTileset = { _statistics: { texturesByteLength: 0 }, tileset: { _statistics: { batchTableByteLength: 0 }, colorBlendMode: import__650.ColorBlendMode.HIGHLIGHT }, getFeature: function(id) { return { batchId: id }; } }; function createPrimitive(rectangle2, pass) { let renderState; if (pass === import__650.Pass.CESIUM_3D_TILE) { renderState = import__650.RenderState.fromCache({ stencilTest: import__650.StencilConstants.setCesium3DTileBit(), stencilMask: import__650.StencilConstants.CESIUM_3D_TILE_MASK, depthTest: { enabled: true } }); } const depthColorAttribute = import__650.ColorGeometryInstanceAttribute.fromColor( new import__650.Color(1, 0, 0, 1) ); return new import__650.Primitive({ geometryInstances: new import__650.GeometryInstance({ geometry: new import__650.RectangleGeometry({ ellipsoid: import__650.Ellipsoid.WGS84, rectangle: rectangle2 }), id: "depth rectangle", attributes: { color: depthColorAttribute } }), appearance: new import__650.PerInstanceColorAppearance({ translucent: false, flat: true, renderState }), asynchronous: false }); } function MockPrimitive(primitive, pass) { this._primitive = primitive; this._pass = pass; this.show = true; } MockPrimitive.prototype.update = function(frameState2) { if (!this.show) { return; } const commandList = frameState2.commandList; const startLength = commandList.length; this._primitive.update(frameState2); for (let i = startLength; i < commandList.length; ++i) { const command = commandList[i]; command.pass = this._pass; } }; MockPrimitive.prototype.isDestroyed = function() { return false; }; MockPrimitive.prototype.destroy = function() { return (0, import__650.destroyObject)(this); }; beforeAll(function() { scene2 = createScene_default({ contextOptions }); rectangle = import__650.Rectangle.fromDegrees(-80, 20, -70, 30); reusableGlobePrimitive = createPrimitive(rectangle, import__650.Pass.GLOBE); reusableTilesetPrimitive = createPrimitive( rectangle, import__650.Pass.CESIUM_3D_TILE ); }); afterAll(function() { reusableGlobePrimitive.destroy(); reusableTilesetPrimitive.destroy(); scene2.destroyForSpecs(); }); beforeEach(function() { globePrimitive = new MockPrimitive(reusableGlobePrimitive, import__650.Pass.GLOBE); tilesetPrimitive = new MockPrimitive( reusableTilesetPrimitive, import__650.Pass.CESIUM_3D_TILE ); }); afterEach(function() { scene2.primitives.removeAll(); globePrimitive = globePrimitive && !globePrimitive.isDestroyed() && globePrimitive.destroy(); tilesetPrimitive = tilesetPrimitive && !tilesetPrimitive.isDestroyed() && tilesetPrimitive.destroy(); geometry = geometry && !geometry.isDestroyed() && geometry.destroy(); }); function loadGeometries(geometries) { return pollToPromise_default(function() { geometries.update(scene2.frameState); scene2.frameState.commandList.length = 0; return geometries.ready; }); } function packBoxes(boxes) { const length2 = boxes.length; const packedBoxes = new Float32Array( length2 * import__650.Vector3DTileGeometry.packedBoxLength ); let offset = 0; for (let i = 0; i < length2; ++i) { const box = boxes[i]; import__650.Cartesian3.pack(box.dimensions, packedBoxes, offset); offset += import__650.Cartesian3.packedLength; import__650.Matrix4.pack(box.modelMatrix, packedBoxes, offset); offset += import__650.Matrix4.packedLength; } return packedBoxes; } function packCylinders(cylinders) { const length2 = cylinders.length; const packedCylinders = new Float32Array( length2 * import__650.Vector3DTileGeometry.packedCylinderLength ); let offset = 0; for (let i = 0; i < length2; ++i) { const cylinder = cylinders[i]; packedCylinders[offset++] = cylinder.radius; packedCylinders[offset++] = cylinder.length; import__650.Matrix4.pack(cylinder.modelMatrix, packedCylinders, offset); offset += import__650.Matrix4.packedLength; } return packedCylinders; } function packEllipsoids(ellipsoids) { const length2 = ellipsoids.length; const packedEllipsoids = new Float32Array( length2 * import__650.Vector3DTileGeometry.packedEllipsoidLength ); let offset = 0; for (let i = 0; i < length2; ++i) { const ellipsoid2 = ellipsoids[i]; import__650.Cartesian3.pack(ellipsoid2.radii, packedEllipsoids, offset); offset += import__650.Cartesian3.packedLength; import__650.Matrix4.pack(ellipsoid2.modelMatrix, packedEllipsoids, offset); offset += import__650.Matrix4.packedLength; } return packedEllipsoids; } function packSpheres(spheres) { const length2 = spheres.length; const packedSpheres = new Float32Array( length2 * import__650.Vector3DTileGeometry.packedSphereLength ); let offset = 0; for (let i = 0; i < length2; ++i) { const sphere = spheres[i]; packedSpheres[offset++] = sphere.radius; import__650.Cartesian3.pack( import__650.Matrix4.getTranslation(sphere.modelMatrix, new import__650.Cartesian3()), packedSpheres, offset ); offset += import__650.Cartesian3.packedLength; } return packedSpheres; } function verifySingleRender(geometryOptions) { const origin = import__650.Rectangle.center(rectangle); const center = ellipsoid.cartographicToCartesian(origin); const modelMatrix = import__650.Transforms.eastNorthUpToFixedFrame(center); import__650.Cartesian3.clone(center, geometryOptions.boundingVolume.center); const batchTable = new import__650.Cesium3DTileBatchTable(mockTileset, 1); batchTable.update(mockTileset, scene2.frameState); scene2.primitives.add(globePrimitive); geometry = scene2.primitives.add( new import__650.Vector3DTileGeometry( (0, import__650.combine)(geometryOptions, { center, modelMatrix, batchTable }) ) ); return loadGeometries(geometry).then(function() { scene2.camera.setView({ destination: rectangle }); scene2.camera.zoomIn(scene2.camera.positionCartographic.height * 0.9); expect(scene2).toRender([255, 255, 255, 255]); batchTable.setColor(0, import__650.Color.BLUE); geometry.updateCommands(0, import__650.Color.BLUE); batchTable.update(mockTileset, scene2.frameState); expect(scene2).toRender([0, 0, 255, 255]); }); } function verifyMultipleRender(modelMatrices, geometryOptions) { const origin = import__650.Rectangle.center(rectangle); const center = ellipsoid.cartographicToCartesian(origin); const modelMatrix = import__650.Transforms.eastNorthUpToFixedFrame(center); import__650.Cartesian3.clone(center, geometryOptions.boundingVolume.center); const length2 = modelMatrices.length; const batchTable = new import__650.Cesium3DTileBatchTable(mockTileset, length2); batchTable.update(mockTileset, scene2.frameState); scene2.primitives.add(globePrimitive); geometry = scene2.primitives.add( new import__650.Vector3DTileGeometry( (0, import__650.combine)(geometryOptions, { center, modelMatrix, batchTable }) ) ); return loadGeometries(geometry).then(function() { let i; for (i = 0; i < length2; ++i) { batchTable.setShow(i, false); } for (i = 0; i < length2; ++i) { const transform = import__650.Matrix4.multiply( modelMatrix, modelMatrices[i], new import__650.Matrix4() ); scene2.camera.lookAtTransform( transform, new import__650.Cartesian3(0, 0, 10) ); batchTable.setShow(i, true); batchTable.update(mockTileset, scene2.frameState); expect(scene2).toRender([255, 255, 255, 255]); batchTable.setColor(i, import__650.Color.BLUE); geometry.updateCommands(i, import__650.Color.BLUE); batchTable.update(mockTileset, scene2.frameState); expect(scene2).toRender([0, 0, 255, 255]); batchTable.setShow(i, false); } }); } it(`renders a single box`, function() { const dimensions = new import__650.Cartesian3(1e6, 1e6, 1e6); const boxes = packBoxes([ { modelMatrix: import__650.Matrix4.IDENTITY, dimensions } ]); const boxBatchIds = new Uint16Array([0]); const bv = new import__650.BoundingSphere( void 0, Math.sqrt(3 * dimensions.x * dimensions.x) ); return verifySingleRender({ boxes, boxBatchIds, boundingVolume: bv }); }); it(`renders multiple boxes`, function() { const dimensions = new import__650.Cartesian3(5e5, 5e5, 5e5); const modelMatrices = [ import__650.Matrix4.fromTranslation(new import__650.Cartesian3(dimensions.x, 0, 0)), import__650.Matrix4.fromTranslation(new import__650.Cartesian3(-dimensions.x, 0, 0)) ]; const boxes = packBoxes([ { modelMatrix: modelMatrices[0], dimensions }, { modelMatrix: modelMatrices[1], dimensions } ]); const boxBatchIds = new Uint16Array([0, 1]); const bv = new import__650.BoundingSphere( void 0, Math.sqrt(3 * 2 * dimensions.x * dimensions.x) ); return verifyMultipleRender(modelMatrices, { boxes, boxBatchIds, boundingVolume: bv }); }); it(`renders a single cylinder`, function() { const radius = 1e6; const length2 = 1e6; const cylinders = packCylinders([ { modelMatrix: import__650.Matrix4.IDENTITY, radius, length: length2 } ]); const cylinderBatchIds = new Uint16Array([0]); const bv = new import__650.BoundingSphere( void 0, Math.sqrt(radius * radius + length2 * length2) ); return verifySingleRender({ cylinders, cylinderBatchIds, boundingVolume: bv }); }); it(`renders multiple cylinders`, function() { const radius = 5e5; const length2 = 5e5; const modelMatrices = [ import__650.Matrix4.fromTranslation(new import__650.Cartesian3(radius, 0, 0)), import__650.Matrix4.fromTranslation(new import__650.Cartesian3(-radius, 0, 0)) ]; const cylinders = packCylinders([ { modelMatrix: modelMatrices[0], radius, length: length2 }, { modelMatrix: modelMatrices[1], radius, length: length2 } ]); const cylinderBatchIds = new Uint16Array([0, 1]); const bv = new import__650.BoundingSphere( void 0, Math.sqrt(2 * (radius * radius + length2 * length2)) ); return verifyMultipleRender(modelMatrices, { cylinders, cylinderBatchIds, boundingVolume: bv }); }); it(`renders a single ellipsoid`, function() { const radii = new import__650.Cartesian3(5e5, 5e5, 5e5); const ellipsoid2 = packEllipsoids([ { modelMatrix: import__650.Matrix4.IDENTITY, radii } ]); const ellipsoidBatchIds = new Uint16Array([0]); const bv = new import__650.BoundingSphere( void 0, import__650.Cartesian3.maximumComponent(radii) ); return verifySingleRender({ ellipsoids: ellipsoid2, ellipsoidBatchIds, boundingVolume: bv }); }); it(`renders multiple ellipsoids`, function() { const radii = new import__650.Cartesian3(5e5, 5e5, 5e5); const modelMatrices = [ import__650.Matrix4.fromTranslation(new import__650.Cartesian3(radii.x, 0, 0)), import__650.Matrix4.fromTranslation(new import__650.Cartesian3(-radii.x, 0, 0)) ]; const ellipsoids = packEllipsoids([ { modelMatrix: modelMatrices[0], radii }, { modelMatrix: modelMatrices[1], radii } ]); const ellipsoidBatchIds = new Uint16Array([0, 1]); const bv = new import__650.BoundingSphere( void 0, 2 * import__650.Cartesian3.maximumComponent(radii) ); return verifyMultipleRender(modelMatrices, { ellipsoids, ellipsoidBatchIds, boundingVolume: bv }); }); it(`renders a single sphere`, function() { const radius = 5e5; const sphere = packSpheres([ { radius, modelMatrix: import__650.Matrix4.IDENTITY } ]); const sphereBatchIds = new Uint16Array([0]); const bv = new import__650.BoundingSphere(void 0, radius); return verifySingleRender({ spheres: sphere, sphereBatchIds, boundingVolume: bv }); }); it(`renders multiple spheres`, function() { const radius = 5e5; const modelMatrices = [ import__650.Matrix4.fromTranslation(new import__650.Cartesian3(radius, 0, 0)), import__650.Matrix4.fromTranslation(new import__650.Cartesian3(-radius, 0, 0)) ]; const spheres = packSpheres([ { modelMatrix: modelMatrices[0], radius }, { modelMatrix: modelMatrices[1], radius } ]); const sphereBatchIds = new Uint16Array([0, 1]); const bv = new import__650.BoundingSphere(void 0, 2 * radius); return verifyMultipleRender(modelMatrices, { spheres, sphereBatchIds, boundingVolume: bv }); }); it(`renders with multiple types of each geometry`, function() { const dimensions = new import__650.Cartesian3(125e3, 125e3, 125e3); const modelMatrices = [ import__650.Matrix4.fromTranslation(new import__650.Cartesian3(dimensions.x, 0, 0)), import__650.Matrix4.fromTranslation(new import__650.Cartesian3(-dimensions.x, 0, 0)) ]; const boxes = packBoxes([ { modelMatrix: modelMatrices[0], dimensions }, { modelMatrix: modelMatrices[1], dimensions } ]); const boxBatchIds = new Uint16Array([0, 1]); const radius = 125e3; const length2 = 125e3; modelMatrices.push( import__650.Matrix4.fromTranslation(new import__650.Cartesian3(radius, 0, 0)), import__650.Matrix4.fromTranslation(new import__650.Cartesian3(-radius, 0, 0)) ); const cylinders = packCylinders([ { modelMatrix: modelMatrices[2], radius, length: length2 }, { modelMatrix: modelMatrices[3], radius, length: length2 } ]); const cylinderBatchIds = new Uint16Array([2, 3]); const radii = new import__650.Cartesian3(125e3, 125e3, 125e3); modelMatrices.push( import__650.Matrix4.fromTranslation(new import__650.Cartesian3(radii.x, 0, 0)), import__650.Matrix4.fromTranslation(new import__650.Cartesian3(-radii.x, 0, 0)) ); const ellipsoids = packEllipsoids([ { modelMatrix: modelMatrices[4], radii }, { modelMatrix: modelMatrices[5], radii } ]); const ellipsoidBatchIds = new Uint16Array([4, 5]); modelMatrices.push( import__650.Matrix4.fromTranslation(new import__650.Cartesian3(radius, 0, 0)), import__650.Matrix4.fromTranslation(new import__650.Cartesian3(-radius, 0, 0)) ); const spheres = packSpheres([ { modelMatrix: modelMatrices[6], radius }, { modelMatrix: modelMatrices[7], radius } ]); const sphereBatchIds = new Uint16Array([6, 7]); const bv = new import__650.BoundingSphere(void 0, 5e7); return verifyMultipleRender(modelMatrices, { boxes, boxBatchIds, cylinders, cylinderBatchIds, ellipsoids, ellipsoidBatchIds, spheres, sphereBatchIds, boundingVolume: bv }); }); it(`renders multiple geometries after a re-batch`, function() { const dimensions = new import__650.Cartesian3(125e3, 125e3, 125e3); const modelMatrices = [ import__650.Matrix4.fromTranslation(new import__650.Cartesian3(dimensions.x, 0, 0)), import__650.Matrix4.fromTranslation(new import__650.Cartesian3(-dimensions.x, 0, 0)) ]; const boxes = packBoxes([ { modelMatrix: modelMatrices[0], dimensions }, { modelMatrix: modelMatrices[1], dimensions } ]); const boxBatchIds = new Uint16Array([0, 1]); const radius = 125e3; let length2 = 125e3; modelMatrices.push( import__650.Matrix4.fromTranslation(new import__650.Cartesian3(radius, 0, 0)), import__650.Matrix4.fromTranslation(new import__650.Cartesian3(-radius, 0, 0)) ); const cylinders = packCylinders([ { modelMatrix: modelMatrices[2], radius, length: length2 }, { modelMatrix: modelMatrices[3], radius, length: length2 } ]); const cylinderBatchIds = new Uint16Array([2, 3]); const origin = import__650.Rectangle.center(rectangle); const center = ellipsoid.cartographicToCartesian(origin); const modelMatrix = import__650.Transforms.eastNorthUpToFixedFrame(center); const bv = new import__650.BoundingSphere(center, 5e7); length2 = modelMatrices.length; const batchTable = new import__650.Cesium3DTileBatchTable(mockTileset, length2); batchTable.update(mockTileset, scene2.frameState); scene2.primitives.add(globePrimitive); geometry = scene2.primitives.add( new import__650.Vector3DTileGeometry({ boxes, boxBatchIds, cylinders, cylinderBatchIds, center, modelMatrix, batchTable, boundingVolume: bv }) ); geometry.forceRebatch = true; return loadGeometries(geometry).then(function() { let i; for (i = 0; i < length2; ++i) { batchTable.setShow(i, false); } for (i = 0; i < length2; ++i) { const transform = import__650.Matrix4.multiply( modelMatrix, modelMatrices[i], new import__650.Matrix4() ); scene2.camera.lookAtTransform( transform, new import__650.Cartesian3(0, 0, 10) ); batchTable.setShow(i, true); batchTable.update(mockTileset, scene2.frameState); expect(scene2).toRender([255, 255, 255, 255]); batchTable.setColor(i, import__650.Color.BLUE); geometry.updateCommands(i, import__650.Color.BLUE); batchTable.update(mockTileset, scene2.frameState); expect(scene2).toRender([0, 0, 255, 255]); batchTable.setShow(i, false); } }); }); it(`renders with inverted classification`, function() { const radii = new import__650.Cartesian3(100, 100, 1e3); const ellipsoids = packEllipsoids([ { modelMatrix: import__650.Matrix4.IDENTITY, radii } ]); const ellipsoidBatchIds = new Uint16Array([0]); const origin = import__650.Rectangle.center(rectangle); const center = ellipsoid.cartographicToCartesian(origin); const modelMatrix = import__650.Transforms.eastNorthUpToFixedFrame(center); const bv = new import__650.BoundingSphere( center, import__650.Cartesian3.maximumComponent(radii) ); const batchTable = new import__650.Cesium3DTileBatchTable(mockTileset, 1); batchTable.update(mockTileset, scene2.frameState); scene2.primitives.add(tilesetPrimitive); geometry = scene2.primitives.add( new import__650.Vector3DTileGeometry({ ellipsoids, ellipsoidBatchIds, boundingVolume: bv, center, modelMatrix, batchTable }) ); return loadGeometries(geometry).then(function() { scene2.camera.lookAtTransform( modelMatrix, new import__650.Cartesian3(0, 0, 1) ); expect(scene2).toRender([255, 255, 255, 255]); scene2.camera.lookAtTransform( modelMatrix, new import__650.Cartesian3(radii.x, 0, 1) ); expect(scene2).toRender([255, 0, 0, 255]); scene2.invertClassification = true; scene2.invertClassificationColor = new import__650.Color(0.25, 0.25, 0.25, 1); expect(scene2).toRender([64, 0, 0, 255]); scene2.invertClassification = false; }); }); it(`renders wireframe`, function() { const origin = import__650.Rectangle.center(rectangle); const center = ellipsoid.cartographicToCartesian(origin); const modelMatrix = import__650.Transforms.eastNorthUpToFixedFrame(center); const batchTable = new import__650.Cesium3DTileBatchTable(mockTileset, 1); batchTable.update(mockTileset, scene2.frameState); scene2.primitives.add(globePrimitive); geometry = scene2.primitives.add( new import__650.Vector3DTileGeometry({ ellipsoids: packEllipsoids([ { modelMatrix: import__650.Matrix4.IDENTITY, radii: new import__650.Cartesian3(1e6, 1e6, 1e6) } ]), ellipsoidBatchIds: new Uint16Array([0]), center, modelMatrix, batchTable, boundingVolume: new import__650.BoundingSphere(center, 1e6) }) ); geometry.debugWireframe = true; return loadGeometries(geometry).then(function() { scene2.camera.setView({ destination: rectangle }); scene2.camera.zoomIn(scene2.camera.positionCartographic.height * 0.9); expect(scene2).toRender([255, 255, 255, 255]); batchTable.setColor(0, import__650.Color.BLUE); geometry.updateCommands(0, import__650.Color.BLUE); batchTable.update(mockTileset, scene2.frameState); expect(scene2).toRender([0, 0, 255, 255]); }); }); it(`renders based on classificationType`, function() { const radii = new import__650.Cartesian3(100, 100, 1e3); const ellipsoids = packEllipsoids([ { modelMatrix: import__650.Matrix4.IDENTITY, radii } ]); const ellipsoidBatchIds = new Uint16Array([0]); const origin = import__650.Rectangle.center(rectangle); const center = ellipsoid.cartographicToCartesian(origin); const modelMatrix = import__650.Transforms.eastNorthUpToFixedFrame(center); const bv = new import__650.BoundingSphere( center, import__650.Cartesian3.maximumComponent(radii) ); const batchTable = new import__650.Cesium3DTileBatchTable(mockTileset, 1); batchTable.update(mockTileset, scene2.frameState); scene2.primitives.add(globePrimitive); scene2.primitives.add(tilesetPrimitive); geometry = scene2.primitives.add( new import__650.Vector3DTileGeometry({ ellipsoids, ellipsoidBatchIds, boundingVolume: bv, center, modelMatrix, batchTable }) ); return loadGeometries(geometry).then(function() { scene2.camera.lookAtTransform( modelMatrix, new import__650.Cartesian3(0, 0, 1) ); geometry.classificationType = import__650.ClassificationType.CESIUM_3D_TILE; globePrimitive.show = false; tilesetPrimitive.show = true; expect(scene2).toRender([255, 255, 255, 255]); globePrimitive.show = true; tilesetPrimitive.show = false; expect(scene2).toRender([255, 0, 0, 255]); geometry.classificationType = import__650.ClassificationType.TERRAIN; globePrimitive.show = false; tilesetPrimitive.show = true; expect(scene2).toRender([255, 0, 0, 255]); globePrimitive.show = true; tilesetPrimitive.show = false; expect(scene2).toRender([255, 255, 255, 255]); geometry.classificationType = import__650.ClassificationType.BOTH; globePrimitive.show = false; tilesetPrimitive.show = true; expect(scene2).toRender([255, 255, 255, 255]); globePrimitive.show = true; tilesetPrimitive.show = false; expect(scene2).toRender([255, 255, 255, 255]); globePrimitive.show = true; tilesetPrimitive.show = true; }); }); it(`picks geometry`, function() { const origin = import__650.Rectangle.center(rectangle); const center = ellipsoid.cartographicToCartesian(origin); const modelMatrix = import__650.Transforms.eastNorthUpToFixedFrame(center); const batchTable = new import__650.Cesium3DTileBatchTable(mockTileset, 1); scene2.primitives.add(globePrimitive); geometry = scene2.primitives.add( new import__650.Vector3DTileGeometry({ ellipsoids: packEllipsoids([ { modelMatrix: import__650.Matrix4.IDENTITY, radii: new import__650.Cartesian3(5e5, 5e5, 5e5) } ]), ellipsoidBatchIds: new Uint16Array([0]), center, modelMatrix, batchTable, boundingVolume: new import__650.BoundingSphere(center, 5e5) }) ); return loadGeometries(geometry).then(function() { scene2.camera.setView({ destination: rectangle }); scene2.camera.zoomIn(scene2.camera.positionCartographic.height * 0.9); const features = []; geometry.createFeatures(mockTileset, features); const getFeature = mockTileset.getFeature; mockTileset.getFeature = function(index) { return features[index]; }; scene2.frameState.passes.pick = true; batchTable.update(mockTileset, scene2.frameState); expect(scene2).toPickAndCall(function(result) { expect(result).toBe(features[0]); }); mockTileset.getFeature = getFeature; }); }); it(`isDestroyed`, function() { geometry = new import__650.Vector3DTileGeometry({}); expect(geometry.isDestroyed()).toEqual(false); geometry.destroy(); expect(geometry.isDestroyed()).toEqual(true); }); } }, "WebGL" ); // packages/engine/Specs/Scene/Vector3DTilePointsSpec.js var import__651 = __toESM(require_Cesium(), 1); var import__652 = __toESM(require_Cesium(), 1); describe( "Scene/Vector3DTilePoints", function() { let scene2; let rectangle; let points; const ellipsoid = import__651.Ellipsoid.WGS84; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); const mockTileset = { _statistics: { texturesByteLength: 0 }, tileset: { _statistics: { batchTableByteLength: 0 }, colorBlendMode: import__651.ColorBlendMode.HIGHLIGHT, ellipsoid: import__651.Ellipsoid.WGS84 }, tile: {}, getFeature: function(id) { return { batchId: id }; } }; beforeEach(function() { rectangle = import__651.Rectangle.fromDegrees(-40, -40, 40, 40); }); afterEach(function() { scene2.primitives.removeAll(); points = points && !points.isDestroyed() && points.destroy(); }); function allPrimitivesReady(points2) { return pollToPromise_default(function() { scene2.renderForSpecs(); const backgroundBillboard = points2._labelCollection._backgroundBillboardCollection.get( 0 ); return (!(0, import__651.defined)(backgroundBillboard) || backgroundBillboard.ready) && points2._labelCollection._labelsToUpdate.length === 0 && (!(0, import__651.defined)(points2._billboardCollection.get(0)) || points2._billboardCollection.get(0).ready); }); } function loadPoints(points2) { return pollToPromise_default(function() { points2.update(scene2.frameState); scene2.frameState.commandList.length = 0; return points2.ready; }); } function zigZag(value) { return (value << 1 ^ value >> 15) & 65535; } const maxShort = 32767; function encodePositions(rectangle2, minimumHeight, maximumHeight, positions) { const length2 = positions.length; const buffer = new Uint16Array(length2 * 3); let lastU = 0; let lastV = 0; let lastH = 0; for (let i = 0; i < length2; ++i) { const position = positions[i]; let u = (position.longitude - rectangle2.west) / rectangle2.width; let v = (position.latitude - rectangle2.south) / rectangle2.height; let h = (position.height - minimumHeight) / (maximumHeight - minimumHeight); u = import__652.Math.clamp(u, 0, 1); v = import__652.Math.clamp(v, 0, 1); h = import__652.Math.clamp(h, 0, 1); u = Math.floor(u * maxShort); v = Math.floor(v * maxShort); h = Math.floor(h * maxShort); buffer[i] = zigZag(u - lastU); buffer[i + length2] = zigZag(v - lastV); buffer[i + length2 * 2] = zigZag(h - lastH); lastU = u; lastV = v; lastH = h; } return buffer; } it("renders a point", function() { const minHeight = 0; const maxHeight = 100; const cartoPositions = [import__651.Cartographic.fromDegrees(0, 0, 10)]; const positions = encodePositions( rectangle, minHeight, maxHeight, cartoPositions ); const batchTable = new import__651.Cesium3DTileBatchTable(mockTileset, 1); batchTable.update(mockTileset, scene2.frameState); points = scene2.primitives.add( new import__651.Vector3DTilePoints({ positions, batchTable, batchIds: new Uint16Array([0]), rectangle, minimumHeight: minHeight, maximumHeight: maxHeight }) ); return loadPoints(points).then(function() { const features = []; points.createFeatures(mockTileset, features); points.applyStyle(void 0, features); scene2.camera.lookAt( import__651.Cartesian3.fromDegrees(0, 0, 30), new import__651.Cartesian3(0, 0, 50) ); return allPrimitivesReady(points); }).then(function() { expect(scene2).toRender([255, 255, 255, 255]); }); }); it("renders multiple points", function() { const minHeight = 0; const maxHeight = 100; const cartoPositions = [ import__651.Cartographic.fromDegrees(0, 0, 10), import__651.Cartographic.fromDegrees(5, 0, 20), import__651.Cartographic.fromDegrees(-5, 0, 1), import__651.Cartographic.fromDegrees(0, 6, 5), import__651.Cartographic.fromDegrees(0, -6, 90) ]; const positions = encodePositions( rectangle, minHeight, maxHeight, cartoPositions ); const batchTable = new import__651.Cesium3DTileBatchTable(mockTileset, 5); batchTable.update(mockTileset, scene2.frameState); points = scene2.primitives.add( new import__651.Vector3DTilePoints({ positions, batchTable, batchIds: new Uint16Array([0, 1, 2, 3, 4]), rectangle, minimumHeight: minHeight, maximumHeight: maxHeight }) ); const style = new import__651.Cesium3DTileStyle({ verticalOrigin: import__651.VerticalOrigin.BOTTOM }); return loadPoints(points).then(function() { const features = []; points.createFeatures(mockTileset, features); points.applyStyle(style, features); const position = ellipsoid.cartographicToCartesian(cartoPositions[0]); scene2.camera.lookAt(position, new import__651.Cartesian3(0, 0, 50)); return allPrimitivesReady(points); }).then(function() { for (let i = 0; i < cartoPositions.length; ++i) { const position = ellipsoid.cartographicToCartesian( cartoPositions[i] ); scene2.camera.lookAt(position, new import__651.Cartesian3(0, 0, 50)); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[0]).toEqual(rgba[1]); expect(rgba[0]).toEqual(rgba[2]); expect(rgba[3]).toEqual(255); }); } }); }); it("picks a point", function() { const minHeight = 0; const maxHeight = 100; const cartoPositions = [import__651.Cartographic.fromDegrees(0, 0, 10)]; const positions = encodePositions( rectangle, minHeight, maxHeight, cartoPositions ); const batchTable = new import__651.Cesium3DTileBatchTable(mockTileset, 1); points = scene2.primitives.add( new import__651.Vector3DTilePoints({ positions, batchTable, batchIds: new Uint16Array([0]), rectangle, minimumHeight: minHeight, maximumHeight: maxHeight }) ); const features = []; const getFeature = mockTileset.getFeature; return loadPoints(points).then(function() { scene2.camera.lookAt( import__651.Cartesian3.fromDegrees(0, 0, 10), new import__651.Cartesian3(0, 0, 50) ); points.createFeatures(mockTileset, features); points.applyStyle(void 0, features); mockTileset.getFeature = function(index) { return features[index]; }; scene2.frameState.passes.pick = true; batchTable.update(mockTileset, scene2.frameState); return allPrimitivesReady(points); }).then(function() { expect(scene2).toPickAndCall(function(result) { expect(result).toBe(features[0]); }); scene2.frameState.passes.pick = false; mockTileset.getFeature = getFeature; }); }); it("renders multiple points with style", function() { const minHeight = 0; const maxHeight = 100; const cartoPositions = [ import__651.Cartographic.fromDegrees(0, 0, 10), import__651.Cartographic.fromDegrees(5, 0, 20), import__651.Cartographic.fromDegrees(-5, 0, 1), import__651.Cartographic.fromDegrees(0, 6, 5), import__651.Cartographic.fromDegrees(0, -6, 90) ]; const positions = encodePositions( rectangle, minHeight, maxHeight, cartoPositions ); const mockTilesetClone = (0, import__651.clone)(mockTileset); const batchTable = new import__651.Cesium3DTileBatchTable(mockTilesetClone, 5); mockTilesetClone.batchTable = batchTable; for (let i = 0; i < 5; ++i) { batchTable.setProperty(i, "temperature", i); } batchTable.update(mockTilesetClone, scene2.frameState); points = scene2.primitives.add( new import__651.Vector3DTilePoints({ positions, batchTable, batchIds: new Uint16Array([0, 1, 2, 3, 4]), rectangle, minimumHeight: minHeight, maximumHeight: maxHeight }) ); const style = new import__651.Cesium3DTileStyle({ show: "true", pointSize: "10.0", color: "rgba(255, 255, 0, 0.5)", pointOutlineColor: "rgba(255, 255, 0, 1.0)", pointOutlineWidth: "11.0 * ${temperature}", labelColor: "rgba(255, 255, 0, 1.0)", labelOutlineColor: "rgba(255, 255, 0, 0.5)", labelOutlineWidth: "1.0", font: '"30px sans-serif"', labelStyle: `${import__651.LabelStyle.FILL_AND_OUTLINE}`, labelText: '"test"', backgroundColor: "rgba(255, 255, 0, 0.2)", backgroundPadding: "vec2(10, 11)", backgroundEnabled: "true", scaleByDistance: "vec4(1.0e4, 1.0, 1.0e6, 0.0)", translucencyByDistance: "vec4(1.0e4, 1.0, 1.0e6, 0.0)", distanceDisplayCondition: "vec2(0.1, 1.0e6)", heightOffset: "0.0", anchorLineEnabled: "true", anchorLineColor: "rgba(255, 255, 0, 1.0)", disableDepthTestDistance: "1.0e6", horizontalOrigin: `${import__651.HorizontalOrigin.CENTER}`, verticalOrigin: `${import__651.VerticalOrigin.CENTER}`, labelHorizontalOrigin: `${import__651.HorizontalOrigin.RIGHT}`, labelVerticalOrigin: `${import__651.VerticalOrigin.BOTTOM}` }); return loadPoints(points).then(function() { const features = []; points.createFeatures(mockTilesetClone, features); points.applyStyle(style, features); let i; for (i = 0; i < features.length; ++i) { const feature = features[i]; expect(feature.show).toEqual(true); expect(feature.pointSize).toEqual(10); expect(feature.color).toEqual(new import__651.Color(1, 1, 0, 0.5)); expect(feature.pointOutlineColor).toEqual( new import__651.Color(1, 1, 0, 1) ); expect(feature.pointOutlineWidth).toEqual(11 * i); expect(feature.labelColor).toEqual(new import__651.Color(1, 1, 0, 1)); expect(feature.labelOutlineColor).toEqual( new import__651.Color(1, 1, 0, 0.5) ); expect(feature.labelOutlineWidth).toEqual(1); expect(feature.font).toEqual("30px sans-serif"); expect(feature.labelStyle).toEqual(import__651.LabelStyle.FILL_AND_OUTLINE); expect(feature.labelText).toEqual("test"); expect(feature.backgroundColor).toEqual( new import__651.Color(1, 1, 0, 0.2) ); expect(feature.backgroundPadding).toEqual(new import__651.Cartesian2(10, 11)); expect(feature.backgroundEnabled).toEqual(true); expect(feature.scaleByDistance).toEqual( new import__651.NearFarScalar(1e4, 1, 1e6, 0) ); expect(feature.translucencyByDistance).toEqual( new import__651.NearFarScalar(1e4, 1, 1e6, 0) ); expect(feature.distanceDisplayCondition).toEqual( new import__651.DistanceDisplayCondition(0.1, 1e6) ); expect(feature.heightOffset).toEqual(0); expect(feature.anchorLineEnabled).toEqual(true); expect(feature.anchorLineColor).toEqual( new import__651.Color(1, 1, 0, 1) ); expect(feature.disableDepthTestDistance).toEqual(1e6); expect(feature.horizontalOrigin).toEqual(import__651.HorizontalOrigin.CENTER); expect(feature.verticalOrigin).toEqual(import__651.VerticalOrigin.CENTER); expect(feature.labelHorizontalOrigin).toEqual( import__651.HorizontalOrigin.RIGHT ); expect(feature.labelVerticalOrigin).toEqual(import__651.VerticalOrigin.BOTTOM); } const position = ellipsoid.cartographicToCartesian(cartoPositions[0]); scene2.camera.lookAt(position, new import__651.Cartesian3(0, 0, 50)); return allPrimitivesReady(points); }).then(function() { let position; for (let i = 0; i < cartoPositions.length; ++i) { position = ellipsoid.cartographicToCartesian(cartoPositions[i]); scene2.camera.lookAt(position, new import__651.Cartesian3(0, 0, 50)); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toBeGreaterThan(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); } }); }); it("renders multiple points and test style options witch can be evaluated to undefined", function() { const testOptions = ( /*[ Cesium3DTileStyle option, Cesium3DTileStyle default value, Cesium3DTileFeature property, expected Cesium3DTileFeature value, expected undefined Cesium3DTileFeature value ]*/ [ [ "scaleByDistance", new import__651.Cartesian4(1e4, 1, 1e6, 0), "scaleByDistance", new import__651.NearFarScalar(1e4, 1, 1e6, 0), void 0 ], [ "translucencyByDistance", new import__651.Cartesian4(1e4, 1, 1e6, 0), "translucencyByDistance", new import__651.NearFarScalar(1e4, 1, 1e6, 0), void 0 ], [ "distanceDisplayCondition", new import__651.Cartesian2(0.1, 1e6), "distanceDisplayCondition", new import__651.DistanceDisplayCondition(0.1, 1e6), void 0 ], [ "disableDepthTestDistance", 1e6, "disableDepthTestDistance", 1e6, void 0 ] ] ); const minHeight = 0; const maxHeight = 100; const cartoPositions = []; for (let i = 0; i < testOptions.length; ++i) { cartoPositions.push(import__651.Cartographic.fromDegrees(0.1 * i, 0, 10)); } const positions = encodePositions( rectangle, minHeight, maxHeight, cartoPositions ); const mockTilesetClone = (0, import__651.clone)(mockTileset); const batchTable = new import__651.Cesium3DTileBatchTable( mockTilesetClone, testOptions.length ); mockTilesetClone.batchTable = batchTable; const batchIds = []; for (let i = 0; i < testOptions.length; ++i) { batchTable.setProperty(i, "pointIndex", i); batchIds.push(i); } batchTable.update(mockTilesetClone, scene2.frameState); points = scene2.primitives.add( new import__651.Vector3DTilePoints({ positions, batchTable, batchIds: new Uint16Array(batchIds), rectangle, minimumHeight: minHeight, maximumHeight: maxHeight }) ); const styleOptions = {}; for (let testOptionIndex = 0; testOptionIndex < testOptions.length; ++testOptionIndex) { const testOption = testOptions[testOptionIndex]; const cesium3DTileStyleOptionName = testOption[0]; const cesium3DTileStyleOptionDefaultValue = testOption[1]; styleOptions[cesium3DTileStyleOptionName] = { evaluate: function(feature) { if (feature.getProperty("pointIndex") === testOptionIndex) { return void 0; } return cesium3DTileStyleOptionDefaultValue; } }; } const style = new import__651.Cesium3DTileStyle(styleOptions); return loadPoints(points).then(function() { const features = []; points.createFeatures(mockTilesetClone, features); points.applyStyle(style, features); let i; for (i = 0; i < features.length; ++i) { const feature = features[i]; for (let testOptionIndex = 0; testOptionIndex < testOptions.length; ++testOptionIndex) { const testOption = testOptions[testOptionIndex]; const cesium3DTileFeaturePropertyName = testOption[2]; const expectedCesium3DTileFeaturePropertyDefaultValue = testOption[3]; const expectedCesium3DTileFeaturePropertyUndefinedValue = testOption[4]; const expectedCesium3DTileFeaturePropertyValue = i === testOptionIndex ? expectedCesium3DTileFeaturePropertyUndefinedValue : expectedCesium3DTileFeaturePropertyDefaultValue; if ((0, import__651.defined)(expectedCesium3DTileFeaturePropertyValue)) { expect(feature[cesium3DTileFeaturePropertyName]).toBeDefined(); expect(feature[cesium3DTileFeaturePropertyName]).toEqual( expectedCesium3DTileFeaturePropertyValue ); } else { expect(feature[cesium3DTileFeaturePropertyName]).toBeUndefined(); } } } const position = ellipsoid.cartographicToCartesian(cartoPositions[0]); scene2.camera.lookAt(position, new import__651.Cartesian3(0, 0, 50)); return allPrimitivesReady(points); }); }); it("renders a point with an image", function() { const minHeight = 0; const maxHeight = 100; const cartoPositions = [import__651.Cartographic.fromDegrees(0, 0, 10)]; const positions = encodePositions( rectangle, minHeight, maxHeight, cartoPositions ); const batchTable = new import__651.Cesium3DTileBatchTable(mockTileset, 1); batchTable.update(mockTileset, scene2.frameState); points = scene2.primitives.add( new import__651.Vector3DTilePoints({ positions, batchTable, batchIds: new Uint16Array([0]), rectangle, minimumHeight: minHeight, maximumHeight: maxHeight }) ); const style = new import__651.Cesium3DTileStyle({ image: '"./Data/Images/Blue10x10.png"' }); return loadPoints(points).then(function() { const features = []; points.createFeatures(mockTileset, features); points.applyStyle(style, features); const collection = points._billboardCollection; expect(collection.length).toEqual(1); const billboard = collection.get(0); expect(billboard).toBeDefined(); expect(billboard.ready).toEqual(false); scene2.camera.lookAt( import__651.Cartesian3.fromDegrees(0, 0, 10), new import__651.Cartesian3(0, 0, 50) ); return pollToPromise_default(function() { scene2.renderForSpecs(); return billboard.ready; }).then(function() { expect(billboard.ready).toEqual(true); expect(scene2).toRender([0, 0, 255, 255]); }); }); }); it("renders multiple points with debug color", function() { const minHeight = 0; const maxHeight = 100; const cartoPositions = [ import__651.Cartographic.fromDegrees(0, 0, 10), import__651.Cartographic.fromDegrees(5, 0, 20), import__651.Cartographic.fromDegrees(-5, 0, 1), import__651.Cartographic.fromDegrees(0, 6, 5), import__651.Cartographic.fromDegrees(0, -6, 90) ]; const positions = encodePositions( rectangle, minHeight, maxHeight, cartoPositions ); const batchTable = new import__651.Cesium3DTileBatchTable(mockTileset, 5); batchTable.update(mockTileset, scene2.frameState); points = scene2.primitives.add( new import__651.Vector3DTilePoints({ positions, batchTable, batchIds: new Uint16Array([0, 1, 2, 3, 4]), rectangle, minimumHeight: minHeight, maximumHeight: maxHeight }) ); const style = new import__651.Cesium3DTileStyle({ verticalOrigin: import__651.VerticalOrigin.BOTTOM }); let position; return loadPoints(points).then(function() { const features = []; points.createFeatures(mockTileset, features); points.applyStyle(style, features); points.applyDebugSettings(true, import__651.Color.YELLOW); position = ellipsoid.cartographicToCartesian(cartoPositions[0]); scene2.camera.lookAt(position, new import__651.Cartesian3(0, 0, 50)); return allPrimitivesReady(points); }).then(function() { for (let i = 0; i < cartoPositions.length; ++i) { position = ellipsoid.cartographicToCartesian(cartoPositions[i]); scene2.camera.lookAt(position, new import__651.Cartesian3(0, 0, 50)); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toBeGreaterThan(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); } points.applyDebugSettings(false); for (let i = 0; i < cartoPositions.length; ++i) { position = ellipsoid.cartographicToCartesian(cartoPositions[i]); scene2.camera.lookAt(position, new import__651.Cartesian3(0, 0, 50)); expect(scene2).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[0]).toEqual(rgba[1]); expect(rgba[0]).toEqual(rgba[2]); expect(rgba[3]).toEqual(255); }); } }); }); it("isDestroyed", function() { points = new import__651.Vector3DTilePoints({}); expect(points.isDestroyed()).toEqual(false); points.destroy(); expect(points.isDestroyed()).toEqual(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/Vector3DTilePolygonsSpec.js var import__653 = __toESM(require_Cesium(), 1); describe( "Scene/Vector3DTilePolygons", function() { createPolygonSpecs({}); function createPolygonSpecs(contextOptions) { const webglMessage = contextOptions.requestWebgl1 ? "" : "WebGL 2"; let scene2; let rectangle; let polygons; let globePrimitive; let tilesetPrimitive; let reusableGlobePrimitive; let reusableTilesetPrimitive; const ellipsoid = import__653.Ellipsoid.WGS84; const mockTileset = { _statistics: { texturesByteLength: 0 }, tileset: { _statistics: { batchTableByteLength: 0 }, colorBlendMode: import__653.ColorBlendMode.HIGHLIGHT }, getFeature: function(id) { return { batchId: id }; } }; function createPrimitive(rectangle2, pass) { let renderState; if (pass === import__653.Pass.CESIUM_3D_TILE) { renderState = import__653.RenderState.fromCache({ stencilTest: import__653.StencilConstants.setCesium3DTileBit(), stencilMask: import__653.StencilConstants.CESIUM_3D_TILE_MASK, depthTest: { enabled: true } }); } const depthColorAttribute = import__653.ColorGeometryInstanceAttribute.fromColor( new import__653.Color(1, 0, 0, 1) ); return new import__653.Primitive({ geometryInstances: new import__653.GeometryInstance({ geometry: new import__653.RectangleGeometry({ ellipsoid: import__653.Ellipsoid.WGS84, rectangle: rectangle2 }), id: "depth rectangle", attributes: { color: depthColorAttribute } }), appearance: new import__653.PerInstanceColorAppearance({ translucent: false, flat: true, renderState }), asynchronous: false }); } function MockPrimitive(primitive, pass) { this._primitive = primitive; this._pass = pass; this.show = true; } MockPrimitive.prototype.update = function(frameState2) { if (!this.show) { return; } const commandList = frameState2.commandList; const startLength = commandList.length; this._primitive.update(frameState2); for (let i = startLength; i < commandList.length; ++i) { const command = commandList[i]; command.pass = this._pass; } }; MockPrimitive.prototype.isDestroyed = function() { return false; }; MockPrimitive.prototype.destroy = function() { return (0, import__653.destroyObject)(this); }; beforeAll(function() { scene2 = createScene_default({ contextOptions }); rectangle = import__653.Rectangle.fromDegrees(-40, -40, 40, 40); reusableGlobePrimitive = createPrimitive(rectangle, import__653.Pass.GLOBE); reusableTilesetPrimitive = createPrimitive( rectangle, import__653.Pass.CESIUM_3D_TILE ); }); afterAll(function() { reusableGlobePrimitive.destroy(); reusableTilesetPrimitive.destroy(); scene2.destroyForSpecs(); }); beforeEach(function() { globePrimitive = new MockPrimitive(reusableGlobePrimitive, import__653.Pass.GLOBE); tilesetPrimitive = new MockPrimitive( reusableTilesetPrimitive, import__653.Pass.CESIUM_3D_TILE ); }); afterEach(function() { scene2.primitives.removeAll(); globePrimitive = globePrimitive && !globePrimitive.isDestroyed() && globePrimitive.destroy(); tilesetPrimitive = tilesetPrimitive && !tilesetPrimitive.isDestroyed() && tilesetPrimitive.destroy(); polygons = polygons && !polygons.isDestroyed() && polygons.destroy(); }); function loadPolygons(polygons2) { return pollToPromise_default(function() { polygons2.update(scene2.frameState); scene2.frameState.commandList.length = 0; return polygons2.ready; }); } function zigZag(value) { return (value << 1 ^ value >> 15) & 65535; } const maxShort = 32767; function encodePositions(rectangle2, positions) { const length2 = positions.length; const buffer = new Uint16Array(length2 * 2); let lastU = 0; let lastV = 0; for (let i = 0; i < length2; ++i) { const position = positions[i]; let u = (position.longitude - rectangle2.west) / rectangle2.width; let v = (position.latitude - rectangle2.south) / rectangle2.height; u = import__653.Math.clamp(u, 0, 1); v = import__653.Math.clamp(v, 0, 1); u = Math.floor(u * maxShort); v = Math.floor(v * maxShort); buffer[i] = zigZag(u - lastU); buffer[i + length2] = zigZag(v - lastV); lastU = u; lastV = v; } return buffer; } function createPolygon(rectangle2) { const cartographicPositions = [ import__653.Rectangle.northwest(rectangle2), import__653.Rectangle.southwest(rectangle2), import__653.Rectangle.southeast(rectangle2), import__653.Rectangle.northeast(rectangle2) ]; return { positions: encodePositions(rectangle2, cartographicPositions), indices: new Uint16Array([0, 1, 2, 0, 2, 3]), counts: new Uint32Array([4]), indexCounts: new Uint32Array([6]) }; } it(`renders a single polygon${webglMessage}`, function() { const rectangle2 = import__653.Rectangle.fromDegrees(-1, -1, 1, 1); const polygonOptions = createPolygon(rectangle2); const batchTable = new import__653.Cesium3DTileBatchTable(mockTileset, 1); batchTable.update(mockTileset, scene2.frameState); scene2.primitives.add(globePrimitive); const center = ellipsoid.cartographicToCartesian( import__653.Rectangle.center(rectangle2) ); polygons = scene2.primitives.add( new import__653.Vector3DTilePolygons( (0, import__653.combine)(polygonOptions, { minimumHeight: -1e4, maximumHeight: 1e4, center, rectangle: rectangle2, boundingVolume: new import__653.BoundingSphere(center, 1e4), batchTable, batchIds: new Uint32Array([0]), isCartographic: true }) ) ); return loadPolygons(polygons).then(function() { scene2.camera.setView({ destination: rectangle2 }); expect(scene2).toRender([255, 255, 255, 255]); batchTable.setColor(0, import__653.Color.BLUE); polygons.updateCommands(0, import__653.Color.BLUE); batchTable.update(mockTileset, scene2.frameState); expect(scene2).toRender([0, 0, 255, 255]); }); }); it(`renders multiple polygons${webglMessage}`, function() { const rectangle1 = import__653.Rectangle.fromDegrees(-1, -1, 1, 1); const rectangle2 = import__653.Rectangle.fromDegrees(1, -1, 2, 1); const cartographicPositions = [ import__653.Rectangle.northwest(rectangle1), import__653.Rectangle.southwest(rectangle1), import__653.Rectangle.southeast(rectangle1), import__653.Rectangle.northeast(rectangle1), import__653.Rectangle.northwest(rectangle2), import__653.Rectangle.southwest(rectangle2), import__653.Rectangle.southeast(rectangle2), import__653.Rectangle.northeast(rectangle2) ]; const rectangle3 = import__653.Rectangle.fromDegrees(-1, -1, 2, 1); const batchTable = new import__653.Cesium3DTileBatchTable(mockTileset, 2); batchTable.update(mockTileset, scene2.frameState); scene2.primitives.add(globePrimitive); const center = ellipsoid.cartographicToCartesian( import__653.Rectangle.center(rectangle3) ); polygons = scene2.primitives.add( new import__653.Vector3DTilePolygons({ positions: encodePositions(rectangle3, cartographicPositions), indices: new Uint16Array([0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7]), counts: new Uint32Array([4, 4]), indexCounts: new Uint32Array([6, 6]), minimumHeight: -1e4, maximumHeight: 1e4, center, rectangle: rectangle3, boundingVolume: new import__653.BoundingSphere(center, 1e4), batchTable, batchIds: new Uint32Array([0, 1]), isCartographic: true }) ); return loadPolygons(polygons).then(function() { scene2.camera.setView({ destination: rectangle1 }); expect(scene2).toRender([255, 255, 255, 255]); batchTable.setColor(0, import__653.Color.BLUE); polygons.updateCommands(0, import__653.Color.BLUE); batchTable.update(mockTileset, scene2.frameState); expect(scene2).toRender([0, 0, 255, 255]); scene2.camera.setView({ destination: rectangle2 }); expect(scene2).toRender([255, 255, 255, 255]); batchTable.setColor(1, import__653.Color.BLUE); polygons.updateCommands(1, import__653.Color.BLUE); batchTable.update(mockTileset, scene2.frameState); expect(scene2).toRender([0, 0, 255, 255]); }); }); it(`renders multiple polygons after re-batch${webglMessage}`, function() { const rectangle1 = import__653.Rectangle.fromDegrees(-1, -1, 1, 1); const rectangle2 = import__653.Rectangle.fromDegrees(1, -1, 2, 1); const cartographicPositions = [ import__653.Rectangle.northwest(rectangle1), import__653.Rectangle.southwest(rectangle1), import__653.Rectangle.southeast(rectangle1), import__653.Rectangle.northeast(rectangle1), import__653.Rectangle.northwest(rectangle2), import__653.Rectangle.southwest(rectangle2), import__653.Rectangle.southeast(rectangle2), import__653.Rectangle.northeast(rectangle2) ]; const rectangle3 = import__653.Rectangle.fromDegrees(-1, -1, 2, 1); const batchTable = new import__653.Cesium3DTileBatchTable(mockTileset, 2); batchTable.update(mockTileset, scene2.frameState); scene2.primitives.add(globePrimitive); const center = ellipsoid.cartographicToCartesian( import__653.Rectangle.center(rectangle3) ); polygons = scene2.primitives.add( new import__653.Vector3DTilePolygons({ positions: encodePositions(rectangle3, cartographicPositions), indices: new Uint16Array([0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7]), counts: new Uint32Array([4, 4]), indexCounts: new Uint32Array([6, 6]), minimumHeight: -1e4, maximumHeight: 1e4, center, rectangle: rectangle3, boundingVolume: new import__653.BoundingSphere(center, 1e4), batchTable, batchIds: new Uint32Array([0, 1]), isCartographic: true }) ); polygons.forceRebatch = true; return loadPolygons(polygons).then(function() { scene2.camera.setView({ destination: rectangle1 }); expect(scene2).toRender([255, 255, 255, 255]); batchTable.setColor(0, import__653.Color.BLUE); polygons.updateCommands(0, import__653.Color.BLUE); batchTable.update(mockTileset, scene2.frameState); expect(scene2).toRender([0, 0, 255, 255]); scene2.camera.setView({ destination: rectangle2 }); expect(scene2).toRender([255, 255, 255, 255]); batchTable.setColor(1, import__653.Color.BLUE); polygons.updateCommands(1, import__653.Color.BLUE); batchTable.update(mockTileset, scene2.frameState); expect(scene2).toRender([0, 0, 255, 255]); }); }); it(`renders multiple polygons with different minimum and maximum heights${webglMessage}`, function() { const rectangle1 = import__653.Rectangle.fromDegrees(-1, -1, 1, 1); const rectangle2 = import__653.Rectangle.fromDegrees(1, -1, 2, 1); const cartographicPositions = [ import__653.Rectangle.northwest(rectangle1), import__653.Rectangle.southwest(rectangle1), import__653.Rectangle.southeast(rectangle1), import__653.Rectangle.northeast(rectangle1), import__653.Rectangle.northwest(rectangle2), import__653.Rectangle.southwest(rectangle2), import__653.Rectangle.southeast(rectangle2), import__653.Rectangle.northeast(rectangle2) ]; const rectangle3 = import__653.Rectangle.fromDegrees(-1, -1, 2, 1); const batchTable = new import__653.Cesium3DTileBatchTable(mockTileset, 2); batchTable.update(mockTileset, scene2.frameState); scene2.primitives.add(globePrimitive); const center = ellipsoid.cartographicToCartesian( import__653.Rectangle.center(rectangle3) ); polygons = scene2.primitives.add( new import__653.Vector3DTilePolygons({ positions: encodePositions(rectangle3, cartographicPositions), indices: new Uint16Array([0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7]), counts: new Uint32Array([4, 4]), indexCounts: new Uint32Array([6, 6]), minimumHeight: -1e4, maximumHeight: 1e4, polygonMinimumHeights: new Float32Array([-1e4, 10]), polygonMaximumHeights: new Float32Array([1e4, 100]), center, rectangle: rectangle3, boundingVolume: new import__653.BoundingSphere(center, 1e4), batchTable, batchIds: new Uint32Array([0, 1]), isCartographic: true }) ); polygons.forceRebatch = true; return loadPolygons(polygons).then(function() { scene2.camera.setView({ destination: rectangle1 }); expect(scene2).toRender([255, 255, 255, 255]); batchTable.setColor(0, import__653.Color.BLUE); polygons.updateCommands(0, import__653.Color.BLUE); batchTable.update(mockTileset, scene2.frameState); expect(scene2).toRender([0, 0, 255, 255]); scene2.camera.setView({ destination: rectangle2 }); expect(scene2).toRender([255, 0, 0, 255]); }); }); it(`renders with inverted classification${webglMessage}`, function() { const rectangle2 = import__653.Rectangle.fromDegrees(-1, -1, 1, 1); const polygonOptions = createPolygon(rectangle2); const batchTable = new import__653.Cesium3DTileBatchTable(mockTileset, 1); batchTable.update(mockTileset, scene2.frameState); scene2.primitives.add(tilesetPrimitive); const center = ellipsoid.cartographicToCartesian( import__653.Rectangle.center(rectangle2) ); polygons = scene2.primitives.add( new import__653.Vector3DTilePolygons( (0, import__653.combine)(polygonOptions, { minimumHeight: -1e4, maximumHeight: 1e4, center, rectangle: rectangle2, boundingVolume: new import__653.BoundingSphere(center, 1e4), batchTable, batchIds: new Uint32Array([0]), isCartographic: true }) ) ); return loadPolygons(polygons).then(function() { scene2.camera.setView({ destination: import__653.Rectangle.fromDegrees(-2, -1, -1, 1) }); expect(scene2).toRender([255, 0, 0, 255]); scene2.invertClassification = true; scene2.invertClassificationColor = new import__653.Color(0.25, 0.25, 0.25, 1); expect(scene2).toRender([64, 0, 0, 255]); scene2.camera.setView({ destination: rectangle2 }); expect(scene2).toRender([255, 255, 255, 255]); scene2.invertClassification = false; }); }); it(`renders wireframe${webglMessage}`, function() { const rectangle2 = import__653.Rectangle.fromDegrees(-1, -1, 1, 1); const polygonOptions = createPolygon(rectangle2); const batchTable = new import__653.Cesium3DTileBatchTable(mockTileset, 1); batchTable.update(mockTileset, scene2.frameState); scene2.primitives.add(globePrimitive); const center = ellipsoid.cartographicToCartesian( import__653.Rectangle.center(rectangle2) ); polygons = scene2.primitives.add( new import__653.Vector3DTilePolygons( (0, import__653.combine)(polygonOptions, { minimumHeight: -1e4, maximumHeight: 1e4, center, rectangle: rectangle2, boundingVolume: new import__653.BoundingSphere(center, 1e4), batchTable, batchIds: new Uint32Array([0]), isCartographic: true }) ) ); polygons.debugWireframe = true; return loadPolygons(polygons).then(function() { scene2.camera.setView({ destination: rectangle2 }); expect(scene2).toRender([255, 255, 255, 255]); batchTable.setColor(0, import__653.Color.BLUE); polygons.updateCommands(0, import__653.Color.BLUE); batchTable.update(mockTileset, scene2.frameState); expect(scene2).toRender([0, 0, 255, 255]); }); }); it(`renders based on classificationType${webglMessage}`, function() { const rectangle2 = import__653.Rectangle.fromDegrees(-1, -1, 1, 1); const polygonOptions = createPolygon(rectangle2); const batchTable = new import__653.Cesium3DTileBatchTable(mockTileset, 1); batchTable.update(mockTileset, scene2.frameState); scene2.primitives.add(globePrimitive); scene2.primitives.add(tilesetPrimitive); const center = ellipsoid.cartographicToCartesian( import__653.Rectangle.center(rectangle2) ); polygons = scene2.primitives.add( new import__653.Vector3DTilePolygons( (0, import__653.combine)(polygonOptions, { minimumHeight: -1e4, maximumHeight: 1e4, center, rectangle: rectangle2, boundingVolume: new import__653.BoundingSphere(center, 1e4), batchTable, batchIds: new Uint32Array([0]), isCartographic: true }) ) ); return loadPolygons(polygons).then(function() { scene2.camera.setView({ destination: rectangle2 }); polygons.classificationType = import__653.ClassificationType.CESIUM_3D_TILE; globePrimitive.show = false; tilesetPrimitive.show = true; expect(scene2).toRender([255, 255, 255, 255]); globePrimitive.show = true; tilesetPrimitive.show = false; expect(scene2).toRender([255, 0, 0, 255]); polygons.classificationType = import__653.ClassificationType.TERRAIN; globePrimitive.show = false; tilesetPrimitive.show = true; expect(scene2).toRender([255, 0, 0, 255]); globePrimitive.show = true; tilesetPrimitive.show = false; expect(scene2).toRender([255, 255, 255, 255]); polygons.classificationType = import__653.ClassificationType.BOTH; globePrimitive.show = false; tilesetPrimitive.show = true; expect(scene2).toRender([255, 255, 255, 255]); globePrimitive.show = true; tilesetPrimitive.show = false; expect(scene2).toRender([255, 255, 255, 255]); globePrimitive.show = true; tilesetPrimitive.show = true; }); }); it(`picks polygons${webglMessage}`, function() { const rectangle2 = import__653.Rectangle.fromDegrees(-1, -1, 1, 1); const polygonOptions = createPolygon(rectangle2); const batchTable = new import__653.Cesium3DTileBatchTable(mockTileset, 1); scene2.primitives.add(globePrimitive); const center = ellipsoid.cartographicToCartesian( import__653.Rectangle.center(rectangle2) ); polygons = scene2.primitives.add( new import__653.Vector3DTilePolygons( (0, import__653.combine)(polygonOptions, { minimumHeight: -1e4, maximumHeight: 1e4, center, rectangle: rectangle2, boundingVolume: new import__653.BoundingSphere(center, 1e4), batchTable, batchIds: new Uint32Array([0]), isCartographic: true }) ) ); polygons.debugWireframe = true; return loadPolygons(polygons).then(function() { scene2.camera.setView({ destination: rectangle2 }); const features = []; polygons.createFeatures(mockTileset, features); const getFeature = mockTileset.getFeature; mockTileset.getFeature = function(index) { return features[index]; }; scene2.frameState.passes.pick = true; batchTable.update(mockTileset, scene2.frameState); expect(scene2).toPickAndCall(function(result) { expect(result).toBe(features[0]); }); mockTileset.getFeature = getFeature; }); }); it(`isDestroyed${webglMessage}`, function() { polygons = new import__653.Vector3DTilePolygons({}); expect(polygons.isDestroyed()).toEqual(false); polygons.destroy(); expect(polygons.isDestroyed()).toEqual(true); }); } }, "WebGL" ); // packages/engine/Specs/Scene/Vector3DTilePolylinesSpec.js var import__654 = __toESM(require_Cesium(), 1); var import__655 = __toESM(require_Cesium(), 1); describe( "Scene/Vector3DTilePolylines", function() { let scene2; let rectangle; let polylines; const ellipsoid = import__654.Ellipsoid.WGS84; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); const mockTileset = { _statistics: { texturesByteLength: 0 }, tileset: { _statistics: { batchTableByteLength: 0 }, colorBlendMode: import__654.ColorBlendMode.HIGHLIGHT }, getFeature: function(id) { return { batchId: id }; } }; beforeEach(function() { rectangle = import__654.Rectangle.fromDegrees(-40, -40, 40, 40); }); afterEach(function() { scene2.primitives.removeAll(); polylines = polylines && !polylines.isDestroyed() && polylines.destroy(); }); function loadPolylines(polylines2) { return pollToPromise_default(function() { polylines2.update(scene2.frameState); scene2.frameState.commandList.length = 0; return polylines2.ready; }); } function zigZag(value) { return (value << 1 ^ value >> 15) & 65535; } const maxShort = 32767; function encodePositions(rectangle2, minimumHeight, maximumHeight, positions) { const length2 = positions.length; const buffer = new Uint16Array(length2 * 3); let lastU = 0; let lastV = 0; let lastH = 0; for (let i = 0; i < length2; ++i) { const position = positions[i]; let u = (position.longitude - rectangle2.west) / rectangle2.width; let v = (position.latitude - rectangle2.south) / rectangle2.height; let h = (position.height - minimumHeight) / (maximumHeight - minimumHeight); u = import__655.Math.clamp(u, 0, 1); v = import__655.Math.clamp(v, 0, 1); h = import__655.Math.clamp(h, 0, 1); u = Math.floor(u * maxShort); v = Math.floor(v * maxShort); h = Math.floor(h * maxShort); buffer[i] = zigZag(u - lastU); buffer[i + length2] = zigZag(v - lastV); buffer[i + length2 * 2] = zigZag(h - lastH); lastU = u; lastV = v; lastH = h; } return buffer; } it("renders a polyline", function() { const minHeight = 0; const maxHeight = 5; const cartoPositions = [ import__654.Cartographic.fromDegrees(0, 0, 1), import__654.Cartographic.fromDegrees(1, 0, 2) ]; const positions = encodePositions( rectangle, minHeight, maxHeight, cartoPositions ); const batchTable = new import__654.Cesium3DTileBatchTable(mockTileset, 1); batchTable.update(mockTileset, scene2.frameState); const center = ellipsoid.cartographicToCartesian( import__654.Rectangle.center(rectangle) ); polylines = scene2.primitives.add( new import__654.Vector3DTilePolylines({ positions, widths: new Uint16Array([10]), counts: new Uint32Array([2]), batchIds: new Uint16Array([0]), rectangle, minimumHeight: minHeight, maximumHeight: maxHeight, center, boundingVolume: new import__654.BoundingSphere(center, 1e6), batchTable, keepDecodedPositions: false }) ); return loadPolylines(polylines).then(function() { scene2.camera.lookAt( import__654.Cartesian3.fromDegrees(0.5, 0, 1.5), new import__654.Cartesian3(0, 0, 1) ); expect(scene2).toRender([255, 255, 255, 255]); }); }); it("renders multiple polylines", function() { const minHeight = 0; const maxHeight = 100; const cartoPositions = [ import__654.Cartographic.fromDegrees(1, 0, 1), import__654.Cartographic.fromDegrees(2, 0, 2), import__654.Cartographic.fromDegrees(-6, 0, 12), import__654.Cartographic.fromDegrees(-5, 0, 15), import__654.Cartographic.fromDegrees(0, 10, 0), import__654.Cartographic.fromDegrees(0, 5, 5), import__654.Cartographic.fromDegrees(0, 0, 10), import__654.Cartographic.fromDegrees(0, -5, 15) ]; const positions = encodePositions( rectangle, minHeight, maxHeight, cartoPositions ); const batchTable = new import__654.Cesium3DTileBatchTable(mockTileset, 1); batchTable.update(mockTileset, scene2.frameState); const center = ellipsoid.cartographicToCartesian( import__654.Rectangle.center(rectangle) ); polylines = scene2.primitives.add( new import__654.Vector3DTilePolylines({ positions, widths: new Uint16Array([10, 10, 10]), counts: new Uint32Array([2, 2, 4]), batchIds: new Uint16Array([0, 1, 2]), rectangle, minimumHeight: minHeight, maximumHeight: maxHeight, center, boundingVolume: new import__654.BoundingSphere(center, 1e6), batchTable, keepDecodedPositions: false }) ); return loadPolylines(polylines).then(function() { for (let i = 0; i < cartoPositions.length; i += 2) { const p1 = cartoPositions[i]; const p2 = cartoPositions[i + 1]; const longitude = import__655.Math.lerp(p1.longitude, p2.longitude, 0.5); const latitude = import__655.Math.lerp(p1.latitude, p2.latitude, 0.5); const height = import__655.Math.lerp(p1.height, p2.height, 0.5); const target = import__654.Cartesian3.fromRadians(longitude, latitude, height); scene2.camera.lookAt(target, new import__654.Cartesian3(0, 0, 1)); expect(scene2).toRender([255, 255, 255, 255]); } }); }); it("picks a polyline", function() { const minHeight = 0; const maxHeight = 5; const cartoPositions = [ import__654.Cartographic.fromDegrees(0, 0, 1), import__654.Cartographic.fromDegrees(1, 0, 2) ]; const positions = encodePositions( rectangle, minHeight, maxHeight, cartoPositions ); const batchTable = new import__654.Cesium3DTileBatchTable(mockTileset, 1); const center = ellipsoid.cartographicToCartesian( import__654.Rectangle.center(rectangle) ); polylines = scene2.primitives.add( new import__654.Vector3DTilePolylines({ positions, widths: new Uint16Array([10]), counts: new Uint32Array([2]), batchIds: new Uint16Array([0]), rectangle, minimumHeight: minHeight, maximumHeight: maxHeight, center, boundingVolume: new import__654.BoundingSphere(center, 1e6), batchTable, keepDecodedPositions: false }) ); return loadPolylines(polylines).then(function() { scene2.camera.lookAt( import__654.Cartesian3.fromDegrees(0.5, 0, 1.5), new import__654.Cartesian3(0, 0, 1) ); const features = []; polylines.createFeatures(mockTileset, features); const getFeature = mockTileset.getFeature; mockTileset.getFeature = function(index) { return features[index]; }; scene2.frameState.passes.pick = true; batchTable.update(mockTileset, scene2.frameState); expect(scene2).toPickAndCall(function(result) { expect(result).toBe(features[0]); }); mockTileset.getFeature = getFeature; }); }); it("isDestroyed", function() { polylines = new import__654.Vector3DTilePolylines({}); expect(polylines.isDestroyed()).toEqual(false); polylines.destroy(); expect(polylines.isDestroyed()).toEqual(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/VertexAttributeSemanticSpec.js var import__656 = __toESM(require_Cesium(), 1); describe("Scene/VertexAttributeSemantic", function() { it("hasSetIndex", function() { const semantics = [ import__656.VertexAttributeSemantic.POSITION, import__656.VertexAttributeSemantic.NORMAL, import__656.VertexAttributeSemantic.TANGENT, import__656.VertexAttributeSemantic.TEXCOORD, import__656.VertexAttributeSemantic.COLOR, import__656.VertexAttributeSemantic.JOINTS, import__656.VertexAttributeSemantic.WEIGHTS, import__656.VertexAttributeSemantic.FEATURE_ID ]; const hasSetIndex = [false, false, false, true, true, true, true, true]; const semanticsLength = semantics.length; for (let i = 0; i < semanticsLength; ++i) { expect(import__656.VertexAttributeSemantic.hasSetIndex(semantics[i])).toBe( hasSetIndex[i] ); } }); it("hasSetIndex throws if semantic is undefined", function() { expect(function() { import__656.VertexAttributeSemantic.hasSetIndex(void 0); }).toThrowDeveloperError(); }); it("hasSetIndex throws if semantic is not a valid value", function() { expect(function() { import__656.VertexAttributeSemantic.hasSetIndex("OTHER"); }).toThrowDeveloperError(); }); it("fromGltfSemantic", function() { const gltfSemantics = [ "POSITION", "NORMAL", "TANGENT", "TEXCOORD_0", "TEXCOORD_1", "COLOR_0", "COLOR_1", "JOINTS_0", "JOINTS_1", "WEIGHTS_0", "WEIGHTS_1", "_FEATURE_ID_0", "_FEATURE_ID_1", "_OTHER" ]; const expectedSemantics = [ import__656.VertexAttributeSemantic.POSITION, import__656.VertexAttributeSemantic.NORMAL, import__656.VertexAttributeSemantic.TANGENT, import__656.VertexAttributeSemantic.TEXCOORD, import__656.VertexAttributeSemantic.TEXCOORD, import__656.VertexAttributeSemantic.COLOR, import__656.VertexAttributeSemantic.COLOR, import__656.VertexAttributeSemantic.JOINTS, import__656.VertexAttributeSemantic.JOINTS, import__656.VertexAttributeSemantic.WEIGHTS, import__656.VertexAttributeSemantic.WEIGHTS, import__656.VertexAttributeSemantic.FEATURE_ID, import__656.VertexAttributeSemantic.FEATURE_ID, void 0 ]; const semanticsLength = gltfSemantics.length; for (let i = 0; i < semanticsLength; ++i) { expect(import__656.VertexAttributeSemantic.fromGltfSemantic(gltfSemantics[i])).toBe( expectedSemantics[i] ); } }); it("fromGltfSemantic throws if gltfSemantic is undefined", function() { expect(function() { import__656.VertexAttributeSemantic.fromGltfSemantic(void 0); }).toThrowDeveloperError(); }); it("fromPntsSemantic", function() { const pntsSemantics = [ "POSITION", "POSITION_QUANTIZED", "RGBA", "RGB", "RGB565", "NORMAL", "NORMAL_OCT16P", "BATCH_ID" ]; const expectedSemantics = [ import__656.VertexAttributeSemantic.POSITION, import__656.VertexAttributeSemantic.POSITION, import__656.VertexAttributeSemantic.COLOR, import__656.VertexAttributeSemantic.COLOR, import__656.VertexAttributeSemantic.COLOR, import__656.VertexAttributeSemantic.NORMAL, import__656.VertexAttributeSemantic.NORMAL, import__656.VertexAttributeSemantic.FEATURE_ID ]; const semanticsLength = pntsSemantics.length; for (let i = 0; i < semanticsLength; ++i) { expect(import__656.VertexAttributeSemantic.fromPntsSemantic(pntsSemantics[i])).toBe( expectedSemantics[i] ); } }); it("fromPntsSemantic throws if pntsSemantic is undefined", function() { expect(function() { import__656.VertexAttributeSemantic.fromPntsSemantic(void 0); }).toThrowDeveloperError(); }); it("fromPntsSemantic throws if pntsSemantic is not a valid value", function() { expect(function() { import__656.VertexAttributeSemantic.fromPntsSemantic("OTHER"); }).toThrowDeveloperError(); }); it("getGlslType", function() { const semantics = [ import__656.VertexAttributeSemantic.POSITION, import__656.VertexAttributeSemantic.NORMAL, import__656.VertexAttributeSemantic.TANGENT, import__656.VertexAttributeSemantic.TEXCOORD, import__656.VertexAttributeSemantic.COLOR, import__656.VertexAttributeSemantic.JOINTS, import__656.VertexAttributeSemantic.WEIGHTS, import__656.VertexAttributeSemantic.FEATURE_ID ]; const expectedShaderTypes = [ "vec3", "vec3", "vec3", "vec2", "vec4", "ivec4", "vec4", "int" ]; const semanticsLength = semantics.length; for (let i = 0; i < semanticsLength; ++i) { expect(import__656.VertexAttributeSemantic.getGlslType(semantics[i])).toBe( expectedShaderTypes[i] ); } }); it("getGlslType throws if semantic is undefined", function() { expect(function() { import__656.VertexAttributeSemantic.getGlslType(void 0); }).toThrowDeveloperError(); }); it("getGlslType throws if semantic is not a valid value", function() { expect(function() { import__656.VertexAttributeSemantic.getGlslType("OTHER"); }).toThrowDeveloperError(); }); it("getVariableName", function() { const semantics = [ import__656.VertexAttributeSemantic.POSITION, import__656.VertexAttributeSemantic.NORMAL, import__656.VertexAttributeSemantic.TANGENT, import__656.VertexAttributeSemantic.TEXCOORD, import__656.VertexAttributeSemantic.COLOR, import__656.VertexAttributeSemantic.JOINTS, import__656.VertexAttributeSemantic.WEIGHTS, import__656.VertexAttributeSemantic.FEATURE_ID ]; const expectedVariableName = [ "positionMC", "normalMC", "tangentMC", "texCoord", "color", "joints", "weights", "featureId" ]; const semanticsLength = semantics.length; for (let i = 0; i < semanticsLength; ++i) { expect(import__656.VertexAttributeSemantic.getVariableName(semantics[i])).toBe( expectedVariableName[i] ); } }); it("getVariableName works with set index", function() { expect( import__656.VertexAttributeSemantic.getVariableName( import__656.VertexAttributeSemantic.FEATURE_ID, 0 ) ).toBe("featureId_0"); }); it("getVariableName throws if semantic is undefined", function() { expect(function() { import__656.VertexAttributeSemantic.getVariableName(void 0); }).toThrowDeveloperError(); }); it("getVariableName throws if semantic is not a valid value", function() { expect(function() { import__656.VertexAttributeSemantic.getVariableName("OTHER"); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/ViewportQuadSpec.js var import__657 = __toESM(require_Cesium(), 1); describe( "Scene/ViewportQuad", function() { let scene2; let viewportQuad; let testImage; beforeAll(function() { scene2 = createScene_default(); return import__657.Resource.fetchImage("./Data/Images/Red16x16.png").then(function(image) { testImage = image; }); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { viewportQuad = new import__657.ViewportQuad(); viewportQuad.rectangle = new import__657.BoundingRectangle(0, 0, 2, 2); }); afterEach(function() { scene2.primitives.removeAll(); }); it("constructs with a rectangle", function() { const rectangle = new import__657.BoundingRectangle(1, 2, 3, 4); const quad = new import__657.ViewportQuad(rectangle); expect(quad.rectangle).toEqual(rectangle); }); it("constructs with a material", function() { const material = import__657.Material.fromType(import__657.Material.StripeType); const quad = new import__657.ViewportQuad(void 0, material); expect(quad.material.type).toEqual(material.type); }); it("gets the default color", function() { expect(viewportQuad.material.uniforms.color).toEqual( new import__657.Color(1, 1, 1, 1) ); }); it("throws when rendered without a rectangle", function() { viewportQuad.rectangle = void 0; scene2.primitives.add(viewportQuad); expect(function() { scene2.renderForSpecs(); }).toThrowDeveloperError(); }); it("throws when rendered without a material", function() { viewportQuad.material = void 0; scene2.primitives.add(viewportQuad); expect(function() { scene2.renderForSpecs(); }).toThrowDeveloperError(); }); it("does not render when show is false", function() { viewportQuad.show = false; expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(viewportQuad); expect(scene2).toRender([0, 0, 0, 255]); }); it("renders material", function() { expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(viewportQuad); expect(scene2).notToRender([0, 0, 0, 255]); }); it("renders user created texture", function() { const texture = new import__657.Texture({ context: scene2.context, source: testImage }); viewportQuad.material = import__657.Material.fromType(import__657.Material.ImageType); viewportQuad.material.uniforms.image = texture; expect(scene2).toRender([0, 0, 0, 255]); scene2.primitives.add(viewportQuad); expect(scene2).toRender([255, 0, 0, 255]); }); it("updates rectangle", function() { const otherRectangle = new import__657.BoundingRectangle(0, 0, 4, 4); scene2.primitives.add(viewportQuad); scene2.renderForSpecs(); viewportQuad.rectangle = otherRectangle; scene2.renderForSpecs(); expect(scene2.frameState.commandList[0].renderState.viewport).toEqual( otherRectangle ); }); it("isDestroyed", function() { const boundRectangle = new import__657.BoundingRectangle(0, 0, 10, 10); const vq = new import__657.ViewportQuad(boundRectangle); expect(vq.isDestroyed()).toEqual(false); vq.destroy(); expect(vq.isDestroyed()).toEqual(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/VoxelBoxShapeSpec.js var import__658 = __toESM(require_Cesium(), 1); describe("Scene/VoxelBoxShape", function() { it("conforms to VoxelShape interface", function() { expect(import__658.VoxelBoxShape).toConformToInterface(import__658.VoxelShape); }); it("constructs", function() { const shape = new import__658.VoxelBoxShape(); expect(shape.shapeTransform).toEqual(new import__658.Matrix4()); }); it("update works with model matrix", function() { const shape = new import__658.VoxelBoxShape(); const translation = new import__658.Cartesian3(1, 2, 3); const scale = new import__658.Cartesian3(2, 3, 4); const angle = import__658.Math.PI_OVER_FOUR; const rotation = import__658.Quaternion.fromAxisAngle(import__658.Cartesian3.UNIT_Z, angle); const modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const minBounds = import__658.VoxelBoxShape.DefaultMinBounds; const maxBounds = import__658.VoxelBoxShape.DefaultMaxBounds; const expectedOrientedBoundingBox = new import__658.OrientedBoundingBox( translation, import__658.Matrix3.fromColumnMajorArray([ scale.x * Math.cos(angle), scale.x * Math.sin(angle), 0, scale.y * Math.cos(angle + import__658.Math.PI_OVER_TWO), scale.y * Math.sin(angle + import__658.Math.PI_OVER_TWO), 0, 0, 0, scale.z ]) ); const expectedBoundingSphere = new import__658.BoundingSphere( translation, import__658.Cartesian3.magnitude(scale) ); const visible = shape.update(modelMatrix, minBounds, maxBounds); expect(shape.orientedBoundingBox.center).toEqual( expectedOrientedBoundingBox.center ); expect(shape.orientedBoundingBox.halfAxes).toEqualEpsilon( expectedOrientedBoundingBox.halfAxes, import__658.Math.EPSILON12 ); expect(shape.boundingSphere).toEqual(expectedBoundingSphere); expect(shape.boundTransform).toEqual(modelMatrix); expect(shape.shapeTransform).toEqual(modelMatrix); expect(visible).toBeTrue(); }); it("update works with non-default minimum and maximum bounds", function() { const shape = new import__658.VoxelBoxShape(); const translation = new import__658.Cartesian3(1, 2, 3); const scale = new import__658.Cartesian3(2, 3, 4); const rotation = import__658.Quaternion.IDENTITY; const modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale, new import__658.Matrix4() ); const minBounds = new import__658.Cartesian3(-0.75, -0.75, -0.75); const maxBounds = new import__658.Cartesian3(-0.25, -0.25, -0.25); const visible = shape.update( modelMatrix, minBounds, maxBounds, minBounds, maxBounds ); const expectedTranslation = new import__658.Cartesian3(0, 0.5, 1); const expectedScale = new import__658.Cartesian3(0.5, 0.75, 1); const expectedRotation = rotation; const expectedModelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( expectedTranslation, expectedRotation, expectedScale, new import__658.Matrix4() ); const expectedOrientedBoundingBox = new import__658.OrientedBoundingBox( expectedTranslation, import__658.Matrix3.fromScale(expectedScale) ); const expectedBoundingSphere = new import__658.BoundingSphere( expectedTranslation, import__658.Cartesian3.magnitude(expectedScale) ); expect(shape.orientedBoundingBox).toEqual(expectedOrientedBoundingBox); expect(shape.boundingSphere).toEqual(expectedBoundingSphere); expect(shape.boundTransform).toEqual(expectedModelMatrix); expect(shape.shapeTransform).toEqual(modelMatrix); expect(visible).toBeTrue(); }); xit("update is visible with zero scale for one component", function() { const shape = new import__658.VoxelBoxShape(); const minBounds = import__658.VoxelBoxShape.DefaultMinBounds; const maxBounds = import__658.VoxelBoxShape.DefaultMaxBounds; const translation = new import__658.Cartesian3(1, 2, 3); const rotation = import__658.Quaternion.IDENTITY; let scale; let modelMatrix; let visible; scale = new import__658.Cartesian3(0, 2, 2); modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); visible = shape.update(modelMatrix, minBounds, maxBounds); expect(visible).toBeTrue(); scale = import__658.Cartesian3.fromElements(2, 0, 2, scale); modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); visible = shape.update(modelMatrix, minBounds, maxBounds); expect(visible).toBeTrue(); scale = import__658.Cartesian3.fromElements(2, 2, 0, scale); modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); visible = shape.update(modelMatrix, minBounds, maxBounds); expect(visible).toBeTrue(); }); it("update is invisible with zero scale for two or more components", function() { const shape = new import__658.VoxelBoxShape(); const minBounds = import__658.VoxelBoxShape.DefaultMinBounds; const maxBounds = import__658.VoxelBoxShape.DefaultMaxBounds; const translation = new import__658.Cartesian3(1, 2, 3); const rotation = import__658.Quaternion.IDENTITY; let scale; let modelMatrix; let visible; scale = new import__658.Cartesian3(0, 0, 2); modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); visible = shape.update(modelMatrix, minBounds, maxBounds); expect(visible).toBeFalse(); scale = import__658.Cartesian3.fromElements(0, 2, 0, scale); modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); visible = shape.update(modelMatrix, minBounds, maxBounds); expect(visible).toBeFalse(); scale = import__658.Cartesian3.fromElements(2, 0, 0, scale); modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); visible = shape.update(modelMatrix, minBounds, maxBounds); expect(visible).toBeFalse(); scale = import__658.Cartesian3.fromElements(0, 0, 0, scale); modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); visible = shape.update(modelMatrix, minBounds, maxBounds); expect(visible).toBeFalse(); }); it("update is visible with zero bounds for one component", function() { const shape = new import__658.VoxelBoxShape(); const translation = import__658.Cartesian3.ZERO; const rotation = import__658.Quaternion.IDENTITY; const scale = import__658.Cartesian3.ONE; const modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); let minBounds; let maxBounds; let expectedScale; let actualScale; let actualTranslation; let visible; const clipMinBounds = new import__658.Cartesian3(-1, -1, -1); const clipMaxBounds = new import__658.Cartesian3(1, 1, 1); minBounds = new import__658.Cartesian3(0, -1, -1); maxBounds = new import__658.Cartesian3(0, 1, 1); expectedScale = new import__658.Cartesian3(0, 1, 1); visible = shape.update( modelMatrix, minBounds, maxBounds, clipMinBounds, clipMaxBounds ); actualScale = import__658.Matrix4.getScale(shape.boundTransform, new import__658.Cartesian3()); actualTranslation = import__658.Matrix4.getTranslation( shape.shapeTransform, new import__658.Cartesian3() ); expect(visible).toBeTrue(); expect(actualScale).toEqual(expectedScale); expect(actualTranslation).toEqual(translation); minBounds = new import__658.Cartesian3(-1, 0, -1); maxBounds = new import__658.Cartesian3(1, 0, 1); expectedScale = new import__658.Cartesian3(1, 0, 1); visible = shape.update( modelMatrix, minBounds, maxBounds, clipMinBounds, clipMaxBounds ); actualScale = import__658.Matrix4.getScale(shape.boundTransform, new import__658.Cartesian3()); actualTranslation = import__658.Matrix4.getTranslation( shape.shapeTransform, new import__658.Cartesian3() ); expect(visible).toBeTrue(); expect(actualScale).toEqual(expectedScale); expect(actualTranslation).toEqual(translation); minBounds = new import__658.Cartesian3(-1, -1, 0); maxBounds = new import__658.Cartesian3(1, 1, 0); expectedScale = new import__658.Cartesian3(1, 1, 0); visible = shape.update( modelMatrix, minBounds, maxBounds, clipMinBounds, clipMaxBounds ); actualScale = import__658.Matrix4.getScale(shape.boundTransform, new import__658.Cartesian3()); actualTranslation = import__658.Matrix4.getTranslation( shape.shapeTransform, new import__658.Cartesian3() ); expect(visible).toBeTrue(); expect(actualScale).toEqual(expectedScale); expect(actualTranslation).toEqual(translation); }); it("update is invisible with zero bounds for two or more components", function() { const shape = new import__658.VoxelBoxShape(); const translation = import__658.Cartesian3.ZERO; const rotation = import__658.Quaternion.IDENTITY; const scale = import__658.Cartesian3.ONE; const modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); let minBounds; let maxBounds; let visible; minBounds = new import__658.Cartesian3(0, 0, -1); maxBounds = new import__658.Cartesian3(0, 0, 1); visible = shape.update(modelMatrix, minBounds, maxBounds); expect(visible).toBeFalse(); minBounds = new import__658.Cartesian3(0, -1, 0); maxBounds = new import__658.Cartesian3(0, 1, 0); visible = shape.update( modelMatrix, minBounds, maxBounds, minBounds, maxBounds ); expect(visible).toBeFalse(); minBounds = new import__658.Cartesian3(-1, 0, 0); maxBounds = new import__658.Cartesian3(1, 0, 0); visible = shape.update(modelMatrix, minBounds, maxBounds); expect(visible).toBeFalse(); minBounds = new import__658.Cartesian3(0, 0, 0); maxBounds = new import__658.Cartesian3(0, 0, 0); visible = shape.update(modelMatrix, minBounds, maxBounds); expect(visible).toBeFalse(); }); it("update is invisible when minimum bounds exceed maximum bounds", function() { const shape = new import__658.VoxelBoxShape(); const translation = import__658.Cartesian3.ZERO; const rotation = import__658.Quaternion.IDENTITY; const scale = import__658.Cartesian3.ONE; const modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); let visible; let minBounds; let maxBounds; const clipMinBounds = new import__658.Cartesian3(-1, -1, -1); const clipMaxBounds = new import__658.Cartesian3(2, 2, 2); minBounds = new import__658.Cartesian3(1, -1, -1); maxBounds = new import__658.Cartesian3(0.9, 1, 1); visible = shape.update( modelMatrix, minBounds, maxBounds, clipMinBounds, clipMaxBounds ); expect(visible).toBeFalse(); minBounds = new import__658.Cartesian3(-1, 1, -1); maxBounds = new import__658.Cartesian3(1, 0.9, 1); visible = shape.update( modelMatrix, minBounds, maxBounds, clipMinBounds, clipMaxBounds ); expect(visible).toBeFalse(); minBounds = new import__658.Cartesian3(-1, -1, 1); maxBounds = new import__658.Cartesian3(1, 1, 0.9); visible = shape.update( modelMatrix, minBounds, maxBounds, clipMinBounds, clipMaxBounds ); expect(visible).toBeFalse(); }); it("update throws with no model matrix parameter", function() { const shape = new import__658.VoxelBoxShape(); const minBounds = import__658.VoxelBoxShape.DefaultMinBounds; const maxBounds = import__658.VoxelBoxShape.DefaultMaxBounds; expect(function() { return shape.update(void 0, minBounds, maxBounds); }).toThrowDeveloperError(); }); it("update throws with no minimum bounds parameter", function() { const shape = new import__658.VoxelBoxShape(); const translation = import__658.Cartesian3.ZERO; const rotation = import__658.Quaternion.IDENTITY; const scale = import__658.Cartesian3.ONE; const modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const maxBounds = import__658.VoxelBoxShape.DefaultMaxBounds; expect(function() { return shape.update(modelMatrix, void 0, maxBounds); }).toThrowDeveloperError(); }); it("update throws with no maximum bounds parameter", function() { const shape = new import__658.VoxelBoxShape(); const translation = import__658.Cartesian3.ZERO; const rotation = import__658.Quaternion.IDENTITY; const scale = import__658.Cartesian3.ONE; const modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const minBounds = import__658.VoxelBoxShape.DefaultMinBounds; expect(function() { return shape.update(modelMatrix, minBounds, void 0); }).toThrowDeveloperError(); }); it("computeOrientedBoundingBoxForTile works for root tile", function() { const shape = new import__658.VoxelBoxShape(); const translation = import__658.Cartesian3.ZERO; const rotation = import__658.Quaternion.IDENTITY; const scale = import__658.Cartesian3.ONE; const modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const minBounds = import__658.VoxelBoxShape.DefaultMinBounds; const maxBounds = import__658.VoxelBoxShape.DefaultMaxBounds; shape.update(modelMatrix, minBounds, maxBounds); const tileLevel = 0; const tileX = 0; const tileY = 0; const tileZ = 0; const orientedBoundingBox = shape.computeOrientedBoundingBoxForTile( tileLevel, tileX, tileY, tileZ, new import__658.OrientedBoundingBox() ); const expectedOrientedBoundingBox = shape.orientedBoundingBox; expect(orientedBoundingBox).toEqual(expectedOrientedBoundingBox); }); it("computeOrientedBoundingBoxForTile works for children of root tile", function() { const shape = new import__658.VoxelBoxShape(); const translation = import__658.Cartesian3.ZERO; const rotation = import__658.Quaternion.IDENTITY; const scale = import__658.Cartesian3.ONE; const modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const minBounds = import__658.VoxelBoxShape.DefaultMinBounds; const maxBounds = import__658.VoxelBoxShape.DefaultMaxBounds; shape.update(modelMatrix, minBounds, maxBounds); const expectedScale = new import__658.Cartesian3(0.5, 0.5, 0.5); let expectedTranslation; const tileLevel = 1; let tileX; let tileY; let tileZ; let orientedBoundingBox; tileX = 0; tileY = 0; tileZ = 0; orientedBoundingBox = shape.computeOrientedBoundingBoxForTile( tileLevel, tileX, tileY, tileZ, new import__658.OrientedBoundingBox() ); expectedTranslation = new import__658.Cartesian3(-0.5, -0.5, -0.5); expect(orientedBoundingBox).toEqual( new import__658.OrientedBoundingBox( expectedTranslation, import__658.Matrix3.fromScale(expectedScale, new import__658.Matrix3()) ) ); tileX = 1; tileY = 0; tileZ = 0; orientedBoundingBox = shape.computeOrientedBoundingBoxForTile( tileLevel, tileX, tileY, tileZ, new import__658.OrientedBoundingBox() ); expectedTranslation = new import__658.Cartesian3(0.5, -0.5, -0.5); expect(orientedBoundingBox).toEqual( new import__658.OrientedBoundingBox( expectedTranslation, import__658.Matrix3.fromScale(expectedScale, new import__658.Matrix3()) ) ); tileX = 0; tileY = 1; tileZ = 0; orientedBoundingBox = shape.computeOrientedBoundingBoxForTile( tileLevel, tileX, tileY, tileZ, new import__658.OrientedBoundingBox() ); expectedTranslation = new import__658.Cartesian3(-0.5, 0.5, -0.5); expect(orientedBoundingBox).toEqual( new import__658.OrientedBoundingBox( expectedTranslation, import__658.Matrix3.fromScale(expectedScale, new import__658.Matrix3()) ) ); tileX = 0; tileY = 0; tileZ = 1; orientedBoundingBox = shape.computeOrientedBoundingBoxForTile( tileLevel, tileX, tileY, tileZ, new import__658.OrientedBoundingBox() ); expectedTranslation = new import__658.Cartesian3(-0.5, -0.5, 0.5); expect(orientedBoundingBox).toEqual( new import__658.OrientedBoundingBox( expectedTranslation, import__658.Matrix3.fromScale(expectedScale, new import__658.Matrix3()) ) ); tileX = 1; tileY = 1; tileZ = 0; orientedBoundingBox = shape.computeOrientedBoundingBoxForTile( tileLevel, tileX, tileY, tileZ, new import__658.OrientedBoundingBox() ); expectedTranslation = new import__658.Cartesian3(0.5, 0.5, -0.5); expect(orientedBoundingBox).toEqual( new import__658.OrientedBoundingBox( expectedTranslation, import__658.Matrix3.fromScale(expectedScale, new import__658.Matrix3()) ) ); tileX = 1; tileY = 0; tileZ = 1; orientedBoundingBox = shape.computeOrientedBoundingBoxForTile( tileLevel, tileX, tileY, tileZ, new import__658.OrientedBoundingBox() ); expectedTranslation = new import__658.Cartesian3(0.5, -0.5, 0.5); expect(orientedBoundingBox).toEqual( new import__658.OrientedBoundingBox( expectedTranslation, import__658.Matrix3.fromScale(expectedScale, new import__658.Matrix3()) ) ); tileX = 1; tileY = 1; tileZ = 1; orientedBoundingBox = shape.computeOrientedBoundingBoxForTile( tileLevel, tileX, tileY, tileZ, new import__658.OrientedBoundingBox() ); expectedTranslation = new import__658.Cartesian3(0.5, 0.5, 0.5); expect(orientedBoundingBox).toEqual( new import__658.OrientedBoundingBox( expectedTranslation, import__658.Matrix3.fromScale(expectedScale, new import__658.Matrix3()) ) ); }); it("computeOrientedBoundingBoxForTile throws with no tile coordinates parameter", function() { const shape = new import__658.VoxelBoxShape(); const translation = import__658.Cartesian3.ZERO; const rotation = import__658.Quaternion.IDENTITY; const scale = import__658.Cartesian3.ONE; const modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const minBounds = import__658.VoxelBoxShape.DefaultMinBounds; const maxBounds = import__658.VoxelBoxShape.DefaultMaxBounds; shape.update(modelMatrix, minBounds, maxBounds); const tileLevel = 0; const tileX = 0; const tileY = 0; const tileZ = 0; expect(function() { return shape.computeOrientedBoundingBoxForTile( void 0, tileX, tileY, tileZ, new import__658.OrientedBoundingBox() ); }).toThrowDeveloperError(); expect(function() { return shape.computeOrientedBoundingBoxForTile( tileLevel, void 0, tileY, tileZ, new import__658.OrientedBoundingBox() ); }).toThrowDeveloperError(); expect(function() { return shape.computeOrientedBoundingBoxForTile( tileLevel, tileX, void 0, tileZ, new import__658.OrientedBoundingBox() ); }).toThrowDeveloperError(); expect(function() { return shape.computeOrientedBoundingBoxForTile( tileLevel, tileX, tileY, void 0, new import__658.OrientedBoundingBox() ); }).toThrowDeveloperError(); }); it("computeOrientedBoundingBoxForTile throws with no result parameter", function() { const shape = new import__658.VoxelBoxShape(); const translation = import__658.Cartesian3.ZERO; const rotation = import__658.Quaternion.IDENTITY; const scale = import__658.Cartesian3.ONE; const modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const minBounds = import__658.VoxelBoxShape.DefaultMinBounds; const maxBounds = import__658.VoxelBoxShape.DefaultMaxBounds; shape.update(modelMatrix, minBounds, maxBounds); const tileLevel = 0; const tileX = 0; const tileY = 0; const tileZ = 0; expect(function() { return shape.computeOrientedBoundingBoxForTile( tileLevel, tileX, tileY, tileZ, void 0 ); }).toThrowDeveloperError(); }); it("computeOrientedBoundingBoxForSample gives expected result", function() { const shape = new import__658.VoxelBoxShape(); const translation = import__658.Cartesian3.ZERO; const rotation = import__658.Quaternion.IDENTITY; const scale = import__658.Cartesian3.ONE; const modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const minBounds = import__658.VoxelBoxShape.DefaultMinBounds; const maxBounds = import__658.VoxelBoxShape.DefaultMaxBounds; shape.update(modelMatrix, minBounds, maxBounds); const tileLevel = 0; const tileX = 0; const tileY = 0; const tileZ = 0; const tileDimensions = new import__658.Cartesian3(8, 8, 8); const paddedDimensions = new import__658.Cartesian3(10, 10, 10); const spatialNode = new import__658.SpatialNode( tileLevel, tileX, tileY, tileZ, void 0, shape, paddedDimensions ); const tileUv = new import__658.Cartesian3(0.5, 0.5, 0.5); const sampleBoundingBox = shape.computeOrientedBoundingBoxForSample( spatialNode, tileDimensions, tileUv, new import__658.OrientedBoundingBox() ); const expectedCenter = new import__658.Cartesian3(0.125, 0.125, 0.125); expect(sampleBoundingBox.center).toEqual(expectedCenter); expect(sampleBoundingBox.halfAxes).toEqual( import__658.Matrix3.fromScale(new import__658.Cartesian3(0.125, 0.125, 0.125)) ); }); it("computeOrientedBoundingBoxForSample throws with missing parameters", function() { const shape = new import__658.VoxelBoxShape(); const translation = import__658.Cartesian3.ZERO; const rotation = import__658.Quaternion.IDENTITY; const scale = import__658.Cartesian3.ONE; const modelMatrix = import__658.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const minBounds = import__658.VoxelBoxShape.DefaultMinBounds; const maxBounds = import__658.VoxelBoxShape.DefaultMaxBounds; shape.update(modelMatrix, minBounds, maxBounds); const tileLevel = 0; const tileX = 0; const tileY = 0; const tileZ = 0; const tileDimensions = new import__658.Cartesian3(8, 8, 8); const paddedDimensions = new import__658.Cartesian3(10, 10, 10); const spatialNode = new import__658.SpatialNode( tileLevel, tileX, tileY, tileZ, void 0, shape, paddedDimensions ); const tileUv = new import__658.Cartesian3(0.5, 0.5, 0.5); expect(function() { shape.computeOrientedBoundingBoxForSample( void 0, tileDimensions, tileUv, new import__658.OrientedBoundingBox() ); }).toThrowDeveloperError(); expect(function() { shape.computeOrientedBoundingBoxForSample( spatialNode, void 0, tileUv, new import__658.OrientedBoundingBox() ); }).toThrowDeveloperError(); expect(function() { shape.computeOrientedBoundingBoxForSample( spatialNode, tileDimensions, void 0, new import__658.OrientedBoundingBox() ); }).toThrowDeveloperError(); expect(function() { shape.computeOrientedBoundingBoxForSample( spatialNode, tileDimensions, tileUv, void 0 ); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/VoxelCellSpec.js var import__659 = __toESM(require_Cesium(), 1); describe("Scene/VoxelCell", function() { const voxelTilesetUrl = "Data/Cesium3DTiles/Voxel/VoxelBox3DTiles/tileset.json"; let scene2; let voxelPrimitive; beforeAll(async function() { scene2 = createScene_default(); const provider = await import__659.Cesium3DTilesVoxelProvider.fromUrl(voxelTilesetUrl); voxelPrimitive = new import__659.VoxelPrimitive({ provider }); scene2.primitives.add(voxelPrimitive); await pollToPromise_default(function() { scene2.renderForSpecs(); const traversal = voxelPrimitive._traversal; return traversal.isRenderable(traversal.rootNode); }); }); afterAll(function() { scene2.destroyForSpecs(); }); it("constructs", function() { const tileIndex = 0; const sampleIndex = 0; const voxelCell = new import__659.VoxelCell(voxelPrimitive, tileIndex, sampleIndex); expect(voxelCell instanceof import__659.VoxelCell).toBe(true); expect(voxelCell.primitive).toBe(voxelPrimitive); expect(voxelCell.tileIndex).toBe(tileIndex); expect(voxelCell.sampleIndex).toBe(sampleIndex); }); it("constructs using factory function fromKeyframeNode", function() { const tileIndex = 0; const sampleIndex = 0; const keyframeNode = voxelPrimitive._traversal.findKeyframeNode(tileIndex); const voxelCell = import__659.VoxelCell.fromKeyframeNode( voxelPrimitive, tileIndex, sampleIndex, keyframeNode ); expect(voxelCell instanceof import__659.VoxelCell).toBe(true); expect(voxelCell.primitive).toBe(voxelPrimitive); expect(voxelCell.tileIndex).toBe(tileIndex); expect(voxelCell.sampleIndex).toBe(sampleIndex); }); it("fromKeyFrameNode throws with missing parameters", function() { const tileIndex = 0; const sampleIndex = 0; const keyframeNode = voxelPrimitive._traversal.findKeyframeNode(tileIndex); expect(function() { return import__659.VoxelCell.fromKeyframeNode( void 0, tileIndex, sampleIndex, keyframeNode ); }).toThrowDeveloperError(); expect(function() { return import__659.VoxelCell.fromKeyframeNode( voxelPrimitive, tileIndex, void 0, keyframeNode ); }).toThrowDeveloperError(); expect(function() { return import__659.VoxelCell.fromKeyframeNode( void 0, tileIndex, sampleIndex, void 0 ); }).toThrowDeveloperError(); }); it("reports sample metadata names and properties", function() { const tileIndex = 0; const sampleIndex = 0; const keyframeNode = voxelPrimitive._traversal.findKeyframeNode(tileIndex); const voxelCell = import__659.VoxelCell.fromKeyframeNode( voxelPrimitive, tileIndex, sampleIndex, keyframeNode ); expect(voxelCell.getNames()).toEqual(["a"]); expect(voxelCell.hasProperty("a")).toBe(true); expect(voxelCell.getProperty("a")).toEqual(new Float32Array(1)); }); it("computes bounding box for the sample", function() { const tileIndex = 0; const sampleIndex = 7; const keyframeNode = voxelPrimitive._traversal.findKeyframeNode(tileIndex); const voxelCell = import__659.VoxelCell.fromKeyframeNode( voxelPrimitive, tileIndex, sampleIndex, keyframeNode ); const orientedBoundingBox = voxelCell.orientedBoundingBox; expect(orientedBoundingBox instanceof import__659.OrientedBoundingBox).toBe(true); const expectedCenter = new import__659.Cartesian3(0.5, 0.5, 0.5); expect(orientedBoundingBox.center).toEqualEpsilon( expectedCenter, import__659.Math.EPSILON6 ); const expectedHalfAxes = new import__659.Matrix3.fromUniformScale(0.5); expect(orientedBoundingBox.halfAxes).toEqualEpsilon( expectedHalfAxes, import__659.Math.EPSILON6 ); }); }); // packages/engine/Specs/Scene/VoxelCylinderShapeSpec.js var import__660 = __toESM(require_Cesium(), 1); describe("Scene/VoxelCylinderShape", function() { it("conforms to VoxelShape interface", function() { expect(import__660.VoxelCylinderShape).toConformToInterface(import__660.VoxelShape); }); it("constructs", function() { const shape = new import__660.VoxelCylinderShape(); expect(shape.shapeTransform).toEqual(new import__660.Matrix4()); }); it("update works with model matrix", function() { const shape = new import__660.VoxelCylinderShape(); const translation = new import__660.Cartesian3(1, 2, 3); const scale = new import__660.Cartesian3(2, 3, 4); const angle = import__660.Math.PI_OVER_FOUR; const rotation = import__660.Quaternion.fromAxisAngle(import__660.Cartesian3.UNIT_Z, angle); const modelMatrix = import__660.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const minBounds = import__660.VoxelCylinderShape.DefaultMinBounds; const maxBounds = import__660.VoxelCylinderShape.DefaultMaxBounds; const visible = shape.update(modelMatrix, minBounds, maxBounds); const expectedOrientedBoundingBox = new import__660.OrientedBoundingBox( translation, import__660.Matrix3.fromColumnMajorArray([ scale.x * Math.cos(angle), scale.x * Math.sin(angle), 0, scale.y * Math.cos(angle + import__660.Math.PI_OVER_TWO), scale.y * Math.sin(angle + import__660.Math.PI_OVER_TWO), 0, 0, 0, scale.z ]) ); const expectedBoundingSphere = new import__660.BoundingSphere( translation, import__660.Cartesian3.magnitude(scale) ); expect(shape.orientedBoundingBox.center).toEqual( expectedOrientedBoundingBox.center ); expect(shape.orientedBoundingBox.halfAxes).toEqualEpsilon( expectedOrientedBoundingBox.halfAxes, import__660.Math.EPSILON12 ); expect(shape.boundingSphere).toEqual(expectedBoundingSphere); expect(shape.boundTransform).toEqual(modelMatrix); expect(shape.shapeTransform).toEqual(modelMatrix); expect(visible).toBeTrue(); }); it("update works with non-default minimum and maximum bounds", function() { const shape = new import__660.VoxelCylinderShape(); const translation = new import__660.Cartesian3(1, 2, 3); const scale = new import__660.Cartesian3(2, 3, 4); const rotation = import__660.Quaternion.IDENTITY; const modelMatrix = import__660.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale, new import__660.Matrix4() ); const minRadius = 0.25; const maxRadius = 0.75; const minHeight = -0.5; const maxHeight = 0.5; const minAngle = -import__660.Math.PI; const maxAngle = 0; const minBounds = new import__660.Cartesian3(minRadius, minHeight, minAngle); const maxBounds = new import__660.Cartesian3(maxRadius, maxHeight, maxAngle); const visible = shape.update(modelMatrix, minBounds, maxBounds); const expectedMinX = translation.x - maxRadius * scale.x; const expectedMaxX = translation.x + maxRadius * scale.x; const expectedMinY = translation.y - maxRadius * scale.y; const expectedMaxY = translation.y; const expectedMinZ = translation.z + minHeight * scale.z; const expectedMaxZ = translation.z + maxHeight * scale.z; const expectedScale = new import__660.Cartesian3( 0.5 * (expectedMaxY - expectedMinY), 0.5 * (expectedMaxX - expectedMinX), 0.5 * (expectedMaxZ - expectedMinZ) ); const expectedTranslation = new import__660.Cartesian3( 0.5 * (expectedMaxX + expectedMinX), 0.5 * (expectedMaxY + expectedMinY), 0.5 * (expectedMaxZ + expectedMinZ) ); const expectedRotation = import__660.Matrix3.fromRotationZ(-import__660.Math.PI_OVER_TWO); const expectedHalfAxes = import__660.Matrix3.multiplyByScale( expectedRotation, expectedScale, new import__660.Matrix3() ); const expectedOrientedBoundingBox = new import__660.OrientedBoundingBox( expectedTranslation, expectedHalfAxes ); const expectedBoundingSphere = new import__660.BoundingSphere( expectedTranslation, import__660.Cartesian3.magnitude(expectedScale) ); const expectedBoundTransform = import__660.Matrix4.setTranslation( import__660.Matrix4.fromRotation(expectedHalfAxes), expectedTranslation, new import__660.Matrix4() ); expect(shape.orientedBoundingBox.center).toEqualEpsilon( expectedOrientedBoundingBox.center, import__660.Math.EPSILON12 ); expect(shape.orientedBoundingBox.halfAxes).toEqualEpsilon( expectedOrientedBoundingBox.halfAxes, import__660.Math.EPSILON12 ); expect(shape.boundingSphere).toEqualEpsilon( expectedBoundingSphere, import__660.Math.EPSILON12 ); expect(shape.boundTransform).toEqualEpsilon( expectedBoundTransform, import__660.Math.EPSILON12 ); expect(shape.shapeTransform).toEqual(modelMatrix); expect(visible).toBeTrue(); }); it("update works with minimum and maximum bounds that cross the 180th meridian", function() { const shape = new import__660.VoxelCylinderShape(); const translation = import__660.Cartesian3.ZERO; const scale = import__660.Cartesian3.ONE; const rotation = import__660.Quaternion.IDENTITY; const modelMatrix = import__660.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale, new import__660.Matrix4() ); const minAngle = +import__660.Math.PI_OVER_TWO; const maxAngle = -import__660.Math.PI_OVER_TWO; const defaultMinBounds = import__660.VoxelCylinderShape.DefaultMinBounds; const defaultMaxBounds = import__660.VoxelCylinderShape.DefaultMaxBounds; const minBounds = new import__660.Cartesian3( defaultMinBounds.x, defaultMinBounds.y, minAngle ); const maxBounds = new import__660.Cartesian3( defaultMaxBounds.x, defaultMaxBounds.y, maxAngle ); const visible = shape.update(modelMatrix, minBounds, maxBounds); const expectedScale = new import__660.Cartesian3(0.5, 1, 1); const expectedTranslation = new import__660.Cartesian3(-0.5, 0, 0); const expectedRotation = import__660.Matrix3.fromRotationZ(import__660.Math.PI); const expectedHalfAxes = import__660.Matrix3.multiplyByScale( expectedRotation, expectedScale, new import__660.Matrix3() ); const expectedOrientedBoundingBox = new import__660.OrientedBoundingBox( expectedTranslation, expectedHalfAxes ); const expectedBoundingSphere = new import__660.BoundingSphere( expectedTranslation, import__660.Cartesian3.magnitude(expectedScale) ); const expectedBoundTransform = import__660.Matrix4.setTranslation( import__660.Matrix4.fromRotation(expectedHalfAxes), expectedTranslation, new import__660.Matrix4() ); expect(shape.orientedBoundingBox.center).toEqualEpsilon( expectedOrientedBoundingBox.center, import__660.Math.EPSILON12 ); expect(shape.orientedBoundingBox.halfAxes).toEqualEpsilon( expectedOrientedBoundingBox.halfAxes, import__660.Math.EPSILON12 ); expect(shape.boundingSphere).toEqualEpsilon( expectedBoundingSphere, import__660.Math.EPSILON12 ); expect(shape.boundTransform).toEqualEpsilon( expectedBoundTransform, import__660.Math.EPSILON12 ); expect(shape.shapeTransform).toEqual(modelMatrix); expect(visible).toBeTrue(); }); it("computeOrientedBoundingBoxForTile returns oriented bounding box for a specified tile", () => { let result = new import__660.OrientedBoundingBox(); const shape = new import__660.VoxelCylinderShape(); const translation = new import__660.Cartesian3(1, 2, 3); const scale = new import__660.Cartesian3(2, 3, 4); const rotation = import__660.Quaternion.IDENTITY; const modelMatrix = import__660.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale, new import__660.Matrix4() ); const minRadius = 0.25; const maxRadius = 0.75; const minHeight = -0.5; const maxHeight = 0.5; const minAngle = -import__660.Math.PI; const maxAngle = 0; const minBounds = new import__660.Cartesian3(minRadius, minHeight, minAngle); const maxBounds = new import__660.Cartesian3(maxRadius, maxHeight, maxAngle); shape.update(modelMatrix, minBounds, maxBounds); result = shape.computeOrientedBoundingBoxForTile(0, 0, 0, 0, result); expect(result.center.x).toEqual(1); expect(result.center.y).toEqual(0.875); expect(result.center.z).toEqual(3); expect(result.halfAxes).toEqualEpsilon( new import__660.Matrix3(0, 1.5, 0, -1.125, 0, 0, 0, 0, 2), import__660.Math.EPSILON12 ); }); it("computeOrientedBoundingBoxForTile throws with missing parameters", () => { const shape = new import__660.VoxelCylinderShape(); const translation = import__660.Cartesian3.ZERO; const scale = import__660.Cartesian3.ONE; const rotation = import__660.Quaternion.IDENTITY; const modelMatrix = import__660.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const minBounds = import__660.VoxelCylinderShape.DefaultMinBounds; const maxBounds = import__660.VoxelCylinderShape.DefaultMaxBounds; shape.update(modelMatrix, minBounds, maxBounds); const result = new import__660.OrientedBoundingBox(); expect(function() { shape.computeOrientedBoundingBoxForTile(void 0, 0, 0, 0, result); }).toThrowDeveloperError(); expect(function() { shape.computeOrientedBoundingBoxForTile(0, void 0, 0, 0, result); }).toThrowDeveloperError(); expect(function() { shape.computeOrientedBoundingBoxForTile(0, 0, void 0, 0, result); }).toThrowDeveloperError(); expect(function() { shape.computeOrientedBoundingBoxForTile(0, 0, 0, void 0, result); }).toThrowDeveloperError(); expect(function() { shape.computeOrientedBoundingBoxForTile(0, 0, 0, 0, void 0); }).toThrowDeveloperError(); }); it("computeOrientedBoundingBoxForSample gives expected result", function() { const shape = new import__660.VoxelCylinderShape(); const translation = import__660.Cartesian3.ZERO; const rotation = import__660.Quaternion.IDENTITY; const scale = import__660.Cartesian3.ONE; const modelMatrix = import__660.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const minBounds = import__660.VoxelCylinderShape.DefaultMinBounds; const maxBounds = import__660.VoxelCylinderShape.DefaultMaxBounds; shape.update(modelMatrix, minBounds, maxBounds); const tileLevel = 0; const tileX = 0; const tileY = 0; const tileZ = 0; const tileDimensions = new import__660.Cartesian3(8, 8, 8); const paddedDimensions = new import__660.Cartesian3(10, 10, 10); const spatialNode = new import__660.SpatialNode( tileLevel, tileX, tileY, tileZ, void 0, shape, paddedDimensions ); const tileUv = new import__660.Cartesian3(0.5, 0.5, 0.5); const sampleBoundingBox = shape.computeOrientedBoundingBoxForSample( spatialNode, tileDimensions, tileUv, new import__660.OrientedBoundingBox() ); const centerAngle = Math.PI / 8; const centerRadius = 0.5434699; const expectedCenter = new import__660.Cartesian3( centerRadius * Math.cos(centerAngle), centerRadius * Math.sin(centerAngle), 0.125 ); expect(sampleBoundingBox.center).toEqualEpsilon( expectedCenter, import__660.Math.EPSILON6 ); const expectedHalfAxes = new import__660.Matrix3( 0.075324, -0.091529, 0, 0.0312, 0.22097, 0, 0, 0, 0.125 ); expect(sampleBoundingBox.halfAxes).toEqualEpsilon( expectedHalfAxes, import__660.Math.EPSILON6 ); }); it("computeOrientedBoundingBoxForSample throws with missing parameters", function() { const shape = new import__660.VoxelCylinderShape(); const translation = import__660.Cartesian3.ZERO; const rotation = import__660.Quaternion.IDENTITY; const scale = import__660.Cartesian3.ONE; const modelMatrix = import__660.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const minBounds = import__660.VoxelCylinderShape.DefaultMinBounds; const maxBounds = import__660.VoxelCylinderShape.DefaultMaxBounds; shape.update(modelMatrix, minBounds, maxBounds); const tileLevel = 0; const tileX = 0; const tileY = 0; const tileZ = 0; const tileDimensions = new import__660.Cartesian3(8, 8, 8); const paddedDimensions = new import__660.Cartesian3(10, 10, 10); const spatialNode = new import__660.SpatialNode( tileLevel, tileX, tileY, tileZ, void 0, shape, paddedDimensions ); const tileUv = new import__660.Cartesian3(0.5, 0.5, 0.5); expect(function() { shape.computeOrientedBoundingBoxForSample( void 0, tileDimensions, tileUv, new import__660.OrientedBoundingBox() ); }).toThrowDeveloperError(); expect(function() { shape.computeOrientedBoundingBoxForSample( spatialNode, void 0, tileUv, new import__660.OrientedBoundingBox() ); }).toThrowDeveloperError(); expect(function() { shape.computeOrientedBoundingBoxForSample( spatialNode, tileDimensions, void 0, new import__660.OrientedBoundingBox() ); }).toThrowDeveloperError(); expect(function() { shape.computeOrientedBoundingBoxForSample( spatialNode, tileDimensions, tileUv, void 0 ); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/VoxelEllipsoidShapeSpec.js var import__661 = __toESM(require_Cesium(), 1); describe("Scene/VoxelEllipsoidShape", function() { it("conforms to VoxelShape interface", function() { expect(import__661.VoxelEllipsoidShape).toConformToInterface(import__661.VoxelShape); }); it("constructs", function() { const shape = new import__661.VoxelEllipsoidShape(); expect(shape.shapeTransform).toEqual(new import__661.Matrix4()); }); it("update works with model matrix", function() { const shape = new import__661.VoxelEllipsoidShape(); const translation = new import__661.Cartesian3(1, 2, 3); const scale = new import__661.Cartesian3(2, 2, 2); const angle = import__661.Math.PI_OVER_FOUR; const rotation = import__661.Quaternion.fromAxisAngle(import__661.Cartesian3.UNIT_Z, angle); const modelMatrix = import__661.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const minBounds = new import__661.Cartesian3( -import__661.Math.PI, -import__661.Math.PI_OVER_TWO, 0 ); const maxBounds = new import__661.Cartesian3( +import__661.Math.PI, +import__661.Math.PI_OVER_TWO, 1e5 ); const maxHeight = maxBounds.z; const expectedOrientedBoundingBox = new import__661.OrientedBoundingBox( translation, import__661.Matrix3.fromRowMajorArray([ 0, 0, scale.z + maxHeight, (scale.x + maxHeight) * Math.cos(angle), -(scale.y + maxHeight) * Math.sin(angle), 0, (scale.x + maxHeight) * Math.sin(angle), (scale.y + maxHeight) * Math.cos(angle), 0 ]) ); const expectedBoundingSphere = import__661.BoundingSphere.fromOrientedBoundingBox( expectedOrientedBoundingBox, new import__661.BoundingSphere() ); const visible = shape.update(modelMatrix, minBounds, maxBounds); expect(shape.orientedBoundingBox.center).toEqual( expectedOrientedBoundingBox.center ); expect(shape.orientedBoundingBox.halfAxes).toEqualEpsilon( expectedOrientedBoundingBox.halfAxes, import__661.Math.EPSILON9 ); expect(shape.boundingSphere).toEqual(expectedBoundingSphere); expect( import__661.Matrix4.getTranslation(shape.boundTransform, new import__661.Cartesian3()) ).toEqualEpsilon(expectedOrientedBoundingBox.center, import__661.Math.EPSILON12); expect( import__661.Matrix4.getMatrix3(shape.boundTransform, new import__661.Matrix3()) ).toEqualEpsilon(expectedOrientedBoundingBox.halfAxes, import__661.Math.EPSILON9); expect( import__661.Matrix4.getTranslation(shape.shapeTransform, new import__661.Cartesian3()) ).toEqualEpsilon(expectedOrientedBoundingBox.center, import__661.Math.EPSILON12); const expectedShapeTransform = import__661.Matrix4.fromRowMajorArray([ (scale.x + maxHeight) * Math.cos(angle), -(scale.x + maxHeight) * Math.sin(angle), 0, expectedOrientedBoundingBox.center.x, (scale.y + maxHeight) * Math.sin(angle), (scale.y + maxHeight) * Math.cos(angle), 0, expectedOrientedBoundingBox.center.y, 0, 0, scale.z + maxHeight, expectedOrientedBoundingBox.center.z, 0, 0, 0, 1 ]); expect(shape.shapeTransform).toEqualEpsilon( expectedShapeTransform, import__661.Math.EPSILON9 ); expect(visible).toBeTrue(); }); it("computeOrientedBoundingBoxForTile returns oriented bounding box for a specified tile", () => { const shape = new import__661.VoxelEllipsoidShape(); const translation = import__661.Cartesian3.ZERO; const scale = import__661.Cartesian3.ONE; const rotation = import__661.Quaternion.IDENTITY; const modelMatrix = import__661.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const minBounds = new import__661.Cartesian3( -import__661.Math.PI, -import__661.Math.PI_OVER_TWO, -0.5 ); const maxBounds = new import__661.Cartesian3( import__661.Math.PI, import__661.Math.PI_OVER_TWO, 0 ); shape.update(modelMatrix, minBounds, maxBounds); let result = new import__661.OrientedBoundingBox(); result = shape.computeOrientedBoundingBoxForTile(0, 0, 0, 0, result); expect(result.center).toEqual(import__661.Cartesian3.ZERO); const expectedHalfAxes = new import__661.Matrix3(0, 0, 1, 1, 0, 0, 0, 1, 0); expect(result.halfAxes).toEqualEpsilon( expectedHalfAxes, import__661.Math.EPSILON12 ); }); it("computeOrientedBoundingBoxForTile throws with missing parameters", () => { const shape = new import__661.VoxelEllipsoidShape(); const translation = import__661.Cartesian3.ZERO; const scale = import__661.Cartesian3.ONE; const rotation = import__661.Quaternion.IDENTITY; const modelMatrix = import__661.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const minBounds = import__661.VoxelEllipsoidShape.DefaultMinBounds; const maxBounds = import__661.VoxelEllipsoidShape.DefaultMaxBounds; shape.update(modelMatrix, minBounds, maxBounds); const result = new import__661.OrientedBoundingBox(); expect(function() { shape.computeOrientedBoundingBoxForTile(void 0, 0, 0, 0, result); }).toThrowDeveloperError(); expect(function() { shape.computeOrientedBoundingBoxForTile(0, void 0, 0, 0, result); }).toThrowDeveloperError(); expect(function() { shape.computeOrientedBoundingBoxForTile(0, 0, void 0, 0, result); }).toThrowDeveloperError(); expect(function() { shape.computeOrientedBoundingBoxForTile(0, 0, 0, void 0, result); }).toThrowDeveloperError(); expect(function() { shape.computeOrientedBoundingBoxForTile(0, 0, 0, 0, void 0); }).toThrowDeveloperError(); }); it("computeOrientedBoundingBoxForSample returns oriented bounding box for a specified sample", () => { const shape = new import__661.VoxelEllipsoidShape(); const translation = import__661.Cartesian3.ZERO; const scale = import__661.Cartesian3.ONE; const rotation = import__661.Quaternion.IDENTITY; const modelMatrix = import__661.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const minBounds = new import__661.Cartesian3( -import__661.Math.PI, -import__661.Math.PI_OVER_TWO, -1 ); const maxBounds = new import__661.Cartesian3( import__661.Math.PI, import__661.Math.PI_OVER_TWO, 0 ); shape.update(modelMatrix, minBounds, maxBounds); const tileLevel = 0; const tileX = 0; const tileY = 0; const tileZ = 0; const tileDimensions = new import__661.Cartesian3(16, 8, 8); const paddedDimensions = new import__661.Cartesian3(18, 10, 10); const spatialNode = new import__661.SpatialNode( tileLevel, tileX, tileY, tileZ, void 0, shape, paddedDimensions ); const tileUv = new import__661.Cartesian3(0.5, 0.5, 0.5); const sampleBoundingBox = shape.computeOrientedBoundingBoxForSample( spatialNode, tileDimensions, tileUv, new import__661.OrientedBoundingBox() ); const centerLongitude = Math.PI / 16; const centerLatitude = Math.PI / 16; const centerRadius = 0.553; const expectedCenter = new import__661.Cartesian3( centerRadius * Math.cos(centerLongitude) * Math.cos(centerLatitude), centerRadius * Math.sin(centerLongitude) * Math.cos(centerLatitude), centerRadius * Math.sin(centerLatitude) ); expect(sampleBoundingBox.center).toEqualEpsilon( expectedCenter, import__661.Math.EPSILON2 ); }); it("computeOrientedBoundingBoxForSample throws with missing parameters", () => { const shape = new import__661.VoxelEllipsoidShape(); const translation = import__661.Cartesian3.ZERO; const scale = import__661.Cartesian3.ONE; const rotation = import__661.Quaternion.IDENTITY; const modelMatrix = import__661.Matrix4.fromTranslationQuaternionRotationScale( translation, rotation, scale ); const minBounds = new import__661.Cartesian3( -import__661.Math.PI, -import__661.Math.PI_OVER_TWO, -1 ); const maxBounds = new import__661.Cartesian3( import__661.Math.PI, import__661.Math.PI_OVER_TWO, 0 ); shape.update(modelMatrix, minBounds, maxBounds); const tileLevel = 0; const tileX = 0; const tileY = 0; const tileZ = 0; const tileDimensions = new import__661.Cartesian3(16, 8, 8); const paddedDimensions = new import__661.Cartesian3(18, 10, 10); const spatialNode = new import__661.SpatialNode( tileLevel, tileX, tileY, tileZ, void 0, shape, paddedDimensions ); const tileUv = new import__661.Cartesian3(0.5, 0.5, 0.5); const result = new import__661.OrientedBoundingBox(); expect(function() { shape.computeOrientedBoundingBoxForSample( void 0, tileDimensions, tileUv, result ); }).toThrowDeveloperError(); expect(function() { shape.computeOrientedBoundingBoxForSample( spatialNode, void 0, tileUv, result ); }).toThrowDeveloperError(); expect(function() { shape.computeOrientedBoundingBoxForSample( spatialNode, tileDimensions, void 0, result ); }).toThrowDeveloperError(); expect(function() { shape.computeOrientedBoundingBoxForSample( spatialNode, tileDimensions, tileUv, void 0 ); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/VoxelPrimitiveSpec.js var import__662 = __toESM(require_Cesium(), 1); describe( "Scene/VoxelPrimitive", function() { let scene2; let provider; beforeEach(async function() { scene2 = createScene_default(); const camera = scene2.camera; camera.position = import__662.Cartesian3.fromElements(-10, -10, -10); camera.direction = import__662.Cartesian3.fromElements(1, 1, 1); provider = await import__662.Cesium3DTilesVoxelProvider.fromUrl( "./Data/Cesium3DTiles/Voxel/VoxelEllipsoid3DTiles/tileset.json" ); return provider; }); afterEach(function() { scene2.destroyForSpecs(); }); it("constructs a primitive", function() { const primitive = new import__662.VoxelPrimitive(); expect(primitive.geometryInstances).not.toBeDefined(); expect(primitive.appearance).not.toBeDefined(); expect(primitive.depthFailAppearance).not.toBeDefined(); expect(primitive.modelMatrix).toEqual(import__662.Matrix4.IDENTITY); expect(primitive.show).toEqual(true); }); it("constructs with options", async function() { const primitive = new import__662.VoxelPrimitive({ provider }); scene2.primitives.add(primitive); expect(primitive.provider).toBe(provider); await pollToPromise_default(() => { scene2.renderForSpecs(); return primitive.ready; }); expect(primitive.shape._type).toBe(provider.shape._type); expect(primitive.dimensions.equals(provider.dimensions)).toBe(true); expect(primitive._tileCount).toBe(provider._tileCount); expect(primitive._traversal).toBeDefined(); expect(primitive.minimumValues).toBe(provider.minimumValues); expect(primitive.maximumValues).toBe(provider.maximumValues); }); it("toggles render options that require shader rebuilds", async function() { const primitive = new import__662.VoxelPrimitive({ provider }); scene2.primitives.add(primitive); function toggleOption(option, defaultValue50, newValue) { expect(primitive[option]).toBe(defaultValue50); primitive[option] = newValue; expect(primitive._shaderDirty).toBe(true); primitive.update(scene2.frameState); expect(primitive[option]).toBe(newValue); expect(primitive._shaderDirty).toBe(false); } await pollToPromise_default(function() { scene2.renderForSpecs(); const traversal = primitive._traversal; return traversal.isRenderable(traversal.rootNode); }); toggleOption("depthTest", true, false); toggleOption("jitter", false, true); toggleOption("nearestSampling", false, true); }); it("sets render parameters", async function() { const primitive = new import__662.VoxelPrimitive({ provider }); scene2.primitives.add(primitive); function setParameter(parameter, defaultValue50, newValue) { expect(primitive[parameter]).toBe(defaultValue50); primitive[parameter] = newValue; primitive.update(scene2.frameState); expect(primitive[parameter]).toBe(newValue); } await pollToPromise_default(function() { scene2.renderForSpecs(); const traversal = primitive._traversal; return traversal.isRenderable(traversal.rootNode); }); setParameter("levelBlendFactor", 0, 0.5); setParameter("screenSpaceError", 4, 2); setParameter("stepSize", 1, 0.5); setParameter("debugDraw", false, true); }); it("sets clipping range extrema when given valid range between 0 and 1", function() { const primitive = new import__662.VoxelPrimitive({ provider }); scene2.primitives.add(primitive); scene2.renderForSpecs(); const setValue = import__662.Cartesian3.fromElements(0.1, 0.5, 0.3); expect(primitive.minClippingBounds.equals(setValue)).toBe(false); primitive.minClippingBounds = setValue; expect(primitive.minClippingBounds.equals(setValue)).toBe(true); expect(primitive.maxClippingBounds.equals(setValue)).toBe(false); primitive.maxClippingBounds = setValue; expect(primitive.maxClippingBounds.equals(setValue)).toBe(true); }); it("vertically exaggerates height bounds for ellipsoid-shaped voxels", function() { const primitive = new import__662.VoxelPrimitive({ provider }); scene2.primitives.add(primitive); scene2.renderForSpecs(); const { minBounds, maxBounds } = primitive; expect(primitive._exaggeratedMinBounds).toEqual(minBounds); expect(primitive._exaggeratedMaxBounds).toEqual(maxBounds); const exaggerationFactor = 2; scene2.verticalExaggeration = exaggerationFactor; scene2.renderForSpecs(); const expectedMinBounds = minBounds.clone(); expectedMinBounds.z *= exaggerationFactor; const expectedMaxBounds = maxBounds.clone(); expectedMaxBounds.z *= exaggerationFactor; expect(primitive._exaggeratedMinBounds).toEqual(expectedMinBounds); expect(primitive._exaggeratedMaxBounds).toEqual(expectedMaxBounds); }); it("applies vertical exaggeration to box-shaped voxels by scaling the model matrix", async function() { const boxProvider = await import__662.Cesium3DTilesVoxelProvider.fromUrl( "./Data/Cesium3DTiles/Voxel/VoxelBox3DTiles/tileset.json" ); const primitive = new import__662.VoxelPrimitive({ provider: boxProvider }); scene2.primitives.add(primitive); scene2.renderForSpecs(); const modelMatrix = primitive.modelMatrix.clone(); expect(primitive._exaggeratedModelMatrix).toEqual(modelMatrix); const exaggerationFactor = 2; scene2.verticalExaggeration = exaggerationFactor; scene2.renderForSpecs(); const scalar = import__662.Cartesian3.fromElements(1, 1, exaggerationFactor); const expectedModelMatrix = import__662.Matrix4.multiplyByScale( modelMatrix, scalar, new import__662.Matrix4() ); expect(primitive._exaggeratedModelMatrix).toEqual(expectedModelMatrix); }); it("uses default style", function() { const primitive = new import__662.VoxelPrimitive({ provider }); scene2.primitives.add(primitive); scene2.renderForSpecs(); primitive.style = void 0; expect(primitive.style).toBe(import__662.VoxelPrimitive.DefaultStyle); }); it("accepts a new Custom Shader", async function() { const primitive = new import__662.VoxelPrimitive({ provider }); scene2.primitives.add(primitive); scene2.renderForSpecs(); await pollToPromise_default(() => { scene2.renderForSpecs(); return primitive.ready; }); expect(primitive.customShader).toBe(import__662.VoxelPrimitive.DefaultCustomShader); primitive.customShader = void 0; scene2.renderForSpecs(); expect(primitive.customShader).toBe(import__662.VoxelPrimitive.DefaultCustomShader); const modifiedShader = new import__662.CustomShader({ fragmentShaderText: `void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) { material.diffuse = vec3(1.0, 1.0, 0.0); material.alpha = 0.8; }` }); primitive.customShader = modifiedShader; scene2.renderForSpecs(); expect(primitive.customShader).toBe(modifiedShader); }); it("destroys", async function() { const primitive = new import__662.VoxelPrimitive({ provider }); scene2.primitives.add(primitive); scene2.renderForSpecs(); expect(primitive.isDestroyed()).toBe(false); await pollToPromise_default(() => { scene2.renderForSpecs(); return primitive.ready; }); primitive.update(scene2.frameState); expect(primitive.isDestroyed()).toBe(false); expect(primitive._pickId).toBeDefined(); expect(primitive._traversal).toBeDefined(); scene2.primitives.remove(primitive); expect(primitive.isDestroyed()).toBe(true); expect(primitive._pickId).toBeUndefined(); expect(primitive._traversal).toBeUndefined(); }); }, "WebGL" ); // packages/engine/Specs/Scene/VoxelRenderResourcesSpec.js var import__663 = __toESM(require_Cesium(), 1); describe("Scene/VoxelRenderResources", function() { let scene2; beforeEach(function() { scene2 = createScene_default(); }); afterEach(function() { scene2.destroyForSpecs(); }); it("constructs", function() { const primitive = new import__663.VoxelPrimitive(); primitive.show = false; primitive.update(scene2.frameState); const renderResources = new import__663.VoxelRenderResources(primitive); expect(renderResources.shaderBuilder).toBeDefined(); expect(renderResources.uniformMap).toBeDefined(); }); }); // packages/engine/Specs/Scene/VoxelShapeTypeSpec.js var import__664 = __toESM(require_Cesium(), 1); describe("Scene/VoxelShapeType", function() { it("getMinBounds works", function() { expect(import__664.VoxelShapeType.getMinBounds(import__664.VoxelShapeType.BOX)).toEqual( import__664.VoxelBoxShape.DefaultMinBounds ); expect(import__664.VoxelShapeType.getMinBounds(import__664.VoxelShapeType.ELLIPSOID)).toEqual( import__664.VoxelEllipsoidShape.DefaultMinBounds ); expect(import__664.VoxelShapeType.getMinBounds(import__664.VoxelShapeType.CYLINDER)).toEqual( import__664.VoxelCylinderShape.DefaultMinBounds ); }); it("getMinBounds throws for invalid type", function() { expect(function() { return import__664.VoxelShapeType.getMinBounds("NOT_A_SHAPE_TYPE"); }).toThrowDeveloperError(); }); it("getMaxBounds works", function() { expect(import__664.VoxelShapeType.getMaxBounds(import__664.VoxelShapeType.BOX)).toEqual( import__664.VoxelBoxShape.DefaultMaxBounds ); expect(import__664.VoxelShapeType.getMaxBounds(import__664.VoxelShapeType.ELLIPSOID)).toEqual( import__664.VoxelEllipsoidShape.DefaultMaxBounds ); expect(import__664.VoxelShapeType.getMaxBounds(import__664.VoxelShapeType.CYLINDER)).toEqual( import__664.VoxelCylinderShape.DefaultMaxBounds ); }); it("getMaxBounds throws for invalid type", function() { expect(function() { return import__664.VoxelShapeType.getMaxBounds("NOT_A_SHAPE_TYPE"); }).toThrowDeveloperError(); }); it("getShapeConstructor works", function() { expect(import__664.VoxelShapeType.getShapeConstructor(import__664.VoxelShapeType.BOX)).toBe( import__664.VoxelBoxShape ); expect(import__664.VoxelShapeType.getShapeConstructor(import__664.VoxelShapeType.ELLIPSOID)).toBe( import__664.VoxelEllipsoidShape ); expect(import__664.VoxelShapeType.getShapeConstructor(import__664.VoxelShapeType.CYLINDER)).toBe( import__664.VoxelCylinderShape ); }); it("getShapeConstructor throws for invalid type", function() { expect(function() { return import__664.VoxelShapeType.getShapeConstructor("NOT_A_SHAPE_TYPE"); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/VoxelTraversalSpec.js var import__665 = __toESM(require_Cesium(), 1); var towardPrimitive = import__665.Cartesian3.fromElements(1, 1, 1); function turnCameraAround(scene2) { scene2.camera.direction = import__665.Cartesian3.negate(towardPrimitive, new import__665.Cartesian3()); scene2.renderForSpecs(); } describe( "Scene/VoxelTraversal", function() { const keyframeCount = 3; const textureMemory = 500; let scene2; let provider; let camera; let primitive; let traversal; beforeEach(async function() { scene2 = createScene_default(); provider = await import__665.Cesium3DTilesVoxelProvider.fromUrl( "./Data/Cesium3DTiles/Voxel/VoxelEllipsoid3DTiles/tileset.json" ); camera = scene2.camera; camera.position = import__665.Cartesian3.fromElements(-6378e3, -6378e3, -6378e3); camera.direction = import__665.Cartesian3.fromElements(1, 1, 1); camera.frustum.fov = import__665.Math.PI_OVER_TWO; primitive = new import__665.VoxelPrimitive({ provider }); scene2.primitives.add(primitive); scene2.renderForSpecs(); traversal = new import__665.VoxelTraversal( primitive, scene2.context, provider.dimensions, provider.types, provider.componentTypes, keyframeCount, textureMemory ); }); afterEach(function() { scene2.destroyForSpecs(); }); it("constructs with arguments", function() { expect(traversal._primitive).toBe(primitive); expect(traversal.megatextures.length).toBe(1); const megatexture = traversal.megatextures[0]; expect(megatexture.datatype).toBe(import__665.MetadataType.FLOAT); }); it("recomputes bounding volume when shape moves", function() { const rootNode = traversal.rootNode; const oldOrientedBoundingBox = rootNode.orientedBoundingBox.clone(); const shape = traversal._primitive._shape; const translation = import__665.Cartesian3.fromElements(1, 1, 1); shape.translation = translation; const modelMatrix = import__665.Matrix4.fromTranslation(translation); shape.update( modelMatrix, import__665.VoxelEllipsoidShape.DefaultMinBounds, import__665.VoxelEllipsoidShape.DefaultMaxBounds ); const keyFrameLocation = 0; const recomputeBoundingVolumes = true; const pauseUpdate = false; traversal.update( scene2.frameState, keyFrameLocation, recomputeBoundingVolumes, pauseUpdate ); const newOrientedBoundingBox = rootNode.orientedBoundingBox.clone(); expect( import__665.OrientedBoundingBox.equals( oldOrientedBoundingBox, newOrientedBoundingBox ) ).toBe(false); expect(newOrientedBoundingBox.center.equals(translation)).toBe(true); }); it("computes screen space error for root tile", function() { const { context, pixelRatio } = scene2.frameState; const screenHeight = context.drawingBufferHeight / pixelRatio; const screenSpaceErrorMultiplier = screenHeight / camera.frustum.sseDenominator; const rootNode = traversal.rootNode; rootNode.computeScreenSpaceError( camera.positionWC, screenSpaceErrorMultiplier ); let distanceToCamera = Math.sqrt( rootNode.orientedBoundingBox.distanceSquaredTo(camera.positionWC) ); distanceToCamera = Math.max(distanceToCamera, import__665.Math.EPSILON7); const error = screenSpaceErrorMultiplier * (rootNode.approximateVoxelSize / distanceToCamera); expect(rootNode.screenSpaceError).toBe(error); }); it("computes visibility for root tile", function() { const rootNode = traversal.rootNode; const visibilityPlaneMask = import__665.CullingVolume.MASK_INDETERMINATE; const visibilityWhenLookingAtRoot = rootNode.visibility( scene2.frameState, visibilityPlaneMask ); expect(visibilityWhenLookingAtRoot).toBe(import__665.CullingVolume.MASK_INSIDE); turnCameraAround(scene2); const visibilityWhenLookingAway = rootNode.visibility( scene2.frameState, visibilityPlaneMask ); expect(visibilityWhenLookingAway).toBe(import__665.CullingVolume.MASK_OUTSIDE); }); it("destroys", function() { expect(traversal.isDestroyed()).toBe(false); traversal.destroy(); expect(traversal.isDestroyed()).toBe(true); }); it("loads tiles into megatexture", async function() { const keyFrameLocation = 0; const recomputeBoundingVolumes = true; const pauseUpdate = false; await pollToPromise_default(function() { traversal.update( scene2.frameState, keyFrameLocation, recomputeBoundingVolumes, pauseUpdate ); scene2.renderForSpecs(); return traversal.megatextures[0].occupiedCount > 0; }); const megatexture = traversal.megatextures[0]; expect(megatexture.occupiedCount).toBe(1); }); it("finds keyframe node with expected metadata values", async function() { const keyFrameLocation = 0; const recomputeBoundingVolumes = true; const pauseUpdate = false; await pollToPromise_default(function() { traversal.update( scene2.frameState, keyFrameLocation, recomputeBoundingVolumes, pauseUpdate ); scene2.renderForSpecs(); return traversal.megatextures[0].occupiedCount > 0; }); const megatextureIndex = 0; const keyframeNode = traversal.findKeyframeNode(megatextureIndex); expect(keyframeNode).toBeDefined(); expect(keyframeNode.state).toBe(import__665.KeyframeNode.LoadState.LOADED); const expectedMetadata = new Float32Array([0, 0, 0, 0, 1, 1, 1, 1]); expect(keyframeNode.metadata[0]).toEqual(expectedMetadata); }); xit("unloads tiles in megatexture", function() { const keyFrameLocation = 0; const recomputeBoundingVolumes = true; const pauseUpdate = false; function updateTraversalTenTimes() { function updateTraversal() { traversal.update( scene2.frameState, keyFrameLocation, recomputeBoundingVolumes, pauseUpdate ); } for (let i = 0; i < 10; i++) { updateTraversal(); } } const eps = import__665.Math.EPSILON7; const bottomLeftNearCorner = import__665.Cartesian3.fromElements( -0.5 - eps, -0.5 - eps, -0.5 - eps ); const topRightFarCorner = import__665.Cartesian3.fromElements( 0.5 + eps, 0.5 + eps, 0.5 + eps ); scene2.camera.position = bottomLeftNearCorner; updateTraversalTenTimes(); const numberOfNodesOnGPU = traversal._keyframeNodesInMegatexture.length; const deepestNode = traversal._keyframeNodesInMegatexture[numberOfNodesOnGPU - 1]; const deepestSpatialNode = deepestNode.spatialNode; const nodeIsInMegatexture = deepestNode.state === import__665.VoxelTraversal.LoadState.LOADED; expect(nodeIsInMegatexture).toBe(true); scene2.camera.position = topRightFarCorner; turnCameraAround(scene2); updateTraversalTenTimes(); const nodeNoLongerInMegatexture = traversal._keyframeNodesInMegatexture.filter(function(keyFrameNode) { const spatialNode = keyFrameNode.spatialNode; return spatialNode.level === deepestSpatialNode.level && spatialNode.x === deepestSpatialNode.x && spatialNode.y === deepestSpatialNode.y && spatialNode.x === deepestSpatialNode.z; }).length === 0; expect(nodeNoLongerInMegatexture).toBe(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/WebMapServiceImageryProviderSpec.js var import_urijs7 = __toESM(require_URI(), 1); var import__666 = __toESM(require_Cesium(), 1); var import__667 = __toESM(require_Cesium(), 1); describe("Scene/WebMapServiceImageryProvider", function() { beforeEach(function() { import__666.RequestScheduler.clearForSpecs(); }); afterEach(function() { import__666.Resource._Implementations.createImage = import__666.Resource._DefaultImplementations.createImage; import__666.Resource._Implementations.loadWithXhr = import__666.Resource._DefaultImplementations.loadWithXhr; }); it("conforms to ImageryProvider interface", function() { expect(import__666.WebMapServiceImageryProvider).toConformToInterface(import__666.ImageryProvider); }); it("requires the url to be specified", function() { function createWithoutUrl() { return new import__666.WebMapServiceImageryProvider({ layers: "someLayer" }); } expect(createWithoutUrl).toThrowDeveloperError(); }); it("requires the layers to be specified", function() { function createWithoutUrl() { return new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server" }); } expect(createWithoutUrl).toThrowDeveloperError(); }); it("returns valid value for hasAlphaChannel", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer" }); expect(typeof provider.hasAlphaChannel).toBe("boolean"); }); it("can use a custom ellipsoid", function() { const ellipsoid = new import__666.Ellipsoid(1, 2, 3); const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", ellipsoid }); expect(provider.tilingScheme.ellipsoid).toEqual(ellipsoid); }); it("includes specified parameters in URL", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", parameters: { something: "foo", another: false, version: "1.3.0" } }); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const uri = new import_urijs7.default(request.url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.something).toEqual("foo"); expect(params.another).toEqual("false"); expect(params.version).toEqual("1.3.0"); deferred.resolve(true); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); }); }); it("includes crs parameters in URL for WMS version 1.3.0", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", crs: "CRS:27", parameters: { version: "1.3.0" } }); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const uri = new import_urijs7.default(request.url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.crs).toEqual("CRS:27"); expect(params.version).toEqual("1.3.0"); deferred.resolve(true); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); }); }); it("includes bbox parameters in URL for WMS version 1.3.0 and CRS EPSG:4326", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", crs: "EPSG:4326", parameters: { version: "1.3.0" } }); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const uri = new import_urijs7.default(request.url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.crs).toEqual("EPSG:4326"); expect(params.version).toEqual("1.3.0"); expect(params.bbox).toEqual("-90,-180,90,0"); deferred.resolve(true); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); }); }); it("reverses axis order for EPSG code between 4000-5000 for WMS version 1.3.0", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", crs: "EPSG:4321", parameters: { version: "1.3.0" } }); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const uri = new import_urijs7.default(request.url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.crs).toEqual("EPSG:4321"); expect(params.version).toEqual("1.3.0"); expect(params.bbox).toEqual("-90,-180,90,0"); deferred.resolve(true); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); }); }); it("reverses axis order for included EPSG code for WMS version 1.3.0", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", crs: "EPSG:3035", parameters: { version: "1.3.0" } }); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const uri = new import_urijs7.default(request.url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.crs).toEqual("EPSG:3035"); expect(params.version).toEqual("1.3.0"); expect(params.bbox).toEqual("-90,-180,90,0"); deferred.resolve(true); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); }); }); it("does not reverse axis order for excluded EPSG code for WMS version 1.3.0", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", crs: "EPSG:4559", parameters: { version: "1.3.0" } }); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const uri = new import_urijs7.default(request.url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.crs).toEqual("EPSG:4559"); expect(params.version).toEqual("1.3.0"); expect(params.bbox).toEqual("-180,-90,0,90"); deferred.resolve(true); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); }); }); it("disregard crs parameters in URL for WMS version 1.1.0", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", crs: "CRS:27", parameters: { version: "1.1.0" } }); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const uri = new import_urijs7.default(request.url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.srs).toEqual("EPSG:4326"); expect(params.version).toEqual("1.1.0"); deferred.resolve(true); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); }); }); it("includes srs parameters in URL for WMS version 1.1.0", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", srs: "IAU2000:30118", parameters: { version: "1.1.0" } }); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const uri = new import_urijs7.default(request.url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.srs).toEqual("IAU2000:30118"); expect(params.version).toEqual("1.1.0"); deferred.resolve(true); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); }); }); it("includes bbox parameters in URL for WMS version 1.1.1", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", crs: "CRS:27", parameters: { version: "1.1.0" } }); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const uri = new import_urijs7.default(request.url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.srs).toEqual("EPSG:4326"); expect(params.version).toEqual("1.1.0"); expect(params.bbox).toEqual("-180,-90,0,90"); deferred.resolve(true); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); }); }); it("supports subdomains string in URL", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "{s}", subdomains: "123", layers: "" }); spyOn(import__666.ImageryProvider, "loadImage"); provider.requestImage(0, 0, 0); const url = import__666.ImageryProvider.loadImage.calls.mostRecent().args[1].url; expect("123".indexOf(url.substring(0, 1))).toBeGreaterThanOrEqual(0); }); it("supports subdomains array in URL", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "{s}", subdomains: ["foo", "bar"], layers: "" }); spyOn(import__666.ImageryProvider, "loadImage"); provider.requestImage(0, 0, 0); const url = import__666.ImageryProvider.loadImage.calls.mostRecent().args[1].url; expect(["foo", "bar"].indexOf(url.substring(0, 3))).toBeGreaterThanOrEqual( 0 ); }); it("supports a question mark at the end of the URL", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server?", layers: "someLayer" }); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const questionMarkCount = request.url.match(/\?/g).length; expect(questionMarkCount).toEqual(1); deferred.resolve(true); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); }); }); it("supports an ampersand at the end of the URL", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server?foo=bar&", layers: "someLayer" }); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const url = request.url; const questionMarkCount = url.match(/\?/g).length; expect(questionMarkCount).toEqual(1); expect(url).not.toContain("&&"); deferred.resolve(true); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); }); }); it("supports a query parameter at the end of the URL", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server?foo=bar", layers: "someLayer" }); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const url = request.url; const questionMarkCount = url.match(/\?/g).length; expect(questionMarkCount).toEqual(1); const uri = new import_urijs7.default(url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.foo).toEqual("bar"); deferred.resolve(true); }); provider.requestImage(0, 0, 0); expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); }); it("defaults WMS version to 1.1.1", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server?foo=bar", layers: "someLayer" }); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const url = request.url; const uri = new import_urijs7.default(url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.version).toEqual("1.1.1"); deferred.resolve(true); }); provider.requestImage(0, 0, 0); expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); }); it("requestImage returns a promise for an image and loads it for cross-origin use", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer" }); expect(provider.url).toEqual("made/up/wms/server"); expect(provider.layers).toEqual("someLayer"); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__666.GeographicTilingScheme); expect(provider.rectangle).toEqual(new import__666.GeographicTilingScheme().rectangle); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { import__666.Resource._DefaultImplementations.createImage( new import__666.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("requestImage requests tiles with SRS EPSG:3857 when tiling scheme is WebMercatorTilingScheme, WMS 1.1.1", function() { const tilingScheme = new import__666.WebMercatorTilingScheme(); const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", tilingScheme }); expect(provider.url).toEqual("made/up/wms/server"); expect(provider.layers).toEqual("someLayer"); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__666.WebMercatorTilingScheme); expect(provider.rectangle).toEqual(new import__666.WebMercatorTilingScheme().rectangle); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const uri = new import_urijs7.default(request.url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.srs).toEqual("EPSG:3857"); expect(params.version).toEqual("1.1.1"); const rect = tilingScheme.tileXYToNativeRectangle(0, 0, 0); expect(params.bbox).toEqual( `${rect.west},${rect.south},${rect.east},${rect.north}` ); import__666.Resource._DefaultImplementations.createImage( new import__666.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("requestImage requests tiles with CRS EPSG:3857 when tiling scheme is WebMercatorTilingScheme, WMS 1.3.0", function() { const tilingScheme = new import__666.WebMercatorTilingScheme(); const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", tilingScheme, parameters: { version: "1.3.0" } }); expect(provider.url).toEqual("made/up/wms/server"); expect(provider.layers).toEqual("someLayer"); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__666.WebMercatorTilingScheme); expect(provider.rectangle).toEqual(new import__666.WebMercatorTilingScheme().rectangle); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const uri = new import_urijs7.default(request.url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.crs).toEqual("EPSG:3857"); expect(params.version).toEqual("1.3.0"); const rect = tilingScheme.tileXYToNativeRectangle(0, 0, 0); expect(params.bbox).toEqual( `${rect.west},${rect.south},${rect.east},${rect.north}` ); import__666.Resource._DefaultImplementations.createImage( new import__666.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("requestImage requests tiles with SRS EPSG:4326 when tiling scheme is GeographicTilingScheme, WMS 1.1.1", function() { const tilingScheme = new import__666.GeographicTilingScheme(); const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", tilingScheme }); expect(provider.url).toEqual("made/up/wms/server"); expect(provider.layers).toEqual("someLayer"); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__666.GeographicTilingScheme); expect(provider.rectangle).toEqual(new import__666.GeographicTilingScheme().rectangle); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const uri = new import_urijs7.default(request.url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.srs).toEqual("EPSG:4326"); expect(params.version).toEqual("1.1.1"); const rect = tilingScheme.tileXYToNativeRectangle(0, 0, 0); expect(params.bbox).toEqual( `${rect.west},${rect.south},${rect.east},${rect.north}` ); import__666.Resource._DefaultImplementations.createImage( new import__666.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("requestImage requests tiles with SRS EPSG:4326 when tiling scheme is GeographicTilingScheme, WMS 1.1.0", function() { const tilingScheme = new import__666.GeographicTilingScheme(); const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", tilingScheme, parameters: { version: "1.1.0" } }); expect(provider.url).toEqual("made/up/wms/server"); expect(provider.layers).toEqual("someLayer"); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__666.GeographicTilingScheme); expect(provider.rectangle).toEqual(new import__666.GeographicTilingScheme().rectangle); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const uri = new import_urijs7.default(request.url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.srs).toEqual("EPSG:4326"); expect(params.version).toEqual("1.1.0"); const rect = tilingScheme.tileXYToNativeRectangle(0, 0, 0); expect(params.bbox).toEqual( `${rect.west},${rect.south},${rect.east},${rect.north}` ); import__666.Resource._DefaultImplementations.createImage( new import__666.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("requestImage requests tiles with CRS CRS:84 when tiling scheme is GeographicTilingScheme, WMS 1.3.0", function() { const tilingScheme = new import__666.GeographicTilingScheme(); const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", tilingScheme, parameters: { version: "1.3.0" } }); expect(provider.url).toEqual("made/up/wms/server"); expect(provider.layers).toEqual("someLayer"); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__666.GeographicTilingScheme); expect(provider.rectangle).toEqual(new import__666.GeographicTilingScheme().rectangle); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const uri = new import_urijs7.default(request.url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.crs).toEqual("CRS:84"); expect(params.version).toEqual("1.3.0"); const rect = tilingScheme.tileXYToNativeRectangle(0, 0, 0); expect(params.bbox).toEqual( `${rect.west},${rect.south},${rect.east},${rect.north}` ); import__666.Resource._DefaultImplementations.createImage( new import__666.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("requestImage requests tiles with CRS CRS:84 when tiling scheme is GeographicTilingScheme, WMS 1.3.1", function() { const tilingScheme = new import__666.GeographicTilingScheme(); const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", tilingScheme, parameters: { version: "1.3.1" } }); expect(provider.url).toEqual("made/up/wms/server"); expect(provider.layers).toEqual("someLayer"); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__666.GeographicTilingScheme); expect(provider.rectangle).toEqual(new import__666.GeographicTilingScheme().rectangle); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const uri = new import_urijs7.default(request.url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.crs).toEqual("CRS:84"); expect(params.version).toEqual("1.3.1"); const rect = tilingScheme.tileXYToNativeRectangle(0, 0, 0); expect(params.bbox).toEqual( `${rect.west},${rect.south},${rect.east},${rect.north}` ); import__666.Resource._DefaultImplementations.createImage( new import__666.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("does not treat parameter names as case sensitive", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server?foo=bar", layers: "someLayer", parameters: { FORMAT: "foo" } }); spyOn(import__666.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { const uri = new import_urijs7.default(request.url); const params = (0, import__666.queryToObject)(uri.query()); expect(params.format).toEqual("foo"); expect(params.format).not.toEqual("image/jpeg"); import__666.Resource._DefaultImplementations.createImage( new import__666.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__666.Resource._Implementations.createImage).toHaveBeenCalled(); }); }); it("turns the supplied credit into a logo", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server?foo=bar", layers: "someLayer" }); expect(provider.credit).toBeUndefined(); const providerWithCredit = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server?foo=bar", layers: "someLayer", credit: "Thanks to our awesome made up source of this imagery!" }); expect(providerWithCredit.credit).toBeDefined(); }); it("uses rectangle passed to constructor", function() { const rectangle = new import__666.Rectangle(0.1, 0.2, 0.3, 0.4); const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", rectangle }); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__666.GeographicTilingScheme); expect(provider.rectangle).toEqualEpsilon(rectangle, import__667.Math.EPSILON14); expect(provider.tileDiscardPolicy).toBeUndefined(); }); it("uses maximumLevel passed to constructor", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", maximumLevel: 5 }); expect(provider.maximumLevel).toEqual(5); }); it("uses minimumLevel passed to constructor", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", minimumLevel: 1 }); expect(provider.minimumLevel).toEqual(1); }); it("uses tilingScheme passed to constructor", function() { const tilingScheme = new import__666.WebMercatorTilingScheme(); const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", tilingScheme }); expect(provider.tilingScheme).toBe(tilingScheme); }); it("uses tileWidth passed to constructor", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", tileWidth: 123 }); expect(provider.tileWidth).toBe(123); }); it("uses tileHeight passed to constructor", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", tileWidth: 456 }); expect(provider.tileWidth).toBe(456); }); it("raises error event when image cannot be loaded", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer" }); const layer = new import__666.ImageryLayer(provider); let tries = 0; provider.errorEvent.addEventListener(function(error) { expect(error.timesRetried).toEqual(tries); ++tries; if (tries < 3) { error.retry = true; } setTimeout(function() { import__666.RequestScheduler.update(); }, 1); }); import__666.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { if (tries === 2) { import__666.Resource._DefaultImplementations.createImage( new import__666.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); } else { setTimeout(function() { deferred.reject(); }, 1); } }; const imagery = new import__666.Imagery(layer, 0, 0, 0); imagery.addReference(); layer._requestImagery(imagery); import__666.RequestScheduler.update(); return pollToPromise_default(function() { return imagery.state === import__666.ImageryState.RECEIVED; }).then(function() { expect(imagery.image).toBeImageOrImageBitmap(); expect(tries).toEqual(2); imagery.releaseReference(); }); }); describe("pickFeatures", function() { it("works with GeoJSON responses", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer" }); import__666.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toContain("GetFeatureInfo"); import__666.Resource._DefaultImplementations.loadWithXhr( "Data/WMS/GetFeatureInfo-GeoJSON.json", responseType, method, data, headers, deferred, overrideMimeType ); }; return provider.pickFeatures(0, 0, 0, 0.5, 0.5).then(function(pickResult) { expect(pickResult.length).toBe(1); const firstResult = pickResult[0]; expect(firstResult).toBeInstanceOf(import__666.ImageryLayerFeatureInfo); expect(firstResult.name).toBe("TOP TANK"); expect(firstResult.description).toContain("GEOSCIENCE AUSTRALIA"); expect(firstResult.position).toEqual( import__666.Cartographic.fromDegrees(145.91299, -30.19445) ); }); }); it("works with MapInfo MXP responses", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer" }); import__666.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toContain("GetFeatureInfo"); import__666.Resource._DefaultImplementations.loadWithXhr( "Data/WMS/GetFeatureInfo-MapInfoMXP.xml", responseType, method, data, headers, deferred, overrideMimeType ); }; return provider.pickFeatures(0, 0, 0, 0.5, 0.5).then(function(pickResult) { expect(pickResult.length).toBe(1); const firstResult = pickResult[0]; expect(firstResult).toBeInstanceOf(import__666.ImageryLayerFeatureInfo); expect(firstResult.name).toBe("SPRINGWOOD"); expect(firstResult.description).toContain("NSW"); }); }); it("works with Esri WMS responses", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer" }); import__666.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toContain("GetFeatureInfo"); import__666.Resource._DefaultImplementations.loadWithXhr( "Data/WMS/GetFeatureInfo-Esri.xml", responseType, method, data, headers, deferred, overrideMimeType ); }; return provider.pickFeatures(0, 0, 0, 0.5, 0.5).then(function(pickResult) { expect(pickResult.length).toBe(1); const firstResult = pickResult[0]; expect(firstResult).toBeInstanceOf(import__666.ImageryLayerFeatureInfo); expect(firstResult.name).toBe("Kyogle (A)"); expect(firstResult.description).toContain("New South Wales"); }); }); it("works with THREDDS XML format", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer" }); import__666.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toContain("GetFeatureInfo"); import__666.Resource._DefaultImplementations.loadWithXhr( "Data/WMS/GetFeatureInfo-THREDDS.xml", responseType, method, data, headers, deferred, overrideMimeType ); }; return provider.pickFeatures(0, 0, 0, 0.5, 0.5).then(function(pickResult) { expect(pickResult.length).toBe(1); const firstResult = pickResult[0]; expect(firstResult).toBeInstanceOf(import__666.ImageryLayerFeatureInfo); expect(+firstResult.properties.value).toBe(42); expect(firstResult.description).toContain("42"); }); }); it("works with msGMLOutput format", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer" }); import__666.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toContain("GetFeatureInfo"); import__666.Resource._DefaultImplementations.loadWithXhr( "Data/WMS/GetFeatureInfo-msGMLOutput.xml", responseType, method, data, headers, deferred, overrideMimeType ); }; return provider.pickFeatures(0, 0, 0, 0.5, 0.5).then(function(pickResult) { expect(pickResult.length).toBe(1); const firstResult = pickResult[0]; expect(firstResult).toBeInstanceOf(import__666.ImageryLayerFeatureInfo); expect(firstResult.name).toBe("Hovercraft"); expect(firstResult.description).toContain("Hovercraft"); }); }); it("works with unknown XML responses", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer" }); import__666.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toContain("GetFeatureInfo"); import__666.Resource._DefaultImplementations.loadWithXhr( "Data/WMS/GetFeatureInfo-Unknown.xml", responseType, method, data, headers, deferred, overrideMimeType ); }; return provider.pickFeatures(0, 0, 0, 0.5, 0.5).then(function(pickResult) { expect(pickResult.length).toBe(1); const firstResult = pickResult[0]; expect(firstResult).toBeInstanceOf(import__666.ImageryLayerFeatureInfo); expect(firstResult.name).toBeUndefined(); expect(firstResult.description).toContain("<FooFeature>"); }); }); it("resolves to undefined on a ServiceException", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer" }); import__666.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toContain("GetFeatureInfo"); import__666.Resource._DefaultImplementations.loadWithXhr( "Data/WMS/GetFeatureInfo-ServiceException.xml", responseType, method, data, headers, deferred, overrideMimeType ); }; return provider.pickFeatures(0, 0, 0, 0.5, 0.5).then(function(pickResult) { expect(pickResult).toBeUndefined(); }); }); it("returns undefined if list of feature info formats is empty", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", getFeatureInfoFormats: [] }); expect(provider.pickFeatures(0, 0, 0, 0.5, 0.5)).toBeUndefined(); }); it("returns undefined if enablePickFeatures is false", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", enablePickFeatures: false }); expect(provider.enablePickFeatures).toBe(false); expect(provider.pickFeatures(0, 0, 0, 0.5, 0.5)).toBeUndefined(); }); it("returns undefined if enablePickFeatures is set to false after initialization", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", enablePickFeatures: true }); provider.enablePickFeatures = false; expect(provider.enablePickFeatures).toBe(false); expect(provider.pickFeatures(0, 0, 0, 0.5, 0.5)).toBeUndefined(); }); it("does not return undefined if enablePickFeatures is set to true after initialization as false", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", enablePickFeatures: false }); provider.enablePickFeatures = true; expect(provider.enablePickFeatures).toBe(true); expect(provider.pickFeatures(0, 0, 0, 0.5, 0.5)).not.toBeUndefined(); }); it("requests XML exclusively if specified in getFeatureInfoFormats", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", getFeatureInfoFormats: [new import__666.GetFeatureInfoFormat("xml")] }); import__666.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toContain("GetFeatureInfo"); expect(url).not.toContain("json"); import__666.Resource._DefaultImplementations.loadWithXhr( "Data/WMS/GetFeatureInfo-MapInfoMXP.xml", responseType, method, data, headers, deferred, overrideMimeType ); }; return provider.pickFeatures(0, 0, 0, 0.5, 0.5).then(function(pickResult) { expect(pickResult.length).toBe(1); const firstResult = pickResult[0]; expect(firstResult).toBeInstanceOf(import__666.ImageryLayerFeatureInfo); expect(firstResult.name).toBe("SPRINGWOOD"); expect(firstResult.description).toContain("NSW"); }); }); it("requests GeoJSON exclusively if specified in getFeatureInfoFormats", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", getFeatureInfoFormats: [new import__666.GetFeatureInfoFormat("json")] }); import__666.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toContain("GetFeatureInfo"); if (url.indexOf("json") >= 0) { deferred.reject(); } else { import__666.Resource._DefaultImplementations.loadWithXhr( "Data/WMS/GetFeatureInfo-MapInfoMXP.xml", responseType, method, data, headers, deferred, overrideMimeType ); } }; return provider.pickFeatures(0, 0, 0, 0.5, 0.5).then(function(features) { expect(features.length).toBe(0); }).catch(function() { }); }); it("generates correct getFeatureInfo link, WMS 1.1.1, version in getFeatureInfoParameters", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", getFeatureInfoParameters: { version: "1.1.1" } }); import__666.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toContain("GetFeatureInfo"); expect(url).toContain("1.1.1"); expect(url).not.toContain("1.3.0"); expect(url).toContain("&x="); expect(url).toContain("&y="); expect(url).not.toContain("&i="); expect(url).not.toContain("&j="); import__666.Resource._DefaultImplementations.loadWithXhr( "Data/WMS/GetFeatureInfo-MapInfoMXP.xml", responseType, method, data, headers, deferred, overrideMimeType ); }; return provider.pickFeatures(0, 0, 0, 0.5, 0.5); }); it("generates correct getFeatureInfo link, WMS 1.3.0, version in getFeatureInfoParameters", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", getFeatureInfoParameters: { version: "1.3.0" } }); import__666.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toContain("GetFeatureInfo"); expect(url).not.toContain("1.1.1"); expect(url).toContain("1.3.0"); expect(url).not.toContain("&x="); expect(url).not.toContain("&y="); expect(url).toContain("&i="); expect(url).toContain("&j="); import__666.Resource._DefaultImplementations.loadWithXhr( "Data/WMS/GetFeatureInfo-MapInfoMXP.xml", responseType, method, data, headers, deferred, overrideMimeType ); }; return provider.pickFeatures(0, 0, 0, 0.5, 0.5); }); it("generates correct getFeatureInfo link, WMS 1.1.1, default version", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer" }); import__666.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toContain("GetFeatureInfo"); expect(url).toContain("1.1.1"); expect(url).not.toContain("1.3.0"); expect(url).toContain("&x="); expect(url).toContain("&y="); expect(url).not.toContain("&i="); expect(url).not.toContain("&j="); import__666.Resource._DefaultImplementations.loadWithXhr( "Data/WMS/GetFeatureInfo-MapInfoMXP.xml", responseType, method, data, headers, deferred, overrideMimeType ); }; return provider.pickFeatures(0, 0, 0, 0.5, 0.5); }); it("uses custom GetFeatureInfo handling function if specified", function() { function fooProcessor(response) { const json = JSON.parse(response); expect(json.custom).toBe(true); const feature = new import__666.ImageryLayerFeatureInfo(); feature.name = "Foo processed!"; return [feature]; } const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", getFeatureInfoFormats: [ new import__666.GetFeatureInfoFormat("foo", "application/foo", fooProcessor) ] }); import__666.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toContain("GetFeatureInfo"); if (url.indexOf(encodeURIComponent("application/foo")) < 0) { deferred.reject(); } return import__666.Resource._DefaultImplementations.loadWithXhr( "Data/WMS/GetFeatureInfo-Custom.json", responseType, method, data, headers, deferred, overrideMimeType ); }; return provider.pickFeatures(0, 0, 0, 0.5, 0.5).then(function(features) { expect(features.length).toBe(1); expect(features[0].name).toEqual("Foo processed!"); }); }); it("works with HTML response", function() { const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer" }); import__666.Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(url).toContain("GetFeatureInfo"); if (url.indexOf(encodeURIComponent("text/html")) < 0) { deferred.reject(); } import__666.Resource._DefaultImplementations.loadWithXhr( "Data/WMS/GetFeatureInfo.html", responseType, method, data, headers, deferred, overrideMimeType ); }; return provider.pickFeatures(0, 0, 0, 0.5, 0.5).then(function(pickResult) { expect(pickResult.length).toBe(1); const firstResult = pickResult[0]; expect(firstResult).toBeInstanceOf(import__666.ImageryLayerFeatureInfo); expect(firstResult.name).toBe("HTML yeah!"); expect(firstResult.description).toContain("great information"); }); }); }); describe("verifyClockTimes", function() { it("requires clock if times is specified", function() { function createWithoutClock() { return new import__666.WebMapServiceImageryProvider({ layers: "someLayer", url: "http://wms.invalid/", times: new import__666.TimeIntervalCollection() }); } expect(createWithoutClock).toThrowDeveloperError(); }); it("tiles preload on requestImage as we approach the next time interval", function() { const times = import__666.TimeIntervalCollection.fromIso8601({ iso8601: "2017-04-26/2017-04-30/P1D", dataCallback: function(interval, index) { return { Time: import__666.JulianDate.toIso8601(interval.start) }; } }); const clock = new import__666.Clock({ currentTime: import__666.JulianDate.fromIso8601("2017-04-26"), shouldAnimate: true }); const provider = new import__666.WebMapServiceImageryProvider({ layers: "someLayer", style: "someStyle", url: "http://wms.invalid/", clock, times }); import__666.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { import__666.Resource._DefaultImplementations.createImage( new import__666.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }; let entry; clock.currentTime = import__666.JulianDate.fromIso8601("2017-04-26T23:59:56Z"); return provider.requestImage(0, 0, 0, new import__666.Request()).then(function() { import__666.RequestScheduler.update(); const cache = provider._timeDynamicImagery._tileCache; expect(cache["1"]).toBeDefined(); entry = cache["1"]["0-0-0"]; expect(entry).toBeDefined(); expect(entry.promise).toBeDefined(); return entry.promise; }).then(function() { expect(entry.request).toBeDefined(); expect(entry.request.state).toEqual(import__666.RequestState.RECEIVED); }); }); it("tiles preload onTick event as we approach the next time interval", function() { const times = import__666.TimeIntervalCollection.fromIso8601({ iso8601: "2017-04-26/2017-04-30/P1D", dataCallback: function(interval, index) { return { Time: import__666.JulianDate.toIso8601(interval.start) }; } }); const clock = new import__666.Clock({ currentTime: import__666.JulianDate.fromIso8601("2017-04-26"), shouldAnimate: true }); const provider = new import__666.WebMapServiceImageryProvider({ layers: "someLayer", style: "someStyle", url: "http://wms.invalid/", clock, times }); import__666.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { import__666.Resource._DefaultImplementations.createImage( new import__666.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }; let entry; return provider.requestImage(0, 0, 0, new import__666.Request()).then(function() { const cache = provider._timeDynamicImagery._tileCache; expect(cache["1"]).toBeUndefined(); clock.currentTime = import__666.JulianDate.fromIso8601("2017-04-26T23:59:55Z"); clock.tick(); import__666.RequestScheduler.update(); expect(cache["1"]).toBeDefined(); entry = cache["1"]["0-0-0"]; expect(entry).toBeDefined(); expect(entry.promise).toBeDefined(); return entry.promise; }).then(function() { expect(entry.request).toBeDefined(); expect(entry.request.state).toEqual(import__666.RequestState.RECEIVED); }); }); it("reload is called once we cross into next interval", function() { const times = import__666.TimeIntervalCollection.fromIso8601({ iso8601: "2017-04-26/2017-04-30/P1D", dataCallback: function(interval, index) { return { Time: import__666.JulianDate.toIso8601(interval.start) }; } }); const clock = new import__666.Clock({ currentTime: import__666.JulianDate.fromIso8601("2017-04-26"), clockStep: import__666.ClockStep.TICK_DEPENDENT, shouldAnimate: true }); import__666.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { import__666.Resource._DefaultImplementations.createImage( new import__666.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }; const provider = new import__666.WebMapServiceImageryProvider({ layers: "someLayer", style: "someStyle", url: "http://wms.invalid/", clock, times }); provider._reload = jasmine.createSpy(); spyOn(provider._timeDynamicImagery, "getFromCache").and.callThrough(); clock.currentTime = import__666.JulianDate.fromIso8601("2017-04-26T23:59:59Z"); return provider.requestImage(0, 0, 0, new import__666.Request()).then(function() { import__666.RequestScheduler.update(); clock.tick(); return provider.requestImage(0, 0, 0, new import__666.Request()); }).then(function() { expect(provider._reload.calls.count()).toEqual(1); const calls = provider._timeDynamicImagery.getFromCache.calls.all(); expect(calls.length).toBe(2); expect(calls[0].returnValue).toBeUndefined(); expect(calls[1].returnValue).toBeDefined(); }); }); it("Data in request comes from the time interval collection", function() { const times = import__666.TimeIntervalCollection.fromIso8601({ iso8601: "2017-04-26/2017-04-30/P1D", dataCallback: function(interval, index) { return { Time: import__666.JulianDate.toIso8601(interval.start), Test: "testValue" }; } }); const clock = new import__666.Clock({ currentTime: import__666.JulianDate.fromIso8601("2017-04-26"), clockStep: import__666.ClockStep.TICK_DEPENDENT, shouldAnimate: false }); import__666.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { import__666.Resource._DefaultImplementations.createImage( new import__666.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }; const provider = new import__666.WebMapServiceImageryProvider({ layers: "someLayer", style: "someStyle", url: "http://wms.invalid/", clock, times }); provider._reload = jasmine.createSpy(); spyOn(provider._timeDynamicImagery, "getFromCache").and.callThrough(); return provider.requestImage(0, 0, 0, new import__666.Request()).then(function() { const queryParameters = provider._tileProvider._resource.queryParameters; expect(queryParameters.Time).toEqual("2017-04-26T00:00:00Z"); expect(queryParameters.Test).toEqual("testValue"); }); }); }); it("uses getFeatureInfoUrl in options for getting the getFeatureInfo URL", function() { const featureUrl = "made/up/wms/feature/server"; const provider = new import__666.WebMapServiceImageryProvider({ url: "made/up/wms/server", layers: "someLayer", getFeatureInfoUrl: featureUrl }); expect(provider._pickFeaturesResource.url).toContain(featureUrl); }); it("uses url in options if getFeatureInfoUrl is absent for pickResources", function() { const featureUrl = "made/up/wms/feature/server"; const getCapabilitiesUrl = "made/up/wms/server"; const provider = new import__666.WebMapServiceImageryProvider({ url: getCapabilitiesUrl, layers: "someLayer" }); expect(provider._pickFeaturesResource.url).not.toContain(featureUrl); expect(provider._pickFeaturesResource.url).toContain(getCapabilitiesUrl); }); }); // packages/engine/Specs/Scene/WebMapTileServiceImageryProviderSpec.js var import_urijs8 = __toESM(require_URI(), 1); var import__668 = __toESM(require_Cesium(), 1); describe("Scene/WebMapTileServiceImageryProvider", function() { beforeEach(function() { import__668.RequestScheduler.clearForSpecs(); }); afterEach(function() { import__668.Resource._Implementations.createImage = import__668.Resource._DefaultImplementations.createImage; }); it("conforms to ImageryProvider interface", function() { expect(import__668.WebMapTileServiceImageryProvider).toConformToInterface( import__668.ImageryProvider ); }); it("generates expected tile urls", function() { const options = { url: "http://wmts.invalid", format: "image/png", layer: "someLayer", style: "someStyle", tileMatrixSetID: "someTMS", tileMatrixLabels: ["first", "second", "third"] }; const provider = new import__668.WebMapTileServiceImageryProvider(options); spyOn(import__668.ImageryProvider, "loadImage"); let tilecol = 12; let tilerow = 5; let level = 1; provider.requestImage(tilecol, tilerow, level); let uri = new import_urijs8.default(import__668.ImageryProvider.loadImage.calls.mostRecent().args[1].url); let queryObject = (0, import__668.queryToObject)(uri.query()); expect(queryObject.request).toEqual("GetTile"); expect(queryObject.service).toEqual("WMTS"); expect(queryObject.version).toEqual("1.0.0"); expect(queryObject.format).toEqual(options.format); expect(queryObject.layer).toEqual(options.layer); expect(queryObject.style).toEqual(options.style); expect(parseInt(queryObject.tilecol, 10)).toEqual(tilecol); expect(queryObject.tilematrixset).toEqual(options.tileMatrixSetID); expect(queryObject.tilematrix).toEqual(options.tileMatrixLabels[level]); expect(parseInt(queryObject.tilerow, 10)).toEqual(tilerow); tilecol = 1; tilerow = 3; level = 2; provider.requestImage(tilecol, tilerow, level); uri = new import_urijs8.default(import__668.ImageryProvider.loadImage.calls.mostRecent().args[1].url); queryObject = (0, import__668.queryToObject)(uri.query()); expect(queryObject.request).toEqual("GetTile"); expect(queryObject.service).toEqual("WMTS"); expect(queryObject.version).toEqual("1.0.0"); expect(queryObject.format).toEqual(options.format); expect(queryObject.layer).toEqual(options.layer); expect(queryObject.style).toEqual(options.style); expect(parseInt(queryObject.tilecol, 10)).toEqual(tilecol); expect(queryObject.tilematrixset).toEqual(options.tileMatrixSetID); expect(queryObject.tilematrix).toEqual(options.tileMatrixLabels[level]); expect(parseInt(queryObject.tilerow, 10)).toEqual(tilerow); }); it("generates expected tile urls for subdomains", function() { const options = { url: "http://wmts{s}.invalid", format: "image/png", layer: "someLayer", style: "someStyle", tileMatrixSetID: "someTMS", tileMatrixLabels: ["first", "second", "third"] }; const provider = new import__668.WebMapTileServiceImageryProvider(options); spyOn(import__668.ImageryProvider, "loadImage"); let tilecol = 12; let tilerow = 5; let level = 1; provider.requestImage(tilecol, tilerow, level); let uri = new import_urijs8.default(import__668.ImageryProvider.loadImage.calls.mostRecent().args[1].url); let queryObject = (0, import__668.queryToObject)(uri.query()); expect(queryObject.request).toEqual("GetTile"); expect(queryObject.service).toEqual("WMTS"); expect(queryObject.version).toEqual("1.0.0"); expect(queryObject.format).toEqual(options.format); expect(queryObject.layer).toEqual(options.layer); expect(queryObject.style).toEqual(options.style); expect(parseInt(queryObject.tilecol, 10)).toEqual(tilecol); expect(queryObject.tilematrixset).toEqual(options.tileMatrixSetID); expect(queryObject.tilematrix).toEqual(options.tileMatrixLabels[level]); expect(parseInt(queryObject.tilerow, 10)).toEqual(tilerow); expect(uri.authority()).toEqual("wmtsa.invalid"); tilecol = 2; tilerow = 3; level = 2; provider.requestImage(tilecol, tilerow, level); uri = new import_urijs8.default(import__668.ImageryProvider.loadImage.calls.mostRecent().args[1].url); queryObject = (0, import__668.queryToObject)(uri.query()); expect(queryObject.request).toEqual("GetTile"); expect(queryObject.service).toEqual("WMTS"); expect(queryObject.version).toEqual("1.0.0"); expect(queryObject.format).toEqual(options.format); expect(queryObject.layer).toEqual(options.layer); expect(queryObject.style).toEqual(options.style); expect(parseInt(queryObject.tilecol, 10)).toEqual(tilecol); expect(queryObject.tilematrixset).toEqual(options.tileMatrixSetID); expect(queryObject.tilematrix).toEqual(options.tileMatrixLabels[level]); expect(parseInt(queryObject.tilerow, 10)).toEqual(tilerow); expect(uri.authority()).toEqual("wmtsb.invalid"); }); it("supports subdomains string urls", function() { const options = { url: "{s}", layer: "", style: "", subdomains: "123", tileMatrixSetID: "" }; const provider = new import__668.WebMapTileServiceImageryProvider(options); spyOn(import__668.ImageryProvider, "loadImage"); const tilecol = 1; const tilerow = 1; const level = 1; provider.requestImage(tilecol, tilerow, level); const url = import__668.ImageryProvider.loadImage.calls.mostRecent().args[1].getUrlComponent(); expect("123".indexOf(url)).toBeGreaterThanOrEqual(0); }); it("supports subdomains array urls", function() { const options = { url: "{s}", layer: "", style: "", subdomains: ["foo", "bar"], tileMatrixSetID: "" }; const provider = new import__668.WebMapTileServiceImageryProvider(options); spyOn(import__668.ImageryProvider, "loadImage"); const tilecol = 1; const tilerow = 1; const level = 1; provider.requestImage(tilecol, tilerow, level); const url = import__668.ImageryProvider.loadImage.calls.mostRecent().args[1].getUrlComponent(); expect(["foo", "bar"].indexOf(url)).toBeGreaterThanOrEqual(0); }); it("generates expected tile urls from template", function() { const options = { url: "http://wmts.invalid/{style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png", format: "image/png", layer: "someLayer", style: "someStyle", tileMatrixSetID: "someTMS", tileMatrixLabels: ["first", "second", "third"] }; const provider = new import__668.WebMapTileServiceImageryProvider(options); spyOn(import__668.ImageryProvider, "loadImage"); const tilecol = 12; const tilerow = 5; const level = 1; provider.requestImage(tilecol, tilerow, level); const uri = new import_urijs8.default( import__668.ImageryProvider.loadImage.calls.mostRecent().args[1].getUrlComponent() ); expect(uri.toString()).toEqual( "http://wmts.invalid/someStyle/someTMS/second/5/12.png" ); }); it("requires the url to be specified", function() { function createWithoutUrl() { return new import__668.WebMapTileServiceImageryProvider({ layer: "someLayer", style: "someStyle", tileMatrixSetID: "someTMS" }); } expect(createWithoutUrl).toThrowDeveloperError(); }); it("requires the layer to be specified", function() { function createWithoutLayer() { return new import__668.WebMapTileServiceImageryProvider({ url: "http://wmts.invalid", style: "someStyle", tileMatrixSetID: "someTMS" }); } expect(createWithoutLayer).toThrowDeveloperError(); }); it("requires the style to be specified", function() { function createWithoutStyle() { return new import__668.WebMapTileServiceImageryProvider({ layer: "someLayer", url: "http://wmts.invalid", tileMatrixSetID: "someTMS" }); } expect(createWithoutStyle).toThrowDeveloperError(); }); it("requires the tileMatrixSetID to be specified", function() { function createWithoutTMS() { return new import__668.WebMapTileServiceImageryProvider({ layer: "someLayer", style: "someStyle", url: "http://wmts.invalid" }); } expect(createWithoutTMS).toThrowDeveloperError(); }); it("requires clock if times is specified", function() { function createWithoutClock() { return new import__668.WebMapTileServiceImageryProvider({ layer: "someLayer", style: "someStyle", url: "http://wmts.invalid", tileMatrixSetID: "someTMS", times: new import__668.TimeIntervalCollection() }); } expect(createWithoutClock).toThrowDeveloperError(); }); it("uses default values for undefined parameters", function() { const provider = new import__668.WebMapTileServiceImageryProvider({ layer: "someLayer", style: "someStyle", url: "http://wmts.invalid", tileMatrixSetID: "someTMS" }); expect(provider.format).toEqual("image/jpeg"); expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.minimumLevel).toEqual(0); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(import__668.WebMercatorTilingScheme); expect(provider.rectangle).toEqual(provider.tilingScheme.rectangle); expect(provider.credit).toBeUndefined(); expect(provider.proxy).toBeUndefined(); }); it("uses parameters passed to constructor", function() { const tilingScheme = new import__668.GeographicTilingScheme(); const rectangle = new import__668.WebMercatorTilingScheme().rectangle; const provider = new import__668.WebMapTileServiceImageryProvider({ layer: "someLayer", style: "someStyle", url: "http://wmts.invalid", tileMatrixSetID: "someTMS", format: "someFormat", tileWidth: 512, tileHeight: 512, tilingScheme, minimumLevel: 0, maximumLevel: 12, rectangle, credit: "Thanks for using our WMTS server." }); expect(provider.format).toEqual("someFormat"); expect(provider.tileWidth).toEqual(512); expect(provider.tileHeight).toEqual(512); expect(provider.minimumLevel).toEqual(0); expect(provider.maximumLevel).toEqual(12); expect(provider.tilingScheme).toEqual(tilingScheme); expect(provider.credit).toBeDefined(); expect(provider.credit).toBeInstanceOf(import__668.Credit); expect(provider.rectangle).toEqual(rectangle); }); it("doesn't care about trailing question mark at the end of URL", function() { const provider1 = new import__668.WebMapTileServiceImageryProvider({ layer: "someLayer", style: "someStyle", url: "http://wmts.invalid", tileMatrixSetID: "someTMS" }); const provider2 = new import__668.WebMapTileServiceImageryProvider({ layer: "someLayer", style: "someStyle", url: "http://wmts.invalid?", tileMatrixSetID: "someTMS" }); spyOn(import__668.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { import__668.Resource._DefaultImplementations.createImage( new import__668.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider1.requestImage(0, 0, 0).then(function(image) { return provider2.requestImage(0, 0, 0).then(function(image2) { expect(import__668.Resource._Implementations.createImage.calls.count()).toEqual(2); const allCalls = import__668.Resource._Implementations.createImage.calls.all(); expect(allCalls[1].args[0].url).toEqual(allCalls[0].args[0].url); }); }); }); it("requestImage returns a promise for an image and loads it for cross-origin use", function() { const provider = new import__668.WebMapTileServiceImageryProvider({ layer: "someLayer", style: "someStyle", url: "http://wmts.invalid", tileMatrixSetID: "someTMS" }); spyOn(import__668.Resource._Implementations, "createImage").and.callFake(function(request, crossOrigin, deferred) { import__668.Resource._DefaultImplementations.createImage( new import__668.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }); return provider.requestImage(0, 0, 0).then(function(image) { expect(import__668.Resource._Implementations.createImage).toHaveBeenCalled(); expect(image).toBeImageOrImageBitmap(); }); }); it("raises error event when image cannot be loaded", function() { const provider = new import__668.WebMapTileServiceImageryProvider({ layer: "someLayer", style: "someStyle", url: "http://wmts.invalid", tileMatrixSetID: "someTMS" }); const layer = new import__668.ImageryLayer(provider); let tries = 0; provider.errorEvent.addEventListener(function(error) { expect(error.timesRetried).toEqual(tries); ++tries; if (tries < 3) { error.retry = true; } setTimeout(function() { import__668.RequestScheduler.update(); }, 1); }); import__668.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { if (tries === 2) { import__668.Resource._DefaultImplementations.createImage( new import__668.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); } else { setTimeout(function() { deferred.reject(); }, 1); } }; const imagery = new import__668.Imagery(layer, 0, 0, 0); imagery.addReference(); layer._requestImagery(imagery); import__668.RequestScheduler.update(); return pollToPromise_default(function() { return imagery.state === import__668.ImageryState.RECEIVED; }).then(function() { expect(imagery.image).toBeImageOrImageBitmap(); expect(tries).toEqual(2); imagery.releaseReference(); }); }); it("tiles preload on requestImage as we approach the next time interval", function() { const times = import__668.TimeIntervalCollection.fromIso8601({ iso8601: "2017-04-26/2017-04-30/P1D", dataCallback: function(interval, index) { return { Time: import__668.JulianDate.toIso8601(interval.start) }; } }); const clock = new import__668.Clock({ currentTime: import__668.JulianDate.fromIso8601("2017-04-26"), shouldAnimate: true }); const provider = new import__668.WebMapTileServiceImageryProvider({ layer: "someLayer", style: "someStyle", url: "http://wmts.invalid/{Time}", tileMatrixSetID: "someTMS", clock, times }); import__668.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { import__668.Resource._DefaultImplementations.createImage( new import__668.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }; let entry; clock.currentTime = import__668.JulianDate.fromIso8601("2017-04-26T23:59:56Z"); return provider.requestImage(0, 0, 0, new import__668.Request()).then(function() { import__668.RequestScheduler.update(); const cache = provider._timeDynamicImagery._tileCache; expect(cache["1"]).toBeDefined(); entry = cache["1"]["0-0-0"]; expect(entry).toBeDefined(); expect(entry.promise).toBeDefined(); return entry.promise; }).then(function() { expect(entry.request).toBeDefined(); expect(entry.request.state).toEqual(import__668.RequestState.RECEIVED); }); }); it("tiles preload onTick event as we approach the next time interval", function() { const times = import__668.TimeIntervalCollection.fromIso8601({ iso8601: "2017-04-26/2017-04-30/P1D", dataCallback: function(interval, index) { return { Time: import__668.JulianDate.toIso8601(interval.start) }; } }); const clock = new import__668.Clock({ currentTime: import__668.JulianDate.fromIso8601("2017-04-26"), shouldAnimate: true }); const provider = new import__668.WebMapTileServiceImageryProvider({ layer: "someLayer", style: "someStyle", url: "http://wmts.invalid/{Time}", tileMatrixSetID: "someTMS", clock, times }); import__668.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { import__668.Resource._DefaultImplementations.createImage( new import__668.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }; let entry; return provider.requestImage(0, 0, 0, new import__668.Request()).then(function() { const cache = provider._timeDynamicImagery._tileCache; expect(cache["1"]).toBeUndefined(); clock.currentTime = import__668.JulianDate.fromIso8601("2017-04-26T23:59:55Z"); clock.tick(); import__668.RequestScheduler.update(); expect(cache["1"]).toBeDefined(); entry = cache["1"]["0-0-0"]; expect(entry).toBeDefined(); expect(entry.promise).toBeDefined(); return entry.promise; }).then(function() { expect(entry.request).toBeDefined(); expect(entry.request.state).toEqual(import__668.RequestState.RECEIVED); }); }); it("reload is called once we cross into next interval", function() { const times = import__668.TimeIntervalCollection.fromIso8601({ iso8601: "2017-04-26/2017-04-30/P1D", dataCallback: function(interval, index) { return { Time: import__668.JulianDate.toIso8601(interval.start) }; } }); const clock = new import__668.Clock({ currentTime: import__668.JulianDate.fromIso8601("2017-04-26"), clockStep: import__668.ClockStep.TICK_DEPENDENT, shouldAnimate: true }); import__668.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { import__668.Resource._DefaultImplementations.createImage( new import__668.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }; const provider = new import__668.WebMapTileServiceImageryProvider({ layer: "someLayer", style: "someStyle", url: "http://wmts.invalid/{Time}", tileMatrixSetID: "someTMS", clock, times }); provider._reload = jasmine.createSpy(); spyOn(provider._timeDynamicImagery, "getFromCache").and.callThrough(); clock.currentTime = import__668.JulianDate.fromIso8601("2017-04-26T23:59:59Z"); return provider.requestImage(0, 0, 0, new import__668.Request()).then(function() { import__668.RequestScheduler.update(); clock.tick(); return provider.requestImage(0, 0, 0, new import__668.Request()); }).then(function() { expect(provider._reload.calls.count()).toEqual(1); const calls = provider._timeDynamicImagery.getFromCache.calls.all(); expect(calls.length).toBe(2); expect(calls[0].returnValue).toBeUndefined(); expect(calls[1].returnValue).toBeDefined(); }); }); it("dimensions work with RESTful requests", function() { let lastUrl; import__668.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { lastUrl = request.url; import__668.Resource._DefaultImplementations.createImage( new import__668.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }; const provider = new import__668.WebMapTileServiceImageryProvider({ layer: "someLayer", style: "someStyle", url: "http://wmts.invalid/{FOO}", tileMatrixSetID: "someTMS", dimensions: { FOO: "BAR" } }); provider._reload = jasmine.createSpy(); return provider.requestImage(0, 0, 0, new import__668.Request()).then(function() { expect(lastUrl).toStartWith("http://wmts.invalid/BAR"); expect(provider._reload.calls.count()).toEqual(0); provider.dimensions = { FOO: "BAZ" }; expect(provider._reload.calls.count()).toEqual(1); return provider.requestImage(0, 0, 0, new import__668.Request()); }).then(function() { expect(lastUrl).toStartWith("http://wmts.invalid/BAZ"); }); }); it("dimensions work with KVP requests", function() { let lastUrl; import__668.Resource._Implementations.createImage = function(request, crossOrigin, deferred) { lastUrl = request.url; import__668.Resource._DefaultImplementations.createImage( new import__668.Request({ url: "Data/Images/Red16x16.png" }), crossOrigin, deferred ); }; const uri = new import_urijs8.default("http://wmts.invalid/kvp"); const query = { tilematrix: 0, layer: "someLayer", style: "someStyle", tilerow: 0, tilecol: 0, tilematrixset: "someTMS", format: "image/jpeg", FOO: "BAR", service: "WMTS", version: "1.0.0", request: "GetTile" }; const provider = new import__668.WebMapTileServiceImageryProvider({ layer: query.layer, style: query.style, url: uri.toString(), tileMatrixSetID: query.tilematrixset, dimensions: { FOO: query.FOO } }); provider._reload = jasmine.createSpy(); return provider.requestImage(0, 0, 0, new import__668.Request()).then(function() { uri.query((0, import__668.objectToQuery)(query)); expect(lastUrl).toEqual(uri.toString()); expect(provider._reload.calls.count()).toEqual(0); query.FOO = "BAZ"; provider.dimensions = { FOO: query.FOO }; expect(provider._reload.calls.count()).toEqual(1); return provider.requestImage(0, 0, 0, new import__668.Request()); }).then(function() { uri.query((0, import__668.objectToQuery)(query)); expect(lastUrl).toEqual(uri.toString()); }); }); }); // packages/engine/Specs/Scene/buildVoxelDrawCommandsSpec.js var import__669 = __toESM(require_Cesium(), 1); describe("Scene/buildVoxelDrawCommands", function() { let scene2; let provider; beforeAll(async function() { scene2 = createScene_default(); provider = await import__669.Cesium3DTilesVoxelProvider.fromUrl( "./Data/Cesium3DTiles/Voxel/VoxelEllipsoid3DTiles/tileset.json" ); }); afterAll(function() { scene2.destroyForSpecs(); }); it("sets up basic voxel draw commands", function() { const primitive = new import__669.VoxelPrimitive({ provider }); primitive.update(scene2.frameState); (0, import__669.buildVoxelDrawCommands)(primitive, scene2.context); expect(primitive._drawCommand).toBeDefined(); expect(primitive._drawCommandPick).toBeDefined(); }); it("adds clipping function for primitive with clipping planes", function() { const primitive = new import__669.VoxelPrimitive({ provider }); const planes = [ new import__669.ClippingPlane(import__669.Cartesian3.UNIT_X, 1), new import__669.ClippingPlane(import__669.Cartesian3.UNIT_Y, 2) ]; primitive.clippingPlanes = new import__669.ClippingPlaneCollection({ planes }); primitive.update(scene2.frameState); (0, import__669.buildVoxelDrawCommands)(primitive, scene2.context); const { shaderProgram } = primitive._drawCommand; const fragmentShaderText = shaderProgram._fragmentShaderText; const clippingFunctionSignature = "vec4 getClippingPlane(highp sampler2D packedClippingPlanes, int clippingPlaneNumber, mat4 transform)"; expect(fragmentShaderText.includes(clippingFunctionSignature)).toBe(true); }); }); // packages/engine/Specs/Scene/computeFlyToLocationForRectangleSpec.js var import__670 = __toESM(require_Cesium(), 1); describe("Scene/computeFlyToLocationForRectangle", function() { let scene2; beforeEach(function() { scene2 = createScene_default(); }); afterEach(function() { scene2.destroyForSpecs(); }); function sampleTest(sceneMode) { const terrainProvider = new MockTerrainProvider_default(); terrainProvider.availability = {}; scene2.globe = new import__670.Globe(); scene2.terrainProvider = terrainProvider; scene2.mode = sceneMode; const rectangle = new import__670.Rectangle(0.2, 0.4, 0.6, 0.8); const cartographics = [ import__670.Rectangle.center(rectangle), import__670.Rectangle.southeast(rectangle), import__670.Rectangle.southwest(rectangle), import__670.Rectangle.northeast(rectangle), import__670.Rectangle.northwest(rectangle) ]; const maxHeight = 1234; const sampledResults = [ import__670.Rectangle.center(rectangle), import__670.Rectangle.southeast(rectangle), import__670.Rectangle.southwest(rectangle), import__670.Rectangle.northeast(rectangle), import__670.Rectangle.northwest(rectangle) ]; sampledResults[0].height = 145; sampledResults[1].height = 1211; sampledResults[2].height = -123; sampledResults[3].height = maxHeight; spyOn( import__670.computeFlyToLocationForRectangle, "_sampleTerrainMostDetailed" ).and.returnValue(Promise.resolve(sampledResults)); let expectedResult; if (sceneMode === import__670.SceneMode.SCENE3D) { expectedResult = scene2.mapProjection.ellipsoid.cartesianToCartographic( scene2.camera.getRectangleCameraCoordinates(rectangle) ); } else { expectedResult = scene2.mapProjection.unproject( scene2.camera.getRectangleCameraCoordinates(rectangle) ); } expectedResult.height += maxHeight; return (0, import__670.computeFlyToLocationForRectangle)(rectangle, scene2).then(function(result) { expect(result).toEqual(expectedResult); expect( import__670.computeFlyToLocationForRectangle._sampleTerrainMostDetailed ).toHaveBeenCalledWith(terrainProvider, cartographics); }); } it("samples terrain and returns expected result in 3D", function() { return sampleTest(import__670.SceneMode.SCENE3D); }); it("samples terrain and returns expected result in CV", function() { return sampleTest(import__670.SceneMode.COLUMBUS_VIEW); }); it("returns height above ellipsoid when in 2D", function() { const terrainProvider = new MockTerrainProvider_default(); terrainProvider.availability = {}; scene2.globe = new import__670.Globe(); scene2.terrainProvider = terrainProvider; scene2.mode = import__670.SceneMode.SCENE2D; const rectangle = new import__670.Rectangle(0.2, 0.4, 0.6, 0.8); const expectedResult = scene2.mapProjection.unproject( scene2.camera.getRectangleCameraCoordinates(rectangle) ); spyOn(import__670.computeFlyToLocationForRectangle, "_sampleTerrainMostDetailed"); return (0, import__670.computeFlyToLocationForRectangle)(rectangle, scene2).then(function(result) { expect(result).toEqual(expectedResult); expect( import__670.computeFlyToLocationForRectangle._sampleTerrainMostDetailed ).not.toHaveBeenCalled(); }); }); it("returns height above ellipsoid when terrain not available", function() { scene2.globe = new import__670.Globe(); scene2.terrainProvider = new MockTerrainProvider_default(); const rectangle = new import__670.Rectangle(0.2, 0.4, 0.6, 0.8); spyOn(import__670.computeFlyToLocationForRectangle, "_sampleTerrainMostDetailed"); const expectedResult = scene2.mapProjection.ellipsoid.cartesianToCartographic( scene2.camera.getRectangleCameraCoordinates(rectangle) ); return (0, import__670.computeFlyToLocationForRectangle)(rectangle, scene2).then(function(result) { expect(result).toEqual(expectedResult); expect( import__670.computeFlyToLocationForRectangle._sampleTerrainMostDetailed ).not.toHaveBeenCalled(); }); }); it("returns height above ellipsoid when terrain undefined", function() { scene2.terrainProvider = void 0; const rectangle = new import__670.Rectangle(0.2, 0.4, 0.6, 0.8); spyOn(import__670.computeFlyToLocationForRectangle, "_sampleTerrainMostDetailed"); const expectedResult = scene2.mapProjection.ellipsoid.cartesianToCartographic( scene2.camera.getRectangleCameraCoordinates(rectangle) ); return (0, import__670.computeFlyToLocationForRectangle)(rectangle, scene2).then(function(result) { expect(result).toEqual(expectedResult); expect( import__670.computeFlyToLocationForRectangle._sampleTerrainMostDetailed ).not.toHaveBeenCalled(); }); }); }); // packages/engine/Specs/Scene/createElevationBandMaterialSpec.js var import__671 = __toESM(require_Cesium(), 1); var import__672 = __toESM(require_Cesium(), 1); describe("Scene/createElevationBandMaterial", function() { let scene2; let isHeightDataPacked; let heightData; let colorData; beforeAll(function() { scene2 = createScene_default(); spyOn(import__671.Texture, "create").and.callFake(function(options) { const data = options.source.arrayBufferView; if (options.sampler.minificationFilter === import__671.TextureMinificationFilter.NEAREST) { heightData = data; isHeightDataPacked = options.pixelFormat === import__671.PixelFormat.RGBA; } else if (options.sampler.minificationFilter === import__671.TextureMinificationFilter.LINEAR) { colorData = data; } }); }); afterAll(function() { scene2.destroyForSpecs(); }); function checkTextureDimensions(expectedDimension) { const colorDimension = colorData.length / 4; expect(colorDimension).toEqual(expectedDimension); const heightDimension = isHeightDataPacked ? heightData.length / 4 : heightData.length; expect(heightDimension).toEqual(expectedDimension); } function checkTexel(texel, expectedColor, expectedHeight) { const r = colorData[texel * 4 + 0]; const g = colorData[texel * 4 + 1]; const b = colorData[texel * 4 + 2]; const a = colorData[texel * 4 + 3]; const color = [r, g, b, a]; const premulipliedColor = import__671.Color.clone(expectedColor, new import__671.Color()); premulipliedColor.red *= premulipliedColor.alpha; premulipliedColor.green *= premulipliedColor.alpha; premulipliedColor.blue *= premulipliedColor.alpha; expect(color).toEqualEpsilon(premulipliedColor.toBytes(), 1); const height = isHeightDataPacked ? import__671.Cartesian4.unpackFloat(import__671.Cartesian4.unpack(heightData, texel * 4)) : heightData[texel]; expect(height).toEqualEpsilon(expectedHeight, import__672.Math.EPSILON5); } it("throws without scene", function() { expect(function() { (0, import__671.createElevationBandMaterial)(); }).toThrowDeveloperError(); }); it("throws without layers", function() { expect(function() { (0, import__671.createElevationBandMaterial)({ scene: scene2 }); }).toThrowDeveloperError(); const layers = []; expect(function() { (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); }).toThrowDeveloperError(); }); it("throws with no entries", function() { const layers = [ { entries: [] } ]; expect(function() { (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); }).toThrowDeveloperError(); }); it("throws with no height", function() { const layers = [ { entries: [ { color: import__671.Color.RED } ] } ]; expect(function() { (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); }).toThrowDeveloperError(); }); it("throws with no color", function() { const layers = [ { entries: [ { height: 0 } ] } ]; expect(function() { (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); }).toThrowDeveloperError(); }); it("creates material with one entry", function() { const layers = [ { entries: [ { height: 0, color: import__671.Color.RED } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(2); checkTexel(1, import__671.Color.RED, import__671.createElevationBandMaterial._maximumHeight); checkTexel(0, import__671.Color.RED, import__671.createElevationBandMaterial._minimumHeight); }); it("creates material with one entry that extends upwards", function() { const layers = [ { entries: [ { height: 0, color: import__671.Color.RED } ], extendUpwards: true } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(2); checkTexel(1, import__671.Color.RED, import__671.createElevationBandMaterial._maximumHeight); checkTexel(0, import__671.Color.RED, 0); }); it("creates material with one entry that extends downwards", function() { const layers = [ { entries: [ { height: 0, color: import__671.Color.RED } ], extendDownwards: true } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(2); checkTexel(1, import__671.Color.RED, 0); checkTexel(0, import__671.Color.RED, import__671.createElevationBandMaterial._minimumHeight); }); it("creates material with one entry that extends upwards and downwards", function() { const layers = [ { entries: [ { height: 0, color: import__671.Color.RED } ], extendUpwards: true, extendDownwards: true } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(2); checkTexel(1, import__671.Color.RED, import__671.createElevationBandMaterial._maximumHeight); checkTexel(0, import__671.Color.RED, import__671.createElevationBandMaterial._minimumHeight); }); it("removes unused entries", function() { const layers = [ { entries: [ { height: 3, color: new import__671.Color(1, 0, 0, 1) }, { height: 3, color: new import__671.Color(0, 1, 0, 1) }, { height: 2, color: new import__671.Color(0, 1, 0, 1) }, { height: 1, color: new import__671.Color(0, 1, 0, 1) }, { height: 0, color: new import__671.Color(0, 1, 0, 1) }, { height: 0, color: new import__671.Color(1, 0, 0, 1) }, { height: 0, color: new import__671.Color(0, 1, 0, 1) }, { height: 0, color: new import__671.Color(1, 0, 0, 1) }, { height: 0, color: new import__671.Color(1, 0, 0, 1) } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(2); checkTexel(1, new import__671.Color(0, 1, 0, 1), 3); checkTexel(0, new import__671.Color(0, 1, 0, 1), 0); }); it("sorts entries", function() { const layers = [ { entries: [ { height: 1, color: new import__671.Color(0, 1, 0, 1) }, { height: 2, color: new import__671.Color(0, 0, 1, 1) }, { height: 0, color: new import__671.Color(1, 0, 0, 1) } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(3); checkTexel(2, new import__671.Color(0, 0, 1, 1), 2); checkTexel(1, new import__671.Color(0, 1, 0, 1), 1); checkTexel(0, new import__671.Color(1, 0, 0, 1), 0); }); it("creates material with antialiased band", function() { const layers = [ { entries: [ { height: 1, color: new import__671.Color(1, 0, 0, 0) }, { height: 0.9, color: new import__671.Color(1, 0, 0, 1) }, { height: -0.9, color: new import__671.Color(1, 0, 0, 1) }, { height: -1, color: new import__671.Color(1, 0, 0, 0) } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(4); checkTexel(3, new import__671.Color(1, 0, 0, 0), 1); checkTexel(2, new import__671.Color(1, 0, 0, 1), 0.9); checkTexel(1, new import__671.Color(1, 0, 0, 1), -0.9); checkTexel(0, new import__671.Color(1, 0, 0, 0), -1); }); it("creates material with one layer completely before another", function() { const layers = [ { entries: [ { height: 1, color: import__671.Color.RED }, { height: 2, color: import__671.Color.RED } ] }, { entries: [ { height: -1, color: import__671.Color.BLUE }, { height: -2, color: import__671.Color.BLUE } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(6); checkTexel(5, import__671.Color.RED, 2); checkTexel(4, import__671.Color.RED, 1); checkTexel(3, import__671.createElevationBandMaterial._emptyColor, 1); checkTexel(2, import__671.createElevationBandMaterial._emptyColor, -1); checkTexel(1, import__671.Color.BLUE, -1); checkTexel(0, import__671.Color.BLUE, -2); }); it("creates material with one layer completely after another", function() { const layers = [ { entries: [ { height: -1, color: import__671.Color.BLUE }, { height: -2, color: import__671.Color.BLUE } ] }, { entries: [ { height: 1, color: import__671.Color.RED }, { height: 2, color: import__671.Color.RED } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(6); checkTexel(5, import__671.Color.RED, 2); checkTexel(4, import__671.Color.RED, 1); checkTexel(3, import__671.createElevationBandMaterial._emptyColor, 1); checkTexel(2, import__671.createElevationBandMaterial._emptyColor, -1); checkTexel(1, import__671.Color.BLUE, -1); checkTexel(0, import__671.Color.BLUE, -2); }); it("creates material with larger transparent layer on top of solid color layer", function() { const layers = [ { entries: [ { height: 1, color: new import__671.Color(1, 1, 1, 1) }, { height: -1, color: new import__671.Color(1, 1, 1, 1) } ] }, { entries: [ { height: 2, color: new import__671.Color(1, 0, 0, 0.5) }, { height: -2, color: new import__671.Color(1, 0, 0, 0.5) } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(6); checkTexel(5, new import__671.Color(1, 0, 0, 0.5), 2); checkTexel(4, new import__671.Color(1, 0, 0, 0.5), 1); checkTexel(3, new import__671.Color(1, 0.5, 0.5, 1), 1); checkTexel(2, new import__671.Color(1, 0.5, 0.5, 1), -1); checkTexel(1, new import__671.Color(1, 0, 0, 0.5), -1); checkTexel(0, new import__671.Color(1, 0, 0, 0.5), -2); }); it("creates material with smaller transparent layer on top of solid color layer", function() { const layers = [ { entries: [ { height: 2, color: new import__671.Color(1, 1, 1, 1) }, { height: -2, color: new import__671.Color(1, 1, 1, 1) } ] }, { entries: [ { height: 1, color: new import__671.Color(1, 0, 0, 0.5) }, { height: -1, color: new import__671.Color(1, 0, 0, 0.5) } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(6); checkTexel(5, new import__671.Color(1, 1, 1, 1), 2); checkTexel(4, new import__671.Color(1, 1, 1, 1), 1); checkTexel(3, new import__671.Color(1, 0.5, 0.5, 1), 1); checkTexel(2, new import__671.Color(1, 0.5, 0.5, 1), -1); checkTexel(1, new import__671.Color(1, 1, 1, 1), -1); checkTexel(0, new import__671.Color(1, 1, 1, 1), -2); }); it("creates material with transparent bi-color layer on top of bi-color layer", function() { const layers = [ { entries: [ { height: 1, color: new import__671.Color(1, 1, 1, 1) }, { height: 0, color: new import__671.Color(1, 1, 1, 1) }, { height: 0, color: new import__671.Color(0, 0, 0, 1) }, { height: -1, color: new import__671.Color(0, 0, 0, 1) } ] }, { entries: [ { height: 1, color: new import__671.Color(1, 0, 0, 0.5) }, { height: 0, color: new import__671.Color(1, 0, 0, 0.5) }, { height: 0, color: new import__671.Color(0, 1, 0, 0.5) }, { height: -1, color: new import__671.Color(0, 1, 0, 0.5) } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(4); checkTexel(3, new import__671.Color(1, 0.5, 0.5, 1), 1); checkTexel(2, new import__671.Color(1, 0.5, 0.5, 1), 0); checkTexel(1, new import__671.Color(0, 0.5, 0, 1), 0); checkTexel(0, new import__671.Color(0, 0.5, 0, 1), -1); }); it("creates material with transparent bi-color layer on top of gradient layer", function() { const layers = [ { entries: [ { height: 1, color: new import__671.Color(0, 0, 0, 1) }, { height: 0, color: new import__671.Color(1, 1, 1, 1) }, { height: -1, color: new import__671.Color(0, 0, 0, 1) } ] }, { entries: [ { height: 1, color: new import__671.Color(1, 0, 0, 0.5) }, { height: 0, color: new import__671.Color(1, 0, 0, 0.5) }, { height: 0, color: new import__671.Color(0, 1, 0, 0.5) }, { height: -1, color: new import__671.Color(0, 1, 0, 0.5) } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(4); checkTexel(3, new import__671.Color(0.5, 0, 0, 1), 1); checkTexel(2, new import__671.Color(1, 0.5, 0.5, 1), 0); checkTexel(1, new import__671.Color(0.5, 1, 0.5, 1), 0); checkTexel(0, new import__671.Color(0, 0.5, 0, 1), -1); }); it("creates material with transparent gradient layer on top of bi-color layer", function() { const layers = [ { entries: [ { height: 1, color: new import__671.Color(1, 1, 1, 1) }, { height: 0, color: new import__671.Color(1, 1, 1, 1) }, { height: 0, color: new import__671.Color(0, 0, 0, 1) }, { height: -1, color: new import__671.Color(0, 0, 0, 1) } ] }, { entries: [ { height: 1, color: new import__671.Color(1, 0, 0, 0.5) }, { height: 0, color: new import__671.Color(0, 1, 0, 0.5) }, { height: -1, color: new import__671.Color(1, 0, 0, 0.5) } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(4); checkTexel(3, new import__671.Color(1, 0.5, 0.5, 1), 1); checkTexel(2, new import__671.Color(0.5, 1, 0.5, 1), 0); checkTexel(1, new import__671.Color(0, 0.5, 0, 1), 0); checkTexel(0, new import__671.Color(0.5, 0, 0, 1), -1); }); it("creates material with transparent gradient layer on top of gradient layer", function() { const layers = [ { entries: [ { height: 1, color: new import__671.Color(1, 1, 1, 1) }, { height: 0, color: new import__671.Color(0, 0, 0, 1) }, { height: -1, color: new import__671.Color(1, 1, 1, 1) } ] }, { entries: [ { height: 1, color: new import__671.Color(1, 0, 0, 0.5) }, { height: 0, color: new import__671.Color(0, 1, 0, 0.5) }, { height: -1, color: new import__671.Color(1, 0, 0, 0.5) } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(3); checkTexel(2, new import__671.Color(1, 0.5, 0.5, 1), 1); checkTexel(1, new import__671.Color(0, 0.5, 0, 1), 0); checkTexel(0, new import__671.Color(1, 0.5, 0.5, 1), -1); }); it("creates material with transparent gradient layer on top of solid color layer", function() { const layers = [ { entries: [ { height: 1, color: new import__671.Color(1, 1, 1, 1) }, { height: -1, color: new import__671.Color(1, 1, 1, 1) } ] }, { entries: [ { height: 1, color: new import__671.Color(1, 0, 0, 0.5) }, { height: 0, color: new import__671.Color(0, 1, 0, 0.5) }, { height: -1, color: new import__671.Color(1, 0, 0, 0.5) } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(3); checkTexel(2, new import__671.Color(1, 0.5, 0.5, 1), 1); checkTexel(1, new import__671.Color(0.5, 1, 0.5, 1), 0); checkTexel(0, new import__671.Color(1, 0.5, 0.5, 1), -1); }); it("creates material with transparent layer on top of gradient layer", function() { const layers = [ { entries: [ { height: 1, color: new import__671.Color(1, 0, 0, 1) }, { height: 0, color: new import__671.Color(0, 1, 0, 1) }, { height: -1, color: new import__671.Color(1, 0, 0, 1) } ] }, { entries: [ { height: 1, color: new import__671.Color(1, 1, 1, 0.5) }, { height: -1, color: new import__671.Color(1, 1, 1, 0.5) } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(3); checkTexel(2, new import__671.Color(1, 0.5, 0.5, 1), 1); checkTexel(1, new import__671.Color(0.5, 1, 0.5, 1), 0); checkTexel(0, new import__671.Color(1, 0.5, 0.5, 1), -1); }); it("creates material with higher layer starting and ending on middle of lower layer", function() { const layers = [ { entries: [ { height: 1, color: new import__671.Color(1, 1, 1, 1) }, { height: 0.5, color: new import__671.Color(1, 1, 1, 1) }, { height: -0.5, color: new import__671.Color(0, 0, 0, 1) }, { height: -1, color: new import__671.Color(0, 0, 0, 1) } ] }, { entries: [ { height: 0.5, color: new import__671.Color(1, 0, 0, 0.5) }, { height: -0.5, color: new import__671.Color(0, 1, 0, 0.5) } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(6); checkTexel(5, new import__671.Color(1, 1, 1, 1), 1); checkTexel(4, new import__671.Color(1, 1, 1, 1), 0.5); checkTexel(3, new import__671.Color(1, 0.5, 0.5, 1), 0.5); checkTexel(2, new import__671.Color(0, 0.5, 0, 1), -0.5); checkTexel(1, new import__671.Color(0, 0, 0, 1), -0.5); checkTexel(0, new import__671.Color(0, 0, 0, 1), -1); }); it("creates material with lower layer starting and ending on middle of higher layer", function() { const layers = [ { entries: [ { height: 1, color: import__671.Color.WHITE }, { height: -1, color: import__671.Color.WHITE } ] }, { entries: [ { height: 2, color: new import__671.Color(1, 0, 0, 0.5) }, { height: 1, color: new import__671.Color(0, 1, 0, 0.5) }, { height: -1, color: new import__671.Color(0, 1, 0, 0.5) }, { height: -2, color: new import__671.Color(1, 0, 0, 0.5) } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(6); checkTexel(5, new import__671.Color(1, 0, 0, 0.5), 2); checkTexel(4, new import__671.Color(0, 1, 0, 0.5), 1); checkTexel(3, new import__671.Color(0.5, 1, 0.5, 1), 1); checkTexel(2, new import__671.Color(0.5, 1, 0.5, 1), -1); checkTexel(1, new import__671.Color(0, 1, 0, 0.5), -1); checkTexel(0, new import__671.Color(1, 0, 0, 0.5), -2); }); it("creates multi-layered material", function() { const layers = [ { entries: [ { height: 1, color: import__671.Color.BLACK }, { height: 0, color: import__671.Color.WHITE }, { height: -1, color: import__671.Color.BLACK } ] }, { entries: [ { height: 2, color: new import__671.Color(1, 0, 0, 1) }, { height: 1, color: new import__671.Color(1, 0, 0, 1) } ] }, { entries: [ { height: -1, color: new import__671.Color(1, 0, 0, 1) }, { height: -2, color: new import__671.Color(1, 0, 0, 1) } ] }, { entries: [ { height: 0.5, color: new import__671.Color(0, 1, 0, 0.5) }, { height: 0, color: new import__671.Color(0, 1, 0, 0.5) } ] }, { entries: [ { height: 0, color: new import__671.Color(0, 0, 1, 0.5) }, { height: -0.5, color: new import__671.Color(0, 0, 1, 0.5) } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(12); checkTexel(11, new import__671.Color(1, 0, 0, 1), 2); checkTexel(10, new import__671.Color(1, 0, 0, 1), 1); checkTexel(9, new import__671.Color(0, 0, 0, 1), 1); checkTexel(8, new import__671.Color(0.5, 0.5, 0.5, 1), 0.5); checkTexel(7, new import__671.Color(0.25, 0.75, 0.25, 1), 0.5); checkTexel(6, new import__671.Color(0.5, 1, 0.5, 1), 0); checkTexel(5, new import__671.Color(0.5, 0.5, 1, 1), 0); checkTexel(4, new import__671.Color(0.25, 0.25, 0.75, 1), -0.5); checkTexel(3, new import__671.Color(0.5, 0.5, 0.5, 1), -0.5); checkTexel(2, new import__671.Color(0, 0, 0, 1), -1); checkTexel(1, new import__671.Color(1, 0, 0, 1), -1); checkTexel(0, new import__671.Color(1, 0, 0, 1), -2); }); it("creates another multi-layered material", function() { const layers = [ { entries: [ { height: 1, color: import__671.Color.BLACK }, { height: 0, color: import__671.Color.BLACK }, { height: 0, color: import__671.Color.WHITE }, { height: -1, color: import__671.Color.WHITE } ] }, { entries: [ { height: 0.5, color: new import__671.Color(0, 0, 1, 1) }, { height: 0, color: new import__671.Color(0, 0, 1, 1) } ] }, { entries: [ { height: 1.1, color: new import__671.Color(1, 0, 0, 0.5) }, { height: 1, color: new import__671.Color(1, 0, 0, 0.5) }, { height: 1, color: new import__671.Color(0, 1, 0, 0.5) }, { height: 0.9, color: new import__671.Color(0, 1, 0, 0.5) } ] }, { entries: [ { height: -0.9, color: new import__671.Color(1, 0, 0, 0.5) }, { height: -1, color: new import__671.Color(1, 0, 0, 0.5) }, { height: -1, color: new import__671.Color(0, 1, 0, 0.5) }, { height: -1.1, color: new import__671.Color(0, 1, 0, 0.5) } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(14); checkTexel(13, new import__671.Color(1, 0, 0, 0.5), 1.1); checkTexel(12, new import__671.Color(1, 0, 0, 0.5), 1); checkTexel(11, new import__671.Color(0, 0.5, 0, 1), 1); checkTexel(10, new import__671.Color(0, 0.5, 0, 1), 0.9); checkTexel(9, new import__671.Color(0, 0, 0, 1), 0.9); checkTexel(8, new import__671.Color(0, 0, 0, 1), 0.5); checkTexel(7, new import__671.Color(0, 0, 1, 1), 0.5); checkTexel(6, new import__671.Color(0, 0, 1, 1), 0); checkTexel(5, new import__671.Color(1, 1, 1, 1), 0); checkTexel(4, new import__671.Color(1, 1, 1, 1), -0.9); checkTexel(3, new import__671.Color(1, 0.5, 0.5, 1), -0.9); checkTexel(2, new import__671.Color(1, 0.5, 0.5, 1), -1); checkTexel(1, new import__671.Color(0, 1, 0, 0.5), -1); checkTexel(0, new import__671.Color(0, 1, 0, 0.5), -1.1); }); it("creates material with complex layers", function() { const layers = [ { entries: [ { height: 1e3, color: import__671.Color.WHITE }, { height: -1e3, color: import__671.Color.BLACK } ], extendDownwards: true }, { entries: [ { height: 500, color: new import__671.Color(1, 0, 0, 1) }, { height: -500, color: new import__671.Color(1, 0, 0, 0.5) } ] } ]; (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(7); checkTexel(6, new import__671.Color(1, 1, 1, 1), 1e3); checkTexel(5, new import__671.Color(0.75, 0.75, 0.75, 1), 500); checkTexel(4, new import__671.Color(1, 0, 0, 1), 500); checkTexel(3, new import__671.Color(0.625, 0.125, 0.125, 1), -500); checkTexel(2, new import__671.Color(0.25, 0.25, 0.25, 1), -500); checkTexel(1, new import__671.Color(0, 0, 0, 1), -1e3); checkTexel( 0, new import__671.Color(0, 0, 0, 1), import__671.createElevationBandMaterial._minimumHeight ); }); it("creates material with unpacked height", function() { const layers = [ { entries: [ { height: 0, color: import__671.Color.RED }, { height: 1, color: import__671.Color.RED } ] } ]; spyOn(import__671.createElevationBandMaterial, "_useFloatTexture").and.returnValue( false ); (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(2); checkTexel(1, import__671.Color.RED, 1); checkTexel(0, import__671.Color.RED, 0); }); it("creates material with packed height", function() { const layers = [ { entries: [ { height: 0, color: import__671.Color.RED }, { height: 1, color: import__671.Color.RED } ] } ]; spyOn(import__671.createElevationBandMaterial, "_useFloatTexture").and.returnValue( true ); (0, import__671.createElevationBandMaterial)({ scene: scene2, layers }); checkTextureDimensions(2); checkTexel(1, import__671.Color.RED, 1); checkTexel(0, import__671.Color.RED, 0); }); }); // packages/engine/Specs/Scene/createTangentSpaceDebugPrimitiveSpec.js var import__673 = __toESM(require_Cesium(), 1); describe("Scene/createTangentSpaceDebugPrimitive", function() { it("computes all attributes", function() { const geometry = new import__673.EllipsoidGeometry({ vertexFormat: import__673.VertexFormat.ALL, radii: new import__673.Cartesian3(5e5, 5e5, 1e6) }); const modelMatrix = import__673.Matrix4.multiplyByTranslation( import__673.Matrix4.IDENTITY, new import__673.Cartesian3(0, 0, 11e6), new import__673.Matrix4() ); const primitive = (0, import__673.createTangentSpaceDebugPrimitive)({ geometry, modelMatrix, length: 1e3 }); expect(primitive.geometryInstances).toBeDefined(); expect(primitive.appearance).toBeDefined(); expect(primitive.asynchronous).toBe(false); const instances = primitive.geometryInstances; expect(instances.length).toEqual(3); expect(instances[0].modelMatrix).toEqual(modelMatrix); expect(instances[1].modelMatrix).toEqual(modelMatrix); expect(instances[2].modelMatrix).toEqual(modelMatrix); expect(instances[0].attributes).toBeDefined(); expect(instances[0].attributes.color).toBeDefined(); expect(instances[1].attributes).toBeDefined(); expect(instances[1].attributes.color).toBeDefined(); expect(instances[2].attributes).toBeDefined(); expect(instances[2].attributes.color).toBeDefined(); expect(instances[0].geometry.primitiveType).toEqual(import__673.PrimitiveType.LINES); expect(instances[1].geometry.primitiveType).toEqual(import__673.PrimitiveType.LINES); expect(instances[2].geometry.primitiveType).toEqual(import__673.PrimitiveType.LINES); }); it("throws without geometry", function() { expect(function() { (0, import__673.createTangentSpaceDebugPrimitive)(); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/createWorldImageryAsyncSpec.js var import__674 = __toESM(require_Cesium(), 1); describe("Core/createWorldImageryAsync", function() { it("resolves to IonImageryProvider instance with default parameters", async function() { spyOn(import__674.Resource.prototype, "fetchJsonp").and.callFake( () => Promise.resolve(createFakeBingMapsMetadataResponse_default(import__674.BingMapsStyle.AERIAL)) ); const provider = await (0, import__674.createWorldImageryAsync)(); expect(provider).toBeInstanceOf(import__674.IonImageryProvider); }); }); // packages/engine/Specs/Scene/findContentMetadataSpec.js var import__675 = __toESM(require_Cesium(), 1); describe("Scene/findContentMetadata", function() { let contentClass; let mockTileset; beforeAll(function() { contentClass = import__675.MetadataClass.fromJson({ id: "content", class: { properties: { name: { type: "STRING" }, color: { type: "VEC3", componentType: "UINT8" } } } }); mockTileset = { schema: { classes: { content: contentClass } } }; }); it("returns undefined if there is no metadata or extension", function() { const contentHeader = { uri: "https://example.com/model.b3dm" }; const metadata = (0, import__675.findContentMetadata)(mockTileset, contentHeader); expect(metadata).not.toBeDefined(); }); it("logs a warning and returns undefined if the tileset is missing a schema", function() { const contentHeader = { uri: "https://example.com/model.b3dm", metadata: { class: "content", properties: { name: "Sample Content", color: [255, 255, 0] } } }; spyOn(import__675.findContentMetadata, "_oneTimeWarning"); const tilesetWithoutSchema = {}; const metadata = (0, import__675.findContentMetadata)(tilesetWithoutSchema, contentHeader); expect(metadata).not.toBeDefined(); expect(import__675.findContentMetadata._oneTimeWarning).toHaveBeenCalled(); }); it("returns metadata if there is metadata", function() { const contentHeader = { uri: "https://example.com/model.b3dm", metadata: { class: "content", properties: { name: "Sample Content", color: [255, 255, 0] } } }; const metadata = (0, import__675.findContentMetadata)(mockTileset, contentHeader); expect(metadata).toBeDefined(); expect(metadata.getProperty("name")).toEqual("Sample Content"); expect(metadata.getProperty("color")).toEqual(new import__675.Cartesian3(255, 255, 0)); }); it("returns metadata if there is an extension (legacy)", function() { const contentHeader = { uri: "https://example.com/model.b3dm", extensions: { "3DTILES_metadata": { class: "content", properties: { name: "Sample Content", color: [255, 255, 0] } } } }; const metadata = (0, import__675.findContentMetadata)(mockTileset, contentHeader); expect(metadata).toBeDefined(); expect(metadata.getProperty("name")).toEqual("Sample Content"); expect(metadata.getProperty("color")).toEqual(new import__675.Cartesian3(255, 255, 0)); }); }); // packages/engine/Specs/Scene/findGroupMetadataSpec.js var import__676 = __toESM(require_Cesium(), 1); describe("Scene/findGroupMetadata", function() { let layerClass; let mockTileset; beforeAll(function() { layerClass = import__676.MetadataClass.fromJson({ id: "layer", class: { properties: { name: { type: "STRING" }, elevation: { type: "SCALAR", componentType: "FLOAT32" } } } }); mockTileset = { metadataExtension: { groups: [ new import__676.GroupMetadata({ id: "testGroup", class: layerClass, group: { properties: { name: "Test Layer testGroup", elevation: 150 } } }) ], groupIds: ["testGroup"] } }; }); it("returns undefined if there is no group or extension", function() { const contentHeader = { uri: "https://example.com/model.b3dm" }; const group = (0, import__676.findGroupMetadata)(mockTileset, contentHeader); expect(group).not.toBeDefined(); }); it("returns the group metadata if there is a group index", function() { const contentHeader = { uri: "https://example.com/model.b3dm", group: 0 }; const group = (0, import__676.findGroupMetadata)(mockTileset, contentHeader); expect(group).toBeDefined(); expect(group.getProperty("name")).toBe("Test Layer testGroup"); expect(group.getProperty("elevation")).toBe(150); }); it("returns the group metadata if there is a group with the same id (legacy)", function() { const contentHeader = { uri: "https://example.com/model.b3dm", group: "testGroup" }; const group = (0, import__676.findGroupMetadata)(mockTileset, contentHeader); expect(group).toBeDefined(); expect(group.getProperty("name")).toBe("Test Layer testGroup"); expect(group.getProperty("elevation")).toBe(150); }); it("returns the group metadata if there is an extension (legacy)", function() { const contentHeader = { uri: "https://example.com/model.b3dm", extensions: { "3DTILES_metadata": { group: "testGroup" } } }; const group = (0, import__676.findGroupMetadata)(mockTileset, contentHeader); expect(group).toBeDefined(); expect(group.getProperty("name")).toBe("Test Layer testGroup"); expect(group.getProperty("elevation")).toBe(150); }); }); // packages/engine/Specs/Scene/findTileMetadataSpec.js var import__677 = __toESM(require_Cesium(), 1); describe("Scene/findTileMetadata", function() { let tileClass; let mockTileset; beforeAll(function() { tileClass = import__677.MetadataClass.fromJson({ id: "tile", class: { properties: { height: { type: "SCALAR", componentType: "FLOAT32" }, color: { type: "VEC3", componentType: "UINT8" } } } }); mockTileset = { schema: { classes: { tile: tileClass } } }; }); const mockBoundingVolume = {}; it("returns undefined if there is no metadata or extension", function() { const tileHeader = { boundingVolume: mockBoundingVolume, geometricError: 64 }; const metadata = (0, import__677.findTileMetadata)(mockTileset, tileHeader); expect(metadata).not.toBeDefined(); }); it("logs a warning and returns undefined if the tileset is missing a schema", function() { const tileHeader = { boundingVolume: mockBoundingVolume, geometricError: 64, metadata: { class: "tile", properties: { height: 250.5, color: [255, 255, 0] } } }; spyOn(import__677.findTileMetadata, "_oneTimeWarning"); const tilesetWithoutSchema = {}; const metadata = (0, import__677.findTileMetadata)(tilesetWithoutSchema, tileHeader); expect(metadata).not.toBeDefined(); expect(import__677.findTileMetadata._oneTimeWarning).toHaveBeenCalled(); }); it("returns metadata if there is metadata", function() { const tileHeader = { boundingVolume: mockBoundingVolume, geometricError: 64, metadata: { class: "tile", properties: { height: 250.5, color: [255, 255, 0] } } }; const metadata = (0, import__677.findTileMetadata)(mockTileset, tileHeader); expect(metadata).toBeDefined(); expect(metadata.getProperty("height")).toEqual(250.5); expect(metadata.getProperty("color")).toEqual(new import__677.Cartesian3(255, 255, 0)); }); it("returns metadata if there is an extension (legacy)", function() { const tileHeader = { boundingVolume: mockBoundingVolume, geometricError: 64, extensions: { "3DTILES_metadata": { class: "tile", properties: { height: 250.5, color: [255, 255, 0] } } } }; const metadata = (0, import__677.findTileMetadata)(mockTileset, tileHeader); expect(metadata).toBeDefined(); expect(metadata.getProperty("height")).toEqual(250.5); expect(metadata.getProperty("color")).toEqual(new import__677.Cartesian3(255, 255, 0)); }); }); // packages/engine/Specs/Scene/hasExtensionSpec.js var import__678 = __toESM(require_Cesium(), 1); describe("Scene/hasExtension", function() { it("detects the presence of an extension", function() { const tile = { extensions: { "3DTILES_extension": {} } }; expect((0, import__678.hasExtension)(tile, "3DTILES_extension")).toEqual(true); }); it("detects the absence of an extension", function() { let tile = {}; expect((0, import__678.hasExtension)(tile, "3DTILES_extension")).toEqual(false); tile = { extensions: {} }; expect((0, import__678.hasExtension)(tile, "3DTILES_extension")).toEqual(false); tile = { extensions: { "3DTILES_other_extension": {} } }; expect((0, import__678.hasExtension)(tile, "3DTILES_extension")).toEqual(false); }); }); // packages/engine/Specs/Scene/parseBatchTableSpec.js var import__679 = __toESM(require_Cesium(), 1); describe("Scene/parseBatchTable", function() { const batchTableJson = {}; const count = 3; const className = import__679.MetadataClass.BATCH_TABLE_CLASS_NAME; function sortByName(a, b) { if (a.name < b.name) { return -1; } if (a.name > b.name) { return 1; } return 0; } it("throws without count", function() { expect(function() { return (0, import__679.parseBatchTable)({ count: void 0, batchTable: batchTableJson }); }).toThrowDeveloperError(); }); it("throws without batchTable", function() { expect(function() { return (0, import__679.parseBatchTable)({ count, batchTable: void 0 }); }).toThrowDeveloperError(); }); it("parses batch table with no properties", function() { const metadata = (0, import__679.parseBatchTable)({ count, batchTable: {} }); expect(metadata).toBeDefined(); }); it("parses batch table with binary properties", function() { const binaryBatchTable = { height: { byteOffset: 0, componentType: "FLOAT", type: "SCALAR" } }; const heightValues = new Float32Array([10, 15, 25]); const binaryBody = new Uint8Array(heightValues.buffer); const metadata = (0, import__679.parseBatchTable)({ count: 3, batchTable: binaryBatchTable, binaryBody }); const propertyTable = metadata.getPropertyTable(0); expect(propertyTable.id).toBe(0); expect(propertyTable.name).toBe("Batch Table"); expect(propertyTable.getProperty(0, "height")).toBe(10); expect(propertyTable.getProperty(1, "height")).toBe(15); expect(propertyTable.getProperty(2, "height")).toBe(25); }); it("transcodes scalars to correct types", function() { const binaryBatchTable = { uint8Property: { byteOffset: 0, componentType: "UNSIGNED_BYTE", type: "SCALAR" }, uint16Property: { byteOffset: 0, componentType: "UNSIGNED_SHORT", type: "SCALAR" }, uint32Property: { byteOffset: 0, componentType: "UNSIGNED_INT", type: "SCALAR" }, int8Property: { byteOffset: 0, componentType: "BYTE", type: "SCALAR" }, int16Property: { byteOffset: 0, componentType: "SHORT", type: "SCALAR" }, int32Property: { byteOffset: 0, componentType: "INT", type: "SCALAR" }, floatProperty: { byteOffset: 0, componentType: "FLOAT", type: "SCALAR" }, doubleProperty: { byteOffset: 0, componentType: "DOUBLE", type: "SCALAR" } }; const binaryBody = new Uint8Array(8); const metadata = (0, import__679.parseBatchTable)({ count: 1, batchTable: binaryBatchTable, binaryBody }); const properties = metadata.schema.classes[className].properties; expect(properties.uint8Property.componentType).toBe( import__679.MetadataComponentType.UINT8 ); expect(properties.uint16Property.componentType).toBe( import__679.MetadataComponentType.UINT16 ); expect(properties.uint32Property.componentType).toBe( import__679.MetadataComponentType.UINT32 ); expect(properties.int8Property.componentType).toBe( import__679.MetadataComponentType.INT8 ); expect(properties.int16Property.componentType).toBe( import__679.MetadataComponentType.INT16 ); expect(properties.int32Property.componentType).toBe( import__679.MetadataComponentType.INT32 ); expect(properties.floatProperty.componentType).toBe( import__679.MetadataComponentType.FLOAT32 ); expect(properties.doubleProperty.componentType).toBe( import__679.MetadataComponentType.FLOAT64 ); const propertyTable = metadata.getPropertyTable(0); expect(propertyTable.getProperty(0, "uint8Property")).toBe(0); expect(propertyTable.getProperty(0, "uint16Property")).toBe(0); expect(propertyTable.getProperty(0, "uint32Property")).toBe(0); expect(propertyTable.getProperty(0, "int8Property")).toBe(0); expect(propertyTable.getProperty(0, "int16Property")).toBe(0); expect(propertyTable.getProperty(0, "int32Property")).toBe(0); expect(propertyTable.getProperty(0, "floatProperty")).toBe(0); expect(propertyTable.getProperty(0, "doubleProperty")).toBe(0); }); it("transcodes binary vectors to vector types", function() { const vectorBatchTable = { vec2Property: { byteOffset: 0, componentType: "FLOAT", type: "VEC2" }, uvec3Property: { byteOffset: 0, componentType: "UNSIGNED_INT", type: "VEC3" }, dvec4Property: { byteOffset: 0, componentType: "DOUBLE", type: "VEC4" } }; const binaryBody = new Uint8Array(8 * 4); const metadata = (0, import__679.parseBatchTable)({ count: 1, batchTable: vectorBatchTable, binaryBody }); const properties = metadata.schema.classes[className].properties; expect(properties.vec2Property.type).toBe(import__679.MetadataType.VEC2); expect(properties.uvec3Property.type).toBe(import__679.MetadataType.VEC3); expect(properties.dvec4Property.type).toBe(import__679.MetadataType.VEC4); expect(properties.vec2Property.componentType).toBe( import__679.MetadataComponentType.FLOAT32 ); expect(properties.uvec3Property.componentType).toBe( import__679.MetadataComponentType.UINT32 ); expect(properties.dvec4Property.componentType).toBe( import__679.MetadataComponentType.FLOAT64 ); const propertyTable = metadata.getPropertyTable(0); expect(propertyTable.getProperty(0, "vec2Property")).toEqual( new import__679.Cartesian2(0, 0) ); expect(propertyTable.getProperty(0, "uvec3Property")).toEqual( new import__679.Cartesian3(0, 0, 0) ); expect(propertyTable.getProperty(0, "dvec4Property")).toEqual( new import__679.Cartesian4(0, 0, 0, 0) ); }); it("parses batch table with JSON properties", function() { const jsonBatchTable = { location: [ [0, 0], [1, 0] ], payload: [ { name: "Shopping Center", color: [0.3, 0.3, 0.3], stores: 15 }, { name: "School", color: [0.6, 0.3, 0.3], students: 1621 } ] }; const metadata = (0, import__679.parseBatchTable)({ count: 2, batchTable: jsonBatchTable }); const properties = metadata.schema.classes[className].properties; expect(properties).toEqual({}); const propertyTable = metadata.getPropertyTable(0); expect(propertyTable.getProperty(0, "location")).toEqual( jsonBatchTable.location[0] ); expect(propertyTable.getProperty(1, "location")).toEqual( jsonBatchTable.location[1] ); expect(propertyTable.getProperty(0, "payload")).toEqual( jsonBatchTable.payload[0] ); expect(propertyTable.getProperty(1, "payload")).toEqual( jsonBatchTable.payload[1] ); }); const hierarchy = { classes: [ { name: "Wheels", length: 8, instances: { tire_location: [ "front_left", "front_right", "back_left", "back_right", "front_left", "front_right", "back_left", "back_right" ] } }, { name: "Car", length: 2, instances: { color: ["blue", "red"], type: ["sedan", "truck"], year: ["2020", "2018"] } } ], instancesLength: 10, classIds: [0, 0, 0, 0, 1, 0, 0, 0, 0, 1], parentIds: [4, 4, 4, 4, 4, 9, 9, 9, 9, 9], parentCounts: [1, 1, 1, 1, 0, 1, 1, 1, 1, 0] }; it("warns for deprecated HIERARCHY extension", function() { const warn = spyOn(import__679.parseBatchTable, "_deprecationWarning"); const oldHierarchyBatchTable = { HIERARCHY: hierarchy }; const metadata = (0, import__679.parseBatchTable)({ count: 10, batchTable: oldHierarchyBatchTable }); expect(warn).toHaveBeenCalled(); const properties = metadata.schema.classes[className].properties; expect(properties).toEqual({}); const propertyTable = metadata.getPropertyTable(0); expect(propertyTable.getProperty(0, "tire_location")).toBe("front_left"); expect(propertyTable.getProperty(0, "color")).toBe("blue"); expect(propertyTable.getProperty(0, "type")).toBe("sedan"); expect(propertyTable.getProperty(0, "year")).toBe("2020"); expect(propertyTable.getProperty(4, "tire_location")).not.toBeDefined(); expect(propertyTable.getProperty(4, "color")).toBe("blue"); expect(propertyTable.getProperty(4, "type")).toBe("sedan"); expect(propertyTable.getProperty(4, "year")).toBe("2020"); expect(propertyTable.getProperty(6, "tire_location")).toBe("front_right"); expect(propertyTable.getProperty(6, "color")).toBe("red"); expect(propertyTable.getProperty(6, "type")).toBe("truck"); expect(propertyTable.getProperty(6, "year")).toBe("2018"); expect(propertyTable.getProperty(9, "tire_location")).not.toBeDefined(); expect(propertyTable.getProperty(9, "color")).toBe("red"); expect(propertyTable.getProperty(9, "type")).toBe("truck"); expect(propertyTable.getProperty(9, "year")).toBe("2018"); }); it("parses batch table with hierarchy", function() { const oldHierarchyBatchTable = { extensions: { "3DTILES_batch_table_hierarchy": hierarchy } }; const metadata = (0, import__679.parseBatchTable)({ count: 10, batchTable: oldHierarchyBatchTable }); const properties = metadata.schema.classes[className].properties; expect(properties).toEqual({}); const propertyTable = metadata.getPropertyTable(0); expect(propertyTable.getProperty(0, "tire_location")).toBe("front_left"); expect(propertyTable.getProperty(0, "color")).toBe("blue"); expect(propertyTable.getProperty(0, "type")).toBe("sedan"); expect(propertyTable.getProperty(0, "year")).toBe("2020"); expect(propertyTable.getProperty(4, "tire_location")).not.toBeDefined(); expect(propertyTable.getProperty(4, "color")).toBe("blue"); expect(propertyTable.getProperty(4, "type")).toBe("sedan"); expect(propertyTable.getProperty(4, "year")).toBe("2020"); expect(propertyTable.getProperty(6, "tire_location")).toBe("front_right"); expect(propertyTable.getProperty(6, "color")).toBe("red"); expect(propertyTable.getProperty(6, "type")).toBe("truck"); expect(propertyTable.getProperty(6, "year")).toBe("2018"); expect(propertyTable.getProperty(9, "tire_location")).not.toBeDefined(); expect(propertyTable.getProperty(9, "color")).toBe("red"); expect(propertyTable.getProperty(9, "type")).toBe("truck"); expect(propertyTable.getProperty(9, "year")).toBe("2018"); }); it("stores extras and extensions in the transcoded StructuralMetadata", function() { const batchTable = { extras: { author: "Cesium", date: "2021-04-15" }, extensions: { "3DTILES_extension": {} } }; const metadata = (0, import__679.parseBatchTable)({ count: 1, batchTable }); expect(metadata.extras).toBe(batchTable.extras); expect(metadata.extensions).toBe(batchTable.extensions); }); it("throws if binaryBody is needed and not provided", function() { const binaryBatchTable = { height: { byteOffset: 0, componentType: "FLOAT", type: "SCALAR" } }; expect(function() { return (0, import__679.parseBatchTable)({ count: 1, batchTable: binaryBatchTable, binaryBody: void 0 }); }).toThrowError(import__679.RuntimeError); }); it("throws if parseAsPropertyAttributes is true and customAttributeOutput is not provided", function() { const binaryBatchTable = { height: { byteOffset: 0, componentType: "FLOAT", type: "SCALAR" } }; const heightValues = new Float32Array([10, 15, 25]); const binaryBody = new Uint8Array(heightValues.buffer); expect(function() { return (0, import__679.parseBatchTable)({ count: 3, batchTable: binaryBatchTable, binaryBody, parseAsPropertyAttributes: true, customAttributeOutput: void 0 }); }).toThrowDeveloperError(); }); it("parses batch table as property attributes", function() { const binaryBatchTable = { height: { byteOffset: 0, componentType: "FLOAT", type: "SCALAR" }, windDirection: { byteOffset: 12, componentType: "FLOAT", type: "VEC2" } }; const values = new Float32Array([ // height values (float) 10, 15, 25, // wind direction values (vec2) 1, 0, 1.1, 0.4, 0.3, 0.2 ]); const binaryBody = new Uint8Array(values.buffer); const customAttributes = []; const metadata = (0, import__679.parseBatchTable)({ count: 3, batchTable: binaryBatchTable, binaryBody, parseAsPropertyAttributes: true, customAttributeOutput: customAttributes }); expect(customAttributes.length).toBe(2); const [heightAttribute, windDirectionAttribute] = customAttributes.sort( sortByName ); expect(heightAttribute.name).toBe("_HEIGHT"); expect(heightAttribute.count).toBe(3); expect(heightAttribute.type).toBe("SCALAR"); expect(heightAttribute.componentDatatype).toBe(import__679.ComponentDatatype.FLOAT); expect(heightAttribute.typedArray).toEqual(values.slice(0, 3)); expect(windDirectionAttribute.name).toBe("_WINDDIRECTION"); expect(windDirectionAttribute.count).toBe(3); expect(windDirectionAttribute.type).toBe("VEC2"); expect(windDirectionAttribute.componentDatatype).toBe( import__679.ComponentDatatype.FLOAT ); expect(windDirectionAttribute.typedArray).toEqual(values.slice(3)); const propertyTable = metadata.getPropertyTable(0); expect(propertyTable).not.toBeDefined(); expect(metadata.propertyAttributes.length).toBe(1); const [propertyAttribute] = metadata.propertyAttributes; const metadataClass = propertyAttribute.class; expect(metadataClass.id).toBe(import__679.MetadataClass.BATCH_TABLE_CLASS_NAME); const heightClassProperty = metadataClass.properties.height; expect(heightClassProperty.name).toBe("height"); expect(heightClassProperty.type).toBe(import__679.MetadataType.SCALAR); expect(heightClassProperty.componentType).toBe( import__679.MetadataComponentType.FLOAT32 ); const windClassProperty = metadataClass.properties["windDirection"]; expect(windClassProperty.name).toBe("windDirection"); expect(windClassProperty.type).toBe(import__679.MetadataType.VEC2); expect(windClassProperty.componentType).toBe(import__679.MetadataComponentType.FLOAT32); const properties = propertyAttribute.properties; const heightProperty = properties.height; expect(heightProperty.attribute).toBe("_HEIGHT"); const windProperty = properties.windDirection; expect(windProperty.attribute).toBe("_WINDDIRECTION"); }); it("sanitizes property attribute property IDs for use in GLSL", function() { const binaryBatchTable = { // will be converted to Height "Height \u26F0\uFE0F": { byteOffset: 0, componentType: "FLOAT", type: "SCALAR" }, // gl_ prefix is reserved in GLSL and will be removed. // this leaves 1234, which starts with a number, so a _ prefix will be // added. Result: _1234 gl_1234: { byteOffset: 12, componentType: "FLOAT", type: "VEC2" } }; const values = new Float32Array([ 10, 15, 25, 1, 0, 1.1, 0.4, 0.3, 0.2 ]); const binaryBody = new Uint8Array(values.buffer); const customAttributes = []; const metadata = (0, import__679.parseBatchTable)({ count: 3, batchTable: binaryBatchTable, binaryBody, parseAsPropertyAttributes: true, customAttributeOutput: customAttributes }); expect(customAttributes.length).toBe(2); const [numericAttribute, unicodeAttribute] = customAttributes.sort( sortByName ); expect(numericAttribute.name).toBe("_1234"); expect(unicodeAttribute.name).toBe("_HEIGHT_"); const [propertyAttribute] = metadata.propertyAttributes; const metadataClass = propertyAttribute.class; const numericClassProperty = metadataClass.properties["_1234"]; expect(numericClassProperty.name).toBe("gl_1234"); const unicodeClassProperty = metadataClass.properties["Height_"]; expect(unicodeClassProperty.name).toBe("Height \u26F0\uFE0F"); const properties = propertyAttribute.properties; const numericProperty = properties["_1234"]; expect(numericProperty.attribute).toBe("_1234"); const unicodeProperty = properties["Height_"]; expect(unicodeProperty.attribute).toBe("_HEIGHT_"); }); it("creates placeholder IDs for invalid GLSL identifiers", function() { const binaryBatchTable = { "\u2716\uFE0F\u2716\uFE0F\u2716\uFE0F": { byteOffset: 0, componentType: "FLOAT", type: "SCALAR" }, temperature: { byteOffset: 12, componentType: "FLOAT", type: "SCALAR" }, // gl_ prefix will be removed, leading to a name collision with // "temperature gl_temperature: { byteOffset: 24, componentType: "FLOAT", type: "SCALAR" } }; const values = new Float32Array([ 10, 15, 25, 20, 30, 15, 25, 20, 20 ]); const binaryBody = new Uint8Array(values.buffer); const customAttributes = []; const metadata = (0, import__679.parseBatchTable)({ count: 3, batchTable: binaryBatchTable, binaryBody, parseAsPropertyAttributes: true, customAttributeOutput: customAttributes }); expect(customAttributes.length).toBe(3); const attributeNames = customAttributes.map(function(attribute) { return attribute.name; }); expect(attributeNames.sort()).toEqual(["_", "_PROPERTY_0", "_TEMPERATURE"]); const [propertyAttribute] = metadata.propertyAttributes; const metadataClass = propertyAttribute.class; const classProperties = [ metadataClass.properties._, metadataClass.properties.property_0, metadataClass.properties.temperature ]; const classPropertyNames = classProperties.map(function(classProperty) { return classProperty.name; }); expect(classPropertyNames.sort()).toEqual( Object.keys(binaryBatchTable).sort() ); const properties = propertyAttribute.properties; expect(Object.keys(properties).sort()).toEqual([ "_", "property_0", "temperature" ]); const semantics = Object.values(properties).map(function(property) { return property.attribute; }); expect(semantics.sort()).toEqual(["_", "_PROPERTY_0", "_TEMPERATURE"]); }); it("handles typed arrays decoded from Draco pnts", function() { const binaryBatchTable = { height: { byteOffset: 0, componentType: "FLOAT", type: "SCALAR", // when decoding Draco, each property is stored in a separate typed // array. typedArray: new Float32Array([10, 15, 25]) }, windDirection: { byteOffset: 12, componentType: "FLOAT", type: "VEC2", // prettier-ignore typedArray: new Float32Array([ 1, 0, 1.1, 0.4, 0.3, 0.2 ]) } }; const binaryBody = void 0; const customAttributes = []; const metadata = (0, import__679.parseBatchTable)({ count: 3, batchTable: binaryBatchTable, binaryBody, parseAsPropertyAttributes: true, customAttributeOutput: customAttributes }); expect(customAttributes.length).toBe(2); const [heightAttribute, windDirectionAttribute] = customAttributes.sort( sortByName ); expect(heightAttribute.name).toBe("_HEIGHT"); expect(heightAttribute.count).toBe(3); expect(heightAttribute.type).toBe("SCALAR"); expect(heightAttribute.componentDatatype).toBe(import__679.ComponentDatatype.FLOAT); expect(heightAttribute.typedArray).toEqual( binaryBatchTable.height.typedArray ); expect(windDirectionAttribute.name).toBe("_WINDDIRECTION"); expect(windDirectionAttribute.count).toBe(3); expect(windDirectionAttribute.type).toBe("VEC2"); expect(windDirectionAttribute.componentDatatype).toBe( import__679.ComponentDatatype.FLOAT ); expect(windDirectionAttribute.typedArray).toEqual( binaryBatchTable.windDirection.typedArray ); const propertyTable = metadata.getPropertyTable(0); expect(propertyTable).not.toBeDefined(); expect(metadata.propertyAttributes.length).toBe(1); const [propertyAttribute] = metadata.propertyAttributes; const metadataClass = propertyAttribute.class; expect(metadataClass.id).toBe(import__679.MetadataClass.BATCH_TABLE_CLASS_NAME); const heightClassProperty = metadataClass.properties.height; expect(heightClassProperty.name).toBe("height"); expect(heightClassProperty.type).toBe(import__679.MetadataType.SCALAR); expect(heightClassProperty.componentType).toBe( import__679.MetadataComponentType.FLOAT32 ); const windClassProperty = metadataClass.properties["windDirection"]; expect(windClassProperty.name).toBe("windDirection"); expect(windClassProperty.type).toBe(import__679.MetadataType.VEC2); expect(windClassProperty.componentType).toBe(import__679.MetadataComponentType.FLOAT32); const properties = propertyAttribute.properties; const heightProperty = properties.height; expect(heightProperty.attribute).toBe("_HEIGHT"); const windProperty = properties.windDirection; expect(windProperty.attribute).toBe("_WINDDIRECTION"); }); it("logs a warning and converts integer attribute property to float", function() { const binaryBatchTable = { height: { byteOffset: 0, componentType: "INT", type: "SCALAR" } }; const heightValues = new Int32Array([10, 15, 25]); const binaryBody = new Uint8Array(heightValues.buffer); spyOn(import__679.parseBatchTable, "_oneTimeWarning"); const customAttributes = []; (0, import__679.parseBatchTable)({ count: 3, batchTable: binaryBatchTable, binaryBody, parseAsPropertyAttributes: true, customAttributeOutput: customAttributes }); expect(customAttributes.length).toBe(1); const [heightAttribute] = customAttributes.sort(sortByName); expect(heightAttribute.name).toBe("_HEIGHT"); expect(heightAttribute.count).toBe(3); expect(heightAttribute.type).toBe("SCALAR"); expect(heightAttribute.componentDatatype).toBe(import__679.ComponentDatatype.FLOAT); expect(import__679.parseBatchTable._oneTimeWarning).toHaveBeenCalled(); }); }); // packages/engine/Specs/Scene/parseFeatureMetadataLegacySpec.js var import__680 = __toESM(require_Cesium(), 1); describe( "Scene/parseFeatureMetadataLegacy", function() { const featureTablesSchema = { classes: { building: { properties: { name: { type: "STRING" }, height: { type: "FLOAT64" } } }, tree: { properties: { species: { type: "STRING" } } } } }; const featureTexturesSchema = { classes: { map: { properties: { color: { type: "ARRAY", componentType: "UINT8", componentCount: 3 }, intensity: { type: "UINT8" } } }, ortho: { properties: { vegetation: { type: "UINT8", normalized: true } } } } }; it("throws without extension", function() { expect(function() { return (0, import__680.parseFeatureMetadataLegacy)({ extension: void 0, schema: import__680.MetadataSchema.fromJson(featureTablesSchema) }); }).toThrowDeveloperError(); }); it("throws without schema", function() { expect(function() { return (0, import__680.parseFeatureMetadataLegacy)({ extension: {}, schema: void 0 }); }).toThrowDeveloperError(); }); it("parses extension with default values", function() { const metadata = (0, import__680.parseFeatureMetadataLegacy)({ extension: {}, schema: import__680.MetadataSchema.fromJson(featureTablesSchema) }); expect(metadata.schema).toBeDefined(); expect(metadata.statistics).toBeUndefined(); expect(metadata.extras).toBeUndefined(); expect(metadata.extensions).toBeUndefined(); }); it("parses extension with feature tables", function() { if (!MetadataTester_default.isSupported()) { return; } const featureTableResults = MetadataTester_default.createFeatureTables({ schema: featureTablesSchema, featureTables: { buildings: { class: "building", properties: { name: ["Building A", "Building B", "Building C"], height: [10, 20, 30] } }, trees: { class: "tree", properties: { species: ["Oak", "Pine"] } } } }); const extension = { schema: featureTablesSchema, featureTables: featureTableResults.featureTables }; const metadata = (0, import__680.parseFeatureMetadataLegacy)({ extension, schema: import__680.MetadataSchema.fromJson(featureTablesSchema), bufferViews: featureTableResults.bufferViews }); const buildingClass = metadata.schema.classes.building; const treeClass = metadata.schema.classes.tree; expect(buildingClass.id).toBe("building"); expect(treeClass.id).toBe("tree"); const buildingsTable = metadata.getPropertyTable(0); const treesTable = metadata.getPropertyTable(1); expect(buildingsTable.id).toBe("buildings"); expect(buildingsTable.name).not.toBeDefined(); expect(buildingsTable.count).toBe(3); expect(buildingsTable.class).toBe(buildingClass); expect(buildingsTable.getPropertyIds().length).toBe(2); expect(buildingsTable.getProperty(0, "name")).toBe("Building A"); expect(buildingsTable.getProperty(1, "name")).toBe("Building B"); expect(buildingsTable.getProperty(2, "name")).toBe("Building C"); expect(buildingsTable.getProperty(0, "height")).toBe(10); expect(buildingsTable.getProperty(1, "height")).toBe(20); expect(buildingsTable.getProperty(2, "height")).toBe(30); expect(treesTable.id).toBe("trees"); expect(treesTable.name).not.toBeDefined(); expect(treesTable.count).toBe(2); expect(treesTable.class).toBe(treeClass); expect(treesTable.getPropertyIds().length).toBe(1); expect(treesTable.getProperty(0, "species")).toBe("Oak"); expect(treesTable.getProperty(1, "species")).toBe("Pine"); }); it("parses extension with feature textures", function() { const context = createContext_default(); const texture0 = new import__680.Texture({ context, pixelFormat: import__680.PixelFormat.RGBA, pixelDatatype: import__680.PixelDatatype.UNSIGNED_BYTE, source: { arrayBufferView: new Uint8Array([1, 2, 3, 4]), width: 1, height: 1 } }); const texture1 = new import__680.Texture({ context, pixelFormat: import__680.PixelFormat.LUMINANCE, pixelDatatype: import__680.PixelDatatype.UNSIGNED_BYTE, source: { arrayBufferView: new Uint8Array([5]), width: 1, height: 1 } }); const textures = { 0: texture0, 1: texture1 }; const extension = { schema: featureTexturesSchema, featureTextures: { mapTexture: { class: "map", properties: { color: { channels: "rgb", texture: { index: 0, texCoord: 0 } }, intensity: { channels: "a", texture: { index: 0, texCoord: 0 } } } }, orthoTexture: { class: "ortho", properties: { vegetation: { channels: "r", texture: { index: 1, texCoord: 1 } } } } } }; const metadata = (0, import__680.parseFeatureMetadataLegacy)({ extension, schema: import__680.MetadataSchema.fromJson(featureTexturesSchema), textures }); const mapClass = metadata.schema.classes.map; const orthoClass = metadata.schema.classes.ortho; expect(mapClass.id).toBe("map"); expect(orthoClass.id).toBe("ortho"); const mapTexture = metadata.getPropertyTexture(0); const orthoTexture = metadata.getPropertyTexture(1); expect(mapTexture.class).toBe(mapClass); expect(mapTexture.id).toBe("mapTexture"); expect(mapTexture.name).not.toBeDefined(); expect(orthoTexture.class).toBe(orthoClass); expect(orthoTexture.id).toBe("orthoTexture"); expect(orthoTexture.name).not.toBeDefined(); texture0.destroy(); texture1.destroy(); context.destroyForSpecs(); }); it("parses extension with statistics", function() { const statistics = { classes: { tree: { count: 100, properties: { height: { min: 10, max: 20 } } } } }; const extension = { statistics }; const metadata = (0, import__680.parseFeatureMetadataLegacy)({ extension, schema: import__680.MetadataSchema.fromJson(featureTexturesSchema) }); expect(metadata.statistics).toBe(statistics); }); it("parses extension with extras", function() { const extras = { description: "Extra" }; const extension = { extras }; const metadata = (0, import__680.parseFeatureMetadataLegacy)({ extension, schema: import__680.MetadataSchema.fromJson(featureTexturesSchema) }); expect(metadata.extras).toBe(extras); }); it("parses extension with extensions", function() { const extensions = { EXT_other_extension: {} }; const extension = { extensions }; const metadata = (0, import__680.parseFeatureMetadataLegacy)({ extension, schema: import__680.MetadataSchema.fromJson(featureTexturesSchema) }); expect(metadata.extensions).toBe(extensions); }); }, "WebGL" ); // packages/engine/Specs/Scene/parseStructuralMetadataSpec.js var import__681 = __toESM(require_Cesium(), 1); describe( "Scene/parseStructuralMetadata", function() { const propertyTablesSchema = { classes: { building: { properties: { name: { type: "STRING" }, height: { type: "SCALAR", componentType: "FLOAT64" } } }, tree: { properties: { species: { type: "STRING" } } } } }; const propertyTexturesSchema = { classes: { map: { properties: { color: { type: "SCALAR", componentType: "UINT8", array: true, count: 3 }, intensity: { type: "SCALAR", componentType: "UINT8" } } }, ortho: { properties: { vegetation: { type: "SCALAR", componentType: "UINT8", normalized: true } } } } }; const propertyAttributesSchema = { classes: { points: { properties: { color: { type: "VEC3", componentType: "UINT8", array: true, count: 3 }, intensity: { type: "SCALAR", componentType: "UINT8" }, pointSize: { type: "SCALAR", componentTYpe: "FLOAT32" } } } } }; it("throws without extension", function() { expect(function() { return (0, import__681.parseStructuralMetadata)({ extension: void 0, schema: import__681.MetadataSchema.fromJson(propertyTablesSchema) }); }).toThrowDeveloperError(); }); it("throws without schema", function() { expect(function() { return (0, import__681.parseStructuralMetadata)({ extension: {}, schema: void 0 }); }).toThrowDeveloperError(); }); it("parses extension with default values", function() { const metadata = (0, import__681.parseStructuralMetadata)({ extension: {}, schema: import__681.MetadataSchema.fromJson(propertyTablesSchema) }); expect(metadata.schema).toBeDefined(); expect(metadata.statistics).toBeUndefined(); expect(metadata.extras).toBeUndefined(); expect(metadata.extensions).toBeUndefined(); }); it("parses extension with property tables", function() { if (!MetadataTester_default.isSupported()) { return; } const propertyTableResults = MetadataTester_default.createPropertyTables({ schema: propertyTablesSchema, propertyTables: [ { name: "Buildings", class: "building", properties: { name: ["Building A", "Building B", "Building C"], height: [10, 20, 30] } }, { name: "Trees", class: "tree", properties: { species: ["Oak", "Pine"] } } ] }); const extension = { schema: propertyTablesSchema, propertyTables: propertyTableResults.propertyTables }; const metadata = (0, import__681.parseStructuralMetadata)({ extension, schema: import__681.MetadataSchema.fromJson(propertyTablesSchema), bufferViews: propertyTableResults.bufferViews }); const buildingClass = metadata.schema.classes.building; const treeClass = metadata.schema.classes.tree; expect(buildingClass.id).toBe("building"); expect(treeClass.id).toBe("tree"); const buildingsTable = metadata.getPropertyTable(0); const treesTable = metadata.getPropertyTable(1); expect(buildingsTable.count).toBe(3); expect(buildingsTable.id).toBe(0); expect(buildingsTable.name).toBe("Buildings"); expect(buildingsTable.class).toBe(buildingClass); expect(buildingsTable.getPropertyIds().length).toBe(2); expect(buildingsTable.getProperty(0, "name")).toBe("Building A"); expect(buildingsTable.getProperty(1, "name")).toBe("Building B"); expect(buildingsTable.getProperty(2, "name")).toBe("Building C"); expect(buildingsTable.getProperty(0, "height")).toBe(10); expect(buildingsTable.getProperty(1, "height")).toBe(20); expect(buildingsTable.getProperty(2, "height")).toBe(30); expect(treesTable.count).toBe(2); expect(treesTable.id).toBe(1); expect(treesTable.name).toBe("Trees"); expect(treesTable.class).toBe(treeClass); expect(treesTable.getPropertyIds().length).toBe(1); expect(treesTable.getProperty(0, "species")).toBe("Oak"); expect(treesTable.getProperty(1, "species")).toBe("Pine"); }); it("parses extension with property textures", function() { const context = createContext_default(); const texture0 = new import__681.Texture({ context, pixelFormat: import__681.PixelFormat.RGBA, pixelDatatype: import__681.PixelDatatype.UNSIGNED_BYTE, source: { arrayBufferView: new Uint8Array([1, 2, 3, 4]), width: 1, height: 1 } }); const texture1 = new import__681.Texture({ context, pixelFormat: import__681.PixelFormat.LUMINANCE, pixelDatatype: import__681.PixelDatatype.UNSIGNED_BYTE, source: { arrayBufferView: new Uint8Array([5]), width: 1, height: 1 } }); const textures = { 0: texture0, 1: texture1 }; const extension = { schema: propertyTexturesSchema, propertyTextures: [ { name: "Map", class: "map", properties: { color: { index: 0, texCoord: 0, channels: [0, 1, 2] }, intensity: { index: 0, texCoord: 0, channels: [3] } } }, { name: "Ortho", class: "ortho", properties: { vegetation: { index: 1, texCoord: 1, channels: [0] } } } ] }; const metadata = (0, import__681.parseStructuralMetadata)({ extension, schema: import__681.MetadataSchema.fromJson(propertyTexturesSchema), textures }); const mapClass = metadata.schema.classes.map; const orthoClass = metadata.schema.classes.ortho; expect(mapClass.id).toBe("map"); expect(orthoClass.id).toBe("ortho"); const mapTexture = metadata.getPropertyTexture(0); const orthoTexture = metadata.getPropertyTexture(1); expect(mapTexture.class).toBe(mapClass); expect(mapTexture.id).toBe(0); expect(mapTexture.name).toBe("Map"); expect(orthoTexture.class).toBe(orthoClass); expect(orthoTexture.id).toBe(1); expect(orthoTexture.name).toBe("Ortho"); texture0.destroy(); texture1.destroy(); context.destroyForSpecs(); }); it("parses extension with property attributes", function() { const extension = { schema: propertyAttributesSchema, propertyAttributes: [ { class: "points", name: "Points", properties: { color: { attribute: "_COLOR" }, intensity: { attribute: "_INTENSITY" }, pointSize: { attribute: "_POINT_SIZE" } } } ] }; const metadata = (0, import__681.parseStructuralMetadata)({ extension, schema: import__681.MetadataSchema.fromJson(propertyAttributesSchema) }); const pointsClass = metadata.schema.classes.points; expect(pointsClass.id).toBe("points"); const propertyAttribute = metadata.getPropertyAttribute(0); expect(propertyAttribute.id).toBe(0); expect(propertyAttribute.name).toBe("Points"); expect(propertyAttribute.class).toBe(pointsClass); expect(propertyAttribute.getProperty("color").attribute).toBe("_COLOR"); expect(propertyAttribute.getProperty("intensity").attribute).toBe( "_INTENSITY" ); expect(propertyAttribute.getProperty("pointSize").attribute).toBe( "_POINT_SIZE" ); }); it("parses extension with statistics", function() { const statistics = { classes: { tree: { count: 100, properties: { height: { min: 10, max: 20 } } } } }; const extension = { statistics }; const metadata = (0, import__681.parseStructuralMetadata)({ extension, schema: import__681.MetadataSchema.fromJson(propertyTexturesSchema) }); expect(metadata.statistics).toBe(statistics); }); it("parses extension with extras", function() { const extras = { description: "Extra" }; const extension = { extras }; const metadata = (0, import__681.parseStructuralMetadata)({ extension, schema: import__681.MetadataSchema.fromJson(propertyTexturesSchema) }); expect(metadata.extras).toBe(extras); }); it("parses extension with extensions", function() { const extensions = { EXT_other_extension: {} }; const extension = { extensions }; const metadata = (0, import__681.parseStructuralMetadata)({ extension, schema: import__681.MetadataSchema.fromJson(propertyTexturesSchema) }); expect(metadata.extensions).toBe(extensions); }); }, "WebGL" ); // packages/engine/Specs/Scene/preprocess3DTileContentSpec.js var import__682 = __toESM(require_Cesium(), 1); describe("Scene/preprocess3DTileContent", function() { function makeBinaryFile(magic) { const binaryFile = new Uint8Array(magic.length + 8); for (let i = 0; i < magic.length; i++) { binaryFile[i] = magic.charCodeAt(i); } return binaryFile; } function makeJsonFile(json) { const jsonString = JSON.stringify(json); const jsonFile = new Uint8Array(jsonString.length); for (let i = 0; i < jsonFile.length; i++) { jsonFile[i] = jsonString.charCodeAt(i); } return jsonFile; } it("detects binary contents by magic number", function() { const magics = ["b3dm", "i3dm", "pnts", "cmpt", "vctr", "geom", "subt"]; magics.forEach(function(magic) { const typedArray = makeBinaryFile(magic); const results = (0, import__682.preprocess3DTileContent)(typedArray.buffer); expect(results).toEqual({ contentType: magic, binaryPayload: typedArray }); }); }); it("detects external tilesets", function() { const externalTileset = { asset: { version: "1.0" }, geometricError: 100, root: {} }; const payload = makeJsonFile(externalTileset); const results = (0, import__682.preprocess3DTileContent)(payload.buffer); expect(results).toEqual({ contentType: import__682.Cesium3DTileContentType.EXTERNAL_TILESET, jsonPayload: externalTileset }); }); it("labels binary glTF as glb", function() { const typedArray = makeBinaryFile("glTF"); const results = (0, import__682.preprocess3DTileContent)(typedArray.buffer); expect(results).toEqual({ contentType: import__682.Cesium3DTileContentType.GLTF_BINARY, binaryPayload: typedArray }); }); it("detects gltf JSON content", function() { const glTF = { asset: { version: "1.0" }, meshes: [] }; const payload = makeJsonFile(glTF); const results = (0, import__682.preprocess3DTileContent)(payload.buffer); expect(results).toEqual({ contentType: import__682.Cesium3DTileContentType.GLTF, jsonPayload: glTF }); }); it("detects GeoJSON content", function() { const geoJson = { type: "FeatureCollection", features: [ { type: "Feature", geometry: { type: "Polygon", coordinates: [ [ [-45, -34.98261613683529, -6.162892770953476], [-45, -35.26438968186486, -6.091842861846089], [-44.700613777413345, -35.40490794190055, -6.194363857619464], [-44.700613777413345, -35.12264233445592, -6.294969339855015], [-45, -34.98261613683529, -6.162892770953476] ] ] } } ] }; const payload = makeJsonFile(geoJson); const results = (0, import__682.preprocess3DTileContent)(payload.buffer); expect(results).toEqual({ contentType: import__682.Cesium3DTileContentType.GEOJSON, jsonPayload: geoJson }); }); it("throws for invalid content", function() { expect(function() { const payload = makeBinaryFile("fake"); (0, import__682.preprocess3DTileContent)(payload.buffer); }).toThrowError(import__682.RuntimeError); }); }); // packages/engine/Specs/Scene/processVoxelPropertiesSpec.js var import__683 = __toESM(require_Cesium(), 1); // Specs/ShaderBuilderTester.js function ShaderBuilderTester() { } function expectHasLine(linesArray, line) { expect(linesArray.indexOf(line)).not.toBe(-1); } function expectEqualUnordered(array1, array2) { expect(array1.slice().sort()).toEqual(array2.slice().sort()); } ShaderBuilderTester.expectHasAttributes = function(shaderBuilder, positionAttributeLine, expectedAttributeLines) { expect(shaderBuilder._positionAttributeLine).toEqual(positionAttributeLine); expectEqualUnordered(shaderBuilder._attributeLines, expectedAttributeLines); }; ShaderBuilderTester.expectHasVertexDefines = function(shaderBuilder, expectedDefines) { expectEqualUnordered( shaderBuilder._vertexShaderParts.defineLines, expectedDefines ); }; ShaderBuilderTester.expectHasFragmentDefines = function(shaderBuilder, expectedDefines) { expectEqualUnordered( shaderBuilder._fragmentShaderParts.defineLines, expectedDefines ); }; ShaderBuilderTester.expectHasVertexUniforms = function(shaderBuilder, expectedUniforms) { expectEqualUnordered( shaderBuilder._vertexShaderParts.uniformLines, expectedUniforms ); }; ShaderBuilderTester.expectHasFragmentUniforms = function(shaderBuilder, expectedUniforms) { expectEqualUnordered( shaderBuilder._fragmentShaderParts.uniformLines, expectedUniforms ); }; ShaderBuilderTester.expectHasVaryings = function(shaderBuilder, expectedVaryings) { expect(shaderBuilder._vertexShaderParts.varyingLines).toEqual( jasmine.arrayWithExactContents( expectedVaryings.map((varying) => jasmine.stringContaining(varying)) ) ); expect(shaderBuilder._fragmentShaderParts.varyingLines).toEqual( jasmine.arrayWithExactContents( expectedVaryings.map((varying) => jasmine.stringContaining(varying)) ) ); }; ShaderBuilderTester.expectHasVertexStructIds = function(shaderBuilder, expectedStructIds) { expect(shaderBuilder._vertexShaderParts.structIds).toEqual(expectedStructIds); }; ShaderBuilderTester.expectHasVertexStruct = function(shaderBuilder, structId, structName, expectedFields) { expectHasLine(shaderBuilder._vertexShaderParts.structIds, structId); const struct = shaderBuilder._structs[structId]; expect(struct.name).toEqual(structName); expectEqualUnordered(struct.fields, expectedFields); }; ShaderBuilderTester.expectHasFragmentStructIds = function(shaderBuilder, expectedStructIds) { expect(shaderBuilder._fragmentShaderParts.structIds).toEqual( expectedStructIds ); }; ShaderBuilderTester.expectHasFragmentStruct = function(shaderBuilder, structId, structName, expectedFields) { expectHasLine(shaderBuilder._fragmentShaderParts.structIds, structId); const struct = shaderBuilder._structs[structId]; expect(struct.name).toEqual(structName); expectEqualUnordered(struct.fields, expectedFields); }; ShaderBuilderTester.expectHasVertexFunctionIds = function(shaderBuilder, expectedFunctionIds) { expect(shaderBuilder._vertexShaderParts.functionIds).toEqual( expectedFunctionIds ); }; ShaderBuilderTester.expectHasVertexFunction = function(shaderBuilder, functionId, signature, bodyLines) { expectHasLine(shaderBuilder._vertexShaderParts.functionIds, functionId); const func = shaderBuilder._functions[functionId]; expect(func.signature).toEqual(signature); expect(func.body).toEqual(bodyLines); }; ShaderBuilderTester.expectHasVertexFunctionUnordered = function(shaderBuilder, functionId, signature, bodyLines) { expectHasLine(shaderBuilder._vertexShaderParts.functionIds, functionId); const func = shaderBuilder._functions[functionId]; expect(func.signature).toEqual(signature); expectEqualUnordered(func.body, bodyLines); }; ShaderBuilderTester.expectHasFragmentFunctionIds = function(shaderBuilder, expectedFunctionIds) { expect(shaderBuilder._fragmentShaderParts.functionIds).toEqual( expectedFunctionIds ); }; ShaderBuilderTester.expectHasFragmentFunction = function(shaderBuilder, functionId, signature, bodyLines) { expectHasLine(shaderBuilder._fragmentShaderParts.functionIds, functionId); const func = shaderBuilder._functions[functionId]; expect(func.signature).toEqual(signature); expect(func.body).toEqual(bodyLines); }; ShaderBuilderTester.expectHasFragmentFunctionUnordered = function(shaderBuilder, functionId, signature, bodyLines) { expectHasLine(shaderBuilder._fragmentShaderParts.functionIds, functionId); const func = shaderBuilder._functions[functionId]; expect(func.signature).toEqual(signature); expectEqualUnordered(func.body, bodyLines); }; ShaderBuilderTester.expectVertexLinesContains = function(shaderBuilder, expectedString) { let hasLine = false; const lines = shaderBuilder._vertexShaderParts.shaderLines; const length2 = lines.length; for (let i = 0; i < length2; i++) { const line = lines[i]; if (line.indexOf(expectedString) > -1) { hasLine = true; break; } } expect(hasLine).toBe(true); }; ShaderBuilderTester.expectVertexLinesEqual = function(shaderBuilder, expectedVertexLines) { expect(shaderBuilder._vertexShaderParts.shaderLines).toEqual( expectedVertexLines ); }; ShaderBuilderTester.expectFragmentLinesContains = function(shaderBuilder, expectedString) { const lines = shaderBuilder._fragmentShaderParts.shaderLines; for (let i = 0; i < lines; i++) { const line = lines[i]; expect(line.indexOf(expectedString)).toBeGreaterThan(-1); } }; ShaderBuilderTester.expectFragmentLinesEqual = function(shaderBuilder, expectedFragmentLines) { expect(shaderBuilder._fragmentShaderParts.shaderLines).toEqual( expectedFragmentLines ); }; var ShaderBuilderTester_default = ShaderBuilderTester; // packages/engine/Specs/Scene/processVoxelPropertiesSpec.js describe("Scene/processVoxelProperties", function() { let scene2; let provider; beforeAll(async function() { scene2 = createScene_default(); provider = await import__683.Cesium3DTilesVoxelProvider.fromUrl( "./Data/Cesium3DTiles/Voxel/VoxelEllipsoid3DTiles/tileset.json" ); }); afterAll(function() { scene2.destroyForSpecs(); }); it("adds shader defines and structs", async function() { const primitive = new import__683.VoxelPrimitive({ provider }); primitive.update(scene2.frameState); const renderResources = new import__683.VoxelRenderResources(primitive); (0, import__683.processVoxelProperties)(renderResources, primitive); const { shaderBuilder } = renderResources; ShaderBuilderTester_default.expectFragmentLinesContains(shaderBuilder, [ "#define METADATA_COUNT 1", "#define STATISTICS" ]); const propertyStatisticsFields = [" float min;", " float max;"]; ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, "PropertyStatistics_a", "PropertyStatistics_a", propertyStatisticsFields ); const statisticsFields = [" PropertyStatistics_a a;"]; ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, "Statistics", "Statistics", statisticsFields ); const metadataFields = [" Statistics statistics;", " float a;"]; ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, "Metadata", "Metadata", metadataFields ); const voxelPropertyFields = [ " vec3 partialDerivativeLocal;", " vec3 partialDerivativeWorld;", " vec3 partialDerivativeView;", " vec3 partialDerivativeValid;" ]; ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, "VoxelProperty_a", "VoxelProperty_a", voxelPropertyFields ); const voxelFields = [ " VoxelProperty_a a;", " vec3 positionEC;", " vec3 positionUv;", " vec3 positionShapeUv;", " vec3 positionUvLocal;", " vec3 surfaceNormal;", " vec3 viewDirUv;", " vec3 viewDirWorld;", " float travelDistance;", " int stepCount;", " int sampleIndex;", " int tileIndex;" ]; ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, "Voxel", "Voxel", voxelFields ); const fragmentInputFields = [" Metadata metadata;", " Voxel voxel;"]; ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, "FragmentInput", "FragmentInput", fragmentInputFields ); const propertiesFields = [" float a;"]; ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, "Properties", "Properties", propertiesFields ); }); }); // packages/engine/Specs/Scene/Model/AlphaPipelineStageSpec.js var import__684 = __toESM(require_Cesium(), 1); describe( "Scene/Model/AlphaPipelineStage", function() { const mockModel = { opaquePass: import__684.Pass.CESIUM_3D_TILE }; const mockPrimitive = {}; const mockFrameState = {}; function mockRenderResources(alphaOptions) { return { model: mockModel, shaderBuilder: new import__684.ShaderBuilder(), alphaOptions: (0, import__684.defaultValue)(alphaOptions, new import__684.ModelAlphaOptions()), uniformMap: {}, renderStateOptions: import__684.RenderState.getState(import__684.RenderState.fromCache()) }; } it("defaults to the model's pass if not specified", function() { const renderResources = mockRenderResources(); expect(renderResources.alphaOptions.pass).not.toBeDefined(); import__684.AlphaPipelineStage.process( renderResources, mockPrimitive, mockFrameState ); expect(renderResources.alphaOptions.pass).toBe(mockModel.opaquePass); }); it("sets render state options when given translucent pass", function() { const alphaOptions = new import__684.ModelAlphaOptions(); alphaOptions.pass = import__684.Pass.TRANSLUCENT; const renderResources = mockRenderResources(alphaOptions); expect(renderResources.alphaOptions.pass).toBe(import__684.Pass.TRANSLUCENT); import__684.AlphaPipelineStage.process( renderResources, mockPrimitive, mockFrameState ); const renderStateOptions = renderResources.renderStateOptions; expect(renderStateOptions.cull.enabled).toBe(false); expect(renderStateOptions.depthMask).toBe(false); expect(renderStateOptions.blending).toBe(import__684.BlendingState.ALPHA_BLEND); }); it("handles alphaCutoff", function() { const cutoff = 0.6; const alphaOptions = new import__684.ModelAlphaOptions(); alphaOptions.alphaCutoff = cutoff; alphaOptions.pass = import__684.Pass.TRANSLUCENT; const renderResources = mockRenderResources(alphaOptions); import__684.AlphaPipelineStage.process( renderResources, mockPrimitive, mockFrameState ); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "ALPHA_MODE_MASK" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform float u_alphaCutoff;" ]); expect(renderResources.uniformMap.u_alphaCutoff()).toBe(cutoff); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/AtmospherePipelineStageSpec.js var import__685 = __toESM(require_Cesium(), 1); describe( "Scene/Model/AtmospherePipelineStage", function() { const boxTexturedGlbUrl = "./Data/Models/glTF-2.0/BoxTextured/glTF-Binary/BoxTextured.glb"; let scene2; let model; beforeAll(async function() { scene2 = createScene_default(); const center = import__685.Cartesian3.fromDegrees(0, 0, 0); model = await loadAndZoomToModelAsync_default( { url: boxTexturedGlbUrl, modelMatrix: import__685.Transforms.eastNorthUpToFixedFrame(center) }, scene2 ); }); let renderResources; beforeEach(async function() { renderResources = new import__685.ModelRenderResources(model); scene2.frameState.camera.position = import__685.Cartesian3.fromDegrees(0.01, 0, 1e3); scene2.frameState.camera.direction = new import__685.Cartesian3(0, -1, 0); scene2.fog.density = 2e-4; }); afterAll(async function() { scene2.destroyForSpecs(); }); it("configures shader", function() { import__685.AtmospherePipelineStage.process(renderResources, model, scene2.frameState); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_ATMOSPHERE", "COMPUTE_POSITION_WC_ATMOSPHERE" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_ATMOSPHERE", "COMPUTE_POSITION_WC_ATMOSPHERE" ]); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "vec3 v_atmosphereRayleighColor;", "vec3 v_atmosphereMieColor;", "float v_atmosphereOpacity;" ]); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__685._shadersAtmosphereStageVS ]); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__685._shadersAtmosphereStageFS ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform bool u_isInFog;" ]); }); it("u_isInFog() is false if the camera is at the model center", function() { const frameState2 = scene2.frameState; frameState2.camera.position = import__685.Cartesian3.clone( model.boundingSphere.center, frameState2.camera.position ); scene2.renderForSpecs(); import__685.AtmospherePipelineStage.process(renderResources, model, frameState2); const uniformMap = renderResources.uniformMap; expect(uniformMap.u_isInFog()).toBe(false); }); it("u_isInFog() is false if the camera is in space", function() { const frameState2 = scene2.frameState; frameState2.camera.position = import__685.Cartesian3.fromDegrees(0.01, 0, 9e5); scene2.renderForSpecs(); import__685.AtmospherePipelineStage.process(renderResources, model, frameState2); const uniformMap = renderResources.uniformMap; expect(uniformMap.u_isInFog()).toBe(false); }); it("u_isInFog() is true when the tile is in fog", function() { scene2.renderForSpecs(); import__685.AtmospherePipelineStage.process(renderResources, model, scene2.frameState); const uniformMap = renderResources.uniformMap; expect(uniformMap.u_isInFog()).toBe(true); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/B3dmLoaderSpec.js var import__686 = __toESM(require_Cesium(), 1); describe( "Scene/Model/B3dmLoader", function() { const withBatchTableUrl = "./Data/Cesium3DTiles/Batched/BatchedWithBatchTable/batchedWithBatchTable.b3dm"; const withBatchTableBinaryUrl = "./Data/Cesium3DTiles/Batched/BatchedWithBatchTableBinary/batchedWithBatchTableBinary.b3dm"; const withoutBatchTableUrl = "./Data/Cesium3DTiles/Batched/BatchedWithoutBatchTable/batchedWithoutBatchTable.b3dm"; const withRtcCenterUrl = "./Data/Cesium3DTiles/Batched/BatchedWithRtcCenter/batchedWithRtcCenter.b3dm"; const withBatchTableHierarchy = "./Data/Cesium3DTiles/Hierarchy/BatchTableHierarchy/tile.b3dm"; const noBatchIdsUrl = "Data/Cesium3DTiles/Batched/BatchedNoBatchIds/batchedNoBatchIds.b3dm"; let scene2; const b3dmLoaders = []; beforeAll(function() { scene2 = createScene_default(); spyOn(import__686.B3dmParser, "_deprecationWarning"); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { for (let i = 0; i < b3dmLoaders.length; i++) { const loader = b3dmLoaders[i]; if (!loader.isDestroyed()) { loader.destroy(); } } b3dmLoaders.length = 0; import__686.ResourceCache.clearForSpecs(); }); async function loadB3dmArrayBuffer(resource, arrayBuffer) { const loader = new import__686.B3dmLoader({ b3dmResource: resource, arrayBuffer }); b3dmLoaders.push(loader); await loader.load(); await waitForLoaderProcess_default(loader, scene2); return loader; } function loadB3dm(b3dmPath) { const resource = import__686.Resource.createIfNeeded(b3dmPath); return import__686.Resource.fetchArrayBuffer({ url: b3dmPath }).then(function(arrayBuffer) { return loadB3dmArrayBuffer(resource, arrayBuffer); }); } async function expectLoadError(arrayBuffer) { const resource = new import__686.Resource("http://example.com/test.b3dm"); await expectAsync( loadB3dmArrayBuffer(resource, arrayBuffer) ).toBeRejectedWithError(import__686.RuntimeError); } it("releases array buffer when finished loading", function() { return loadB3dm(noBatchIdsUrl).then(function(loader) { expect(loader.components).toBeDefined(); expect(loader._arrayBuffer).not.toBeDefined(); }); }); it("loads BatchedNoBatchIds", function() { return loadB3dm(noBatchIdsUrl).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); const structuralMetadata = components.structuralMetadata; expect(structuralMetadata).toBeUndefined(); }); }); it("loads BatchedWithBatchTable", function() { return loadB3dm(withBatchTableUrl).then(function(loader) { const components = loader.components; const structuralMetadata = components.structuralMetadata; const propertyTable = structuralMetadata.getPropertyTable(0); expect(propertyTable).toBeDefined(); expect(propertyTable.count).toEqual(10); expect(propertyTable.class).toBeDefined(); }); }); it("loads BatchedWithBatchTableBinary", function() { return loadB3dm(withBatchTableBinaryUrl).then(function(loader) { const components = loader.components; const structuralMetadata = components.structuralMetadata; const propertyTable = structuralMetadata.getPropertyTable(0); expect(propertyTable).toBeDefined(); expect(propertyTable.count).toEqual(10); expect(propertyTable.class).toBeDefined(); }); }); it("loads BatchedWithoutBatchTableUrl", function() { return loadB3dm(withoutBatchTableUrl).then(function(loader) { const components = loader.components; const structuralMetadata = components.structuralMetadata; const propertyTable = structuralMetadata.getPropertyTable(0); expect(propertyTable).toBeDefined(); expect(propertyTable.count).toEqual(10); expect(propertyTable.class).toBeUndefined(); }); }); it("loads BatchedWithRtcCenterUrl", function() { return loadB3dm(withRtcCenterUrl).then(function(loader) { const components = loader.components; const structuralMetadata = components.structuralMetadata; const propertyTable = structuralMetadata.getPropertyTable(0); expect(propertyTable).toBeDefined(); expect(propertyTable.count).toEqual(10); expect(loader.components.transform).toEqual( import__686.Matrix4.fromTranslation(new import__686.Cartesian3(0.1, 0.2, 0.3)) ); }); }); it("loads BatchTableHierarchy", function() { return loadB3dm(withBatchTableHierarchy).then(function(loader) { const components = loader.components; const structuralMetadata = components.structuralMetadata; const propertyTable = structuralMetadata.getPropertyTable(0); expect(propertyTable).toBeDefined(); expect(propertyTable.count).toEqual(30); expect(propertyTable._batchTableHierarchy).toBeDefined(); }); }); it("throws with invalid version", async function() { const arrayBuffer = Cesium3DTilesTester_default.generateBatchedTileBuffer({ version: 2 }); await expectLoadError(arrayBuffer); }); it("throws with empty gltf", async function() { const arrayBuffer = Cesium3DTilesTester_default.generateBatchedTileBuffer(); await expectLoadError(arrayBuffer); }); it("destroys b3dm loader", function() { const unloadGltfLoader = spyOn( import__686.GltfLoader.prototype, "unload" ).and.callThrough(); return loadB3dm(withBatchTableUrl).then(function(loader) { expect(loader.components).toBeDefined(); expect(loader.isDestroyed()).toBe(false); loader.destroy(); expect(loader.components).toBeUndefined(); expect(loader.isDestroyed()).toBe(true); expect(unloadGltfLoader.calls.count()).toBe(1); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/BatchTexturePipelineStageSpec.js var import__687 = __toESM(require_Cesium(), 1); describe("Scene/Model/BatchTexturePipelineStage", function() { function expectUniformMap(uniformMap, expected) { for (const key in expected) { if (expected.hasOwnProperty(key)) { const expectedValue = expected[key]; const uniformFunction = uniformMap[key]; expect(uniformFunction).toBeDefined(); expect(uniformFunction()).toEqual(expectedValue); } } } function verifyBatchTextureUniforms(featureTable, uniformMap) { const expectedUniforms = { model_featuresLength: featureTable.featuresLength, model_batchTexture: featureTable.batchTexture.batchTexture, model_textureDimensions: featureTable.batchTexture.textureDimensions, model_textureStep: featureTable.batchTexture.textureStep }; expectUniformMap(uniformMap, expectedUniforms); } function verifyBatchTextureShaders(shaderBuilder) { ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "MULTILINE_BATCH_TEXTURE" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "MULTILINE_BATCH_TEXTURE" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform int model_featuresLength;", "uniform sampler2D model_batchTexture;", "uniform vec4 model_textureStep;", "uniform vec2 model_textureDimensions;" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform int model_featuresLength;", "uniform sampler2D model_batchTexture;", "uniform vec4 model_textureStep;", "uniform vec2 model_textureDimensions;" ]); } it("sets up batch textures from Model", function() { const renderResources = { shaderBuilder: new import__687.ShaderBuilder(), model: { featureTableId: 0, featureTables: [ { featuresLength: 10, batchTexture: { batchTexture: 0, textureDimensions: { y: 2 }, textureStep: 2 } } ] } }; import__687.BatchTexturePipelineStage.process(renderResources, {}, {}); verifyBatchTextureShaders(renderResources.shaderBuilder); verifyBatchTextureUniforms( renderResources.model.featureTables[0], renderResources.uniformMap ); }); }); // packages/engine/Specs/Scene/Model/CPUStylingPipelineStageSpec.js var import__688 = __toESM(require_Cesium(), 1); describe("Scene/Model/CPUStylingPipelineStage", function() { const defaultRenderResources = { alphaOptions: new import__688.ModelAlphaOptions(), model: { colorBlendMode: import__688.ColorBlendMode.HIGHLIGHT, colorBlendAmount: 0.5, featureTableId: 0, featureTables: [ { featuresLength: 10, batchTexture: { translucentFeaturesLength: 0 } } ] }, shaderBuilder: new import__688.ShaderBuilder(), uniformMap: {} }; it("adds shader functions", function() { const renderResources = (0, import__688.clone)(defaultRenderResources, true); const shaderBuilder = renderResources.shaderBuilder; import__688.CPUStylingPipelineStage.process(renderResources); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__688._shadersCPUStylingStageFS ]); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__688._shadersCPUStylingStageVS ]); }); it("adds color blend uniform", function() { const renderResources = (0, import__688.clone)(defaultRenderResources, true); renderResources.model.colorBlendAmount = 0.75; renderResources.model.colorBlendMode = import__688.ColorBlendMode.MIX; const colorBlend = import__688.ColorBlendMode.getColorBlend( renderResources.model.colorBlendMode, renderResources.model.colorBlendAmount ); import__688.CPUStylingPipelineStage.process(renderResources); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform bool model_commandTranslucent;", "uniform float model_colorBlend;" ]); expect(uniformMap.model_colorBlend()).toEqual(colorBlend); expect(uniformMap.model_commandTranslucent()).toBe(false); }); it("doesn't add color blend uniform if model color is present", function() { const renderResources = (0, import__688.clone)(defaultRenderResources, true); renderResources.model.color = import__688.Color.RED; renderResources.model.colorBlendAmount = 0.75; renderResources.model.colorBlendMode = import__688.ColorBlendMode.MIX; import__688.CPUStylingPipelineStage.process(renderResources); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform bool model_commandTranslucent;" ]); expect(uniformMap.model_colorBlend).toBeUndefined(); expect(uniformMap.model_commandTranslucent()).toBe(false); }); it("adds command translucent uniform", function() { const renderResources = (0, import__688.clone)(defaultRenderResources, true); renderResources.alphaOptions.pass = import__688.Pass.TRANSLUCENT; import__688.CPUStylingPipelineStage.process(renderResources); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform bool model_commandTranslucent;", "uniform float model_colorBlend;" ]); expect(uniformMap.model_commandTranslucent()).toEqual(true); }); it("model_commandTranslucent accounts for changes from later pipeline stages", function() { const renderResources = (0, import__688.clone)(defaultRenderResources, true); renderResources.model.color = import__688.Color.RED; renderResources.model.colorBlendAmount = 0.75; renderResources.model.colorBlendMode = import__688.ColorBlendMode.MIX; import__688.CPUStylingPipelineStage.process(renderResources); const uniformMap = renderResources.uniformMap; expect(uniformMap.model_commandTranslucent()).toBe(false); renderResources.alphaOptions.pass = import__688.Pass.TRANSLUCENT; expect(uniformMap.model_commandTranslucent()).toBe(true); }); }); // packages/engine/Specs/Scene/Model/ClassificationModelDrawCommandSpec.js var import__689 = __toESM(require_Cesium(), 1); describe( "Scene/Model/ClassificationModelDrawCommand", function() { const noColor = new import__689.Color(0, 0, 0, 0); const batchLengths = [6, 6, 3]; const batchOffsets = [0, 6, 12]; const mockPickId = "mockPickId"; const mockFrameState = { commandList: [], passes: { render: true, pick: false } }; const mockFrameStateWithInvertedClassification = { commandList: [], invertClassification: true, passes: { render: true, pick: false } }; const mockFrameStatePickOnly = { commandList: [], passes: { render: false, pick: true } }; function mockRenderResources(options) { const debugWireframe = (0, import__689.defaultValue)(options.debugWireframe, false); const allowPicking = (0, import__689.defaultValue)(options.allowPicking, false); return { model: { classificationType: options.classificationType, _enableDebugWireframe: debugWireframe, debugWireframe, allowPicking }, runtimePrimitive: { boundingSphere: new import__689.BoundingSphere(import__689.Cartesian3.ZERO, 1), batchLengths: options.batchLengths, batchOffsets: options.batchOffsets }, pickId: options.pickId }; } function createDrawCommand2(options) { options = (0, import__689.defaultValue)(options, {}); options.modelMatrix = import__689.Matrix4.clone(import__689.Matrix4.IDENTITY); const boundingSphere = new import__689.BoundingSphere(import__689.Cartesian3.ZERO, 1); options.boundingVolume = import__689.BoundingSphere.transform( boundingSphere, options.modelMatrix, boundingSphere ); options.renderState = (0, import__689.defaultValue)( options.renderState, import__689.RenderState.fromCache() ); options.pass = import__689.Pass.OPAQUE; options.uniformMap = {}; return new import__689.DrawCommand(options); } function verifyStencilDepthCommand(command, expectedPass, expectedStencilFunction, testForPicking) { testForPicking = (0, import__689.defaultValue)(testForPicking, false); expect(command.pass).toBe(expectedPass); expect(command.pickId).toBeUndefined(); const expectedValue = testForPicking; expect(command.cull).toBe(expectedValue); expect(command.pickOnly).toBe(expectedValue); const renderState = command.renderState; expect(renderState.colorMask).toEqual({ red: false, green: false, blue: false, alpha: false }); const expectedStencilTest = { enabled: true, frontFunction: expectedStencilFunction, frontOperation: { fail: import__689.StencilOperation.KEEP, zFail: import__689.StencilOperation.DECREMENT_WRAP, zPass: import__689.StencilOperation.KEEP }, backFunction: expectedStencilFunction, backOperation: { fail: import__689.StencilOperation.KEEP, zFail: import__689.StencilOperation.INCREMENT_WRAP, zPass: import__689.StencilOperation.KEEP }, reference: import__689.StencilConstants.CESIUM_3D_TILE_MASK, mask: import__689.StencilConstants.CESIUM_3D_TILE_MASK }; expect(renderState.stencilTest).toEqual(expectedStencilTest); expect(renderState.stencilMask).toEqual( import__689.StencilConstants.CLASSIFICATION_MASK ); expect(renderState.depthTest).toEqual({ enabled: true, func: import__689.DepthFunction.LESS_OR_EQUAL }); expect(renderState.depthMask).toEqual(false); } const expectedColorCommandBlending = (0, import__689.clone)( import__689.BlendingState.PRE_MULTIPLIED_ALPHA_BLEND, true ); expectedColorCommandBlending.color = noColor; function verifyColorCommand(command, expectedPass, testForPicking) { testForPicking = (0, import__689.defaultValue)(testForPicking, false); expect(command.pass).toBe(expectedPass); if (testForPicking) { expect(command.cull).toBe(true); expect(command.pickOnly).toBe(true); expect(command.pickId).toBeDefined(); } else { expect(command.cull).toBe(false); expect(command.pickOnly).toBe(false); expect(command.pickId).toBeUndefined(); } const renderState = command.renderState; const expectedStencilTest = { enabled: true, frontFunction: import__689.StencilFunction.NOT_EQUAL, frontOperation: { fail: import__689.StencilOperation.ZERO, zFail: import__689.StencilOperation.ZERO, zPass: import__689.StencilOperation.ZERO }, backFunction: import__689.StencilFunction.NOT_EQUAL, backOperation: { fail: import__689.StencilOperation.ZERO, zFail: import__689.StencilOperation.ZERO, zPass: import__689.StencilOperation.ZERO }, reference: 0, mask: import__689.StencilConstants.CLASSIFICATION_MASK }; expect(renderState.stencilTest).toEqual(expectedStencilTest); expect(renderState.stencilMask).toEqual( import__689.StencilConstants.CLASSIFICATION_MASK ); expect(renderState.depthTest.enabled).toEqual(false); expect(renderState.depthMask).toEqual(false); if (testForPicking) { expect(renderState.blending.enabled).toBe(false); } else { expect(renderState.blending).toEqual(expectedColorCommandBlending); } } beforeEach(function() { mockFrameState.commandList.length = 0; mockFrameStateWithInvertedClassification.commandList.length = 0; mockFrameStatePickOnly.commandList.length = 0; }); function verifyBatchedStencilAndColorCommands(drawCommand, commandList, expectedPass, expectedStencilFunction, testForPicking) { const batchLengths2 = drawCommand.batchLengths; const batchOffsets2 = drawCommand.batchOffsets; const numBatches = batchLengths2.length; expect(commandList.length).toEqual(numBatches * 2); testForPicking = (0, import__689.defaultValue)(testForPicking, false); for (let i = 0; i < numBatches; i++) { const stencilDepthCommand = commandList[i * 2]; expect(stencilDepthCommand.count).toBe(batchLengths2[i]); expect(stencilDepthCommand.offset).toBe(batchOffsets2[i]); verifyStencilDepthCommand( stencilDepthCommand, expectedPass, expectedStencilFunction, testForPicking ); const colorCommand = commandList[i * 2 + 1]; verifyColorCommand(colorCommand, expectedPass, testForPicking); expect(colorCommand.count).toBe(batchLengths2[i]); expect(colorCommand.offset).toBe(batchOffsets2[i]); } } it("throws for undefined command", function() { expect(function() { return new import__689.ClassificationModelDrawCommand({ command: void 0, primitiveRenderResources: {} }); }).toThrowDeveloperError(); }); it("throws for undefined primitiveRenderResources", function() { expect(function() { return new import__689.ClassificationModelDrawCommand({ command: new import__689.DrawCommand(), primitiveRenderResources: void 0 }); }).toThrowDeveloperError(); }); it("constructs for terrain classification", function() { const renderResources = mockRenderResources({ classificationType: import__689.ClassificationType.TERRAIN, batchLengths, batchOffsets }); const command = createDrawCommand2(); const drawCommand = new import__689.ClassificationModelDrawCommand({ primitiveRenderResources: renderResources, command }); expect(drawCommand.command).toBe(command); expect(drawCommand.runtimePrimitive).toBe( renderResources.runtimePrimitive ); expect(drawCommand.model).toBe(renderResources.model); expect(drawCommand.modelMatrix).toBe(command.modelMatrix); expect(drawCommand.boundingVolume).toBe(command.boundingVolume); expect(drawCommand.classificationType).toBe(import__689.ClassificationType.TERRAIN); expect(drawCommand._classifiesTerrain).toBe(true); expect(drawCommand._classifies3DTiles).toBe(false); const commandList = drawCommand._commandListTerrain; const expectedPass = import__689.Pass.TERRAIN_CLASSIFICATION; const expectedStencilFunction = import__689.StencilFunction.ALWAYS; verifyBatchedStencilAndColorCommands( drawCommand, commandList, expectedPass, expectedStencilFunction ); expect(drawCommand._commandList3DTiles.length).toBe(0); expect(drawCommand._commandListIgnoreShow.length).toBe(0); expect(drawCommand._commandListDebugWireframe.length).toBe(0); }); it("constructs for 3D Tiles classification", function() { const renderResources = mockRenderResources({ classificationType: import__689.ClassificationType.CESIUM_3D_TILE, batchLengths, batchOffsets }); const command = createDrawCommand2(); const drawCommand = new import__689.ClassificationModelDrawCommand({ primitiveRenderResources: renderResources, command }); expect(drawCommand.command).toBe(command); expect(drawCommand.runtimePrimitive).toBe( renderResources.runtimePrimitive ); expect(drawCommand.model).toBe(renderResources.model); expect(drawCommand.modelMatrix).toBe(command.modelMatrix); expect(drawCommand.boundingVolume).toBe(command.boundingVolume); expect(drawCommand.classificationType).toBe( import__689.ClassificationType.CESIUM_3D_TILE ); expect(drawCommand._classifiesTerrain).toBe(false); expect(drawCommand._classifies3DTiles).toBe(true); const commandList = drawCommand._commandList3DTiles; const expectedPass = import__689.Pass.CESIUM_3D_TILE_CLASSIFICATION; const expectedStencilFunction = import__689.StencilFunction.EQUAL; verifyBatchedStencilAndColorCommands( drawCommand, commandList, expectedPass, expectedStencilFunction ); expect(drawCommand._commandListTerrain.length).toBe(0); expect(drawCommand._commandListIgnoreShow.length).toBe(0); expect(drawCommand._commandListDebugWireframe.length).toBe(0); }); it("constructs for both classifications", function() { const renderResources = mockRenderResources({ classificationType: import__689.ClassificationType.BOTH, batchLengths, batchOffsets }); const command = createDrawCommand2(); const drawCommand = new import__689.ClassificationModelDrawCommand({ primitiveRenderResources: renderResources, command }); expect(drawCommand.command).toBe(command); expect(drawCommand.runtimePrimitive).toBe( renderResources.runtimePrimitive ); expect(drawCommand.model).toBe(renderResources.model); expect(drawCommand.modelMatrix).toBe(command.modelMatrix); expect(drawCommand.boundingVolume).toBe(command.boundingVolume); expect(drawCommand.classificationType).toBe(import__689.ClassificationType.BOTH); expect(drawCommand._classifiesTerrain).toBe(true); expect(drawCommand._classifies3DTiles).toBe(true); let commandList = drawCommand._commandListTerrain; let expectedPass = import__689.Pass.TERRAIN_CLASSIFICATION; let expectedStencilFunction = import__689.StencilFunction.ALWAYS; verifyBatchedStencilAndColorCommands( drawCommand, commandList, expectedPass, expectedStencilFunction ); commandList = drawCommand._commandList3DTiles; expectedPass = import__689.Pass.CESIUM_3D_TILE_CLASSIFICATION; expectedStencilFunction = import__689.StencilFunction.EQUAL; verifyBatchedStencilAndColorCommands( drawCommand, commandList, expectedPass, expectedStencilFunction ); expect(drawCommand._commandListIgnoreShow.length).toBe(0); expect(drawCommand._commandListDebugWireframe.length).toBe(0); }); it("constructs for debug wireframe", function() { const renderResources = mockRenderResources({ classificationType: import__689.ClassificationType.BOTH, debugWireframe: true, batchLengths, batchOffsets }); const command = createDrawCommand2(); const drawCommand = new import__689.ClassificationModelDrawCommand({ primitiveRenderResources: renderResources, command }); expect(drawCommand.command).toBe(command); expect(drawCommand.runtimePrimitive).toBe( renderResources.runtimePrimitive ); expect(drawCommand.model).toBe(renderResources.model); expect(drawCommand.modelMatrix).toBe(command.modelMatrix); expect(drawCommand.boundingVolume).toBe(command.boundingVolume); expect(drawCommand.classificationType).toBe(import__689.ClassificationType.BOTH); expect(drawCommand._classifiesTerrain).toBe(true); expect(drawCommand._classifies3DTiles).toBe(true); expect(drawCommand._useDebugWireframe).toBe(true); const numBatches = batchLengths.length; const commandList = drawCommand._commandListDebugWireframe; expect(commandList.length).toEqual(numBatches); for (let i = 0; i < numBatches; i++) { const wireframeCommand = commandList[i]; expect(wireframeCommand.count).toBe(batchLengths[i] * 2); expect(wireframeCommand.offset).toBe(batchOffsets[i] * 2); expect(wireframeCommand.pass).toBe(import__689.Pass.OPAQUE); } expect(drawCommand._commandListTerrain.length).toBe(0); expect(drawCommand._commandList3DTiles.length).toBe(0); expect(drawCommand._commandListIgnoreShow.length).toBe(0); }); describe("pick commands", function() { it("constructs pick commands for terrain classification", function() { const renderResources = mockRenderResources({ allowPicking: true, pickId: mockPickId, classificationType: import__689.ClassificationType.TERRAIN, batchLengths, batchOffsets }); const command = createDrawCommand2(); const drawCommand = new import__689.ClassificationModelDrawCommand({ primitiveRenderResources: renderResources, command }); expect(drawCommand.classificationType).toBe(import__689.ClassificationType.TERRAIN); expect(drawCommand._classifiesTerrain).toBe(true); expect(drawCommand._classifies3DTiles).toBe(false); expect(drawCommand._pickId).toEqual(mockPickId); const commandList = drawCommand._commandListTerrainPicking; const expectedPass = import__689.Pass.TERRAIN_CLASSIFICATION; const expectedStencilFunction = import__689.StencilFunction.ALWAYS; const testForPicking = true; verifyBatchedStencilAndColorCommands( drawCommand, commandList, expectedPass, expectedStencilFunction, testForPicking ); expect(drawCommand._commandListTerrain.length).toBe(6); expect(drawCommand._commandList3DTiles.length).toBe(0); expect(drawCommand._commandList3DTilesPicking.length).toBe(0); expect(drawCommand._commandListIgnoreShow.length).toBe(0); expect(drawCommand._commandListDebugWireframe.length).toBe(0); }); it("constructs pick commands for 3D Tiles classification", function() { const renderResources = mockRenderResources({ allowPicking: true, pickId: mockPickId, classificationType: import__689.ClassificationType.CESIUM_3D_TILE, batchLengths, batchOffsets }); const command = createDrawCommand2(); const drawCommand = new import__689.ClassificationModelDrawCommand({ primitiveRenderResources: renderResources, command }); expect(drawCommand.classificationType).toBe( import__689.ClassificationType.CESIUM_3D_TILE ); expect(drawCommand._classifiesTerrain).toBe(false); expect(drawCommand._classifies3DTiles).toBe(true); expect(drawCommand._pickId).toEqual(mockPickId); const commandList = drawCommand._commandList3DTilesPicking; const expectedPass = import__689.Pass.CESIUM_3D_TILE_CLASSIFICATION; const expectedStencilFunction = import__689.StencilFunction.EQUAL; const testForPicking = true; verifyBatchedStencilAndColorCommands( drawCommand, commandList, expectedPass, expectedStencilFunction, testForPicking ); expect(drawCommand._commandList3DTiles.length).toBe(6); expect(drawCommand._commandListTerrain.length).toBe(0); expect(drawCommand._commandListTerrainPicking.length).toBe(0); expect(drawCommand._commandListIgnoreShow.length).toBe(0); expect(drawCommand._commandListDebugWireframe.length).toBe(0); }); it("constructs pick commands for both classifications", function() { const renderResources = mockRenderResources({ allowPicking: true, pickId: mockPickId, classificationType: import__689.ClassificationType.BOTH, batchLengths, batchOffsets }); const command = createDrawCommand2(); const drawCommand = new import__689.ClassificationModelDrawCommand({ primitiveRenderResources: renderResources, command }); expect(drawCommand.classificationType).toBe(import__689.ClassificationType.BOTH); expect(drawCommand._classifiesTerrain).toBe(true); expect(drawCommand._classifies3DTiles).toBe(true); const testForPicking = true; let commandList = drawCommand._commandListTerrainPicking; let expectedPass = import__689.Pass.TERRAIN_CLASSIFICATION; let expectedStencilFunction = import__689.StencilFunction.ALWAYS; verifyBatchedStencilAndColorCommands( drawCommand, commandList, expectedPass, expectedStencilFunction, testForPicking ); commandList = drawCommand._commandList3DTilesPicking; expectedPass = import__689.Pass.CESIUM_3D_TILE_CLASSIFICATION; expectedStencilFunction = import__689.StencilFunction.EQUAL; verifyBatchedStencilAndColorCommands( drawCommand, commandList, expectedPass, expectedStencilFunction, testForPicking ); expect(drawCommand._commandListTerrain.length).toBe(6); expect(drawCommand._commandList3DTiles.length).toBe(6); expect(drawCommand._commandListIgnoreShow.length).toBe(0); expect(drawCommand._commandListDebugWireframe.length).toBe(0); }); it("does not construct pick commands if allowPicking is false", function() { const renderResources = mockRenderResources({ allowPicking: false, pickId: mockPickId, classificationType: import__689.ClassificationType.BOTH, batchLengths, batchOffsets }); const command = createDrawCommand2(); const drawCommand = new import__689.ClassificationModelDrawCommand({ primitiveRenderResources: renderResources, command }); expect(drawCommand.classificationType).toBe(import__689.ClassificationType.BOTH); expect(drawCommand._classifiesTerrain).toBe(true); expect(drawCommand._classifies3DTiles).toBe(true); expect(drawCommand._pickId).toEqual(mockPickId); expect(drawCommand._commandListTerrain.length).toBe(6); expect(drawCommand._commandList3DTiles.length).toBe(6); expect(drawCommand._commandListTerrainPicking.length).toBe(0); expect(drawCommand._commandList3DTilesPicking.length).toBe(0); }); }); describe("pushCommands", function() { it("pushCommands works for render pass", function() { const renderResources = mockRenderResources({ classificationType: import__689.ClassificationType.BOTH, batchLengths, batchOffsets }); const command = createDrawCommand2(); const drawCommand = new import__689.ClassificationModelDrawCommand({ primitiveRenderResources: renderResources, command }); const commandList = mockFrameState.commandList; drawCommand.pushCommands(mockFrameState, commandList); expect(commandList.length).toEqual(12); const commandListTerrain = commandList.slice(0, 6); let expectedPass = import__689.Pass.TERRAIN_CLASSIFICATION; let expectedStencilFunction = import__689.StencilFunction.ALWAYS; verifyBatchedStencilAndColorCommands( drawCommand, commandListTerrain, expectedPass, expectedStencilFunction ); const commandList3DTiles = commandList.slice(6, 12); expectedPass = import__689.Pass.CESIUM_3D_TILE_CLASSIFICATION; expectedStencilFunction = import__689.StencilFunction.EQUAL; verifyBatchedStencilAndColorCommands( drawCommand, commandList3DTiles, expectedPass, expectedStencilFunction ); }); it("pushCommands works for render pass", function() { const renderResources = mockRenderResources({ classificationType: import__689.ClassificationType.BOTH, batchLengths, batchOffsets }); const command = createDrawCommand2(); const drawCommand = new import__689.ClassificationModelDrawCommand({ primitiveRenderResources: renderResources, command }); const commandList = mockFrameState.commandList; drawCommand.pushCommands(mockFrameState, commandList); expect(commandList.length).toEqual(12); const commandListTerrain = commandList.slice(0, 6); let expectedPass = import__689.Pass.TERRAIN_CLASSIFICATION; let expectedStencilFunction = import__689.StencilFunction.ALWAYS; verifyBatchedStencilAndColorCommands( drawCommand, commandListTerrain, expectedPass, expectedStencilFunction ); const commandList3DTiles = commandList.slice(6, 12); expectedPass = import__689.Pass.CESIUM_3D_TILE_CLASSIFICATION; expectedStencilFunction = import__689.StencilFunction.EQUAL; verifyBatchedStencilAndColorCommands( drawCommand, commandList3DTiles, expectedPass, expectedStencilFunction ); }); it("pushCommands works for pick pass", function() { const renderResources = mockRenderResources({ allowPicking: true, pickId: mockPickId, classificationType: import__689.ClassificationType.BOTH, batchLengths, batchOffsets }); const command = createDrawCommand2(); const drawCommand = new import__689.ClassificationModelDrawCommand({ primitiveRenderResources: renderResources, command }); const commandList = mockFrameStatePickOnly.commandList; drawCommand.pushCommands(mockFrameStatePickOnly, commandList); expect(commandList.length).toEqual(12); const testForPicking = true; const commandListTerrain = commandList.slice(0, 6); let expectedPass = import__689.Pass.TERRAIN_CLASSIFICATION; let expectedStencilFunction = import__689.StencilFunction.ALWAYS; verifyBatchedStencilAndColorCommands( drawCommand, commandListTerrain, expectedPass, expectedStencilFunction, testForPicking ); const commandList3DTiles = commandList.slice(6, 12); expectedPass = import__689.Pass.CESIUM_3D_TILE_CLASSIFICATION; expectedStencilFunction = import__689.StencilFunction.EQUAL; verifyBatchedStencilAndColorCommands( drawCommand, commandList3DTiles, expectedPass, expectedStencilFunction, testForPicking ); }); it("pushCommands derives ignore show commands for 3D Tiles", function() { const renderResources = mockRenderResources({ classificationType: import__689.ClassificationType.CESIUM_3D_TILE, batchLengths, batchOffsets }); const command = createDrawCommand2(); const drawCommand = new import__689.ClassificationModelDrawCommand({ primitiveRenderResources: renderResources, command }); const commandListIgnoreShow = drawCommand._commandListIgnoreShow; expect(commandListIgnoreShow.length).toBe(0); const commandList = mockFrameStateWithInvertedClassification.commandList; drawCommand.pushCommands( mockFrameStateWithInvertedClassification, commandList ); expect(commandList.length).toBe(9); const commandList3DTiles = commandList.slice(0, 6); let expectedPass = import__689.Pass.CESIUM_3D_TILE_CLASSIFICATION; const expectedStencilFunction = import__689.StencilFunction.EQUAL; verifyBatchedStencilAndColorCommands( drawCommand, commandList3DTiles, expectedPass, expectedStencilFunction ); const length2 = commandListIgnoreShow.length; expect(length2).toBe(3); expectedPass = import__689.Pass.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW; const indexOffset = 6; for (let i = 0; i < length2; i++) { const ignoreShowCommand = commandListIgnoreShow[i]; expect(commandList[indexOffset + i]).toBe(ignoreShowCommand); verifyStencilDepthCommand( ignoreShowCommand, expectedPass, expectedStencilFunction ); } }); it("pushCommands doesn't derive ignore show command for terrain", function() { const renderResources = mockRenderResources({ classificationType: import__689.ClassificationType.TERRAIN, batchLengths, batchOffsets }); const command = createDrawCommand2(); const drawCommand = new import__689.ClassificationModelDrawCommand({ primitiveRenderResources: renderResources, command }); const commandListIgnoreShow = drawCommand._commandListIgnoreShow; expect(commandListIgnoreShow.length).toBe(0); const commandList = mockFrameStateWithInvertedClassification.commandList; drawCommand.pushCommands( mockFrameStateWithInvertedClassification, commandList ); expect(commandList.length).toBe(6); expect(commandListIgnoreShow.length).toBe(0); }); }); it("updates model matrix", function() { const renderResources = mockRenderResources({ classificationType: import__689.ClassificationType.BOTH, batchLengths, batchOffsets }); const command = createDrawCommand2(); const drawCommand = new import__689.ClassificationModelDrawCommand({ primitiveRenderResources: renderResources, command }); expect(drawCommand.modelMatrix).toBe(command.modelMatrix); const commandList = []; commandList.push.apply(commandList, drawCommand._commandListTerrain); commandList.push.apply(commandList, drawCommand._commandList3DTiles); const length2 = commandList.length; expect(length2).toEqual(12); for (let i = 0; i < length2; i++) { const command2 = commandList[i]; expect(command2.modelMatrix).toEqual(import__689.Matrix4.IDENTITY); expect(command2.boundingVolume.center).toEqual(import__689.Cartesian3.ZERO); } const translation = import__689.Cartesian3.fromDegrees(100, 25); const modelMatrix = import__689.Matrix4.fromTranslation(translation, new import__689.Matrix4()); drawCommand.modelMatrix = modelMatrix; expect(drawCommand.modelMatrix).toEqual(modelMatrix); for (let i = 0; i < length2; i++) { const command2 = commandList[i]; expect(command2.modelMatrix).toEqual(modelMatrix); expect(command2.boundingVolume.center).toEqual(translation); } }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/ClassificationPipelineStageSpec.js var import__690 = __toESM(require_Cesium(), 1); describe("Scene/Model/ClassificationPipelineStage", function() { const mockFrameState = {}; function generateFeatureIds(batchLengths) { const featureIds = []; const length2 = batchLengths.length; for (let id = 0; id < length2; id++) { const batchLength = batchLengths[id]; const batch = new Array(batchLength); batch.fill(id); featureIds.push.apply(featureIds, batch); } return featureIds; } function mockPrimitive(featureIds, indices) { const positionAttribute = { semantic: import__690.VertexAttributeSemantic.POSITION, count: featureIds.length }; const featureIdAttribute = { semantic: import__690.VertexAttributeSemantic.FEATURE_ID, setIndex: 0, typedArray: featureIds, count: featureIds.length }; const primitive = { primitiveType: import__690.PrimitiveType.TRIANGLES, attributes: [positionAttribute, featureIdAttribute], indices }; return primitive; } function mockRenderResources(primitive) { return { shaderBuilder: new import__690.ShaderBuilder(), uniformMap: {}, model: {}, primitive, runtimePrimitive: { batchLengths: void 0, batchOffsets: void 0 } }; } it("throws for primitive with no position attribute", function() { const inputBatchLengths = [6]; const featureIds = generateFeatureIds(inputBatchLengths); const primitive = mockPrimitive(featureIds); const positionAttribute = primitive.attributes[0]; positionAttribute.semantic = import__690.VertexAttributeSemantic.NORMAL; const renderResources = mockRenderResources(primitive); expect(function() { import__690.ClassificationPipelineStage.process( renderResources, primitive, mockFrameState ); }).toThrowError(import__690.RuntimeError); }); it("adds classification define to the shader", function() { const inputBatchLengths = [6]; const featureIds = generateFeatureIds(inputBatchLengths); const primitive = mockPrimitive(featureIds); const renderResources = mockRenderResources(primitive); import__690.ClassificationPipelineStage.process( renderResources, primitive, mockFrameState ); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_CLASSIFICATION" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_CLASSIFICATION" ]); }); it("computes single batch for primitive without feature IDs", function() { const inputBatchLengths = [6]; const featureIds = generateFeatureIds(inputBatchLengths); const primitive = mockPrimitive(featureIds); primitive.attributes.length = 1; const renderResources = mockRenderResources(primitive); import__690.ClassificationPipelineStage.process( renderResources, primitive, mockFrameState ); const runtimePrimitive = renderResources.runtimePrimitive; const batchLengths = runtimePrimitive.batchLengths; const batchOffsets = runtimePrimitive.batchOffsets; expect(batchLengths).toEqual(inputBatchLengths); expect(batchOffsets).toEqual([0]); }); it("computes single batch for primitive with feature IDs", function() { const inputBatchLengths = [6]; const featureIds = generateFeatureIds(inputBatchLengths); const primitive = mockPrimitive(featureIds); const renderResources = mockRenderResources(primitive); import__690.ClassificationPipelineStage.process( renderResources, primitive, mockFrameState ); const runtimePrimitive = renderResources.runtimePrimitive; const batchLengths = runtimePrimitive.batchLengths; const batchOffsets = runtimePrimitive.batchOffsets; expect(batchLengths).toEqual(inputBatchLengths); expect(batchOffsets).toEqual([0]); }); it("computes multiple batches for primitive with feature IDs", function() { const inputBatchLengths = [6, 3, 9, 12]; const featureIds = generateFeatureIds(inputBatchLengths); const primitive = mockPrimitive(featureIds); const renderResources = mockRenderResources(primitive); import__690.ClassificationPipelineStage.process( renderResources, primitive, mockFrameState ); const runtimePrimitive = renderResources.runtimePrimitive; const batchLengths = runtimePrimitive.batchLengths; const batchOffsets = runtimePrimitive.batchOffsets; expect(batchLengths).toEqual(inputBatchLengths); expect(batchOffsets).toEqual([0, 6, 9, 18]); }); it("computes multiple batches for primitive with feature IDs and indices", function() { const featureIds = [2, 1, 0, 0, 1, 2, 2, 1, 0, 0, 2]; const indices = { // prettier-ignore typedArray: [ 2, 3, 8, 2, 8, 9, // Two triangles with feature ID 0 1, 4, 7, // One triangle with feature ID 1 0, 5, 6, 0, 6, 10 // Two triangles with feature ID 2 ], count: 15 }; const primitive = mockPrimitive(featureIds, indices); const renderResources = mockRenderResources(primitive); import__690.ClassificationPipelineStage.process( renderResources, primitive, mockFrameState ); const runtimePrimitive = renderResources.runtimePrimitive; const batchLengths = runtimePrimitive.batchLengths; const batchOffsets = runtimePrimitive.batchOffsets; expect(batchLengths).toEqual([6, 3, 6]); expect(batchOffsets).toEqual([0, 6, 9]); }); it("doesn't recompute batches for primitive if they are already defined", function() { const inputBatchLengths = [6]; const featureIds = generateFeatureIds(inputBatchLengths); const primitive = mockPrimitive(featureIds); const renderResources = mockRenderResources(primitive); const runtimePrimitive = renderResources.runtimePrimitive; runtimePrimitive.batchLengths = []; runtimePrimitive.batchOffsets = []; import__690.ClassificationPipelineStage.process( renderResources, primitive, mockFrameState ); const batchLengths = runtimePrimitive.batchLengths; const batchOffsets = runtimePrimitive.batchOffsets; expect(batchLengths).toEqual([]); expect(batchOffsets).toEqual([]); }); }); // packages/engine/Specs/Scene/Model/CustomShaderPipelineStageSpec.js var import__691 = __toESM(require_Cesium(), 1); describe("Scene/Model/CustomShaderPipelineStage", function() { const primitive = { attributes: [ { semantic: "POSITION", type: import__691.AttributeType.VEC3 }, { semantic: "NORMAL", type: import__691.AttributeType.VEC3 }, { semantic: "TEXCOORD", setIndex: 0, type: import__691.AttributeType.VEC2 } ] }; const primitiveWithCustomAttributes = { attributes: [ { semantic: "POSITION", type: import__691.AttributeType.VEC3 }, { name: "_TEMPERATURE", type: import__691.AttributeType.SCALAR } ] }; const primitiveWithColorAttributes = { attributes: [ { semantic: "POSITION", type: import__691.AttributeType.VEC3 }, { semantic: "COLOR", setIndex: 0, type: import__691.AttributeType.VEC3 }, { semantic: "COLOR", setIndex: 1, type: import__691.AttributeType.VEC4 } ] }; const emptyVertexShader = "void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) {}"; const emptyFragmentShader = "void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {}"; const emptyShader = new import__691.CustomShader({ vertexShaderText: emptyVertexShader, fragmentShaderText: emptyFragmentShader }); function mockRenderResources(customShader) { return { shaderBuilder: new import__691.ShaderBuilder(), uniformMap: {}, model: { customShader }, lightingOptions: new import__691.ModelLightingOptions(), alphaOptions: new import__691.ModelAlphaOptions() }; } it("sets defines in the shader", function() { const renderResources = mockRenderResources(emptyShader); const shaderBuilder = renderResources.shaderBuilder; import__691.CustomShaderPipelineStage.process(renderResources, primitive); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_CUSTOM_VERTEX_SHADER" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_CUSTOM_FRAGMENT_SHADER", "CUSTOM_SHADER_MODIFY_MATERIAL" ]); }); it("adds uniforms from the custom shader", function() { const uniforms = { u_time: { type: import__691.UniformType.FLOAT }, u_enableAnimation: { type: import__691.UniformType.BOOL } }; const customShader = new import__691.CustomShader({ uniforms, vertexShaderText: emptyVertexShader, fragmentShaderText: emptyFragmentShader }); const renderResources = mockRenderResources(customShader); const shaderBuilder = renderResources.shaderBuilder; import__691.CustomShaderPipelineStage.process(renderResources, primitive); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform bool u_enableAnimation;", "uniform float u_time;" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform bool u_enableAnimation;", "uniform float u_time;" ]); expect(renderResources.uniformMap).toEqual(customShader.uniformMap); }); it("adds varying declarations from the custom shader", function() { const varyings = { v_distanceFromCenter: import__691.VaryingType.FLOAT, v_computedMatrix: import__691.VaryingType.MAT3 }; const customShader = new import__691.CustomShader({ vertexShaderText: emptyVertexShader, fragmentShaderText: emptyFragmentShader, varyings }); const renderResources = mockRenderResources(customShader); const shaderBuilder = renderResources.shaderBuilder; import__691.CustomShaderPipelineStage.process(renderResources, primitive); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "float v_distanceFromCenter;", "mat2 v_computedMatrix;" ]); }); it("overrides the lighting model if specified in the custom shader", function() { const customShader = new import__691.CustomShader({ vertexShaderText: emptyVertexShader, fragmentShaderText: emptyFragmentShader, lightingModel: import__691.LightingModel.PBR }); const renderResources = mockRenderResources(customShader); import__691.CustomShaderPipelineStage.process(renderResources, primitive); expect(renderResources.lightingOptions.lightingModel).toBe( import__691.LightingModel.PBR ); }); it("sets alpha options", function() { const customShader = new import__691.CustomShader({ vertexShaderText: emptyVertexShader, fragmentShaderText: emptyFragmentShader }); const renderResources = mockRenderResources(customShader); import__691.CustomShaderPipelineStage.process(renderResources, primitive); expect(renderResources.alphaOptions.pass).not.toBeDefined(); }); it("does not modify pass if translucencyMode = INHERIT", function() { const customShader = new import__691.CustomShader({ vertexShaderText: emptyVertexShader, fragmentShaderText: emptyFragmentShader, translucencyMode: import__691.CustomShaderTranslucencyMode.INHERIT }); const renderResources = mockRenderResources(customShader); renderResources.alphaOptions.pass = import__691.Pass.CESIUM_3D_TILE; import__691.CustomShaderPipelineStage.process(renderResources, primitive); expect(renderResources.alphaOptions.pass).toBe(import__691.Pass.CESIUM_3D_TILE); }); it("sets pass for translucent custom shader", function() { const customShader = new import__691.CustomShader({ vertexShaderText: emptyVertexShader, fragmentShaderText: emptyFragmentShader, translucencyMode: import__691.CustomShaderTranslucencyMode.TRANSLUCENT }); const renderResources = mockRenderResources(customShader); import__691.CustomShaderPipelineStage.process(renderResources, primitive); expect(renderResources.alphaOptions.pass).toBe(import__691.Pass.TRANSLUCENT); }); it("sets pass to undefined for opaque custom shader", function() { const customShader = new import__691.CustomShader({ vertexShaderText: emptyVertexShader, fragmentShaderText: emptyFragmentShader, translucencyMode: import__691.CustomShaderTranslucencyMode.opaque }); const renderResources = mockRenderResources(customShader); import__691.CustomShaderPipelineStage.process(renderResources, primitive); expect(renderResources.alphaOptions.pass).not.toBeDefined(); }); it("unlit and translucency work even if no shader code is present", function() { const customShader = new import__691.CustomShader({ lightingModel: import__691.LightingModel.PBR, translucencyMode: import__691.CustomShaderTranslucencyMode.TRANSLUCENT }); const renderResources = mockRenderResources(customShader); const shaderBuilder = renderResources.shaderBuilder; import__691.CustomShaderPipelineStage.process(renderResources, primitive); expect(renderResources.alphaOptions.pass).toBe(import__691.Pass.TRANSLUCENT); expect(renderResources.lightingOptions.lightingModel).toBe( import__691.LightingModel.PBR ); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, []); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, []); }); it("generates shader code from built-in attributes", function() { const customShader = new import__691.CustomShader({ vertexShaderText: ` void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) { vec3 normalMC = vsInput.attributes.normalMC; vec2 texCoord = vsInput.attributes.texCoord_0; vsOutput.positionMC = vsInput.attributes.positionMC; } `, fragmentShaderText: ` void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) { vec3 positionMC = fsInput.attributes.positionMC; vec3 normalEC = fsInput.attributes.normalEC; vec2 texCoord = fsInput.attributes.texCoord_0; } ` }); const renderResources = mockRenderResources(customShader); const shaderBuilder = renderResources.shaderBuilder; import__691.CustomShaderPipelineStage.process(renderResources, primitive); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_VS, import__691.CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES, [" vec3 positionMC;", " vec3 normalMC;", " vec2 texCoord_0;"] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_FS, import__691.CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES, [" vec3 positionMC;", " vec3 normalEC;", " vec2 texCoord_0;"] ); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_VERTEX_INPUT, "VertexInput", [ " Attributes attributes;", " FeatureIds featureIds;", " Metadata metadata;", " MetadataClass metadataClass;", " MetadataStatistics metadataStatistics;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_FRAGMENT_INPUT, "FragmentInput", [ " Attributes attributes;", " FeatureIds featureIds;", " Metadata metadata;", " MetadataClass metadataClass;", " MetadataStatistics metadataStatistics;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__691.CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_VS, import__691.CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_VS, [ " vsInput.attributes.positionMC = attributes.positionMC;", " vsInput.attributes.normalMC = attributes.normalMC;", " vsInput.attributes.texCoord_0 = attributes.texCoord_0;" ] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__691.CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_FS, import__691.CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_FS, [ " fsInput.attributes.positionMC = attributes.positionMC;", " fsInput.attributes.normalEC = attributes.normalEC;", " fsInput.attributes.texCoord_0 = attributes.texCoord_0;" ] ); }); it("generates shader code for custom attributes", function() { const customShader = new import__691.CustomShader({ vertexShaderText: ` void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) { float temperature = vsInput.attributes.temperature; vec3 positionMC = vsInput.attributes.positionMC; } `, fragmentShaderText: ` void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) { float temperature = fsInput.attributes.temperature; vec3 positionMC = fsInput.attributes.positionMC; } ` }); const renderResources = mockRenderResources(customShader); const shaderBuilder = renderResources.shaderBuilder; import__691.CustomShaderPipelineStage.process( renderResources, primitiveWithCustomAttributes ); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_VS, import__691.CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES, [" vec3 positionMC;", " float temperature;"] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_FS, import__691.CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES, [" vec3 positionMC;", " float temperature;"] ); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_VERTEX_INPUT, "VertexInput", [ " Attributes attributes;", " FeatureIds featureIds;", " Metadata metadata;", " MetadataClass metadataClass;", " MetadataStatistics metadataStatistics;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_FRAGMENT_INPUT, "FragmentInput", [ " Attributes attributes;", " FeatureIds featureIds;", " Metadata metadata;", " MetadataClass metadataClass;", " MetadataStatistics metadataStatistics;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__691.CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_VS, import__691.CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_VS, [ " vsInput.attributes.positionMC = attributes.positionMC;", " vsInput.attributes.temperature = attributes.temperature;" ] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__691.CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_FS, import__691.CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_FS, [ " fsInput.attributes.positionMC = attributes.positionMC;", " fsInput.attributes.temperature = attributes.temperature;" ] ); }); it("treats COLOR attributes as vec4", function() { const customShader = new import__691.CustomShader({ varyings: { v_color: import__691.VaryingType.FLOAT, v_computedMatrix: import__691.VaryingType.MAT3 }, vertexShaderText: ` void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) { vec4 color += vsInput.attributes.color_0 + vsInput.attributes.color_1; } `, fragmentShaderText: ` void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) { vec4 color += fsInput.attributes.color_0 + fsInput.attributes.color_1; } ` }); const renderResources = mockRenderResources(customShader); const shaderBuilder = renderResources.shaderBuilder; import__691.CustomShaderPipelineStage.process( renderResources, primitiveWithColorAttributes ); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_VS, import__691.CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES, [" vec4 color_0;", " vec4 color_1;"] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_FS, import__691.CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES, [" vec4 color_0;", " vec4 color_1;"] ); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_VERTEX_INPUT, "VertexInput", [ " Attributes attributes;", " FeatureIds featureIds;", " Metadata metadata;", " MetadataClass metadataClass;", " MetadataStatistics metadataStatistics;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_FRAGMENT_INPUT, "FragmentInput", [ " Attributes attributes;", " FeatureIds featureIds;", " Metadata metadata;", " MetadataClass metadataClass;", " MetadataStatistics metadataStatistics;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__691.CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_VS, import__691.CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_VS, [ " vsInput.attributes.color_0 = attributes.color_0;", " vsInput.attributes.color_1 = attributes.color_1;" ] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__691.CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_FS, import__691.CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_FS, [ " fsInput.attributes.color_0 = attributes.color_0;", " fsInput.attributes.color_1 = attributes.color_1;" ] ); }); it("only generates input lines for attributes that are used", function() { const customShader = new import__691.CustomShader({ vertexShaderText: ` void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) { vsOutput.positionMC = 2.0 * vsInput.attributes.positionMC - 1.0; } `, fragmentShaderText: ` void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) { float temperature = fsInput.attributes.temperature; material.diffuse = vec3(temperature / 90.0, 0.0, 0.0); } ` }); const renderResources = mockRenderResources(customShader); const shaderBuilder = renderResources.shaderBuilder; import__691.CustomShaderPipelineStage.process( renderResources, primitiveWithCustomAttributes ); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_VS, import__691.CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES, [" vec3 positionMC;"] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_FS, import__691.CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES, [" float temperature;"] ); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_VERTEX_INPUT, "VertexInput", [ " Attributes attributes;", " FeatureIds featureIds;", " Metadata metadata;", " MetadataClass metadataClass;", " MetadataStatistics metadataStatistics;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_FRAGMENT_INPUT, "FragmentInput", [ " Attributes attributes;", " FeatureIds featureIds;", " Metadata metadata;", " MetadataClass metadataClass;", " MetadataStatistics metadataStatistics;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__691.CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_VS, import__691.CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_VS, [" vsInput.attributes.positionMC = attributes.positionMC;"] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__691.CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_FS, import__691.CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_FS, [" fsInput.attributes.temperature = attributes.temperature;"] ); }); it("generates the shader lines in the correct order", function() { const renderResources = mockRenderResources(emptyShader); const shaderBuilder = renderResources.shaderBuilder; import__691.CustomShaderPipelineStage.process(renderResources, primitive); expect(shaderBuilder._vertexShaderParts.structIds).toEqual([ import__691.CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_VS, import__691.CustomShaderPipelineStage.STRUCT_ID_VERTEX_INPUT ]); expect(shaderBuilder._fragmentShaderParts.structIds).toEqual([ import__691.CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_FS, import__691.CustomShaderPipelineStage.STRUCT_ID_FRAGMENT_INPUT ]); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ "#line 0", emptyVertexShader, import__691._shadersCustomShaderStageVS ]); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ "#line 0", emptyFragmentShader, import__691._shadersCustomShaderStageFS ]); }); it("does not add positions in other coordinate systems if not needed", function() { const renderResources = mockRenderResources(emptyShader); const shaderBuilder = renderResources.shaderBuilder; import__691.CustomShaderPipelineStage.process(renderResources, primitive); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_FRAGMENT_INPUT, "FragmentInput", [ " Attributes attributes;", " FeatureIds featureIds;", " Metadata metadata;", " MetadataClass metadataClass;", " MetadataStatistics metadataStatistics;" ] ); }); it("configures positions in other coordinate systems when present in the shader", function() { const customShader = new import__691.CustomShader({ vertexShaderText: emptyVertexShader, fragmentShaderText: ` void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) { material.diffuse = fsInput.attributes.positionMC; material.specular = fsInput.attributes.positionWC; material.normal = fsInput.attributes.positionEC; } ` }); const renderResources = mockRenderResources(customShader); const shaderBuilder = renderResources.shaderBuilder; import__691.CustomShaderPipelineStage.process(renderResources, primitive); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "COMPUTE_POSITION_WC_CUSTOM_SHADER", "HAS_CUSTOM_VERTEX_SHADER" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "COMPUTE_POSITION_WC_CUSTOM_SHADER", "HAS_CUSTOM_FRAGMENT_SHADER", "CUSTOM_SHADER_MODIFY_MATERIAL" ]); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_VS, import__691.CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES, [] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_FS, import__691.CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES, [" vec3 positionMC;", " vec3 positionWC;", " vec3 positionEC;"] ); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_VERTEX_INPUT, "VertexInput", [ " Attributes attributes;", " FeatureIds featureIds;", " Metadata metadata;", " MetadataClass metadataClass;", " MetadataStatistics metadataStatistics;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_FRAGMENT_INPUT, "FragmentInput", [ " Attributes attributes;", " FeatureIds featureIds;", " Metadata metadata;", " MetadataClass metadataClass;", " MetadataStatistics metadataStatistics;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__691.CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_VS, import__691.CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_VS, [] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__691.CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_FS, import__691.CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_FS, [ " fsInput.attributes.positionMC = attributes.positionMC;", " fsInput.attributes.positionWC = attributes.positionWC;", " fsInput.attributes.positionEC = attributes.positionEC;" ] ); }); it("infers default values for built-in attributes", function() { const customShader = new import__691.CustomShader({ vertexShaderText: ` void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) { vec2 texCoords = vsInput.attributes.texCoord_1; } `, fragmentShaderText: ` void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) { material.diffuse = vec3(fsInput.attributes.tangentEC); } ` }); const renderResources = mockRenderResources(customShader); const shaderBuilder = renderResources.shaderBuilder; import__691.CustomShaderPipelineStage.process(renderResources, primitive); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_VS, import__691.CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES, [" vec2 texCoord_1;"] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_FS, import__691.CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES, [" vec3 tangentEC;"] ); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_VERTEX_INPUT, "VertexInput", [ " Attributes attributes;", " FeatureIds featureIds;", " Metadata metadata;", " MetadataClass metadataClass;", " MetadataStatistics metadataStatistics;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_FRAGMENT_INPUT, "FragmentInput", [ " Attributes attributes;", " FeatureIds featureIds;", " Metadata metadata;", " MetadataClass metadataClass;", " MetadataStatistics metadataStatistics;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__691.CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_VS, import__691.CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_VS, [" vsInput.attributes.texCoord_1 = vec2(0.0);"] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__691.CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_FS, import__691.CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_FS, [" fsInput.attributes.tangentEC = vec3(1.0, 0.0, 0.0);"] ); }); it("handles incompatible primitives gracefully", function() { const customShader = new import__691.CustomShader({ vertexShaderText: ` void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) { vec3 texCoords = vsInput.attributes.notAnAttribute; } `, fragmentShaderText: ` void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) { material.diffuse *= fsInput.attributes.alsoNotAnAttribute; } ` }); const renderResources = mockRenderResources(customShader); const shaderBuilder = renderResources.shaderBuilder; spyOn(import__691.CustomShaderPipelineStage, "_oneTimeWarning"); import__691.CustomShaderPipelineStage.process(renderResources, primitive); expect(import__691.CustomShaderPipelineStage._oneTimeWarning.calls.count()).toBe(2); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); }); it("disables vertex shader if vertexShaderText is not provided", function() { const customShader = new import__691.CustomShader({ fragmentShaderText: emptyFragmentShader }); const renderResources = mockRenderResources(customShader); const shaderBuilder = renderResources.shaderBuilder; import__691.CustomShaderPipelineStage.process(renderResources, primitive); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_CUSTOM_FRAGMENT_SHADER", "CUSTOM_SHADER_MODIFY_MATERIAL" ]); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, []); ShaderBuilderTester_default.expectFragmentLinesContains( shaderBuilder, emptyFragmentShader ); }); it("disables fragment shader if fragmentShaderText is not provided", function() { const customShader = new import__691.CustomShader({ vertexShaderText: emptyVertexShader }); const renderResources = mockRenderResources(customShader); const shaderBuilder = renderResources.shaderBuilder; import__691.CustomShaderPipelineStage.process(renderResources, primitive); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_CUSTOM_VERTEX_SHADER" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); ShaderBuilderTester_default.expectVertexLinesContains( shaderBuilder, emptyVertexShader ); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, []); }); it("disables custom shader if neither fragmentShaderText nor vertexShaderText are provided", function() { const renderResources = mockRenderResources(new import__691.CustomShader()); const shaderBuilder = renderResources.shaderBuilder; import__691.CustomShaderPipelineStage.process(renderResources, primitive); expect(shaderBuilder).toEqual(new import__691.ShaderBuilder()); expect(renderResources.uniformMap).toEqual({}); expect(renderResources.lightingOptions).toEqual(new import__691.ModelLightingOptions()); }); it("handles fragment-only custom shader that computes positionWC", function() { const customShader = new import__691.CustomShader({ fragmentShaderText: ` void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) { material.diffuse = fsInput.attributes.positionWC; } ` }); const renderResources = mockRenderResources(customShader); const shaderBuilder = renderResources.shaderBuilder; import__691.CustomShaderPipelineStage.process(renderResources, primitive); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "COMPUTE_POSITION_WC_CUSTOM_SHADER" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "COMPUTE_POSITION_WC_CUSTOM_SHADER", "HAS_CUSTOM_FRAGMENT_SHADER", "CUSTOM_SHADER_MODIFY_MATERIAL" ]); expect(shaderBuilder._vertexShaderParts.structIds).toEqual([]); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_FS, import__691.CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES, [" vec3 positionWC;"] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__691.CustomShaderPipelineStage.STRUCT_ID_FRAGMENT_INPUT, "FragmentInput", [ " Attributes attributes;", " FeatureIds featureIds;", " Metadata metadata;", " MetadataClass metadataClass;", " MetadataStatistics metadataStatistics;" ] ); expect(shaderBuilder._vertexShaderParts.functionIds).toEqual([]); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__691.CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_FS, import__691.CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_FS, [" fsInput.attributes.positionWC = attributes.positionWC;"] ); }); }); // packages/engine/Specs/Scene/Model/CustomShaderSpec.js var import__692 = __toESM(require_Cesium(), 1); describe("Scene/Model/CustomShader", function() { const emptyVertexShader = "void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) {}"; const emptyFragmentShader = "void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {}"; it("constructs with default values", function() { const customShader = new import__692.CustomShader(); expect(customShader.mode).toBe(import__692.CustomShaderMode.MODIFY_MATERIAL); expect(customShader.lightingModel).not.toBeDefined(); expect(customShader.translucencyMode).toBe( import__692.CustomShaderTranslucencyMode.INHERIT ); expect(customShader.uniforms).toEqual({}); expect(customShader.varyings).toEqual({}); expect(customShader.vertexShaderText).not.toBeDefined(); expect(customShader.fragmentShaderText).not.toBeDefined(); expect(customShader.uniformMap).toEqual({}); }); it("constructs", function() { const customShader = new import__692.CustomShader({ mode: import__692.CustomShaderMode.REPLACE_MATERIAL, translucencyMode: import__692.CustomShaderTranslucencyMode.TRANSLUCENT, lightingModel: import__692.LightingModel.PBR, vertexShaderText: emptyVertexShader, fragmentShaderText: emptyFragmentShader }); expect(customShader.mode).toBe(import__692.CustomShaderMode.REPLACE_MATERIAL); expect(customShader.lightingModel).toBe(import__692.LightingModel.PBR); expect(customShader.translucencyMode).toBe( import__692.CustomShaderTranslucencyMode.TRANSLUCENT ); expect(customShader.uniforms).toEqual({}); expect(customShader.varyings).toEqual({}); expect(customShader.vertexShaderText).toBe(emptyVertexShader); expect(customShader.fragmentShaderText).toBe(emptyFragmentShader); expect(customShader.uniformMap).toEqual({}); }); it("defines uniforms", function() { const uniforms = { u_time: { value: 0, type: import__692.UniformType.FLOAT }, u_offset: { value: new import__692.Cartesian2(1, 2), type: import__692.UniformType.VEC2 } }; const customShader = new import__692.CustomShader({ uniforms }); expect(customShader.uniforms).toBe(uniforms); expect(customShader.uniformMap.u_time()).toBe(uniforms.u_time.value); expect(customShader.uniformMap.u_offset()).toBe(uniforms.u_offset.value); }); it("setUniform throws for undefined uniformName", function() { const customShader = new import__692.CustomShader(); expect(function() { return customShader.setUniform(void 0, 45); }).toThrowDeveloperError(); }); it("setUniform throws for undefined value", function() { const customShader = new import__692.CustomShader(); expect(function() { return customShader.setUniform("u_time", void 0); }).toThrowDeveloperError(); }); it("setUniform throws for undeclared uniform", function() { const customShader = new import__692.CustomShader(); expect(function() { return customShader.setUniform("u_time", 10); }).toThrowDeveloperError(); }); it("setUniform updates uniform values", function() { const uniforms = { u_time: { value: 0, type: import__692.UniformType.FLOAT }, u_offset: { value: new import__692.Cartesian2(1, 2), type: import__692.UniformType.VEC2 } }; const customShader = new import__692.CustomShader({ uniforms }); expect(customShader.uniformMap.u_time()).toBe(0); customShader.setUniform("u_time", 10); expect(customShader.uniformMap.u_time()).toBe(10); }); it("setUniform clones vectors", function() { const uniforms = { u_vector: { type: import__692.UniformType.VEC3, value: new import__692.Cartesian3() } }; const customShader = new import__692.CustomShader({ uniforms }); const value = new import__692.Cartesian3(1, 0, 0); customShader.setUniform("u_vector", value); const result = customShader.uniformMap.u_vector(); expect(result).toEqual(value); expect(result).not.toBe(value); }); it("setUniform clones matrices", function() { const uniforms = { u_matrix: { type: import__692.UniformType.MAT2, value: new import__692.Matrix2() } }; const customShader = new import__692.CustomShader({ uniforms }); const value = new import__692.Matrix2(2, 0, 0, 2); customShader.setUniform("u_matrix", value); const result = customShader.uniformMap.u_matrix(); expect(result).toEqual(value); expect(result).not.toBe(value); }); it("declares varyings", function() { const varyings = { v_dist_from_center: import__692.VaryingType.FLOAT, v_computedMatrix: import__692.VaryingType.MAT4 }; const customShader = new import__692.CustomShader({ varyings }); expect(customShader.varyings).toBe(varyings); }); it("detects input variables in the shader text", function() { const customShader = new import__692.CustomShader({ vertexShaderText: [ "void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput)", "{", " float value = vsInput.featureIds.featureId_0;", " float value2 = vsInput.metadata.temperature;", " positionMC += vsInput.attributes.expansion * vsInput.attributes.normalMC;", "}" ].join("\n"), fragmentShaderText: [ "void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material)", "{", " float value = fsInput.featureIds.featureId_1 + fsInput.featureIds.instanceFeatureId_0;", " float value2 = fsInput.metadata.pressure;", " material.normalEC = normalize(fsInput.attributes.normalEC);", " material.diffuse = fsInput.attributes.color_0;", " material.specular = fsInput.attributes.positionWC / 1.0e6;", "}" ].join("\n") }); const expectedVertexVariables = { attributeSet: { expansion: true, normalMC: true }, featureIdSet: { featureId_0: true }, metadataSet: { temperature: true } }; const expectedFragmentVariables = { attributeSet: { normalEC: true, color_0: true, positionWC: true }, materialSet: { normalEC: true, diffuse: true, specular: true }, featureIdSet: { featureId_1: true, instanceFeatureId_0: true }, metadataSet: { pressure: true } }; expect(customShader.usedVariablesVertex).toEqual(expectedVertexVariables); expect(customShader.usedVariablesFragment).toEqual( expectedFragmentVariables ); }); describe("variable validation", function() { function makeSingleVariableVS(variableName) { return new import__692.CustomShader({ vertexShaderText: [ "void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput)", "{", ` vsOutput.positionMC = vsInput.attributes.${variableName};`, "}" ].join("\n") }); } function makeSingleVariableFS(variableName) { return new import__692.CustomShader({ fragmentShaderText: [ "void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material)", "{", ` material.diffuse = fsInput.attributes.${variableName};`, "}" ].join("\n") }); } it("validates position", function() { expect(function() { return makeSingleVariableVS("position"); }).toThrowDeveloperError(); expect(function() { return makeSingleVariableVS("positionMC"); }).not.toThrowDeveloperError(); expect(function() { return makeSingleVariableVS("positionWC"); }).toThrowDeveloperError(); expect(function() { return makeSingleVariableVS("positionEC"); }).toThrowDeveloperError(); expect(function() { return makeSingleVariableFS("position"); }).toThrowDeveloperError(); expect(function() { return makeSingleVariableFS("positionMC"); }).not.toThrowDeveloperError(); expect(function() { return makeSingleVariableFS("positionWC"); }).not.toThrowDeveloperError(); expect(function() { return makeSingleVariableFS("positionEC"); }).not.toThrowDeveloperError(); }); it("validates normal", function() { expect(function() { return makeSingleVariableVS("normal"); }).toThrowDeveloperError(); expect(function() { return makeSingleVariableVS("normalMC"); }).not.toThrowDeveloperError(); expect(function() { return makeSingleVariableVS("normalEC"); }).toThrowDeveloperError(); expect(function() { return makeSingleVariableFS("normal"); }).toThrowDeveloperError(); expect(function() { return makeSingleVariableFS("normalMC"); }).toThrowDeveloperError(); expect(function() { return makeSingleVariableFS("normalEC"); }).not.toThrowDeveloperError(); }); it("validates tangent", function() { expect(function() { return makeSingleVariableVS("tangent"); }).toThrowDeveloperError(); expect(function() { return makeSingleVariableVS("tangentMC"); }).not.toThrowDeveloperError(); expect(function() { return makeSingleVariableVS("tangentEC"); }).toThrowDeveloperError(); expect(function() { return makeSingleVariableFS("tangent"); }).toThrowDeveloperError(); expect(function() { return makeSingleVariableFS("tangentMC"); }).toThrowDeveloperError(); expect(function() { return makeSingleVariableFS("tangentEC"); }).not.toThrowDeveloperError(); }); it("validates bitangent", function() { expect(function() { return makeSingleVariableVS("bitangent"); }).toThrowDeveloperError(); expect(function() { return makeSingleVariableVS("bitangentMC"); }).not.toThrowDeveloperError(); expect(function() { return makeSingleVariableVS("bitangentEC"); }).toThrowDeveloperError(); expect(function() { return makeSingleVariableFS("bitangent"); }).toThrowDeveloperError(); expect(function() { return makeSingleVariableFS("bitangentMC"); }).toThrowDeveloperError(); expect(function() { return makeSingleVariableFS("bitangentEC"); }).not.toThrowDeveloperError(); }); }); describe( "texture uniforms", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); const shaders = []; afterEach(function() { for (let i = 0; i < shaders.length; i++) { const shader = shaders[i]; if (!shader.isDestroyed()) { shader.destroy(); } } shaders.length = 0; }); const blueUrl = "Data/Images/Blue2x2.png"; const greenUrl = "Data/Images/Green1x4.png"; function waitForTextureLoad(customShader, textureId) { const textureManager = customShader._textureManager; const oldValue = textureManager.getTexture(textureId); return pollToPromise_default(function() { scene2.renderForSpecs(); customShader.update(scene2.frameState); return textureManager.getTexture(textureId) !== oldValue; }).then(function() { return textureManager.getTexture(textureId); }); } it("supports texture uniforms", function() { const customShader = new import__692.CustomShader({ vertexShaderText: emptyVertexShader, fragmentShaderText: emptyFragmentShader, uniforms: { u_blue: { type: import__692.UniformType.SAMPLER_2D, value: new import__692.TextureUniform({ url: blueUrl }) } } }); shaders.push(customShader); expect(customShader.uniformMap.u_blue).toBeDefined(); expect(customShader.uniformMap.u_blue()).not.toBeDefined(); return waitForTextureLoad(customShader, "u_blue").then(function(texture) { expect(customShader.uniformMap.u_blue()).toBe(texture); expect(texture.width).toBe(2); expect(texture.height).toBe(2); }); }); it("can change texture uniform value", function() { const customShader = new import__692.CustomShader({ vertexShaderText: emptyVertexShader, fragmentShaderText: emptyFragmentShader, uniforms: { u_testTexture: { type: import__692.UniformType.SAMPLER_2D, value: new import__692.TextureUniform({ url: blueUrl }) } } }); shaders.push(customShader); return waitForTextureLoad(customShader, "u_testTexture").then(function(blueTexture) { expect(customShader.uniformMap.u_testTexture()).toBe(blueTexture); expect(blueTexture.width).toBe(2); expect(blueTexture.height).toBe(2); customShader.setUniform( "u_testTexture", new import__692.TextureUniform({ url: greenUrl }) ); return waitForTextureLoad(customShader, "u_testTexture").then( function(greenTexture) { expect(customShader.uniformMap.u_testTexture()).toBe( greenTexture ); expect(greenTexture.width).toBe(1); expect(greenTexture.height).toBe(4); } ); }); }); it("destroys", function() { const customShader = new import__692.CustomShader({ vertexShaderText: emptyVertexShader, fragmentShaderText: emptyFragmentShader, uniforms: { u_blue: { type: import__692.UniformType.SAMPLER_2D, value: new import__692.TextureUniform({ url: blueUrl }) } } }); shaders.push(customShader); return waitForTextureLoad(customShader, "u_blue").then(function(texture) { expect(customShader.isDestroyed()).toBe(false); expect(texture.isDestroyed()).toBe(false); customShader.destroy(); expect(customShader.isDestroyed()).toBe(true); expect(texture.isDestroyed()).toBe(true); }); }); }, "WebGL" ); }); // packages/engine/Specs/Scene/Model/DequantizationPipelineStageSpec.js var import__693 = __toESM(require_Cesium(), 1); describe( "Scene/Model/DequantizationPipelineStage", function() { const boxUncompressed = "./Data/Models/glTF-2.0/BoxTextured/glTF-Binary/BoxTextured.glb"; const boxWithLines = "./Data/Models/glTF-2.0/BoxWithLines/glTF-Draco/BoxWithLines.gltf"; const milkTruck = "./Data/Models/glTF-2.0/CesiumMilkTruck/glTF-Draco/CesiumMilkTruck.gltf"; const boxDracoRGBColors = "./Data/Models/glTF-2.0/BoxVertexColorsDracoRGB/glTF-Draco/BoxVertexColorsDracoRGB.gltf"; let scene2; const gltfLoaders = []; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { const gltfLoadersLength = gltfLoaders.length; for (let i = 0; i < gltfLoadersLength; ++i) { const gltfLoader = gltfLoaders[i]; if (!gltfLoader.isDestroyed()) { gltfLoader.destroy(); } } gltfLoaders.length = 0; import__693.ResourceCache.clearForSpecs(); }); function getOptions(gltfPath, options) { const resource = new import__693.Resource({ url: gltfPath }); return (0, import__693.combine)(options, { gltfResource: resource, incrementallyLoadTextures: false // Default to false if not supplied }); } async function loadGltf(gltfPath, options) { const gltfLoader = new import__693.GltfLoader(getOptions(gltfPath, options)); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, scene2); return gltfLoader; } function mockRenderResources() { return { uniformMap: {}, shaderBuilder: new import__693.ShaderBuilder(), model: {} }; } it("adds a dequantization function", function() { const renderResources = mockRenderResources(); const shaderBuilder = renderResources.shaderBuilder; return loadGltf(boxWithLines).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; import__693.DequantizationPipelineStage.process(renderResources, primitive); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "USE_DEQUANTIZATION" ]); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__693.DequantizationPipelineStage.FUNCTION_ID_DEQUANTIZATION_STAGE_VS, import__693.DequantizationPipelineStage.FUNCTION_SIGNATURE_DEQUANTIZATION_STAGE_VS, [ " attributes.normalMC = czm_octDecode(a_quantized_normalMC, model_normalizationRange_normalMC).zxy;", " attributes.positionMC = model_quantizedVolumeOffset_positionMC + a_quantized_positionMC * model_quantizedVolumeStepSize_positionMC;" ] ); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentFunctionIds(shaderBuilder, []); }); }); it("adds dequantization uniforms", function() { const renderResources = mockRenderResources(); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; return loadGltf(milkTruck).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; import__693.DequantizationPipelineStage.process(renderResources, primitive); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform float model_normalizationRange_normalMC;", "uniform vec2 model_quantizedVolumeOffset_texCoord_0;", "uniform vec2 model_quantizedVolumeStepSize_texCoord_0;", "uniform vec3 model_quantizedVolumeOffset_positionMC;", "uniform vec3 model_quantizedVolumeStepSize_positionMC;" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); const uniformValues = { normalRange: uniformMap.model_normalizationRange_normalMC(), positionOffset: uniformMap.model_quantizedVolumeOffset_positionMC(), positionStepSize: uniformMap.model_quantizedVolumeStepSize_positionMC(), texCoordOffset: uniformMap.model_quantizedVolumeOffset_texCoord_0(), texCoordStepSize: uniformMap.model_quantizedVolumeStepSize_texCoord_0() }; const expected = { normalRange: 1023, positionOffset: new import__693.Cartesian3( -2.430910110473633, 0.2667999863624573, -1.3960000276565552 ), positionStepSize: new import__693.Cartesian3( 2971928118058615e-19, 2971928118058615e-19, 2971928118058615e-19 ), texCoordOffset: new import__693.Cartesian2( 0.0029563899151980877, 0.015672028064727783 ), texCoordStepSize: new import__693.Cartesian2( 2397004064622816e-19, 2397004064622816e-19 ) }; expect(uniformValues).toEqualEpsilon(expected, import__693.Math.EPSILON15); }); }); it("promotes vertex color dequantization uniforms to vec4", function() { const renderResources = mockRenderResources(); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; return loadGltf(boxDracoRGBColors).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[2].primitives[0]; import__693.DequantizationPipelineStage.process(renderResources, primitive); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform float model_normalizationRange_normalMC;", "uniform vec2 model_quantizedVolumeOffset_texCoord_0;", "uniform vec2 model_quantizedVolumeStepSize_texCoord_0;", "uniform vec3 model_quantizedVolumeOffset_positionMC;", "uniform vec3 model_quantizedVolumeStepSize_positionMC;", "uniform vec4 model_quantizedVolumeOffset_color_0;", "uniform vec4 model_quantizedVolumeStepSize_color_0;" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); const uniformValues = { normalRange: uniformMap.model_normalizationRange_normalMC(), texCoordOffset: uniformMap.model_quantizedVolumeOffset_texCoord_0(), texCoordStepSize: uniformMap.model_quantizedVolumeStepSize_texCoord_0(), positionOffset: uniformMap.model_quantizedVolumeOffset_positionMC(), positionStepSize: uniformMap.model_quantizedVolumeStepSize_positionMC(), colorOffset: uniformMap.model_quantizedVolumeOffset_color_0(), colorStepSize: uniformMap.model_quantizedVolumeStepSize_color_0() }; const expected = { normalRange: 1023, positionOffset: new import__693.Cartesian3(-0.5, -0.5, -0.5), positionStepSize: new import__693.Cartesian3( 6103888176768602e-20, 6103888176768602e-20, 6103888176768602e-20 ), texCoordOffset: new import__693.Cartesian2(0, 0), texCoordStepSize: new import__693.Cartesian2( 2442002442002442e-19, 2442002442002442e-19 ), colorOffset: new import__693.Cartesian4( 4908018991223173e-25, 6933663971722126e-19, 28382812160998583e-21, 0 ), colorStepSize: new import__693.Cartesian4( 0.00392145689795999, 0.00392145689795999, 0.00392145689795999, 1 ) }; expect(uniformValues).toEqualEpsilon(expected, import__693.Math.EPSILON15); }); }); it("only dequantizes position and texcoords for classification models", function() { const renderResources = mockRenderResources(); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; renderResources.model.classificationType = import__693.ClassificationType.BOTH; return loadGltf(boxDracoRGBColors).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[2].primitives[0]; import__693.DequantizationPipelineStage.process(renderResources, primitive); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform vec2 model_quantizedVolumeOffset_texCoord_0;", "uniform vec2 model_quantizedVolumeStepSize_texCoord_0;", "uniform vec3 model_quantizedVolumeOffset_positionMC;", "uniform vec3 model_quantizedVolumeStepSize_positionMC;" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); const uniformValues = { texCoordOffset: uniformMap.model_quantizedVolumeOffset_texCoord_0(), texCoordStepSize: uniformMap.model_quantizedVolumeStepSize_texCoord_0(), positionOffset: uniformMap.model_quantizedVolumeOffset_positionMC(), positionStepSize: uniformMap.model_quantizedVolumeStepSize_positionMC() }; const expected = { texCoordOffset: new import__693.Cartesian2(0, 0), texCoordStepSize: new import__693.Cartesian2( 2442002442002442e-19, 2442002442002442e-19 ), positionOffset: new import__693.Cartesian3(-0.5, -0.5, -0.5), positionStepSize: new import__693.Cartesian3( 6103888176768602e-20, 6103888176768602e-20, 6103888176768602e-20 ) }; expect(uniformValues).toEqualEpsilon(expected, import__693.Math.EPSILON15); }); }); it("skips non-quantized attributes", function() { const renderResources = mockRenderResources(); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; return loadGltf(boxUncompressed).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; import__693.DequantizationPipelineStage.process(renderResources, primitive); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); expect(uniformMap).toEqual({}); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "USE_DEQUANTIZATION" ]); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__693.DequantizationPipelineStage.FUNCTION_ID_DEQUANTIZATION_STAGE_VS, import__693.DequantizationPipelineStage.FUNCTION_SIGNATURE_DEQUANTIZATION_STAGE_VS, [] ); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentFunctionIds(shaderBuilder, []); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/FeatureIdPipelineStageSpec.js var import__694 = __toESM(require_Cesium(), 1); describe( "Scene/Model/FeatureIdPipelineStage", function() { const boxInstanced = "./Data/Models/glTF-2.0/BoxInstanced/glTF/box-instanced.gltf"; const boxTexturedBinary = "./Data/Models/glTF-2.0/BoxTextured/glTF-Binary/BoxTextured.glb"; const buildingsMetadata = "./Data/Models/glTF-2.0/BuildingsMetadata/glTF/buildings-metadata.gltf"; const microcosm = "./Data/Models/glTF-2.0/Microcosm/glTF/microcosm.gltf"; const weather = "./Data/Models/glTF-2.0/Weather/glTF/weather.gltf"; const largeFeatureIdTexture = "./Data/Models/glTF-2.0/LargeFeatureIdTexture/glTF/LargeFeatureIdTexture.gltf"; const featureIdTextureWithTextureTransformUrl = "./Data/Models/glTF-2.0/FeatureIdTextureWithTextureTransform/glTF/FeatureIdTextureWithTextureTransform.gltf"; let scene2; const gltfLoaders = []; const resources = []; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); function cleanup(resourcesArray) { for (let i = 0; i < resourcesArray.length; i++) { const resource = resourcesArray[i]; if (!resource.isDestroyed()) { resource.destroy(); } } resourcesArray.length = 0; } afterEach(function() { cleanup(resources); cleanup(gltfLoaders); import__694.ResourceCache.clearForSpecs(); }); function getOptions(gltfPath, options) { const resource = new import__694.Resource({ url: gltfPath }); return (0, import__694.combine)(options, { gltfResource: resource, incrementallyLoadTextures: false // Default to false if not supplied }); } async function loadGltf(gltfPath, options) { const gltfLoader = new import__694.GltfLoader(getOptions(gltfPath, options)); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, scene2); return gltfLoader; } function mockRenderResources(node) { return { shaderBuilder: new import__694.ShaderBuilder(), uniformMap: {}, model: { // pointer to the global resources so they can be cleaned up // in afterEach() _pipelineResources: resources, statistics: new import__694.ModelStatistics() }, attributes: [ { semantic: import__694.VertexAttributeSemantic.POSITION } ], attributeIndex: 1, runtimeNode: { node } }; } it("handles primitives without feature IDs gracefully", function() { return loadGltf(boxTexturedBinary).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[1]; const primitive = node.primitives[0]; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(node); import__694.FeatureIdPipelineStage.process(renderResources, primitive, frameState2); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__694.FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS, import__694.FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS, [] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__694.FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS, import__694.FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS, [] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS, [] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS, [] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_SET_FEATURE_ID_VARYINGS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_SET_FEATURE_ID_VARYINGS, [] ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasAttributes(shaderBuilder, void 0, []); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, []); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__694._shadersFeatureIdStageVS ]); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__694._shadersFeatureIdStageFS ]); expect(resources).toEqual([]); expect(renderResources.attributes.length).toBe(1); const uniformMap = renderResources.uniformMap; expect(uniformMap).toEqual({}); const statistics = renderResources.model.statistics; expect(statistics.geometryByteLength).toBe(0); expect(statistics.texturesByteLength).toBe(0); }); }); it("processes feature ID attributes", function() { return loadGltf(weather).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const primitive = node.primitives[0]; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(node); import__694.FeatureIdPipelineStage.process(renderResources, primitive, frameState2); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__694.FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS, import__694.FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS, [ " int featureId_0;", " int featureId_1;", " int perPoint;", " int town;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__694.FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS, import__694.FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS, [ " int featureId_0;", " int featureId_1;", " int perPoint;", " int town;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS, [ " featureIds.featureId_0 = int(czm_round(a_implicit_featureId_0));", " featureIds.featureId_1 = int(czm_round(attributes.featureId_0));" ] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS, [ " featureIds.featureId_0 = int(czm_round(v_implicit_featureId_0));", " featureIds.featureId_1 = int(czm_round(attributes.featureId_0));" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_VS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES, [ " featureIds.perPoint = featureIds.featureId_0;", " featureIds.town = featureIds.featureId_1;" ] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_FS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES, [ " featureIds.perPoint = featureIds.featureId_0;", " featureIds.town = featureIds.featureId_1;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_SET_FEATURE_ID_VARYINGS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_SET_FEATURE_ID_VARYINGS, [" v_implicit_featureId_0 = a_implicit_featureId_0;"] ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasAttributes(shaderBuilder, void 0, [ "in float a_implicit_featureId_0;" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "float v_implicit_featureId_0;" ]); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__694._shadersFeatureIdStageVS ]); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__694._shadersFeatureIdStageFS ]); expect(resources.length).toBe(1); const vertexBuffer = resources[0]; expect(vertexBuffer).toBeDefined(); expect(vertexBuffer.vertexArrayDestroyable).toBe(false); expect(renderResources.attributes.length).toBe(2); const implicitAttribute = renderResources.attributes[1]; expect(implicitAttribute.index).toBe(1); expect(implicitAttribute.instanceDivisor).toBeUndefined(); expect(implicitAttribute.value).toBeUndefined(); expect(implicitAttribute.vertexBuffer).toBe(vertexBuffer); expect(implicitAttribute.normalize).toBe(false); expect(implicitAttribute.componentsPerAttribute).toBe(1); expect(implicitAttribute.componentDatatype).toBe( import__694.ComponentDatatype.FLOAT ); expect(implicitAttribute.strideInBytes).toBe(4); expect(implicitAttribute.offsetInBytes).toBe(0); const uniformMap = renderResources.uniformMap; expect(uniformMap).toEqual({}); const statistics = renderResources.model.statistics; expect(statistics.geometryByteLength).toBe(vertexBuffer.sizeInBytes); expect(statistics.texturesByteLength).toBe(0); }); }); it("processes implicit feature ID attribute with default feature IDs", function() { return loadGltf(buildingsMetadata).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[1]; const primitive = node.primitives[0]; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(node); import__694.FeatureIdPipelineStage.process(renderResources, primitive, frameState2); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__694.FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS, import__694.FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS, [ " int featureId_0;", " int featureId_1;", " int buildings;", " int defaultIdsTest;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__694.FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS, import__694.FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS, [ " int featureId_0;", " int featureId_1;", " int buildings;", " int defaultIdsTest;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS, [ " featureIds.featureId_0 = int(czm_round(attributes.featureId_0));", " featureIds.featureId_1 = int(czm_round(a_implicit_featureId_1));" ] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS, [ " featureIds.featureId_0 = int(czm_round(attributes.featureId_0));", " featureIds.featureId_1 = int(czm_round(v_implicit_featureId_1));" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_VS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES, [ " featureIds.buildings = featureIds.featureId_0;", " featureIds.defaultIdsTest = featureIds.featureId_1;" ] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_FS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES, [ " featureIds.buildings = featureIds.featureId_0;", " featureIds.defaultIdsTest = featureIds.featureId_1;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_SET_FEATURE_ID_VARYINGS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_SET_FEATURE_ID_VARYINGS, [" v_implicit_featureId_1 = a_implicit_featureId_1;"] ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasAttributes(shaderBuilder, void 0, [ "in float a_implicit_featureId_1;" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "float v_implicit_featureId_1;" ]); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__694._shadersFeatureIdStageVS ]); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__694._shadersFeatureIdStageFS ]); expect(resources.length).toBe(1); const vertexBuffer = resources[0]; expect(vertexBuffer).toBeDefined(); expect(vertexBuffer.vertexArrayDestroyable).toBe(false); expect(renderResources.attributes.length).toBe(2); const implicitAttribute = renderResources.attributes[1]; expect(implicitAttribute.index).toBe(1); expect(implicitAttribute.instanceDivisor).toBeUndefined(); expect(implicitAttribute.value).toBeUndefined(); expect(implicitAttribute.vertexBuffer).toBe(vertexBuffer); expect(implicitAttribute.normalize).toBe(false); expect(implicitAttribute.componentsPerAttribute).toBe(1); expect(implicitAttribute.componentDatatype).toBe( import__694.ComponentDatatype.FLOAT ); expect(implicitAttribute.strideInBytes).toBe(4); expect(implicitAttribute.offsetInBytes).toBe(0); const uniformMap = renderResources.uniformMap; expect(uniformMap).toEqual({}); const statistics = renderResources.model.statistics; expect(statistics.geometryByteLength).toBe(vertexBuffer.sizeInBytes); expect(statistics.texturesByteLength).toBe(0); }); }); it("processes feature ID texture", function() { return loadGltf(microcosm).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const primitive = node.primitives[0]; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(node); import__694.FeatureIdPipelineStage.process(renderResources, primitive, frameState2); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__694.FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS, import__694.FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS, [] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__694.FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS, import__694.FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS, [" int featureId_0;", " int landCover;"] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS, [] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS, [ " featureIds.featureId_0 = czm_unpackUint(texture(u_featureIdTexture_0, v_texCoord_0).r);" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_VS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES, [] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_FS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES, [" featureIds.landCover = featureIds.featureId_0;"] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_SET_FEATURE_ID_VARYINGS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_SET_FEATURE_ID_VARYINGS, [] ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasAttributes(shaderBuilder, void 0, []); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform sampler2D u_featureIdTexture_0;" ]); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, []); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__694._shadersFeatureIdStageVS ]); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__694._shadersFeatureIdStageFS ]); expect(resources).toEqual([]); expect(renderResources.attributes.length).toBe(1); const uniformMap = renderResources.uniformMap; expect(uniformMap.u_featureIdTexture_0).toBeDefined(); const featureIdTexture = primitive.featureIds[0]; expect(uniformMap.u_featureIdTexture_0()).toBe( featureIdTexture.textureReader.texture ); }); }); it("adds feature ID texture transforms to the shader", async function() { const gltfLoader = await loadGltf( featureIdTextureWithTextureTransformUrl ); const components = gltfLoader.components; const node = components.nodes[0]; const primitive = node.primitives[0]; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(node); import__694.FeatureIdPipelineStage.process(renderResources, primitive, frameState2); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__694.FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS, import__694.FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS, [] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__694.FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS, import__694.FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS, [" int featureId_0;"] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS, [] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS, [ " featureIds.featureId_0 = czm_unpackUint(texture(u_featureIdTexture_0, vec2(u_featureIdTexture_0Transform * vec3(v_texCoord_0, 1.0))).r);" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_VS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES, [] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_SET_FEATURE_ID_VARYINGS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_SET_FEATURE_ID_VARYINGS, [] ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasAttributes(shaderBuilder, void 0, []); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform sampler2D u_featureIdTexture_0;", "uniform mat3 u_featureIdTexture_0Transform;" ]); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, []); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__694._shadersFeatureIdStageVS ]); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__694._shadersFeatureIdStageFS ]); expect(resources).toEqual([]); expect(renderResources.attributes.length).toBe(1); const uniformMap = renderResources.uniformMap; expect(uniformMap.u_featureIdTexture_0).toBeDefined(); const featureIdTexture = primitive.featureIds[0]; expect(uniformMap.u_featureIdTexture_0()).toBe( featureIdTexture.textureReader.texture ); }); it("processes feature ID textures with multiple channels", function() { return loadGltf(largeFeatureIdTexture).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const primitive = node.primitives[0]; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(node); import__694.FeatureIdPipelineStage.process(renderResources, primitive, frameState2); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__694.FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS, import__694.FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS, [] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__694.FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS, import__694.FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS, [ " int featureId_0;", " int featureId_1;", " int featureId_2;", " int featureId_3;", " int featureId_4;", " int featureId_5;", " int featureId_6;", " int idsRGBA;", " int idsRGB;", " int idsG;", " int idsBA;", " int idsGR;", " int idsAGBB;", " int idsGWithNull;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS, [] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS, [ " featureIds.featureId_0 = czm_unpackUint(texture(u_featureIdTexture_0, v_texCoord_0).rgba);", " featureIds.featureId_1 = czm_unpackUint(texture(u_featureIdTexture_1, v_texCoord_0).rgb);", " featureIds.featureId_2 = czm_unpackUint(texture(u_featureIdTexture_2, v_texCoord_0).g);", " featureIds.featureId_3 = czm_unpackUint(texture(u_featureIdTexture_3, v_texCoord_0).ba);", " featureIds.featureId_4 = czm_unpackUint(texture(u_featureIdTexture_4, v_texCoord_0).gr);", " featureIds.featureId_5 = czm_unpackUint(texture(u_featureIdTexture_5, v_texCoord_0).agbb);", " featureIds.featureId_6 = czm_unpackUint(texture(u_featureIdTexture_6, v_texCoord_0).g);" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_VS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES, [] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_FS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES, [ " featureIds.idsRGBA = featureIds.featureId_0;", " featureIds.idsRGB = featureIds.featureId_1;", " featureIds.idsG = featureIds.featureId_2;", " featureIds.idsBA = featureIds.featureId_3;", " featureIds.idsGR = featureIds.featureId_4;", " featureIds.idsAGBB = featureIds.featureId_5;", " featureIds.idsGWithNull = featureIds.featureId_6;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_SET_FEATURE_ID_VARYINGS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_SET_FEATURE_ID_VARYINGS, [] ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasAttributes(shaderBuilder, void 0, []); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform sampler2D u_featureIdTexture_0;", "uniform sampler2D u_featureIdTexture_1;", "uniform sampler2D u_featureIdTexture_2;", "uniform sampler2D u_featureIdTexture_3;", "uniform sampler2D u_featureIdTexture_4;", "uniform sampler2D u_featureIdTexture_5;", "uniform sampler2D u_featureIdTexture_6;" ]); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, []); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__694._shadersFeatureIdStageVS ]); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__694._shadersFeatureIdStageFS ]); expect(resources).toEqual([]); expect(renderResources.attributes.length).toBe(1); const uniformMap = renderResources.uniformMap; const featureIdTexture = primitive.featureIds[0]; const texture = featureIdTexture.textureReader.texture; expect(uniformMap.u_featureIdTexture_0()).toBe(texture); expect(uniformMap.u_featureIdTexture_1()).toBe(texture); expect(uniformMap.u_featureIdTexture_2()).toBe(texture); expect(uniformMap.u_featureIdTexture_3()).toBe(texture); expect(uniformMap.u_featureIdTexture_4()).toBe(texture); expect(uniformMap.u_featureIdTexture_5()).toBe(texture); expect(uniformMap.u_featureIdTexture_6()).toBe(texture); }); }); it("processes instance feature IDs", function() { return loadGltf(boxInstanced).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const primitive = node.primitives[0]; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(node); import__694.FeatureIdPipelineStage.process(renderResources, primitive, frameState2); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__694.FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS, import__694.FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS, [ " int instanceFeatureId_0;", " int instanceFeatureId_1;", " int perInstance;", " int section;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__694.FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS, import__694.FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS, [ " int instanceFeatureId_0;", " int instanceFeatureId_1;", " int perInstance;", " int section;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS, [ " featureIds.instanceFeatureId_0 = int(czm_round(a_implicit_instanceFeatureId_0));", " featureIds.instanceFeatureId_1 = int(czm_round(a_instanceFeatureId_0));" ] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS, [ " featureIds.instanceFeatureId_0 = int(czm_round(v_implicit_instanceFeatureId_0));", " featureIds.instanceFeatureId_1 = int(czm_round(v_instanceFeatureId_0));" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_VS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES, [ " featureIds.perInstance = featureIds.instanceFeatureId_0;", " featureIds.section = featureIds.instanceFeatureId_1;" ] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_FS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES, [ " featureIds.perInstance = featureIds.instanceFeatureId_0;", " featureIds.section = featureIds.instanceFeatureId_1;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__694.FeatureIdPipelineStage.FUNCTION_ID_SET_FEATURE_ID_VARYINGS, import__694.FeatureIdPipelineStage.FUNCTION_SIGNATURE_SET_FEATURE_ID_VARYINGS, [ " v_instanceFeatureId_0 = a_instanceFeatureId_0;", " v_implicit_instanceFeatureId_0 = a_implicit_instanceFeatureId_0;" ] ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasAttributes(shaderBuilder, void 0, [ "in float a_implicit_instanceFeatureId_0;" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "float v_instanceFeatureId_0;", "float v_implicit_instanceFeatureId_0;" ]); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__694._shadersFeatureIdStageVS ]); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__694._shadersFeatureIdStageFS ]); expect(resources.length).toBe(1); const vertexBuffer = resources[0]; expect(vertexBuffer).toBeDefined(); expect(vertexBuffer.vertexArrayDestroyable).toBe(false); expect(renderResources.attributes.length).toBe(2); const implicitAttribute = renderResources.attributes[1]; expect(implicitAttribute.index).toBe(1); expect(implicitAttribute.instanceDivisor).toBe(1); expect(implicitAttribute.value).toBeUndefined(); expect(implicitAttribute.vertexBuffer).toBe(vertexBuffer); expect(implicitAttribute.normalize).toBe(false); expect(implicitAttribute.componentsPerAttribute).toBe(1); expect(implicitAttribute.componentDatatype).toBe( import__694.ComponentDatatype.FLOAT ); expect(implicitAttribute.strideInBytes).toBe(4); expect(implicitAttribute.offsetInBytes).toBe(0); const uniformMap = renderResources.uniformMap; expect(uniformMap).toEqual({}); const statistics = renderResources.model.statistics; expect(statistics.geometryByteLength).toBe(vertexBuffer.sizeInBytes); expect(statistics.texturesByteLength).toBe(0); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/GeoJsonLoaderSpec.js var import__695 = __toESM(require_Cesium(), 1); describe( "Scene/Model/GeoJsonLoader", function() { const geoJsonMultiPointUrl = "./Data/Cesium3DTiles/GeoJson/MultiPoint/multiPoint.geojson"; const geoJsonPointUrl = "./Data/Cesium3DTiles/GeoJson/Point/point.geojson"; const geoJsonMultiPolygonUrl = "./Data/Cesium3DTiles/GeoJson/MultiPolygon/multiPolygon.geojson"; const geoJsonPolygonUrl = "./Data/Cesium3DTiles/GeoJson/Polygon/polygon.geojson"; const geoJsonPolygonHeightsUrl = "./Data/Cesium3DTiles/GeoJson/PolygonHeights/polygonHeights.geojson"; const geoJsonPolygonHoleUrl = "./Data/Cesium3DTiles/GeoJson/PolygonHole/polygonHole.geojson"; const geoJsonPolygonNoPropertiesUrl = "./Data/Cesium3DTiles/GeoJson/PolygonNoProperties/polygonNoProperties.geojson"; const geoJsonLineStringUrl = "./Data/Cesium3DTiles/GeoJson/LineString/lineString.geojson"; const geoJsonMultiLineStringUrl = "./Data/Cesium3DTiles/GeoJson/MultiLineString/multiLineString.geojson"; const geoJsonMultipleFeaturesUrl = "./Data/Cesium3DTiles/GeoJson/MultipleFeatures/multipleFeatures.geojson"; let scene2; const geoJsonLoaders = []; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { for (let i = 0; i < geoJsonLoaders.length; i++) { const loader = geoJsonLoaders[i]; if (!loader.isDestroyed()) { loader.destroy(); } } geoJsonLoaders.length = 0; import__695.ResourceCache.clearForSpecs(); }); async function loadGeoJson(geoJsonPath) { const json = await import__695.Resource.fetchJson({ url: geoJsonPath }); const loader = new import__695.GeoJsonLoader({ geoJson: json }); geoJsonLoaders.push(loader); await loader.load(); await waitForLoaderProcess_default(loader, scene2); return loader; } function getAttribute(attributes, semantic, setIndex) { const attributesLength = attributes.length; for (let i = 0; i < attributesLength; ++i) { const attribute = attributes[i]; if (attribute.semantic === semantic && attribute.setIndex === setIndex) { return attribute; } } return void 0; } function testLoader(url, expected) { return loadGeoJson(url).then(function(loader) { const components = loader.components; const scene3 = components.scene; const rootNode = scene3.nodes[0]; const primitive = rootNode.primitives[0]; const attributes = primitive.attributes; const positionAttribute = getAttribute( attributes, import__695.VertexAttributeSemantic.POSITION ); const featureIdAttribute = getAttribute( attributes, import__695.VertexAttributeSemantic.FEATURE_ID, 0 ); const indices = primitive.indices; const material = primitive.material; const featureIdAccessor = primitive.featureIds[0]; const transform = components.transform; const structuralMetadata = components.structuralMetadata; const propertyTable = structuralMetadata.getPropertyTable(0); expect(positionAttribute.buffer).toBeDefined(); expect(positionAttribute.buffer.sizeInBytes).toBe( expected.vertexCount * 3 * 4 ); expect(positionAttribute.count).toBe(expected.vertexCount); expect(positionAttribute.min).toBeDefined(); expect(positionAttribute.max).toBeDefined(); expect(featureIdAttribute.buffer).toBeDefined(); expect(featureIdAttribute.buffer.sizeInBytes).toBe( expected.vertexCount * 4 ); expect(featureIdAttribute.count).toBe(expected.vertexCount); if (primitive.primitiveType === import__695.PrimitiveType.LINES) { expect(indices.buffer).toBeDefined(); expect(indices.buffer.sizeInBytes).toBe(expected.indexCount * 2); expect(indices.count).toBe(expected.indexCount); expect(indices.indexDatatype).toBe(import__695.IndexDatatype.UNSIGNED_SHORT); } expect(material.unlit).toBe(true); expect(primitive.featureIds.length).toBe(1); expect(featureIdAccessor.featureCount).toEqual(expected.featureCount); expect(featureIdAccessor.nullFeatureId).not.toBeDefined(); expect(featureIdAccessor.propertyTableId).toBe(0); expect(featureIdAccessor.setIndex).toBe(0); expect(featureIdAccessor.positionalLabel).toBe("featureId_0"); expect(transform).not.toEqual(import__695.Matrix4.IDENTITY); expect(propertyTable.id).toBe(0); expect(propertyTable.count).toBe(expected.featureCount); if (expected.hasProperties && expected.featureCount === 1) { expect(propertyTable.getProperty(0, "name")).toBe("UL"); expect(propertyTable.getProperty(0, "code")).toBe(12); } else if (expected.hasProperties && expected.featureCount === 2) { expect(propertyTable.getProperty(0, "name")).toBe("AL"); expect(propertyTable.getProperty(0, "code")).toBe(11); expect(propertyTable.getProperty(1, "name")).toBe("UL"); expect(propertyTable.getProperty(1, "code")).toBe(12); } }); } it("loads GeoJSON MultiPoint", function() { return testLoader(geoJsonMultiPointUrl, { vertexCount: 10, featureCount: 1, hasProperties: true }); }); it("loads GeoJSON Point", function() { return testLoader(geoJsonPointUrl, { vertexCount: 1, featureCount: 1, hasProperties: true }); }); it("loads GeoJSON MultiPolygon", function() { return testLoader(geoJsonMultiPolygonUrl, { vertexCount: 10, indexCount: 16, featureCount: 1, hasProperties: true }); }); it("loads GeoJSON Polygon", function() { return testLoader(geoJsonPolygonUrl, { vertexCount: 5, indexCount: 8, featureCount: 1, hasProperties: true }); }); it("loads GeoJSON Polygon with heights", function() { return testLoader(geoJsonPolygonHeightsUrl, { vertexCount: 5, indexCount: 8, featureCount: 1, hasProperties: true }); }); it("loads GeoJSON Polygon with hole", function() { return testLoader(geoJsonPolygonHoleUrl, { vertexCount: 10, indexCount: 16, featureCount: 1, hasProperties: true }); }); it("loads GeoJSON Polygon with no properties", function() { return testLoader(geoJsonPolygonNoPropertiesUrl, { vertexCount: 5, indexCount: 8, featureCount: 1, hasProperties: false }); }); it("loads GeoJSON LineString", function() { return testLoader(geoJsonLineStringUrl, { vertexCount: 5, indexCount: 8, featureCount: 1, hasProperties: true }); }); it("loads GeoJSON MultiLineString", function() { return testLoader(geoJsonMultiLineStringUrl, { vertexCount: 10, indexCount: 16, featureCount: 1, hasProperties: true }); }); it("loads GeoJSON with multiple features", function() { return testLoader(geoJsonMultipleFeaturesUrl, { vertexCount: 10, indexCount: 16, featureCount: 2, hasProperties: true }); }); it("destroys GeoJson loader", function() { return loadGeoJson(geoJsonPolygonUrl).then(function(loader) { expect(loader.components).toBeDefined(); expect(loader.isDestroyed()).toBe(false); loader.destroy(); expect(loader.components).toBeUndefined(); expect(loader.isDestroyed()).toBe(true); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/GeometryPipelineStageSpec.js var import__696 = __toESM(require_Cesium(), 1); describe( "Scene/Model/GeometryPipelineStage", function() { const positionOnlyPrimitive = { attributes: [ { semantic: import__696.VertexAttributeSemantic.POSITION, buffer: new Float32Array([0, 1, 2, 3, 4, 5]).buffer, count: 2, type: import__696.AttributeType.VEC3, componentDatatype: import__696.ComponentDatatype.FLOAT, byteOffset: 0, byteStride: 12 } ] }; const customAttributePrimitive = { attributes: [ { semantic: import__696.VertexAttributeSemantic.POSITION, buffer: new Float32Array([0, 1, 2, 3, 4, 5]).buffer, count: 2, type: import__696.AttributeType.VEC3, componentDatatype: import__696.ComponentDatatype.FLOAT, byteOffset: 0, byteStride: 12 }, { name: "_TEMPERATURE", buffer: new Uint32Array([0, 1, 2, 3, 4, 5]).buffer, count: 3, type: import__696.AttributeType.VEC2, componentDatatype: import__696.ComponentDatatype.UNSIGNED_SHORT, byteOffset: 0, byteStride: 4 } ] }; const boomBoxSpecularGlossiness = "./Data/Models/glTF-2.0/BoomBox/glTF-pbrSpecularGlossiness/BoomBox.gltf"; const boxTextured = "./Data/Models/glTF-2.0/BoxTextured/glTF-Binary/BoxTextured.glb"; const boxTexturedWithPropertyAttributes = "./Data/Models/glTF-2.0/BoxTexturedWithPropertyAttributes/glTF/BoxTexturedWithPropertyAttributes.gltf"; const boxVertexColors = "./Data/Models/glTF-2.0/BoxVertexColors/glTF/BoxVertexColors.gltf"; const pointCloudRGB = "./Data/Models/glTF-2.0/PointCloudWithRGBColors/glTF-Binary/PointCloudWithRGBColors.glb"; const microcosm = "./Data/Models/glTF-2.0/Microcosm/glTF/microcosm.gltf"; const weather = "./Data/Models/glTF-2.0/Weather/glTF/weather.gltf"; const buildingsMetadata = "./Data/Models/glTF-2.0/BuildingsMetadata/glTF/buildings-metadata.gltf"; const dracoMilkTruck = "./Data/Models/glTF-2.0/CesiumMilkTruck/glTF-Draco/CesiumMilkTruck.gltf"; const dracoBoxWithTangents = "./Data/Models/glTF-2.0/BoxWithTangents/glTF-Draco/BoxWithTangents.gltf"; const boxInstancedTranslationUrl = "./Data/Models/glTF-2.0/BoxInstancedTranslation/glTF/box-instanced-translation.gltf"; let scene2; let scene2D; const gltfLoaders = []; beforeAll(function() { scene2 = createScene_default(); scene2D = createScene_default(); scene2D.morphTo2D(0); scene2D.updateFrameState(); }); afterAll(function() { scene2.destroyForSpecs(); scene2D.destroyForSpecs(); }); afterEach(function() { const gltfLoadersLength = gltfLoaders.length; for (let i = 0; i < gltfLoadersLength; ++i) { const gltfLoader = gltfLoaders[i]; if (!gltfLoader.isDestroyed()) { gltfLoader.destroy(); } } gltfLoaders.length = 0; import__696.ResourceCache.clearForSpecs(); }); function verifyFeatureStruct(shaderBuilder) { ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__696.SelectedFeatureIdPipelineStage.STRUCT_ID_SELECTED_FEATURE, import__696.SelectedFeatureIdPipelineStage.STRUCT_NAME_SELECTED_FEATURE, [] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__696.SelectedFeatureIdPipelineStage.STRUCT_ID_SELECTED_FEATURE, import__696.SelectedFeatureIdPipelineStage.STRUCT_NAME_SELECTED_FEATURE, [] ); } function getOptions(gltfPath, options) { const resource = new import__696.Resource({ url: gltfPath }); return (0, import__696.combine)(options, { gltfResource: resource, incrementallyLoadTextures: false // Default to false if not supplied }); } async function loadGltf(gltfPath, options) { const gltfLoader = new import__696.GltfLoader(getOptions(gltfPath, options)); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, scene2); return gltfLoader; } function mockRenderResources(primitive) { const count = (0, import__696.defined)(primitive.indices) ? primitive.indices.count : primitive.attributes[0].count; return { attributes: [], shaderBuilder: new import__696.ShaderBuilder(), attributeIndex: 1, count, model: { type: import__696.ModelType.TILE_GLTF, statistics: new import__696.ModelStatistics() }, runtimeNode: { node: {} }, runtimePrimitive: {} }; } it("processes POSITION attribute from primitive", function() { const renderResources = mockRenderResources(positionOnlyPrimitive); import__696.GeometryPipelineStage.process( renderResources, positionOnlyPrimitive, scene2.frameState ); const shaderBuilder = renderResources.shaderBuilder; const attributes = renderResources.attributes; expect(attributes.length).toEqual(1); const positionAttribute = attributes[0]; expect(positionAttribute.index).toEqual(0); expect(positionAttribute.vertexBuffer).toBeDefined(); expect(positionAttribute.componentsPerAttribute).toEqual(3); expect(positionAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(positionAttribute.offsetInBytes).toBe(0); expect(positionAttribute.strideInBytes).toBe(12); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [" vec3 positionMC;"] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [" vec3 positionMC;", " vec3 positionWC;", " vec3 positionEC;"] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES, [" attributes.positionMC = a_positionMC;"] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, [] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_FS, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, [] ); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "vec3 v_positionEC;", "vec3 v_positionMC;", "vec3 v_positionWC;" ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasAttributes( shaderBuilder, "in vec3 a_positionMC;", [] ); verifyFeatureStruct(shaderBuilder); }); it("processes POSITION, NORMAL and TEXCOORD attributes from primitive", function() { return loadGltf(boxTextured).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; const renderResources = mockRenderResources(primitive); import__696.GeometryPipelineStage.process( renderResources, primitive, scene2.frameState ); const shaderBuilder = renderResources.shaderBuilder; const attributes = renderResources.attributes; expect(attributes.length).toEqual(3); const normalAttribute = attributes[0]; expect(normalAttribute.index).toEqual(1); expect(normalAttribute.vertexBuffer).toBeDefined(); expect(normalAttribute.componentsPerAttribute).toEqual(3); expect(normalAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(normalAttribute.offsetInBytes).toBe(0); expect(normalAttribute.strideInBytes).toBe(12); const positionAttribute = attributes[1]; expect(positionAttribute.index).toEqual(0); expect(positionAttribute.vertexBuffer).toBeDefined(); expect(positionAttribute.componentsPerAttribute).toEqual(3); expect(positionAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(positionAttribute.offsetInBytes).toBe(288); expect(positionAttribute.strideInBytes).toBe(12); const texCoord0Attribute = attributes[2]; expect(texCoord0Attribute.index).toEqual(2); expect(texCoord0Attribute.vertexBuffer).toBeDefined(); expect(texCoord0Attribute.componentsPerAttribute).toEqual(2); expect(texCoord0Attribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(texCoord0Attribute.offsetInBytes).toBe(0); expect(texCoord0Attribute.strideInBytes).toBe(8); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [" vec3 positionMC;", " vec3 normalMC;", " vec2 texCoord_0;"] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 positionWC;", " vec3 positionEC;", " vec3 normalEC;", " vec2 texCoord_0;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES, [ " attributes.positionMC = a_positionMC;", " attributes.normalMC = a_normalMC;", " attributes.texCoord_0 = a_texCoord_0;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, [" v_texCoord_0 = attributes.texCoord_0;"] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_FS, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, [" attributes.texCoord_0 = v_texCoord_0;"] ); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "vec3 v_normalEC;", "vec2 v_texCoord_0;", "vec3 v_positionEC;", "vec3 v_positionMC;", "vec3 v_positionWC;" ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_NORMALS", "HAS_TEXCOORD_0" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_NORMALS", "HAS_TEXCOORD_0" ]); ShaderBuilderTester_default.expectHasAttributes( shaderBuilder, "in vec3 a_positionMC;", ["in vec3 a_normalMC;", "in vec2 a_texCoord_0;"] ); verifyFeatureStruct(shaderBuilder); }); }); it("processes POSITION attribute from primitive for 2D", function() { return loadGltf(boxTextured).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; const renderResources = mockRenderResources(primitive); const runtimePrimitive = renderResources.runtimePrimitive; renderResources.model._projectTo2D = true; runtimePrimitive.positionBuffer2D = {}; import__696.GeometryPipelineStage.process( renderResources, primitive, scene2D.frameState ); const shaderBuilder = renderResources.shaderBuilder; const attributes = renderResources.attributes; expect(attributes.length).toEqual(4); const normalAttribute = attributes[0]; expect(normalAttribute.index).toEqual(1); const positionAttribute = attributes[1]; expect(positionAttribute.index).toEqual(0); expect(positionAttribute.vertexBuffer).toBeDefined(); expect(positionAttribute.componentsPerAttribute).toEqual(3); expect(positionAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(positionAttribute.offsetInBytes).toBe(288); expect(positionAttribute.strideInBytes).toBe(12); const position2DAttribute = attributes[2]; expect(position2DAttribute.index).toEqual(2); expect(position2DAttribute.vertexBuffer).toBe( runtimePrimitive.positionBuffer2D ); expect(position2DAttribute.componentsPerAttribute).toEqual(3); expect(position2DAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(position2DAttribute.offsetInBytes).toBe(0); expect(position2DAttribute.strideInBytes).toBeUndefined(); const texCoord0Attribute = attributes[3]; expect(texCoord0Attribute.index).toEqual(3); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 position2D;", " vec3 normalMC;", " vec2 texCoord_0;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES, [ " attributes.positionMC = a_positionMC;", " attributes.position2D = a_position2D;", " attributes.normalMC = a_normalMC;", " attributes.texCoord_0 = a_texCoord_0;" ] ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_NORMALS", "HAS_TEXCOORD_0" ]); ShaderBuilderTester_default.expectHasAttributes( shaderBuilder, "in vec3 a_positionMC;", [ "in vec3 a_position2D;", "in vec3 a_normalMC;", "in vec2 a_texCoord_0;" ] ); verifyFeatureStruct(shaderBuilder); }); }); it("processes POSITION, NORMAL, TEXCOORD and TANGENT attributes from primitive", function() { return loadGltf(boomBoxSpecularGlossiness).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const renderResources = mockRenderResources(primitive); import__696.GeometryPipelineStage.process( renderResources, primitive, scene2.frameState ); const shaderBuilder = renderResources.shaderBuilder; const attributes = renderResources.attributes; expect(attributes.length).toEqual(4); const texCoord0Attribute = attributes[0]; expect(texCoord0Attribute.index).toEqual(1); expect(texCoord0Attribute.vertexBuffer).toBeDefined(); expect(texCoord0Attribute.componentsPerAttribute).toEqual(2); expect(texCoord0Attribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(texCoord0Attribute.offsetInBytes).toBe(0); expect(texCoord0Attribute.strideInBytes).toBe(8); const normalAttribute = attributes[1]; expect(normalAttribute.index).toEqual(2); expect(normalAttribute.vertexBuffer).toBeDefined(); expect(normalAttribute.componentsPerAttribute).toEqual(3); expect(normalAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(normalAttribute.offsetInBytes).toBe(0); expect(normalAttribute.strideInBytes).toBe(12); const tangentAttribute = attributes[2]; expect(tangentAttribute.index).toEqual(3); expect(tangentAttribute.vertexBuffer).toBeDefined(); expect(tangentAttribute.componentsPerAttribute).toEqual(4); expect(tangentAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(tangentAttribute.offsetInBytes).toBe(0); expect(tangentAttribute.strideInBytes).toBe(16); const positionAttribute = attributes[3]; expect(positionAttribute.index).toEqual(0); expect(positionAttribute.vertexBuffer).toBeDefined(); expect(positionAttribute.componentsPerAttribute).toEqual(3); expect(positionAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(positionAttribute.offsetInBytes).toBe(0); expect(positionAttribute.strideInBytes).toBe(12); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 normalMC;", " vec3 tangentMC;", " float tangentSignMC;", " vec3 bitangentMC;", " vec2 texCoord_0;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 positionWC;", " vec3 positionEC;", " vec3 normalEC;", " vec3 tangentEC;", " vec3 bitangentEC;", " vec2 texCoord_0;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES, [ " attributes.positionMC = a_positionMC;", " attributes.normalMC = a_normalMC;", " attributes.tangentMC = a_tangentMC.xyz;", " attributes.tangentSignMC = a_tangentMC.w;", " attributes.texCoord_0 = a_texCoord_0;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, [" v_texCoord_0 = attributes.texCoord_0;"] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_FS, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, [" attributes.texCoord_0 = v_texCoord_0;"] ); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "vec3 v_normalEC;", "vec3 v_tangentEC;", "vec3 v_bitangentEC;", "vec2 v_texCoord_0;", "vec3 v_positionEC;", "vec3 v_positionMC;", "vec3 v_positionWC;" ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_BITANGENTS", "HAS_NORMALS", "HAS_TANGENTS", "HAS_TEXCOORD_0" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_BITANGENTS", "HAS_NORMALS", "HAS_TANGENTS", "HAS_TEXCOORD_0" ]); ShaderBuilderTester_default.expectHasAttributes( shaderBuilder, "in vec3 a_positionMC;", [ "in vec3 a_normalMC;", "in vec4 a_tangentMC;", "in vec2 a_texCoord_0;" ] ); verifyFeatureStruct(shaderBuilder); }); }); it("processes multiple TEXCOORD attributes from primitive", function() { return loadGltf(microcosm).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const renderResources = mockRenderResources(primitive); import__696.GeometryPipelineStage.process( renderResources, primitive, scene2.frameState ); const shaderBuilder = renderResources.shaderBuilder; const attributes = renderResources.attributes; expect(attributes.length).toEqual(3); const positionAttribute = attributes[0]; expect(positionAttribute.index).toEqual(0); expect(positionAttribute.vertexBuffer).toBeDefined(); expect(positionAttribute.componentsPerAttribute).toEqual(3); expect(positionAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); const texCoord0Attribute = attributes[1]; expect(texCoord0Attribute.index).toEqual(1); expect(texCoord0Attribute.vertexBuffer).toBeDefined(); expect(texCoord0Attribute.componentsPerAttribute).toEqual(2); expect(texCoord0Attribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(texCoord0Attribute.offsetInBytes).toBe(0); expect(texCoord0Attribute.strideInBytes).toBe(8); const texCoord1Attribute = attributes[2]; expect(texCoord1Attribute.index).toEqual(2); expect(texCoord1Attribute.vertexBuffer).toBeDefined(); expect(texCoord1Attribute.componentsPerAttribute).toEqual(2); expect(texCoord1Attribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(texCoord1Attribute.offsetInBytes).toBe(0); expect(texCoord1Attribute.strideInBytes).toBe(8); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec2 texCoord_0;", " vec2 texCoord_1;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 positionWC;", " vec3 positionEC;", " vec2 texCoord_0;", " vec2 texCoord_1;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES, [ " attributes.positionMC = a_positionMC;", " attributes.texCoord_0 = a_texCoord_0;", " attributes.texCoord_1 = a_texCoord_1;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, [ " v_texCoord_0 = attributes.texCoord_0;", " v_texCoord_1 = attributes.texCoord_1;" ] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_FS, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, [ " attributes.texCoord_0 = v_texCoord_0;", " attributes.texCoord_1 = v_texCoord_1;" ] ); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "vec2 v_texCoord_0;", "vec2 v_texCoord_1;", "vec3 v_positionEC;", "vec3 v_positionMC;", "vec3 v_positionWC;" ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_TEXCOORD_0", "HAS_TEXCOORD_1" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_TEXCOORD_0", "HAS_TEXCOORD_1" ]); ShaderBuilderTester_default.expectHasAttributes( shaderBuilder, "in vec3 a_positionMC;", ["in vec2 a_texCoord_0;", "in vec2 a_texCoord_1;"] ); verifyFeatureStruct(shaderBuilder); }); }); it("processes POSITION, NORMAL, TEXCOORD and COLOR attributes from primitive", function() { return loadGltf(boxVertexColors).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[2].primitives[0]; const renderResources = mockRenderResources(primitive); import__696.GeometryPipelineStage.process( renderResources, primitive, scene2.frameState ); const shaderBuilder = renderResources.shaderBuilder; const attributes = renderResources.attributes; expect(attributes.length).toEqual(4); const color0Attribute = attributes[0]; expect(color0Attribute.index).toEqual(1); expect(color0Attribute.vertexBuffer).toBeDefined(); expect(color0Attribute.componentsPerAttribute).toEqual(4); expect(color0Attribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(color0Attribute.offsetInBytes).toBe(0); expect(color0Attribute.strideInBytes).toBe(16); const normalAttribute = attributes[1]; expect(normalAttribute.index).toEqual(2); expect(normalAttribute.vertexBuffer).toBeDefined(); expect(normalAttribute.componentsPerAttribute).toEqual(3); expect(normalAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(normalAttribute.offsetInBytes).toBe(0); expect(normalAttribute.strideInBytes).toBe(12); const positionAttribute = attributes[2]; expect(positionAttribute.index).toEqual(0); expect(positionAttribute.vertexBuffer).toBeDefined(); expect(positionAttribute.componentsPerAttribute).toEqual(3); expect(positionAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(positionAttribute.offsetInBytes).toBe(0); expect(positionAttribute.strideInBytes).toBe(12); const texCoord0Attribute = attributes[3]; expect(texCoord0Attribute.index).toEqual(3); expect(texCoord0Attribute.vertexBuffer).toBeDefined(); expect(texCoord0Attribute.componentsPerAttribute).toEqual(2); expect(texCoord0Attribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(texCoord0Attribute.offsetInBytes).toBe(0); expect(texCoord0Attribute.strideInBytes).toBe(8); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 normalMC;", " vec4 color_0;", " vec2 texCoord_0;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 positionWC;", " vec3 positionEC;", " vec3 normalEC;", " vec4 color_0;", " vec2 texCoord_0;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES, [ " attributes.positionMC = a_positionMC;", " attributes.normalMC = a_normalMC;", " attributes.color_0 = a_color_0;", " attributes.texCoord_0 = a_texCoord_0;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, [ " v_color_0 = attributes.color_0;", " v_texCoord_0 = attributes.texCoord_0;" ] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_FS, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, [ " attributes.color_0 = v_color_0;", " attributes.texCoord_0 = v_texCoord_0;" ] ); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "vec3 v_normalEC;", "vec4 v_color_0;", "vec2 v_texCoord_0;", "vec3 v_positionEC;", "vec3 v_positionMC;", "vec3 v_positionWC;" ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_NORMALS", "HAS_COLOR_0", "HAS_TEXCOORD_0" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_NORMALS", "HAS_COLOR_0", "HAS_TEXCOORD_0" ]); ShaderBuilderTester_default.expectHasAttributes( shaderBuilder, "in vec3 a_positionMC;", ["in vec3 a_normalMC;", "in vec4 a_color_0;", "in vec2 a_texCoord_0;"] ); verifyFeatureStruct(shaderBuilder); }); }); it("promotes vec3 vertex colors to vec4 in the shader", function() { return loadGltf(pointCloudRGB).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const renderResources = mockRenderResources(primitive); import__696.GeometryPipelineStage.process( renderResources, primitive, scene2.frameState ); const shaderBuilder = renderResources.shaderBuilder; const attributes = renderResources.attributes; expect(attributes.length).toEqual(2); const positionAttribute = attributes[0]; expect(positionAttribute.index).toEqual(0); expect(positionAttribute.vertexBuffer).toBeDefined(); expect(positionAttribute.componentsPerAttribute).toEqual(3); expect(positionAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(positionAttribute.offsetInBytes).toBe(0); expect(positionAttribute.strideInBytes).toBe(24); const color0Attribute = attributes[1]; expect(color0Attribute.index).toEqual(1); expect(color0Attribute.vertexBuffer).toBeDefined(); expect(color0Attribute.componentsPerAttribute).toEqual(3); expect(color0Attribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(color0Attribute.offsetInBytes).toBe(12); expect(color0Attribute.strideInBytes).toBe(24); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [" vec3 positionMC;", " vec4 color_0;"] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 positionWC;", " vec3 positionEC;", " vec4 color_0;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES, [ " attributes.positionMC = a_positionMC;", " attributes.color_0 = a_color_0;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, [" v_color_0 = attributes.color_0;"] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_FS, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, [" attributes.color_0 = v_color_0;"] ); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "vec4 v_color_0;", "vec3 v_positionEC;", "vec3 v_positionMC;", "vec3 v_positionWC;" ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_COLOR_0", "PRIMITIVE_TYPE_POINTS" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_COLOR_0", "PRIMITIVE_TYPE_POINTS" ]); ShaderBuilderTester_default.expectHasAttributes( shaderBuilder, "in vec3 a_positionMC;", ["in vec4 a_color_0;"] ); verifyFeatureStruct(shaderBuilder); }); }); it("processes custom vertex attribute from primitive", function() { const renderResources = mockRenderResources(customAttributePrimitive); import__696.GeometryPipelineStage.process( renderResources, customAttributePrimitive, scene2.frameState ); const shaderBuilder = renderResources.shaderBuilder; const attributes = renderResources.attributes; expect(attributes.length).toEqual(2); const positionAttribute = attributes[0]; expect(positionAttribute.index).toEqual(0); expect(positionAttribute.vertexBuffer).toBeDefined(); expect(positionAttribute.componentsPerAttribute).toEqual(3); expect(positionAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(positionAttribute.offsetInBytes).toBe(0); expect(positionAttribute.strideInBytes).toBe(12); const customAttribute = attributes[1]; expect(customAttribute.index).toEqual(1); expect(customAttribute.vertexBuffer).toBeDefined(); expect(customAttribute.componentsPerAttribute).toEqual(2); expect(customAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.UNSIGNED_SHORT ); expect(customAttribute.offsetInBytes).toBe(0); expect(customAttribute.strideInBytes).toBe(4); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [" vec3 positionMC;", " vec2 temperature;"] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 positionWC;", " vec3 positionEC;", " vec2 temperature;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES, [ " attributes.positionMC = a_positionMC;", " attributes.temperature = a_temperature;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, [" v_temperature = attributes.temperature;"] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_FS, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, [" attributes.temperature = v_temperature;"] ); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "vec2 v_temperature;", "vec3 v_positionEC;", "vec3 v_positionMC;", "vec3 v_positionWC;" ]); ShaderBuilderTester_default.expectHasAttributes( shaderBuilder, "in vec3 a_positionMC;", ["in vec2 a_temperature;"] ); verifyFeatureStruct(shaderBuilder); }); it("processes POSITION, NORMAL and _FEATURE_ID_n attributes from primitive", function() { return loadGltf(buildingsMetadata).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; const renderResources = mockRenderResources(primitive); import__696.GeometryPipelineStage.process( renderResources, primitive, scene2.frameState ); const shaderBuilder = renderResources.shaderBuilder; const attributes = renderResources.attributes; expect(attributes.length).toEqual(3); const positionAttribute = attributes[0]; expect(positionAttribute.index).toEqual(0); expect(positionAttribute.vertexBuffer).toBeDefined(); expect(positionAttribute.componentsPerAttribute).toEqual(3); expect(positionAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(positionAttribute.offsetInBytes).toBe(0); expect(positionAttribute.strideInBytes).toBe(12); const normalAttribute = attributes[1]; expect(normalAttribute.index).toEqual(1); expect(normalAttribute.vertexBuffer).toBeDefined(); expect(normalAttribute.componentsPerAttribute).toEqual(3); expect(normalAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(normalAttribute.offsetInBytes).toBe(0); expect(normalAttribute.strideInBytes).toBe(12); const featureId0Attribute = attributes[2]; expect(featureId0Attribute.index).toEqual(2); expect(featureId0Attribute.vertexBuffer).toBeDefined(); expect(featureId0Attribute.componentsPerAttribute).toEqual(1); expect(featureId0Attribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(featureId0Attribute.offsetInBytes).toBe(0); expect(featureId0Attribute.strideInBytes).toBe(4); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 normalMC;", " float featureId_0;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 positionWC;", " vec3 positionEC;", " vec3 normalEC;", " float featureId_0;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES, [ " attributes.positionMC = a_positionMC;", " attributes.normalMC = a_normalMC;", " attributes.featureId_0 = a_featureId_0;" ] ); ShaderBuilderTester_default.expectHasAttributes( shaderBuilder, "in vec3 a_positionMC;", ["in float a_featureId_0;", "in vec3 a_normalMC;"] ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_FEATURE_ID_0", "HAS_NORMALS" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_FEATURE_ID_0", "HAS_NORMALS" ]); verifyFeatureStruct(shaderBuilder); }); }); it("sets PRIMITIVE_TYPE_POINTS for point primitive types", function() { return loadGltf(weather).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const renderResources = mockRenderResources(primitive); import__696.GeometryPipelineStage.process( renderResources, primitive, scene2.frameState ); const shaderBuilder = renderResources.shaderBuilder; const attributes = renderResources.attributes; expect(attributes.length).toEqual(2); const positionAttribute = attributes[0]; expect(positionAttribute.index).toEqual(0); expect(positionAttribute.vertexBuffer).toBeDefined(); expect(positionAttribute.componentsPerAttribute).toEqual(3); expect(positionAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(positionAttribute.offsetInBytes).toBe(0); expect(positionAttribute.strideInBytes).toBe(12); const featureId0Attribute = attributes[1]; expect(featureId0Attribute.index).toEqual(1); expect(featureId0Attribute.vertexBuffer).toBeDefined(); expect(featureId0Attribute.componentsPerAttribute).toEqual(1); expect(featureId0Attribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(featureId0Attribute.offsetInBytes).toBe(0); expect(featureId0Attribute.strideInBytes).toBe(4); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [" vec3 positionMC;", " float featureId_0;"] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 positionWC;", " vec3 positionEC;", " float featureId_0;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES, [ " attributes.positionMC = a_positionMC;", " attributes.featureId_0 = a_featureId_0;" ] ); ShaderBuilderTester_default.expectHasAttributes( shaderBuilder, "in vec3 a_positionMC;", ["in float a_featureId_0;"] ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_FEATURE_ID_0", "PRIMITIVE_TYPE_POINTS" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_FEATURE_ID_0", "PRIMITIVE_TYPE_POINTS" ]); verifyFeatureStruct(shaderBuilder); }); }); it("prepares Draco model for dequantization stage", function() { return loadGltf(dracoMilkTruck).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const renderResources = mockRenderResources(primitive); import__696.GeometryPipelineStage.process( renderResources, primitive, scene2.frameState ); const shaderBuilder = renderResources.shaderBuilder; const attributes = renderResources.attributes; expect(attributes.length).toEqual(3); const normalAttribute = attributes[0]; expect(normalAttribute.index).toEqual(1); expect(normalAttribute.vertexBuffer).toBeDefined(); expect(normalAttribute.componentsPerAttribute).toEqual(2); expect(normalAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.UNSIGNED_SHORT ); expect(normalAttribute.offsetInBytes).toBe(0); expect(normalAttribute.strideInBytes).not.toBeDefined(); const positionAttribute = attributes[1]; expect(positionAttribute.index).toEqual(0); expect(positionAttribute.vertexBuffer).toBeDefined(); expect(positionAttribute.componentsPerAttribute).toEqual(3); expect(positionAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.UNSIGNED_SHORT ); expect(positionAttribute.offsetInBytes).toBe(0); expect(positionAttribute.strideInBytes).not.toBeDefined(); const texCoord0Attribute = attributes[2]; expect(texCoord0Attribute.index).toEqual(2); expect(texCoord0Attribute.vertexBuffer).toBeDefined(); expect(texCoord0Attribute.componentsPerAttribute).toEqual(2); expect(texCoord0Attribute.componentDatatype).toEqual( import__696.ComponentDatatype.UNSIGNED_SHORT ); expect(texCoord0Attribute.offsetInBytes).toBe(0); expect(texCoord0Attribute.strideInBytes).not.toBeDefined(); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [" vec3 positionMC;", " vec3 normalMC;", " vec2 texCoord_0;"] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 positionWC;", " vec3 positionEC;", " vec3 normalEC;", " vec2 texCoord_0;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES, [] ); ShaderBuilderTester_default.expectHasAttributes( shaderBuilder, "in vec3 a_quantized_positionMC;", ["in vec2 a_quantized_normalMC;", "in vec2 a_quantized_texCoord_0;"] ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_NORMALS", "HAS_TEXCOORD_0" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_NORMALS", "HAS_TEXCOORD_0" ]); }); }); it("prepares Draco model with tangents for dequantization stage", function() { return loadGltf(dracoBoxWithTangents).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const renderResources = mockRenderResources(primitive); import__696.GeometryPipelineStage.process( renderResources, primitive, scene2.frameState ); const shaderBuilder = renderResources.shaderBuilder; const attributes = renderResources.attributes; expect(attributes.length).toEqual(4); const positionAttribute = attributes[0]; expect(positionAttribute.index).toEqual(0); expect(positionAttribute.vertexBuffer).toBeDefined(); expect(positionAttribute.componentsPerAttribute).toEqual(3); expect(positionAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.UNSIGNED_SHORT ); expect(positionAttribute.offsetInBytes).toBe(0); expect(positionAttribute.strideInBytes).not.toBeDefined(); const normalAttribute = attributes[1]; expect(normalAttribute.index).toEqual(1); expect(normalAttribute.vertexBuffer).toBeDefined(); expect(normalAttribute.componentsPerAttribute).toEqual(2); expect(normalAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.UNSIGNED_BYTE ); expect(normalAttribute.offsetInBytes).toBe(0); expect(normalAttribute.strideInBytes).not.toBeDefined(); const tangentAttribute = attributes[2]; expect(tangentAttribute.index).toEqual(2); expect(tangentAttribute.vertexBuffer).toBeDefined(); expect(tangentAttribute.componentsPerAttribute).toEqual(4); expect(tangentAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(normalAttribute.offsetInBytes).toBe(0); expect(normalAttribute.strideInBytes).not.toBeDefined(); const texCoord0Attribute = attributes[3]; expect(texCoord0Attribute.index).toEqual(3); expect(texCoord0Attribute.vertexBuffer).toBeDefined(); expect(texCoord0Attribute.componentsPerAttribute).toEqual(2); expect(texCoord0Attribute.componentDatatype).toEqual( import__696.ComponentDatatype.UNSIGNED_SHORT ); expect(texCoord0Attribute.offsetInBytes).toBe(0); expect(texCoord0Attribute.strideInBytes).not.toBeDefined(); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 normalMC;", " vec3 tangentMC;", " float tangentSignMC;", " vec3 bitangentMC;", " vec2 texCoord_0;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 positionWC;", " vec3 positionEC;", " vec3 normalEC;", " vec3 tangentEC;", " vec3 bitangentEC;", " vec2 texCoord_0;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES, [ " attributes.tangentMC = a_tangentMC.xyz;", " attributes.tangentSignMC = a_tangentMC.w;" ] ); ShaderBuilderTester_default.expectHasAttributes( shaderBuilder, "in vec3 a_quantized_positionMC;", [ "in vec2 a_quantized_normalMC;", "in vec2 a_quantized_texCoord_0;", "in vec4 a_tangentMC;" ] ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_BITANGENTS", "HAS_NORMALS", "HAS_TANGENTS", "HAS_TEXCOORD_0" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_BITANGENTS", "HAS_NORMALS", "HAS_TANGENTS", "HAS_TEXCOORD_0" ]); }); }); it("processes Draco model for 2D", function() { return loadGltf(dracoMilkTruck).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const renderResources = mockRenderResources(primitive); renderResources.model._projectTo2D = true; renderResources.runtimePrimitive.positionBuffer2D = {}; import__696.GeometryPipelineStage.process( renderResources, primitive, scene2D.frameState ); const shaderBuilder = renderResources.shaderBuilder; const attributes = renderResources.attributes; expect(attributes.length).toEqual(4); const normalAttribute = attributes[0]; expect(normalAttribute.index).toEqual(1); expect(normalAttribute.vertexBuffer).toBeDefined(); expect(normalAttribute.componentsPerAttribute).toEqual(2); expect(normalAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.UNSIGNED_SHORT ); expect(normalAttribute.offsetInBytes).toBe(0); expect(normalAttribute.strideInBytes).not.toBeDefined(); const positionAttribute = attributes[1]; expect(positionAttribute.index).toEqual(0); expect(positionAttribute.vertexBuffer).toBeDefined(); expect(positionAttribute.componentsPerAttribute).toEqual(3); expect(positionAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.UNSIGNED_SHORT ); expect(positionAttribute.offsetInBytes).toBe(0); expect(positionAttribute.strideInBytes).not.toBeDefined(); const positionAttribute2D = attributes[2]; expect(positionAttribute2D.index).toEqual(2); expect(positionAttribute2D.vertexBuffer).toBeDefined(); expect(positionAttribute2D.componentsPerAttribute).toEqual(3); expect(positionAttribute2D.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(positionAttribute2D.offsetInBytes).toBe(0); expect(positionAttribute2D.strideInBytes).not.toBeDefined(); const texCoord0Attribute = attributes[3]; expect(texCoord0Attribute.index).toEqual(3); expect(texCoord0Attribute.vertexBuffer).toBeDefined(); expect(texCoord0Attribute.componentsPerAttribute).toEqual(2); expect(texCoord0Attribute.componentDatatype).toEqual( import__696.ComponentDatatype.UNSIGNED_SHORT ); expect(texCoord0Attribute.offsetInBytes).toBe(0); expect(texCoord0Attribute.strideInBytes).not.toBeDefined(); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 position2D;", " vec3 normalMC;", " vec2 texCoord_0;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 positionWC;", " vec3 positionEC;", " vec3 normalEC;", " vec2 texCoord_0;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES, [" attributes.position2D = a_position2D;"] ); ShaderBuilderTester_default.expectHasAttributes( shaderBuilder, "in vec3 a_quantized_positionMC;", [ "in vec3 a_position2D;", "in vec2 a_quantized_normalMC;", "in vec2 a_quantized_texCoord_0;" ] ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_NORMALS", "HAS_TEXCOORD_0" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_NORMALS", "HAS_TEXCOORD_0" ]); }); }); it("processes model with matrix attributes", function() { return loadGltf(boxTexturedWithPropertyAttributes).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; const renderResources = mockRenderResources(primitive); import__696.GeometryPipelineStage.process( renderResources, primitive, scene2.frameState ); const shaderBuilder = renderResources.shaderBuilder; const attributes = renderResources.attributes; expect(attributes.length).toEqual(6); const normalAttribute = attributes[0]; expect(normalAttribute.index).toEqual(1); expect(normalAttribute.vertexBuffer).toBeDefined(); expect(normalAttribute.componentsPerAttribute).toEqual(3); expect(normalAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(normalAttribute.offsetInBytes).toBe(0); expect(normalAttribute.strideInBytes).toBe(12); const positionAttribute = attributes[1]; expect(positionAttribute.index).toEqual(0); expect(positionAttribute.vertexBuffer).toBeDefined(); expect(positionAttribute.componentsPerAttribute).toEqual(3); expect(positionAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(positionAttribute.offsetInBytes).toBe(288); expect(positionAttribute.strideInBytes).toBe(12); const texCoord0Attribute = attributes[2]; expect(texCoord0Attribute.index).toEqual(2); expect(texCoord0Attribute.vertexBuffer).toBeDefined(); expect(texCoord0Attribute.componentsPerAttribute).toEqual(2); expect(texCoord0Attribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(texCoord0Attribute.offsetInBytes).toBe(0); expect(texCoord0Attribute.strideInBytes).toBe(8); const warpMatrixAttribute = attributes[3]; expect(warpMatrixAttribute.index).toEqual(3); expect(warpMatrixAttribute.vertexBuffer).toBeDefined(); expect(warpMatrixAttribute.componentsPerAttribute).toEqual(2); expect(warpMatrixAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(warpMatrixAttribute.offsetInBytes).toBe(0); expect(warpMatrixAttribute.strideInBytes).toBe(16); const warpMatrixAttributePart2 = attributes[4]; expect(warpMatrixAttributePart2.index).toEqual(4); expect(warpMatrixAttributePart2.vertexBuffer).toBeDefined(); expect(warpMatrixAttributePart2.componentsPerAttribute).toEqual(2); expect(warpMatrixAttributePart2.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(warpMatrixAttributePart2.offsetInBytes).toBe(8); expect(warpMatrixAttributePart2.strideInBytes).toBe(16); const temperaturesAttribute = attributes[5]; expect(temperaturesAttribute.index).toEqual(5); expect(temperaturesAttribute.vertexBuffer).toBeDefined(); expect(temperaturesAttribute.componentsPerAttribute).toEqual(2); expect(temperaturesAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.UNSIGNED_SHORT ); expect(temperaturesAttribute.offsetInBytes).toBe(0); expect(temperaturesAttribute.strideInBytes).toBe(4); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 normalMC;", " vec2 texCoord_0;", " mat2 warp_matrix;", " vec2 temperatures;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [ " vec3 positionMC;", " vec3 positionWC;", " vec3 positionEC;", " vec3 normalEC;", " vec2 texCoord_0;", " mat2 warp_matrix;", " vec2 temperatures;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES, [ " attributes.positionMC = a_positionMC;", " attributes.normalMC = a_normalMC;", " attributes.texCoord_0 = a_texCoord_0;", " attributes.warp_matrix = a_warp_matrix;", " attributes.temperatures = a_temperatures;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, [ " v_texCoord_0 = attributes.texCoord_0;", " v_warp_matrix = attributes.warp_matrix;", " v_temperatures = attributes.temperatures;" ] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_FS, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS, [ " attributes.texCoord_0 = v_texCoord_0;", " attributes.warp_matrix = v_warp_matrix;", " attributes.temperatures = v_temperatures;" ] ); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "vec3 v_normalEC;", "vec2 v_texCoord_0;", "vec3 v_positionEC;", "vec3 v_positionMC;", "vec3 v_positionWC;", "mat2 v_warp_matrix;", "vec2 v_temperatures;" ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_NORMALS", "HAS_TEXCOORD_0" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_NORMALS", "HAS_TEXCOORD_0" ]); ShaderBuilderTester_default.expectHasAttributes( shaderBuilder, "in vec3 a_positionMC;", [ "in vec3 a_normalMC;", "in vec2 a_texCoord_0;", "in mat2 a_warp_matrix;", "in vec2 a_temperatures;" ] ); verifyFeatureStruct(shaderBuilder); }); }); it("processes POSITION attribute for instanced model for 2D", function() { return loadGltf(boxInstancedTranslationUrl).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const primitive = node.primitives[0]; const renderResources = mockRenderResources(primitive); renderResources.runtimeNode.node = node; renderResources.model._projectTo2D = true; import__696.GeometryPipelineStage.process( renderResources, primitive, scene2D.frameState ); const shaderBuilder = renderResources.shaderBuilder; const attributes = renderResources.attributes; expect(attributes.length).toEqual(2); const normalAttribute = attributes[1]; expect(normalAttribute.index).toEqual(1); const positionAttribute = attributes[0]; expect(positionAttribute.index).toEqual(0); expect(positionAttribute.vertexBuffer).toBeDefined(); expect(positionAttribute.componentsPerAttribute).toEqual(3); expect(positionAttribute.componentDatatype).toEqual( import__696.ComponentDatatype.FLOAT ); expect(positionAttribute.offsetInBytes).toBe(0); expect(positionAttribute.strideInBytes).toBe(12); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__696.GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS, import__696.GeometryPipelineStage.STRUCT_NAME_PROCESSED_ATTRIBUTES, [" vec3 positionMC;", " vec3 position2D;", " vec3 normalMC;"] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__696.GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES, import__696.GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES, [ " attributes.positionMC = a_positionMC;", " attributes.normalMC = a_normalMC;" ] ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_NORMALS" ]); ShaderBuilderTester_default.expectHasAttributes( shaderBuilder, "in vec3 a_positionMC;", ["in vec3 a_normalMC;"] ); verifyFeatureStruct(shaderBuilder); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/I3dmLoaderSpec.js var import__697 = __toESM(require_Cesium(), 1); describe( "Scene/Model/I3dmLoader", function() { const instancedGltfExternalUrl = "./Data/Cesium3DTiles/Instanced/InstancedGltfExternal/instancedGltfExternal.i3dm"; const instancedWithBatchTableUrl = "./Data/Cesium3DTiles/Instanced/InstancedWithBatchTable/instancedWithBatchTable.i3dm"; const instancedWithBatchTableBinaryUrl = "./Data/Cesium3DTiles/Instanced/InstancedWithBatchTableBinary/instancedWithBatchTableBinary.i3dm"; const instancedWithoutBatchTableUrl = "./Data/Cesium3DTiles/Instanced/InstancedWithoutBatchTable/instancedWithoutBatchTable.i3dm"; const instancedOrientationUrl = "./Data/Cesium3DTiles/Instanced/InstancedOrientation/instancedOrientation.i3dm"; const instancedOct32POrientationUrl = "./Data/Cesium3DTiles/Instanced/InstancedOct32POrientation/instancedOct32POrientation.i3dm"; const instancedScaleUrl = "./Data/Cesium3DTiles/Instanced/InstancedScale/instancedScale.i3dm"; const instancedScaleNonUniformUrl = "./Data/Cesium3DTiles/Instanced/InstancedScaleNonUniform/instancedScaleNonUniform.i3dm"; const instancedRTCUrl = "./Data/Cesium3DTiles/Instanced/InstancedRTC/instancedRTC.i3dm"; const instancedZeroRTCUrl = "./Data/Cesium3DTiles/Instanced/InstancedZeroRTC/instancedZeroRTC.i3dm"; const instancedQuantizedUrl = "./Data/Cesium3DTiles/Instanced/InstancedQuantized/instancedQuantized.i3dm"; const instancedQuantizedOct32POrientationUrl = "./Data/Cesium3DTiles/Instanced/InstancedQuantizedOct32POrientation/instancedQuantizedOct32POrientation.i3dm"; const instancedWithTransformUrl = "./Data/Cesium3DTiles/Instanced/InstancedWithTransform/instancedWithTransform.i3dm"; const instancedWithBatchIdsUrl = "./Data/Cesium3DTiles/Instanced/InstancedWithBatchIds/instancedWithBatchIds.i3dm"; const instancedTexturedUrl = "./Data/Cesium3DTiles/Instanced/InstancedTextured/instancedTextured.i3dm"; let scene2; const i3dmLoaders = []; beforeAll(function() { scene2 = createScene_default(); spyOn(import__697.I3dmParser, "_deprecationWarning"); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { for (let i = 0; i < i3dmLoaders.length; i++) { const loader = i3dmLoaders[i]; if (!loader.isDestroyed()) { loader.destroy(); } } i3dmLoaders.length = 0; import__697.ResourceCache.clearForSpecs(); }); async function loadI3dm(path) { const resource = import__697.Resource.createIfNeeded(path); const arrayBuffer = await import__697.Resource.fetchArrayBuffer({ url: path }); const loader = new import__697.I3dmLoader({ i3dmResource: resource, arrayBuffer }); i3dmLoaders.push(loader); await loader.load(); await waitForLoaderProcess_default(loader, scene2); return loader; } async function expectLoadError(arrayBuffer) { const resource = import__697.Resource.createIfNeeded( "http://example.com/content.i3dm" ); const loader = new import__697.I3dmLoader({ i3dmResource: resource, arrayBuffer }); i3dmLoaders.push(loader); await expectAsync( (async () => { await loader.load(); await waitForLoaderProcess_default(loader, scene2); })() ).toBeRejectedWithError(import__697.RuntimeError); } function verifyInstances(loader, expectedSemantics, instancesLength) { const components = loader.components; const structuralMetadata = components.structuralMetadata; expect(structuralMetadata).toBeDefined(); let bufferCount = 0; for (let i = 0; i < components.nodes.length; i++) { const node = components.nodes[i]; if (node.primitives.length > 0) { const instances = node.instances; expect(instances).toBeDefined(); const attributesLength = instances.attributes.length; expect(attributesLength).toEqual(expectedSemantics.length); const hasRotation = expectedSemantics.indexOf(import__697.InstanceAttributeSemantic.ROTATION) >= 0; for (let j = 0; j < attributesLength; j++) { const attribute = node.instances.attributes[j]; expect(expectedSemantics.indexOf(attribute.semantic) > -1).toEqual( true ); expect(attribute.count).toEqual(instancesLength); const isTransformAttribute = attribute.semantic === import__697.InstanceAttributeSemantic.TRANSLATION || attribute.semantic === import__697.InstanceAttributeSemantic.ROTATION || attribute.semantic === import__697.InstanceAttributeSemantic.SCALE; const isTranslationAttribute = attribute.semantic === import__697.InstanceAttributeSemantic.TRANSLATION; if (hasRotation && isTransformAttribute) { expect(attribute.typedArray).toBeDefined(); expect(attribute.buffer).toBeUndefined(); } else if (isTranslationAttribute) { expect(attribute.typedArray).toBeDefined(); expect(attribute.buffer).toBeDefined(); bufferCount++; } else { expect(attribute.typedArray).toBeUndefined(); expect(attribute.buffer).toBeDefined(); bufferCount++; } } } } expect(loader._buffers.length).toEqual(bufferCount); } it("releases array buffer when finished loading", function() { return loadI3dm(instancedWithBatchTableUrl).then(function(loader) { expect(loader.components).toBeDefined(); expect(loader._arrayBuffer).not.toBeDefined(); }); }); it("loads InstancedGltfExternalUrl", function() { return loadI3dm(instancedGltfExternalUrl).then(function(loader) { verifyInstances( loader, [ import__697.InstanceAttributeSemantic.TRANSLATION, import__697.InstanceAttributeSemantic.ROTATION, import__697.InstanceAttributeSemantic.FEATURE_ID ], 25 ); }); }); it("loads InstancedWithBatchTableUrl", function() { return loadI3dm(instancedWithBatchTableUrl).then(function(loader) { verifyInstances( loader, [ import__697.InstanceAttributeSemantic.TRANSLATION, import__697.InstanceAttributeSemantic.ROTATION, import__697.InstanceAttributeSemantic.FEATURE_ID ], 25 ); }); }); it("loads InstancedWithBatchTableBinaryUrl", function() { return loadI3dm(instancedWithBatchTableBinaryUrl).then(function(loader) { verifyInstances( loader, [ import__697.InstanceAttributeSemantic.TRANSLATION, import__697.InstanceAttributeSemantic.ROTATION, import__697.InstanceAttributeSemantic.FEATURE_ID ], 25 ); }); }); it("loads InstancedWithoutBatchTableUrl", function() { return loadI3dm(instancedWithoutBatchTableUrl).then(function(loader) { verifyInstances( loader, [ import__697.InstanceAttributeSemantic.TRANSLATION, import__697.InstanceAttributeSemantic.ROTATION, import__697.InstanceAttributeSemantic.FEATURE_ID ], 25 ); }); }); it("loads InstancedOrientationUrl", function() { return loadI3dm(instancedOrientationUrl).then(function(loader) { verifyInstances( loader, [ import__697.InstanceAttributeSemantic.TRANSLATION, import__697.InstanceAttributeSemantic.ROTATION, import__697.InstanceAttributeSemantic.FEATURE_ID ], 25 ); }); }); it("loads InstancedOct32POrientationUrl", function() { return loadI3dm(instancedOct32POrientationUrl).then(function(loader) { verifyInstances( loader, [ import__697.InstanceAttributeSemantic.TRANSLATION, import__697.InstanceAttributeSemantic.ROTATION, import__697.InstanceAttributeSemantic.FEATURE_ID ], 25 ); }); }); it("loads InstancedScaleUrl", function() { return loadI3dm(instancedScaleUrl).then(function(loader) { verifyInstances( loader, [ import__697.InstanceAttributeSemantic.TRANSLATION, import__697.InstanceAttributeSemantic.ROTATION, import__697.InstanceAttributeSemantic.SCALE, import__697.InstanceAttributeSemantic.FEATURE_ID ], 25 ); }); }); it("loads InstancedScaleNonUniformUrl", function() { return loadI3dm(instancedScaleNonUniformUrl).then(function(loader) { verifyInstances( loader, [ import__697.InstanceAttributeSemantic.TRANSLATION, import__697.InstanceAttributeSemantic.ROTATION, import__697.InstanceAttributeSemantic.SCALE, import__697.InstanceAttributeSemantic.FEATURE_ID ], 25 ); }); }); it("loads InstancedRTCUrl", function() { return loadI3dm(instancedRTCUrl).then(function(loader) { verifyInstances( loader, [ import__697.InstanceAttributeSemantic.TRANSLATION, import__697.InstanceAttributeSemantic.ROTATION, import__697.InstanceAttributeSemantic.FEATURE_ID ], 25 ); const transform = loader.components.transform; expect(transform).toEqualEpsilon(new import__697.Matrix4( 1, 0, 0, 1.2150138340490046e6, 0, 1, 0, -473631675897742e-8, 0, 0, 1, 4.0816084380407534e6, 0, 0, 0, 1 ), import__697.Math.EPSILON8); }); }); it("loads InstancedZeroRTCUrl", function() { return loadI3dm(instancedZeroRTCUrl).then(function(loader) { verifyInstances( loader, [ import__697.InstanceAttributeSemantic.TRANSLATION, import__697.InstanceAttributeSemantic.ROTATION, import__697.InstanceAttributeSemantic.FEATURE_ID ], 25 ); const transform = loader.components.transform; expect(transform).toEqualEpsilon(new import__697.Matrix4( 1, 0, 0, 12150138125e-4, 0, 1, 0, -473631675e-2, 0, 0, 1, 40816085e-1, 0, 0, 0, 1 ), import__697.Math.EPSILON8); }); }); it("loads InstancedQuantizedUrl", function() { return loadI3dm(instancedQuantizedUrl).then(function(loader) { verifyInstances( loader, [ import__697.InstanceAttributeSemantic.TRANSLATION, import__697.InstanceAttributeSemantic.ROTATION, import__697.InstanceAttributeSemantic.FEATURE_ID ], 25 ); const transform = loader.components.transform; expect(transform).toEqualEpsilon(new import__697.Matrix4( 1, 0, 0, 12150138125e-4, 0, 1, 0, -473631675e-2, 0, 0, 1, 40816085e-1, 0, 0, 0, 1 ), import__697.Math.EPSILON8); }); }); it("loads InstancedQuantizedOct32POrientationUrl", function() { return loadI3dm(instancedQuantizedOct32POrientationUrl).then(function(loader) { verifyInstances( loader, [ import__697.InstanceAttributeSemantic.TRANSLATION, import__697.InstanceAttributeSemantic.ROTATION, import__697.InstanceAttributeSemantic.FEATURE_ID ], 25 ); }); }); it("loads InstancedWithTransformUrl", function() { return loadI3dm(instancedWithTransformUrl).then(function(loader) { verifyInstances( loader, [ import__697.InstanceAttributeSemantic.TRANSLATION, import__697.InstanceAttributeSemantic.FEATURE_ID ], 25 ); }); }); it("loads InstancedWithBatchIdsUrl", function() { return loadI3dm(instancedWithBatchIdsUrl).then(function(loader) { verifyInstances( loader, [ import__697.InstanceAttributeSemantic.TRANSLATION, import__697.InstanceAttributeSemantic.ROTATION, import__697.InstanceAttributeSemantic.FEATURE_ID ], 25 ); }); }); it("loads InstancedTexturedUrl", function() { return loadI3dm(instancedTexturedUrl).then(function(loader) { verifyInstances( loader, [ import__697.InstanceAttributeSemantic.TRANSLATION, import__697.InstanceAttributeSemantic.ROTATION, import__697.InstanceAttributeSemantic.FEATURE_ID ], 25 ); }); }); it("destroys buffers when unloaded", function() { return loadI3dm(instancedGltfExternalUrl).then(function(loader) { const buffers = loader._buffers; expect(buffers.length).toBe(1); const buffer = buffers[0]; loader.destroy(); expect(buffer.isDestroyed()).toBe(true); }); }); it("throws with invalid format", async function() { const arrayBuffer = Cesium3DTilesTester_default.generateInstancedTileBuffer({ gltfFormat: 2 }); await expectLoadError(arrayBuffer); }); it("throws with invalid version", async function() { const arrayBuffer = Cesium3DTilesTester_default.generateInstancedTileBuffer({ version: 2 }); await expectLoadError(arrayBuffer); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/ImageBasedLightingPipelineStageSpec.js var import__698 = __toESM(require_Cesium(), 1); describe("Scene/Model/ImageBasedLightingPipelineStage", function() { const mockFrameState = { context: { floatingPointTexture: true, colorBufferFloat: true } }; it("configures the render resources for default image-based lighting", function() { const imageBasedLighting = new import__698.ImageBasedLighting(); const mockModel = { imageBasedLighting, _iblReferenceFrameMatrix: import__698.Matrix3.clone(import__698.Matrix3.IDENTITY) }; const renderResources = { shaderBuilder: new import__698.ShaderBuilder(), uniformMap: {}, model: mockModel }; const shaderBuilder = renderResources.shaderBuilder; import__698.ImageBasedLightingPipelineStage.process( renderResources, mockModel, mockFrameState ); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "USE_IBL_LIGHTING", "USE_SUN_LUMINANCE" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform vec2 model_iblFactor;", "uniform mat3 model_iblReferenceFrameMatrix;", "uniform float model_luminanceAtZenith;" ]); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__698._shadersImageBasedLightingStageFS ]); const uniformMap = renderResources.uniformMap; expect( import__698.Cartesian2.equals( uniformMap.model_iblFactor(), imageBasedLighting.imageBasedLightingFactor ) ).toBe(true); expect( import__698.Matrix3.equals( uniformMap.model_iblReferenceFrameMatrix(), mockModel._iblReferenceFrameMatrix ) ).toBe(true); expect(uniformMap.model_luminanceAtZenith()).toEqual( imageBasedLighting.luminanceAtZenith ); }); const testCoefficients = [ new import__698.Cartesian3(1, 1, 1), new import__698.Cartesian3(2, 2, 2), new import__698.Cartesian3(3, 3, 3), new import__698.Cartesian3(4, 4, 4), new import__698.Cartesian3(5, 5, 5), new import__698.Cartesian3(6, 6, 6), new import__698.Cartesian3(7, 7, 7), new import__698.Cartesian3(8, 8, 8), new import__698.Cartesian3(9, 9, 9) ]; it("configures the render resources for spherical harmonics", function() { const imageBasedLighting = new import__698.ImageBasedLighting({ sphericalHarmonicCoefficients: testCoefficients }); imageBasedLighting.luminanceAtZenith = void 0; const mockModel = { imageBasedLighting, _iblReferenceFrameMatrix: import__698.Matrix3.clone(import__698.Matrix3.IDENTITY) }; const renderResources = { shaderBuilder: new import__698.ShaderBuilder(), uniformMap: {}, model: mockModel }; const shaderBuilder = renderResources.shaderBuilder; import__698.ImageBasedLightingPipelineStage.process( renderResources, mockModel, mockFrameState ); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "USE_IBL_LIGHTING", "DIFFUSE_IBL", "CUSTOM_SPHERICAL_HARMONICS" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform vec2 model_iblFactor;", "uniform mat3 model_iblReferenceFrameMatrix;", "uniform vec3 model_sphericalHarmonicCoefficients[9];" ]); const uniformMap = renderResources.uniformMap; expect( import__698.Cartesian2.equals( uniformMap.model_iblFactor(), imageBasedLighting.imageBasedLightingFactor ) ).toBe(true); expect( import__698.Matrix3.equals( uniformMap.model_iblReferenceFrameMatrix(), mockModel._iblReferenceFrameMatrix ) ).toBe(true); expect(uniformMap.model_sphericalHarmonicCoefficients()).toBe( testCoefficients ); }); it("configures the render resources for specular environment maps", function() { const mockAtlas = { texture: { dimensions: {} }, maximumMipmapLevel: 0, ready: true }; const imageBasedLighting = new import__698.ImageBasedLighting({ specularEnvironmentMaps: "example.ktx2" }); imageBasedLighting.luminanceAtZenith = void 0; imageBasedLighting._specularEnvironmentMapAtlas = mockAtlas; const mockModel = { imageBasedLighting, _iblReferenceFrameMatrix: import__698.Matrix3.clone(import__698.Matrix3.IDENTITY) }; const renderResources = { shaderBuilder: new import__698.ShaderBuilder(), uniformMap: {}, model: mockModel }; const shaderBuilder = renderResources.shaderBuilder; import__698.ImageBasedLightingPipelineStage.process( renderResources, mockModel, mockFrameState ); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "USE_IBL_LIGHTING", "SPECULAR_IBL", "CUSTOM_SPECULAR_IBL" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform vec2 model_iblFactor;", "uniform mat3 model_iblReferenceFrameMatrix;", "uniform sampler2D model_specularEnvironmentMaps;", "uniform vec2 model_specularEnvironmentMapsSize;", "uniform float model_specularEnvironmentMapsMaximumLOD;" ]); const uniformMap = renderResources.uniformMap; expect( import__698.Cartesian2.equals( uniformMap.model_iblFactor(), imageBasedLighting.imageBasedLightingFactor ) ).toBe(true); expect( import__698.Matrix3.equals( uniformMap.model_iblReferenceFrameMatrix(), mockModel._iblReferenceFrameMatrix ) ).toBe(true); expect(uniformMap.model_specularEnvironmentMaps()).toBeDefined(); expect(uniformMap.model_specularEnvironmentMapsSize()).toBeDefined(); expect(uniformMap.model_specularEnvironmentMapsMaximumLOD()).toBeDefined(); }); }); // packages/engine/Specs/Scene/Model/InstancingPipelineStageSpec.js var import__699 = __toESM(require_Cesium(), 1); describe( "Scene/Model/InstancingPipelineStage", function() { const webglStub = !!window.webglStub; const scratchMatrix4 = new import__699.Matrix4(); const boxInstanced = "./Data/Models/glTF-2.0/BoxInstanced/glTF/box-instanced.gltf"; const boxInstancedTranslation = "./Data/Models/glTF-2.0/BoxInstancedTranslation/glTF/box-instanced-translation.gltf"; const boxInstancedTranslationMinMax = "./Data/Models/glTF-2.0/BoxInstancedTranslationWithMinMax/glTF/box-instanced-translation-min-max.gltf"; const instancedWithNormalizedRotation = "./Data/Models/glTF-2.0/InstancedWithNormalizedRotation/glTF/InstancedWithNormalizedRotation.gltf"; const i3dmInstancedOrientation = "./Data/Cesium3DTiles/Instanced/InstancedOrientation/instancedOrientation.i3dm"; let scene2; let scene2D; const gltfLoaders = []; beforeAll(function() { scene2 = createScene_default(); scene2.renderForSpecs(); scene2D = createScene_default(); scene2D.morphTo2D(0); scene2D.renderForSpecs(); }); afterAll(function() { scene2 = createScene_default(); scene2D.destroyForSpecs(); }); afterEach(function() { const gltfLoadersLength = gltfLoaders.length; for (let i = 0; i < gltfLoadersLength; ++i) { const gltfLoader = gltfLoaders[i]; if (!gltfLoader.isDestroyed()) { gltfLoader.destroy(); } } gltfLoaders.length = 0; import__699.ResourceCache.clearForSpecs(); }); function mockRenderResources(node) { return { attributeIndex: 1, attributes: [], instancingTranslationMax: void 0, instancingTranslationMin: void 0, shaderBuilder: new import__699.ShaderBuilder(), model: { _modelResources: [], _pipelineResources: [], statistics: new import__699.ModelStatistics() }, runtimeNode: { node } }; } function mockRenderResourcesFor2D(node, components) { return { attributeIndex: 1, attributes: [], instancingTranslationMax: void 0, instancingTranslationMin: void 0, shaderBuilder: new import__699.ShaderBuilder(), model: { _modelResources: [], _pipelineResources: [], statistics: new import__699.ModelStatistics(), _projectTo2D: true, sceneGraph: { components, computedModelMatrix: import__699.Matrix4.IDENTITY, axisCorrectionMatrix: import__699.Matrix4.IDENTITY } }, runtimeNode: { computedTransform: import__699.Matrix4.IDENTITY, node } }; } function getOptions(gltfPath, options) { const resource = new import__699.Resource({ url: gltfPath }); return (0, import__699.combine)(options, { gltfResource: resource, incrementallyLoadTexture: false }); } function getI3dmOptions(gltfPath, options) { const resource = new import__699.Resource({ url: gltfPath }); return (0, import__699.combine)(options, { i3dmResource: resource, incrementallyLoadTexture: false }); } async function loadGltf(gltfPath, options) { const gltfLoader = new import__699.GltfLoader(getOptions(gltfPath, options)); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, scene2); return gltfLoader; } async function loadI3dm(i3dmPath) { const arrayBuffer = await import__699.Resource.fetchArrayBuffer(i3dmPath); const i3dmLoader = new import__699.I3dmLoader( getI3dmOptions(i3dmPath, { arrayBuffer }) ); gltfLoaders.push(i3dmLoader); await i3dmLoader.load(); await waitForLoaderProcess_default(i3dmLoader, scene2); return i3dmLoader; } function verifyTypedArraysUnloaded(instances) { const attributes = instances.attributes; const length2 = attributes.length; for (let i = 0; i < length2; i++) { const attribute = attributes[i]; expect(attribute.typedArray).toBeUndefined(); } } it("computes instancing TRANSLATION min and max from typed arrays", function() { return loadGltf(boxInstanced).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const renderResources = mockRenderResources(node); import__699.InstancingPipelineStage.process( renderResources, node, scene2.frameState ); expect(renderResources.attributes.length).toBe(4); const runtimeNode = renderResources.runtimeNode; expect(runtimeNode.instancingTranslationMin).toEqual( new import__699.Cartesian3(-2, -2, 0) ); expect(runtimeNode.instancingTranslationMax).toEqual( new import__699.Cartesian3(2, 2, 0) ); import__699.InstancingPipelineStage.process( renderResources, node, scene2.frameState ); expect(runtimeNode.instancingTranslationMin).toEqual( new import__699.Cartesian3(-2, -2, 0) ); expect(runtimeNode.instancingTranslationMax).toEqual( new import__699.Cartesian3(2, 2, 0) ); }); }); it("sets instancing TRANSLATION min and max from attributes", function() { return loadGltf(boxInstancedTranslationMinMax).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const renderResources = mockRenderResources(node); import__699.InstancingPipelineStage.process( renderResources, node, scene2.frameState ); expect(renderResources.attributes.length).toBe(1); const runtimeNode = renderResources.runtimeNode; expect(runtimeNode.instancingTranslationMax).toEqual( new import__699.Cartesian3(2, 2, 0) ); expect(runtimeNode.instancingTranslationMin).toEqual( new import__699.Cartesian3(-2, -2, 0) ); import__699.InstancingPipelineStage.process( renderResources, node, scene2.frameState ); expect(runtimeNode.instancingTranslationMin).toEqual( new import__699.Cartesian3(-2, -2, 0) ); expect(runtimeNode.instancingTranslationMax).toEqual( new import__699.Cartesian3(2, 2, 0) ); }); }); it("creates instancing matrices vertex attributes when ROTATION is present", function() { return loadGltf(boxInstanced).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const instances = node.instances; const renderResources = mockRenderResources(node); const runtimeNode = renderResources.runtimeNode; scene2.renderForSpecs(); import__699.InstancingPipelineStage.process( renderResources, node, scene2.frameState ); expect(renderResources.attributes.length).toBe(4); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_INSTANCING", "HAS_INSTANCE_MATRICES" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_INSTANCING", "HAS_INSTANCE_MATRICES" ]); ShaderBuilderTester_default.expectHasAttributes(shaderBuilder, void 0, [ "in vec4 a_instancingTransformRow0;", "in vec4 a_instancingTransformRow1;", "in vec4 a_instancingTransformRow2;", "in float a_instanceFeatureId_0;" ]); expect(runtimeNode.instancingTransformsBuffer).toBeDefined(); verifyTypedArraysUnloaded(instances); expect(renderResources.model._modelResources.length).toEqual(1); expect(renderResources.model.statistics.geometryByteLength).toBe(0); }); }); it("creates instancing matrices vertex attributes for 2D", function() { return loadGltf(boxInstanced, { loadAttributesFor2D: true }).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const renderResources = mockRenderResourcesFor2D(node, components); scene2D.renderForSpecs(); import__699.InstancingPipelineStage.process( renderResources, node, scene2D.frameState ); expect(renderResources.attributes.length).toBe(7); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_INSTANCING", "HAS_INSTANCE_MATRICES", "USE_2D_INSTANCING" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_INSTANCING", "HAS_INSTANCE_MATRICES" ]); ShaderBuilderTester_default.expectHasAttributes(shaderBuilder, void 0, [ "in vec4 a_instancingTransformRow0;", "in vec4 a_instancingTransformRow1;", "in vec4 a_instancingTransformRow2;", "in vec4 a_instancingTransform2DRow0;", "in vec4 a_instancingTransform2DRow1;", "in vec4 a_instancingTransform2DRow2;", "in float a_instanceFeatureId_0;" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform mat4 u_modelView2D;" ]); const runtimeNode = renderResources.runtimeNode; expect(runtimeNode.instancingTransformsBuffer).toBeDefined(); expect(runtimeNode.instancingTransformsBuffer2D).toBeDefined(); expect(runtimeNode.instancingReferencePoint2D).toBeDefined(); const translationMatrix = import__699.Matrix4.fromTranslation( runtimeNode.instancingReferencePoint2D, scratchMatrix4 ); const expectedMatrix = import__699.Matrix4.multiplyTransformation( scene2D.context.uniformState.view, translationMatrix, scratchMatrix4 ); const uniformMap = renderResources.uniformMap; expect(uniformMap.u_modelView2D()).toEqual(expectedMatrix); expect(renderResources.model._pipelineResources.length).toEqual(0); expect(renderResources.model._modelResources.length).toEqual(2); expect(renderResources.model.statistics.geometryByteLength).toBe(0); }); }); it("correctly creates transform matrices", function() { return loadGltf(boxInstanced).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const renderResources = mockRenderResources(node); const expectedTransformsTypedArray = new Float32Array([ 0.5999999642372131, 0, 0, -2, 0, 0.4949747323989868, -0.7071067094802856, 2, 0, 0.49497467279434204, 0.7071067690849304, 0, 0.7071068286895752, 4174155421310388e-23, 0.3535534143447876, -2, 0.5, 0.7071068286895752, -0.2500000298023224, -2, -0.5000000596046448, 0.7071068286895752, 0.25, 0, 0.375, -0.10000001639127731, 0.3535534143447876, 2, 0.6401650905609131, 0.029289301484823227, -0.2500000298023224, -2, 0.10983504354953766, 0.1707106977701187, 0.25, 0, 0.4898979365825653, -0.3674234449863434, 0.44999992847442627, 2, 0.5277916193008423, 0.028420301154255867, -0.6749999523162842, 2, 0.3484765887260437, 0.4734894633293152, 0.3897113800048828, 0 ]); const transforms = import__699.InstancingPipelineStage._getInstanceTransformsAsMatrices( node.instances, node.instances.attributes[0].count, renderResources ); const transformsTypedArray = import__699.InstancingPipelineStage._transformsToTypedArray( transforms ); expect(transformsTypedArray.length).toEqual( expectedTransformsTypedArray.length ); for (let i = 0; i < expectedTransformsTypedArray.length; i++) { expect(transformsTypedArray[i]).toEqualEpsilon( expectedTransformsTypedArray[i], import__699.Math.EPSILON10 ); } }); }); it("dequantizes normalized rotations", function() { if (webglStub) { return; } return loadGltf(instancedWithNormalizedRotation).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const renderResources = mockRenderResources(node); const secondMatrixComponents = [ 1.1007905724243354, 0.07140440309598281, -0.1331359457080602, 0, -0.04344372372420601, 1.0874251248973055, 0.22401538735190446, 0, 0.1446942006095891, -0.21672946758564085, 1.0801183172918447, 0, 1.1111111640930176, 1.1111111640930176, 1.1111111640930176, 1 ]; const expectedTransforms = [ import__699.Matrix4.IDENTITY, import__699.Matrix4.unpack(secondMatrixComponents) ]; const transforms = import__699.InstancingPipelineStage._getInstanceTransformsAsMatrices( node.instances, node.instances.attributes[0].count, renderResources ); expect(transforms.length).toBe(10); const length2 = expectedTransforms.length; for (let i = 0; i < length2; i++) { expect(transforms[i]).toEqualEpsilon( expectedTransforms[i], import__699.Math.EPSILON10 ); } }); }); it("creates TRANSLATION vertex attributes with min/max present", function() { return loadGltf(boxInstancedTranslationMinMax).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const renderResources = mockRenderResources(node); scene2.renderForSpecs(); import__699.InstancingPipelineStage.process( renderResources, node, scene2.frameState ); expect(renderResources.attributes.length).toBe(1); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_INSTANCING", "HAS_INSTANCE_TRANSLATION" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_INSTANCING", "HAS_INSTANCE_TRANSLATION" ]); ShaderBuilderTester_default.expectHasAttributes(shaderBuilder, void 0, [ "in vec3 a_instanceTranslation;" ]); expect(renderResources.model._pipelineResources.length).toEqual(0); expect(renderResources.model._modelResources.length).toEqual(0); expect(renderResources.model.statistics.geometryByteLength).toBe(0); }); }); it("creates TRANSLATION vertex attributes without min/max present", function() { return loadGltf(boxInstancedTranslation).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const renderResources = mockRenderResources(node); const instances = node.instances; scene2.renderForSpecs(); import__699.InstancingPipelineStage.process( renderResources, node, scene2.frameState ); expect(renderResources.attributes.length).toBe(1); const translationAttribute = import__699.ModelUtility.getAttributeBySemantic( instances, import__699.InstanceAttributeSemantic.TRANSLATION ); expect(translationAttribute.typedArray).toBeUndefined(); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_INSTANCING", "HAS_INSTANCE_TRANSLATION" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_INSTANCING", "HAS_INSTANCE_TRANSLATION" ]); ShaderBuilderTester_default.expectHasAttributes(shaderBuilder, void 0, [ "in vec3 a_instanceTranslation;" ]); expect(renderResources.model._pipelineResources.length).toEqual(0); expect(renderResources.model._modelResources.length).toEqual(0); expect(renderResources.model.statistics.geometryByteLength).toBe(0); }); }); it("creates TRANSLATION vertex attributes for 2D", function() { const renderResources = mockRenderResourcesFor2D(); const model = renderResources.model; const runtimeNode = renderResources.runtimeNode; return loadGltf(boxInstancedTranslationMinMax, { loadAttributesFor2D: true }).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const instances = node.instances; model.sceneGraph.components = components; runtimeNode.node = node; scene2D.renderForSpecs(); import__699.InstancingPipelineStage.process( renderResources, node, scene2D.frameState ); expect(renderResources.attributes.length).toBe(2); const translationAttribute = import__699.ModelUtility.getAttributeBySemantic( instances, import__699.InstanceAttributeSemantic.TRANSLATION ); expect(translationAttribute.typedArray).toBeUndefined(); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_INSTANCING", "HAS_INSTANCE_TRANSLATION", "USE_2D_INSTANCING" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_INSTANCING", "HAS_INSTANCE_TRANSLATION" ]); ShaderBuilderTester_default.expectHasAttributes(shaderBuilder, void 0, [ "in vec3 a_instanceTranslation;", "in vec3 a_instanceTranslation2D;" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform mat4 u_modelView2D;" ]); expect(runtimeNode.instancingReferencePoint2D).toBeDefined(); const translationMatrix = import__699.Matrix4.fromTranslation( runtimeNode.instancingReferencePoint2D, scratchMatrix4 ); const expectedMatrix = import__699.Matrix4.multiplyTransformation( scene2D.context.uniformState.view, translationMatrix, scratchMatrix4 ); const uniformMap = renderResources.uniformMap; expect(uniformMap.u_modelView2D()).toEqual(expectedMatrix); expect(runtimeNode.instancingTranslationBuffer2D).toBeDefined(); expect(model._pipelineResources.length).toEqual(0); expect(model._modelResources.length).toEqual(1); expect(model.statistics.geometryByteLength).toBe(0); }); }); it("adds uniforms for legacy instancing path", function() { const renderResources = { attributeIndex: 1, attributes: [], instancingTranslationMax: void 0, instancingTranslationMin: void 0, shaderBuilder: new import__699.ShaderBuilder(), model: { _pipelineResources: [], _modelResources: [], statistics: new import__699.ModelStatistics(), modelMatrix: import__699.Matrix4.fromUniformScale(2), sceneGraph: { axisCorrectionMatrix: import__699.ModelUtility.getAxisCorrectionMatrix( import__699.Axis.Y, import__699.Axis.Z, new import__699.Matrix4() ) } }, uniformMap: {}, runtimeNode: { computedTransform: import__699.Matrix4.fromTranslation( new import__699.Cartesian3(0, 2, 0) ) } }; return loadI3dm(i3dmInstancedOrientation, { i3dmResource: import__699.Resource.createIfNeeded(i3dmInstancedOrientation) }).then(function(i3dmLoader) { const components = i3dmLoader.components; const node = components.nodes[0]; const shaderBuilder = renderResources.shaderBuilder; const runtimeNode = renderResources.runtimeNode; renderResources.model.sceneGraph.components = components; scene2.renderForSpecs(); import__699.InstancingPipelineStage.process( renderResources, node, scene2.frameState ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_INSTANCING", "HAS_INSTANCE_MATRICES", "USE_LEGACY_INSTANCING" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform mat4 u_instance_modifiedModelView;", "uniform mat4 u_instance_nodeTransform;" ]); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__699._shadersInstancingStageCommon, import__699._shadersLegacyInstancingStageVS ]); const model = renderResources.model; const sceneGraph = model.sceneGraph; const view = scene2.frameState.context.uniformState.view3D; const modelMatrix = model.modelMatrix; const rtcTransform = components.transform; let expectedModelView = import__699.Matrix4.multiplyTransformation( view, modelMatrix, new import__699.Matrix4() ); expectedModelView = import__699.Matrix4.multiplyTransformation( expectedModelView, rtcTransform, expectedModelView ); const uniformMap = renderResources.uniformMap; expect(uniformMap.u_instance_modifiedModelView()).toEqualEpsilon( expectedModelView, import__699.Math.EPSILON8 ); const axisCorrection = sceneGraph.axisCorrectionMatrix; const computedTransform = runtimeNode.computedTransform; const expectedNodeTransform = import__699.Matrix4.multiplyTransformation( axisCorrection, computedTransform, new import__699.Matrix4() ); expect(uniformMap.u_instance_nodeTransform()).toEqualEpsilon( expectedNodeTransform, import__699.Math.EPSILON8 ); expect(renderResources.model.statistics.geometryByteLength).toBe(0); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/LightingPipelineStageSpec.js var import__700 = __toESM(require_Cesium(), 1); describe("Scene/Model/LightingPipelineStage", function() { const mockPrimitive = {}; const mockModel = {}; const optionsUnlit = new import__700.ModelLightingOptions(); optionsUnlit.lightingModel = import__700.LightingModel.UNLIT; it("supports light color", function() { const mockModelWithLightColor = { lightColor: new import__700.Cartesian3(1, 0, 0) }; const shaderBuilder = new import__700.ShaderBuilder(); const renderResources = { model: mockModelWithLightColor, shaderBuilder, lightingOptions: optionsUnlit, uniformMap: {} }; import__700.LightingPipelineStage.process(renderResources, mockPrimitive); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "USE_CUSTOM_LIGHT_COLOR", "LIGHTING_UNLIT" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform vec3 model_lightColorHdr;" ]); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__700._shadersLightingStageFS ]); expect(renderResources.uniformMap.model_lightColorHdr).toBeDefined(); }); it("supports unlit lighting", function() { const shaderBuilder = new import__700.ShaderBuilder(); const renderResources = { model: mockModel, shaderBuilder, lightingOptions: optionsUnlit }; import__700.LightingPipelineStage.process(renderResources, mockPrimitive); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "LIGHTING_UNLIT" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__700._shadersLightingStageFS ]); }); it("supports PBR lighting", function() { const optionsPbr = new import__700.ModelLightingOptions(); optionsPbr.lightingModel = import__700.LightingModel.PBR; const shaderBuilder = new import__700.ShaderBuilder(); const renderResources = { model: mockModel, shaderBuilder, lightingOptions: optionsPbr }; import__700.LightingPipelineStage.process(renderResources, mockPrimitive); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "LIGHTING_PBR" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__700._shadersLightingStageFS ]); }); }); // packages/engine/Specs/Scene/Model/MaterialPipelineStageSpec.js var import__701 = __toESM(require_Cesium(), 1); describe( "Scene/Model/MaterialPipelineStage", function() { let scene2; const gltfLoaders = []; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); const mockFrameState = { context: { defaultTexture: {}, defaultNormalTexture: {}, defaultEmissiveTexture: {} } }; afterEach(function() { const gltfLoadersLength = gltfLoaders.length; for (let i = 0; i < gltfLoadersLength; ++i) { const gltfLoader = gltfLoaders[i]; if (!gltfLoader.isDestroyed()) { gltfLoader.destroy(); } } gltfLoaders.length = 0; import__701.ResourceCache.clearForSpecs(); }); function getOptions(gltfPath, options) { const resource = new import__701.Resource({ url: gltfPath }); return (0, import__701.combine)(options, { gltfResource: resource, incrementallyLoadTextures: false // Default to false if not supplied }); } async function loadGltf(gltfPath, options) { const gltfLoader = new import__701.GltfLoader(getOptions(gltfPath, options)); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, scene2); return gltfLoader; } const boomBox = "./Data/Models/glTF-2.0/BoomBox/glTF/BoomBox.gltf"; const boomBoxSpecularGlossiness = "./Data/Models/glTF-2.0/BoomBox/glTF-pbrSpecularGlossiness/BoomBox.gltf"; const boxUnlit = "./Data/Models/glTF-2.0/UnlitTest/glTF/UnlitTest.gltf"; const boxNoNormals = "./Data/Models/glTF-2.0/BoxNoNormals/glTF/BoxNoNormals.gltf"; const triangle = "./Data/Models/glTF-2.0/Triangle/glTF/Triangle.gltf"; const twoSidedPlane = "./Data/Models/glTF-2.0/TwoSidedPlane/glTF/TwoSidedPlane.gltf"; function expectUniformMap(uniformMap, expected) { for (const key in expected) { if (expected.hasOwnProperty(key)) { const expectedValue = expected[key]; const uniformFunction = uniformMap[key]; expect(uniformFunction).toBeDefined(); expect(uniformFunction()).toEqual(expectedValue); } } } function mockRenderResources(classificationType) { return { shaderBuilder: new import__701.ShaderBuilder(), uniformMap: {}, lightingOptions: new import__701.ModelLightingOptions(), alphaOptions: new import__701.ModelAlphaOptions(), renderStateOptions: import__701.RenderState.getState(import__701.RenderState.fromCache()), model: { statistics: new import__701.ModelStatistics(), classificationType } }; } it("processes default material", function() { return loadGltf(triangle).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const renderResources = mockRenderResources(); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "USE_METALLIC_ROUGHNESS" ]); const expectedUniforms = {}; expectUniformMap(uniformMap, expectedUniforms); }); }); it("adds material and metallic roughness uniforms", function() { return loadGltf(boomBox).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const renderResources = mockRenderResources(); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform sampler2D u_baseColorTexture;", "uniform sampler2D u_emissiveTexture;", "uniform sampler2D u_metallicRoughnessTexture;", "uniform sampler2D u_normalTexture;", "uniform sampler2D u_occlusionTexture;", "uniform vec3 u_emissiveFactor;" ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_BASE_COLOR_TEXTURE", "HAS_EMISSIVE_FACTOR", "HAS_EMISSIVE_TEXTURE", "HAS_METALLIC_ROUGHNESS_TEXTURE", "HAS_NORMAL_TEXTURE", "HAS_OCCLUSION_TEXTURE", "TEXCOORD_BASE_COLOR v_texCoord_0", "TEXCOORD_EMISSIVE v_texCoord_0", "TEXCOORD_METALLIC_ROUGHNESS v_texCoord_0", "TEXCOORD_NORMAL v_texCoord_0", "TEXCOORD_OCCLUSION v_texCoord_0", "USE_METALLIC_ROUGHNESS" ]); const metallicRoughness = primitive.material.metallicRoughness; const material = primitive.material; const expectedUniforms = { u_emissiveTexture: material.emissiveTexture.texture, u_emissiveFactor: material.emissiveFactor, u_normalTexture: material.normalTexture.texture, u_occlusionTexture: material.occlusionTexture.texture, u_baseColorTexture: metallicRoughness.baseColorTexture.texture, u_metallicRoughnessTexture: metallicRoughness.metallicRoughnessTexture.texture }; expectUniformMap(uniformMap, expectedUniforms); }); }); it("adds metallic roughness uniforms without defaults", function() { return loadGltf(boomBox).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const metallicRoughness = primitive.material.metallicRoughness; metallicRoughness.baseColorFactor = new import__701.Cartesian4(0.5, 0.5, 0.5, 0.5); metallicRoughness.metallicFactor = 0.5; metallicRoughness.roughnessFactor = 0.5; const renderResources = mockRenderResources(); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform float u_metallicFactor;", "uniform float u_roughnessFactor;", "uniform sampler2D u_baseColorTexture;", "uniform sampler2D u_emissiveTexture;", "uniform sampler2D u_metallicRoughnessTexture;", "uniform sampler2D u_normalTexture;", "uniform sampler2D u_occlusionTexture;", "uniform vec3 u_emissiveFactor;", "uniform vec4 u_baseColorFactor;" ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_BASE_COLOR_FACTOR", "HAS_BASE_COLOR_TEXTURE", "HAS_EMISSIVE_FACTOR", "HAS_EMISSIVE_TEXTURE", "HAS_METALLIC_FACTOR", "HAS_METALLIC_ROUGHNESS_TEXTURE", "HAS_NORMAL_TEXTURE", "HAS_OCCLUSION_TEXTURE", "HAS_ROUGHNESS_FACTOR", "TEXCOORD_BASE_COLOR v_texCoord_0", "TEXCOORD_EMISSIVE v_texCoord_0", "TEXCOORD_METALLIC_ROUGHNESS v_texCoord_0", "TEXCOORD_NORMAL v_texCoord_0", "TEXCOORD_OCCLUSION v_texCoord_0", "USE_METALLIC_ROUGHNESS" ]); const expectedUniforms = { u_baseColorTexture: metallicRoughness.baseColorTexture.texture, u_baseColorFactor: metallicRoughness.baseColorFactor, u_metallicRoughnessTexture: metallicRoughness.metallicRoughnessTexture.texture, u_metallicFactor: metallicRoughness.metallicFactor, u_roughnessFactor: metallicRoughness.roughnessFactor }; expectUniformMap(uniformMap, expectedUniforms); }); }); it("doesn't add emissive uniforms when emissive factor is default", function() { return loadGltf(boomBox).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const material = primitive.material; material.emissiveFactor = import__701.Cartesian3.clone( import__701.ModelComponents.Material.DEFAULT_EMISSIVE_FACTOR ); const metallicRoughness = material.metallicRoughness; const renderResources = mockRenderResources(); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform sampler2D u_baseColorTexture;", "uniform sampler2D u_metallicRoughnessTexture;", "uniform sampler2D u_normalTexture;", "uniform sampler2D u_occlusionTexture;" ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_BASE_COLOR_TEXTURE", "HAS_METALLIC_ROUGHNESS_TEXTURE", "HAS_NORMAL_TEXTURE", "HAS_OCCLUSION_TEXTURE", "TEXCOORD_BASE_COLOR v_texCoord_0", "TEXCOORD_METALLIC_ROUGHNESS v_texCoord_0", "TEXCOORD_NORMAL v_texCoord_0", "TEXCOORD_OCCLUSION v_texCoord_0", "USE_METALLIC_ROUGHNESS" ]); const expectedUniforms = { u_normalTexture: material.normalTexture.texture, u_occlusionTexture: material.occlusionTexture.texture, u_baseColorTexture: metallicRoughness.baseColorTexture.texture, u_metallicRoughnessTexture: metallicRoughness.metallicRoughnessTexture.texture }; expectUniformMap(uniformMap, expectedUniforms); }); }); it("adds specular glossiness uniforms", function() { return loadGltf(boomBoxSpecularGlossiness).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const renderResources = mockRenderResources(); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform float u_glossinessFactor;", "uniform sampler2D u_diffuseTexture;", "uniform sampler2D u_emissiveTexture;", "uniform sampler2D u_normalTexture;", "uniform sampler2D u_occlusionTexture;", "uniform sampler2D u_specularGlossinessTexture;", "uniform vec3 u_emissiveFactor;" ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_DIFFUSE_TEXTURE", "HAS_EMISSIVE_FACTOR", "HAS_EMISSIVE_TEXTURE", "HAS_GLOSSINESS_FACTOR", "HAS_NORMAL_TEXTURE", "HAS_OCCLUSION_TEXTURE", "HAS_SPECULAR_GLOSSINESS_TEXTURE", "TEXCOORD_DIFFUSE v_texCoord_0", "TEXCOORD_EMISSIVE v_texCoord_0", "TEXCOORD_NORMAL v_texCoord_0", "TEXCOORD_OCCLUSION v_texCoord_0", "TEXCOORD_SPECULAR_GLOSSINESS v_texCoord_0", "USE_SPECULAR_GLOSSINESS" ]); const specularGlossiness = primitive.material.specularGlossiness; const expectedUniforms = { u_diffuseTexture: specularGlossiness.diffuseTexture.texture, u_specularGlossinessTexture: specularGlossiness.specularGlossinessTexture.texture, u_glossinessFactor: specularGlossiness.glossinessFactor }; expectUniformMap(uniformMap, expectedUniforms); }); }); it("adds specular glossiness uniforms without defaults", function() { return loadGltf(boomBoxSpecularGlossiness).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const specularGlossiness = primitive.material.specularGlossiness; specularGlossiness.diffuseFactor = new import__701.Cartesian4(0.5, 0.5, 0.5, 0.5); specularGlossiness.specularFactor = new import__701.Cartesian3(0.5, 0.5, 0.5); const renderResources = mockRenderResources(); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform float u_glossinessFactor;", "uniform sampler2D u_diffuseTexture;", "uniform sampler2D u_emissiveTexture;", "uniform sampler2D u_normalTexture;", "uniform sampler2D u_occlusionTexture;", "uniform sampler2D u_specularGlossinessTexture;", "uniform vec3 u_emissiveFactor;", "uniform vec3 u_specularFactor;", "uniform vec4 u_diffuseFactor;" ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_DIFFUSE_FACTOR", "HAS_DIFFUSE_TEXTURE", "HAS_EMISSIVE_FACTOR", "HAS_EMISSIVE_TEXTURE", "HAS_GLOSSINESS_FACTOR", "HAS_NORMAL_TEXTURE", "HAS_OCCLUSION_TEXTURE", "HAS_SPECULAR_FACTOR", "HAS_SPECULAR_GLOSSINESS_TEXTURE", "TEXCOORD_DIFFUSE v_texCoord_0", "TEXCOORD_EMISSIVE v_texCoord_0", "TEXCOORD_NORMAL v_texCoord_0", "TEXCOORD_OCCLUSION v_texCoord_0", "TEXCOORD_SPECULAR_GLOSSINESS v_texCoord_0", "USE_SPECULAR_GLOSSINESS" ]); const expectedUniforms = { u_diffuseTexture: specularGlossiness.diffuseTexture.texture, u_diffuseFactor: specularGlossiness.diffuseFactor, u_specularGlossinessTexture: specularGlossiness.specularGlossinessTexture.texture, u_specularFactor: specularGlossiness.specularFactor, u_glossinessFactor: specularGlossiness.glossinessFactor }; expectUniformMap(uniformMap, expectedUniforms); }); }); it("doesn't add texture uniforms for classification models", function() { return loadGltf(boomBox).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const renderResources = mockRenderResources(import__701.ClassificationType.BOTH); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform vec3 u_emissiveFactor;" ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_EMISSIVE_FACTOR", "USE_METALLIC_ROUGHNESS" ]); const material = primitive.material; const expectedUniforms = { u_emissiveFactor: material.emissiveFactor }; expectUniformMap(uniformMap, expectedUniforms); }); }); it("doesn't add metallic roughness textures for classification models", function() { return loadGltf(boomBox).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const metallicRoughness = primitive.material.metallicRoughness; metallicRoughness.baseColorFactor = new import__701.Cartesian4(0.5, 0.5, 0.5, 0.5); metallicRoughness.metallicFactor = 0.5; metallicRoughness.roughnessFactor = 0.5; const renderResources = mockRenderResources(); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform float u_metallicFactor;", "uniform float u_roughnessFactor;", "uniform sampler2D u_baseColorTexture;", "uniform sampler2D u_emissiveTexture;", "uniform sampler2D u_metallicRoughnessTexture;", "uniform sampler2D u_normalTexture;", "uniform sampler2D u_occlusionTexture;", "uniform vec3 u_emissiveFactor;", "uniform vec4 u_baseColorFactor;" ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_BASE_COLOR_FACTOR", "HAS_BASE_COLOR_TEXTURE", "HAS_EMISSIVE_FACTOR", "HAS_EMISSIVE_TEXTURE", "HAS_METALLIC_FACTOR", "HAS_METALLIC_ROUGHNESS_TEXTURE", "HAS_NORMAL_TEXTURE", "HAS_OCCLUSION_TEXTURE", "HAS_ROUGHNESS_FACTOR", "TEXCOORD_BASE_COLOR v_texCoord_0", "TEXCOORD_EMISSIVE v_texCoord_0", "TEXCOORD_METALLIC_ROUGHNESS v_texCoord_0", "TEXCOORD_NORMAL v_texCoord_0", "TEXCOORD_OCCLUSION v_texCoord_0", "USE_METALLIC_ROUGHNESS" ]); const expectedUniforms = { u_baseColorFactor: metallicRoughness.baseColorFactor, u_metallicFactor: metallicRoughness.metallicFactor, u_roughnessFactor: metallicRoughness.roughnessFactor }; expectUniformMap(uniformMap, expectedUniforms); }); }); it("enables PBR lighting for metallic roughness materials", function() { return loadGltf(boomBox).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const renderResources = mockRenderResources(); const lightingOptions = renderResources.lightingOptions; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); expect(lightingOptions.lightingModel).toBe(import__701.LightingModel.PBR); }); }); it("enables PBR lighting for specular glossiness materials", function() { return loadGltf(boomBoxSpecularGlossiness).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const renderResources = mockRenderResources(); const lightingOptions = renderResources.lightingOptions; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); expect(lightingOptions.lightingModel).toBe(import__701.LightingModel.PBR); }); }); it("enables unlit lighting when KHR_materials_unlit is present", function() { return loadGltf(boxUnlit).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; const renderResources = mockRenderResources(); const lightingOptions = renderResources.lightingOptions; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); expect(lightingOptions.lightingModel).toBe(import__701.LightingModel.UNLIT); }); }); it("enables unlit lighting for classification models", function() { return loadGltf(boxUnlit).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; const renderResources = mockRenderResources(import__701.ClassificationType.BOTH); const lightingOptions = renderResources.lightingOptions; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); expect(lightingOptions.lightingModel).toBe(import__701.LightingModel.UNLIT); }); }); it("gracefully falls back to unlit shading for models without normals", function() { return loadGltf(boxNoNormals).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; const renderResources = mockRenderResources(); const lightingOptions = renderResources.lightingOptions; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); expect(lightingOptions.lightingModel).toBe(import__701.LightingModel.UNLIT); }); }); it("handles opaque material", function() { return loadGltf(boomBox).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const renderResources = mockRenderResources(); import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); expect(renderResources.alphaOptions.pass).not.toBeDefined(); expect(renderResources.alphaOptions.alphaCutoff).not.toBeDefined(); }); }); it("handles alpha mask material", function() { return loadGltf(boomBox).then(function(gltfLoader) { const cutoff = 0.6; const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; primitive.material.alphaMode = import__701.AlphaMode.MASK; primitive.material.alphaCutoff = cutoff; const renderResources = mockRenderResources(); import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); expect(renderResources.alphaOptions.pass).not.toBeDefined(); expect(renderResources.alphaOptions.alphaCutoff).toBe(cutoff); }); }); it("handles translucent material", function() { return loadGltf(boomBox).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; primitive.material.alphaMode = import__701.AlphaMode.BLEND; const renderResources = mockRenderResources(); renderResources.pass = import__701.Pass.OPAQUE; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); expect(renderResources.alphaOptions.pass).toBe(import__701.Pass.TRANSLUCENT); expect(renderResources.alphaOptions.alphaCutoff).not.toBeDefined(); }); }); it("disables back-face culling if model.backFaceCulling is false", function() { return loadGltf(boxUnlit).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; const renderResources = mockRenderResources(); const renderStateOptions = renderResources.renderStateOptions; renderResources.model.backFaceCulling = false; renderResources.cull = true; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); expect(renderStateOptions.cull.enabled).toBe(false); }); }); it("enables back-face culling if material is not double-sided", function() { return loadGltf(boxUnlit).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; const renderResources = mockRenderResources(); const renderStateOptions = renderResources.renderStateOptions; renderResources.model.backFaceCulling = true; renderResources.cull = true; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); expect(renderStateOptions.cull.enabled).toBe(true); }); }); it("disables back-face culling if material is double-sided", function() { return loadGltf(boxUnlit).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; const renderResources = mockRenderResources(); renderResources.model.backFaceCulling = true; const renderStateOptions = renderResources.renderStateOptions; primitive.material.doubleSided = true; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); expect(renderStateOptions.cull.enabled).toBe(false); }); }); it("adds material stage functions to the fragment shader", function() { return loadGltf(boxUnlit).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; primitive.material.doubleSided = true; const renderResources = mockRenderResources(); const shaderBuilder = renderResources.shaderBuilder; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, []); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__701._shadersMaterialStageFS ]); }); }); it("adds define to shader if material is double-sided", function() { return loadGltf(twoSidedPlane).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const renderResources = mockRenderResources(); const shaderBuilder = renderResources.shaderBuilder; import__701.MaterialPipelineStage.process( renderResources, primitive, mockFrameState ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_DOUBLE_SIDED_MATERIAL" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_BASE_COLOR_TEXTURE", "HAS_DOUBLE_SIDED_MATERIAL", "HAS_METALLIC_ROUGHNESS_TEXTURE", "HAS_NORMAL_TEXTURE", "TEXCOORD_BASE_COLOR v_texCoord_0", "TEXCOORD_METALLIC_ROUGHNESS v_texCoord_0", "TEXCOORD_NORMAL v_texCoord_0", "USE_METALLIC_ROUGHNESS" ]); }); }); it("_processTextureTransform updates the shader and uniform map", function() { const shaderBuilder = new import__701.ShaderBuilder(); const uniformMap = {}; const matrix = new import__701.Matrix3(0.5, 0, 0.5, 0, 0.5, 0, 0, 0, 1); const textureReader = { transform: matrix }; import__701.MaterialPipelineStage._processTextureTransform( shaderBuilder, uniformMap, textureReader, "u_testTexture", "TEST" ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_TEST_TEXTURE_TRANSFORM" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform mat3 u_testTextureTransform;" ]); expectUniformMap(uniformMap, { u_testTextureTransform: matrix }); }); it("_processTexture processes texture transforms if present", function() { const shaderBuilder = new import__701.ShaderBuilder(); const uniformMap = {}; const matrix = new import__701.Matrix3(0.5, 0, 0.5, 0, 0.5, 0, 0, 0, 1); const mockTexture = {}; const textureReader = { transform: matrix, texture: mockTexture, texCoord: 1 }; import__701.MaterialPipelineStage._processTexture( shaderBuilder, uniformMap, textureReader, "u_testTexture", "TEST", mockFrameState.context.defaultTexture ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_TEST_TEXTURE", "TEXCOORD_TEST v_texCoord_1", "HAS_TEST_TEXTURE_TRANSFORM" ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform sampler2D u_testTexture;", "uniform mat3 u_testTextureTransform;" ]); expectUniformMap(uniformMap, { u_testTextureTransform: matrix }); }); it("_processTexture creates texture uniforms with a default value", function() { const shaderBuilder = new import__701.ShaderBuilder(); const uniformMap = {}; const matrix = new import__701.Matrix3(0.5, 0, 0.5, 0, 0.5, 0, 0, 0, 1); const mockTexture = {}; const textureReader = { transform: matrix, texture: mockTexture, texCoord: 1 }; import__701.MaterialPipelineStage._processTexture( shaderBuilder, uniformMap, textureReader, "u_testTexture", "TEST", mockFrameState.context.defaultTexture ); expectUniformMap(uniformMap, { u_testTexture: mockTexture }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/MetadataPipelineStageSpec.js var import__702 = __toESM(require_Cesium(), 1); describe( "Scene/Model/MetadataPipelineStage", function() { const pointCloudWithPropertyAttributes = "./Data/Models/glTF-2.0/PointCloudWithPropertyAttributes/glTF/PointCloudWithPropertyAttributes.gltf"; const simplePropertyTexture = "./Data/Models/glTF-2.0/SimplePropertyTexture/glTF/SimplePropertyTexture.gltf"; const propertyTextureWithVectorProperties = "./Data/Models/glTF-2.0/PropertyTextureWithVectorProperties/glTF/PropertyTextureWithVectorProperties.gltf"; const propertyTextureWithTextureTransformUrl = "./Data/Models/glTF-2.0/PropertyTextureWithTextureTransform/glTF/PropertyTextureWithTextureTransform.gltf"; const boxTexturedBinary = "./Data/Models/glTF-2.0/BoxTextured/glTF-Binary/BoxTextured.glb"; const tilesetWithMetadataStatistics = "./Data/Cesium3DTiles/Metadata/PropertyAttributesPointCloud/tileset.json"; let scene2; const gltfLoaders = []; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); function cleanup(resourcesArray) { for (let i = 0; i < resourcesArray.length; i++) { const resource = resourcesArray[i]; if (!resource.isDestroyed()) { resource.destroy(); } } resourcesArray.length = 0; } afterEach(function() { cleanup(gltfLoaders); scene2.primitives.removeAll(); import__702.ResourceCache.clearForSpecs(); }); async function loadGltf(gltfPath) { const gltfLoader = new import__702.GltfLoader({ gltfResource: new import__702.Resource({ url: gltfPath }), incrementallyLoadTextures: false }); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, scene2); return gltfLoader; } function mockRenderResources(components) { return { shaderBuilder: new import__702.ShaderBuilder(), model: { statistics: new import__702.ModelStatistics(), structuralMetadata: components.structuralMetadata }, uniformMap: {} }; } function checkMetadataClassStructs(shaderBuilder, metadataTypes) { for (const metadataType of metadataTypes) { const structName = `${metadataType}MetadataClass`; const structFields = [ ` ${metadataType} noData;`, ` ${metadataType} defaultValue;`, ` ${metadataType} minValue;`, ` ${metadataType} maxValue;` ]; ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, structName, structName, structFields ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, structName, structName, structFields ); } } it("Handles primitives without metadata gracefully", function() { return loadGltf(boxTexturedBinary).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[1]; const primitive = node.primitives[0]; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(components); import__702.MetadataPipelineStage.process(renderResources, primitive, frameState2); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__702.MetadataPipelineStage.STRUCT_ID_METADATA_VS, import__702.MetadataPipelineStage.STRUCT_NAME_METADATA, [] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__702.MetadataPipelineStage.STRUCT_ID_METADATA_FS, import__702.MetadataPipelineStage.STRUCT_NAME_METADATA, [] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__702.MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_VS, import__702.MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA, [] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__702.MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS, import__702.MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA, [] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__702.MetadataPipelineStage.FUNCTION_ID_SET_METADATA_VARYINGS, import__702.MetadataPipelineStage.FUNCTION_SIGNATURE_SET_METADATA_VARYINGS, [] ); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); expect(renderResources.uniformMap).toEqual({}); }); }); it("Adds property attributes to the shader", function() { return loadGltf(pointCloudWithPropertyAttributes).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const primitive = node.primitives[0]; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(components); import__702.MetadataPipelineStage.process(renderResources, primitive, frameState2); const shaderBuilder = renderResources.shaderBuilder; const metadataTypes = ["float"]; checkMetadataClassStructs(shaderBuilder, metadataTypes); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__702.MetadataPipelineStage.STRUCT_ID_METADATA_VS, import__702.MetadataPipelineStage.STRUCT_NAME_METADATA, [ " float circleT;", " float iteration;", " float pointId;", " float toroidalNormalized;", " float poloidalNormalized;", " float toroidalAngle;", " float poloidalAngle;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__702.MetadataPipelineStage.STRUCT_ID_METADATA_FS, import__702.MetadataPipelineStage.STRUCT_NAME_METADATA, [ " float circleT;", " float iteration;", " float pointId;", " float toroidalNormalized;", " float poloidalNormalized;", " float toroidalAngle;", " float poloidalAngle;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__702.MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_VS, import__702.MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA, [ " metadata.circleT = attributes.circle_t;", " metadata.iteration = attributes.featureId_0;", " metadata.pointId = attributes.featureId_1;", " metadata.toroidalNormalized = czm_valueTransform(u_toroidalNormalized_offset, u_toroidalNormalized_scale, attributes.featureId_0);", " metadata.poloidalNormalized = czm_valueTransform(u_poloidalNormalized_offset, u_poloidalNormalized_scale, attributes.featureId_1);", " metadata.toroidalAngle = czm_valueTransform(u_toroidalAngle_offset, u_toroidalAngle_scale, attributes.featureId_0);", " metadata.poloidalAngle = czm_valueTransform(u_poloidalAngle_offset, u_poloidalAngle_scale, attributes.featureId_1);" ] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__702.MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS, import__702.MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA, [ " metadata.circleT = attributes.circle_t;", " metadata.iteration = attributes.featureId_0;", " metadata.pointId = attributes.featureId_1;", " metadata.toroidalNormalized = czm_valueTransform(u_toroidalNormalized_offset, u_toroidalNormalized_scale, attributes.featureId_0);", " metadata.poloidalNormalized = czm_valueTransform(u_poloidalNormalized_offset, u_poloidalNormalized_scale, attributes.featureId_1);", " metadata.toroidalAngle = czm_valueTransform(u_toroidalAngle_offset, u_toroidalAngle_scale, attributes.featureId_0);", " metadata.poloidalAngle = czm_valueTransform(u_poloidalAngle_offset, u_poloidalAngle_scale, attributes.featureId_1);" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__702.MetadataPipelineStage.FUNCTION_ID_SET_METADATA_VARYINGS, import__702.MetadataPipelineStage.FUNCTION_SIGNATURE_SET_METADATA_VARYINGS, [] ); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform float u_toroidalNormalized_offset;", "uniform float u_toroidalNormalized_scale;", "uniform float u_poloidalNormalized_offset;", "uniform float u_poloidalNormalized_scale;", "uniform float u_toroidalAngle_offset;", "uniform float u_toroidalAngle_scale;", "uniform float u_poloidalAngle_offset;", "uniform float u_poloidalAngle_scale;" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform float u_toroidalNormalized_offset;", "uniform float u_toroidalNormalized_scale;", "uniform float u_poloidalNormalized_offset;", "uniform float u_poloidalNormalized_scale;", "uniform float u_toroidalAngle_offset;", "uniform float u_toroidalAngle_scale;", "uniform float u_poloidalAngle_offset;", "uniform float u_poloidalAngle_scale;" ]); const uniformMap = renderResources.uniformMap; expect(uniformMap.u_toroidalNormalized_offset()).toBe(0); expect(uniformMap.u_toroidalNormalized_scale()).toBe( 0.034482758620689655 ); expect(uniformMap.u_poloidalNormalized_offset()).toBe(0); expect(uniformMap.u_poloidalNormalized_scale()).toBe( 0.05263157894736842 ); expect(uniformMap.u_toroidalAngle_offset()).toBe(0); expect(uniformMap.u_toroidalAngle_scale()).toBe(0.21666156231653746); expect(uniformMap.u_poloidalAngle_offset()).toBe(-3.141592653589793); expect(uniformMap.u_poloidalAngle_scale()).toBe(0.3306939635357677); }); }); it("Adds property textures to the shader", function() { return loadGltf(simplePropertyTexture).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const primitive = node.primitives[0]; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(components); import__702.MetadataPipelineStage.process(renderResources, primitive, frameState2); const shaderBuilder = renderResources.shaderBuilder; const metadataTypes = ["int", "float"]; checkMetadataClassStructs(shaderBuilder, metadataTypes); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__702.MetadataPipelineStage.STRUCT_ID_METADATA_VS, import__702.MetadataPipelineStage.STRUCT_NAME_METADATA, [] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__702.MetadataPipelineStage.STRUCT_ID_METADATA_FS, import__702.MetadataPipelineStage.STRUCT_NAME_METADATA, [ " float insulation;", " int insideTemperature;", " int outsideTemperature;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__702.MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_VS, import__702.MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA, [] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__702.MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS, import__702.MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA, [ " metadata.insulation = texture(u_propertyTexture_1, attributes.texCoord_0).b;", " metadata.insideTemperature = int(255.0 * texture(u_propertyTexture_1, attributes.texCoord_0).r);", " metadata.outsideTemperature = int(255.0 * texture(u_propertyTexture_1, attributes.texCoord_0).g);", " metadataClass.insulation.defaultValue = float(1);" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__702.MetadataPipelineStage.FUNCTION_ID_SET_METADATA_VARYINGS, import__702.MetadataPipelineStage.FUNCTION_SIGNATURE_SET_METADATA_VARYINGS, [] ); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform sampler2D u_propertyTexture_1;" ]); const structuralMetadata = renderResources.model.structuralMetadata; const propertyTexture1 = structuralMetadata.getPropertyTexture(0); const texture1 = propertyTexture1.getProperty("insulation"); const uniformMap = renderResources.uniformMap; expect(uniformMap.u_propertyTexture_1()).toBe( texture1.textureReader.texture ); }); }); it("Adds property texture transform to the shader", async function() { const gltfLoader = await loadGltf(propertyTextureWithTextureTransformUrl); const components = gltfLoader.components; const node = components.nodes[0]; const primitive = node.primitives[0]; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(components); import__702.MetadataPipelineStage.process(renderResources, primitive, frameState2); const shaderBuilder = renderResources.shaderBuilder; const metadataTypes = ["float"]; checkMetadataClassStructs(shaderBuilder, metadataTypes); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__702.MetadataPipelineStage.STRUCT_ID_METADATA_VS, import__702.MetadataPipelineStage.STRUCT_NAME_METADATA, [] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__702.MetadataPipelineStage.STRUCT_ID_METADATA_FS, import__702.MetadataPipelineStage.STRUCT_NAME_METADATA, [" float exampleProperty;"] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__702.MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_VS, import__702.MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA, [] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__702.MetadataPipelineStage.FUNCTION_ID_SET_METADATA_VARYINGS, import__702.MetadataPipelineStage.FUNCTION_SIGNATURE_SET_METADATA_VARYINGS, [] ); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform sampler2D u_propertyTexture_0;", "uniform mat3 u_propertyTexture_0Transform;" ]); const structuralMetadata = renderResources.model.structuralMetadata; const propertyTexture0 = structuralMetadata.getPropertyTexture(0); const texture1 = propertyTexture0.getProperty("exampleProperty"); const uniformMap = renderResources.uniformMap; expect(uniformMap.u_propertyTexture_0()).toBe( texture1.textureReader.texture ); }); it("Handles property textures with vector values", function() { return loadGltf(propertyTextureWithVectorProperties).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const primitive = node.primitives[0]; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(components); import__702.MetadataPipelineStage.process(renderResources, primitive, frameState2); const shaderBuilder = renderResources.shaderBuilder; const metadataTypes = ["vec2", "int", "ivec3", "vec3"]; checkMetadataClassStructs(shaderBuilder, metadataTypes); ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__702.MetadataPipelineStage.STRUCT_ID_METADATA_VS, import__702.MetadataPipelineStage.STRUCT_NAME_METADATA, [] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__702.MetadataPipelineStage.STRUCT_ID_METADATA_FS, import__702.MetadataPipelineStage.STRUCT_NAME_METADATA, [ " vec2 vec2Property;", " int uint8Property;", " ivec3 uint8vec3Property;", " vec3 arrayProperty;", " vec2 valueTransformProperty;" ] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__702.MetadataPipelineStage.STRUCT_ID_METADATA_CLASS_FS, import__702.MetadataPipelineStage.STRUCT_NAME_METADATA_CLASS, [ " vec2MetadataClass vec2Property;", " intMetadataClass uint8Property;", " ivec3MetadataClass uint8vec3Property;", " vec3MetadataClass arrayProperty;", " vec2MetadataClass valueTransformProperty;" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__702.MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_VS, import__702.MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA, [] ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( shaderBuilder, import__702.MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS, import__702.MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA, [ " metadata.vec2Property = texture(u_propertyTexture_1, attributes.texCoord_0).gb;", " metadata.uint8Property = int(255.0 * texture(u_propertyTexture_1, attributes.texCoord_0).r);", " metadata.uint8vec3Property = ivec3(255.0 * texture(u_propertyTexture_1, attributes.texCoord_0).rgb);", " metadata.arrayProperty = texture(u_propertyTexture_1, attributes.texCoord_0).rgb;", " metadata.valueTransformProperty = czm_valueTransform(u_valueTransformProperty_offset, u_valueTransformProperty_scale, texture(u_propertyTexture_1, attributes.texCoord_0).rg);", " metadataClass.uint8vec3Property.defaultValue = ivec3(255,0,0);", " metadataClass.uint8vec3Property.maxValue = ivec3(30,17,50);", " metadataClass.uint8vec3Property.minValue = ivec3(10,10,10);", " metadataClass.uint8vec3Property.noData = ivec3(19,13,50);" ] ); ShaderBuilderTester_default.expectHasVertexFunctionUnordered( shaderBuilder, import__702.MetadataPipelineStage.FUNCTION_ID_SET_METADATA_VARYINGS, import__702.MetadataPipelineStage.FUNCTION_SIGNATURE_SET_METADATA_VARYINGS, [] ); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform sampler2D u_propertyTexture_1;", "uniform vec2 u_valueTransformProperty_offset;", "uniform vec2 u_valueTransformProperty_scale;" ]); const structuralMetadata = renderResources.model.structuralMetadata; const propertyTexture1 = structuralMetadata.getPropertyTexture(0); const texture1 = propertyTexture1.getProperty("arrayProperty"); const uniformMap = renderResources.uniformMap; expect(uniformMap.u_propertyTexture_1()).toBe( texture1.textureReader.texture ); expect(uniformMap.u_valueTransformProperty_offset()).toEqual( new import__702.Cartesian2(1, 1) ); expect(uniformMap.u_valueTransformProperty_scale()).toEqual( new import__702.Cartesian2(2, 2) ); }); }); it("Handles a tileset with metadata statistics", function() { const modelPos = import__702.Cartesian3.fromDegrees(-75.152325, 39.94704); const offset = new import__702.HeadingPitchRange(0, 0, 5); scene2.camera.lookAt(modelPos, offset); const tilesetOptions = { modelMatrix: import__702.Transforms.eastNorthUpToFixedFrame(modelPos) }; return Cesium3DTilesTester_default.loadTileset( scene2, tilesetWithMetadataStatistics, tilesetOptions ).then(function(tileset) { expect(tileset).toBeDefined(); expect(tileset.tilesLoaded).toBe(true); const metadataExtension = tileset.metadataExtension; expect(metadataExtension).toBeDefined(); expect(metadataExtension.statistics).toBeDefined(); const model = tileset.root.children[1].content._model; expect(model).toBeDefined(); const shaderBuilder = new import__702.ShaderBuilder(); const renderResources = { shaderBuilder, model, uniformMap: {} }; const primitive = model.sceneGraph.components.nodes[0].primitives[0]; expect(primitive).toBeDefined(); const frameState2 = scene2.frameState; import__702.MetadataPipelineStage.process(renderResources, primitive, frameState2); const metadataTypes = ["float"]; checkMetadataClassStructs(shaderBuilder, metadataTypes); const structName = `floatMetadataStatistics`; const structFields = [ ` float minValue;`, ` float maxValue;`, ` float mean;`, ` float median;`, ` float standardDeviation;`, ` float variance;`, ` float sum;` ]; ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, structName, structName, structFields ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, structName, structName, structFields ); const metadataFields = [ " float classification;", " float intensity;" ]; ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__702.MetadataPipelineStage.STRUCT_ID_METADATA_VS, import__702.MetadataPipelineStage.STRUCT_NAME_METADATA, metadataFields ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__702.MetadataPipelineStage.STRUCT_ID_METADATA_FS, import__702.MetadataPipelineStage.STRUCT_NAME_METADATA, metadataFields ); const metadataClassFields = [ " floatMetadataClass classification;", " floatMetadataClass intensity;" ]; ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__702.MetadataPipelineStage.STRUCT_ID_METADATA_CLASS_VS, import__702.MetadataPipelineStage.STRUCT_NAME_METADATA_CLASS, metadataClassFields ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__702.MetadataPipelineStage.STRUCT_ID_METADATA_CLASS_FS, import__702.MetadataPipelineStage.STRUCT_NAME_METADATA_CLASS, metadataClassFields ); const metadataStatisticsFields = [ " floatMetadataStatistics intensity;" ]; ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__702.MetadataPipelineStage.STRUCT_ID_METADATA_STATISTICS_VS, import__702.MetadataPipelineStage.STRUCT_NAME_METADATA_STATISTICS, metadataStatisticsFields ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__702.MetadataPipelineStage.STRUCT_ID_METADATA_STATISTICS_FS, import__702.MetadataPipelineStage.STRUCT_NAME_METADATA_STATISTICS, metadataStatisticsFields ); const assignments = [ " metadata.classification = attributes.classification;", " metadata.intensity = attributes.intensity;", " metadataStatistics.intensity.mean = float(0.28973701532415364);", " metadataStatistics.intensity.median = float(0.25416669249534607);", " metadataStatistics.intensity.standardDeviation = float(0.18222664489583626);", " metadataStatistics.intensity.variance = float(0.03320655011);", " metadataStatistics.intensity.sum = float(8500.30455558002);", " metadataStatistics.intensity.minValue = float(0);", " metadataStatistics.intensity.maxValue = float(0.6333333849906921);" ]; ShaderBuilderTester_default.expectHasVertexFunctionUnordered( renderResources.shaderBuilder, import__702.MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_VS, import__702.MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA, assignments ); ShaderBuilderTester_default.expectHasFragmentFunctionUnordered( renderResources.shaderBuilder, import__702.MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS, import__702.MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA, assignments ); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/Model3DTileContentSpec.js var import__703 = __toESM(require_Cesium(), 1); describe( "Scene/Model/Model3DTileContent", function() { const gltfContentUrl = "./Data/Cesium3DTiles/GltfContent/glTF/tileset.json"; const glbContentUrl = "./Data/Cesium3DTiles/GltfContent/glb/tileset.json"; const buildingsMetadataUrl = "./Data/Cesium3DTiles/Metadata/StructuralMetadata/tileset.json"; const withoutBatchTableUrl = "./Data/Cesium3DTiles/Batched/BatchedWithoutBatchTable/tileset.json"; const noBatchIdsUrl = "Data/Cesium3DTiles/Batched/BatchedNoBatchIds/tileset.json"; const withBatchTableUrl = "./Data/Cesium3DTiles/Batched/BatchedWithBatchTable/tileset.json"; const withBatchTableBinaryUrl = "./Data/Cesium3DTiles/Batched/BatchedWithBatchTableBinary/tileset.json"; const translucentUrl = "./Data/Cesium3DTiles/Batched/BatchedTranslucent/tileset.json"; const translucentOpaqueMixUrl = "./Data/Cesium3DTiles/Batched/BatchedTranslucentOpaqueMix/tileset.json"; const withTransformBoxUrl = "./Data/Cesium3DTiles/Batched/BatchedWithTransformBox/tileset.json"; const withTransformSphereUrl = "./Data/Cesium3DTiles/Batched/BatchedWithTransformSphere/tileset.json"; const withTransformRegionUrl = "./Data/Cesium3DTiles/Batched/BatchedWithTransformRegion/tileset.json"; const texturedUrl = "./Data/Cesium3DTiles/Batched/BatchedTextured/tileset.json"; const withCopyrightUrl = "./Data/Cesium3DTiles/Batched/BatchedWithCopyright/tileset.json"; const instancedWithBatchTableUrl = "./Data/Cesium3DTiles/Instanced/InstancedWithBatchTable/tileset.json"; const instancedExternalGltfUrl = "./Data/Cesium3DTiles/Instanced/InstancedGltfExternal/tileset.json"; const instancedWithoutNormalsUrl = "./Data/Cesium3DTiles/Instanced/InstancedWithoutNormals/tileset.json"; const instancedWithoutBatchTableUrl = "./Data/Cesium3DTiles/Instanced/InstancedWithoutBatchTable/tileset.json"; const instancedWithBatchIdsUrl = "./Data/Cesium3DTiles/Instanced/InstancedWithBatchIds/tileset.json"; const instancedTexturedUrl = "./Data/Cesium3DTiles/Instanced/InstancedTextured/tileset.json"; const pointCloudRGBUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudRGB/tileset.json"; const pointCloudRGBAUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudRGBA/tileset.json"; const pointCloudNoColorUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudNoColor/tileset.json"; const pointCloudNormalsUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudNormals/tileset.json"; const pointCloudQuantizedOctEncodedUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudQuantizedOctEncoded/tileset.json"; const pointCloudDracoUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudDraco/tileset.json"; const pointCloudWGS84Url = "./Data/Cesium3DTiles/PointCloud/PointCloudWGS84/tileset.json"; const pointCloudBatchedUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudBatched/tileset.json"; const pointCloudWithPerPointPropertiesUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudWithPerPointProperties/tileset.json"; const pointCloudWithUnicodePropertyIdsUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudWithUnicodePropertyIds/tileset.json"; const geoJsonMultiPolygonUrl = "./Data/Cesium3DTiles/GeoJson/MultiPolygon/tileset.json"; const geoJsonPolygonUrl = "./Data/Cesium3DTiles/GeoJson/Polygon/tileset.json"; const geoJsonPolygonHeightsUrl = "./Data/Cesium3DTiles/GeoJson/PolygonHeights/tileset.json"; const geoJsonPolygonHoleUrl = "./Data/Cesium3DTiles/GeoJson/PolygonHole/tileset.json"; const geoJsonPolygonNoPropertiesUrl = "./Data/Cesium3DTiles/GeoJson/PolygonNoProperties/tileset.json"; const geoJsonLineStringUrl = "./Data/Cesium3DTiles/GeoJson/LineString/tileset.json"; const geoJsonMultiLineStringUrl = "./Data/Cesium3DTiles/GeoJson/MultiLineString/tileset.json"; const geoJsonMultipleFeaturesUrl = "./Data/Cesium3DTiles/GeoJson/MultipleFeatures/tileset.json"; let scene2; const centerLongitude = -1.31968; const centerLatitude = 0.698874; const webglStub = !!window.webglStub; function setCamera(longitude, latitude, range) { const center = import__703.Cartesian3.fromRadians(longitude, latitude); scene2.camera.lookAt(center, new import__703.HeadingPitchRange(0, -1.57, range)); } beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { scene2.morphTo3D(0); setCamera(centerLongitude, centerLatitude, 100); }); afterEach(function() { scene2.primitives.removeAll(); }); describe("geoJSON", function() { beforeEach(function() { setCamera(centerLongitude, centerLatitude, 1); }); function rendersGeoJson(url) { return Cesium3DTilesTester_default.loadTileset(scene2, url).then(function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); }); } it("renders GeoJSON MultiPolygon", function() { return rendersGeoJson(geoJsonMultiPolygonUrl); }); it("renders GeoJSON Polygon", function() { return rendersGeoJson(geoJsonPolygonUrl); }); it("renders GeoJSON Polygon with heights", function() { return rendersGeoJson(geoJsonPolygonHeightsUrl); }); it("renders GeoJSON Polygon with hole", function() { return rendersGeoJson(geoJsonPolygonHoleUrl); }); it("renders GeoJSON Polygon with no properties", function() { return rendersGeoJson(geoJsonPolygonNoPropertiesUrl); }); it("renders GeoJSON LineString", function() { return rendersGeoJson(geoJsonLineStringUrl); }); it("renders GeoJSON MultiLineString", function() { return rendersGeoJson(geoJsonMultiLineStringUrl); }); it("renders GeoJSON with multiple features", function() { return rendersGeoJson(geoJsonMultipleFeaturesUrl); }); function picksGeoJson(url, hasProperties, expectedFeatureId) { expectedFeatureId = (0, import__703.defaultValue)(expectedFeatureId, 0); return Cesium3DTilesTester_default.loadTileset(scene2, url).then(function(tileset) { const content = tileset.root.content; tileset.show = false; expect(scene2).toPickPrimitive(void 0); tileset.show = true; expect(scene2).toPickAndCall(function(result) { expect(result).toBeDefined(); expect(result.primitive).toBe(tileset); expect(result.content).toBe(content); const featureId = result.featureId; expect(featureId).toBe(expectedFeatureId); const feature = content.getFeature(featureId); expect(feature).toBeDefined(); if (hasProperties) { expect(feature.getProperty("name")).toBe("UL"); expect(feature.getProperty("code")).toBe(12); } else { expect(feature.getProperty("name")).toBeUndefined(); expect(feature.getProperty("code")).toBeUndefined(); } }); }); } it("picks GeoJSON MultiPolygon", function() { return picksGeoJson(geoJsonMultiPolygonUrl, true); }); it("picks GeoJSON Polygon", function() { return picksGeoJson(geoJsonPolygonUrl, true); }); it("picks GeoJSON Polygon with heights", function() { return picksGeoJson(geoJsonPolygonHeightsUrl, true); }); it("picks GeoJSON Polygon with hole", function() { return picksGeoJson(geoJsonPolygonHoleUrl, true); }); it("picks GeoJSON Polygon with no properties", function() { return picksGeoJson(geoJsonPolygonNoPropertiesUrl, false); }); it("picks GeoJSON LineString", function() { return picksGeoJson(geoJsonLineStringUrl, true); }); it("picks GeoJSON MultiLineString", function() { return picksGeoJson(geoJsonMultiLineStringUrl, true); }); it("picks GeoJSON with multiple features", function() { return picksGeoJson(geoJsonMultipleFeaturesUrl, true, 1); }); }); describe("b3dm", function() { beforeEach(function() { setCamera(centerLongitude, centerLatitude, 15); }); it("renders b3dm content with batch table", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(tileset) { Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); } ); }); it("renders b3dm with a binary batch table", function() { return Cesium3DTilesTester_default.loadTileset( scene2, withBatchTableBinaryUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); }); }); it("renders b3dm content without batch table", function() { return Cesium3DTilesTester_default.loadTileset( scene2, withoutBatchTableUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); }); }); it("renders b3dm content without features", function() { return Cesium3DTilesTester_default.loadTileset(scene2, noBatchIdsUrl).then( function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); } ); }); it("picks from b3dm", function() { return Cesium3DTilesTester_default.loadTileset( scene2, withoutBatchTableUrl ).then(function(tileset) { const content = tileset.root.content; tileset.show = false; expect(scene2).toPickPrimitive(void 0); tileset.show = true; expect(scene2).toPickAndCall(function(result) { expect(result).toBeDefined(); expect(result.primitive).toBe(tileset); expect(result.content).toBe(content); const featureId = result.featureId; expect(featureId).toBe(0); expect(content.hasProperty(featureId, "id")).toBe(false); expect(content.getFeature(featureId)).toBeDefined(); }); }); }); it("renders with all features translucent", function() { return Cesium3DTilesTester_default.loadTileset(scene2, translucentUrl).then( function(tileset) { Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); } ); }); it("renders with a mix of opaque and translucent features", function() { return Cesium3DTilesTester_default.loadTileset( scene2, translucentOpaqueMixUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); }); }); it("renders with textures", function() { return Cesium3DTilesTester_default.loadTileset(scene2, texturedUrl).then( function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); } ); }); function expectRenderWithTransform(url) { setCamera(centerLongitude, centerLatitude, 15); return Cesium3DTilesTester_default.loadTileset(scene2, url).then(function(tileset) { Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); const newLongitude = -1.31962; const newLatitude = 0.698874; const newCenter = import__703.Cartesian3.fromRadians( newLongitude, newLatitude, 0 ); const newHPR = new import__703.HeadingPitchRoll(); const newTransform = import__703.Transforms.headingPitchRollToFixedFrame( newCenter, newHPR ); tileset.root.transform = newTransform; scene2.renderForSpecs(); setCamera(newLongitude, newLatitude, 15); Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); }); } it("renders with a tile transform and box bounding volume", function() { return expectRenderWithTransform(withTransformBoxUrl); }); it("renders with a tile transform and sphere bounding volume", function() { return expectRenderWithTransform(withTransformSphereUrl); }); it("renders with a tile transform and region bounding volume", function() { return expectRenderWithTransform(withTransformRegionUrl); }); it("picks from b3dm batch table", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(tileset) { const content = tileset.root.content; tileset.show = false; expect(scene2).toPickPrimitive(void 0); tileset.show = true; expect(scene2).toPickAndCall(function(result) { expect(result).toBeDefined(); expect(result.primitive).toBe(tileset); expect(result.content).toBe(content); const featureId = result.featureId; expect(featureId).toBe(0); expect(content.batchTable).toBeDefined(); expect(content.hasProperty(featureId, "id")).toBe(true); expect(content.getFeature(featureId)).toBeDefined(); }); } ); }); it("can get features and properties", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(tileset) { const content = tileset.root.content; expect(content.featuresLength).toBe(10); expect(content.innerContents).toBeUndefined(); expect(content.hasProperty(0, "id")).toBe(true); expect(content.getFeature(0)).toBeDefined(); } ); }); it("gets memory usage", function() { return Cesium3DTilesTester_default.loadTileset(scene2, texturedUrl).then( function(tileset) { const content = tileset.root.content; const geometryByteLength = 9360; const texturesByteLength = 65536; const batchTexturesByteLength = content.featuresLength * 4; const pickTexturesByteLength = content.featuresLength * 4; expect(content.geometryByteLength).toEqual(geometryByteLength); expect(content.texturesByteLength).toEqual(texturesByteLength); expect(content.batchTableByteLength).toEqual(0); content.getFeature(0).color = import__703.Color.RED; scene2.renderForSpecs(); expect(content.geometryByteLength).toEqual(geometryByteLength); expect(content.texturesByteLength).toEqual(texturesByteLength); expect(content.batchTableByteLength).toEqual( batchTexturesByteLength ); scene2.pickForSpecs(); expect(content.geometryByteLength).toEqual(geometryByteLength); expect(content.texturesByteLength).toEqual(texturesByteLength); expect(content.batchTableByteLength).toEqual( batchTexturesByteLength + pickTexturesByteLength ); } ); }); it("gets copyright from glTF", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withCopyrightUrl).then( function(tileset) { const creditDisplay = scene2.frameState.creditDisplay; const credits = creditDisplay._currentFrameCredits.lightboxCredits.values; expect(credits.length).toEqual(1); expect(credits[0].credit.html).toEqual("Sample Copyright"); } ); }); it("shows copyright from glTF on screen", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withCopyrightUrl, { showCreditsOnScreen: true }).then(function(tileset) { const creditDisplay = scene2.frameState.creditDisplay; const credits = creditDisplay._currentFrameCredits.screenCredits.values; expect(credits.length).toEqual(1); expect(credits[0].credit.html).toEqual("Sample Copyright"); }); }); it("toggles showing copyright from glTF on screen", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withCopyrightUrl, { showCreditsOnScreen: false }).then(function(tileset) { const creditDisplay = scene2.frameState.creditDisplay; const lightboxCredits = creditDisplay._currentFrameCredits.lightboxCredits.values; const screenCredits = creditDisplay._currentFrameCredits.screenCredits.values; expect(lightboxCredits.length).toEqual(1); expect(lightboxCredits[0].credit.html).toEqual("Sample Copyright"); expect(screenCredits.length).toEqual(0); tileset.showCreditsOnScreen = true; scene2.renderForSpecs(); expect(screenCredits.length).toEqual(1); expect(screenCredits[0].credit.html).toEqual("Sample Copyright"); expect(lightboxCredits.length).toEqual(0); tileset.showCreditsOnScreen = false; scene2.renderForSpecs(); expect(lightboxCredits.length).toEqual(1); expect(lightboxCredits[0].credit.html).toEqual("Sample Copyright"); expect(screenCredits.length).toEqual(0); }); }); }); describe("i3dm", function() { beforeEach(function() { setCamera(centerLongitude, centerLatitude, 27); }); it("renders i3dm content", function() { return Cesium3DTilesTester_default.loadTileset( scene2, instancedWithBatchTableUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); }); }); it("renders with external gltf", function() { return Cesium3DTilesTester_default.loadTileset( scene2, instancedExternalGltfUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); }); }); it("renders without normals", function() { return Cesium3DTilesTester_default.loadTileset( scene2, instancedWithoutNormalsUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); }); }); it("renders with batch table", function() { return Cesium3DTilesTester_default.loadTileset( scene2, instancedWithBatchTableUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); }); }); it("renders without batch table", function() { return Cesium3DTilesTester_default.loadTileset( scene2, instancedWithoutBatchTableUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); }); }); it("renders with batch ids", function() { return Cesium3DTilesTester_default.loadTileset( scene2, instancedWithBatchIdsUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); }); }); it("renders with textures", function() { return Cesium3DTilesTester_default.loadTileset( scene2, instancedTexturedUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); }); }); it("gets memory usage", function() { return Cesium3DTilesTester_default.loadTileset( scene2, instancedTexturedUrl ).then(function(tileset) { const content = tileset.root.content; const geometryByteLength = 840 + 1300; const texturesByteLength = 65536; const batchTexturesByteLength = content.featuresLength * 4; const pickTexturesByteLength = content.featuresLength * 4; expect(content.geometryByteLength).toEqual(geometryByteLength); expect(content.texturesByteLength).toEqual(texturesByteLength); expect(content.batchTableByteLength).toEqual(0); content.getFeature(0).color = import__703.Color.RED; scene2.renderForSpecs(); expect(content.geometryByteLength).toEqual(geometryByteLength); expect(content.texturesByteLength).toEqual(texturesByteLength); expect(content.batchTableByteLength).toEqual(batchTexturesByteLength); scene2.pickForSpecs(); expect(content.geometryByteLength).toEqual(geometryByteLength); expect(content.texturesByteLength).toEqual(texturesByteLength); expect(content.batchTableByteLength).toEqual( batchTexturesByteLength + pickTexturesByteLength ); }); }); it("picks from i3dm batch table", function() { return Cesium3DTilesTester_default.loadTileset( scene2, instancedWithBatchTableUrl ).then(function(tileset) { const content = tileset.root.content; tileset.show = false; expect(scene2).toPickPrimitive(void 0); tileset.show = true; expect(scene2).toPickAndCall(function(result) { expect(result).toBeDefined(); expect(result.primitive).toBe(tileset); expect(result.content).toBe(content); const featureId = result.featureId; expect(featureId).toBe(12); expect(content.hasProperty(featureId, "Height")).toBe(true); expect(content.getFeature(featureId)).toBeDefined(); }); }); }); }); describe("pnts", function() { const time2 = new import__703.JulianDate(2457522); const renderOptions = { time: time2 }; beforeEach(function() { renderOptions.scene = scene2; setCamera(centerLongitude, centerLatitude, 5); }); it("renders point cloud with rgba colors", function() { return Cesium3DTilesTester_default.loadTileset(scene2, pointCloudRGBAUrl).then( function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); } ); }); it("renders point cloud with draco encoded positions, normals, colors, and batch table properties", function() { return Cesium3DTilesTester_default.loadTileset(scene2, pointCloudDracoUrl).then( function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); tileset.style = new import__703.Cesium3DTileStyle({ color: "vec4(Number(${secondaryColor}[0] < 1.0), 0.0, 0.0, 1.0)" }); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(rgba[1]); expect(rgba[0]).toBeGreaterThan(rgba[2]); }); } ); }); it("renders point cloud that is not defined relative to center", function() { return Cesium3DTilesTester_default.loadTileset(scene2, pointCloudWGS84Url).then( function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); } ); }); it("renders point cloud with batch table", function() { return Cesium3DTilesTester_default.loadTileset( scene2, pointCloudBatchedUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); }); }); it("renders point cloud with per-point properties", function() { return Cesium3DTilesTester_default.loadTileset( scene2, pointCloudWithPerPointPropertiesUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); }); }); it("renders with debug color", function() { import__703.Math.setRandomNumberSeed(0); return Cesium3DTilesTester_default.loadTileset(scene2, pointCloudRGBUrl).then( function(tileset) { let color; expect(renderOptions).toRenderAndCall(function(rgba) { color = rgba; }); tileset.debugColorizeTiles = true; expect(renderOptions).notToRender(color); tileset.debugColorizeTiles = false; expect(renderOptions).toRender(color); } ); }); it("renders pnts with color style", function() { return Cesium3DTilesTester_default.loadTileset( scene2, pointCloudWithPerPointPropertiesUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); tileset.style = new import__703.Cesium3DTileStyle({ color: 'color("red")' }); expect(renderOptions).toRender([255, 0, 0, 255]); tileset.style = new import__703.Cesium3DTileStyle({ color: "rgba(255, 0, 0, 0.005)" }); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[0]).toBeLessThan(255); expect(rgba[1]).toBe(0); expect(rgba[2]).toBe(0); expect(rgba[3]).toBe(255); }); tileset.style = void 0; expect(renderOptions).notToRender([0, 0, 0, 255]); }); }); it("renders pnts with show style", function() { return Cesium3DTilesTester_default.loadTileset( scene2, pointCloudWithPerPointPropertiesUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); tileset.style = new import__703.Cesium3DTileStyle({ show: false }); expect(renderOptions).toRender([0, 0, 0, 255]); tileset.style = new import__703.Cesium3DTileStyle({ show: true }); expect(renderOptions).notToRender([0, 0, 0, 255]); tileset.style = void 0; expect(renderOptions).notToRender([0, 0, 0, 255]); }); }); it("renders pnts with point size style", function() { return Cesium3DTilesTester_default.loadTileset( scene2, pointCloudWithPerPointPropertiesUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); scene2.camera.moveDown(5); Cesium3DTilesTester_default.expectRenderBlank(scene2, tileset); tileset.style = new import__703.Cesium3DTileStyle({ pointSize: 5 }); expect(renderOptions).notToRender([0, 0, 0, 255]); tileset.style = void 0; expect(renderOptions).toRender([0, 0, 0, 255]); }); }); it("renders pnts with style using point cloud semantics", function() { return Cesium3DTilesTester_default.loadTileset( scene2, pointCloudWithPerPointPropertiesUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); tileset.style = new import__703.Cesium3DTileStyle({ color: "vec4(${COLOR}[0], 0.0, 0.0, 1.0)" }); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[1]).toBe(0); expect(rgba[2]).toBe(0); expect(rgba[3]).toBe(255); }); tileset.style = new import__703.Cesium3DTileStyle({ show: "${POSITION}[0] > -50.0" }); expect(renderOptions).notToRender([0, 0, 0, 255]); tileset.style = new import__703.Cesium3DTileStyle({ show: "${POSITION}[0] > 50.0" }); expect(renderOptions).toRender([0, 0, 0, 255]); tileset.style = void 0; expect(renderOptions).notToRender([0, 0, 0, 255]); }); }); it("renders pnts with style using point cloud properties", function() { return Cesium3DTilesTester_default.loadTileset( scene2, pointCloudWithPerPointPropertiesUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); tileset.style = new import__703.Cesium3DTileStyle({ show: "${temperature} > 1.0" }); expect(renderOptions).toRender([0, 0, 0, 255]); tileset.style = new import__703.Cesium3DTileStyle({ show: "${temperature} > 0.1" }); expect(renderOptions).notToRender([0, 0, 0, 255]); tileset.style = void 0; expect(renderOptions).notToRender([0, 0, 0, 255]); }); }); it("renders pnts with style using point cloud properties (unicode)", function() { return Cesium3DTilesTester_default.loadTileset( scene2, pointCloudWithUnicodePropertyIdsUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); tileset.style = new import__703.Cesium3DTileStyle({ color: "color() * ${temperature_}" }); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBe(rgba[1]); expect(rgba[0]).toBe(rgba[2]); expect(rgba[0]).toBeGreaterThan(0); expect(rgba[0]).toBeLessThan(255); }); tileset.style = void 0; expect(renderOptions).notToRender([0, 0, 0, 255]); }); }); it("renders pnts with style and normals", function() { return Cesium3DTilesTester_default.loadTileset( scene2, pointCloudNormalsUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); tileset.style = new import__703.Cesium3DTileStyle({ color: 'color("red")', pointSize: 5 }); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[0]).toBeLessThan(255); expect(rgba[1]).toBe(0); expect(rgba[2]).toBe(0); expect(rgba[3]).toBe(255); }); tileset.style = void 0; expect(renderOptions).notToRender([0, 0, 0, 255]); }); }); it("throws if style references the NORMAL semantic for pnts without normals", function() { return Cesium3DTilesTester_default.loadTileset( scene2, pointCloudWithPerPointPropertiesUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); tileset.style = new import__703.Cesium3DTileStyle({ color: "${NORMAL}[0] > 0.5" }); expect(function() { scene2.renderForSpecs(); }).toThrowError(import__703.RuntimeError); }); }); it("picks", function() { return Cesium3DTilesTester_default.loadTileset(scene2, pointCloudRGBUrl).then( function(tileset) { const content = tileset.root.content; tileset.show = false; expect(scene2).toPickPrimitive(void 0); tileset.show = true; expect(scene2).toPickAndCall(function(result) { expect(result).toBeDefined(); expect(result.primitive).toBe(tileset); expect(result.content).toBe(content); }); } ); }); it("picks based on batchId", function() { return Cesium3DTilesTester_default.loadTileset( scene2, pointCloudBatchedUrl ).then(function(tileset) { let color; expect(scene2).toRenderAndCall(function(rgba) { color = rgba; }); expect(scene2).toPickAndCall(function(first) { expect(first).toBeDefined(); first.color = import__703.Color.clone(import__703.Color.YELLOW, first.color); expect(scene2).notToRender(color); first.show = false; expect(scene2).toPickAndCall(function(second) { expect(second).toBeDefined(); expect(second).not.toBe(first); }); }); }); }); it("point cloud without batch table works", function() { return Cesium3DTilesTester_default.loadTileset(scene2, pointCloudRGBUrl).then( function(tileset) { const content = tileset.root.content; expect(content.featuresLength).toBe(0); expect(content.innerContents).toBeUndefined(); expect(content.hasProperty(0, "name")).toBe(false); expect(function() { return content.getFeature(0); }).toThrowDeveloperError(); } ); }); it("batched point cloud works", function() { return Cesium3DTilesTester_default.loadTileset( scene2, pointCloudBatchedUrl ).then(function(tileset) { const content = tileset.root.content; expect(content.featuresLength).toBe(8); expect(content.innerContents).toBeUndefined(); expect(content.hasProperty(0, "name")).toBe(true); expect(content.getFeature(0)).toBeDefined(); }); }); it("point cloud with per-point properties work", function() { return Cesium3DTilesTester_default.loadTileset( scene2, pointCloudWithPerPointPropertiesUrl ).then(function(tileset) { const content = tileset.root.content; expect(content.featuresLength).toBe(0); expect(content.innerContents).toBeUndefined(); }); }); it("Supports back face culling when there are per-point normals", function() { if (webglStub) { return; } return Cesium3DTilesTester_default.loadTileset( scene2, pointCloudBatchedUrl ).then(function(tileset) { let pickedCountCulling = 0; let pickedCount = 0; tileset.pointCloudShading.backFaceCulling = true; expect(scene2).toDrillPickAndCall(function(pickedObjects) { pickedCountCulling = pickedObjects.length; }); tileset.pointCloudShading.backFaceCulling = false; expect(scene2).toDrillPickAndCall(function(pickedObjects) { pickedCount = pickedObjects.length; }); expect(pickedCount).toBeGreaterThan(pickedCountCulling); }); }); it("gets memory usage", function() { const promises = [ Cesium3DTilesTester_default.loadTileset(scene2, pointCloudNoColorUrl), Cesium3DTilesTester_default.loadTileset(scene2, pointCloudRGBUrl), Cesium3DTilesTester_default.loadTileset(scene2, pointCloudNormalsUrl), Cesium3DTilesTester_default.loadTileset( scene2, pointCloudQuantizedOctEncodedUrl ) ]; const expectedGeometryMemory = [ 1e3 * 12, // 3 floats (xyz) 1e3 * 15, // 3 floats (xyz), 3 bytes (rgb) 1e3 * 27, // 3 floats (xyz), 3 bytes (rgb), 3 floats (normal) 1e3 * 11 // 3 shorts (quantized xyz), 3 bytes (rgb), 2 bytes (oct-encoded normal) ]; return Promise.all(promises).then(function(tilesets) { const length2 = tilesets.length; for (let i = 0; i < length2; ++i) { const content = tilesets[i].root.content; expect(content.geometryByteLength).toEqual( expectedGeometryMemory[i] ); expect(content.texturesByteLength).toEqual(0); } }); }); it("picks from i3dm batch table", function() { setCamera(centerLongitude, centerLatitude, 25); return Cesium3DTilesTester_default.loadTileset( scene2, instancedWithBatchTableUrl ).then(function(tileset) { const content = tileset.root.content; tileset.show = false; expect(scene2).toPickPrimitive(void 0); tileset.show = true; expect(scene2).toPickAndCall(function(result) { expect(result).toBeDefined(); expect(result.primitive).toBe(tileset); expect(result.content).toBe(content); const featureId = result.featureId; expect(featureId).toBe(12); expect(content.hasProperty(featureId, "Height")).toBe(true); expect(content.getFeature(featureId)).toBeDefined(); }); }); }); it("gets memory usage for batch point cloud", function() { return Cesium3DTilesTester_default.loadTileset( scene2, pointCloudBatchedUrl ).then(function(tileset) { const content = tileset.root.content; const pointCloudGeometryMemory = 1e3 * 25; const binaryPropertyMemory = 8 * (12 + 4); const batchTexturesByteLength = content.featuresLength * 4; const pickTexturesByteLength = content.featuresLength * 4; expect(content.geometryByteLength).toEqual(pointCloudGeometryMemory); expect(content.texturesByteLength).toEqual(0); expect(content.batchTableByteLength).toEqual(binaryPropertyMemory); content.getFeature(0).color = import__703.Color.RED; scene2.renderForSpecs(); expect(content.geometryByteLength).toEqual(pointCloudGeometryMemory); expect(content.texturesByteLength).toEqual(0); expect(content.batchTableByteLength).toEqual( binaryPropertyMemory + batchTexturesByteLength ); scene2.pickForSpecs(); expect(content.geometryByteLength).toEqual(pointCloudGeometryMemory); expect(content.texturesByteLength).toEqual(0); expect(content.batchTableByteLength).toEqual( binaryPropertyMemory + batchTexturesByteLength + pickTexturesByteLength ); }); }); }); describe("point cloud attenuation", function() { let noAttenuationPixelCount; function attenuationTest(postLoadCallback) { const scene3 = createScene_default({ canvas: createCanvas_default(10, 10) }); noAttenuationPixelCount = scene3.logarithmicDepthBuffer ? 20 : 16; const center = new import__703.Cartesian3.fromRadians( centerLongitude, centerLatitude, 5 ); scene3.camera.lookAt(center, new import__703.HeadingPitchRange(0, -1.57, 5)); scene3.postProcessStages.fxaa.enabled = false; scene3.camera.zoomIn(6); return Cesium3DTilesTester_default.loadTileset( scene3, pointCloudNoColorUrl ).then(function(tileset) { tileset.pointCloudShading.eyeDomeLighting = false; tileset.root.refine = import__703.Cesium3DTileRefine.REPLACE; postLoadCallback(scene3, tileset); scene3.destroyForSpecs(); }); } it("attenuates points based on geometric error", function() { return attenuationTest(function(scene3, tileset) { tileset.pointCloudShading.attenuation = true; tileset.pointCloudShading.geometricErrorScale = 1; tileset.pointCloudShading.maximumAttenuation = void 0; tileset.pointCloudShading.baseResolution = void 0; tileset.maximumScreenSpaceError = 16; expect(scene3).toRenderPixelCountAndCall(function(pixelCount) { expect(pixelCount).toBeGreaterThan(noAttenuationPixelCount); }); }); }); it("modulates attenuation using the tileset screen space error", function() { return attenuationTest(function(scene3, tileset) { tileset.pointCloudShading.attenuation = true; tileset.pointCloudShading.geometricErrorScale = 1; tileset.pointCloudShading.maximumAttenuation = void 0; tileset.pointCloudShading.baseResolution = void 0; tileset.maximumScreenSpaceError = 1; expect(scene3).toRenderPixelCountAndCall(function(pixelCount) { expect(pixelCount).toEqual(noAttenuationPixelCount); }); }); }); it("modulates attenuation using the maximumAttenuation parameter", function() { return attenuationTest(function(scene3, tileset) { tileset.pointCloudShading.attenuation = true; tileset.pointCloudShading.geometricErrorScale = 1; tileset.pointCloudShading.maximumAttenuation = 1; tileset.pointCloudShading.baseResolution = void 0; tileset.maximumScreenSpaceError = 16; expect(scene3).toRenderPixelCountAndCall(function(pixelCount) { expect(pixelCount).toEqual(noAttenuationPixelCount); }); }); }); it("modulates attenuation using the baseResolution parameter", function() { return attenuationTest(function(scene3, tileset) { tileset.pointCloudShading.attenuation = true; tileset.pointCloudShading.geometricErrorScale = 1; tileset.pointCloudShading.maximumAttenuation = void 0; tileset.pointCloudShading.baseResolution = 0.2; tileset.maximumScreenSpaceError = 16; expect(scene3).toRenderPixelCountAndCall(function(pixelCount) { expect(pixelCount).toEqual(noAttenuationPixelCount); }); }); }); it("modulates attenuation using the geometricErrorScale parameter", function() { return attenuationTest(function(scene3, tileset) { tileset.pointCloudShading.attenuation = true; tileset.pointCloudShading.geometricErrorScale = 0.2; tileset.pointCloudShading.maximumAttenuation = void 0; tileset.pointCloudShading.baseResolution = 1; tileset.maximumScreenSpaceError = 1; expect(scene3).toRenderPixelCountAndCall(function(pixelCount) { expect(pixelCount).toEqual(noAttenuationPixelCount); }); }); }); it("attenuates points based on geometric error in 2D", function() { return attenuationTest(function(scene3, tileset) { scene3.morphTo2D(0); tileset.pointCloudShading.attenuation = true; tileset.pointCloudShading.geometricErrorScale = 1; tileset.pointCloudShading.maximumAttenuation = void 0; tileset.pointCloudShading.baseResolution = void 0; tileset.maximumScreenSpaceError = 16; expect(scene3).toRenderPixelCountAndCall(function(pixelCount) { expect(pixelCount).toBeGreaterThan(noAttenuationPixelCount); }); }); }); }); describe("glTF", function() { beforeEach(function() { setCamera(centerLongitude, centerLatitude, 100); }); it("becomes ready with glb", async function() { const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, glbContentUrl ); expect(tileset.root.contentReady).toBeTrue(); expect(tileset.root.content).toBeDefined(); }); it("becomes ready with glTF", async function() { const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, gltfContentUrl ); expect(tileset.root.contentReady).toBeTrue(); expect(tileset.root.content).toBeDefined(); }); it("renders glb content", function() { return Cesium3DTilesTester_default.loadTileset(scene2, glbContentUrl).then( function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); } ); }); it("renders glTF content", function() { return Cesium3DTilesTester_default.loadTileset( scene2, buildingsMetadataUrl ).then(function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); }); }); it("throws when calling getFeature without a feature table", function() { return Cesium3DTilesTester_default.loadTileset(scene2, gltfContentUrl).then( function(tileset) { const content = tileset.root.content; expect(function() { content.getFeature(0); }).toThrowDeveloperError(); } ); }); it("throws when calling getFeature with invalid index", function() { return Cesium3DTilesTester_default.loadTileset( scene2, buildingsMetadataUrl ).then(function(tileset) { const content = tileset.root.content; expect(function() { content.getFeature(-1); }).toThrowDeveloperError(); expect(function() { content.getFeature(1e3); }).toThrowDeveloperError(); expect(function() { content.getFeature(); }).toThrowDeveloperError(); }); }); it("picks from glTF", function() { return Cesium3DTilesTester_default.loadTileset(scene2, gltfContentUrl).then( function(tileset) { const content = tileset.root.content; tileset.show = false; expect(scene2).toPickPrimitive(void 0); tileset.show = true; expect(scene2).toPickAndCall(function(result) { expect(result).toBeDefined(); expect(result.primitive).toBe(tileset); expect(result.content).toBe(content); expect(result.featureId).toBeUndefined(); expect(content.hasProperty(0, "id")).toBe(false); expect(function() { return content.getFeature(0); }).toThrowDeveloperError(); }); } ); }); it("picks from glTF feature table", function() { return Cesium3DTilesTester_default.loadTileset( scene2, buildingsMetadataUrl ).then(function(tileset) { const content = tileset.root.content; tileset.show = false; expect(scene2).toPickPrimitive(void 0); tileset.show = true; expect(scene2).toPickAndCall(function(result) { expect(result).toBeDefined(); expect(result.primitive).toBe(tileset); expect(result.content).toBe(content); const featureId = result.featureId; expect(featureId).toBe(0); expect(content.batchTable).toBeDefined(); expect(content.hasProperty(featureId, "id")).toBe(true); expect(content.getFeature(featureId)).toBeDefined(); }); }); }); it("destroys glTF content", function() { return Cesium3DTilesTester_default.tileDestroys(scene2, buildingsMetadataUrl); }); }); describe("tileset.preloadWhenHidden", function() { beforeEach(function() { setCamera(centerLongitude, centerLatitude, 15); }); it("renders correctly when tileset starts hidden and tileset.preloadWhenHidden is true", function() { const tilesetOptions = { show: false, preloadWhenHidden: true }; return Cesium3DTilesTester_default.loadTileset( scene2, noBatchIdsUrl, tilesetOptions ).then(function(tileset) { Cesium3DTilesTester_default.expectRender(scene2, tileset); }); }); it("does not render when tileset starts hidden and tileset.preloadWhenHidden is false", function() { const tilesetOptions = { show: false, preloadWhenHidden: false }; return Cesium3DTilesTester_default.loadTileset( scene2, noBatchIdsUrl, tilesetOptions ).then(function(tileset) { Cesium3DTilesTester_default.expectRenderBlank(scene2, tileset); }); }); }); describe("clipping planes", function() { beforeEach(function() { setCamera(centerLongitude, centerLatitude, 15); }); it("Links model to tileset clipping planes based on bounding volume clipping", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(tileset) { const tile = tileset.root; const content = tile.content; const model = content._model; const passOptions = import__703.Cesium3DTilePass.getPassOptions( import__703.Cesium3DTilePass.RENDER ); expect(model.clippingPlanes).toBeUndefined(); const clippingPlaneCollection = new import__703.ClippingPlaneCollection({ planes: [new import__703.ClippingPlane(import__703.Cartesian3.UNIT_X, 0)] }); tileset.clippingPlanes = clippingPlaneCollection; clippingPlaneCollection.update(scene2.frameState); tile.update(tileset, scene2.frameState, passOptions); expect(model.clippingPlanes).toBeDefined(); expect(model.clippingPlanes).toBe(tileset.clippingPlanes); tile._isClipped = false; tile.update(tileset, scene2.frameState, passOptions); expect(model.clippingPlanes).toBeUndefined(); } ); }); it("Links model to tileset clipping planes if tileset clipping planes are reassigned", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(tileset) { const tile = tileset.root; const model = tile.content._model; const passOptions = import__703.Cesium3DTilePass.getPassOptions( import__703.Cesium3DTilePass.RENDER ); expect(model.clippingPlanes).toBeUndefined(); const clippingPlaneCollection = new import__703.ClippingPlaneCollection({ planes: [new import__703.ClippingPlane(import__703.Cartesian3.UNIT_X, 0)] }); tileset.clippingPlanes = clippingPlaneCollection; clippingPlaneCollection.update(scene2.frameState); tile.update(tileset, scene2.frameState, passOptions); expect(model.clippingPlanes).toBeDefined(); expect(model.clippingPlanes).toBe(tileset.clippingPlanes); const newClippingPlaneCollection = new import__703.ClippingPlaneCollection({ planes: [new import__703.ClippingPlane(import__703.Cartesian3.UNIT_X, 0)] }); tileset.clippingPlanes = newClippingPlaneCollection; newClippingPlaneCollection.update(scene2.frameState); expect(model.clippingPlanes).not.toBe(tileset.clippingPlanes); tile.update(tileset, scene2.frameState, passOptions); expect(model.clippingPlanes).toBe(tileset.clippingPlanes); } ); }); it("replaces clipping planes collection with one of the same length", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(tileset) { const tile = tileset.root; const model = tile.content._model; const passOptions = import__703.Cesium3DTilePass.getPassOptions( import__703.Cesium3DTilePass.RENDER ); expect(model.clippingPlanes).toBeUndefined(); spyOn(model, "resetDrawCommands"); const clippingPlaneCollection = new import__703.ClippingPlaneCollection({ planes: [new import__703.ClippingPlane(import__703.Cartesian3.UNIT_X, 0)] }); tileset.clippingPlanes = clippingPlaneCollection; tile.update(tileset, scene2.frameState, passOptions); expect(model.resetDrawCommands).toHaveBeenCalled(); expect(model.resetDrawCommands.calls.count()).toBe(1); const newClippingPlaneCollection = new import__703.ClippingPlaneCollection({ planes: [new import__703.ClippingPlane(import__703.Cartesian3.UNIT_X, 0)] }); tileset.clippingPlanes = newClippingPlaneCollection; tile.update(tileset, scene2.frameState, passOptions); expect(model.resetDrawCommands.calls.count()).toBe(2); } ); }); it("clipping planes selectively disable rendering", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(tileset) { let color; expect(scene2).toRenderAndCall(function(rgba) { color = rgba; }); const clipPlane = new import__703.ClippingPlane(import__703.Cartesian3.UNIT_Z, -10); tileset.clippingPlanes = new import__703.ClippingPlaneCollection({ planes: [clipPlane] }); expect(scene2).notToRender(color); clipPlane.distance = 5; expect(scene2).toRender(color); } ); }); it("clipping planes apply edge styling", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(tileset) { let color; expect(scene2).toRenderAndCall(function(rgba) { color = rgba; }); const clipPlane = new import__703.ClippingPlane(import__703.Cartesian3.UNIT_Z, -10); tileset.clippingPlanes = new import__703.ClippingPlaneCollection({ planes: [clipPlane], modelMatrix: import__703.Transforms.eastNorthUpToFixedFrame( tileset.boundingSphere.center ), edgeWidth: 20, edgeColor: import__703.Color.RED }); expect(scene2).notToRender(color); } ); }); it("clipping planes union regions (Uint8)", function() { spyOn(import__703.ClippingPlaneCollection, "useFloatTexture").and.returnValue( false ); return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(tileset) { let color; expect(scene2).toRenderAndCall(function(rgba) { color = rgba; }); tileset.clippingPlanes = new import__703.ClippingPlaneCollection({ planes: [ new import__703.ClippingPlane(import__703.Cartesian3.UNIT_Z, 0), new import__703.ClippingPlane(import__703.Cartesian3.UNIT_X, 0) ], modelMatrix: import__703.Transforms.eastNorthUpToFixedFrame( tileset.boundingSphere.center ), unionClippingRegions: true }); expect(scene2).notToRender(color); tileset.clippingPlanes.unionClippingRegions = false; expect(scene2).toRender(color); } ); }); it("clipping planes union regions (Float)", function() { if (!import__703.ClippingPlaneCollection.useFloatTexture(scene2.context)) { return; } return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl).then( function(tileset) { let color; expect(scene2).toRenderAndCall(function(rgba) { color = rgba; }); tileset.clippingPlanes = new import__703.ClippingPlaneCollection({ planes: [ new import__703.ClippingPlane(import__703.Cartesian3.UNIT_Z, -10), new import__703.ClippingPlane(import__703.Cartesian3.UNIT_X, 1) ], modelMatrix: import__703.Transforms.eastNorthUpToFixedFrame( tileset.boundingSphere.center ), unionClippingRegions: true }); expect(scene2).notToRender(color); tileset.clippingPlanes.unionClippingRegions = false; expect(scene2).toRender(color); } ); }); }); describe("clipping polygons", function() { const positions = import__703.Cartesian3.fromRadiansArray([ centerLongitude + 1e-3, centerLatitude + 1e-3, centerLongitude + 1e-3, centerLatitude - 1e-3, centerLongitude - 1e-3, centerLatitude - 1e-3, centerLongitude - 1e-3, centerLatitude + 1e-3 ]); let polygon; beforeEach(function() { setCamera(centerLongitude, centerLatitude, 15); polygon = new import__703.ClippingPolygon({ positions }); }); it("clipping planes selectively disable rendering", async function() { if (!scene2.context.webgl2) { return; } const tileset = await Cesium3DTilesTester_default.loadTileset( scene2, withBatchTableUrl ); let color; expect(scene2).toRenderAndCall(function(rgba) { color = rgba; }); const collection = new import__703.ClippingPolygonCollection({ polygons: [polygon] }); tileset.clippingPolygons = collection; expect(scene2).notToRender(color); collection.inverse = true; expect(scene2).toRender(color); }); }); describe("classification", function() { let globePrimitive; let tilesetPrimitive; let reusableGlobePrimitive; let reusableTilesetPrimitive; function createPrimitive(rectangle, pass) { let renderState; if (pass === import__703.Pass.CESIUM_3D_TILE) { renderState = import__703.RenderState.fromCache({ stencilTest: import__703.StencilConstants.setCesium3DTileBit(), stencilMask: import__703.StencilConstants.CESIUM_3D_TILE_MASK, depthTest: { enabled: true } }); } const depthColorAttribute = import__703.ColorGeometryInstanceAttribute.fromColor( new import__703.Color(0, 0, 0, 1) ); return new import__703.Primitive({ geometryInstances: new import__703.GeometryInstance({ geometry: new import__703.RectangleGeometry({ ellipsoid: import__703.Ellipsoid.WGS84, rectangle }), id: "depth rectangle", attributes: { color: depthColorAttribute } }), appearance: new import__703.PerInstanceColorAppearance({ translucent: false, flat: true, renderState }), asynchronous: false }); } function MockPrimitive(primitive, pass) { this._primitive = primitive; this._pass = pass; this.show = true; } MockPrimitive.prototype.update = function(frameState2) { if (!this.show) { return; } const commandList = frameState2.commandList; const startLength = commandList.length; this._primitive.update(frameState2); for (let i = startLength; i < commandList.length; ++i) { const command = commandList[i]; command.pass = this._pass; } }; MockPrimitive.prototype.isDestroyed = function() { return false; }; MockPrimitive.prototype.destroy = function() { return (0, import__703.destroyObject)(this); }; let modelMatrix; beforeAll(function() { scene2 = createScene_default(); const translation = import__703.Ellipsoid.WGS84.geodeticSurfaceNormalCartographic( new import__703.Cartographic(centerLongitude, centerLatitude) ); import__703.Cartesian3.multiplyByScalar(translation, -5, translation); modelMatrix = import__703.Matrix4.fromTranslation(translation); const offset = import__703.Math.toRadians(0.01); const rectangle = new import__703.Rectangle( centerLongitude - offset, centerLatitude - offset, centerLongitude + offset, centerLatitude + offset ); reusableGlobePrimitive = createPrimitive(rectangle, import__703.Pass.GLOBE); reusableTilesetPrimitive = createPrimitive( rectangle, import__703.Pass.CESIUM_3D_TILE ); }); beforeEach(function() { setCamera(centerLongitude, centerLatitude, 15); globePrimitive = new MockPrimitive(reusableGlobePrimitive, import__703.Pass.GLOBE); tilesetPrimitive = new MockPrimitive( reusableTilesetPrimitive, import__703.Pass.CESIUM_3D_TILE ); scene2.primitives.add(globePrimitive); scene2.primitives.add(tilesetPrimitive); }); afterEach(function() { scene2.primitives.removeAll(); globePrimitive = globePrimitive && !globePrimitive.isDestroyed() && globePrimitive.destroy(); tilesetPrimitive = tilesetPrimitive && !tilesetPrimitive.isDestroyed() && tilesetPrimitive.destroy(); }); afterAll(function() { reusableGlobePrimitive.destroy(); reusableTilesetPrimitive.destroy(); }); it("classifies 3D Tiles", function() { setCamera(centerLongitude, centerLatitude, 15); return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl, { classificationType: import__703.ClassificationType.CESIUM_3D_TILE, modelMatrix }).then(function(tileset) { globePrimitive.show = false; tilesetPrimitive.show = true; Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); globePrimitive.show = true; tilesetPrimitive.show = false; Cesium3DTilesTester_default.expectRenderBlank(scene2, tileset); globePrimitive.show = true; tilesetPrimitive.show = true; }); }); it("classifies globe", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl, { classificationType: import__703.ClassificationType.TERRAIN, modelMatrix }).then(function(tileset) { globePrimitive.show = false; tilesetPrimitive.show = true; Cesium3DTilesTester_default.expectRenderBlank(scene2, tileset); globePrimitive.show = true; tilesetPrimitive.show = false; Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); globePrimitive.show = true; tilesetPrimitive.show = true; }); }); it("classifies both 3D Tiles and globe", function() { return Cesium3DTilesTester_default.loadTileset(scene2, withBatchTableUrl, { classificationType: import__703.ClassificationType.BOTH, modelMatrix }).then(function(tileset) { globePrimitive.show = false; tilesetPrimitive.show = true; Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); globePrimitive.show = true; tilesetPrimitive.show = false; Cesium3DTilesTester_default.expectRenderTileset(scene2, tileset); globePrimitive.show = true; tilesetPrimitive.show = true; }); }); }); describe("metadata", function() { let metadataClass; let groupMetadata; let contentMetadataClass; let contentMetadata; beforeAll(function() { metadataClass = import__703.MetadataClass.fromJson({ id: "test", class: { properties: { name: { type: "STRING" }, height: { type: "SCALAR", componentType: "FLOAT32" } } } }); groupMetadata = new import__703.GroupMetadata({ id: "testGroup", group: { properties: { name: "Test Group", height: 35.6 } }, class: metadataClass }); contentMetadataClass = import__703.MetadataClass.fromJson({ id: "contentTest", class: { properties: { author: { type: "STRING" }, color: { type: "VEC3", componentType: "UINT8" } } } }); contentMetadata = new import__703.ContentMetadata({ content: { properties: { author: "Test Author", color: [255, 0, 0] } }, class: contentMetadataClass }); }); beforeEach(function() { setCamera(centerLongitude, centerLatitude, 15); }); it("assigns group metadata", function() { return Cesium3DTilesTester_default.loadTileset( scene2, withoutBatchTableUrl ).then(function(tileset) { const content = tileset.root.content; content.group = new import__703.Cesium3DContentGroup({ metadata: groupMetadata }); expect(content.group.metadata).toBe(groupMetadata); }); }); it("assigns metadata", function() { return Cesium3DTilesTester_default.loadTileset( scene2, withoutBatchTableUrl ).then(function(tileset) { const content = tileset.root.content; content.metadata = contentMetadata; expect(content.metadata).toBe(contentMetadata); }); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/ModelAnimationChannelSpec.js var import__704 = __toESM(require_Cesium(), 1); describe("Scene/Model/ModelAnimationChannel", function() { const AnimatedPropertyType = import__704.ModelComponents.AnimatedPropertyType; const times = [0, 0.25, 0.5, 1]; const translationPoints = [ import__704.Cartesian3.ZERO, new import__704.Cartesian3(1, 0, 0), new import__704.Cartesian3(1, 1, 0), new import__704.Cartesian3(0, 1, 0) ]; const rotationPoints = [ import__704.Quaternion.IDENTITY, new import__704.Quaternion(0.707, 0, 0.707, 0), new import__704.Quaternion(0, 0, 1, 0), new import__704.Quaternion(0.707, 0, -0.707, 0) ]; const scalePoints = [ new import__704.Cartesian3(1, 1, 1), new import__704.Cartesian3(1, 2, 1), new import__704.Cartesian3(1, 1, 2), new import__704.Cartesian3(2, 1, 1) ]; const weightPoints = [0, 0, 0.5, 0.25, 1, 0.5, 0.5, 0.25]; const mockNode = { translation: import__704.Cartesian3.ZERO, rotation: import__704.Quaternion.IDENTITY, scale: new import__704.Cartesian3(1, 1, 1) }; const scratchTransform = new import__704.Matrix4(); const transform = import__704.Matrix4.clone(import__704.Matrix4.IDENTITY); const transformToRoot = import__704.Matrix4.clone(import__704.Matrix4.IDENTITY); const mockSceneGraph = { computedModelMatrix: import__704.Matrix4.clone(import__704.Matrix4.IDENTITY), components: { upAxis: import__704.Axis.Y, forwardAxis: import__704.Axis.Z } }; const runtimeAnimation = { model: { clampAnimations: true } }; let runtimeNode; function createMockChannel(mockNode2, mockSampler, path) { const mockTarget = { node: mockNode2, path }; const mockChannel = { sampler: mockSampler, target: mockTarget }; return mockChannel; } beforeEach(function() { runtimeNode = new import__704.ModelRuntimeNode({ node: mockNode, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [] }); }); it("throws for undefined channel", function() { expect(function() { return new import__704.ModelAnimationChannel({ channel: void 0, runtimeAnimation, runtimeNode }); }).toThrowDeveloperError(); }); it("throws for undefined runtimeAnimation", function() { expect(function() { return new import__704.ModelAnimationChannel({ channel: {}, runtimeAnimation: void 0, runtimeNode }); }).toThrowDeveloperError(); }); it("throws for undefined runtimeNode", function() { expect(function() { return new import__704.ModelAnimationChannel({ channel: {}, runtimeAnimation, runtimeNode: void 0 }); }).toThrowDeveloperError(); }); it("constructs constant spline", function() { const mockSampler = { input: [0], interpolation: import__704.InterpolationType.LINEAR, output: [import__704.Cartesian3.ZERO] }; const mockChannel = createMockChannel( mockNode, mockSampler, AnimatedPropertyType.TRANSLATION ); const runtimeChannel = new import__704.ModelAnimationChannel({ channel: mockChannel, runtimeAnimation, runtimeNode }); expect(runtimeChannel.channel).toBe(mockChannel); expect(runtimeChannel.runtimeAnimation).toBe(runtimeAnimation); expect(runtimeChannel.runtimeNode).toBe(runtimeNode); expect(runtimeChannel.splines.length).toBe(1); expect(runtimeChannel.splines[0] instanceof import__704.ConstantSpline).toBe(true); }); it("constructs linear spline", function() { const mockSampler = { input: times, interpolation: import__704.InterpolationType.LINEAR, output: translationPoints }; const mockChannel = createMockChannel( mockNode, mockSampler, AnimatedPropertyType.TRANSLATION ); const runtimeChannel = new import__704.ModelAnimationChannel({ channel: mockChannel, runtimeAnimation, runtimeNode }); expect(runtimeChannel.channel).toBe(mockChannel); expect(runtimeChannel.runtimeAnimation).toBe(runtimeAnimation); expect(runtimeChannel.runtimeNode).toBe(runtimeNode); expect(runtimeChannel.splines.length).toBe(1); expect(runtimeChannel.splines[0] instanceof import__704.LinearSpline).toBe(true); }); it("constructs quaternion spline", function() { const mockSampler = { input: times, interpolation: import__704.InterpolationType.LINEAR, output: rotationPoints }; const mockChannel = createMockChannel( mockNode, mockSampler, AnimatedPropertyType.ROTATION ); const runtimeChannel = new import__704.ModelAnimationChannel({ channel: mockChannel, runtimeAnimation, runtimeNode }); expect(runtimeChannel.channel).toBe(mockChannel); expect(runtimeChannel.runtimeAnimation).toBe(runtimeAnimation); expect(runtimeChannel.runtimeNode).toBe(runtimeNode); expect(runtimeChannel.splines.length).toBe(1); expect(runtimeChannel.splines[0] instanceof import__704.QuaternionSpline).toBe(true); }); it("constructs stepped spline", function() { const mockSampler = { input: times, interpolation: import__704.InterpolationType.STEP, output: scalePoints }; const mockChannel = createMockChannel( mockNode, mockSampler, AnimatedPropertyType.SCALE ); const runtimeChannel = new import__704.ModelAnimationChannel({ channel: mockChannel, runtimeAnimation, runtimeNode }); expect(runtimeChannel.channel).toBe(mockChannel); expect(runtimeChannel.runtimeAnimation).toBe(runtimeAnimation); expect(runtimeChannel.runtimeNode).toBe(runtimeNode); expect(runtimeChannel.splines.length).toBe(1); expect(runtimeChannel.splines[0] instanceof import__704.SteppedSpline).toBe(true); }); it("constructs cubic spline", function() { const cubicTimes = [0, 0.5, 1]; const cubicPoints = [ import__704.Cartesian3.ZERO, new import__704.Cartesian3(1, 1, 1), new import__704.Cartesian3(2, 2, 2), new import__704.Cartesian3(3, 3, 3), new import__704.Cartesian3(4, 4, 4), new import__704.Cartesian3(5, 5, 5), new import__704.Cartesian3(6, 6, 6), new import__704.Cartesian3(7, 7, 7), new import__704.Cartesian3(8, 8, 8) ]; const mockSampler = { input: cubicTimes, interpolation: import__704.InterpolationType.CUBICSPLINE, output: cubicPoints }; const mockChannel = createMockChannel( mockNode, mockSampler, AnimatedPropertyType.TRANSLATION ); const runtimeChannel = new import__704.ModelAnimationChannel({ channel: mockChannel, runtimeAnimation, runtimeNode }); expect(runtimeChannel.channel).toBe(mockChannel); expect(runtimeChannel.runtimeAnimation).toBe(runtimeAnimation); expect(runtimeChannel.runtimeNode).toBe(runtimeNode); expect(runtimeChannel.splines.length).toBe(1); expect(runtimeChannel.splines[0] instanceof import__704.HermiteSpline).toBe(true); const spline = runtimeChannel.splines[0]; const expectedInTangents = [cubicPoints[3], cubicPoints[6]]; const expectedOutTangents = [cubicPoints[2], cubicPoints[5]]; const expectedPoints = [cubicPoints[1], cubicPoints[4], cubicPoints[7]]; expect(spline.inTangents).toEqual(expectedInTangents); expect(spline.outTangents).toEqual(expectedOutTangents); expect(spline.points).toEqual(expectedPoints); }); it("constructs weight splines", function() { const mockSampler = { input: times, interpolation: import__704.InterpolationType.LINEAR, output: weightPoints }; runtimeNode._morphWeights = [0, 0]; const mockChannel = createMockChannel( mockNode, mockSampler, AnimatedPropertyType.WEIGHTS ); const runtimeChannel = new import__704.ModelAnimationChannel({ channel: mockChannel, runtimeAnimation, runtimeNode }); expect(runtimeChannel.channel).toBe(mockChannel); expect(runtimeChannel.runtimeAnimation).toBe(runtimeAnimation); expect(runtimeChannel.runtimeNode).toBe(runtimeNode); expect(runtimeChannel.splines.length).toBe(2); expect(runtimeChannel.splines[0] instanceof import__704.LinearSpline).toBe(true); expect(runtimeChannel.splines[1] instanceof import__704.LinearSpline).toBe(true); }); it("constructs cubic weight splines", function() { const cubicWeightTimes = [0, 0.5]; const cubicWeightPoints = [ 0, 0, // in-tangents of both morph targets, first keyframe 0, 0, // values of both morph targets, first keyframe 0.2, -0.5, // out-tangents of both morph targets, first keyframe 0.3, 0, // in-tangents, second keyframe 1, 0.5, // values, second keyframe 0, 0 ]; const mockSampler = { input: cubicWeightTimes, interpolation: import__704.InterpolationType.CUBICSPLINE, output: cubicWeightPoints }; runtimeNode._morphWeights = [0, 0]; const mockChannel = createMockChannel( mockNode, mockSampler, AnimatedPropertyType.WEIGHTS ); const runtimeChannel = new import__704.ModelAnimationChannel({ channel: mockChannel, runtimeAnimation, runtimeNode }); expect(runtimeChannel.channel).toBe(mockChannel); expect(runtimeChannel.runtimeAnimation).toBe(runtimeAnimation); expect(runtimeChannel.runtimeNode).toBe(runtimeNode); expect(runtimeChannel.splines.length).toBe(2); const firstSpline = runtimeChannel.splines[0]; expect(firstSpline instanceof import__704.HermiteSpline).toBe(true); expect(firstSpline.inTangents).toEqual([0.3]); expect(firstSpline.points).toEqual([0, 1]); expect(firstSpline.outTangents).toEqual([0.2]); const secondSpline = runtimeChannel.splines[1]; expect(secondSpline instanceof import__704.HermiteSpline).toBe(true); expect(secondSpline.inTangents).toEqual([0]); expect(secondSpline.points).toEqual([0, 0.5]); expect(secondSpline.outTangents).toEqual([-0.5]); }); it("animates node translation", function() { const mockSampler = { input: times, interpolation: import__704.InterpolationType.LINEAR, output: translationPoints }; const mockChannel = createMockChannel( mockNode, mockSampler, AnimatedPropertyType.TRANSLATION ); const runtimeChannel = new import__704.ModelAnimationChannel({ channel: mockChannel, runtimeAnimation, runtimeNode }); expect(runtimeNode.translation).toEqual(import__704.Cartesian3.ZERO); expect(runtimeNode.transform).toEqual(import__704.Matrix4.IDENTITY); let time2 = times[1]; let expected = import__704.Cartesian3.clone(translationPoints[1]); runtimeChannel.animate(time2); expect(runtimeNode.translation).toEqual(expected); expect(runtimeNode.transform).toEqual( import__704.Matrix4.fromTranslation(expected, scratchTransform) ); time2 = (times[1] + times[2]) / 2; expected = import__704.Cartesian3.lerp( translationPoints[1], translationPoints[2], 0.5, expected ); runtimeChannel.animate(time2); expect(runtimeNode.translation).toEqual(expected); expect(runtimeNode.transform).toEqual( import__704.Matrix4.fromTranslation(expected, scratchTransform) ); }); it("animates node rotation", function() { const mockSampler = { input: times, interpolation: import__704.InterpolationType.LINEAR, output: rotationPoints }; const mockChannel = createMockChannel( mockNode, mockSampler, AnimatedPropertyType.ROTATION ); const runtimeChannel = new import__704.ModelAnimationChannel({ channel: mockChannel, runtimeAnimation, runtimeNode }); expect(runtimeNode.rotation).toEqual(import__704.Quaternion.IDENTITY); expect(runtimeNode.transform).toEqual(import__704.Matrix4.IDENTITY); let time2 = times[1]; let expected = import__704.Quaternion.clone(rotationPoints[1]); let expectedMatrix = import__704.Matrix3.fromQuaternion(expected); runtimeChannel.animate(time2); expect(runtimeNode.rotation).toEqual(expected); expect( runtimeNode.transform.equalsEpsilon( import__704.Matrix4.fromRotation(expectedMatrix, scratchTransform), import__704.Math.EPSILON6 ) ).toBe(true); time2 = (times[1] + times[2]) / 2; expected = import__704.Quaternion.slerp( rotationPoints[1], rotationPoints[2], 0.5, expected ); expectedMatrix = import__704.Matrix3.fromQuaternion(expected, expectedMatrix); runtimeChannel.animate(time2); expect( runtimeNode.rotation.equalsEpsilon(expected, import__704.Math.EPSILON6) ).toEqual(true); expect( runtimeNode.transform.equalsEpsilon( import__704.Matrix4.fromRotation(expectedMatrix, scratchTransform), import__704.Math.EPSILON6 ) ); }); it("animates node scale", function() { const mockSampler = { input: times, interpolation: import__704.InterpolationType.LINEAR, output: scalePoints }; const mockChannel = createMockChannel( mockNode, mockSampler, AnimatedPropertyType.SCALE ); const runtimeChannel = new import__704.ModelAnimationChannel({ channel: mockChannel, runtimeAnimation, runtimeNode }); let expected = new import__704.Cartesian3(1, 1, 1); expect(runtimeNode.scale).toEqual(expected); expect(runtimeNode.transform).toEqual(import__704.Matrix4.IDENTITY); let time2 = times[1]; expected = import__704.Cartesian3.clone(scalePoints[1], expected); runtimeChannel.animate(time2); expect(runtimeNode.scale).toEqual(expected); expect(runtimeNode.transform).toEqual( import__704.Matrix4.fromScale(expected, scratchTransform) ); time2 = (times[1] + times[2]) / 2; expected = import__704.Cartesian3.lerp(scalePoints[1], scalePoints[2], 0.5, expected); runtimeChannel.animate(time2); expect(runtimeNode.scale).toEqual(expected); expect(runtimeNode.transform).toEqual( import__704.Matrix4.fromScale(expected, scratchTransform) ); }); it("animates node weights", function() { const mockSampler = { input: times, interpolation: import__704.InterpolationType.LINEAR, output: weightPoints }; runtimeNode._morphWeights = [0, 0]; const mockChannel = createMockChannel( mockNode, mockSampler, AnimatedPropertyType.WEIGHTS ); const runtimeChannel = new import__704.ModelAnimationChannel({ channel: mockChannel, runtimeAnimation, runtimeNode }); let expected = [0, 0]; expect(runtimeNode.morphWeights).toEqual(expected); let time2 = times[1]; expected = weightPoints.slice(2, 4); runtimeChannel.animate(time2); expect(runtimeNode.morphWeights).toEqual(expected); time2 = (times[1] + times[2]) / 2; expected[0] = (weightPoints[2] + weightPoints[4]) / 2; expected[1] = (weightPoints[3] + weightPoints[5]) / 2; runtimeChannel.animate(time2); expect(runtimeNode.morphWeights).toEqual(expected); }); it("clamps animations", function() { const mockSampler = { input: times, interpolation: import__704.InterpolationType.LINEAR, output: translationPoints }; const mockChannel = createMockChannel( mockNode, mockSampler, AnimatedPropertyType.TRANSLATION ); const runtimeChannel = new import__704.ModelAnimationChannel({ channel: mockChannel, runtimeAnimation, runtimeNode }); expect(runtimeNode.translation).toEqual(import__704.Cartesian3.ZERO); expect(runtimeNode.transform).toEqual(import__704.Matrix4.IDENTITY); let time2 = 10; let expected = import__704.Cartesian3.clone(translationPoints[3]); runtimeChannel.animate(time2); expect(runtimeNode.translation).toEqual(expected); expect(runtimeNode.transform).toEqual( import__704.Matrix4.fromTranslation(expected, scratchTransform) ); time2 = -10; expected = import__704.Cartesian3.clone(translationPoints[0]); runtimeChannel.animate(time2); expect(runtimeNode.translation).toEqual(expected); expect(runtimeNode.transform).toEqual( import__704.Matrix4.fromTranslation(expected, scratchTransform) ); }); it("wraps animations", function() { const mockSampler = { input: times, interpolation: import__704.InterpolationType.LINEAR, output: translationPoints }; const mockChannel = createMockChannel( mockNode, mockSampler, AnimatedPropertyType.TRANSLATION ); const wrappedRuntimeAnimation = { model: { clampAnimations: false } }; const runtimeChannel = new import__704.ModelAnimationChannel({ channel: mockChannel, runtimeAnimation: wrappedRuntimeAnimation, runtimeNode }); expect(runtimeNode.translation).toEqual(import__704.Cartesian3.ZERO); expect(runtimeNode.transform).toEqual(import__704.Matrix4.IDENTITY); let time2 = 1.25; let expected = import__704.Cartesian3.clone(translationPoints[1]); runtimeChannel.animate(time2); expect(runtimeNode.translation).toEqual(expected); expect(runtimeNode.transform).toEqual( import__704.Matrix4.fromTranslation(expected, scratchTransform) ); time2 = -0.5; expected = import__704.Cartesian3.clone(translationPoints[2]); runtimeChannel.animate(time2); expect(runtimeNode.translation).toEqual(expected); expect(runtimeNode.transform).toEqual( import__704.Matrix4.fromTranslation(expected, scratchTransform) ); }); it("doesn't modify node that is animated by user", function() { const mockSampler = { input: times, interpolation: import__704.InterpolationType.LINEAR, output: translationPoints }; const mockChannel = createMockChannel( mockNode, mockSampler, AnimatedPropertyType.TRANSLATION ); const runtimeChannel = new import__704.ModelAnimationChannel({ channel: mockChannel, runtimeAnimation, runtimeNode }); expect(runtimeNode.translation).toEqual(import__704.Cartesian3.ZERO); expect(runtimeNode.transform).toEqual(import__704.Matrix4.IDENTITY); runtimeNode.userAnimated = true; const time2 = 10; runtimeChannel.animate(time2); expect(runtimeNode.translation).toEqual(import__704.Cartesian3.ZERO); expect(runtimeNode.transform).toEqual(import__704.Matrix4.IDENTITY); }); }); // packages/engine/Specs/Scene/Model/ModelAnimationCollectionSpec.js var import__705 = __toESM(require_Cesium(), 1); describe( "Scene/Model/ModelAnimationCollection", function() { const animatedTriangleUrl = "./Data/Models/glTF-2.0/AnimatedTriangle/glTF/AnimatedTriangle.gltf"; const interpolationTestUrl = "./Data/Models/glTF-2.0/InterpolationTest/glTF-Binary/InterpolationTest.glb"; const defaultDate = import__705.JulianDate.fromDate( /* @__PURE__ */ new Date("January 1, 2014 12:00:00 UTC") ); const scratchJulianDate = new import__705.JulianDate(); let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.primitives.removeAll(); import__705.ResourceCache.clearForSpecs(); }); it("initializes", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const animationCollection = model.activeAnimations; expect(animationCollection).toBeDefined(); expect(animationCollection.model).toBe(model); expect(animationCollection.length).toBe(0); }); }); it("throws when add is called on non-ready model", async function() { const model = await import__705.Model.fromGltfAsync({ gltf: animatedTriangleUrl }); expect(function() { model.activeAnimations.add({ index: 0 }); }).toThrowDeveloperError(); }); it("throws when add is not given a name or index", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { expect(function() { model.activeAnimations.add({}); }).toThrowDeveloperError(); }); }); it("throws when add is given invalid name", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { expect(function() { model.activeAnimations.add({ name: "Invalid name" }); }).toThrowDeveloperError(); }); }); it("throws when add is given invalid index", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { expect(function() { model.activeAnimations.add({ index: 2 }); }).toThrowDeveloperError(); }); }); it("throws when add is given invalid multiplier", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { expect(function() { model.activeAnimations.add({ index: 0, multiplier: 0 }); }).toThrowDeveloperError(); }); }); it("add works with name", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const runtimeAnimation = model.activeAnimations.add({ name: "Sample Animation" }); const animationCollection = model.activeAnimations; expect(animationCollection.length).toBe(1); expect(runtimeAnimation).toBe( animationCollection._runtimeAnimations[0] ); expect(runtimeAnimation.startTime).toBeUndefined(); expect(runtimeAnimation.delay).toBe(0); expect(runtimeAnimation.stopTime).toBeUndefined(); expect(runtimeAnimation.removeOnStop).toBe(false); expect(runtimeAnimation.multiplier).toBe(1); expect(runtimeAnimation.reverse).toBe(false); expect(runtimeAnimation.loop).toBe(import__705.ModelAnimationLoop.NONE); }); }); it("add works with index", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const runtimeAnimation = model.activeAnimations.add({ index: 0 }); const animationCollection = model.activeAnimations; expect(animationCollection.length).toBe(1); expect(runtimeAnimation).toBe( animationCollection._runtimeAnimations[0] ); expect(runtimeAnimation.startTime).toBeUndefined(); expect(runtimeAnimation.delay).toBe(0); expect(runtimeAnimation.stopTime).toBeUndefined(); expect(runtimeAnimation.removeOnStop).toBe(false); expect(runtimeAnimation.multiplier).toBe(1); expect(runtimeAnimation.reverse).toBe(false); expect(runtimeAnimation.loop).toBe(import__705.ModelAnimationLoop.NONE); }); }); it("add works with options", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const options = { index: 0, startTime: import__705.JulianDate.fromDate( /* @__PURE__ */ new Date("January 1, 2014 12:00:00 UTC") ), delay: 5, stopTime: import__705.JulianDate.fromDate( /* @__PURE__ */ new Date("January 1, 2014 12:01:30 UTC") ), multiplier: 0.5, reverse: true, loop: import__705.ModelAnimationLoop.REPEAT, removeOnStop: true }; const runtimeAnimation = model.activeAnimations.add(options); const animationCollection = model.activeAnimations; expect(animationCollection.length).toBe(1); expect(runtimeAnimation).toBe( animationCollection._runtimeAnimations[0] ); expect(runtimeAnimation.startTime).toEqual(options.startTime); expect(runtimeAnimation.delay).toBe(5); expect(runtimeAnimation.stopTime).toEqual(options.stopTime); expect(runtimeAnimation.removeOnStop).toBe(true); expect(runtimeAnimation.multiplier).toBe(0.5); expect(runtimeAnimation.reverse).toBe(true); expect(runtimeAnimation.loop).toBe(import__705.ModelAnimationLoop.REPEAT); }); }); it("throws when addAll is called on non-ready model", async function() { const model = await import__705.Model.fromGltfAsync({ gltf: animatedTriangleUrl }); expect(function() { model.activeAnimations.addAll(); }).toThrowDeveloperError(); }); it("throws when addAll is given invalid multiplier", function() { return loadAndZoomToModelAsync_default( { gltf: interpolationTestUrl }, scene2 ).then(function(model) { expect(function() { model.activeAnimations.addAll({ multiplier: 0 }); }).toThrowDeveloperError(); }); }); it("addAll works", function() { return loadAndZoomToModelAsync_default( { gltf: interpolationTestUrl }, scene2 ).then(function(model) { const runtimeAnimations = model.activeAnimations.addAll(); const animationCollection = model.activeAnimations; const length2 = animationCollection.length; expect(length2).toBe(9); for (let i = 0; i < length2; i++) { const runtimeAnimation = runtimeAnimations[i]; expect(runtimeAnimation).toBe( animationCollection._runtimeAnimations[i] ); expect(runtimeAnimation.startTime).toBeUndefined(); expect(runtimeAnimation.delay).toBe(0); expect(runtimeAnimation.stopTime).toBeUndefined(); expect(runtimeAnimation.removeOnStop).toBe(false); expect(runtimeAnimation.multiplier).toBe(1); expect(runtimeAnimation.reverse).toBe(false); expect(runtimeAnimation.loop).toBe(import__705.ModelAnimationLoop.NONE); } }); }); it("addAll works with options", function() { return loadAndZoomToModelAsync_default( { gltf: interpolationTestUrl }, scene2 ).then(function(model) { const options = { startTime: import__705.JulianDate.fromDate( /* @__PURE__ */ new Date("January 1, 2014 12:00:00 UTC") ), delay: 5, stopTime: import__705.JulianDate.fromDate( /* @__PURE__ */ new Date("January 1, 2014 12:01:30 UTC") ), multiplier: 0.5, reverse: true, loop: import__705.ModelAnimationLoop.REPEAT, removeOnStop: true }; const runtimeAnimations = model.activeAnimations.addAll(options); const animationCollection = model.activeAnimations; const length2 = animationCollection.length; expect(length2).toBe(9); for (let i = 0; i < length2; i++) { const runtimeAnimation = runtimeAnimations[i]; expect(runtimeAnimation).toBe( animationCollection._runtimeAnimations[i] ); expect(runtimeAnimation.startTime).toEqual(options.startTime); expect(runtimeAnimation.delay).toBe(5); expect(runtimeAnimation.stopTime).toEqual(options.stopTime); expect(runtimeAnimation.removeOnStop).toBe(true); expect(runtimeAnimation.multiplier).toBe(0.5); expect(runtimeAnimation.reverse).toBe(true); expect(runtimeAnimation.loop).toBe(import__705.ModelAnimationLoop.REPEAT); } }); }); it("contains returns false for undefined", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const animationCollection = model.activeAnimations; animationCollection.add({ index: 0 }); expect(animationCollection.contains(void 0)).toBe(false); }); }); it("contains returns false for animation not in collection", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(firstModel) { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(secondModel) { const firstCollection = firstModel.activeAnimations; const animation = firstCollection.add({ index: 0 }); const secondCollection = secondModel.activeAnimations; expect(secondCollection.contains(animation)).toBe(false); }); }); }); it("contains returns true for animation in collection", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const animationCollection = model.activeAnimations; const animation = animationCollection.add({ index: 0 }); expect(animationCollection.contains(animation)).toBe(true); }); }); it("throws when get is not given index", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const animationCollection = model.activeAnimations; animationCollection.add({ index: 0 }); expect(function() { animationCollection.get(); }).toThrowDeveloperError(); }); }); it("throws when get is given out-of-range index", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const animationCollection = model.activeAnimations; animationCollection.add({ index: 0 }); expect(function() { animationCollection.get(2); }).toThrowDeveloperError(); }); }); it("get works", function() { return loadAndZoomToModelAsync_default( { gltf: interpolationTestUrl }, scene2 ).then(function(model) { const animationCollection = model.activeAnimations; const animation = animationCollection.add({ index: 3 }); expect(animationCollection.get(0)).toBe(animation); }); }); it("remove returns false for undefined", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const animationCollection = model.activeAnimations; animationCollection.add({ index: 0 }); expect(animationCollection.remove(void 0)).toBe(false); }); }); it("remove returns false for animation not in collection", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(firstModel) { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(secondModel) { const firstCollection = firstModel.activeAnimations; const animation = firstCollection.add({ index: 0 }); const secondCollection = secondModel.activeAnimations; expect(secondCollection.remove(animation)).toBe(false); }); }); }); it("remove returns true for animation in collection", function() { return loadAndZoomToModelAsync_default( { gltf: interpolationTestUrl }, scene2 ).then(function(model) { const animationCollection = model.activeAnimations; const animationToRemove = animationCollection.add({ index: 0 }); animationCollection.add({ index: 1 }); expect(animationCollection.length).toBe(2); expect(animationCollection.remove(animationToRemove)).toBe(true); expect(animationCollection.length).toBe(1); expect(animationCollection.remove(animationToRemove)).toBe(false); }); }); it("removeAll works", function() { return loadAndZoomToModelAsync_default( { gltf: interpolationTestUrl }, scene2 ).then(function(model) { const animationCollection = model.activeAnimations; animationCollection.addAll(); expect(animationCollection.length).toBe(9); animationCollection.removeAll(); expect(animationCollection.length).toBe(0); }); }); it("update returns false when there are no animations", function() { return loadAndZoomToModelAsync_default( { gltf: interpolationTestUrl }, scene2 ).then(function(model) { const animationCollection = model.activeAnimations; expect(animationCollection.length).toBe(0); expect(animationCollection.update()).toBe(false); }); }); it("raises animation start, update, and stop events when removeOnStop is true", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { let time2 = defaultDate; const animations = model.activeAnimations; const animation = animations.add({ index: 0, startTime: time2, removeOnStop: true }); const spyStart = jasmine.createSpy("listener"); animation.start.addEventListener(spyStart); const spyUpdate = jasmine.createSpy("listener"); animation.update.addEventListener(spyUpdate); let stopped = false; animation.stop.addEventListener(function(model2, animation2) { stopped = true; }); const spyStop = jasmine.createSpy("listener"); animation.stop.addEventListener(spyStop); return pollToPromise_default( function() { scene2.renderForSpecs(time2); time2 = import__705.JulianDate.addSeconds(time2, 1, scratchJulianDate); return stopped; }, { timeout: 1e4 } ).then(function() { expect(spyStart).toHaveBeenCalledWith(model, animation); expect(spyUpdate.calls.count()).toBeGreaterThanOrEqual(2); expect(spyUpdate.calls.argsFor(0)[0]).toBe(model); expect(spyUpdate.calls.argsFor(0)[1]).toBe(animation); expect(spyUpdate.calls.argsFor(0)[2]).toEqual(0); expect(spyUpdate.calls.argsFor(1)[2]).toEqual(1); expect(spyStop).toHaveBeenCalledWith(model, animation); expect(animations.length).toEqual(0); }); }); }); it("finishes animation when it reaches its end", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const time2 = defaultDate; const animationCollection = model.activeAnimations; const animation = animationCollection.add({ index: 0 }); const spyUpdate = jasmine.createSpy("listener"); animation.update.addEventListener(spyUpdate); scene2.renderForSpecs(time2); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 1, scratchJulianDate) ); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 2, scratchJulianDate) ); expect(spyUpdate.calls.count()).toEqual(3); expect(spyUpdate.calls.argsFor(0)[2]).toEqual(0); expect(spyUpdate.calls.argsFor(1)[2]).toEqual(1); expect(spyUpdate.calls.argsFor(2)[2]).toEqual(1); }); }); it("animates with a delay", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const time2 = defaultDate; const animationCollection = model.activeAnimations; const animation = animationCollection.add({ index: 0, startTime: time2, delay: 1 }); const spyStart = jasmine.createSpy("listener"); animation.start.addEventListener(spyStart); scene2.renderForSpecs(time2); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 1, scratchJulianDate) ); expect(spyStart.calls.count()).toEqual(1); }); }); it("animates with startTime", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const time2 = defaultDate; const animationCollection = model.activeAnimations; const animation = animationCollection.add({ index: 0, startTime: time2 }); const spyUpdate = jasmine.createSpy("listener"); animation.update.addEventListener(spyUpdate); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, -2, scratchJulianDate) ); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, -1, scratchJulianDate) ); scene2.renderForSpecs(time2); expect(spyUpdate.calls.count()).toEqual(1); expect(spyUpdate.calls.argsFor(0)[2]).toEqual(0); }); }); it("animates with an explicit stopTime", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const time2 = import__705.JulianDate.fromDate( /* @__PURE__ */ new Date("January 1, 2014 12:00:00 UTC") ); const endDate = /* @__PURE__ */ new Date("January 1, 2014 12:00:00 UTC"); endDate.setMilliseconds(500); const stopTime = import__705.JulianDate.fromDate(endDate); const animationCollection = model.activeAnimations; const animation = animationCollection.add({ index: 0, startTime: time2, stopTime }); const spyUpdate = jasmine.createSpy("listener"); animation.update.addEventListener(spyUpdate); scene2.renderForSpecs(time2); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 0.5, scratchJulianDate) ); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 1, scratchJulianDate) ); expect(spyUpdate.calls.count()).toEqual(3); expect(spyUpdate.calls.argsFor(0)[2]).toEqual(0); expect(spyUpdate.calls.argsFor(1)[2]).toEqual(0.5); expect(spyUpdate.calls.argsFor(1)[2]).toEqual(0.5); }); }); it("animates with an explicit animation time", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const time2 = defaultDate; const animationCollection = model.activeAnimations; let animationTime = 0; const animation = animationCollection.add({ index: 0, animationTime: function(duration) { return animationTime / duration; } }); const spyUpdate = jasmine.createSpy("listener"); animation.update.addEventListener(spyUpdate); scene2.renderForSpecs(time2); animationTime = 0.1; scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 1, scratchJulianDate) ); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 2, scratchJulianDate) ); animationTime = 0.2; scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 2, scratchJulianDate) ); animationTime = 0.3; scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 3, scratchJulianDate) ); expect(spyUpdate.calls.count()).toEqual(3); expect(spyUpdate.calls.argsFor(0)[2]).toEqualEpsilon( 0, import__705.Math.EPSILON14 ); expect(spyUpdate.calls.argsFor(1)[2]).toEqualEpsilon( 0.1, import__705.Math.EPSILON14 ); expect(spyUpdate.calls.argsFor(2)[2]).toEqualEpsilon( 0.3, import__705.Math.EPSILON14 ); }); }); it("animates while paused with an explicit animation time", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const time2 = defaultDate; const animationCollection = model.activeAnimations; animationCollection.animateWhilePaused = true; let animationTime = 0; const animation = animationCollection.add({ index: 0, animationTime: function(duration) { return animationTime / duration; } }); const spyUpdate = jasmine.createSpy("listener"); animation.update.addEventListener(spyUpdate); scene2.renderForSpecs(time2); animationTime = 0.1; scene2.renderForSpecs(time2); scene2.renderForSpecs(time2); animationTime = 0.3; scene2.renderForSpecs(time2); expect(spyUpdate.calls.count()).toEqual(3); expect(spyUpdate.calls.argsFor(0)[2]).toEqualEpsilon( 0, import__705.Math.EPSILON14 ); expect(spyUpdate.calls.argsFor(1)[2]).toEqualEpsilon( 0.1, import__705.Math.EPSILON14 ); expect(spyUpdate.calls.argsFor(2)[2]).toEqualEpsilon( 0.3, import__705.Math.EPSILON14 ); }); }); it("animates with a multiplier", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const time2 = defaultDate; const animationCollection = model.activeAnimations; const animation = animationCollection.add({ index: 0, startTime: time2, multiplier: 0.5 }); const spyUpdate = jasmine.createSpy("listener"); animation.update.addEventListener(spyUpdate); scene2.renderForSpecs(time2); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 1, scratchJulianDate) ); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 2, scratchJulianDate) ); expect(spyUpdate.calls.count()).toEqual(3); expect(spyUpdate.calls.argsFor(0)[2]).toEqual(0); expect(spyUpdate.calls.argsFor(1)[2]).toEqual(0.5); expect(spyUpdate.calls.argsFor(2)[2]).toEqual(1); }); }); it("animates with reverse", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const time2 = defaultDate; const animationCollection = model.activeAnimations; const animation = animationCollection.add({ index: 0, startTime: time2, reverse: true }); const spyUpdate = jasmine.createSpy("listener"); animation.update.addEventListener(spyUpdate); scene2.renderForSpecs(time2); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 0.5, scratchJulianDate) ); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 1, scratchJulianDate) ); expect(spyUpdate.calls.count()).toEqual(3); expect(spyUpdate.calls.argsFor(0)[2]).toEqual(1); expect(spyUpdate.calls.argsFor(1)[2]).toEqual(0.5); expect(spyUpdate.calls.argsFor(2)[2]).toEqual(0); }); }); it("animates with REPEAT", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const time2 = defaultDate; const animationCollection = model.activeAnimations; const animation = animationCollection.add({ index: 0, startTime: time2, loop: import__705.ModelAnimationLoop.REPEAT }); const spyUpdate = jasmine.createSpy("listener"); animation.update.addEventListener(spyUpdate); scene2.renderForSpecs(time2); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 0.5, scratchJulianDate) ); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 1, scratchJulianDate) ); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 1.5, scratchJulianDate) ); expect(spyUpdate.calls.count()).toEqual(4); expect(spyUpdate.calls.argsFor(0)[2]).toEqual(0); expect(spyUpdate.calls.argsFor(1)[2]).toEqual(0.5); expect(spyUpdate.calls.argsFor(2)[2]).toEqual(0); expect(spyUpdate.calls.argsFor(3)[2]).toEqual(0.5); }); }); it("animates with MIRRORED_REPEAT", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl }, scene2 ).then(function(model) { const time2 = defaultDate; const animationCollection = model.activeAnimations; const animation = animationCollection.add({ index: 0, startTime: time2, loop: import__705.ModelAnimationLoop.MIRRORED_REPEAT }); const spyUpdate = jasmine.createSpy("listener"); animation.update.addEventListener(spyUpdate); scene2.renderForSpecs(time2); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 0.5, scratchJulianDate) ); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 1, scratchJulianDate) ); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 1.5, scratchJulianDate) ); scene2.renderForSpecs( import__705.JulianDate.addSeconds(time2, 2, scratchJulianDate) ); expect(spyUpdate.calls.count()).toEqual(5); expect(spyUpdate.calls.argsFor(0)[2]).toEqual(0); expect(spyUpdate.calls.argsFor(1)[2]).toEqual(0.5); expect(spyUpdate.calls.argsFor(2)[2]).toEqual(1); expect(spyUpdate.calls.argsFor(3)[2]).toEqual(0.5); expect(spyUpdate.calls.argsFor(4)[2]).toEqual(0); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/ModelAnimationSpec.js var import__706 = __toESM(require_Cesium(), 1); describe("Scene/Model/ModelAnimation", function() { const AnimatedPropertyType = import__706.ModelComponents.AnimatedPropertyType; const mockNode = { translation: import__706.Cartesian3.ZERO, rotation: import__706.Quaternion.IDENTITY, scale: new import__706.Cartesian3(1, 1, 1), index: 0 }; let runtimeNode; let mockSceneGraph; let mockModel; function createMockChannel(mockNode2, mockSampler, path) { const mockTarget = { node: mockNode2, path }; const mockChannel = { sampler: mockSampler, target: mockTarget }; return mockChannel; } beforeEach(function() { mockSceneGraph = { _runtimeNodes: [] }; runtimeNode = new import__706.ModelRuntimeNode({ node: mockNode, transform: import__706.Matrix4.IDENTITY, transformToRoot: import__706.Matrix4.IDENTITY, sceneGraph: mockSceneGraph, children: [] }); mockSceneGraph._runtimeNodes.push(runtimeNode); mockModel = { clampAnimations: true, sceneGraph: mockSceneGraph }; }); const mockTranslationSampler = { input: [0, 0.5, 1], interpolation: import__706.InterpolationType.LINEAR, output: [ import__706.Cartesian3.ZERO, new import__706.Cartesian3(1, 2, 3), new import__706.Cartesian3(4, 5, 6) ] }; const mockRotationSampler = { input: [0.25, 0.75, 1.25], interpolation: import__706.InterpolationType.STEP, output: [ import__706.Quaternion.IDENTITY, new import__706.Quaternion(0, 0, 0.707, -0.707), import__706.Quaternion.IDENTITY ] }; const emptyOptions = {}; it("initializes", function() { const mockAnimation = { channels: [ createMockChannel( mockNode, mockTranslationSampler, AnimatedPropertyType.TRANSLATION ), createMockChannel( mockNode, mockRotationSampler, AnimatedPropertyType.ROTATION ) ], name: "Sample Animation" }; const runtimeAnimation = new import__706.ModelAnimation( mockModel, mockAnimation, emptyOptions ); expect(runtimeAnimation.animation).toBe(mockAnimation); expect(runtimeAnimation.name).toEqual("Sample Animation"); expect(runtimeAnimation.model).toBe(mockModel); const channels = runtimeAnimation.runtimeChannels; expect(channels.length).toEqual(2); expect(channels[0]._path).toEqual(AnimatedPropertyType.TRANSLATION); expect(channels[1]._path).toEqual(AnimatedPropertyType.ROTATION); expect(runtimeAnimation.localStartTime).toBe(0); expect(runtimeAnimation.localStopTime).toBe(1.25); expect(runtimeAnimation.startTime).toBeUndefined(); expect(runtimeAnimation.delay).toBe(0); expect(runtimeAnimation.stopTime).toBeUndefined(); expect(runtimeAnimation.removeOnStop).toBe(false); expect(runtimeAnimation.multiplier).toBe(1); expect(runtimeAnimation.reverse).toBe(false); expect(runtimeAnimation.loop).toBe(import__706.ModelAnimationLoop.NONE); }); it("initializes with options", function() { const mockAnimation = { channels: [ createMockChannel( mockNode, mockTranslationSampler, AnimatedPropertyType.TRANSLATION ), createMockChannel( mockNode, mockRotationSampler, AnimatedPropertyType.ROTATION ) ], name: "Sample Animation" }; const options = { startTime: import__706.JulianDate.fromDate(/* @__PURE__ */ new Date("January 1, 2014 12:00:00 UTC")), delay: 5, stopTime: import__706.JulianDate.fromDate(/* @__PURE__ */ new Date("January 1, 2014 12:01:30 UTC")), multiplier: 0.5, reverse: true, loop: import__706.ModelAnimationLoop.REPEAT, removeOnStop: true }; const runtimeAnimation = new import__706.ModelAnimation( mockModel, mockAnimation, options ); expect(runtimeAnimation.animation).toBe(mockAnimation); expect(runtimeAnimation.name).toEqual("Sample Animation"); expect(runtimeAnimation.model).toBe(mockModel); const channels = runtimeAnimation.runtimeChannels; expect(channels.length).toEqual(2); expect(channels[0]._path).toEqual(AnimatedPropertyType.TRANSLATION); expect(channels[1]._path).toEqual(AnimatedPropertyType.ROTATION); expect(runtimeAnimation.localStartTime).toBe(0); expect(runtimeAnimation.localStopTime).toBe(1.25); expect(runtimeAnimation.startTime).toEqual(options.startTime); expect(runtimeAnimation.delay).toBe(5); expect(runtimeAnimation.stopTime).toEqual(options.stopTime); expect(runtimeAnimation.removeOnStop).toBe(true); expect(runtimeAnimation.multiplier).toBe(0.5); expect(runtimeAnimation.reverse).toBe(true); expect(runtimeAnimation.loop).toBe(import__706.ModelAnimationLoop.REPEAT); }); it("initializes without invalid channels", function() { const mockAnimation = { channels: [ createMockChannel( mockNode, mockTranslationSampler, AnimatedPropertyType.TRANSLATION ), { sampler: mockRotationSampler, target: void 0 } ], name: "Sample Animation" }; const runtimeAnimation = new import__706.ModelAnimation( mockModel, mockAnimation, emptyOptions ); expect(runtimeAnimation.animation).toBe(mockAnimation); expect(runtimeAnimation.name).toEqual("Sample Animation"); expect(runtimeAnimation.model).toBe(mockModel); const channels = runtimeAnimation.runtimeChannels; expect(channels.length).toEqual(1); expect(channels[0]._path).toEqual(AnimatedPropertyType.TRANSLATION); expect(runtimeAnimation.localStartTime).toBe(0); expect(runtimeAnimation.localStopTime).toBe(1); }); it("animates", function() { const mockAnimation = { channels: [ createMockChannel( mockNode, mockTranslationSampler, AnimatedPropertyType.TRANSLATION ), createMockChannel( mockNode, mockRotationSampler, AnimatedPropertyType.ROTATION ) ], name: "Sample Animation" }; const runtimeAnimation = new import__706.ModelAnimation( mockModel, mockAnimation, emptyOptions ); expect(runtimeNode.translation).toEqual(import__706.Cartesian3.ZERO); expect(runtimeNode.rotation).toEqual(import__706.Quaternion.IDENTITY); runtimeAnimation.animate(0.5); expect(runtimeNode.translation).toEqual(new import__706.Cartesian3(1, 2, 3)); expect(runtimeNode.rotation).toEqual(import__706.Quaternion.IDENTITY); runtimeAnimation.animate(1); expect(runtimeNode.translation).toEqual(new import__706.Cartesian3(4, 5, 6)); expect(runtimeNode.rotation).toEqual( new import__706.Quaternion(0, 0, 0.707, -0.707) ); }); }); // packages/engine/Specs/Scene/Model/ModelArticulationSpec.js var import__707 = __toESM(require_Cesium(), 1); describe("Scene/Model/ModelArticulation", function() { const mockSceneGraph = {}; const articulation = { name: "SampleArticulation", stages: [] }; function createTranslateStage(name, value) { return { name, type: import__707.ArticulationStageType.XTRANSLATE, minimumValue: -100, maximumValue: 100, initialValue: value }; } function createRotateStage(name, value) { return { name, type: import__707.ArticulationStageType.ZROTATE, minimumValue: -360, maximumValue: 360, initialValue: value }; } function createScaleStage(name, value) { return { name, type: import__707.ArticulationStageType.UNIFORMSCALE, minimumValue: 0, maximumValue: 1, initialValue: value }; } function mockRuntimeNode(transform) { return { originalTransform: import__707.Matrix4.clone(transform), transform: import__707.Matrix4.clone(transform) }; } beforeEach(function() { const stages = articulation.stages; stages.length = 0; stages.push(createTranslateStage("MoveX", 50)); stages.push(createRotateStage("RotateZ", 180)); stages.push(createScaleStage("Size", 0.5)); }); it("throws for undefined articulation", function() { expect(function() { return new import__707.ModelArticulation({ articulation: void 0, sceneGraph: mockSceneGraph }); }).toThrowDeveloperError(); }); it("throws for undefined scene graph", function() { expect(function() { return new import__707.ModelArticulation({ articulation: {}, sceneGraph: void 0 }); }).toThrowDeveloperError(); }); it("constructs", function() { const runtimeArticulation = new import__707.ModelArticulation({ articulation, sceneGraph: mockSceneGraph }); expect(runtimeArticulation.articulation).toBe(articulation); expect(runtimeArticulation.sceneGraph).toBe(mockSceneGraph); expect(runtimeArticulation.name).toEqual("SampleArticulation"); const runtimeStages = runtimeArticulation.runtimeStages; expect(runtimeStages.length).toEqual(3); const runtimeStagesByName = runtimeArticulation._runtimeStagesByName; const xTranslateStage = runtimeStages[0]; expect(xTranslateStage.name).toBe("MoveX"); expect(xTranslateStage.runtimeArticulation).toBe(runtimeArticulation); expect(runtimeStagesByName[xTranslateStage.name]).toBe(xTranslateStage); const zRotateStage = runtimeStages[1]; expect(zRotateStage.name).toBe("RotateZ"); expect(zRotateStage.runtimeArticulation).toBe(runtimeArticulation); expect(runtimeStagesByName[zRotateStage.name]).toBe(zRotateStage); const uniformScaleStage = runtimeStages[2]; expect(uniformScaleStage.name).toBe("Size"); expect(uniformScaleStage.runtimeArticulation).toBe(runtimeArticulation); expect(runtimeStagesByName[uniformScaleStage.name]).toBe(uniformScaleStage); expect(runtimeArticulation.runtimeNodes.length).toBe(0); expect(runtimeArticulation._dirty).toBe(true); }); it("setArticulationStage does not throw if stage name doesn't exist", function() { const runtimeArticulation = new import__707.ModelArticulation({ articulation, sceneGraph: mockSceneGraph }); const runtimeStages = runtimeArticulation.runtimeStages; expect(runtimeStages.length).toEqual(3); const xTranslateStage = runtimeStages[0]; const zRotateStage = runtimeStages[1]; const uniformScaleStage = runtimeStages[2]; expect(xTranslateStage.currentValue).toBe(50); expect(zRotateStage.currentValue).toBe(180); expect(uniformScaleStage.currentValue).toBe(0.5); runtimeArticulation._dirty = false; expect(function() { runtimeArticulation.setArticulationStage("NonexistentStage", 100); }).not.toThrowDeveloperError(); expect(xTranslateStage.currentValue).toBe(50); expect(zRotateStage.currentValue).toBe(180); expect(uniformScaleStage.currentValue).toBe(0.5); expect(runtimeArticulation._dirty).toBe(false); }); it("setArticulationStage works", function() { const runtimeArticulation = new import__707.ModelArticulation({ articulation, sceneGraph: mockSceneGraph }); runtimeArticulation._dirty = false; const runtimeStages = runtimeArticulation.runtimeStages; expect(runtimeStages.length).toEqual(3); const xTranslateStage = runtimeStages[0]; const zRotateStage = runtimeStages[1]; const uniformScaleStage = runtimeStages[2]; expect(xTranslateStage.currentValue).toBe(50); expect(zRotateStage.currentValue).toBe(180); expect(uniformScaleStage.currentValue).toBe(0.5); runtimeArticulation.setArticulationStage("MoveX", 0); expect(xTranslateStage.currentValue).toBe(0); expect(zRotateStage.currentValue).toBe(180); expect(uniformScaleStage.currentValue).toBe(0.5); expect(runtimeArticulation._dirty).toBe(true); runtimeArticulation._dirty = false; runtimeArticulation.setArticulationStage("RotateZ", -480); expect(xTranslateStage.currentValue).toBe(0); expect(zRotateStage.currentValue).toBe(-360); expect(uniformScaleStage.currentValue).toBe(0.5); expect(runtimeArticulation._dirty).toBe(true); runtimeArticulation._dirty = false; runtimeArticulation.setArticulationStage("Size", 2); expect(xTranslateStage.currentValue).toBe(0); expect(zRotateStage.currentValue).toBe(-360); expect(uniformScaleStage.currentValue).toBe(1); expect(runtimeArticulation._dirty).toBe(true); }); it("apply does nothing if articulation is not dirty", function() { const runtimeArticulation = new import__707.ModelArticulation({ articulation, sceneGraph: mockSceneGraph }); runtimeArticulation._dirty = false; const transform = import__707.Matrix4.fromTranslation( new import__707.Cartesian3(1, 2, 3), new import__707.Matrix4() ); const node = mockRuntimeNode(transform); runtimeArticulation.runtimeNodes.push(node); expect(node.transform).toEqual(transform); expect(runtimeArticulation._dirty).toBe(false); runtimeArticulation.apply(); expect(node.transform).toEqual(transform); }); it("apply works", function() { const runtimeArticulation = new import__707.ModelArticulation({ articulation, sceneGraph: mockSceneGraph }); const transform = import__707.Matrix4.fromTranslation( new import__707.Cartesian3(1, 2, 3), new import__707.Matrix4() ); const node = mockRuntimeNode(transform); runtimeArticulation.runtimeNodes.push(node); expect(runtimeArticulation._dirty).toBe(true); let expectedMatrix = import__707.Matrix4.fromTranslation( new import__707.Cartesian3(50, 0, 0), new import__707.Matrix4() ); const rotation = import__707.Math.toRadians(180); const expectedRotation = import__707.Matrix3.fromRotationZ(rotation, new import__707.Matrix3()); expectedMatrix = import__707.Matrix4.multiplyByMatrix3( expectedMatrix, expectedRotation, expectedMatrix ); expectedMatrix = import__707.Matrix4.multiplyByUniformScale( expectedMatrix, 0.5, expectedMatrix ); expectedMatrix = import__707.Matrix4.multiplyTransformation( transform, expectedMatrix, expectedMatrix ); runtimeArticulation.apply(); expect(runtimeArticulation._dirty).toBe(false); expect(node.transform).toEqual(expectedMatrix); expect(node.originalTransform).toEqual(transform); }); }); // packages/engine/Specs/Scene/Model/ModelArticulationStageSpec.js var import__708 = __toESM(require_Cesium(), 1); describe("Scene/Model/ModelArticulationStage", function() { const scratchCartesian3 = new import__708.Cartesian3(); const scratchMatrix3 = new import__708.Matrix3(); const scratchExpectedMatrix = new import__708.Matrix4(); const scratchResultMatrix = new import__708.Matrix4(); function mockRuntimeArticulation() { return { name: "SampleArticulation", _runtimeStages: [], _runtimeStagesByName: {}, _dirty: false }; } it("throws for undefined stage", function() { expect(function() { return new import__708.ModelArticulationStage({ stage: void 0, runtimeArticulation: {} }); }).toThrowDeveloperError(); }); it("throws for undefined runtime articulation", function() { expect(function() { return new import__708.ModelArticulationStage({ stage: {}, runtimeArticulation: void 0 }); }).toThrowDeveloperError(); }); it("constructs", function() { const stage = { name: "SampleStage", type: import__708.ArticulationStageType.XTRANSLATE, minimumValue: -100, maximumValue: 100, initialValue: 0 }; const runtimeArticulation = mockRuntimeArticulation(); const runtimeStage = new import__708.ModelArticulationStage({ stage, runtimeArticulation }); expect(runtimeStage.stage).toBe(stage); expect(runtimeStage.runtimeArticulation).toBe(runtimeArticulation); expect(runtimeStage.name).toBe("SampleStage"); expect(runtimeStage.type).toBe(import__708.ArticulationStageType.XTRANSLATE); expect(runtimeStage.minimumValue).toBe(-100); expect(runtimeStage.maximumValue).toBe(100); expect(runtimeStage.currentValue).toBe(0); }); it("currentValue sets new value", function() { const stage = { name: "SampleStage", type: import__708.ArticulationStageType.XTRANSLATE, minimumValue: -100, maximumValue: 100, initialValue: 0 }; const runtimeArticulation = mockRuntimeArticulation(); const runtimeStage = new import__708.ModelArticulationStage({ stage, runtimeArticulation }); expect(runtimeStage.currentValue).toBe(0); runtimeStage.currentValue = 50; expect(runtimeStage.currentValue).toBe(50); expect(runtimeArticulation._dirty).toBe(true); }); it("currentValue clamps new value", function() { const stage = { name: "SampleStage", type: import__708.ArticulationStageType.XTRANSLATE, minimumValue: -100, maximumValue: 100, initialValue: 0 }; const runtimeArticulation = mockRuntimeArticulation(); const runtimeStage = new import__708.ModelArticulationStage({ stage, runtimeArticulation }); expect(runtimeStage.currentValue).toBe(0); runtimeStage.currentValue = 150; expect(runtimeStage.currentValue).toBe(100); expect(runtimeArticulation._dirty).toBe(true); runtimeArticulation._dirty = false; runtimeStage.currentValue = -150; expect(runtimeStage.currentValue).toBe(-100); expect(runtimeArticulation._dirty).toBe(true); }); it("currentValue has no effect if given value is the same", function() { const stage = { name: "SampleStage", type: import__708.ArticulationStageType.XTRANSLATE, minimumValue: -100, maximumValue: 100, initialValue: 0 }; const runtimeArticulation = mockRuntimeArticulation(); const runtimeStage = new import__708.ModelArticulationStage({ stage, runtimeArticulation }); expect(runtimeStage.currentValue).toBe(0); runtimeStage.currentValue = 0; expect(runtimeStage.currentValue).toBe(0); expect(runtimeArticulation._dirty).toBe(false); }); it("applyStageToMatrix works for xTranslate", function() { const stage = { name: "SampleStage", type: import__708.ArticulationStageType.XTRANSLATE, minimumValue: -100, maximumValue: 100, initialValue: 50 }; const runtimeArticulation = mockRuntimeArticulation(); const runtimeStage = new import__708.ModelArticulationStage({ stage, runtimeArticulation }); expect(runtimeStage.currentValue).toBe(50); const expectedTranslation = import__708.Cartesian3.fromElements( 50, 0, 0, scratchCartesian3 ); const expectedMatrix = import__708.Matrix4.fromTranslation( expectedTranslation, scratchExpectedMatrix ); let resultMatrix = import__708.Matrix4.clone(import__708.Matrix4.IDENTITY, scratchResultMatrix); resultMatrix = runtimeStage.applyStageToMatrix(resultMatrix); expect(resultMatrix).toEqual(expectedMatrix); }); it("applyStageToMatrix works for yTranslate", function() { const stage = { name: "SampleStage", type: import__708.ArticulationStageType.YTRANSLATE, minimumValue: -100, maximumValue: 100, initialValue: 50 }; const runtimeArticulation = mockRuntimeArticulation(); const runtimeStage = new import__708.ModelArticulationStage({ stage, runtimeArticulation }); expect(runtimeStage.currentValue).toBe(50); const expectedTranslation = import__708.Cartesian3.fromElements( 0, 50, 0, scratchCartesian3 ); const expectedMatrix = import__708.Matrix4.fromTranslation( expectedTranslation, scratchExpectedMatrix ); let resultMatrix = import__708.Matrix4.clone(import__708.Matrix4.IDENTITY, scratchResultMatrix); resultMatrix = runtimeStage.applyStageToMatrix(resultMatrix); expect(resultMatrix).toEqual(expectedMatrix); }); it("applyStageToMatrix works for zTranslate", function() { const stage = { name: "SampleStage", type: import__708.ArticulationStageType.ZTRANSLATE, minimumValue: -100, maximumValue: 100, initialValue: 50 }; const runtimeArticulation = mockRuntimeArticulation(); const runtimeStage = new import__708.ModelArticulationStage({ stage, runtimeArticulation }); expect(runtimeStage.currentValue).toBe(50); const expectedTranslation = import__708.Cartesian3.fromElements( 0, 0, 50, scratchCartesian3 ); const expectedMatrix = import__708.Matrix4.fromTranslation( expectedTranslation, scratchExpectedMatrix ); let resultMatrix = import__708.Matrix4.clone(import__708.Matrix4.IDENTITY, scratchResultMatrix); resultMatrix = runtimeStage.applyStageToMatrix(resultMatrix); expect(resultMatrix).toEqual(expectedMatrix); }); it("applyStageToMatrix works for xRotate", function() { const stage = { name: "SampleStage", type: import__708.ArticulationStageType.XROTATE, minimumValue: -360, maximumValue: 360, initialValue: 180 }; const runtimeArticulation = mockRuntimeArticulation(); const runtimeStage = new import__708.ModelArticulationStage({ stage, runtimeArticulation }); expect(runtimeStage.currentValue).toBe(180); const value = import__708.Math.toRadians(180); const expectedRotation = import__708.Matrix3.fromRotationX(value, scratchMatrix3); const expectedMatrix = import__708.Matrix4.fromRotation( expectedRotation, scratchExpectedMatrix ); let resultMatrix = import__708.Matrix4.clone(import__708.Matrix4.IDENTITY, scratchResultMatrix); resultMatrix = runtimeStage.applyStageToMatrix(resultMatrix); expect(resultMatrix).toEqual(expectedMatrix); }); it("applyStageToMatrix works for yRotate", function() { const stage = { name: "SampleStage", type: import__708.ArticulationStageType.YROTATE, minimumValue: -360, maximumValue: 360, initialValue: 180 }; const runtimeArticulation = mockRuntimeArticulation(); const runtimeStage = new import__708.ModelArticulationStage({ stage, runtimeArticulation }); expect(runtimeStage.currentValue).toBe(180); const value = import__708.Math.toRadians(180); const expectedRotation = import__708.Matrix3.fromRotationY(value, scratchMatrix3); const expectedMatrix = import__708.Matrix4.fromRotation( expectedRotation, scratchExpectedMatrix ); let resultMatrix = import__708.Matrix4.clone(import__708.Matrix4.IDENTITY, scratchResultMatrix); resultMatrix = runtimeStage.applyStageToMatrix(resultMatrix); expect(resultMatrix).toEqual(expectedMatrix); }); it("applyStageToMatrix works for zRotate", function() { const stage = { name: "SampleStage", type: import__708.ArticulationStageType.ZROTATE, minimumValue: -360, maximumValue: 360, initialValue: 180 }; const runtimeArticulation = mockRuntimeArticulation(); const runtimeStage = new import__708.ModelArticulationStage({ stage, runtimeArticulation }); expect(runtimeStage.currentValue).toBe(180); const value = import__708.Math.toRadians(180); const expectedRotation = import__708.Matrix3.fromRotationZ(value, scratchMatrix3); const expectedMatrix = import__708.Matrix4.fromRotation( expectedRotation, scratchExpectedMatrix ); let resultMatrix = import__708.Matrix4.clone(import__708.Matrix4.IDENTITY, scratchResultMatrix); resultMatrix = runtimeStage.applyStageToMatrix(resultMatrix); expect(resultMatrix).toEqual(expectedMatrix); }); it("applyStageToMatrix works for xScale", function() { const stage = { name: "SampleStage", type: import__708.ArticulationStageType.XSCALE, minimumValue: 0, maximumValue: 1, initialValue: 0.5 }; const runtimeArticulation = mockRuntimeArticulation(); const runtimeStage = new import__708.ModelArticulationStage({ stage, runtimeArticulation }); expect(runtimeStage.currentValue).toBe(0.5); const expectedScale = import__708.Cartesian3.fromElements( 0.5, 1, 1, scratchCartesian3 ); const expectedMatrix = import__708.Matrix4.fromScale( expectedScale, scratchExpectedMatrix ); let resultMatrix = import__708.Matrix4.clone(import__708.Matrix4.IDENTITY, scratchResultMatrix); resultMatrix = runtimeStage.applyStageToMatrix(resultMatrix); expect(resultMatrix).toEqual(expectedMatrix); }); it("applyStageToMatrix works for yScale", function() { const stage = { name: "SampleStage", type: import__708.ArticulationStageType.YSCALE, minimumValue: 0, maximumValue: 1, initialValue: 0.5 }; const runtimeArticulation = mockRuntimeArticulation(); const runtimeStage = new import__708.ModelArticulationStage({ stage, runtimeArticulation }); expect(runtimeStage.currentValue).toBe(0.5); const expectedScale = import__708.Cartesian3.fromElements( 1, 0.5, 1, scratchCartesian3 ); const expectedMatrix = import__708.Matrix4.fromScale( expectedScale, scratchExpectedMatrix ); let resultMatrix = import__708.Matrix4.clone(import__708.Matrix4.IDENTITY, scratchResultMatrix); resultMatrix = runtimeStage.applyStageToMatrix(resultMatrix); expect(resultMatrix).toEqual(expectedMatrix); }); it("applyStageToMatrix works for zScale", function() { const stage = { name: "SampleStage", type: import__708.ArticulationStageType.ZSCALE, minimumValue: 0, maximumValue: 1, initialValue: 0.5 }; const runtimeArticulation = mockRuntimeArticulation(); const runtimeStage = new import__708.ModelArticulationStage({ stage, runtimeArticulation }); expect(runtimeStage.currentValue).toBe(0.5); const expectedScale = import__708.Cartesian3.fromElements( 1, 1, 0.5, scratchCartesian3 ); const expectedMatrix = import__708.Matrix4.fromScale( expectedScale, scratchExpectedMatrix ); let resultMatrix = import__708.Matrix4.clone(import__708.Matrix4.IDENTITY, scratchResultMatrix); resultMatrix = runtimeStage.applyStageToMatrix(resultMatrix); expect(resultMatrix).toEqual(expectedMatrix); }); it("applyStageToMatrix works for uniformScale", function() { const stage = { name: "SampleStage", type: import__708.ArticulationStageType.UNIFORMSCALE, minimumValue: 0, maximumValue: 1, initialValue: 0.5 }; const runtimeArticulation = mockRuntimeArticulation(); const runtimeStage = new import__708.ModelArticulationStage({ stage, runtimeArticulation }); expect(runtimeStage.currentValue).toBe(0.5); const expectedMatrix = import__708.Matrix4.fromUniformScale(0.5, scratchExpectedMatrix); let resultMatrix = import__708.Matrix4.clone(import__708.Matrix4.IDENTITY, scratchResultMatrix); resultMatrix = runtimeStage.applyStageToMatrix(resultMatrix); expect(resultMatrix).toEqual(expectedMatrix); }); }); // packages/engine/Specs/Scene/Model/ModelClippingPlanesPipelineStageSpec.js var import__709 = __toESM(require_Cesium(), 1); describe("Scene/Model/ModelClippingPlanesPipelineStage", function() { let plane; let clippingPlanes; beforeEach(function() { plane = new import__709.ClippingPlane(import__709.Cartesian3.UNIT_X, 0); clippingPlanes = new import__709.ClippingPlaneCollection({ planes: [plane] }); clippingPlanes._clippingPlanesTexture = { width: 1, height: 1 }; }); it("configures the render resources for default clipping planes", function() { const mockFrameState = { context: {} }; const mockModel = { clippingPlanes, _clippingPlanesMatrix: import__709.Matrix4.clone(import__709.Matrix4.IDENTITY) }; const renderResources = { shaderBuilder: new import__709.ShaderBuilder(), uniformMap: {}, model: mockModel }; const shaderBuilder = renderResources.shaderBuilder; import__709.ModelClippingPlanesPipelineStage.process( renderResources, mockModel, mockFrameState ); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_CLIPPING_PLANES", "CLIPPING_PLANES_LENGTH 1", "CLIPPING_PLANES_TEXTURE_WIDTH 1", "CLIPPING_PLANES_TEXTURE_HEIGHT 1" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform sampler2D model_clippingPlanes;", "uniform vec4 model_clippingPlanesEdgeStyle;", "uniform mat4 model_clippingPlanesMatrix;" ]); const uniformMap = renderResources.uniformMap; expect(uniformMap.model_clippingPlanes()).toBeDefined(); const edgeColor = clippingPlanes.edgeColor; const expectedStyle = new import__709.Color( edgeColor.r, edgeColor.g, edgeColor.b, clippingPlanes.edgeWidth ); expect( import__709.Color.equals(uniformMap.model_clippingPlanesEdgeStyle(), expectedStyle) ).toBe(true); expect( import__709.Matrix4.equals( uniformMap.model_clippingPlanesMatrix(), mockModel._clippingPlanesMatrix ) ).toBe(true); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__709._shadersModelClippingPlanesStageFS ]); }); it("configures the render resources for unioned clipping planes", function() { const mockFrameState = { context: {} }; const mockModel = { clippingPlanes, _clippingPlanesMatrix: import__709.Matrix4.clone(import__709.Matrix4.IDENTITY) }; clippingPlanes.unionClippingRegions = true; const renderResources = { shaderBuilder: new import__709.ShaderBuilder(), uniformMap: {}, model: mockModel }; const shaderBuilder = renderResources.shaderBuilder; import__709.ModelClippingPlanesPipelineStage.process( renderResources, mockModel, mockFrameState ); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_CLIPPING_PLANES", "CLIPPING_PLANES_LENGTH 1", "UNION_CLIPPING_REGIONS", "CLIPPING_PLANES_TEXTURE_WIDTH 1", "CLIPPING_PLANES_TEXTURE_HEIGHT 1" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform sampler2D model_clippingPlanes;", "uniform vec4 model_clippingPlanesEdgeStyle;", "uniform mat4 model_clippingPlanesMatrix;" ]); }); it("configures the render resources for float texture clipping planes", function() { const mockFrameState = { context: { floatingPointTexture: true } }; const mockModel = { clippingPlanes, _clippingPlanesMatrix: import__709.Matrix4.clone(import__709.Matrix4.IDENTITY) }; const renderResources = { shaderBuilder: new import__709.ShaderBuilder(), uniformMap: {}, model: mockModel }; const shaderBuilder = renderResources.shaderBuilder; import__709.ModelClippingPlanesPipelineStage.process( renderResources, mockModel, mockFrameState ); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_CLIPPING_PLANES", "CLIPPING_PLANES_LENGTH 1", "USE_CLIPPING_PLANES_FLOAT_TEXTURE", "CLIPPING_PLANES_TEXTURE_WIDTH 1", "CLIPPING_PLANES_TEXTURE_HEIGHT 1" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform sampler2D model_clippingPlanes;", "uniform vec4 model_clippingPlanesEdgeStyle;", "uniform mat4 model_clippingPlanesMatrix;" ]); }); }); // packages/engine/Specs/Scene/Model/ModelClippingPolygonsPipelineStageSpec.js var import__710 = __toESM(require_Cesium(), 1); describe("Scene/Model/ModelClippingPolygonsPipelineStage", function() { const positions = import__710.Cartesian3.fromRadiansArray([ -1.3194369277314022, 0.6988062530900625, -1.31941, 0.69879, -1.3193931220959367, 0.698743632490865 ]); let polygon, clippingPolygons, context, model; beforeEach(function() { polygon = new import__710.ClippingPolygon({ positions }); clippingPolygons = new import__710.ClippingPolygonCollection({ polygons: [polygon] }); clippingPolygons._clippingPolygonsTexture = { width: 1, height: 1 }; model = new import__710.Model({ loader: {}, resource: {} }); context = createContext_default(); import__710.ContextLimits._maximumTextureSize = 64; }); afterEach(function() { context.destroyForSpecs(); }); it("configures the render resources for default clipping polygons", function() { if (!context.webgl2) { return; } const mockFrameState = { context }; const renderResources = { shaderBuilder: new import__710.ShaderBuilder(), uniformMap: {}, model }; const shaderBuilder = renderResources.shaderBuilder; model.clippingPolygons = clippingPolygons; clippingPolygons.update(mockFrameState); import__710.ModelClippingPolygonsPipelineStage.process( renderResources, model, mockFrameState ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "CLIPPING_POLYGON_REGIONS_LENGTH 1", "ENABLE_CLIPPING_POLYGONS" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "CLIPPING_POLYGON_REGIONS_LENGTH 1", "ENABLE_CLIPPING_POLYGONS" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform sampler2D model_clippingExtents;" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform sampler2D model_clippingDistance;" ]); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "vec2 v_clippingPosition;", "int v_regionIndex;" ]); const uniformMap = renderResources.uniformMap; expect(uniformMap.model_clippingDistance()).toBeDefined(); expect(uniformMap.model_clippingExtents()).toBeDefined(); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__710._shadersModelClippingPolygonsStageVS ]); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__710._shadersModelClippingPolygonsStageFS ]); }); it("configures the render resources for inverse clipping", function() { if (!context.webgl2) { return; } const mockFrameState = { context }; const renderResources = { shaderBuilder: new import__710.ShaderBuilder(), uniformMap: {}, model }; const shaderBuilder = renderResources.shaderBuilder; clippingPolygons.inverse = true; model.clippingPolygons = clippingPolygons; clippingPolygons.update(mockFrameState); import__710.ModelClippingPolygonsPipelineStage.process( renderResources, model, mockFrameState ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "CLIPPING_POLYGON_REGIONS_LENGTH 1", "ENABLE_CLIPPING_POLYGONS" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "CLIPPING_POLYGON_REGIONS_LENGTH 1", "ENABLE_CLIPPING_POLYGONS", "CLIPPING_INVERSE" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform sampler2D model_clippingExtents;" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform sampler2D model_clippingDistance;" ]); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "vec2 v_clippingPosition;", "int v_regionIndex;" ]); const uniformMap = renderResources.uniformMap; expect(uniformMap.model_clippingDistance()).toBeDefined(); expect(uniformMap.model_clippingExtents()).toBeDefined(); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__710._shadersModelClippingPolygonsStageVS ]); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__710._shadersModelClippingPolygonsStageFS ]); }); }); // packages/engine/Specs/Scene/Model/ModelColorPipelineStageSpec.js var import__711 = __toESM(require_Cesium(), 1); describe( "Scene/Model/ModelColorPipelineStage", function() { function mockRenderResources(mockModel) { const defaultAlphaOptions = new import__711.ModelAlphaOptions(); defaultAlphaOptions.pass = import__711.Pass.OPAQUE; return { shaderBuilder: new import__711.ShaderBuilder(), uniformMap: {}, model: mockModel, alphaOptions: defaultAlphaOptions, renderStateOptions: import__711.RenderState.getState(import__711.RenderState.fromCache()) }; } it("configures the render resources for opaque color", function() { const mockModel = { color: import__711.Color.RED, colorBlendMode: import__711.ColorBlendMode.REPLACE, colorBlendAmount: 0.25 }; const renderResources = mockRenderResources(mockModel); const shaderBuilder = renderResources.shaderBuilder; import__711.ModelColorPipelineStage.process(renderResources, mockModel); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_MODEL_COLOR" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform vec4 model_color;", "uniform float model_colorBlend;" ]); expect(renderResources.alphaOptions.pass).toBe(import__711.Pass.OPAQUE); const uniformMap = renderResources.uniformMap; expect(uniformMap.model_color()).toEqual(mockModel.color); expect(uniformMap.model_colorBlend()).toEqual( import__711.ColorBlendMode.getColorBlend( mockModel.colorBlendMode, mockModel.colorBlendAmount ) ); }); it("configures the render resources for translucent color", function() { const mockModel = { color: import__711.Color.RED.withAlpha(0.2), colorBlendMode: import__711.ColorBlendMode.MIX, colorBlendAmount: 0.25 }; const renderResources = mockRenderResources(mockModel); const shaderBuilder = renderResources.shaderBuilder; import__711.ModelColorPipelineStage.process(renderResources, mockModel); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_MODEL_COLOR" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform vec4 model_color;", "uniform float model_colorBlend;" ]); expect(renderResources.alphaOptions.pass).toBe(import__711.Pass.TRANSLUCENT); const uniformMap = renderResources.uniformMap; expect(uniformMap.model_color()).toEqual(mockModel.color); expect(uniformMap.model_colorBlend()).toEqual( import__711.ColorBlendMode.getColorBlend( mockModel.colorBlendMode, mockModel.colorBlendAmount ) ); }); it("configures the render state for transparent color", function() { const mockModel = { color: import__711.Color.RED.withAlpha(0), colorBlendMode: import__711.ColorBlendMode.MIX, colorBlendAmount: 0.25, hasSilhouette: function() { return false; } }; const renderResources = mockRenderResources(mockModel); import__711.ModelColorPipelineStage.process(renderResources, mockModel); const renderStateOptions = renderResources.renderStateOptions; expect(renderStateOptions.colorMask).toEqual({ red: false, green: false, blue: false, alpha: false }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/ModelDrawCommandSpec.js var import__712 = __toESM(require_Cesium(), 1); describe( "Scene/Model/ModelDrawCommand", function() { const noColor = new import__712.Color(0, 0, 0, 0); const scratchModelMatrix = new import__712.Matrix4(); const scratchExpectedMatrix = new import__712.Matrix4(); const scratchTranslation = new import__712.Cartesian3(); const scratchExpectedTranslation = new import__712.Cartesian3(); const scratchProjection = new import__712.GeographicProjection(); const mockContext = { stencilBuffer: true }; const mockFrameState = { commandList: [], mode: import__712.SceneMode.SCENE3D, mapProjection: scratchProjection, context: mockContext }; const mockFrameState2D = { commandList: [], mode: import__712.SceneMode.SCENE2D, mapProjection: scratchProjection, context: mockContext }; function mockModel(options) { options = (0, import__712.defaultValue)(options, import__712.defaultValue.EMPTY_OBJECT); const modelColor = (0, import__712.defaultValue)(options.color, import__712.Color.WHITE); const silhouetteColor = (0, import__712.defaultValue)(options.silhouetteColor, import__712.Color.RED); const silhouetteSize = (0, import__712.defaultValue)(options.silhouetteSize, 0); const skipLevelOfDetail = (0, import__712.defaultValue)(options.skipLevelOfDetail, false); return { sceneGraph: { _boundingSphere2D: new import__712.BoundingSphere(import__712.Cartesian3.ZERO, 1) }, color: modelColor, silhouetteSize, silhouetteColor, _silhouetteId: 1, isTranslucent: function() { return modelColor.alpha > 0 && modelColor.alpha < 1; }, isInvisible: function() { return modelColor.alpha === 0; }, hasSilhouette: function() { return silhouetteSize > 0; }, hasSkipLevelOfDetail: function() { return skipLevelOfDetail; }, shadows: import__712.ShadowMode.ENABLED, _projectTo2D: false, content: { tileset: { hasMixedContent: true, _backfaceCommands: [] }, tile: { _finalResolution: false, _selectionDepth: 0 } } }; } function mockRenderResources(options) { options = (0, import__712.defaultValue)(options, import__712.defaultValue.EMPTY_OBJECT); const model = mockModel(options.modelOptions); const resources = { model, runtimePrimitive: { primitive: { material: { doubleSided: false } }, boundingSphere: new import__712.BoundingSphere(import__712.Cartesian3.ZERO, 1) }, hasSilhouette: model.hasSilhouette(), hasSkipLevelOfDetail: model.hasSkipLevelOfDetail() }; const boundingSphereTransform2D = (0, import__712.defaultValue)( options.boundingSphereTransform2D, import__712.Matrix4.IDENTITY ); const sceneGraph = resources.model.sceneGraph; sceneGraph._boundingSphere2D = import__712.BoundingSphere.transform( sceneGraph._boundingSphere2D, boundingSphereTransform2D, sceneGraph._boundingSphere2D ); return resources; } function createDrawCommand2(options) { options = (0, import__712.defaultValue)(options, {}); options.modelMatrix = (0, import__712.defaultValue)( options.modelMatrix, import__712.Matrix4.clone(import__712.Matrix4.IDENTITY) ); const boundingSphere = new import__712.BoundingSphere(import__712.Cartesian3.ZERO, 1); options.boundingVolume = import__712.BoundingSphere.transform( boundingSphere, options.modelMatrix, boundingSphere ); options.renderState = (0, import__712.defaultValue)( options.renderState, import__712.RenderState.fromCache({ depthTest: { enabled: true, func: import__712.DepthFunction.LESS_OR_EQUAL } }) ); options.pass = (0, import__712.defaultValue)(options.pass, import__712.Pass.OPAQUE); options.uniformMap = {}; return new import__712.DrawCommand(options); } const idlMatrix = import__712.Matrix4.fromTranslation( import__712.Cartesian3.fromDegrees(180, 0), new import__712.Matrix4() ); const idlMatrix2D = import__712.Transforms.basisTo2D( mockFrameState2D.mapProjection, idlMatrix, idlMatrix ); function createModelDrawCommand(options) { options = (0, import__712.defaultValue)(options, import__712.defaultValue.EMPTY_OBJECT); const deriveSilhouette = options.deriveSilhouette; const derive2D = options.derive2D; const deriveSkipLevelOfDetail = options.deriveSkipLevelOfDetail; const modelOptions = { silhouetteSize: deriveSilhouette ? 1 : 0, skipLevelOfDetail: deriveSkipLevelOfDetail }; const transform2D = derive2D ? idlMatrix2D : import__712.Matrix4.IDENTITY; const renderResources = mockRenderResources({ modelOptions, boundingSphereTransform2D: transform2D }); const command = createDrawCommand2({ modelMatrix: transform2D, pass: import__712.Pass.OPAQUE }); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); if (derive2D) { drawCommand.pushCommands( mockFrameState2D, mockFrameState2D.commandList ); mockFrameState2D.commandList.length = 0; } return drawCommand; } function computeExpected2DMatrix(modelMatrix, frameState2) { const result = import__712.Matrix4.clone(modelMatrix, scratchExpectedMatrix); result[13] -= import__712.Math.sign(modelMatrix[13]) * 2 * import__712.Math.PI * frameState2.mapProjection.ellipsoid.maximumRadius; return result; } function verifyDerivedCommandsDefined(drawCommand, expected) { const translucentDefined = (0, import__712.defaultValue)(expected.translucent, false); const translucentCommand = drawCommand._translucentCommand; expect((0, import__712.defined)(translucentCommand)).toBe(translucentDefined); const skipLevelOfDetailDefined = (0, import__712.defaultValue)( expected.skipLevelOfDetail, false ); const skipLodBackfaceCommand = drawCommand._skipLodBackfaceCommand; const skipLodStencilCommand = drawCommand._skipLodStencilCommand; expect((0, import__712.defined)(skipLodBackfaceCommand)).toBe(skipLevelOfDetailDefined); expect((0, import__712.defined)(skipLodStencilCommand)).toBe(skipLevelOfDetailDefined); const silhouetteDefined = (0, import__712.defaultValue)(expected.silhouette, false); const silhouetteModelCommand = drawCommand._silhouetteModelCommand; const silhouetteColorCommand = drawCommand._silhouetteColorCommand; expect((0, import__712.defined)(silhouetteModelCommand)).toBe(silhouetteDefined); expect((0, import__712.defined)(silhouetteColorCommand)).toBe(silhouetteDefined); } function verifyDerivedCommandUpdateFlags(derivedCommand, expected) { expect(derivedCommand.updateShadows).toEqual(expected.updateShadows); expect(derivedCommand.updateBackFaceCulling).toEqual( expected.updateBackFaceCulling ); expect(derivedCommand.updateCullFace).toEqual(expected.updateCullFace); expect(derivedCommand.updateDebugShowBoundingVolume).toEqual( expected.updateDebugShowBoundingVolume ); } beforeEach(function() { mockFrameState.commandList.length = 0; mockFrameState2D.commandList.length = 0; }); it("throws for undefined command", function() { expect(function() { return new import__712.ModelDrawCommand({ command: void 0, primitiveRenderResources: {} }); }).toThrowDeveloperError(); }); it("throws for undefined primitiveRenderResources", function() { expect(function() { return new import__712.ModelDrawCommand({ command: new import__712.DrawCommand(), primitiveRenderResources: void 0 }); }).toThrowDeveloperError(); }); it("constructs", function() { const renderResources = mockRenderResources(); const command = createDrawCommand2(); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); expect(drawCommand.command).toBe(command); expect(drawCommand.runtimePrimitive).toBe( renderResources.runtimePrimitive ); expect(drawCommand.model).toBe(renderResources.model); expect(drawCommand.modelMatrix).toBe(command.modelMatrix); expect(drawCommand.boundingVolume).toBe(command.boundingVolume); const originalCommand = drawCommand._originalCommand; expect(originalCommand).toBeDefined(); expect(originalCommand.command).toBe(command); expect(originalCommand.is2D).toBe(false); verifyDerivedCommandUpdateFlags(originalCommand, { updateShadows: true, updateBackFaceCulling: true, updateCullFace: true, updateDebugShowBoundingVolume: true }); const derivedCommands = drawCommand._derivedCommands; expect(derivedCommands.length).toEqual(2); expect(derivedCommands[0]).toBe(originalCommand); verifyDerivedCommandsDefined(drawCommand, { translucent: true, skipLevelOfDetail: false, silhouette: false }); const translucentCommand = drawCommand._translucentCommand; expect(derivedCommands[1]).toBe(translucentCommand); expect(translucentCommand.is2D).toBe(false); verifyDerivedCommandUpdateFlags(translucentCommand, { updateShadows: true, updateBackFaceCulling: false, updateCullFace: false, updateDebugShowBoundingVolume: true }); const innerCommand = translucentCommand.command; expect(innerCommand).not.toEqual(command); expect(innerCommand.pass).toEqual(import__712.Pass.TRANSLUCENT); const renderState = innerCommand.renderState; expect(renderState.cull.enabled).toBe(false); expect(renderState.depthTest.enabled).toBe(true); expect(renderState.depthMask).toBe(false); const expectedBlending = (0, import__712.clone)(import__712.BlendingState.ALPHA_BLEND); expectedBlending.color = noColor; expect(renderState.blending).toEqual(expectedBlending); }); it("doesn't derive translucent command if original command is translucent", function() { const renderResources = mockRenderResources(); const command = createDrawCommand2({ pass: import__712.Pass.TRANSLUCENT }); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const originalCommand = drawCommand._originalCommand; expect(originalCommand).toBeDefined(); expect(originalCommand.command.pass).toBe(import__712.Pass.TRANSLUCENT); const derivedCommands = drawCommand._derivedCommands; expect(derivedCommands.length).toEqual(1); expect(derivedCommands[0]).toBe(originalCommand); expect(drawCommand._translucentCommand).toBeUndefined(); }); describe("silhouette commands", function() { function verifySilhouetteModelDerivedCommand(derivedCommand, stencilReference, modelIsInvisible) { const command = derivedCommand.command; const renderState = command.renderState; const expectedStencilTest = { enabled: true, frontFunction: import__712.WebGLConstants.ALWAYS, backFunction: import__712.WebGLConstants.ALWAYS, reference: stencilReference, mask: ~0, frontOperation: { fail: import__712.WebGLConstants.KEEP, zFail: import__712.WebGLConstants.KEEP, zPass: import__712.WebGLConstants.REPLACE }, backOperation: { fail: import__712.WebGLConstants.KEEP, zFail: import__712.WebGLConstants.KEEP, zPass: import__712.WebGLConstants.REPLACE } }; expect(renderState.stencilTest).toEqual(expectedStencilTest); if (modelIsInvisible) { const expectedColorMask = { red: false, green: false, blue: false, alpha: false }; expect(renderState.colorMask).toEqual(expectedColorMask); } } function verifySilhouetteColorDerivedCommand(derivedCommand, stencilReference, silhouetteIsTranslucent) { const command = derivedCommand.command; const renderState = command.renderState; expect(renderState.depthTest.enabled).toBe(true); expect(renderState.cull.enabled).toBe(false); if (silhouetteIsTranslucent) { expect(command.pass).toBe(import__712.Pass.TRANSLUCENT); expect(renderState.depthMask).toBe(false); const expectedBlending = (0, import__712.clone)(import__712.BlendingState.ALPHA_BLEND, true); expectedBlending.color = noColor; expect(renderState.blending).toEqual(expectedBlending); } const expectedStencilTest = { enabled: true, frontFunction: import__712.WebGLConstants.NOTEQUAL, backFunction: import__712.WebGLConstants.NOTEQUAL, reference: stencilReference, mask: ~0, frontOperation: { fail: import__712.WebGLConstants.KEEP, zFail: import__712.WebGLConstants.KEEP, zPass: import__712.WebGLConstants.KEEP }, backOperation: { fail: import__712.WebGLConstants.KEEP, zFail: import__712.WebGLConstants.KEEP, zPass: import__712.WebGLConstants.KEEP } }; expect(renderState.stencilTest).toEqual(expectedStencilTest); expect(command.uniformMap.model_silhouettePass()).toBe(true); expect(command.castShadows).toBe(false); expect(command.receiveShadows).toBe(false); } function verifySilhouetteCommands(drawCommand, modelIsTranslucent, modelIsInvisible, silhouetteIsTranslucent) { const command = drawCommand.command; const derivedCommands = drawCommand._derivedCommands; expect(derivedCommands.length).toEqual(3); const originalCommand = drawCommand._originalCommand; expect(derivedCommands[0]).toBe(originalCommand); expect(originalCommand.is2D).toBe(false); verifyDerivedCommandsDefined(drawCommand, { translucent: false, skipLevelOfDetail: false, silhouette: true }); const stencilReference = 1; const silhouetteModelCommand = derivedCommands[1]; expect(silhouetteModelCommand.command).not.toEqual(command); expect(silhouetteModelCommand.is2D).toBe(false); verifyDerivedCommandUpdateFlags(silhouetteModelCommand, { updateShadows: true, updateBackFaceCulling: !modelIsTranslucent, updateCullFace: !modelIsTranslucent, updateDebugShowBoundingVolume: true }); verifySilhouetteModelDerivedCommand( silhouetteModelCommand, stencilReference, modelIsInvisible ); const silhouetteColorCommand = derivedCommands[2]; expect(silhouetteColorCommand.command).not.toEqual(command); expect(silhouetteColorCommand.is2D).toBe(false); verifyDerivedCommandUpdateFlags(silhouetteColorCommand, { updateShadows: false, updateBackFaceCulling: false, updateCullFace: false, updateDebugShowBoundingVolume: false }); verifySilhouetteColorDerivedCommand( silhouetteColorCommand, stencilReference, silhouetteIsTranslucent ); } it("derives silhouette commands for opaque model", function() { const renderResources = mockRenderResources({ modelOptions: { silhouetteSize: 1 } }); const command = createDrawCommand2(); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const modelIsTranslucent = false; const modelIsInvisible = false; const silhouetteIsTranslucent = false; verifySilhouetteCommands( drawCommand, modelIsTranslucent, modelIsInvisible, silhouetteIsTranslucent ); }); it("derives silhouette commands for translucent model", function() { const renderResources = mockRenderResources({ modelOptions: { color: new import__712.Color(1, 1, 1, 0.5), silhouetteSize: 1 } }); const command = createDrawCommand2({ pass: import__712.Pass.TRANSLUCENT }); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const modelIsTranslucent = true; const modelIsInvisible = false; const silhouetteIsTranslucent = false; verifySilhouetteCommands( drawCommand, modelIsTranslucent, modelIsInvisible, silhouetteIsTranslucent ); }); it("derives silhouette commands for invisible model", function() { const renderResources = mockRenderResources({ modelOptions: { color: new import__712.Color(1, 1, 1, 0), silhouetteSize: 1 } }); const command = createDrawCommand2(); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const modelIsTranslucent = false; const modelIsInvisible = true; const silhouetteIsTranslucent = false; verifySilhouetteCommands( drawCommand, modelIsTranslucent, modelIsInvisible, silhouetteIsTranslucent ); }); it("derives silhouette commands for translucent silhouette color", function() { const renderResources = mockRenderResources({ modelOptions: { color: new import__712.Color(1, 1, 1, 1), silhouetteColor: new import__712.Color(1, 1, 1, 0.5), silhouetteSize: 1 } }); const command = createDrawCommand2(); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const modelIsTranslucent = false; const modelIsInvisible = false; const silhouetteIsTranslucent = true; verifySilhouetteCommands( drawCommand, modelIsTranslucent, modelIsInvisible, silhouetteIsTranslucent ); }); }); describe("skipLeveOfDetail commands", function() { const expectedColorMask = { red: false, green: false, blue: false, alpha: false }; const expectedPolygonOffset = { enabled: true, factor: 5, units: 5 }; function verifySkipLodBackfaceCommand(command) { const renderState = command.renderState; expect(renderState.cull.enabled).toBe(true); expect(renderState.cull.face).toBe(import__712.CullFace.FRONT); expect(renderState.colorMask).toEqual(expectedColorMask); expect(renderState.polygonOffset).toEqual(expectedPolygonOffset); const uniformMap = command.uniformMap; expect(uniformMap.u_polygonOffset()).toEqual(new import__712.Cartesian2(5, 5)); expect(command.castShadows).toBe(false); expect(command.receiveShadows).toBe(false); } function verifySkipLodStencilCommand(command) { const renderState = command.renderState; const stencilTest = renderState.stencilTest; expect(stencilTest.enabled).toBe(true); expect(stencilTest.mask).toEqual(import__712.StencilConstants.SKIP_LOD_MASK); expect(stencilTest.reference).toEqual( import__712.StencilConstants.CESIUM_3D_TILE_MASK ); expect(stencilTest.frontFunction).toEqual( import__712.StencilFunction.GREATER_OR_EQUAL ); expect(stencilTest.frontOperation.zPass).toEqual( import__712.StencilOperation.REPLACE ); expect(stencilTest.backFunction).toEqual( import__712.StencilFunction.GREATER_OR_EQUAL ); expect(stencilTest.backOperation.zPass).toEqual( import__712.StencilOperation.REPLACE ); const expectedStencilMask = import__712.StencilConstants.CESIUM_3D_TILE_MASK | import__712.StencilConstants.SKIP_LOD_MASK; expect(renderState.stencilMask).toEqual(expectedStencilMask); } it("constructs skipLevelOfDetail commands", function() { const renderResources = mockRenderResources({ modelOptions: { skipLevelOfDetail: true } }); const command = createDrawCommand2(); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const derivedCommands = drawCommand._derivedCommands; expect(derivedCommands.length).toEqual(4); const originalCommand = drawCommand._originalCommand; expect(derivedCommands[0]).toBe(originalCommand); expect(originalCommand.is2D).toBe(false); verifyDerivedCommandsDefined(drawCommand, { translucent: true, skipLevelOfDetail: true, silhouette: false }); const translucentCommand = drawCommand._translucentCommand; expect(derivedCommands[1]).toBe(translucentCommand); expect(translucentCommand.is2D).toBe(false); const skipLodBackfaceCommand = drawCommand._skipLodBackfaceCommand; expect(derivedCommands[2]).toBe(skipLodBackfaceCommand); expect(skipLodBackfaceCommand.is2D).toBe(false); verifyDerivedCommandUpdateFlags(skipLodBackfaceCommand, { updateShadows: false, updateBackFaceCulling: false, updateCullFace: true, updateDebugShowBoundingVolume: false }); const innerBackfaceCommand = skipLodBackfaceCommand.command; expect(innerBackfaceCommand).not.toEqual(command); verifySkipLodBackfaceCommand(innerBackfaceCommand); const skipLodStencilCommand = drawCommand._skipLodStencilCommand; expect(derivedCommands[3]).toBe(skipLodStencilCommand); expect(skipLodStencilCommand.is2D).toBe(false); verifyDerivedCommandUpdateFlags(skipLodStencilCommand, { updateShadows: true, updateBackFaceCulling: true, updateCullFace: true, updateDebugShowBoundingVolume: true }); const innerStencilCommand = skipLodStencilCommand.command; expect(innerStencilCommand).not.toEqual(command); verifySkipLodStencilCommand(innerStencilCommand); }); it("doesn't construct skipLevelOfDetail commands if original command is translucent", function() { const renderResources = mockRenderResources({ modelOptions: { skipLevelOfDetail: true } }); const command = createDrawCommand2({ pass: import__712.Pass.TRANSLUCENT }); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const originalCommand = drawCommand._originalCommand; expect(originalCommand).toBeDefined(); expect(originalCommand.command.pass).toBe(import__712.Pass.TRANSLUCENT); const derivedCommands = drawCommand._derivedCommands; expect(derivedCommands.length).toEqual(1); expect(derivedCommands[0]).toBe(originalCommand); verifyDerivedCommandsDefined(drawCommand, { translucent: false, skipLevelOfDetail: false, silhouette: false }); }); }); describe("pushCommands", function() { it("pushCommands pushes original command if styleCommandsNeeded is undefined", function() { const renderResources = mockRenderResources(); const command = createDrawCommand2(); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const commandList = mockFrameState.commandList; drawCommand.pushCommands(mockFrameState, commandList); expect(commandList.length).toEqual(1); expect(commandList[0]).toBe(command); }); it("pushCommands pushes original command if style is ALL_OPAQUE", function() { const renderResources = mockRenderResources(); const command = createDrawCommand2(); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const model = renderResources.model; model.styleCommandsNeeded = import__712.StyleCommandsNeeded.ALL_OPAQUE; const commandList = mockFrameState.commandList; drawCommand.pushCommands(mockFrameState, commandList); expect(commandList.length).toEqual(1); expect(commandList[0]).toBe(command); }); it("pushCommands pushes translucent command if style is ALL_TRANSLUCENT", function() { const renderResources = mockRenderResources(); const command = createDrawCommand2(); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const model = renderResources.model; model.styleCommandsNeeded = import__712.StyleCommandsNeeded.ALL_TRANSLUCENT; const commandList = mockFrameState.commandList; drawCommand.pushCommands(mockFrameState, commandList); expect(commandList.length).toEqual(1); const translucentDrawCommand = drawCommand._translucentCommand.command; expect(commandList[0]).toBe(translucentDrawCommand); }); it("pushCommands pushes both commands if style is OPAQUE_AND_TRANSLUCENT", function() { const renderResources = mockRenderResources(); const command = createDrawCommand2(); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const model = renderResources.model; model.styleCommandsNeeded = import__712.StyleCommandsNeeded.OPAQUE_AND_TRANSLUCENT; const originalDrawCommand = drawCommand._originalCommand.command; const translucentDrawCommand = drawCommand._translucentCommand.command; const commandList = mockFrameState.commandList; drawCommand.pushCommands(mockFrameState, commandList); expect(commandList.length).toEqual(2); expect(commandList[0]).toBe(translucentDrawCommand); expect(commandList[1]).toBe(originalDrawCommand); }); it("pushCommands pushes silhouette model command", function() { const renderResources = mockRenderResources({ modelOptions: { silhouetteSize: 1 } }); const command = createDrawCommand2(); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const silhouetteModelDrawCommand = drawCommand._silhouetteModelCommand.command; const commandList = mockFrameState.commandList; drawCommand.pushCommands(mockFrameState, commandList); expect(commandList.length).toEqual(1); expect(commandList[0]).toBe(silhouetteModelDrawCommand); }); it("pushCommands pushes skipLevelOfDetail commands", function() { const renderResources = mockRenderResources({ modelOptions: { skipLevelOfDetail: true } }); const command = createDrawCommand2(); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const skipLodBackfaceCommand = drawCommand._skipLodBackfaceCommand; const skipLodStencilCommand = drawCommand._skipLodStencilCommand; const commandList = mockFrameState.commandList; drawCommand.pushCommands(mockFrameState, commandList); expect(commandList.length).toEqual(1); expect(commandList[0]).toBe(skipLodStencilCommand.command); const tileset = drawCommand.model.content.tileset; const backfaceCommands = tileset._backfaceCommands; expect(backfaceCommands.length).toEqual(1); expect(backfaceCommands[0]).toBe(skipLodBackfaceCommand.command); }); it("pushCommands doesn't push skipLevelOfDetail backface commmand if tile is at final resolution", function() { const renderResources = mockRenderResources({ modelOptions: { skipLevelOfDetail: true } }); const command = createDrawCommand2(); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const content = drawCommand.model.content; content.tile._finalResolution = true; const skipLodStencilCommand = drawCommand._skipLodStencilCommand; const commandList = mockFrameState.commandList; drawCommand.pushCommands(mockFrameState, commandList); expect(commandList.length).toEqual(1); expect(commandList[0]).toBe(skipLodStencilCommand.command); const backfaceCommands = content.tileset._backfaceCommands; expect(backfaceCommands.length).toEqual(0); }); it("pushCommands derives 2D command if model is near IDL", function() { const renderResources = mockRenderResources({ boundingSphereTransform2D: idlMatrix2D }); const command = createDrawCommand2({ modelMatrix: idlMatrix2D }); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const originalCommand = drawCommand._originalCommand; expect(originalCommand.derivedCommand2D).toBeUndefined(); drawCommand.pushCommands( mockFrameState2D, mockFrameState2D.commandList ); const originalCommand2D = originalCommand.derivedCommand2D; expect(originalCommand2D).toBeDefined(); expect(originalCommand2D.is2D).toBe(true); const originalDrawCommand = originalCommand.command; const originalDrawCommand2D = originalCommand2D.command; expect(originalDrawCommand.modelMatrix).toBe(drawCommand._modelMatrix); expect(originalDrawCommand2D.modelMatrix).toBe( drawCommand._modelMatrix2D ); const commandList = mockFrameState2D.commandList; expect(commandList.length).toEqual(2); expect(commandList[0]).toBe(originalDrawCommand); expect(commandList[1]).toBe(originalDrawCommand2D); }); it("pushCommands derives 2D translucent command", function() { const renderResources = mockRenderResources({ boundingSphereTransform2D: idlMatrix2D }); const command = createDrawCommand2({ modelMatrix: idlMatrix2D }); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const model = renderResources.model; model.styleCommandsNeeded = import__712.StyleCommandsNeeded.OPAQUE_AND_TRANSLUCENT; const originalCommand = drawCommand._originalCommand; const translucentCommand = drawCommand._translucentCommand; expect(originalCommand.derivedCommand2D).toBeUndefined(); expect(translucentCommand.derivedCommand2D).toBeUndefined(); drawCommand.pushCommands( mockFrameState2D, mockFrameState2D.commandList ); const originalCommand2D = originalCommand.derivedCommand2D; expect(originalCommand2D).toBeDefined(); expect(originalCommand2D.is2D).toBe(true); const translucentCommand2D = translucentCommand.derivedCommand2D; expect(translucentCommand2D).toBeDefined(); expect(translucentCommand2D.is2D).toBe(true); const originalDrawCommand = originalCommand.command; const originalDrawCommand2D = originalCommand2D.command; const translucentDrawCommand = translucentCommand.command; const translucentDrawCommand2D = translucentCommand2D.command; expect(translucentDrawCommand.modelMatrix).toBe( drawCommand._modelMatrix ); expect(translucentDrawCommand2D.modelMatrix).toBe( drawCommand._modelMatrix2D ); const commandList = mockFrameState2D.commandList; expect(commandList.length).toEqual(4); expect(commandList[0]).toBe(translucentDrawCommand); expect(commandList[1]).toBe(translucentDrawCommand2D); expect(commandList[2]).toBe(originalDrawCommand); expect(commandList[3]).toBe(originalDrawCommand2D); }); it("pushCommands derives 2D silhouette commands", function() { const renderResources = mockRenderResources({ modelOptions: { silhouetteSize: 1 }, boundingSphereTransform2D: idlMatrix2D }); const command = createDrawCommand2({ modelMatrix: idlMatrix2D }); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const silhouetteModelCommand = drawCommand._silhouetteModelCommand; const silhouetteColorCommand = drawCommand._silhouetteColorCommand; expect(silhouetteModelCommand.derivedCommand2D).toBeUndefined(); expect(silhouetteColorCommand.derivedCommand2D).toBeUndefined(); drawCommand.pushCommands( mockFrameState2D, mockFrameState2D.commandList ); const silhouetteModelCommand2D = silhouetteModelCommand.derivedCommand2D; expect(silhouetteModelCommand2D).toBeDefined(); expect(silhouetteModelCommand2D.is2D).toBe(true); const silhouetteColorCommand2D = silhouetteColorCommand.derivedCommand2D; expect(silhouetteColorCommand2D).toBeDefined(); expect(silhouetteColorCommand2D.is2D).toBe(true); const modelDrawCommand = silhouetteModelCommand.command; const modelDrawCommand2D = silhouetteModelCommand2D.command; expect(modelDrawCommand.modelMatrix).toBe(drawCommand._modelMatrix); expect(modelDrawCommand2D.modelMatrix).toBe(drawCommand._modelMatrix2D); const colorDrawCommand = silhouetteColorCommand.command; const colorDrawCommand2D = silhouetteColorCommand2D.command; expect(colorDrawCommand.modelMatrix).toBe(drawCommand._modelMatrix); expect(colorDrawCommand2D.modelMatrix).toBe(drawCommand._modelMatrix2D); const commandList = mockFrameState2D.commandList; expect(commandList.length).toEqual(2); expect(commandList[0]).toBe(modelDrawCommand); expect(commandList[1]).toBe(modelDrawCommand2D); }); it("pushCommands derives 2D skipLevelOfDetail commands", function() { const renderResources = mockRenderResources({ modelOptions: { skipLevelOfDetail: true }, boundingSphereTransform2D: idlMatrix2D }); const command = createDrawCommand2({ modelMatrix: idlMatrix2D }); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const skipLodBackfaceCommand = drawCommand._skipLodBackfaceCommand; const skipLodStencilCommand = drawCommand._skipLodStencilCommand; expect(skipLodBackfaceCommand.derivedCommand2D).toBeUndefined(); expect(skipLodStencilCommand.derivedCommand2D).toBeUndefined(); drawCommand.pushCommands( mockFrameState2D, mockFrameState2D.commandList ); const skipLodBackfaceCommand2D = skipLodBackfaceCommand.derivedCommand2D; expect(skipLodBackfaceCommand2D).toBeDefined(); expect(skipLodBackfaceCommand2D.is2D).toBe(true); const skipLodStencilCommand2D = skipLodStencilCommand.derivedCommand2D; expect(skipLodStencilCommand2D).toBeDefined(); expect(skipLodStencilCommand2D.is2D).toBe(true); const backfaceDrawCommand = skipLodBackfaceCommand.command; const backfaceDrawCommand2D = skipLodBackfaceCommand2D.command; expect(backfaceDrawCommand.modelMatrix).toBe(drawCommand._modelMatrix); expect(backfaceDrawCommand2D.modelMatrix).toBe( drawCommand._modelMatrix2D ); const stencilDrawCommand = skipLodStencilCommand.command; const stencilDrawCommand2D = skipLodStencilCommand2D.command; expect(stencilDrawCommand.modelMatrix).toBe(drawCommand._modelMatrix); expect(stencilDrawCommand2D.modelMatrix).toBe( drawCommand._modelMatrix2D ); const commandList = mockFrameState2D.commandList; expect(commandList.length).toEqual(2); expect(commandList[0]).toBe(stencilDrawCommand); expect(commandList[1]).toBe(stencilDrawCommand2D); const tileset = drawCommand.model.content.tileset; const backfaceCommands = tileset._backfaceCommands; expect(backfaceCommands.length).toEqual(2); expect(backfaceCommands[0]).toBe(backfaceDrawCommand); expect(backfaceCommands[1]).toBe(backfaceDrawCommand2D); }); it("pushCommands doesn't derive 2D commands if model is not near IDL", function() { const modelMatrix = import__712.Matrix4.fromTranslation( import__712.Cartesian3.fromDegrees(100, 250), scratchModelMatrix ); const modelMatrix2D = import__712.Transforms.basisTo2D( mockFrameState2D.mapProjection, modelMatrix, modelMatrix ); const renderResources = mockRenderResources({ boundingSphereTransform2D: modelMatrix2D }); const command = createDrawCommand2({ modelMatrix: modelMatrix2D }); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const originalCommand = drawCommand._originalCommand; expect(originalCommand.derivedCommand2D).toBeUndefined(); drawCommand.pushCommands( mockFrameState2D, mockFrameState2D.commandList ); expect(originalCommand.derivedCommand2D).toBeUndefined(); const commandList = mockFrameState2D.commandList; expect(commandList.length).toEqual(1); expect(commandList[0]).toBe(originalCommand.command); }); it("pushCommands updates model matrix for 2D commands", function() { const renderResources = mockRenderResources({ boundingSphereTransform2D: idlMatrix2D }); const command = createDrawCommand2({ modelMatrix: idlMatrix2D }); const drawCommand = new import__712.ModelDrawCommand({ primitiveRenderResources: renderResources, command }); const translation = import__712.Matrix4.getTranslation( idlMatrix2D, scratchTranslation ); drawCommand.pushCommands( mockFrameState2D, mockFrameState2D.commandList ); const expectedModelMatrix = computeExpected2DMatrix( idlMatrix2D, mockFrameState2D ); const expectedTranslation = import__712.Matrix4.getTranslation( expectedModelMatrix, scratchExpectedTranslation ); const originalCommand = drawCommand._originalCommand; const originalCommand2D = originalCommand.derivedCommand2D; const translucentCommand = drawCommand._translucentCommand; const translucentCommand2D = translucentCommand.derivedCommand2D; const originalDrawCommand = originalCommand.command; const translucentDrawCommand = translucentCommand.command; expect(originalDrawCommand.modelMatrix).toEqual(idlMatrix2D); expect(translucentDrawCommand.modelMatrix).toEqual(idlMatrix2D); expect(originalDrawCommand.boundingVolume.center).toEqual(translation); expect(translucentDrawCommand.boundingVolume.center).toEqual( translation ); const originalDrawCommand2D = originalCommand2D.command; const translucentDrawCommand2D = translucentCommand2D.command; expect(originalDrawCommand2D.modelMatrix).toEqual(expectedModelMatrix); expect(translucentDrawCommand2D.modelMatrix).toEqual( expectedModelMatrix ); expect(originalDrawCommand2D.boundingVolume.center).toEqual( expectedTranslation ); expect(translucentDrawCommand2D.boundingVolume.center).toEqual( expectedTranslation ); }); }); describe("pushSilhouetteCommands", function() { it("pushSilhouetteCommands pushes silhouette-pass commands", function() { const drawCommand = createModelDrawCommand({ deriveSilhouette: true }); const silhouetteModelCommand = drawCommand._silhouetteModelCommand; const silhouetteColorCommand = drawCommand._silhouetteColorCommand; const modelDrawCommand = silhouetteModelCommand.command; const colorDrawCommand = silhouetteColorCommand.command; const commandList = mockFrameState.commandList; drawCommand.pushCommands(mockFrameState, commandList); expect(commandList.length).toEqual(1); expect(commandList[0]).toBe(modelDrawCommand); const silhouetteCommands = []; drawCommand.pushSilhouetteCommands(mockFrameState, silhouetteCommands); expect(silhouetteCommands.length).toEqual(1); expect(silhouetteCommands[0]).toBe(colorDrawCommand); }); it("pushSilhouetteCommands pushes 2D silhouette-pass commands", function() { const drawCommand = createModelDrawCommand({ derive2D: true, deriveSilhouette: true }); const silhouetteModelCommand = drawCommand._silhouetteModelCommand; const silhouetteColorCommand = drawCommand._silhouetteColorCommand; const silhouetteModelCommand2D = silhouetteModelCommand.derivedCommand2D; const silhouetteColorCommand2D = silhouetteColorCommand.derivedCommand2D; const modelDrawCommand = silhouetteModelCommand.command; const modelDrawCommand2D = silhouetteModelCommand2D.command; const colorDrawCommand = silhouetteColorCommand.command; const colorDrawCommand2D = silhouetteColorCommand2D.command; const commandList = mockFrameState2D.commandList; drawCommand.pushCommands(mockFrameState2D, commandList); expect(commandList.length).toEqual(2); expect(commandList[0]).toBe(modelDrawCommand); expect(commandList[1]).toBe(modelDrawCommand2D); const silhouetteCommands = []; drawCommand.pushSilhouetteCommands( mockFrameState2D, silhouetteCommands ); expect(silhouetteCommands.length).toEqual(2); expect(silhouetteCommands[0]).toBe(colorDrawCommand); expect(silhouetteCommands[1]).toBe(colorDrawCommand2D); }); }); describe("model matrix", function() { it("updates model matrix", function() { const drawCommand = createModelDrawCommand(); expect(drawCommand.modelMatrix).toEqual(import__712.Matrix4.IDENTITY); expect(drawCommand.boundingVolume.center).toEqual(import__712.Cartesian3.ZERO); const derivedCommands = drawCommand._derivedCommands; const length2 = derivedCommands.length; expect(length2).toEqual(2); for (let i = 0; i < length2; i++) { const command = derivedCommands[i].command; expect(command.modelMatrix).toEqual(import__712.Matrix4.IDENTITY); expect(command.boundingVolume.center).toEqual(import__712.Cartesian3.ZERO); } const translation = import__712.Cartesian3.fromDegrees(100, 25); const modelMatrix = import__712.Matrix4.fromTranslation( translation, scratchModelMatrix ); drawCommand.modelMatrix = modelMatrix; expect(drawCommand.modelMatrix).toEqual(modelMatrix); expect(drawCommand.boundingVolume.center).toEqual(translation); for (let i = 0; i < length2; i++) { const command = derivedCommands[i].command; expect(command.modelMatrix).toEqual(modelMatrix); expect(command.boundingVolume.center).toEqual(translation); } }); it("updates model matrix for 2D commands", function() { const drawCommand = createModelDrawCommand({ derive2D: true }); const derivedCommands = drawCommand._derivedCommands; expect(derivedCommands.length).toEqual(4); let modelMatrix2D = import__712.Matrix4.fromTranslation( import__712.Cartesian3.fromDegrees(100, 25), scratchModelMatrix ); modelMatrix2D = import__712.Transforms.basisTo2D( mockFrameState2D.mapProjection, modelMatrix2D, modelMatrix2D ); const translation = import__712.Matrix4.getTranslation( modelMatrix2D, scratchTranslation ); drawCommand.modelMatrix = modelMatrix2D; expect(drawCommand.modelMatrix).toEqual(modelMatrix2D); expect(drawCommand.boundingVolume.center).toEqual(translation); for (let i = 0; i < 2; i++) { const command = derivedCommands[i].command; expect(command.modelMatrix).toEqual(modelMatrix2D); expect(command.boundingVolume.center).toEqual(translation); } drawCommand.pushCommands( mockFrameState2D, mockFrameState2D.commandList ); const expectedModelMatrix = computeExpected2DMatrix( modelMatrix2D, mockFrameState2D ); const expectedTranslation = import__712.Matrix4.getTranslation( expectedModelMatrix, scratchExpectedTranslation ); for (let i = 2; i < 4; i++) { const command = derivedCommands[i].command; expect(command.modelMatrix).toEqual(expectedModelMatrix); expect(command.boundingVolume.center).toEqual(expectedTranslation); } }); }); describe("shadows", function() { it("updates shadows", function() { const drawCommand = createModelDrawCommand(); const derivedCommands = drawCommand._derivedCommands; const length2 = derivedCommands.length; expect(length2).toEqual(2); for (let i = 0; i < length2; i++) { const command = derivedCommands[i].command; expect(command.castShadows).toBe(false); expect(command.receiveShadows).toBe(false); } drawCommand.shadows = import__712.ShadowMode.ENABLED; for (let i = 0; i < length2; i++) { const command = derivedCommands[i].command; expect(command.castShadows).toBe(true); expect(command.receiveShadows).toBe(true); } }); it("doesn't update shadows for silhouette color command", function() { const drawCommand = createModelDrawCommand({ deriveSilhouette: true }); const derivedCommands = drawCommand._derivedCommands; const length2 = derivedCommands.length; expect(length2).toEqual(3); for (let i = 0; i < length2; i++) { const command = derivedCommands[i].command; expect(command.castShadows).toBe(false); expect(command.receiveShadows).toBe(false); } drawCommand.shadows = import__712.ShadowMode.ENABLED; for (let i = 0; i < length2; i++) { const derivedCommand = derivedCommands[i]; const command = derivedCommand.command; const updateShadows = derivedCommand.updateShadows; if (!updateShadows) { expect(derivedCommand).toBe(drawCommand._silhouetteColorCommand); } expect(command.castShadows).toBe(updateShadows); expect(command.receiveShadows).toBe(updateShadows); } }); it("doesn't update shadows for skipLevelOfDetail backface command", function() { const drawCommand = createModelDrawCommand({ deriveSkipLevelOfDetail: true }); const derivedCommands = drawCommand._derivedCommands; const length2 = derivedCommands.length; expect(length2).toEqual(4); for (let i = 0; i < length2; i++) { const command = derivedCommands[i].command; expect(command.castShadows).toBe(false); expect(command.receiveShadows).toBe(false); } drawCommand.shadows = import__712.ShadowMode.ENABLED; for (let i = 0; i < length2; i++) { const derivedCommand = derivedCommands[i]; const command = derivedCommand.command; const updateShadows = derivedCommand.updateShadows; if (!updateShadows) { expect(derivedCommand).toBe(drawCommand._skipLodBackfaceCommand); } expect(command.castShadows).toBe(updateShadows); expect(command.receiveShadows).toBe(updateShadows); } }); it("doesn't update shadows for 2D commands", function() { const drawCommand = createModelDrawCommand({ derive2D: true }); const derivedCommands = drawCommand._derivedCommands; const length2 = derivedCommands.length; expect(length2).toEqual(4); for (let i = 0; i < length2; i++) { const command = derivedCommands[i].command; expect(command.castShadows).toBe(false); expect(command.receiveShadows).toBe(false); } drawCommand.shadows = import__712.ShadowMode.ENABLED; for (let i = 0; i < length2; i++) { const derivedCommand = derivedCommands[i]; const command = derivedCommand.command; const updateShadows = derivedCommand.updateShadows; if (!updateShadows) { expect(derivedCommand.is2D).toBe(true); } expect(command.castShadows).toBe(updateShadows); expect(command.receiveShadows).toBe(updateShadows); } }); }); describe("back face culling", function() { it("updates back face culling for opaque command", function() { const drawCommand = createModelDrawCommand(); const derivedCommands = drawCommand._derivedCommands; const length2 = derivedCommands.length; expect(length2).toEqual(2); for (let i = 0; i < length2; i++) { const command = derivedCommands[i].command; expect(command.renderState.cull.enabled).toBe(false); } drawCommand.backFaceCulling = true; for (let i = 0; i < length2; i++) { const derivedCommand = derivedCommands[i]; const command = derivedCommand.command; const updateBackFaceCulling = derivedCommand.updateBackFaceCulling; if (!updateBackFaceCulling) { expect(derivedCommand).toBe(drawCommand._translucentCommand); } expect(command.renderState.cull.enabled).toBe(updateBackFaceCulling); } }); it("doesn't update back face culling for silhouette-pass command", function() { const drawCommand = createModelDrawCommand({ deriveSilhouette: true }); const derivedCommands = drawCommand._derivedCommands; const length2 = derivedCommands.length; expect(length2).toEqual(3); for (let i = 0; i < length2; i++) { const command = derivedCommands[i].command; expect(command.renderState.cull.enabled).toBe(false); } drawCommand.backFaceCulling = true; for (let i = 0; i < length2; i++) { const derivedCommand = derivedCommands[i]; const command = derivedCommand.command; const updateBackFaceCulling = derivedCommand.updateBackFaceCulling; if (!updateBackFaceCulling) { expect(derivedCommand).toBe(drawCommand._silhouetteColorCommand); } expect(command.renderState.cull.enabled).toBe(updateBackFaceCulling); } }); it("doesn't update back face culling for skipLevelOfDetail backface command", function() { const drawCommand = createModelDrawCommand({ deriveSkipLevelOfDetail: true }); const derivedCommands = drawCommand._derivedCommands; const length2 = derivedCommands.length; expect(length2).toEqual(4); for (let i = 0; i < length2; i++) { const derivedCommand = derivedCommands[i]; const command = derivedCommand.command; const backfaceCulling = command.renderState.cull.enabled; if (backfaceCulling) { expect(derivedCommand).toBe(drawCommand._skipLodBackfaceCommand); } } drawCommand.backFaceCulling = true; for (let i = 0; i < length2; i++) { const derivedCommand = derivedCommands[i]; const command = derivedCommand.command; const isBackfaceCommand = derivedCommand === drawCommand._skipLodBackfaceCommand; const isTranslucentCommand = derivedCommand === drawCommand._translucentCommand; if (isTranslucentCommand) { expect(derivedCommand.updateBackFaceCulling).toBe(false); expect(command.renderState.cull.enabled).toBe(false); } else if (isBackfaceCommand) { expect(derivedCommand.updateBackFaceCulling).toBe(false); expect(command.renderState.cull.enabled).toBe(true); } else { expect(derivedCommand.updateBackFaceCulling).toBe(true); expect(command.renderState.cull.enabled).toBe(true); } } drawCommand.backFaceCulling = false; for (let i = 0; i < length2; i++) { const derivedCommand = derivedCommands[i]; const command = derivedCommand.command; const isBackfaceCommand = derivedCommand === drawCommand._skipLodBackfaceCommand; const isTranslucentCommand = derivedCommand === drawCommand._translucentCommand; if (isTranslucentCommand) { expect(derivedCommand.updateBackFaceCulling).toBe(false); expect(command.renderState.cull.enabled).toBe(false); } else if (isBackfaceCommand) { expect(derivedCommand.updateBackFaceCulling).toBe(false); expect(command.renderState.cull.enabled).toBe(true); } else { expect(derivedCommand.updateBackFaceCulling).toBe(true); expect(command.renderState.cull.enabled).toBe(false); } } }); }); describe("cull face", function() { it("updates cull face for opaque command", function() { const drawCommand = createModelDrawCommand(); const derivedCommands = drawCommand._derivedCommands; const length2 = derivedCommands.length; expect(length2).toEqual(2); for (let i = 0; i < length2; i++) { const command = derivedCommands[i].command; expect(command.renderState.cull.face).toBe(import__712.CullFace.BACK); } drawCommand.cullFace = import__712.CullFace.FRONT; for (let i = 0; i < length2; i++) { const derivedCommand = derivedCommands[i]; const command = derivedCommand.command; const updateCullFace = derivedCommand.updateCullFace; if (!updateCullFace) { expect(derivedCommand).toBe(drawCommand._translucentCommand); expect(command.renderState.cull.face).toBe(import__712.CullFace.BACK); } else { expect(command.renderState.cull.face).toBe(import__712.CullFace.FRONT); } } }); it("doesn't update cull face for silhouette command", function() { const drawCommand = createModelDrawCommand({ deriveSilhouette: true }); const derivedCommands = drawCommand._derivedCommands; const length2 = derivedCommands.length; expect(length2).toEqual(3); for (let i = 0; i < length2; i++) { const command = derivedCommands[i].command; expect(command.renderState.cull.face).toBe(import__712.CullFace.BACK); } drawCommand.cullFace = import__712.CullFace.FRONT; for (let i = 0; i < length2; i++) { const derivedCommand = derivedCommands[i]; const command = derivedCommand.command; const updateCullFace = derivedCommand.updateCullFace; if (!updateCullFace) { expect(derivedCommand).toBe(drawCommand._silhouetteColorCommand); expect(command.renderState.cull.face).toBe(import__712.CullFace.BACK); } else { expect(command.renderState.cull.face).toBe(import__712.CullFace.FRONT); } } }); }); describe("debugShowBoundingVolume", function() { it("updates debugShowBoundingVolume", function() { const drawCommand = createModelDrawCommand(); const derivedCommands = drawCommand._derivedCommands; const length2 = derivedCommands.length; expect(length2).toEqual(2); for (let i = 0; i < length2; i++) { const command = derivedCommands[i].command; expect(command.debugShowBoundingVolume).toBe(false); } drawCommand.debugShowBoundingVolume = true; for (let i = 0; i < length2; i++) { const command = derivedCommands[i].command; expect(command.debugShowBoundingVolume).toBe(true); } }); it("doesn't update debugShowBoundingVolume for silhouette command", function() { const drawCommand = createModelDrawCommand({ deriveSilhouette: true }); const derivedCommands = drawCommand._derivedCommands; const length2 = derivedCommands.length; expect(length2).toEqual(3); for (let i = 0; i < length2; i++) { const command = derivedCommands[i].command; expect(command.debugShowBoundingVolume).toBe(false); } drawCommand.debugShowBoundingVolume = true; for (let i = 0; i < length2; i++) { const derivedCommand = derivedCommands[i]; const command = derivedCommand.command; const updateDebugShowBoundingVolume = derivedCommand.updateDebugShowBoundingVolume; if (!updateDebugShowBoundingVolume) { expect(derivedCommand).toBe(drawCommand._silhouetteColorCommand); } expect(command.debugShowBoundingVolume).toBe( updateDebugShowBoundingVolume ); } }); it("doesn't update debugShowBoundingVolume for skipLevelOfDetail backface command", function() { const drawCommand = createModelDrawCommand({ deriveSkipLevelOfDetail: true }); const derivedCommands = drawCommand._derivedCommands; const length2 = derivedCommands.length; expect(length2).toEqual(4); for (let i = 0; i < length2; i++) { const command = derivedCommands[i].command; expect(command.debugShowBoundingVolume).toBe(false); } drawCommand.debugShowBoundingVolume = true; for (let i = 0; i < length2; i++) { const derivedCommand = derivedCommands[i]; const command = derivedCommand.command; const updateDebugShowBoundingVolume = derivedCommand.updateDebugShowBoundingVolume; if (!updateDebugShowBoundingVolume) { expect(derivedCommand).toBe(drawCommand._skipLodBackfaceCommand); } expect(command.debugShowBoundingVolume).toBe( updateDebugShowBoundingVolume ); } }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/ModelFeatureSpec.js var import__713 = __toESM(require_Cesium(), 1); describe("Scene/Model/ModelFeature", function() { const mockModel = { type: import__713.ModelType.GLTF }; let feature; let featureTable; beforeEach(function() { const properties = { height: { semantic: "HEIGHT_SEMANTIC", type: "SCALAR", componentType: "FLOAT32" }, name: { type: "STRING" }, HEIGHT_SEMANTIC: { type: "SCALAR", componentType: "FLOAT32" } }; const propertyValues = { height: [1], name: ["A"], HEIGHT_SEMANTIC: [3] }; const mockPropertyTable = MetadataTester_default.createPropertyTable({ properties, propertyValues }); featureTable = new import__713.ModelFeatureTable({ propertyTable: mockPropertyTable, model: mockModel }); feature = featureTable.getFeature(0); }); it("constructs", function() { const mockFeatureTable = {}; const feature2 = new import__713.ModelFeature({ model: mockModel, featureTable: mockFeatureTable, featureId: 3 }); expect(feature2.primitive).toBe(mockModel); expect(feature2.featureTable).toBe(mockFeatureTable); expect(feature2.featureId).toBe(3); }); it("gets and sets show", function() { expect(feature.show).toBe(true); feature.show = false; expect(feature.show).toBe(false); }); it("gets and sets color", function() { expect(feature.color).toEqual(new import__713.Color()); feature.color = import__713.Color.RED; expect(feature.color).toEqual(import__713.Color.RED); }); it("gets primitive", function() { expect(feature.primitive).toBe(mockModel); }); it("gets featureTable", function() { expect(feature.featureTable).toBe(featureTable); }); it("gets featureId", function() { expect(feature.featureId).toBe(0); }); it("hasProperty works", function() { expect(feature.hasProperty("height")).toBe(true); expect(feature.hasProperty("width")).toBe(false); }); it("getProperty works", function() { expect(feature.getProperty("height")).toBe(1); expect(feature.getProperty("name")).toBe("A"); expect(feature.getProperty("HEIGHT_SEMANTIC")).toBe(3); }); it("getPropertyInherited works", function() { expect(feature.getPropertyInherited("height")).toEqual(1); expect(feature.getPropertyInherited("_height")).toBeUndefined(); }); it("getPropertyIds works", function() { const results = []; expect(feature.getPropertyIds(results)).toEqual([ "height", "name", "HEIGHT_SEMANTIC" ]); }); it("setProperty works", function() { expect(feature.getProperty("height")).toEqual(1); feature.setProperty("height", 3); expect(feature.getProperty("height")).toEqual(3); }); }); // packages/engine/Specs/Scene/Model/ModelFeatureTableSpec.js var import__714 = __toESM(require_Cesium(), 1); describe("Scene/Model/ModelFeatureTable", function() { let mockPropertyTable; let properties; let propertyValues; beforeAll(function() { properties = { height: { semantic: "HEIGHT_SEMANTIC", type: "SCALAR", componentType: "FLOAT32" }, name: { type: "STRING" }, HEIGHT_SEMANTIC: { type: "SCALAR", componentType: "FLOAT32" } }; propertyValues = { height: [1, 2], name: ["A", "B"], HEIGHT_SEMANTIC: [3, 4] }; mockPropertyTable = MetadataTester_default.createPropertyTable({ properties, propertyValues }); }); it("creates ModelFeatures when model does not have content", function() { const table = new import__714.ModelFeatureTable({ propertyTable: mockPropertyTable, model: { type: import__714.ModelType.GLTF } }); expect(table._featuresLength).toEqual(mockPropertyTable.count); const modelFeatures = table._features; for (let i = 0; i < modelFeatures.length; i++) { const feature = table.getFeature(i); expect(feature).toBeInstanceOf(import__714.ModelFeature); } }); it("creates ModelFeatures when model has content", function() { const table = new import__714.ModelFeatureTable({ propertyTable: mockPropertyTable, model: { content: { tileset: {} }, type: import__714.ModelType.TILE_GLTF } }); expect(table._featuresLength).toEqual(mockPropertyTable.count); const modelFeatures = table._features; for (let i = 0; i < modelFeatures.length; i++) { const feature = table.getFeature(i); expect(feature).toBeInstanceOf(import__714.Cesium3DTileFeature); } }); it("hasProperty works", function() { const table = new import__714.ModelFeatureTable({ model: { type: import__714.ModelType.GLTF }, propertyTable: mockPropertyTable }); const modelFeatures = table._features; for (let i = 0; i < modelFeatures.length; i++) { const feature = modelFeatures[i]; expect(feature.hasProperty("height")).toEqual(true); expect(feature.hasProperty("width")).toEqual(false); } }); it("hasPropertyBySemantic works", function() { const table = new import__714.ModelFeatureTable({ model: { type: import__714.ModelType.GLTF }, propertyTable: mockPropertyTable }); const modelFeatures = table._features; for (let i = 0; i < modelFeatures.length; i++) { expect(table.hasPropertyBySemantic(i, "HEIGHT_SEMANTIC")).toEqual(true); expect(table.hasPropertyBySemantic(i, "WIDTH_SEMANTIC")).toEqual(false); } }); it("getFeature works", function() { const table = new import__714.ModelFeatureTable({ model: { type: import__714.ModelType.GLTF }, propertyTable: mockPropertyTable }); expect(table._featuresLength).toEqual(mockPropertyTable.count); const modelFeatures = table._features; for (let i = 0; i < modelFeatures.length; i++) { const feature = table.getFeature(i); expect(feature).toEqual(modelFeatures[i]); expect(feature).toBeInstanceOf(import__714.ModelFeature); } }); it("getProperty works", function() { const table = new import__714.ModelFeatureTable({ model: { type: import__714.ModelType.GLTF }, propertyTable: mockPropertyTable }); expect(table._featuresLength).toEqual(mockPropertyTable.count); const modelFeatures = table._features; for (const propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { for (let i = 0; i < modelFeatures.length; i++) { const feature = modelFeatures[i]; expect(feature.getProperty(propertyName)).toEqual( propertyValues[propertyName][i] ); } } } }); it("getPropertyInherited works", function() { const table = new import__714.ModelFeatureTable({ model: { type: import__714.ModelType.GLTF }, propertyTable: mockPropertyTable }); expect(table._featuresLength).toEqual(mockPropertyTable.count); const modelFeatures = table._features; let i; let feature; for (i = 0; i < modelFeatures.length; i++) { feature = modelFeatures[i]; expect(feature.getPropertyInherited("height")).toEqual( propertyValues["height"][i] ); expect(feature.getPropertyInherited("_height")).toBeUndefined(); } for (i = 0; i < modelFeatures.length; i++) { feature = modelFeatures[i]; expect(feature.getPropertyInherited("HEIGHT_SEMANTIC")).toEqual( propertyValues["height"][i] ); expect(feature.getPropertyInherited("_HEIGHT_")).toBeUndefined(); } }); it("getPropertyIds works", function() { const table = new import__714.ModelFeatureTable({ model: { type: import__714.ModelType.GLTF }, propertyTable: mockPropertyTable }); const modelFeatures = table._features; let results; for (let i = 0; i < modelFeatures.length; i++) { results = []; const feature = modelFeatures[i]; expect(feature.getPropertyIds(results)).toEqual([ "height", "name", "HEIGHT_SEMANTIC" ]); } }); it("setProperty works", function() { const table = new import__714.ModelFeatureTable({ model: { type: import__714.ModelType.GLTF }, propertyTable: mockPropertyTable }); const feature = table._features[0]; expect(feature.getProperty("height")).toEqual(1); feature.setProperty("height", 3); expect(feature.getProperty("height")).toEqual(3); }); it("destroy works", function() { const table = new import__714.ModelFeatureTable({ model: { type: import__714.ModelType.GLTF }, propertyTable: mockPropertyTable }); const batchTexture = table._batchTexture; expect(batchTexture.isDestroyed()).toEqual(false); expect(table.isDestroyed()).toEqual(false); table.destroy(); expect(batchTexture.isDestroyed()).toEqual(true); expect(table.isDestroyed()).toEqual(true); }); }); // packages/engine/Specs/Scene/Model/ModelMatrixUpdateStageSpec.js var import__715 = __toESM(require_Cesium(), 1); describe( "Scene/Model/ModelMatrixUpdateStage", function() { const simpleSkin = "./Data/Models/glTF-2.0/SimpleSkin/glTF/SimpleSkin.gltf"; function getStaticLeafNode(model) { return model.sceneGraph._runtimeNodes[0]; } function getParentRootNode(model) { return model.sceneGraph._runtimeNodes[1]; } function getChildLeafNode(model) { return model.sceneGraph._runtimeNodes[2]; } function getDrawCommand(runtimeNode) { return runtimeNode.runtimePrimitives[0].drawCommand; } const rotation = import__715.Quaternion.fromAxisAngle( import__715.Cartesian3.UNIT_Y, import__715.Math.toRadians(180) ); const modelMatrix = import__715.Matrix4.fromTranslationQuaternionRotationScale( new import__715.Cartesian3(10, 0, 0), rotation, new import__715.Cartesian3(1, 1, 1) ); let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.primitives.removeAll(); import__715.ResourceCache.clearForSpecs(); }); const mockPrimitive = { material: { doubleSided: false }, attributes: [ { semantic: "POSITION", max: new import__715.Cartesian3(0.5, 2, 0), min: new import__715.Cartesian3(-0.5, 0, 0) } ] }; function mockRenderResources(model) { return { model, runtimePrimitive: { boundingSphere: new import__715.BoundingSphere(), primitive: mockPrimitive } }; } function modifyModel(model) { const sceneGraph = model.sceneGraph; sceneGraph._axisCorrectionMatrix = import__715.Matrix4.IDENTITY; const meshNode = getStaticLeafNode(model); const modelDrawCommand = getDrawCommand(meshNode); const drawCommand = modelDrawCommand.command; const renderResources = mockRenderResources(model); const rootNode = getParentRootNode(model); const rootDrawCommand = (0, import__715.clone)(drawCommand); rootDrawCommand.modelMatrix = import__715.Matrix4.clone(import__715.Matrix4.IDENTITY); rootDrawCommand.boundingVolume = new import__715.BoundingSphere(); let runtimePrimitive = new import__715.ModelRuntimePrimitive({ node: rootNode, model, primitive: mockPrimitive }); runtimePrimitive.drawCommand = new import__715.ModelDrawCommand({ command: rootDrawCommand, primitiveRenderResources: renderResources }); spyOn(runtimePrimitive, "configurePipeline"); rootNode.runtimePrimitives.push(runtimePrimitive); rootNode._transformDirty = true; const leafNode = getChildLeafNode(model); const leafDrawCommand = (0, import__715.clone)(drawCommand); leafDrawCommand.modelMatrix = import__715.Matrix4.clone(import__715.Matrix4.IDENTITY); leafDrawCommand.boundingVolume = new import__715.BoundingSphere(); runtimePrimitive = new import__715.ModelRuntimePrimitive({ node: leafNode, model, primitive: mockPrimitive }); runtimePrimitive.drawCommand = new import__715.ModelDrawCommand({ command: leafDrawCommand, primitiveRenderResources: renderResources }); spyOn(runtimePrimitive, "configurePipeline"); leafNode.runtimePrimitives.push(runtimePrimitive); leafNode._transformDirty = true; } function applyTransform(node, transform) { const expectedOriginalTransform = import__715.Matrix4.clone(node.originalTransform); expect(node._transformDirty).toEqual(false); node.transform = import__715.Matrix4.multiplyTransformation( node.transform, transform, new import__715.Matrix4() ); expect(node._transformDirty).toEqual(true); expect( import__715.Matrix4.equals(node.originalTransform, expectedOriginalTransform) ).toBe(true); } it("updates leaf nodes using node transform setter", async function() { const model = await loadAndZoomToModelAsync_default( { gltf: simpleSkin }, scene2 ); scene2.renderForSpecs(); const sceneGraph = model.sceneGraph; const node = getStaticLeafNode(model); const primitive = node.runtimePrimitives[0]; let drawCommand = getDrawCommand(node); const transform = import__715.Matrix4.fromTranslation(new import__715.Cartesian3(0, 5, 0)); applyTransform(node, transform); const expectedComputedTransform = import__715.Matrix4.multiplyTransformation( sceneGraph.computedModelMatrix, node.transform, new import__715.Matrix4() ); const expectedModelMatrix = import__715.Matrix4.multiplyTransformation( drawCommand.modelMatrix, transform, new import__715.Matrix4() ); const expectedBoundingSphere = import__715.BoundingSphere.transform( primitive.boundingSphere, expectedComputedTransform, new import__715.BoundingSphere() ); scene2.renderForSpecs(); drawCommand = getDrawCommand(node); expect( import__715.Matrix4.equalsEpsilon( drawCommand.modelMatrix, expectedModelMatrix, import__715.Math.EPSILON15 ) ).toBe(true); expect( import__715.BoundingSphere.equals( drawCommand.boundingVolume, expectedBoundingSphere ) ).toBe(true); }); it("updates nodes with children using node transform setter", async function() { const model = await loadAndZoomToModelAsync_default( { gltf: simpleSkin }, scene2 ); modifyModel(model); scene2.renderForSpecs(); const rootNode = getParentRootNode(model); const staticLeafNode = getStaticLeafNode(model); const transformedLeafNode = getChildLeafNode(model); let rootDrawCommand = getDrawCommand(rootNode); let staticDrawCommand = getDrawCommand(staticLeafNode); let transformedDrawCommand = getDrawCommand(transformedLeafNode); const childTransformation = import__715.Matrix4.fromTranslation( new import__715.Cartesian3(0, 5, 0) ); applyTransform(transformedLeafNode, childTransformation); const rootTransformation = import__715.Matrix4.fromTranslation( new import__715.Cartesian3(12, 5, 0) ); applyTransform(rootNode, rootTransformation); const expectedRootModelMatrix = import__715.Matrix4.multiplyTransformation( rootTransformation, rootDrawCommand.modelMatrix, new import__715.Matrix4() ); const expectedStaticLeafModelMatrix = import__715.Matrix4.clone( staticDrawCommand.modelMatrix, new import__715.Matrix4() ); const finalTransform = new import__715.Matrix4(); import__715.Matrix4.multiply(rootTransformation, childTransformation, finalTransform); const expectedTransformedLeafModelMatrix = import__715.Matrix4.multiplyTransformation( finalTransform, transformedDrawCommand.modelMatrix, new import__715.Matrix4() ); scene2.renderForSpecs(); rootDrawCommand = getDrawCommand(rootNode); staticDrawCommand = getDrawCommand(staticLeafNode); transformedDrawCommand = getDrawCommand(transformedLeafNode); expect(rootDrawCommand.modelMatrix).toEqual(expectedRootModelMatrix); expect(staticDrawCommand.modelMatrix).toEqual( expectedStaticLeafModelMatrix ); expect(transformedDrawCommand.modelMatrix).toEqual( expectedTransformedLeafModelMatrix ); }); it("updates with new model matrix", async function() { const model = await loadAndZoomToModelAsync_default( { gltf: simpleSkin }, scene2 ); modifyModel(model); scene2.renderForSpecs(); const rootNode = getParentRootNode(model); const staticLeafNode = getStaticLeafNode(model); const transformedLeafNode = getChildLeafNode(model); let rootDrawCommand = getDrawCommand(rootNode); let staticDrawCommand = getDrawCommand(staticLeafNode); let transformedDrawCommand = getDrawCommand(transformedLeafNode); const expectedRootModelMatrix = import__715.Matrix4.multiplyTransformation( modelMatrix, rootDrawCommand.modelMatrix, new import__715.Matrix4() ); const expectedStaticLeafModelMatrix = import__715.Matrix4.multiplyTransformation( modelMatrix, staticDrawCommand.modelMatrix, new import__715.Matrix4() ); const expectedTransformedLeafModelMatrix = import__715.Matrix4.multiplyTransformation( modelMatrix, transformedDrawCommand.modelMatrix, new import__715.Matrix4() ); model.modelMatrix = modelMatrix; scene2.renderForSpecs(); rootDrawCommand = getDrawCommand(rootNode); staticDrawCommand = getDrawCommand(staticLeafNode); transformedDrawCommand = getDrawCommand(transformedLeafNode); expect(rootDrawCommand.modelMatrix).toEqual(expectedRootModelMatrix); expect(staticDrawCommand.modelMatrix).toEqual( expectedStaticLeafModelMatrix ); expect(transformedDrawCommand.modelMatrix).toEqual( expectedTransformedLeafModelMatrix ); }); it("updates with new model matrix and model scale", async function() { const model = await loadAndZoomToModelAsync_default( { gltf: simpleSkin }, scene2 ); modifyModel(model); scene2.renderForSpecs(); const modelScale = 5; const scaledModelMatrix = import__715.Matrix4.multiplyByUniformScale( modelMatrix, modelScale, new import__715.Matrix4() ); const rootNode = getParentRootNode(model); const staticLeafNode = getStaticLeafNode(model); const transformedLeafNode = getChildLeafNode(model); let rootDrawCommand = getDrawCommand(rootNode); let staticDrawCommand = getDrawCommand(staticLeafNode); let transformedDrawCommand = getDrawCommand(transformedLeafNode); const expectedRootModelMatrix = import__715.Matrix4.multiplyTransformation( scaledModelMatrix, rootDrawCommand.modelMatrix, new import__715.Matrix4() ); const expectedStaticLeafModelMatrix = import__715.Matrix4.multiplyTransformation( scaledModelMatrix, staticDrawCommand.modelMatrix, new import__715.Matrix4() ); const expectedTransformedLeafModelMatrix = import__715.Matrix4.multiplyTransformation( scaledModelMatrix, transformedDrawCommand.modelMatrix, new import__715.Matrix4() ); model.modelMatrix = modelMatrix; model.scale = modelScale; scene2.renderForSpecs(); rootDrawCommand = getDrawCommand(rootNode); staticDrawCommand = getDrawCommand(staticLeafNode); transformedDrawCommand = getDrawCommand(transformedLeafNode); expect(rootDrawCommand.modelMatrix).toEqual(expectedRootModelMatrix); expect(staticDrawCommand.modelMatrix).toEqual( expectedStaticLeafModelMatrix ); expect(transformedDrawCommand.modelMatrix).toEqual( expectedTransformedLeafModelMatrix ); }); it("updates render state cull face when scale is negative", async function() { const model = await loadAndZoomToModelAsync_default( { gltf: simpleSkin }, scene2 ); modifyModel(model); const rootNode = getParentRootNode(model); const childNode = getChildLeafNode(model); const rootPrimitive = rootNode.runtimePrimitives[0]; const childPrimitive = childNode.runtimePrimitives[0]; const rootDrawCommand = rootPrimitive.drawCommand; const childDrawCommand = childPrimitive.drawCommand; expect(rootDrawCommand.cullFace).toBe(import__715.CullFace.BACK); expect(childDrawCommand.cullFace).toBe(import__715.CullFace.BACK); model.modelMatrix = import__715.Matrix4.fromUniformScale(-1); scene2.renderForSpecs(); expect(rootPrimitive.drawCommand).toBe(rootDrawCommand); expect(rootDrawCommand.cullFace).toBe(import__715.CullFace.FRONT); expect(childDrawCommand.cullFace).toBe(import__715.CullFace.FRONT); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/ModelNodeSpec.js var import__716 = __toESM(require_Cesium(), 1); describe("Scene/Model/ModelNode", function() { const mockNode = { name: "Mock Node", index: 0 }; let runtimeNode, mockModel; const nodeTransform = import__716.Matrix4.fromTranslation(new import__716.Cartesian3(1, 2, 3)); beforeEach(function() { runtimeNode = new import__716.ModelRuntimeNode({ node: mockNode, transform: nodeTransform, transformToRoot: import__716.Matrix4.IDENTITY, children: [], sceneGraph: {} }); mockModel = { _userAnimationDirty: false }; }); it("throws for undefined model", function() { expect(function() { return new import__716.ModelNode(void 0, runtimeNode); }).toThrowDeveloperError(); }); it("throws for undefined runtimeNode", function() { expect(function() { return new import__716.ModelNode(mockModel, void 0); }).toThrowDeveloperError(); }); it("constructs", function() { const node = new import__716.ModelNode(mockModel, runtimeNode); expect(node.name).toEqual("Mock Node"); expect(node.id).toEqual(0); expect(node.show).toBe(true); expect(node.matrix).toBe(runtimeNode.transform); expect(node.originalMatrix).toBe(runtimeNode.originalTransform); }); it("sets show for runtime node", function() { const node = new import__716.ModelNode(mockModel, runtimeNode); node.show = false; expect(runtimeNode.show).toBe(false); node.show = true; expect(runtimeNode.show).toBe(true); }); it("sets matrix for runtime node", function() { const node = new import__716.ModelNode(mockModel, runtimeNode); expect(node.matrix).toEqual(nodeTransform); expect(node.originalMatrix).toEqual(nodeTransform); expect(runtimeNode.userAnimated).toBe(false); expect(mockModel._userAnimationDirty).toBe(false); const matrix = import__716.Matrix4.fromTranslation(new import__716.Cartesian3(10, 10, 10)); node.matrix = matrix; expect(node.matrix).toEqual(matrix); expect(node.originalMatrix).toEqual(nodeTransform); expect(runtimeNode.transform).toEqual(matrix); expect(runtimeNode.transform).not.toBe(matrix); expect(runtimeNode.originalTransform).toEqual(nodeTransform); expect(runtimeNode.userAnimated).toBe(true); expect(mockModel._userAnimationDirty).toBe(true); }); it("setting matrix to undefined resets node transform", function() { const node = new import__716.ModelNode(mockModel, runtimeNode); const matrix = import__716.Matrix4.fromTranslation(new import__716.Cartesian3(10, 10, 10)); node.matrix = matrix; expect(node.matrix).toEqual(matrix); expect(node.originalMatrix).toEqual(nodeTransform); expect(runtimeNode.transform).toEqual(matrix); expect(runtimeNode.transform).not.toBe(matrix); expect(runtimeNode.originalTransform).toEqual(nodeTransform); expect(runtimeNode.userAnimated).toBe(true); expect(mockModel._userAnimationDirty).toBe(true); node.matrix = void 0; expect(node.matrix).toEqual(node.originalMatrix); expect(node.originalMatrix).toEqual(nodeTransform); expect(runtimeNode.transform).toEqual(runtimeNode.originalTransform); expect(runtimeNode.transform).not.toBe(runtimeNode.originalTransform); expect(runtimeNode.userAnimated).toBe(false); }); }); // packages/engine/Specs/Scene/Model/ModelRenderResourcesSpec.js var import__717 = __toESM(require_Cesium(), 1); describe( "Scene/Model/ModelRenderResources", function() { const mockModel = {}; it("throws for undefined model", function() { expect(function() { return new import__717.ModelRenderResources(void 0); }).toThrowDeveloperError(); }); it("constructs", function() { const modelResources = new import__717.ModelRenderResources(mockModel); const defaultRenderState = import__717.RenderState.getState( import__717.RenderState.fromCache({ depthTest: { enabled: true, func: import__717.DepthFunction.LESS_OR_EQUAL } }) ); expect(modelResources.model).toBe(mockModel); expect(modelResources.shaderBuilder).toBeDefined(); expect(modelResources.renderStateOptions).toEqual(defaultRenderState); expect(modelResources.hasSilhouette).toBe(false); expect(modelResources.hasSkipLevelOfDetail).toBe(false); ShaderBuilderTester_default.expectHasFragmentDefines( modelResources.shaderBuilder, [] ); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/ModelRuntimeNodeSpec.js var import__718 = __toESM(require_Cesium(), 1); describe("Scene/Model/ModelRuntimeNode", function() { const mockNode = { matrix: import__718.Matrix4.IDENTITY }; const mockRuntimeNode = { transform: import__718.Matrix4.IDENTITY }; const mockChildRuntimeNode = { transform: import__718.Matrix4.IDENTITY }; const transform = import__718.Matrix4.clone(import__718.Matrix4.IDENTITY); const transformToRoot = import__718.Matrix4.clone(import__718.Matrix4.IDENTITY); const mockSceneGraph = { computedModelMatrix: import__718.Matrix4.clone(import__718.Matrix4.IDENTITY), _runtimeNodes: [mockChildRuntimeNode, mockRuntimeNode], components: { upAxis: import__718.Axis.Y, forwardAxis: import__718.Axis.Z } }; const scratchMatrix = new import__718.Matrix4(); function verifyTransforms(transform2, transformToRoot2, runtimeNode, originalTransform) { originalTransform = (0, import__718.defaultValue)(originalTransform, transform2); expect(runtimeNode.transform).toEqual(transform2); expect(runtimeNode.originalTransform).toEqual(originalTransform); expect(runtimeNode.transformToRoot).toEqual(transformToRoot2); const computedTransform = import__718.Matrix4.multiplyTransformation( transformToRoot2, transform2, scratchMatrix ); expect(runtimeNode.computedTransform).toEqual(computedTransform); } it("throws for undefined node", function() { expect(function() { return new import__718.ModelRuntimeNode({ node: void 0, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [] }); }).toThrowDeveloperError(); }); it("throws for undefined transform", function() { expect(function() { return new import__718.ModelRuntimeNode({ node: mockNode, transform: void 0, transformToRoot, sceneGraph: mockSceneGraph, children: [] }); }).toThrowDeveloperError(); }); it("throws for undefined transform to root", function() { expect(function() { return new import__718.ModelRuntimeNode({ node: mockNode, transform, transformToRoot: void 0, sceneGraph: mockSceneGraph, children: [] }); }).toThrowDeveloperError(); }); it("throws for undefined scene graph", function() { expect(function() { return new import__718.ModelRuntimeNode({ node: mockNode, transform, transformToRoot, sceneGraph: void 0, children: [] }); }).toThrowDeveloperError(); }); it("throws for undefined children", function() { expect(function() { return new import__718.ModelRuntimeNode({ node: mockNode, transform, sceneGraph: mockSceneGraph, trasnformToRoot: transformToRoot, children: void 0 }); }).toThrowDeveloperError(); }); it("constructs", function() { const node = new import__718.ModelRuntimeNode({ node: mockNode, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [] }); expect(node.node).toBe(mockNode); expect(node.sceneGraph).toBe(mockSceneGraph); expect(node.children.length).toEqual(0); verifyTransforms(transform, transformToRoot, node); expect(node.show).toBe(true); expect(node.userAnimated).toBe(false); node.configurePipeline(); expect(node.pipelineStages).toEqual([import__718.NodeStatisticsPipelineStage]); expect(node.updateStages).toEqual([import__718.ModelMatrixUpdateStage]); expect(node.runtimePrimitives).toEqual([]); expect(node.translation).toBeUndefined(); expect(node.rotation).toBeUndefined(); expect(node.scale).toBeUndefined(); expect(node.morphWeights).toEqual([]); }); it("constructs with default transform parameters", function() { const mockNodeWithNoMatrix = {}; const node = new import__718.ModelRuntimeNode({ node: mockNodeWithNoMatrix, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [] }); expect(node.node).toBe(mockNodeWithNoMatrix); expect(node.sceneGraph).toBe(mockSceneGraph); expect(node.children.length).toEqual(0); verifyTransforms(transform, transformToRoot, node); expect(node.translation).toEqual(import__718.Cartesian3.ZERO); expect(node.rotation).toEqual(import__718.Quaternion.IDENTITY); expect(node.scale).toEqual(new import__718.Cartesian3(1, 1, 1)); }); it("constructs with given transform parameters", function() { const mockNodeWithParameters = { translation: new import__718.Cartesian3(1, 2, 3), rotation: new import__718.Quaternion(0.707, 0, 0.707, 0), scale: new import__718.Cartesian3(1, 1, 2) }; const node = new import__718.ModelRuntimeNode({ node: mockNodeWithParameters, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [] }); expect(node.node).toBe(mockNodeWithParameters); expect(node.sceneGraph).toBe(mockSceneGraph); expect(node.children.length).toEqual(0); verifyTransforms(transform, transformToRoot, node); expect(node.translation).toEqual(new import__718.Cartesian3(1, 2, 3)); expect(node.rotation).toEqual(new import__718.Quaternion(0.707, 0, 0.707, 0)); expect(node.scale).toEqual(new import__718.Cartesian3(1, 1, 2)); }); it("setting translation throws if node was constructed with matrix", function() { const node = new import__718.ModelRuntimeNode({ node: mockNode, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [] }); expect(function() { node.translation = new import__718.Cartesian3(1, 2, 3); }).toThrowDeveloperError(); }); it("setting rotation throws if node was constructed with matrix", function() { const node = new import__718.ModelRuntimeNode({ node: mockNode, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [] }); expect(function() { node.rotation = import__718.Quaternion.IDENTITY; }).toThrowDeveloperError(); }); it("setting scale throws if node was constructed with matrix", function() { const node = new import__718.ModelRuntimeNode({ node: mockNode, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [] }); expect(function() { node.scale = new import__718.Cartesian3(1, 1, 2); }).toThrowDeveloperError(); }); it("setting morphWeights throws if given different length array", function() { const node = new import__718.ModelRuntimeNode({ node: mockNode, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [] }); expect(function() { node.morphWeights = [0, 1, 2]; }).toThrowDeveloperError(); }); const scratchTransform = new import__718.Matrix4(); it("sets translation", function() { const mockNodeWithTranslation = { translation: import__718.Cartesian3.ZERO }; const node = new import__718.ModelRuntimeNode({ node: mockNodeWithTranslation, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [] }); verifyTransforms(transform, transformToRoot, node); expect(node.translation).toEqual(import__718.Cartesian3.ZERO); const translation = new import__718.Cartesian3(1, 2, 3); node.translation = translation; node.updateComputedTransform(); const translationMatrix = import__718.Matrix4.fromTranslation( translation, scratchTransform ); expect(node.translation).toEqual(translation); verifyTransforms(translationMatrix, transformToRoot, node, transform); }); it("sets rotation", function() { const mockNodeWithRotation = { rotation: import__718.Quaternion.IDENTITY }; const node = new import__718.ModelRuntimeNode({ node: mockNodeWithRotation, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [] }); verifyTransforms(transform, transformToRoot, node); expect(node.rotation).toEqual(import__718.Quaternion.IDENTITY); const rotation = new import__718.Quaternion(0.707, 0, 0.707, 0); node.rotation = rotation; node.updateComputedTransform(); const rotationMatrix3 = import__718.Matrix3.fromQuaternion(rotation, new import__718.Matrix3()); const rotationMatrix = import__718.Matrix4.fromRotation( rotationMatrix3, scratchTransform ); expect(node.rotation).toEqual(rotation); verifyTransforms(rotationMatrix, transformToRoot, node, transform); }); it("sets scale", function() { const mockNodeWithScale = { scale: new import__718.Cartesian3(1, 1, 1) }; const node = new import__718.ModelRuntimeNode({ node: mockNodeWithScale, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [] }); verifyTransforms(transform, transformToRoot, node); expect(node.scale).toEqual(new import__718.Cartesian3(1, 1, 1)); const scale = new import__718.Cartesian3(2, 3, 4); node.scale = scale; node.updateComputedTransform(); const scaleMatrix = import__718.Matrix4.fromScale(scale, scratchTransform); expect(node.scale).toEqual(scale); verifyTransforms(scaleMatrix, transformToRoot, node, transform); }); it("sets morphWeights", function() { const mockNodeWithWeights = { morphWeights: [0, 0, 0] }; const node = new import__718.ModelRuntimeNode({ node: mockNodeWithWeights, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [] }); expect(node.morphWeights).not.toBe(mockNodeWithWeights.morphWeights); expect(node.morphWeights).toEqual(mockNodeWithWeights.morphWeights); const morphWeights = [1, 2, 3]; node.morphWeights = morphWeights; expect(node.morphWeights).not.toBe(morphWeights); expect(node.morphWeights).toEqual(morphWeights); }); it("adds instancing pipeline stage if node is instanced", function() { const instancedMockNode = { instances: { attributes: [] } }; const node = new import__718.ModelRuntimeNode({ node: instancedMockNode, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [] }); expect(node.node).toBe(instancedMockNode); expect(node.sceneGraph).toBe(mockSceneGraph); expect(node.children.length).toEqual(0); verifyTransforms(transform, transformToRoot, node); node.configurePipeline(); expect(node.pipelineStages).toEqual([ import__718.InstancingPipelineStage, import__718.NodeStatisticsPipelineStage ]); expect(node.updateStages).toEqual([import__718.ModelMatrixUpdateStage]); expect(node.runtimePrimitives).toEqual([]); }); it("getChild throws for undefined index", function() { const node = new import__718.ModelRuntimeNode({ node: mockNode, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [0] }); expect(function() { node.getChild(); }).toThrowDeveloperError(); }); it("getChild throws for invalid index", function() { const node = new import__718.ModelRuntimeNode({ node: mockNode, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [0] }); expect(function() { node.getChild("s"); }).toThrowDeveloperError(); }); it("getChild throws for out of range index", function() { const node = new import__718.ModelRuntimeNode({ node: mockNode, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [0] }); expect(function() { node.getChild(2); }).toThrowDeveloperError(); expect(function() { node.getChild(-1); }).toThrowDeveloperError(); }); it("getChild works", function() { const node = new import__718.ModelRuntimeNode({ node: mockNode, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [0] }); const child = node.getChild(0); expect(child).toBeDefined(); expect(child.transform).toBeDefined(); }); it("sets transform without replacing original", function() { const node = new import__718.ModelRuntimeNode({ node: mockNode, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [0] }); const newTransform = import__718.Matrix4.multiplyByTranslation( import__718.Matrix4.IDENTITY, new import__718.Cartesian3(10, 0, 0), new import__718.Matrix4() ); node.transform = newTransform; expect(node._transformDirty).toBe(true); expect(import__718.Matrix4.equals(node.transform, newTransform)).toBe(true); expect(import__718.Matrix4.equals(node.originalTransform, transform)).toBe(true); }); it("updateComputedTransform updates computedTransform matrix", function() { const node = new import__718.ModelRuntimeNode({ node: mockNode, transform, transformToRoot, sceneGraph: mockSceneGraph, children: [0] }); verifyTransforms(transform, transformToRoot, node); const newTransform = import__718.Matrix4.multiplyByTranslation( import__718.Matrix4.IDENTITY, new import__718.Cartesian3(10, 0, 0), new import__718.Matrix4() ); node.transform = newTransform; node.updateComputedTransform(); const originalTransform = transform; verifyTransforms(newTransform, transformToRoot, node, originalTransform); }); }); // packages/engine/Specs/Scene/Model/ModelRuntimePrimitiveSpec.js var import__719 = __toESM(require_Cesium(), 1); describe("Scene/Model/ModelRuntimePrimitive", function() { const mockPrimitive = { featureIds: [], attributes: [] }; const mockNode = {}; const mockModel = { type: import__719.ModelType.GLTF, allowPicking: true, featureIdLabel: "featureId_0" }; const mockWebgl1Context = { webgl2: false }; const mockWebgl2Context = { webgl2: true }; const mockFrameState = createFrameState_default(mockWebgl1Context); const mockFrameStateWebgl2 = createFrameState_default(mockWebgl2Context); const mockFrameState2D = createFrameState_default(mockWebgl1Context); mockFrameState2D.mode = import__719.SceneMode.SCENE2D; const mockFrameState3DOnly = createFrameState_default(mockWebgl1Context); mockFrameState3DOnly.scene3DOnly = true; const emptyVertexShader = "void vertexMain(VertexInput vsInput, inout vec3 position) {}"; const emptyFragmentShader = "void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {}"; function verifyExpectedStages(stages, expectedStages) { expect(stages.length, expectedStages.stages); for (let i = 0; i < stages.length; i++) { expect(stages[i].name).toEqual(expectedStages[i].name); } } it("throws for undefined primitive", function() { expect(function() { return new import__719.ModelRuntimePrimitive({ primitive: void 0, node: mockNode, model: mockModel }); }).toThrowDeveloperError(); }); it("throws for undefined node", function() { expect(function() { return new import__719.ModelRuntimePrimitive({ primitive: mockPrimitive, node: void 0, model: mockModel }); }).toThrowDeveloperError(); }); it("throws for undefined model", function() { expect(function() { return new import__719.ModelRuntimePrimitive({ primitive: mockPrimitive, node: mockNode, model: void 0 }); }).toThrowDeveloperError(); }); it("constructs", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: mockPrimitive, node: mockNode, model: mockModel }); expect(primitive.primitive).toBe(mockPrimitive); expect(primitive.node).toBe(mockNode); expect(primitive.model).toBe(mockModel); }); it("configures the pipeline stages for model picking", function() { let primitive = new import__719.ModelRuntimePrimitive({ primitive: mockPrimitive, node: mockNode, model: mockModel }); let expectedStages = [ import__719.GeometryPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.PickingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; verifyExpectedStages(primitive.pipelineStages, expectedStages); primitive = new import__719.ModelRuntimePrimitive({ primitive: mockPrimitive, node: mockNode, model: { type: import__719.ModelType.GLTF, allowPicking: false, content: {} } }); expectedStages = [ import__719.GeometryPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("configures the pipeline stages for instance feature picking", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: mockPrimitive, node: { instances: { featureIds: [ { label: "defaultIds", positionalLabel: "instanceFeatureId_0" }, { propertyTableId: 0, positionalLabel: "instanceFeatureId_1" } ] } }, model: { type: import__719.ModelType.GLTF, allowPicking: true, instanceFeatureIdLabel: "instanceFeatureId_1", content: {} } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.SelectedFeatureIdPipelineStage, import__719.BatchTexturePipelineStage, import__719.CPUStylingPipelineStage, import__719.LightingPipelineStage, import__719.PickingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("configures the pipeline stages for feature picking", function() { let primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [ { label: "defaultIds", positionalLabel: "featureId_0" }, { propertyTableId: 0, label: "pickingIds" } ], attributes: [ { semantic: import__719.VertexAttributeSemantic.FEATURE_ID } ] }, node: {}, model: { type: import__719.ModelType.GLTF, allowPicking: true, featureIdLabel: "pickingIds", content: {} } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.SelectedFeatureIdPipelineStage, import__719.BatchTexturePipelineStage, import__719.CPUStylingPipelineStage, import__719.LightingPipelineStage, import__719.PickingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [ { positionalLabel: "featureId_0" }, { propertyTableId: 0, positionalLabel: "featureId_1" } ], attributes: [] }, node: {}, model: { type: import__719.ModelType.GLTF, allowPicking: true, featureIdLabel: "featureId_1", content: {} } }); primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("configures dequantization", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], attributes: [ { semantic: "POSITION" }, { semantic: "NORMAL", quantization: {} } ] }, node: mockNode, model: mockModel }); primitive.configurePipeline(mockFrameState); expect(primitive.pipelineStages).toEqual([ import__719.GeometryPipelineStage, import__719.DequantizationPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.PickingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]); }); it("configures the pipeline stages for custom shaders", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: mockPrimitive, node: mockNode, model: { type: import__719.ModelType.GLTF, content: {}, customShader: new import__719.CustomShader({ vertexShaderText: emptyVertexShader, fragmentShaderText: emptyFragmentShader }), allowPicking: false } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.CustomShaderPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("disables the material stage if the custom shader mode is REPLACE_MATERIAL", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: mockPrimitive, node: mockNode, model: { type: import__719.ModelType.GLTF, content: {}, customShader: new import__719.CustomShader({ mode: import__719.CustomShaderMode.REPLACE_MATERIAL, vertexShaderText: emptyVertexShader, fragmentShaderText: emptyFragmentShader }), allowPicking: false } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.CustomShaderPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("does not disable the material stage if the custom shader has no fragment shader", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: mockPrimitive, node: mockNode, model: { type: import__719.ModelType.GLTF, content: {}, customShader: new import__719.CustomShader({ mode: import__719.CustomShaderMode.REPLACE_MATERIAL, vertexShaderText: emptyVertexShader }), allowPicking: false } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.CustomShaderPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("configures point cloud attenuation stage for 3D Tiles point clouds", function() { const pointCloudShading = new import__719.PointCloudShading({ attenuation: true }); const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], attributes: [], primitiveType: import__719.PrimitiveType.POINTS }, node: mockNode, model: { type: import__719.ModelType.TILE_PNTS, featureIdLabel: "featureId_0", pointCloudShading, content: { tileset: { pointCloudShading } } } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.PointCloudStylingPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("configures point cloud styling stage for point cloud gltf", function() { const pointCloudShading = new import__719.PointCloudShading({ attenuation: true }); const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], attributes: [], primitiveType: import__719.PrimitiveType.POINTS }, node: mockNode, model: { type: import__719.ModelType.GLTF, featureIdLabel: "featureId_0", pointCloudShading } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.PointCloudStylingPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("skips point cloud attenuation if attenuation is false", function() { const pointCloudShading = new import__719.PointCloudShading({ attenuation: false }); const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], attributes: [], primitiveType: import__719.PrimitiveType.POINTS }, node: mockNode, model: { type: import__719.ModelType.GLTF, featureIdLabel: "featureId_0", pointCloudShading } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("skips point cloud attenuation if point cloud shading is not set", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], attributes: [], primitiveType: import__719.PrimitiveType.POINTS }, node: mockNode, model: { type: import__719.ModelType.GLTF, featureIdLabel: "featureId_0", pointCloudShading: void 0 } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("configures point cloud styling stage for 3d tiles point clouds", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], attributes: [], primitiveType: import__719.PrimitiveType.POINTS }, node: mockNode, model: { type: import__719.ModelType.TILE_PNTS, featureIdLabel: "featureId_0", style: new import__719.Cesium3DTileStyle() } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.PointCloudStylingPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("skips point cloud styling stage without a style", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], attributes: [], primitiveType: import__719.PrimitiveType.POINTS }, node: mockNode, model: { type: import__719.ModelType.TILE_PNTS, featureIdLabel: "featureId_0" } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("configures the pipeline stages for morph targets", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: { morphTargets: [{}], morphWeights: [0], featureIds: [], featureIdTextures: [], attributes: [], primitiveType: import__719.PrimitiveType.TRIANGLES }, node: mockNode, model: { type: import__719.ModelType.GLTF, featureIdLabel: "featureId_0" } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.MorphTargetsPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("configures the pipeline stages for skinning", function() { const mockSkin = { index: 0, inverseBindMatrices: [], joints: [] }; const mockNode2 = { skin: mockSkin }; const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], attributes: [], primitiveType: import__719.PrimitiveType.TRIANGLES }, node: mockNode2, model: { type: import__719.ModelType.GLTF, featureIdLabel: "featureId_0", pointCloudShading: void 0 } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.SkinningPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("configures pipeline for debugWireframe if model.enableDebugWireframe is true(WebGL 1)", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], attributes: [], primitiveType: import__719.PrimitiveType.TRIANGLES }, node: mockNode, model: { debugWireframe: true, _enableDebugWireframe: true, type: import__719.ModelType.GLTF, featureIdLabel: "featureId_0" } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.WireframePipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("does not include wireframe stage if model.enableDebugWireframe is false (WebGL 1)", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], attributes: [], primitiveType: import__719.PrimitiveType.TRIANGLES }, node: mockNode, model: { debugWireframe: true, _enableDebugWireframe: false, type: import__719.ModelType.GLTF, featureIdLabel: "featureId_0" } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("configures pipeline for debugWireframe (WebGL 2)", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], attributes: [], primitiveType: import__719.PrimitiveType.TRIANGLES }, node: mockNode, model: { debugWireframe: true, type: import__719.ModelType.GLTF, featureIdLabel: "featureId_0" } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.WireframePipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameStateWebgl2); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("does not include wireframe stage for non-triangle primitives", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], attributes: [], primitiveType: import__719.PrimitiveType.POINTS }, node: mockNode, model: { debugWireframe: true, type: import__719.ModelType.GLTF, featureIdLabel: "featureId_0" } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameStateWebgl2); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("configures pipeline for projectTo2D", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], attributes: [], primitiveType: import__719.PrimitiveType.TRIANGLES }, node: mockNode, model: { _projectTo2D: true, type: import__719.ModelType.GLTF, featureIdLabel: "featureId_0" } }); const expectedStages = [ import__719.SceneMode2DPipelineStage, import__719.GeometryPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState2D); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("does not add scenemode 2D stage if scene is 3D", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], attributes: [], primitiveType: import__719.PrimitiveType.TRIANGLES }, node: mockNode, model: { _projectTo2D: true, type: import__719.ModelType.GLTF, featureIdLabel: "featureId_0" } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("does not add scenemode 2D stage if scene is 3D only", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], attributes: [], primitiveType: import__719.PrimitiveType.TRIANGLES }, node: mockNode, model: { _projectTo2D: true, type: import__719.ModelType.GLTF, featureIdLabel: "featureId_0" } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState3DOnly); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("adds outline stage for CESIUM_primitive_outline", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], attributes: [], primitiveType: import__719.PrimitiveType.TRIANGLES, outlineCoordinates: {} }, node: mockNode, model: { type: import__719.ModelType.GLTF, featureIdLabel: "featureId_0", _enableShowOutline: true } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.PrimitiveOutlinePipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("does not add outline stage if outlines are disabled", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], attributes: [], primitiveType: import__719.PrimitiveType.TRIANGLES, outlineCoordinates: {} }, node: mockNode, model: { type: import__719.ModelType.GLTF, featureIdLabel: "featureId_0", _enableShowOutline: false } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("configures pipeline stages for classification", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: { featureIds: [], featureIdTextures: [], primitiveType: import__719.PrimitiveType.TRIANGLES }, node: mockNode, model: { type: import__719.ModelType.GLTF, featureIdLabel: "featureId_0", classificationType: import__719.ClassificationType.BOTH } }); const expectedStages = [ import__719.GeometryPipelineStage, import__719.ClassificationPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.LightingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(mockFrameState); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); it("configures pipeline stages for vertical exaggeration", function() { const primitive = new import__719.ModelRuntimePrimitive({ primitive: mockPrimitive, node: mockNode, model: mockModel }); const frameState2 = createFrameState_default(mockWebgl2Context); frameState2.verticalExaggeration = 2; const expectedStages = [ import__719.GeometryPipelineStage, import__719.MaterialPipelineStage, import__719.FeatureIdPipelineStage, import__719.MetadataPipelineStage, import__719.VerticalExaggerationPipelineStage, import__719.LightingPipelineStage, import__719.PickingPipelineStage, import__719.AlphaPipelineStage, import__719.PrimitiveStatisticsPipelineStage ]; primitive.configurePipeline(frameState2); verifyExpectedStages(primitive.pipelineStages, expectedStages); }); }); // packages/engine/Specs/Scene/Model/ModelSceneGraphSpec.js var import__720 = __toESM(require_Cesium(), 1); describe( "Scene/Model/ModelSceneGraph", function() { const parentGltfUrl = "./Data/Cesium3DTiles/GltfContent/glTF/parent.gltf"; const vertexColorGltfUrl = "./Data/Models/glTF-2.0/VertexColorTest/glTF/VertexColorTest.gltf"; const buildingsMetadata = "./Data/Models/glTF-2.0/BuildingsMetadata/glTF/buildings-metadata.gltf"; const simpleSkinGltfUrl = "./Data/Models/glTF-2.0/SimpleSkin/glTF/SimpleSkin.gltf"; const boxArticulationsUrl = "./Data/Models/glTF-2.0/BoxArticulations/glTF/BoxArticulations.gltf"; const duckUrl = "./Data/Models/glTF-2.0/Duck/glTF-Draco/Duck.gltf"; let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.primitives.removeAll(); scene2.fog = new import__720.Fog(); import__720.ResourceCache.clearForSpecs(); }); it("creates runtime nodes and runtime primitives from a model", async function() { const model = await loadAndZoomToModelAsync_default( { gltf: vertexColorGltfUrl }, scene2 ); const sceneGraph = model._sceneGraph; const components = sceneGraph._components; expect(sceneGraph).toBeDefined(); const runtimeNodes = sceneGraph._runtimeNodes; expect(runtimeNodes.length).toEqual(components.nodes.length); expect(runtimeNodes[0].runtimePrimitives.length).toEqual(1); expect(runtimeNodes[1].runtimePrimitives.length).toEqual(1); }); it("builds draw commands for all opaque styled features", async function() { const style = new import__720.Cesium3DTileStyle({ color: { conditions: [["${height} > 1", "color('red')"]] } }); const model = await loadAndZoomToModelAsync_default( { gltf: buildingsMetadata }, scene2 ); model.style = style; const frameState2 = scene2.frameState; const commandList = frameState2.commandList; commandList.length = 0; model._drawCommandsBuilt = false; scene2.renderForSpecs(); expect(commandList.length).toEqual(1); expect(commandList[0].pass).toEqual(import__720.Pass.OPAQUE); }); it("builds draw commands for all translucent styled features", async function() { const style = new import__720.Cesium3DTileStyle({ color: { conditions: [["${height} > 1", "color('red', 0.1)"]] } }); const model = await loadAndZoomToModelAsync_default( { gltf: buildingsMetadata }, scene2 ); model.style = style; const frameState2 = scene2.frameState; const commandList = frameState2.commandList; commandList.length = 0; model._drawCommandsBuilt = false; scene2.renderForSpecs(); expect(commandList.length).toEqual(1); expect(commandList[0].pass).toEqual(import__720.Pass.TRANSLUCENT); }); it("builds draw commands for both opaque and translucent styled features", async function() { const style = new import__720.Cesium3DTileStyle({ color: { conditions: [ ["${height} > 80", "color('red', 0.1)"], ["true", "color('blue')"] ] } }); const model = await loadAndZoomToModelAsync_default( { gltf: buildingsMetadata }, scene2 ); model.style = style; const frameState2 = scene2.frameState; const commandList = frameState2.commandList; commandList.length = 0; model._drawCommandsBuilt = false; scene2.renderForSpecs(); expect(commandList.length).toEqual(2); expect(commandList[0].pass).toEqual(import__720.Pass.TRANSLUCENT); expect(commandList[1].pass).toEqual(import__720.Pass.OPAQUE); }); it("builds draw commands for each primitive", async function() { spyOn(import__720.ModelSceneGraph.prototype, "buildDrawCommands").and.callThrough(); spyOn(import__720.ModelSceneGraph.prototype, "pushDrawCommands").and.callThrough(); const model = await loadAndZoomToModelAsync_default( { gltf: parentGltfUrl }, scene2 ); const sceneGraph = model._sceneGraph; const runtimeNodes = sceneGraph._runtimeNodes; let primitivesCount = 0; for (let i = 0; i < runtimeNodes.length; i++) { primitivesCount += runtimeNodes[i].runtimePrimitives.length; } const frameState2 = scene2.frameState; frameState2.commandList.length = 0; scene2.renderForSpecs(); expect(import__720.ModelSceneGraph.prototype.buildDrawCommands).toHaveBeenCalled(); expect(import__720.ModelSceneGraph.prototype.pushDrawCommands).toHaveBeenCalled(); expect(frameState2.commandList.length).toEqual(primitivesCount); model._drawCommandsBuilt = false; frameState2.commandList.length = 0; scene2.renderForSpecs(); expect(import__720.ModelSceneGraph.prototype.buildDrawCommands).toHaveBeenCalled(); expect(import__720.ModelSceneGraph.prototype.pushDrawCommands).toHaveBeenCalled(); expect(frameState2.commandList.length).toEqual(primitivesCount); }); it("stores runtime nodes correctly", async function() { const model = await loadAndZoomToModelAsync_default( { gltf: parentGltfUrl }, scene2 ); const sceneGraph = model._sceneGraph; const components = sceneGraph._components; const runtimeNodes = sceneGraph._runtimeNodes; expect(runtimeNodes[0].node).toEqual(components.nodes[0]); expect(runtimeNodes[1].node).toEqual(components.nodes[1]); const rootNodes = sceneGraph._rootNodes; expect(rootNodes[0]).toEqual(0); }); it("propagates node transforms correctly", async function() { const model = await loadAndZoomToModelAsync_default( { gltf: parentGltfUrl, upAxis: import__720.Axis.Z, forwardAxis: import__720.Axis.X }, scene2 ); const sceneGraph = model._sceneGraph; const components = sceneGraph._components; const runtimeNodes = sceneGraph._runtimeNodes; expect(components.upAxis).toEqual(import__720.Axis.Z); expect(components.forwardAxis).toEqual(import__720.Axis.X); const parentTransform = import__720.ModelUtility.getNodeTransform( components.nodes[0] ); const childTransform = import__720.ModelUtility.getNodeTransform(components.nodes[1]); expect(runtimeNodes[0].transform).toEqual(parentTransform); expect(runtimeNodes[0].transformToRoot).toEqual(import__720.Matrix4.IDENTITY); expect(runtimeNodes[1].transform).toEqual(childTransform); expect(runtimeNodes[1].transformToRoot).toEqual(parentTransform); }); it("creates runtime skin from model", async function() { const model = await loadAndZoomToModelAsync_default( { gltf: simpleSkinGltfUrl }, scene2 ); const sceneGraph = model._sceneGraph; const components = sceneGraph._components; const runtimeNodes = sceneGraph._runtimeNodes; expect(runtimeNodes[0].node).toEqual(components.nodes[0]); expect(runtimeNodes[1].node).toEqual(components.nodes[1]); expect(runtimeNodes[2].node).toEqual(components.nodes[2]); const rootNodes = sceneGraph._rootNodes; expect(rootNodes[0]).toEqual(0); expect(rootNodes[1]).toEqual(1); const runtimeSkins = sceneGraph._runtimeSkins; expect(runtimeSkins[0].skin).toEqual(components.skins[0]); expect(runtimeSkins[0].joints).toEqual([ runtimeNodes[1], runtimeNodes[2] ]); expect(runtimeSkins[0].jointMatrices.length).toEqual(2); const skinnedNodes = sceneGraph._skinnedNodes; expect(skinnedNodes[0]).toEqual(0); expect(runtimeNodes[0].computedJointMatrices.length).toEqual(2); }); it("creates articulation from model", async function() { const model = await loadAndZoomToModelAsync_default( { gltf: boxArticulationsUrl }, scene2 ); const sceneGraph = model._sceneGraph; const components = sceneGraph._components; const runtimeNodes = sceneGraph._runtimeNodes; expect(runtimeNodes[0].node).toEqual(components.nodes[0]); const rootNodes = sceneGraph._rootNodes; expect(rootNodes[0]).toEqual(0); const runtimeArticulations = sceneGraph._runtimeArticulations; const runtimeArticulation = runtimeArticulations["SampleArticulation"]; expect(runtimeArticulation).toBeDefined(); expect(runtimeArticulation.name).toBe("SampleArticulation"); expect(runtimeArticulation.runtimeNodes.length).toBe(1); expect(runtimeArticulation.runtimeStages.length).toBe(10); }); it("applies articulations", async function() { const model = await loadAndZoomToModelAsync_default( { gltf: boxArticulationsUrl }, scene2 ); const sceneGraph = model._sceneGraph; const runtimeNodes = sceneGraph._runtimeNodes; const rootNode = runtimeNodes[0]; expect(rootNode.transform).toEqual(rootNode.originalTransform); sceneGraph.setArticulationStage("SampleArticulation MoveX", 1); sceneGraph.setArticulationStage("SampleArticulation MoveY", 2); sceneGraph.setArticulationStage("SampleArticulation MoveZ", 3); sceneGraph.setArticulationStage("SampleArticulation Yaw", 4); sceneGraph.setArticulationStage("SampleArticulation Pitch", 5); sceneGraph.setArticulationStage("SampleArticulation Roll", 6); sceneGraph.setArticulationStage("SampleArticulation Size", 0.9); sceneGraph.setArticulationStage("SampleArticulation SizeX", 0.8); sceneGraph.setArticulationStage("SampleArticulation SizeY", 0.7); sceneGraph.setArticulationStage("SampleArticulation SizeZ", 0.6); expect(rootNode.transform).toEqual(rootNode.originalTransform); sceneGraph.applyArticulations(); const expected = [ 0.714769048324, -0.0434061192623, -0.074974104652, 0, -0.061883302957, 0.0590679731276, -0.62416458676, 0, 0.037525155822, 0.5366347296529, 0.047064101083, 0, 1, 3, -2, 1 ]; expect(rootNode.transform).toEqualEpsilon(expected, import__720.Math.EPSILON10); }); it("adds ModelColorPipelineStage when color is set on the model", async function() { spyOn(import__720.ModelColorPipelineStage, "process"); await loadAndZoomToModelAsync_default( { color: import__720.Color.RED, gltf: parentGltfUrl }, scene2 ); expect(import__720.ModelColorPipelineStage.process).toHaveBeenCalled(); }); it("adds CustomShaderPipelineStage when customShader is set on the model", async function() { spyOn(import__720.CustomShaderPipelineStage, "process"); const model = await loadAndZoomToModelAsync_default( { gltf: buildingsMetadata }, scene2 ); model.customShader = new import__720.CustomShader(); model.update(scene2.frameState); expect(import__720.CustomShaderPipelineStage.process).toHaveBeenCalled(); }); it("does not add fog stage when fog is not enabled", async function() { spyOn(import__720.AtmospherePipelineStage, "process"); scene2.fog.enabled = false; scene2.fog.renderable = false; const model = await loadAndZoomToModelAsync_default( { gltf: buildingsMetadata }, scene2 ); model.customShader = new import__720.CustomShader(); model.update(scene2.frameState); expect(import__720.AtmospherePipelineStage.process).not.toHaveBeenCalled(); }); it("does not add fog stage when fog is not renderable", async function() { spyOn(import__720.AtmospherePipelineStage, "process"); scene2.fog.enabled = true; scene2.fog.renderable = false; const model = await loadAndZoomToModelAsync_default( { gltf: buildingsMetadata }, scene2 ); model.customShader = new import__720.CustomShader(); model.update(scene2.frameState); expect(import__720.AtmospherePipelineStage.process).not.toHaveBeenCalled(); }); it("adds fog stage when fog is enabled and renderable", async function() { spyOn(import__720.AtmospherePipelineStage, "process"); scene2.fog.enabled = true; scene2.fog.renderable = true; const model = await loadAndZoomToModelAsync_default( { gltf: buildingsMetadata }, scene2 ); model.customShader = new import__720.CustomShader(); model.update(scene2.frameState); expect(import__720.AtmospherePipelineStage.process).toHaveBeenCalled(); }); it("pushDrawCommands ignores hidden nodes", async function() { const model = await loadAndZoomToModelAsync_default( { gltf: duckUrl }, scene2 ); const frameState2 = scene2.frameState; const commandList = frameState2.commandList; const sceneGraph = model._sceneGraph; const rootNode = sceneGraph._runtimeNodes[0]; const meshNode = sceneGraph._runtimeNodes[2]; expect(rootNode.show).toBe(true); expect(meshNode.show).toBe(true); sceneGraph.pushDrawCommands(frameState2); const originalLength = commandList.length; expect(originalLength).not.toEqual(0); commandList.length = 0; meshNode.show = false; sceneGraph.pushDrawCommands(frameState2); expect(commandList.length).toEqual(0); meshNode.show = true; rootNode.show = false; sceneGraph.pushDrawCommands(frameState2); expect(commandList.length).toEqual(0); rootNode.show = true; sceneGraph.pushDrawCommands(frameState2); expect(commandList.length).toEqual(originalLength); }); it("throws for undefined options.model", function() { expect(function() { return new import__720.ModelSceneGraph({ model: void 0, modelComponents: {} }); }).toThrowDeveloperError(); }); it("throws for undefined options.modelComponents", function() { expect(function() { return new import__720.ModelSceneGraph({ model: {}, modelComponents: void 0 }); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/ModelSilhouettePipelineStageSpec.js var import__721 = __toESM(require_Cesium(), 1); describe("Scene/Model/ModelSilhouettePipelineStage", function() { beforeEach(function() { import__721.ModelSilhouettePipelineStage.silhouettesLength = 0; }); it("configures the render resources for silhouette", function() { const mockModel = { silhouetteColor: import__721.Color.RED, silhouetteSize: 1, _silhouetteId: void 0 }; const renderResources = { shaderBuilder: new import__721.ShaderBuilder(), uniformMap: {}, model: mockModel }; const shaderBuilder = renderResources.shaderBuilder; import__721.ModelSilhouettePipelineStage.process(renderResources, mockModel); expect(import__721.ModelSilhouettePipelineStage.silhouettesLength).toEqual(1); expect(mockModel._silhouetteId).toEqual(1); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_SILHOUETTE" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_SILHOUETTE" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform float model_silhouetteSize;", "uniform bool model_silhouettePass;" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform vec4 model_silhouetteColor;", "uniform bool model_silhouettePass;" ]); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__721._shadersModelSilhouetteStageVS ]); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__721._shadersModelSilhouetteStageFS ]); const uniformMap = renderResources.uniformMap; expect(uniformMap.model_silhouetteColor()).toEqual( mockModel.silhouetteColor ); expect(uniformMap.model_silhouetteSize()).toEqual(mockModel.silhouetteSize); expect(uniformMap.model_silhouettePass()).toBe(false); expect(renderResources.hasSilhouette).toBe(true); }); }); // packages/engine/Specs/Scene/Model/ModelSkinSpec.js var import__722 = __toESM(require_Cesium(), 1); describe("Scene/Model/ModelSkin", function() { const mockNodes = [{ index: 0 }, { index: 1 }, { index: 2 }]; const mockRuntimeNodes = [ { node: mockNodes[0], transform: import__722.Matrix4.clone(import__722.Matrix4.IDENTITY), transformToRoot: import__722.Matrix4.clone(import__722.Matrix4.IDENTITY) }, { node: mockNodes[1], transform: import__722.Matrix4.clone(import__722.Matrix4.IDENTITY), transformToRoot: import__722.Matrix4.clone(import__722.Matrix4.IDENTITY) }, { node: mockNodes[2], transform: import__722.Matrix4.clone(import__722.Matrix4.IDENTITY), transformToRoot: import__722.Matrix4.clone(import__722.Matrix4.IDENTITY) } ]; const mockSceneGraph = { _runtimeNodes: mockRuntimeNodes }; const mockSkin = { inverseBindMatrices: [ import__722.Matrix4.clone(import__722.Matrix4.IDENTITY), import__722.Matrix4.clone(import__722.Matrix4.IDENTITY) ], joints: [mockNodes[1], mockNodes[2]] }; it("throws for undefined skin", function() { expect(function() { return new import__722.ModelSkin({ skin: void 0, sceneGraph: mockSceneGraph }); }).toThrowDeveloperError(); }); it("throws for undefined scene graph", function() { expect(function() { return new import__722.ModelSkin({ skin: mockSkin, sceneGraph: void 0 }); }).toThrowDeveloperError(); }); it("constructs", function() { const skin = new import__722.ModelSkin({ skin: mockSkin, sceneGraph: mockSceneGraph }); expect(skin.skin).toBe(mockSkin); expect(skin.sceneGraph).toBe(mockSceneGraph); expect(skin.inverseBindMatrices).toEqual(mockSkin.inverseBindMatrices); expect(skin.joints).toEqual([mockRuntimeNodes[1], mockRuntimeNodes[2]]); expect(skin.jointMatrices).toEqual([import__722.Matrix4.IDENTITY, import__722.Matrix4.IDENTITY]); }); }); // packages/engine/Specs/Scene/Model/ModelSpec.js var import__723 = __toESM(require_Cesium(), 1); describe( "Scene/Model/Model", function() { const webglStub = !!window.webglStub; const triangleWithoutIndicesUrl = "./Data/Models/glTF-2.0/TriangleWithoutIndices/glTF/TriangleWithoutIndices.gltf"; const animatedTriangleUrl = "./Data/Models/glTF-2.0/AnimatedTriangle/glTF/AnimatedTriangle.gltf"; const animatedTriangleOffset = new import__723.HeadingPitchRange( import__723.Math.PI / 2, 0, 2 ); const boxTexturedGltfUrl = "./Data/Models/glTF-2.0/BoxTextured/glTF/BoxTextured.gltf"; const boxTexturedGlbUrl = "./Data/Models/glTF-2.0/BoxTextured/glTF-Binary/BoxTextured.glb"; const buildingsMetadata = "./Data/Models/glTF-2.0/BuildingsMetadata/glTF/buildings-metadata.gltf"; const boxInstanced = "./Data/Models/glTF-2.0/BoxInstanced/glTF/box-instanced.gltf"; const boxInstancedNoNormalsUrl = "./Data/Models/glTF-2.0/BoxInstancedNoNormals/glTF/BoxInstancedNoNormals.gltf"; const boxUnlitUrl = "./Data/Models/glTF-2.0/UnlitTest/glTF/UnlitTest.gltf"; const boxArticulationsUrl = "./Data/Models/glTF-2.0/BoxArticulations/glTF/BoxArticulations.gltf"; const boxArticulationsMatrix = import__723.Matrix4.fromRowMajorArray([ 1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1 ]); const boxWithOffsetUrl = "./Data/Models/glTF-2.0/BoxWithOffset/glTF/BoxWithOffset.gltf"; const microcosm = "./Data/Models/glTF-2.0/Microcosm/glTF/microcosm.gltf"; const morphPrimitivesTestUrl = "./Data/Models/glTF-2.0/MorphPrimitivesTest/glTF/MorphPrimitivesTest.gltf"; const pointCloudUrl = "./Data/Models/glTF-2.0/PointCloudWithRGBColors/glTF-Binary/PointCloudWithRGBColors.glb"; const twoSidedPlaneUrl = "./Data/Models/glTF-2.0/TwoSidedPlane/glTF/TwoSidedPlane.gltf"; const vertexColorTestUrl = "./Data/Models/glTF-2.0/VertexColorTest/glTF/VertexColorTest.gltf"; const emissiveTextureUrl = "./Data/Models/glTF-2.0/BoxEmissive/glTF/BoxEmissive.gltf"; const boomBoxUrl = "./Data/Models/glTF-2.0/BoomBox/glTF-pbrSpecularGlossiness/BoomBox.gltf"; const riggedFigureUrl = "./Data/Models/glTF-2.0/RiggedFigureTest/glTF/RiggedFigureTest.gltf"; const dracoCesiumManUrl = "./Data/Models/glTF-2.0/CesiumMan/glTF-Draco/CesiumMan.gltf"; const boxCesiumRtcUrl = "./Data/Models/glTF-2.0/BoxCesiumRtc/glTF/BoxCesiumRtc.gltf"; const propertyTextureWithTextureTransformUrl = "./Data/Models/glTF-2.0/PropertyTextureWithTextureTransform/glTF/PropertyTextureWithTextureTransform.gltf"; const featureIdTextureWithTextureTransformUrl = "./Data/Models/glTF-2.0/FeatureIdTextureWithTextureTransform/glTF/FeatureIdTextureWithTextureTransform.gltf"; const fixedFrameTransform = import__723.Transforms.localFrameToFixedFrameGenerator( "north", "west" ); const modelMatrix = import__723.Transforms.headingPitchRollToFixedFrame( import__723.Cartesian3.fromDegrees(-123.0744619, 44.0503706, 0), new import__723.HeadingPitchRoll(0, 0, 0), import__723.Ellipsoid.WGS84, fixedFrameTransform ); let scene2; let scene2D; let sceneCV; beforeAll(function() { scene2 = createScene_default(); scene2D = createScene_default(); scene2D.morphTo2D(0); sceneCV = createScene_default(); sceneCV.morphToColumbusView(0); }); afterAll(function() { scene2.destroyForSpecs(); scene2D.destroyForSpecs(); sceneCV.destroyForSpecs(); }); afterEach(function() { scene2.primitives.removeAll(); scene2D.primitives.removeAll(); sceneCV.primitives.removeAll(); scene2.verticalExaggeration = 1; import__723.ResourceCache.clearForSpecs(); }); function zoomTo(model, zoom) { zoom = (0, import__723.defaultValue)(zoom, 4); const camera = scene2.camera; const center = model.boundingSphere.center; const r = zoom * Math.max(model.boundingSphere.radius, camera.frustum.near); camera.lookAt(center, new import__723.HeadingPitchRange(0, 0, r)); } const scratchBytes = []; const defaultDate = import__723.JulianDate.fromDate( /* @__PURE__ */ new Date("January 1, 2014 12:00:00 UTC") ); function verifyRender(model, shouldRender, options) { expect(model.ready).toBe(true); options = (0, import__723.defaultValue)(options, import__723.defaultValue.EMPTY_OBJECT); const zoomToModel = (0, import__723.defaultValue)(options.zoomToModel, true); if (zoomToModel) { zoomTo(model); } const backgroundColor = (0, import__723.defaultValue)( options.backgroundColor, import__723.Color.BLACK ); const targetScene = (0, import__723.defaultValue)(options.scene, scene2); targetScene.backgroundColor = backgroundColor; const backgroundColorBytes = backgroundColor.toBytes(scratchBytes); const time2 = (0, import__723.defaultValue)(options.time, defaultDate); expect({ scene: targetScene, time: time2 }).toRenderAndCall(function(rgba) { if (shouldRender) { expect(rgba).not.toEqual(backgroundColorBytes); } else { expect(rgba).toEqual(backgroundColorBytes); } }); targetScene.backgroundColor = import__723.Color.BLACK; } function verifyDebugWireframe(model, primitiveType, options) { options = (0, import__723.defaultValue)(options, import__723.defaultValue.EMPTY_OBJECT); const modelHasIndices = (0, import__723.defaultValue)(options.hasIndices, true); const targetScene = (0, import__723.defaultValue)(options.scene, scene2); const commandList = targetScene.frameState.commandList; const commandCounts = []; let i, command; targetScene.renderForSpecs(); for (i = 0; i < commandList.length; i++) { command = commandList[i]; expect(command.primitiveType).toBe(primitiveType); if (!modelHasIndices) { expect(command.vertexArray.indexBuffer).toBeUndefined(); } commandCounts.push(command.count); } model.debugWireframe = true; expect(model._drawCommandsBuilt).toBe(false); targetScene.renderForSpecs(); for (i = 0; i < commandList.length; i++) { command = commandList[i]; expect(command.primitiveType).toBe(import__723.PrimitiveType.LINES); expect(command.vertexArray.indexBuffer).toBeDefined(); const expectedCount = import__723.WireframeIndexGenerator.getWireframeIndicesCount( primitiveType, commandCounts[i] ); expect(command.count).toEqual(expectedCount); } model.debugWireframe = false; expect(model._drawCommandsBuilt).toBe(false); targetScene.renderForSpecs(); for (i = 0; i < commandList.length; i++) { command = commandList[i]; expect(command.primitiveType).toBe(primitiveType); if (!modelHasIndices) { expect(command.vertexArray.indexBuffer).toBeUndefined(); } expect(command.count).toEqual(commandCounts[i]); } } it("fromGltfAsync throws with undefined options", async function() { await expectAsync(import__723.Model.fromGltfAsync()).toBeRejectedWithDeveloperError(); }); it("fromGltfAsync throws with undefined url", async function() { await expectAsync( import__723.Model.fromGltfAsync({}) ).toBeRejectedWithDeveloperError(); }); it("initializes and renders from Uint8Array", function() { const resource = import__723.Resource.createIfNeeded(boxTexturedGlbUrl); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { return loadAndZoomToModelAsync_default( { gltf: new Uint8Array(buffer) }, scene2 ).then(function(model) { expect(model.ready).toEqual(true); expect(model._sceneGraph).toBeDefined(); expect(model._resourcesLoaded).toEqual(true); verifyRender(model, true); }); }); }); it("initializes and renders from JSON object", function() { const resource = import__723.Resource.createIfNeeded(boxTexturedGltfUrl); return resource.fetchJson().then(function(gltf) { return loadAndZoomToModelAsync_default( { gltf, basePath: boxTexturedGltfUrl }, scene2 ).then(function(model) { expect(model.ready).toEqual(true); expect(model._sceneGraph).toBeDefined(); expect(model._resourcesLoaded).toEqual(true); verifyRender(model, true); }); }); }); it("initializes and renders from JSON object with external buffers", function() { const resource = import__723.Resource.createIfNeeded(microcosm); return resource.fetchJson().then(function(gltf) { return loadAndZoomToModelAsync_default( { gltf, basePath: microcosm }, scene2 ).then(function(model) { expect(model.ready).toEqual(true); expect(model._sceneGraph).toBeDefined(); expect(model._resourcesLoaded).toEqual(true); verifyRender(model, true); }); }); }); it("initializes and renders with url", function() { return loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl }, scene2 ).then(function(model) { expect(model.ready).toEqual(true); expect(model._sceneGraph).toBeDefined(); expect(model._resourcesLoaded).toEqual(true); verifyRender(model, true); }); }); it("calls gltfCallback", function() { let wasCalled = false; return loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl, gltfCallback: (gltf) => { wasCalled = true; expect(gltf).toEqual( jasmine.objectContaining({ asset: { generator: "COLLADA2GLTF", version: "2.0" } }) ); } }, scene2 ).then(function(model) { expect(model.ready).toEqual(true); expect(model._sceneGraph).toBeDefined(); expect(model._resourcesLoaded).toEqual(true); expect(wasCalled).toBeTrue(); verifyRender(model, true); }); }); it("raises errorEvent when a texture fails to load and incrementallyLoadTextures is true", async function() { const resource = import__723.Resource.createIfNeeded(boxTexturedGltfUrl); const gltf = await resource.fetchJson(); gltf.images[0].uri = "non-existent-path.png"; const model = await import__723.Model.fromGltfAsync({ gltf, basePath: boxTexturedGltfUrl, incrementallyLoadTextures: true }); scene2.primitives.add(model); let finished = false; model.errorEvent.addEventListener((e) => { expect(e).toBeInstanceOf(import__723.RuntimeError); expect(e.message).toContain("Failed to load texture"); expect(e.message).toContain( "Failed to load image: non-existent-path.png" ); finished = true; }); return pollToPromise_default(function() { scene2.renderForSpecs(); return model.ready && finished; }); }); it("raises errorEvent when a texture fails to load and incrementallyLoadTextures is false", async function() { const resource = import__723.Resource.createIfNeeded(boxTexturedGltfUrl); const gltf = await resource.fetchJson(); gltf.images[0].uri = "non-existent-path.png"; const model = await import__723.Model.fromGltfAsync({ gltf, basePath: boxTexturedGltfUrl, incrementallyLoadTextures: false }); scene2.primitives.add(model); let finished = false; model.errorEvent.addEventListener((e) => { expect(e).toBeInstanceOf(import__723.RuntimeError); expect(e.message).toContain( `Failed to load model: ${boxTexturedGltfUrl}` ); expect(e.message).toContain("Failed to load texture"); finished = true; }); return pollToPromise_default(function() { scene2.renderForSpecs(); return finished; }); }); it("raises errorEvent when external buffer fails to load", async function() { const resource = import__723.Resource.createIfNeeded(boxTexturedGltfUrl); const gltf = await resource.fetchJson(); gltf.buffers[0].uri = "non-existent-path.bin"; const model = await import__723.Model.fromGltfAsync({ gltf, basePath: boxTexturedGltfUrl, incrementallyLoadTextures: false }); scene2.primitives.add(model); let finished = false; model.errorEvent.addEventListener((e) => { expect(e).toBeInstanceOf(import__723.RuntimeError); expect(e.message).toContain( `Failed to load model: ${boxTexturedGltfUrl}` ); expect(e.message).toContain("Failed to load vertex buffer"); finished = true; }); return pollToPromise_default(function() { scene2.renderForSpecs(); return finished; }); }); it("loads with asynchronous set to true", function() { const jobSchedulerExecute = spyOn( import__723.JobScheduler.prototype, "execute" ).and.callThrough(); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, asynchronous: true }, scene2 ).then(function(model) { const loader = model.loader; expect(loader._asynchronous).toBe(true); expect(jobSchedulerExecute).toHaveBeenCalled(); }); }); it("loads with asynchronous set to false", function() { const jobSchedulerExecute = spyOn( import__723.JobScheduler.prototype, "execute" ).and.callThrough(); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, asynchronous: false }, scene2 ).then(function(model) { const loader = model.loader; expect(loader._asynchronous).toBe(false); expect(jobSchedulerExecute).not.toHaveBeenCalled(); }); }); it("initializes feature table", function() { return loadAndZoomToModelAsync_default({ gltf: buildingsMetadata }, scene2).then( function(model) { expect(model.ready).toEqual(true); expect(model.featureTables).toBeDefined(); const featureTable = model.featureTables[0]; expect(featureTable).toBeDefined(); const featuresLength = featureTable.featuresLength; expect(featuresLength).toEqual(10); expect(featureTable.batchTexture).toBeDefined(); expect(featureTable.batchTexture._featuresLength).toEqual(10); for (let i = 0; i < featuresLength; i++) { const modelFeature = featureTable.getFeature(i); expect(modelFeature instanceof import__723.ModelFeature).toEqual(true); expect(modelFeature._featureId).toEqual(i); expect(modelFeature.primitive).toEqual(model); expect(modelFeature.featureTable).toEqual(featureTable); } expect(model._resourcesLoaded).toEqual(true); } ); }); it("sets default properties", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl }, scene2 ).then(function(model) { expect(model.show).toEqual(true); expect(model.modelMatrix).toEqual(import__723.Matrix4.IDENTITY); expect(model.scale).toEqual(1); expect(model.minimumPixelSize).toEqual(0); expect(model.maximumScale).toBeUndefined(); expect(model.id).toBeUndefined(); expect(model.allowPicking).toEqual(true); expect(model.activeAnimations).toBeDefined(); expect(model.clampAnimations).toEqual(true); expect(model.shadows).toEqual(import__723.ShadowMode.ENABLED); expect(model.debugShowBoundingVolume).toEqual(false); expect(model._enableDebugWireframe).toEqual(false); expect(model.debugWireframe).toEqual(false); expect(model.cull).toEqual(true); expect(model.backFaceCulling).toEqual(true); expect(model.opaquePass).toEqual(import__723.Pass.OPAQUE); expect(model.customShader).toBeUndefined(); expect(model.heightReference).toEqual(import__723.HeightReference.NONE); expect(model.scene).toBeUndefined(); expect(model.distanceDisplayCondition).toBeUndefined(); expect(model.color).toBeUndefined(); expect(model.colorBlendMode).toEqual(import__723.ColorBlendMode.HIGHLIGHT); expect(model.colorBlendAmount).toEqual(0.5); expect(model.silhouetteColor).toEqual(import__723.Color.RED); expect(model.silhouetteSize).toEqual(0); expect(model._enableShowOutline).toEqual(true); expect(model.showOutline).toEqual(true); expect(model.outlineColor).toEqual(import__723.Color.BLACK); expect(model.clippingPlanes).toBeUndefined(); expect(model.lightColor).toBeUndefined(); expect(model.imageBasedLighting).toBeDefined(); expect(model.credit).toBeUndefined(); expect(model.showCreditsOnScreen).toEqual(false); expect(model.splitDirection).toEqual(import__723.SplitDirection.NONE); expect(model._projectTo2D).toEqual(false); }); }); it("renders model without indices", function() { const resource = import__723.Resource.createIfNeeded(triangleWithoutIndicesUrl); return resource.fetchJson().then(function(gltf) { return loadAndZoomToModelAsync_default( { gltf, basePath: triangleWithoutIndicesUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame( import__723.Cartesian3.fromDegrees(0, 0, 100) ) }, scene2 ).then(function(model) { const center = model.boundingSphere.center; const range = 4 * model.boundingSphere.radius; scene2.camera.lookAt( center, new import__723.HeadingPitchRange(-import__723.Math.PI_OVER_TWO, 0, range) ); scene2.camera.moveDown(0.1); verifyRender(model, true, { zoomToModel: false }); }); }); }); it("renders model with vertex colors", function() { const resource = import__723.Resource.createIfNeeded(vertexColorTestUrl); return resource.fetchJson().then(function(gltf) { return loadAndZoomToModelAsync_default( { gltf, basePath: vertexColorTestUrl }, scene2 ).then(function(model) { const renderOptions = { scene: scene2, time: defaultDate }; scene2.camera.moveLeft(0.5); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toEqual(0); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(255); expect(rgba[3]).toEqual(255); }); scene2.camera.moveRight(1); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toEqual(255); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); }); }); }); }); it("renders model with double-sided material", function() { const resource = import__723.Resource.createIfNeeded(twoSidedPlaneUrl); return resource.fetchJson().then(function(gltf) { return loadAndZoomToModelAsync_default( { gltf, basePath: twoSidedPlaneUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame( import__723.Cartesian3.fromDegrees(0, 0, 100) ) }, scene2 ).then(function(model) { const renderOptions = { scene: scene2, time: defaultDate }; const center = model.boundingSphere.center; const range = 4 * model.boundingSphere.radius; scene2.camera.lookAt( center, new import__723.HeadingPitchRange(0, -import__723.Math.PI_OVER_TWO, range) ); let result; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); result = rgba; }); scene2.camera.lookAt( center, new import__723.HeadingPitchRange(0, import__723.Math.PI_OVER_TWO, range) ); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba[0]).toBeLessThan(result[0]); expect(rgba[1]).toBeLessThan(result[1]); expect(rgba[2]).toBeLessThan(result[2]); expect(rgba[3]).toEqual(result[3]); }); }); }); }); xit("renders model with emissive texture", function() { const resource = import__723.Resource.createIfNeeded(emissiveTextureUrl); return resource.fetchJson().then(function(gltf) { return loadAndZoomToModelAsync_default( { gltf, basePath: emissiveTextureUrl }, scene2 ).then(function(model) { const renderOptions = { scene: scene2, time: defaultDate }; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeGreaterThan(20); expect(rgba[1]).toBeLessThan(20); expect(rgba[2]).toBeLessThan(20); expect(rgba[3]).toEqual(255); }); }); }); }); it("renders model with the KHR_materials_pbrSpecularGlossiness extension", function() { const offset = new import__723.HeadingPitchRange(0, -import__723.Math.PI_OVER_FOUR, 2); const resource = import__723.Resource.createIfNeeded(boomBoxUrl); return resource.fetchJson().then(function(gltf) { return loadAndZoomToModelAsync_default( { gltf, basePath: boomBoxUrl, // This model is tiny, so scale it up so it's visible. scale: 10, offset }, scene2 ).then(function(model) { verifyRender(model, true); }); }); }); it("transforms property textures with KHR_texture_transform", async function() { const resource = import__723.Resource.createIfNeeded( propertyTextureWithTextureTransformUrl ); const customShader = new import__723.CustomShader({ fragmentShaderText: ` void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) { float value = float(fsInput.metadata.exampleProperty); float i = value * 255.0; if (i < 16.0 * 3.0) { material.diffuse = vec3(1.0, 0.0, 0.0); } else if (i >= 48.0 * 3.0) { material.diffuse = vec3(1.0, 0.0, 0.0); } else { material.diffuse = vec3(0.0, 0.0, 0.0); } } ` }); const gltf = await resource.fetchJson(); await loadAndZoomToModelAsync_default( { gltf, basePath: propertyTextureWithTextureTransformUrl, customShader, // This is important to make sure that the property // texture is fully loaded when the model is rendered! incrementallyLoadTextures: false }, scene2 ); const renderOptions = { scene: scene2, time: defaultDate }; scene2.camera.position = new import__723.Cartesian3(0.15, 0.1, 0.1); scene2.camera.direction = import__723.Cartesian3.negate( import__723.Cartesian3.UNIT_X, new import__723.Cartesian3() ); scene2.camera.up = import__723.Cartesian3.clone(import__723.Cartesian3.UNIT_Z); scene2.camera.frustum.near = 0.01; scene2.camera.frustum.far = 5; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeLessThan(50); expect(rgba[1]).toBeLessThan(50); expect(rgba[2]).toBeLessThan(50); }); }); it("transforms feature ID textures with KHR_texture_transform", async function() { const resource = import__723.Resource.createIfNeeded( featureIdTextureWithTextureTransformUrl ); const customShader = new import__723.CustomShader({ fragmentShaderText: ` void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) { int id = fsInput.featureIds.featureId_0; if (id < 16 * 3) { material.diffuse = vec3(1.0, 0.0, 0.0); } else if (id >= 48 * 3) { material.diffuse = vec3(1.0, 0.0, 0.0); } else { material.diffuse = vec3(0.0, 0.0, 0.0); } } ` }); const gltf = await resource.fetchJson(); await loadAndZoomToModelAsync_default( { gltf, basePath: featureIdTextureWithTextureTransformUrl, customShader, // This is important to make sure that the feature ID // texture is fully loaded when the model is rendered! incrementallyLoadTextures: false }, scene2 ); const renderOptions = { scene: scene2, time: defaultDate }; scene2.camera.position = new import__723.Cartesian3(0.15, 0.1, 0.1); scene2.camera.direction = import__723.Cartesian3.negate( import__723.Cartesian3.UNIT_X, new import__723.Cartesian3() ); scene2.camera.up = import__723.Cartesian3.clone(import__723.Cartesian3.UNIT_Z); scene2.camera.frustum.near = 0.01; scene2.camera.frustum.far = 5; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeLessThan(50); expect(rgba[1]).toBeLessThan(50); expect(rgba[2]).toBeLessThan(50); }); }); it("renders model with morph targets", function() { const offset = new import__723.HeadingPitchRange(0, -import__723.Math.PI_OVER_FOUR, 2); const resource = import__723.Resource.createIfNeeded(morphPrimitivesTestUrl); return resource.fetchJson().then(function(gltf) { return loadAndZoomToModelAsync_default( { gltf, basePath: morphPrimitivesTestUrl, offset }, scene2 ).then(function(model) { const renderOptions = { backgroundColor: import__723.Color.BLUE, zoomToModel: false }; scene2.camera.moveDown(0.25); verifyRender(model, true, renderOptions); }); }); }); it("renders Draco-compressed model", function() { return loadAndZoomToModelAsync_default({ gltf: dracoCesiumManUrl }, scene2).then( function(model) { verifyRender(model, true); } ); }); it("fails to load with Draco decoding error", async function() { import__723.DracoLoader._getDecoderTaskProcessor(); await pollToPromise_default(function() { return import__723.DracoLoader._taskProcessorReady; }); const decoder = import__723.DracoLoader._getDecoderTaskProcessor(); spyOn(decoder, "scheduleTask").and.callFake(function() { return Promise.reject({ message: "Custom error" }); }); const model = scene2.primitives.add( await import__723.Model.fromGltfAsync({ url: dracoCesiumManUrl }) ); let failed = false; model.errorEvent.addEventListener((e) => { expect(e).toBeInstanceOf(import__723.RuntimeError); expect(e.message).toContain( `Failed to load model: ${dracoCesiumManUrl}` ); expect(e.message).toContain("Failed to load Draco"); expect(e.message).toContain("Custom error"); failed = true; }); await pollToPromise_default( function() { scene2.renderForSpecs(); return failed; }, { timeout: 1e4 } ); }); it("renders model without animations added", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl, offset: animatedTriangleOffset }, scene2 ).then(function(model) { const animationCollection = model.activeAnimations; expect(animationCollection).toBeDefined(); expect(animationCollection.length).toBe(0); scene2.camera.moveDown(0.5); verifyRender(model, true, { zoomToModel: false }); }); }); it("renders model with animations added", function() { return loadAndZoomToModelAsync_default( { gltf: animatedTriangleUrl, offset: animatedTriangleOffset }, scene2 ).then(function(model) { scene2.camera.moveDown(0.5); const startTime = defaultDate; const animationCollection = model.activeAnimations; animationCollection.add({ index: 0, startTime }); expect(animationCollection.length).toBe(1); verifyRender(model, true, { zoomToModel: false, time: startTime }); const time2 = import__723.JulianDate.addSeconds(startTime, 0.5, new import__723.JulianDate()); verifyRender(model, false, { zoomToModel: false, time: time2 }); }); }); it("renders model with CESIUM_RTC extension", function() { return loadAndZoomToModelAsync_default( { gltf: boxCesiumRtcUrl }, scene2 ).then(function(model) { verifyRender(model, true); }); }); it("adds animation to draco-compressed model", function() { return loadAndZoomToModelAsync_default({ gltf: dracoCesiumManUrl }, scene2).then( function(model) { verifyRender(model, true); const animationCollection = model.activeAnimations; const animation = animationCollection.add({ index: 0 }); expect(animation).toBeDefined(); expect(animationCollection.length).toBe(1); } ); }); it("renders model with instancing but no normals", function() { const offset = new import__723.HeadingPitchRange( import__723.Math.PI_OVER_TWO, -import__723.Math.PI_OVER_FOUR, 1 ); const resource = import__723.Resource.createIfNeeded(boxInstancedNoNormalsUrl); return resource.fetchJson().then(function(gltf) { return loadAndZoomToModelAsync_default( { gltf, basePath: boxInstancedNoNormalsUrl, offset }, scene2 ).then(function(model) { const renderOptions = { zoomToModel: false }; verifyRender(model, true, renderOptions); }); }); }); it("show works", function() { const resource = import__723.Resource.createIfNeeded(boxTexturedGlbUrl); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { return loadAndZoomToModelAsync_default( { gltf: new Uint8Array(buffer), show: false }, scene2 ).then(function(model) { expect(model.ready).toEqual(true); expect(model.show).toEqual(false); verifyRender(model, false); model.show = true; expect(model.show).toEqual(true); verifyRender(model, true); }); }); }); it("renders in 2D", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, modelMatrix }, scene2D ).then(function(model) { expect(model.ready).toEqual(true); verifyRender(model, true, { zoomToModel: false, scene: scene2D }); }); }); it("renders in 2D over the IDL", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame( import__723.Cartesian3.fromDegrees(180, 0) ) }, scene2D ).then(function(model) { expect(model.ready).toEqual(true); verifyRender(model, true, { zoomToModel: false, scene: scene2D }); model.modelMatrix = import__723.Transforms.eastNorthUpToFixedFrame( import__723.Cartesian3.fromDegrees(-180, 0) ); verifyRender(model, true, { zoomToModel: false, scene: scene2D }); }); }); it("renders in CV", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, modelMatrix }, sceneCV ).then(function(model) { expect(model.ready).toEqual(true); scene2.camera.moveBackward(1); verifyRender(model, true, { zoomToModel: false, scene: sceneCV }); }); }); it("renders in CV after draw commands are reset", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, modelMatrix }, sceneCV ).then(function(model) { expect(model.ready).toEqual(true); scene2.camera.moveBackward(1); verifyRender(model, true, { zoomToModel: false, scene: sceneCV }); model._drawCommandsBuilt = false; verifyRender(model, true, { zoomToModel: false, scene: sceneCV }); }); }); it("projectTo2D works for 2D", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, modelMatrix, projectTo2D: true, incrementallyLoadTextures: false }, scene2D ).then(function(model) { expect(model.ready).toEqual(true); verifyRender(model, true, { zoomToModel: false, scene: scene2D }); }); }); it("projectTo2D works for CV", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, modelMatrix, projectTo2D: true, incrementallyLoadTextures: false }, sceneCV ).then(function(model) { expect(model.ready).toEqual(true); sceneCV.camera.moveBackward(1); verifyRender(model, true, { zoomToModel: false, scene: sceneCV }); }); }); it("does not render during morph", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, modelMatrix, projectTo2D: true }, scene2 ).then(function(model) { const commandList = scene2.frameState.commandList; expect(model.ready).toEqual(true); scene2.renderForSpecs(); expect(commandList.length).toBeGreaterThan(0); scene2.morphTo2D(1); scene2.renderForSpecs(); expect(commandList.length).toBe(0); scene2.completeMorph(); scene2.morphTo3D(0); scene2.renderForSpecs(); expect(commandList.length).toBeGreaterThan(0); }); }); describe("style", function() { it("applies style to model with feature table", function() { let model; let style; return loadAndZoomToModelAsync_default({ gltf: buildingsMetadata }, scene2).then( function(result) { model = result; verifyRender(model, true); style = new import__723.Cesium3DTileStyle({ color: { conditions: [["${height} > 1", "color('red')"]] } }); model.style = style; verifyRender(model, true); expect(model._styleCommandsNeeded).toBe( import__723.StyleCommandsNeeded.ALL_OPAQUE ); style = new import__723.Cesium3DTileStyle({ color: { conditions: [["${height} > 1", "color('red', 0.5)"]] } }); model.style = style; verifyRender(model, true); expect(model._styleCommandsNeeded).toBe( import__723.StyleCommandsNeeded.ALL_TRANSLUCENT ); style = new import__723.Cesium3DTileStyle({ color: { conditions: [["${height} > 1", "color('red', 0.0)"]] } }); style = new import__723.Cesium3DTileStyle({ show: { conditions: [["${height} > 1", "false"]] } }); model.style = style; verifyRender(model, false); model.style = void 0; verifyRender(model, true); } ); }); it("applies style to model without feature table", function() { let model; let style; return loadAndZoomToModelAsync_default({ gltf: boxTexturedGlbUrl }, scene2).then( function(result) { const renderOptions = { scene: scene2, time: defaultDate }; model = result; let original; verifyRender(model, true); expect(renderOptions).toRenderAndCall(function(rgba) { original = rgba; }); style = new import__723.Cesium3DTileStyle({ color: "color('red')" }); model.style = style; verifyRender(model, true); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toEqual(original[0]); expect(rgba[1]).toBeLessThan(original[1]); expect(rgba[2]).toBeLessThan(original[2]); expect(rgba[3]).toEqual(original[3]); }); style = new import__723.Cesium3DTileStyle({ color: "color('red', 0.5)" }); model.style = style; verifyRender(model, true); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeLessThan(original[0]); expect(rgba[1]).toBeLessThan(original[1]); expect(rgba[2]).toBeLessThan(original[2]); expect(rgba[3]).toEqual(original[3]); }); style = new import__723.Cesium3DTileStyle({ color: "color('red', 0.0)" }); model.style = style; verifyRender(model, false, { zoomToModel: false }); style = new import__723.Cesium3DTileStyle({ show: "false" }); model.style = style; verifyRender(model, false, { zoomToModel: false }); model.style = void 0; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toEqual(original[0]); expect(rgba[1]).toEqual(original[1]); expect(rgba[2]).toEqual(original[2]); expect(rgba[3]).toEqual(original[3]); }); } ); }); }); describe("credits", function() { const boxWithCreditsUrl = "./Data/Models/glTF-2.0/BoxWithCopyright/glTF/Box.gltf"; it("initializes with credit", function() { const credit = new import__723.Credit("User Credit"); const resource = import__723.Resource.createIfNeeded(boxTexturedGltfUrl); return resource.fetchJson().then(function(gltf) { return loadAndZoomToModelAsync_default( { gltf, basePath: boxTexturedGltfUrl, credit }, scene2 ).then(function(model) { scene2.renderForSpecs(); const creditDisplay = scene2.frameState.creditDisplay; const credits = creditDisplay._currentFrameCredits.lightboxCredits.values; const length2 = credits.length; expect(length2).toEqual(1); expect(credits[0].credit.html).toEqual("User Credit"); }); }); }); it("initializes with credit string", function() { const creditString = "User Credit"; const resource = import__723.Resource.createIfNeeded(boxTexturedGltfUrl); return resource.fetchJson().then(function(gltf) { return loadAndZoomToModelAsync_default( { gltf, basePath: boxTexturedGltfUrl, credit: creditString }, scene2 ).then(function(model) { scene2.renderForSpecs(); const creditDisplay = scene2.frameState.creditDisplay; const credits = creditDisplay._currentFrameCredits.lightboxCredits.values; const length2 = credits.length; expect(length2).toEqual(1); expect(credits[0].credit.html).toEqual(creditString); }); }); }); it("gets copyrights from gltf", function() { const resource = import__723.Resource.createIfNeeded(boxWithCreditsUrl); return resource.fetchJson().then(function(gltf) { return loadAndZoomToModelAsync_default( { gltf, basePath: boxWithCreditsUrl }, scene2 ).then(function(model) { const expectedCredits = [ "First Source", "Second Source", "Third Source" ]; scene2.renderForSpecs(); const creditDisplay = scene2.frameState.creditDisplay; const credits = creditDisplay._currentFrameCredits.lightboxCredits.values; const length2 = credits.length; expect(length2).toEqual(expectedCredits.length); for (let i = 0; i < length2; i++) { expect(credits[i].credit.html).toEqual(expectedCredits[i]); } }); }); }); it("displays all types of credits", function() { const resource = import__723.Resource.createIfNeeded(boxWithCreditsUrl); return resource.fetchJson().then(function(gltf) { return loadAndZoomToModelAsync_default( { gltf, basePath: boxWithCreditsUrl, credit: "User Credit" }, scene2 ).then(function(model) { model._resourceCredits = [new import__723.Credit("Resource Credit")]; const expectedCredits = [ "User Credit", "Resource Credit", "First Source", "Second Source", "Third Source" ]; scene2.renderForSpecs(); const creditDisplay = scene2.frameState.creditDisplay; const credits = creditDisplay._currentFrameCredits.lightboxCredits.values; const length2 = credits.length; expect(length2).toEqual(expectedCredits.length); for (let i = 0; i < length2; i++) { expect(credits[i].credit.html).toEqual(expectedCredits[i]); } }); }); }); it("initializes with showCreditsOnScreen", function() { const resource = import__723.Resource.createIfNeeded(boxWithCreditsUrl); return resource.fetchJson().then(function(gltf) { return loadAndZoomToModelAsync_default( { gltf, basePath: boxWithCreditsUrl, credit: "User Credit", showCreditsOnScreen: true }, scene2 ).then(function(model) { const expectedCredits = [ "User Credit", "First Source", "Second Source", "Third Source" ]; scene2.renderForSpecs(); const creditDisplay = scene2.frameState.creditDisplay; const credits = creditDisplay._currentFrameCredits.screenCredits.values; const length2 = credits.length; expect(length2).toEqual(expectedCredits.length); for (let i = 0; i < length2; i++) { expect(credits[i].credit.html).toEqual(expectedCredits[i]); } }); }); }); it("changing showCreditsOnScreen works", function() { const resource = import__723.Resource.createIfNeeded(boxWithCreditsUrl); return resource.fetchJson().then(function(gltf) { return loadAndZoomToModelAsync_default( { gltf, basePath: boxWithCreditsUrl, credit: "User Credit", showCreditsOnScreen: false }, scene2 ).then(function(model) { const expectedCredits = [ "User Credit", "First Source", "Second Source", "Third Source" ]; scene2.renderForSpecs(); const creditDisplay = scene2.frameState.creditDisplay; const lightboxCredits = creditDisplay._currentFrameCredits.lightboxCredits.values; const screenCredits = creditDisplay._currentFrameCredits.screenCredits.values; let length2 = lightboxCredits.length; expect(length2).toEqual(expectedCredits.length); for (let i = 0; i < length2; i++) { expect(lightboxCredits[i].credit.html).toEqual( expectedCredits[i] ); } expect(screenCredits.length).toEqual(0); model.showCreditsOnScreen = true; scene2.renderForSpecs(); length2 = screenCredits.length; expect(length2).toEqual(expectedCredits.length); for (let i = 0; i < length2; i++) { expect(screenCredits[i].credit.html).toEqual(expectedCredits[i]); } expect(lightboxCredits.length).toEqual(0); model.showCreditsOnScreen = false; scene2.renderForSpecs(); length2 = lightboxCredits.length; expect(length2).toEqual(expectedCredits.length); for (let i = 0; i < length2; i++) { expect(lightboxCredits[i].credit.html).toEqual( expectedCredits[i] ); } expect(screenCredits.length).toEqual(0); }); }); }); it("showCreditsOnScreen overrides existing credit setting", function() { const resource = import__723.Resource.createIfNeeded(boxTexturedGltfUrl); return resource.fetchJson().then(function(gltf) { return loadAndZoomToModelAsync_default( { gltf, basePath: boxTexturedGltfUrl, credit: new import__723.Credit("User Credit", false), showCreditsOnScreen: true }, scene2 ).then(function(model) { scene2.renderForSpecs(); const creditDisplay = scene2.frameState.creditDisplay; const credits = creditDisplay._currentFrameCredits.screenCredits.values; const length2 = credits.length; expect(length2).toEqual(1); for (let i = 0; i < length2; i++) { expect(credits[i].credit.html).toEqual("User Credit"); } }); }); }); }); describe("debugWireframe", function() { const triangleStripUrl = "./Data/Models/glTF-2.0/TriangleStrip/glTF/TriangleStrip.gltf"; const triangleFanUrl = "./Data/Models/glTF-2.0/TriangleFan/glTF/TriangleFan.gltf"; let sceneWithWebgl1; beforeAll(function() { sceneWithWebgl1 = createScene_default({ contextOptions: { requestWebgl1: true } }); }); afterEach(function() { sceneWithWebgl1.primitives.removeAll(); }); afterAll(function() { sceneWithWebgl1.destroyForSpecs(); }); it("debugWireframe works for WebGL1 if enableDebugWireframe is true", function() { const resource = import__723.Resource.createIfNeeded(boxTexturedGlbUrl); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { return loadAndZoomToModelAsync_default( { gltf: new Uint8Array(buffer), enableDebugWireframe: true }, sceneWithWebgl1 ).then(function(model) { verifyDebugWireframe(model, import__723.PrimitiveType.TRIANGLES); }); }); }); it("debugWireframe does nothing in WebGL1 if enableDebugWireframe is false", function() { const resource = import__723.Resource.createIfNeeded(boxTexturedGlbUrl); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { return loadAndZoomToModelAsync_default( { gltf: new Uint8Array(buffer), enableDebugWireframe: false }, sceneWithWebgl1 ).then(function(model) { const commandList = scene2.frameState.commandList; const commandCounts = []; let i, command; sceneWithWebgl1.renderForSpecs(); for (i = 0; i < commandList.length; i++) { command = commandList[i]; expect(command.primitiveType).toBe(import__723.PrimitiveType.TRIANGLES); commandCounts.push(command.count); } model.debugWireframe = true; expect(model._drawCommandsBuilt).toBe(false); sceneWithWebgl1.renderForSpecs(); for (i = 0; i < commandList.length; i++) { command = commandList[i]; expect(command.primitiveType).toBe(import__723.PrimitiveType.TRIANGLES); expect(command.count).toEqual(commandCounts[i]); } }); }); }); it("debugWireframe works for WebGL2", function() { if (!scene2.context.webgl2) { return; } const resource = import__723.Resource.createIfNeeded(boxTexturedGlbUrl); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { return loadAndZoomToModelAsync_default( { gltf: new Uint8Array(buffer) }, scene2 ).then(function(model) { verifyDebugWireframe(model, import__723.PrimitiveType.TRIANGLES, { scene: scene2 }); }); }); }); it("debugWireframe works for model without indices", function() { return loadAndZoomToModelAsync_default( { gltf: triangleWithoutIndicesUrl, enableDebugWireframe: true }, scene2 ).then(function(model) { verifyDebugWireframe(model, import__723.PrimitiveType.TRIANGLES, { hasIndices: false }); }); }); it("debugWireframe works for model with triangle strip", function() { return loadAndZoomToModelAsync_default( { gltf: triangleStripUrl, enableDebugWireframe: true }, scene2 ).then(function(model) { verifyDebugWireframe(model, import__723.PrimitiveType.TRIANGLE_STRIP); }); }); it("debugWireframe works for model with triangle fan", function() { return loadAndZoomToModelAsync_default( { gltf: triangleFanUrl, enableDebugWireframe: true }, scene2 ).then(function(model) { verifyDebugWireframe(model, import__723.PrimitiveType.TRIANGLE_FAN); }); }); it("debugWireframe ignores points", function() { return loadAndZoomToModelAsync_default( { gltf: pointCloudUrl, enableDebugWireframe: true }, scene2 ).then(function(model) { let i; scene2.renderForSpecs(); const commandList = scene2.frameState.commandList; for (i = 0; i < commandList.length; i++) { const command = commandList[i]; expect(command.primitiveType).toBe(import__723.PrimitiveType.POINTS); expect(command.vertexArray.indexBuffer).toBeUndefined(); } model.debugWireframe = true; for (i = 0; i < commandList.length; i++) { const command = commandList[i]; expect(command.primitiveType).toBe(import__723.PrimitiveType.POINTS); expect(command.vertexArray.indexBuffer).toBeUndefined(); } }); }); }); it("debugShowBoundingVolume works", function() { const resource = import__723.Resource.createIfNeeded(boxTexturedGlbUrl); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { return loadAndZoomToModelAsync_default( { gltf: new Uint8Array(buffer), debugShowBoundingVolume: true }, scene2 ).then(function(model) { let i; scene2.renderForSpecs(); const commandList = scene2.frameState.commandList; for (i = 0; i < commandList.length; i++) { expect(commandList[i].debugShowBoundingVolume).toBe(true); } model.debugShowBoundingVolume = false; expect(model._debugShowBoundingVolumeDirty).toBe(true); scene2.renderForSpecs(); for (i = 0; i < commandList.length; i++) { expect(commandList[i].debugShowBoundingVolume).toBe(false); } }); }); }); describe("boundingSphere", function() { it("boundingSphere throws if model is not ready", async function() { const model = await import__723.Model.fromGltfAsync({ url: boxTexturedGlbUrl }); expect(function() { return model.boundingSphere; }).toThrowDeveloperError(); }); it("boundingSphere works", function() { const resource = import__723.Resource.createIfNeeded(boxTexturedGlbUrl); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { return loadAndZoomToModelAsync_default( { gltf: new Uint8Array(buffer) }, scene2 ).then(function(model) { const boundingSphere = model.boundingSphere; expect(boundingSphere).toBeDefined(); expect(boundingSphere.center).toEqual(new import__723.Cartesian3()); expect(boundingSphere.radius).toEqualEpsilon( 0.8660254037844386, import__723.Math.EPSILON8 ); }); }); }); it("boundingSphere accounts for axis correction", function() { const resource = import__723.Resource.createIfNeeded(riggedFigureUrl); return resource.fetchJson().then(function(gltf) { return loadAndZoomToModelAsync_default({ gltf }, scene2).then(function(model) { const boundingSphere = model.boundingSphere; expect(boundingSphere).toBeDefined(); expect(boundingSphere.center).toEqualEpsilon( new import__723.Cartesian3(0.0320296511054039, 0, 0.7249599695205688), import__723.Math.EPSILON3 ); expect(boundingSphere.radius).toEqualEpsilon( 0.9484635280120018, import__723.Math.EPSILON3 ); }); }); }); it("boundingSphere accounts for transform from CESIUM_RTC extension", function() { return loadAndZoomToModelAsync_default( { gltf: boxCesiumRtcUrl }, scene2 ).then(function(model) { const boundingSphere = model.boundingSphere; expect(boundingSphere).toBeDefined(); expect(boundingSphere.center).toEqual(new import__723.Cartesian3(6378137, 0, 0)); }); }); it("boundingSphere updates bounding sphere when invoked", function() { return loadAndZoomToModelAsync_default({ gltf: boxTexturedGlbUrl }, scene2).then( function(model) { const expectedRadius = 0.8660254037844386; const translation = new import__723.Cartesian3(10, 0, 0); const modelMatrix2 = import__723.Matrix4.fromTranslation(translation); model.modelMatrix = modelMatrix2; model.scale = 2; const boundingSphere = model.boundingSphere; expect(boundingSphere.center).toEqual(translation); expect(boundingSphere.radius).toEqualEpsilon( 2 * expectedRadius, import__723.Math.EPSILON8 ); } ); }); }); describe("picking and id", function() { it("initializes with id", function() { const offset = new import__723.HeadingPitchRange(0, -import__723.Math.PI_OVER_FOUR, 2); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, offset, id: boxTexturedGlbUrl }, scene2 ).then(function(model) { expect(model.id).toBe(boxTexturedGlbUrl); const pickIds = model._pickIds; expect(pickIds.length).toEqual(1); expect(pickIds[0].object.id).toEqual(boxTexturedGlbUrl); }); }); it("changing id works", function() { const offset = new import__723.HeadingPitchRange(0, -import__723.Math.PI_OVER_FOUR, 2); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, offset }, scene2 ).then(function(model) { expect(model.id).toBeUndefined(); const pickIds = model._pickIds; expect(pickIds.length).toEqual(1); expect(pickIds[0].object.id).toBeUndefined(); model.id = boxTexturedGlbUrl; scene2.renderForSpecs(); expect(pickIds[0].object.id).toBe(boxTexturedGlbUrl); model.id = void 0; scene2.renderForSpecs(); expect(pickIds[0].object.id).toBeUndefined(); }); }); it("picks box textured", function() { if (import__723.FeatureDetection.isInternetExplorer()) { return; } const offset = new import__723.HeadingPitchRange(0, -import__723.Math.PI_OVER_FOUR, 2); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, offset }, scene2 ).then(function(model) { expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toBeInstanceOf(import__723.Model); expect(result.primitive).toEqual(model); }); }); }); it("picks box textured with id", function() { if (import__723.FeatureDetection.isInternetExplorer()) { return; } const offset = new import__723.HeadingPitchRange(0, -import__723.Math.PI_OVER_FOUR, 2); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, offset, id: boxTexturedGlbUrl }, scene2 ).then(function(model) { expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toBeInstanceOf(import__723.Model); expect(result.primitive).toEqual(model); expect(result.id).toEqual(boxTexturedGlbUrl); }); }); }); it("picks box textured with a new id", function() { if (import__723.FeatureDetection.isInternetExplorer()) { return; } const offset = new import__723.HeadingPitchRange(0, -import__723.Math.PI_OVER_FOUR, 2); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, offset, id: boxTexturedGlbUrl }, scene2 ).then(function(model) { expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toBeInstanceOf(import__723.Model); expect(result.primitive).toEqual(model); expect(result.id).toEqual(boxTexturedGlbUrl); }); model.id = "new id"; expect(scene2).toPickAndCall(function(result) { expect(result.primitive).toBeInstanceOf(import__723.Model); expect(result.primitive).toEqual(model); expect(result.id).toEqual("new id"); }); }); }); it("doesn't pick when allowPicking is false", function() { if (import__723.FeatureDetection.isInternetExplorer()) { return; } const offset = new import__723.HeadingPitchRange(0, -import__723.Math.PI_OVER_FOUR, 2); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, allowPicking: false, offset }, scene2 ).then(function() { expect(scene2).toPickAndCall(function(result) { expect(result).toBeUndefined(); }); }); }); it("doesn't pick when model is hidden", function() { if (import__723.FeatureDetection.isInternetExplorer()) { return; } const offset = new import__723.HeadingPitchRange(0, -import__723.Math.PI_OVER_FOUR, 2); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, offset }, scene2 ).then(function(model) { model.show = false; expect(scene2).toPickAndCall(function(result) { expect(result).toBeUndefined(); }); }); }); }); describe("features", function() { function setFeaturesWithOpacity(featureTable, opaqueFeaturesLength, translucentFeaturesLength) { let i, feature; for (i = 0; i < opaqueFeaturesLength; i++) { feature = featureTable.getFeature(i); feature.color = import__723.Color.RED; } for (i = opaqueFeaturesLength; i < opaqueFeaturesLength + translucentFeaturesLength; i++) { feature = featureTable.getFeature(i); feature.color = import__723.Color.RED.withAlpha(0.5); } } it("resets draw commands when the style commands needed are changed", function() { return loadAndZoomToModelAsync_default( { gltf: buildingsMetadata }, scene2 ).then(function(model) { const featureTable = model.featureTables[model.featureTableId]; setFeaturesWithOpacity(featureTable, 10, 0); scene2.renderForSpecs(); expect(featureTable.styleCommandsNeededDirty).toEqual(false); expect(featureTable._styleCommandsNeeded).toEqual( import__723.StyleCommandsNeeded.ALL_OPAQUE ); setFeaturesWithOpacity(featureTable, 8, 2); scene2.renderForSpecs(); expect(featureTable.styleCommandsNeededDirty).toEqual(true); expect(featureTable._styleCommandsNeeded).toEqual( import__723.StyleCommandsNeeded.OPAQUE_AND_TRANSLUCENT ); setFeaturesWithOpacity(featureTable, 2, 8); scene2.renderForSpecs(); expect(featureTable.styleCommandsNeededDirty).toEqual(false); expect(featureTable._styleCommandsNeeded).toEqual( import__723.StyleCommandsNeeded.OPAQUE_AND_TRANSLUCENT ); setFeaturesWithOpacity(featureTable, 0, 10); scene2.renderForSpecs(); expect(featureTable.styleCommandsNeededDirty).toEqual(true); expect(featureTable._styleCommandsNeeded).toEqual( import__723.StyleCommandsNeeded.ALL_TRANSLUCENT ); }); }); it("selects feature table for instanced feature ID attributes", function() { if (webglStub) { return; } return loadAndZoomToModelAsync_default( { gltf: boxInstanced, instanceFeatureIdLabel: "section" }, scene2 ).then(function(model) { expect(model.featureTableId).toEqual(1); }); }); it("selects feature table for feature ID textures", function() { return loadAndZoomToModelAsync_default( { gltf: microcosm }, scene2 ).then(function(model) { expect(model.featureTableId).toEqual(0); }); }); it("selects feature table for feature ID attributes", function() { return loadAndZoomToModelAsync_default( { gltf: buildingsMetadata }, scene2 ).then(function(model) { expect(model.featureTableId).toEqual(0); }); }); it("featureIdLabel setter works", function() { return loadAndZoomToModelAsync_default( { gltf: buildingsMetadata }, scene2 ).then(function(model) { expect(model.featureIdLabel).toBe("featureId_0"); model.featureIdLabel = "buildings"; expect(model.featureIdLabel).toBe("buildings"); model.featureIdLabel = 1; expect(model.featureIdLabel).toBe("featureId_1"); }); }); it("instanceFeatureIdLabel setter works", function() { if (webglStub) { return; } return loadAndZoomToModelAsync_default( { gltf: boxInstanced }, scene2 ).then(function(model) { expect(model.instanceFeatureIdLabel).toBe("instanceFeatureId_0"); model.instanceFeatureIdLabel = "section"; expect(model.instanceFeatureIdLabel).toBe("section"); model.instanceFeatureIdLabel = 1; expect(model.instanceFeatureIdLabel).toBe("instanceFeatureId_1"); }); }); }); describe("model matrix", function() { it("initializes with model matrix", function() { const translation = new import__723.Cartesian3(10, 0, 0); const transform = import__723.Matrix4.fromTranslation(translation); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, upAxis: import__723.Axis.Z, forwardAxis: import__723.Axis.X, modelMatrix: transform }, scene2 ).then(function(model) { const sceneGraph = model.sceneGraph; scene2.renderForSpecs(); expect(sceneGraph.computedModelMatrix).toEqual(transform); expect(model.boundingSphere.center).toEqual(translation); verifyRender(model, true); expect(sceneGraph.computedModelMatrix).not.toBe(transform); expect(model.modelMatrix).not.toBe(transform); }); }); it("changing model matrix works", function() { const translation = new import__723.Cartesian3(10, 0, 0); const updateModelMatrix = spyOn( import__723.ModelSceneGraph.prototype, "updateModelMatrix" ).and.callThrough(); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, upAxis: import__723.Axis.Z, forwardAxis: import__723.Axis.X }, scene2 ).then(function(model) { verifyRender(model, true); const sceneGraph = model.sceneGraph; const transform = import__723.Matrix4.fromTranslation(translation); import__723.Matrix4.multiplyTransformation( model.modelMatrix, transform, model.modelMatrix ); scene2.renderForSpecs(); expect(updateModelMatrix).toHaveBeenCalled(); expect(sceneGraph.computedModelMatrix).toEqual(transform); verifyRender(model, false, { zoomToModel: false }); }); }); it("changing model matrix affects bounding sphere", function() { const translation = new import__723.Cartesian3(10, 0, 0); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, upAxis: import__723.Axis.Z, forwardAxis: import__723.Axis.X }, scene2 ).then(function(model) { const transform = import__723.Matrix4.fromTranslation(translation); expect(model.boundingSphere.center).toEqual(import__723.Cartesian3.ZERO); import__723.Matrix4.multiplyTransformation( model.modelMatrix, transform, model.modelMatrix ); scene2.renderForSpecs(); expect(model.boundingSphere.center).toEqual(translation); }); }); it("changing model matrix in 2D mode works if projectTo2D is false", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, modelMatrix }, scene2D ).then(function(model) { verifyRender(model, true, { zoomToModel: false, scene: scene2D }); model.modelMatrix = import__723.Matrix4.fromTranslation( new import__723.Cartesian3(10, 10, 10) ); verifyRender(model, false, { zoomToModel: false, scene: scene2D }); }); }); it("changing model matrix in 2D mode throws if projectTo2D is true", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, modelMatrix, projectTo2D: true }, scene2D ).then(function(model) { expect(function() { model.modelMatrix = import__723.Matrix4.IDENTITY; scene2D.renderForSpecs(); }).toThrowDeveloperError(); }); }); }); describe("height reference", function() { beforeEach(() => { scene2.globe = new import__723.Globe(); }); afterEach(() => { scene2.globe = void 0; }); it("initializes with height reference", async function() { const position = import__723.Cartesian3.fromDegrees(-72, 40); const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, heightReference: import__723.HeightReference.CLAMP_TO_GROUND, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame(position), scene: scene2 }, scene2 ); expect(model.heightReference).toEqual(import__723.HeightReference.CLAMP_TO_GROUND); expect(model._scene).toBe(scene2); expect(model._clampedModelMatrix).toBeDefined(); }); it("changing height reference works", async function() { const position = import__723.Cartesian3.fromDegrees(-72, 40); const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, heightReference: import__723.HeightReference.NONE, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame(position), scene: scene2 }, scene2 ); expect(model.heightReference).toEqual(import__723.HeightReference.NONE); expect(model._clampedModelMatrix).toBeUndefined(); model.heightReference = import__723.HeightReference.CLAMP_TO_GROUND; expect(model._heightDirty).toBe(true); scene2.renderForSpecs(); expect(model.heightReference).toEqual(import__723.HeightReference.CLAMP_TO_GROUND); expect(model._clampedModelMatrix).toBeDefined(); }); it("creates height update callback when initializing with height reference", async function() { spyOn(scene2, "updateHeight"); const position = import__723.Cartesian3.fromDegrees(-72, 40); const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame(position), heightReference: import__723.HeightReference.CLAMP_TO_GROUND, scene: scene2 }, scene2 ); expect(model.heightReference).toEqual(import__723.HeightReference.CLAMP_TO_GROUND); expect(scene2.updateHeight).toHaveBeenCalledWith( import__723.Ellipsoid.WGS84.cartesianToCartographic(position), jasmine.any(Function), import__723.HeightReference.CLAMP_TO_GROUND ); }); it("creates height update callback after setting height reference", async function() { const removeCallback = jasmine.createSpy(); spyOn(scene2, "updateHeight").and.returnValue(removeCallback); const position = import__723.Cartesian3.fromDegrees(-72, 40); const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame(position), heightReference: import__723.HeightReference.NONE, scene: scene2 }, scene2 ); model.heightReference = import__723.HeightReference.CLAMP_TO_GROUND; expect(model.heightReference).toEqual(import__723.HeightReference.CLAMP_TO_GROUND); scene2.renderForSpecs(); expect(scene2.updateHeight).toHaveBeenCalledWith( import__723.Ellipsoid.WGS84.cartesianToCartographic(position), jasmine.any(Function), import__723.HeightReference.CLAMP_TO_GROUND ); }); it("removes height update callback after changing height reference", async function() { const removeCallback = jasmine.createSpy(); spyOn(scene2, "updateHeight").and.returnValue(removeCallback); const position = import__723.Cartesian3.fromDegrees(-72, 40); const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame(position), heightReference: import__723.HeightReference.CLAMP_TO_GROUND, scene: scene2 }, scene2 ); model.heightReference = import__723.HeightReference.NONE; expect(model.heightReference).toEqual(import__723.HeightReference.NONE); scene2.renderForSpecs(); expect(removeCallback).toHaveBeenCalled(); }); it("updates height reference callback when the height reference changes", async function() { const removeCallback = jasmine.createSpy(); spyOn(scene2, "updateHeight").and.returnValue(removeCallback); const position = import__723.Cartesian3.fromDegrees(-72, 40); const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame(position), heightReference: import__723.HeightReference.CLAMP_TO_GROUND, scene: scene2 }, scene2 ); expect(scene2.updateHeight).toHaveBeenCalledWith( import__723.Ellipsoid.WGS84.cartesianToCartographic(position), jasmine.any(Function), import__723.HeightReference.CLAMP_TO_GROUND ); model.heightReference = import__723.HeightReference.RELATIVE_TO_GROUND; scene2.renderForSpecs(); expect(removeCallback).toHaveBeenCalled(); expect(scene2.updateHeight).toHaveBeenCalledWith( import__723.Ellipsoid.WGS84.cartesianToCartographic(position), jasmine.any(Function), import__723.HeightReference.RELATIVE_TO_GROUND ); }); it("updates height reference callback when the model matrix changes", async function() { const removeCallback = jasmine.createSpy(); spyOn(scene2, "updateHeight").and.returnValue(removeCallback); let position = import__723.Cartesian3.fromDegrees(-72, 40); const modelMatrix2 = import__723.Transforms.eastNorthUpToFixedFrame(position); const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, modelMatrix: import__723.Matrix4.clone(modelMatrix2), heightReference: import__723.HeightReference.CLAMP_TO_GROUND, scene: scene2 }, scene2 ); expect(scene2.updateHeight).toHaveBeenCalledWith( import__723.Ellipsoid.WGS84.cartesianToCartographic(position), jasmine.any(Function), import__723.HeightReference.CLAMP_TO_GROUND ); position = import__723.Cartesian3.fromDegrees(-73, 40); model.modelMatrix[12] = position.x; model.modelMatrix[13] = position.y; model.modelMatrix[14] = position.z; scene2.renderForSpecs(); expect(removeCallback).toHaveBeenCalled(); expect(scene2.updateHeight).toHaveBeenCalledWith( import__723.Ellipsoid.WGS84.cartesianToCartographic(position), jasmine.any(Function), import__723.HeightReference.CLAMP_TO_GROUND ); }); it("updates height reference callback when the model matrix is set", async function() { const removeCallback = jasmine.createSpy(); spyOn(scene2, "updateHeight").and.returnValue(removeCallback); let position = import__723.Cartesian3.fromDegrees(-72, 40); const modelMatrix2 = import__723.Transforms.eastNorthUpToFixedFrame(position); const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, modelMatrix: import__723.Matrix4.clone(modelMatrix2), heightReference: import__723.HeightReference.CLAMP_TO_GROUND, scene: scene2 }, scene2 ); expect(scene2.updateHeight).toHaveBeenCalledWith( import__723.Ellipsoid.WGS84.cartesianToCartographic(position), jasmine.any(Function), import__723.HeightReference.CLAMP_TO_GROUND ); position = import__723.Cartesian3.fromDegrees(-73, 40); modelMatrix2[12] = position.x; modelMatrix2[13] = position.y; modelMatrix2[14] = position.z; model.modelMatrix = modelMatrix2; scene2.renderForSpecs(); expect(removeCallback).toHaveBeenCalled(); expect(scene2.updateHeight).toHaveBeenCalledWith( import__723.Ellipsoid.WGS84.cartesianToCartographic(position), jasmine.any(Function), import__723.HeightReference.CLAMP_TO_GROUND ); }); it("height reference callback updates the position", async function() { let invokeCallback; spyOn(scene2, "updateHeight").and.callFake( (cartographic2, updateCallback) => { invokeCallback = (height) => { cartographic2.height = height; updateCallback(cartographic2); }; } ); const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame( import__723.Cartesian3.fromDegrees(-72, 40) ), heightReference: import__723.HeightReference.CLAMP_TO_GROUND, scene: scene2 }, scene2 ); invokeCallback(100); const matrix = model._clampedModelMatrix; const position = new import__723.Cartesian3(matrix[12], matrix[13], matrix[14]); const cartographic = import__723.Ellipsoid.WGS84.cartesianToCartographic(position); expect(cartographic.height).toEqualEpsilon(100, import__723.Math.EPSILON9); }); it("height reference accounts for change in terrain provider", async function() { const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame( import__723.Cartesian3.fromDegrees(-72, 40) ), heightReference: import__723.HeightReference.CLAMP_TO_GROUND, scene: scene2 }, scene2 ); expect(model._heightDirty).toBe(false); const terrainProvider = new import__723.CesiumTerrainProvider({ url: "made/up/url", requestVertexNormals: true }); scene2.terrainProvider = terrainProvider; expect(model._heightDirty).toBe(true); scene2.terrainProvider = void 0; }); it("throws when initializing height reference with no scene", async function() { await expectAsync( loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame( import__723.Cartesian3.fromDegrees(-72, 40) ), heightReference: import__723.HeightReference.CLAMP_TO_GROUND, scene: void 0 }, scene2 ) ).toBeRejectedWithDeveloperError( "Height reference is not supported without a scene." ); }); it("throws when changing height reference with no scene", async function() { const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame( import__723.Cartesian3.fromDegrees(-72, 40) ), heightReference: import__723.HeightReference.NONE }, scene2 ); expect(function() { model.heightReference = import__723.HeightReference.CLAMP_TO_GROUND; scene2.renderForSpecs(); }).toThrowDeveloperError(); }); it("works when initializing height reference with no globe", function() { return expectAsync( loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame( import__723.Cartesian3.fromDegrees(-72, 40) ), heightReference: import__723.HeightReference.CLAMP_TO_GROUND, scene: scene2 }, scene2 ) ).toBeResolved(); }); it("destroys height reference callback", async function() { const removeCallback = jasmine.createSpy(); spyOn(scene2, "updateHeight").and.returnValue(removeCallback); const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame( import__723.Cartesian3.fromDegrees(-72, 40) ), heightReference: import__723.HeightReference.CLAMP_TO_GROUND, scene: scene2 }, scene2 ); scene2.primitives.remove(model); expect(model.isDestroyed()).toBe(true); expect(removeCallback).toHaveBeenCalled(); }); }); describe("distance display condition", function() { it("initializes with distance display condition", function() { const near = 10; const far = 100; const condition = new import__723.DistanceDisplayCondition(near, far); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, distanceDisplayCondition: condition }, scene2 ).then(function(model) { verifyRender(model, false); }); }); it("changing distance display condition works", function() { const near = 10; const far = 100; const condition = new import__723.DistanceDisplayCondition(near, far); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl }, scene2 ).then(function(model) { verifyRender(model, true); model.distanceDisplayCondition = condition; verifyRender(model, false); model.distanceDisplayCondition = void 0; verifyRender(model, true); }); }); it("distanceDisplayCondition works with camera movement", function() { const near = 10; const far = 100; const condition = new import__723.DistanceDisplayCondition(near, far); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl }, scene2 ).then(function(model) { verifyRender(model, true); model.distanceDisplayCondition = condition; verifyRender(model, false); const frameState2 = scene2.frameState; frameState2.camera.lookAt( import__723.Cartesian3.ZERO, new import__723.HeadingPitchRange(0, 0, (far + near) * 0.5) ); verifyRender(model, true, { zoomToModel: false }); frameState2.camera.lookAt( import__723.Cartesian3.ZERO, new import__723.HeadingPitchRange(0, 0, far + 10) ); verifyRender(model, false, { zoomToModel: false }); }); }); it("distanceDisplayCondition throws when near >= far", function() { const near = 101; const far = 100; const condition = new import__723.DistanceDisplayCondition(near, far); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl }, scene2 ).then(function(model) { expect(function() { model.distanceDisplayCondition = condition; }).toThrowDeveloperError(); }); }); }); describe("model color", function() { it("initializes with model color", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, color: import__723.Color.BLACK }, scene2 ).then(function(model) { verifyRender(model, false); }); }); it("changing model color works", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl }, scene2 ).then(function(model) { verifyRender(model, true); model.color = import__723.Color.BLACK; verifyRender(model, false); model.color = import__723.Color.RED; verifyRender(model, true); model.color = void 0; verifyRender(model, true); }); }); it("renders with translucent color", function() { const offset = new import__723.HeadingPitchRange(0, -import__723.Math.PI_OVER_FOUR, 2); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, offset }, scene2 ).then(function(model) { const renderOptions = { scene: scene2, time: defaultDate }; let result; expect(renderOptions).toRenderAndCall(function(rgba) { result = rgba; }); model.color = import__723.Color.fromAlpha(import__723.Color.WHITE, 0.5); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toBeLessThan(result[0]); expect(rgba[1]).toBeLessThan(result[1]); expect(rgba[2]).toBeLessThan(result[2]); expect(rgba[3]).toBe(255); }); }); }); it("doesn't render invisible model", function() { const offset = new import__723.HeadingPitchRange(0, -import__723.Math.PI_OVER_FOUR, 2); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, color: import__723.Color.fromAlpha(import__723.Color.BLACK, 0), offset }, scene2 ).then(function(model) { verifyRender(model, false); const commands = scene2.frameState.commandList; expect(commands.length).toBe(0); }); }); }); function verifyHighlightColor(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[0]).toBeLessThan(255); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); } function verifyReplaceColor(rgba) { expect(rgba[0]).toEqual(255); expect(rgba[1]).toEqual(0); expect(rgba[2]).toEqual(0); expect(rgba[3]).toEqual(255); } function verifyMixColor(rgba) { expect(rgba[0]).toBeGreaterThan(0); expect(rgba[0]).toBeLessThan(255); expect(rgba[1]).toBeGreaterThan(0); expect(rgba[1]).toBeLessThan(255); expect(rgba[2]).toBeGreaterThan(0); expect(rgba[2]).toBeLessThan(255); expect(rgba[3]).toEqual(255); } describe("colorBlendMode", function() { const offset = new import__723.HeadingPitchRange(0, -import__723.Math.PI_OVER_FOUR, 2); it("initializes with ColorBlendMode.HIGHLIGHT", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, offset, color: import__723.Color.RED, colorBlendMode: import__723.ColorBlendMode.HIGHLIGHT }, scene2 ).then(function(model) { expect(model.colorBlendMode).toEqual(import__723.ColorBlendMode.HIGHLIGHT); const renderOptions = { scene: scene2, time: defaultDate }; expect(renderOptions).toRenderAndCall(function(rgba) { verifyHighlightColor(rgba); }); }); }); it("initializes with ColorBlendMode.REPLACE", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, offset, color: import__723.Color.RED, colorBlendMode: import__723.ColorBlendMode.REPLACE }, scene2 ).then(function(model) { expect(model.colorBlendMode).toEqual(import__723.ColorBlendMode.REPLACE); const renderOptions = { scene: scene2, time: defaultDate }; expect(renderOptions).toRenderAndCall(function(rgba) { verifyReplaceColor(rgba); }); }); }); it("initializes with ColorBlendMode.MIX", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, offset, color: import__723.Color.RED, colorBlendMode: import__723.ColorBlendMode.MIX }, scene2 ).then(function(model) { expect(model.colorBlendMode).toEqual(import__723.ColorBlendMode.MIX); const renderOptions = { scene: scene2, time: defaultDate }; expect(renderOptions).toRenderAndCall(function(rgba) { verifyMixColor(rgba); }); }); }); it("toggles colorBlendMode", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, offset, color: import__723.Color.RED, colorBlendMode: import__723.ColorBlendMode.REPLACE }, scene2 ).then(function(model) { expect(model.colorBlendMode).toEqual(import__723.ColorBlendMode.REPLACE); const renderOptions = { scene: scene2, time: defaultDate }; expect(renderOptions).toRenderAndCall(function(rgba) { verifyReplaceColor(rgba); }); model.colorBlendMode = import__723.ColorBlendMode.HIGHLIGHT; expect(model.colorBlendMode).toEqual(import__723.ColorBlendMode.HIGHLIGHT); expect(renderOptions).toRenderAndCall(function(rgba) { verifyHighlightColor(rgba); }); model.colorBlendMode = import__723.ColorBlendMode.MIX; expect(model.colorBlendMode).toEqual(import__723.ColorBlendMode.MIX); expect(renderOptions).toRenderAndCall(function(rgba) { verifyMixColor(rgba); }); }); }); }); describe("colorBlendAmount", function() { const offset = new import__723.HeadingPitchRange(0, -import__723.Math.PI_OVER_FOUR, 2); it("initializes with colorBlendAmount", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, offset, color: import__723.Color.RED, colorBlendMode: import__723.ColorBlendMode.MIX, colorBlendAmount: 1 }, scene2 ).then(function(model) { expect(model.colorBlendAmount).toEqual(1); const renderOptions = { scene: scene2, time: defaultDate }; expect(renderOptions).toRenderAndCall(function(rgba) { verifyReplaceColor(rgba); }); }); }); it("changing colorBlendAmount works", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, offset }, scene2 ).then(function(model) { const renderOptions = { scene: scene2, time: defaultDate }; let originalColor; expect(renderOptions).toRenderAndCall(function(rgba) { originalColor = rgba; }); model.color = import__723.Color.RED; model.colorBlendMode = import__723.ColorBlendMode.MIX; model.colorBlendAmount = 1; expect(model.colorBlendAmount).toEqual(1); expect(renderOptions).toRenderAndCall(function(rgba) { verifyReplaceColor(rgba); }); model.colorBlendAmount = 0.5; expect(model.colorBlendAmount).toEqual(0.5); expect(renderOptions).toRenderAndCall(function(rgba) { verifyMixColor(rgba); }); model.colorBlendAmount = 0; expect(model.colorBlendAmount).toEqual(0); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba[0]).toEqual(originalColor[0]); expect(rgba[1]).toEqual(originalColor[1]); expect(rgba[2]).toEqual(originalColor[2]); expect(rgba[3]).toEqual(originalColor[3]); }); }); }); }); describe("silhouette", function() { it("initializes with silhouette size", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, silhouetteSize: 1 }, scene2 ).then(function(model) { const commands = scene2.frameState.commandList; scene2.renderForSpecs(); expect(commands.length).toBe(2); expect(commands[0].renderState.stencilTest.enabled).toBe(true); expect(commands[0].pass).toBe(import__723.Pass.OPAQUE); expect(commands[1].renderState.stencilTest.enabled).toBe(true); expect(commands[1].pass).toBe(import__723.Pass.OPAQUE); }); }); it("changing silhouette size works", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl }, scene2 ).then(function(model) { const commands = scene2.frameState.commandList; scene2.renderForSpecs(); expect(commands.length).toBe(1); expect(commands[0].renderState.stencilTest.enabled).toBe(false); expect(commands[0].pass).toBe(import__723.Pass.OPAQUE); model.silhouetteSize = 1; scene2.renderForSpecs(); expect(commands.length).toBe(2); expect(commands[0].renderState.stencilTest.enabled).toBe(true); expect(commands[0].pass).toBe(import__723.Pass.OPAQUE); expect(commands[1].renderState.stencilTest.enabled).toBe(true); expect(commands[1].pass).toBe(import__723.Pass.OPAQUE); model.silhouetteSize = 0; scene2.renderForSpecs(); expect(commands.length).toBe(1); expect(commands[0].renderState.stencilTest.enabled).toBe(false); expect(commands[0].pass).toBe(import__723.Pass.OPAQUE); }); }); it("silhouette works with translucent color", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, silhouetteSize: 1, silhouetteColor: import__723.Color.fromAlpha(import__723.Color.GREEN, 0.5) }, scene2 ).then(function(model) { const commands = scene2.frameState.commandList; scene2.renderForSpecs(); expect(commands.length).toBe(2); expect(commands[0].renderState.stencilTest.enabled).toBe(true); expect(commands[0].pass).toBe(import__723.Pass.OPAQUE); expect(commands[1].renderState.stencilTest.enabled).toBe(true); expect(commands[1].pass).toBe(import__723.Pass.TRANSLUCENT); }); }); it("silhouette is disabled by invisible color", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, silhouetteSize: 1 }, scene2 ).then(function(model) { const commands = scene2.frameState.commandList; scene2.renderForSpecs(); expect(commands.length).toBe(2); expect(commands[0].renderState.stencilTest.enabled).toBe(true); expect(commands[0].pass).toBe(import__723.Pass.OPAQUE); expect(commands[1].renderState.stencilTest.enabled).toBe(true); expect(commands[1].pass).toBe(import__723.Pass.OPAQUE); model.silhouetteColor = import__723.Color.fromAlpha(import__723.Color.GREEN, 0); scene2.renderForSpecs(); expect(commands.length).toBe(1); expect(commands[0].renderState.stencilTest.enabled).toBe(false); expect(commands[0].pass).toBe(import__723.Pass.OPAQUE); }); }); it("silhouette works for invisible model", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, silhouetteSize: 1, color: import__723.Color.fromAlpha(import__723.Color.WHITE, 0) }, scene2 ).then(function(model) { const commands = scene2.frameState.commandList; scene2.renderForSpecs(); expect(commands.length).toBe(2); expect(commands[0].renderState.colorMask).toEqual({ red: false, green: false, blue: false, alpha: false }); expect(commands[0].renderState.depthMask).toEqual(false); expect(commands[0].renderState.stencilTest.enabled).toBe(true); expect(commands[0].pass).toBe(import__723.Pass.TRANSLUCENT); expect(commands[1].renderState.stencilTest.enabled).toBe(true); expect(commands[1].pass).toBe(import__723.Pass.TRANSLUCENT); }); }); it("silhouette works for translucent model", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, silhouetteSize: 1, color: import__723.Color.fromAlpha(import__723.Color.WHITE, 0.5) }, scene2 ).then(function(model) { const commands = scene2.frameState.commandList; scene2.renderForSpecs(); expect(commands.length).toBe(2); expect(commands[0].renderState.stencilTest.enabled).toBe(true); expect(commands[0].pass).toBe(import__723.Pass.TRANSLUCENT); expect(commands[1].renderState.stencilTest.enabled).toBe(true); expect(commands[1].pass).toBe(import__723.Pass.TRANSLUCENT); }); }); it("silhouette works for translucent model and translucent silhouette color", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, silhouetteSize: 1, color: import__723.Color.fromAlpha(import__723.Color.WHITE, 0.5), silhouetteColor: import__723.Color.fromAlpha(import__723.Color.RED, 0.5) }, scene2 ).then(function(model) { const commands = scene2.frameState.commandList; scene2.renderForSpecs(); expect(commands.length).toBe(2); expect(commands[0].renderState.stencilTest.enabled).toBe(true); expect(commands[0].pass).toBe(import__723.Pass.TRANSLUCENT); expect(commands[1].renderState.stencilTest.enabled).toBe(true); expect(commands[1].pass).toBe(import__723.Pass.TRANSLUCENT); }); }); it("silhouette works for multiple models", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, silhouetteSize: 1 }, scene2 ).then(function(model) { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, silhouetteSize: 1 }, scene2 ).then(function(model2) { const commands = scene2.frameState.commandList; scene2.renderForSpecs(); const length2 = commands.length; expect(length2).toBe(4); for (let i = 0; i < length2; i++) { const command = commands[i]; expect(command.renderState.stencilTest.enabled).toBe(true); expect(command.pass).toBe(import__723.Pass.OPAQUE); } const reference1 = commands[0].renderState.stencilTest.reference; const reference2 = commands[2].renderState.stencilTest.reference; expect(reference2).toEqual(reference1 + 1); }); }); }); }); describe("light color", function() { it("initializes with light color", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, lightColor: import__723.Cartesian3.ZERO }, scene2 ).then(function(model) { verifyRender(model, false); }); }); it("changing light color works", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl }, scene2 ).then(function(model) { model.lightColor = import__723.Cartesian3.ZERO; verifyRender(model, false); model.lightColor = new import__723.Cartesian3(1, 0, 0); verifyRender(model, true); model.lightColor = void 0; verifyRender(model, true); }); }); it("light color doesn't affect unlit models", function() { return loadAndZoomToModelAsync_default({ gltf: boxUnlitUrl }, scene2).then( function(model) { const options = { zoomToModel: false }; scene2.camera.moveRight(1); verifyRender(model, true, options); model.lightColor = import__723.Cartesian3.ZERO; verifyRender(model, true, options); } ); }); }); describe("imageBasedLighting", function() { afterEach(function() { scene2.highDynamicRange = false; }); it("initializes with imageBasedLighting", function() { const ibl = new import__723.ImageBasedLighting({ imageBasedLightingFactor: import__723.Cartesian2.ZERO, luminanceAtZenith: 0.5 }); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, imageBasedLighting: ibl }, scene2 ).then(function(model) { expect(model.imageBasedLighting).toBe(ibl); }); }); it("creates default imageBasedLighting", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl }, scene2 ).then(function(model) { const imageBasedLighting = model.imageBasedLighting; expect(imageBasedLighting).toBeDefined(); expect( import__723.Cartesian2.equals( imageBasedLighting.imageBasedLightingFactor, new import__723.Cartesian2(1, 1) ) ).toBe(true); expect(imageBasedLighting.luminanceAtZenith).toBe(0.2); expect( imageBasedLighting.sphericalHarmonicCoefficients ).toBeUndefined(); expect(imageBasedLighting.specularEnvironmentMaps).toBeUndefined(); }); }); it("changing imageBasedLighting works", function() { const imageBasedLighting = new import__723.ImageBasedLighting({ imageBasedLightingFactor: import__723.Cartesian2.ZERO }); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl }, scene2 ).then(function(model) { const renderOptions = { scene: scene2, time: defaultDate }; let result; verifyRender(model, true); expect(renderOptions).toRenderAndCall(function(rgba) { result = rgba; }); model.imageBasedLighting = imageBasedLighting; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual(result); }); }); }); it("changing imageBasedLightingFactor works", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, imageBasedLighting: new import__723.ImageBasedLighting({ imageBasedLightingFactor: import__723.Cartesian2.ZERO }) }, scene2 ).then(function(model) { const renderOptions = { scene: scene2, time: defaultDate }; let result; verifyRender(model, true); expect(renderOptions).toRenderAndCall(function(rgba) { result = rgba; }); const ibl = model.imageBasedLighting; ibl.imageBasedLightingFactor = new import__723.Cartesian2(1, 1); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual(result); }); }); }); it("changing luminanceAtZenith works", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, imageBasedLighting: new import__723.ImageBasedLighting({ luminanceAtZenith: 0 }) }, scene2 ).then(function(model) { const renderOptions = { scene: scene2, time: defaultDate }; let result; verifyRender(model, true); expect(renderOptions).toRenderAndCall(function(rgba) { result = rgba; }); const ibl = model.imageBasedLighting; ibl.luminanceAtZenith = 0.2; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual(result); }); }); }); it("changing sphericalHarmonicCoefficients works", function() { if (!scene2.highDynamicRangeSupported) { return; } const L00 = new import__723.Cartesian3( 0.692622075009195, 0.4543516001819, 0.36910172299235 ); const L1_1 = new import__723.Cartesian3( 0.289407068366422, 0.16789310162658, 0.106174907004792 ); const L10 = new import__723.Cartesian3( -0.591502034778913, -0.28152432317119, 0.124647554708491 ); const L11 = new import__723.Cartesian3( 0.34945458117126, 0.163273486841657, -0.03095643545207 ); const L2_2 = new import__723.Cartesian3( 0.22171176447426, 0.11771991868122, 0.031381053430064 ); const L2_1 = new import__723.Cartesian3( -0.348955284677868, -0.187256994042823, -0.026299717727617 ); const L20 = new import__723.Cartesian3( 0.119982671127227, 0.076784552175028, 0.055517838847755 ); const L21 = new import__723.Cartesian3( -0.545546043202299, -0.279787444030397, -0.086854000285261 ); const L22 = new import__723.Cartesian3( 0.160417569726332, 0.120896423762313, 0.121102528320197 ); const coefficients = [L00, L1_1, L10, L11, L2_2, L2_1, L20, L21, L22]; return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, imageBasedLighting: new import__723.ImageBasedLighting({ sphericalHarmonicCoefficients: coefficients }) }, scene2 ).then(function(model) { scene2.highDynamicRange = true; const renderOptions = { scene: scene2, time: defaultDate }; let result; verifyRender(model, true); expect(renderOptions).toRenderAndCall(function(rgba) { result = rgba; }); const ibl = model.imageBasedLighting; ibl.sphericalHarmonicCoefficients = void 0; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual(result); }); }); }); it("changing specularEnvironmentMaps works", function() { if (!scene2.highDynamicRangeSupported) { return; } const url = "./Data/EnvironmentMap/kiara_6_afternoon_2k_ibl.ktx2"; return loadAndZoomToModelAsync_default( { gltf: boomBoxUrl, scale: 10, imageBasedLighting: new import__723.ImageBasedLighting({ specularEnvironmentMaps: url }) }, scene2 ).then(function(model) { const ibl = model.imageBasedLighting; return pollToPromise_default(function() { scene2.render(); return (0, import__723.defined)(ibl.specularEnvironmentMapAtlas) && ibl.specularEnvironmentMapAtlas.ready; }).then(function() { scene2.highDynamicRange = true; const renderOptions = { scene: scene2, time: defaultDate }; let result; verifyRender(model, true); expect(renderOptions).toRenderAndCall(function(rgba) { result = rgba; }); ibl.specularEnvironmentMaps = void 0; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual(result); }); }); }); }); it("renders when specularEnvironmentMaps aren't supported", function() { spyOn(import__723.OctahedralProjectedCubeMap, "isSupported").and.returnValue(false); return loadAndZoomToModelAsync_default( { gltf: boomBoxUrl, scale: 10 }, scene2 ).then(function(model) { expect(scene2.specularEnvironmentMapsSupported).toBe(false); verifyRender(model, true); }); }); }); describe("scale", function() { it("initializes with scale", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, upAxis: import__723.Axis.Z, forwardAxis: import__723.Axis.X, scale: 0 }, scene2 ).then(function(model) { scene2.renderForSpecs(); verifyRender(model, false); expect(model.boundingSphere.center).toEqual(import__723.Cartesian3.ZERO); expect(model.boundingSphere.radius).toEqual(0); }); }); it("changing scale works", function() { const updateModelMatrix = spyOn( import__723.ModelSceneGraph.prototype, "updateModelMatrix" ).and.callThrough(); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, upAxis: import__723.Axis.Z, forwardAxis: import__723.Axis.X }, scene2 ).then(function(model) { verifyRender(model, true); model.scale = 0; scene2.renderForSpecs(); expect(updateModelMatrix).toHaveBeenCalled(); verifyRender(model, false); model.scale = 1; scene2.renderForSpecs(); expect(updateModelMatrix).toHaveBeenCalled(); verifyRender(model, true); }); }); it("changing scale affects bounding sphere", function() { const resource = import__723.Resource.createIfNeeded(boxTexturedGlbUrl); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { return loadAndZoomToModelAsync_default( { gltf: new Uint8Array(buffer), scale: 10 }, scene2 ).then(function(model) { scene2.renderForSpecs(); const expectedRadius = 0.866; const boundingSphere = model.boundingSphere; expect(boundingSphere.center).toEqual(import__723.Cartesian3.ZERO); expect(boundingSphere.radius).toEqualEpsilon( expectedRadius * 10, import__723.Math.EPSILON3 ); model.scale = 0; scene2.renderForSpecs(); expect(boundingSphere.center).toEqual(import__723.Cartesian3.ZERO); expect(boundingSphere.radius).toEqual(0); model.scale = 1; scene2.renderForSpecs(); expect(boundingSphere.center).toEqual(import__723.Cartesian3.ZERO); expect(boundingSphere.radius).toEqualEpsilon( expectedRadius, import__723.Math.EPSILON3 ); }); }); }); it("changing scale affects bounding sphere for uncentered models", function() { const resource = import__723.Resource.createIfNeeded(boxWithOffsetUrl); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { return loadAndZoomToModelAsync_default( { gltf: new Uint8Array(buffer), scale: 10 }, scene2 ).then(function(model) { const expectedRadius = 0.866; const expectedCenter = new import__723.Cartesian3(5, 0, 0); const expectedTranslation = import__723.Matrix4.fromTranslation(expectedCenter); const axisCorrectionMatrix = import__723.ModelUtility.getAxisCorrectionMatrix( import__723.Axis.Y, import__723.Axis.Z, new import__723.Matrix4() ); import__723.Matrix4.multiplyTransformation( axisCorrectionMatrix, expectedTranslation, expectedTranslation ); import__723.Matrix4.getTranslation(expectedTranslation, expectedCenter); const boundingSphere = model.boundingSphere; expect(boundingSphere.center).toEqual( import__723.Cartesian3.multiplyByScalar( expectedCenter, 10, new import__723.Cartesian3() ) ); expect(boundingSphere.radius).toEqualEpsilon( expectedRadius * 10, import__723.Math.EPSILON3 ); model.scale = 0; scene2.renderForSpecs(); expect(boundingSphere.center).toEqual(import__723.Cartesian3.ZERO); expect(boundingSphere.radius).toEqual(0); model.scale = 1; scene2.renderForSpecs(); expect(boundingSphere.center).toEqual(expectedCenter); expect(boundingSphere.radius).toEqualEpsilon( expectedRadius, import__723.Math.EPSILON3 ); }); }); }); }); describe("minimumPixelSize", function() { it("initializes with minimumPixelSize", function() { const resource = import__723.Resource.createIfNeeded(boxTexturedGlbUrl); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { return loadAndZoomToModelAsync_default( { gltf: new Uint8Array(buffer), upAxis: import__723.Axis.Z, forwardAxis: import__723.Axis.X, minimumPixelSize: 1, offset: new import__723.HeadingPitchRange(0, 0, 500) }, scene2 ).then(function(model) { const renderOptions = { zoomToModel: false }; const expectedRadius = 0.866; scene2.renderForSpecs(); verifyRender(model, true, renderOptions); expect(model.scale).toEqual(1); expect(model.boundingSphere.radius).toEqualEpsilon( expectedRadius, import__723.Math.EPSILON3 ); }); }); }); it("changing minimumPixelSize works", function() { const updateModelMatrix = spyOn( import__723.ModelSceneGraph.prototype, "updateModelMatrix" ).and.callThrough(); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, upAxis: import__723.Axis.Z, forwardAxis: import__723.Axis.X, minimumPixelSize: 1, offset: new import__723.HeadingPitchRange(0, 0, 500) }, scene2 ).then(function(model) { const renderOptions = { zoomToModel: false }; scene2.renderForSpecs(); expect(updateModelMatrix).toHaveBeenCalled(); verifyRender(model, true, renderOptions); model.minimumPixelSize = 0; scene2.renderForSpecs(); expect(updateModelMatrix).toHaveBeenCalled(); verifyRender(model, false, renderOptions); model.minimumPixelSize = 1; scene2.renderForSpecs(); expect(updateModelMatrix).toHaveBeenCalled(); verifyRender(model, true, renderOptions); }); }); it("changing minimumPixelSize doesn't affect bounding sphere or scale", function() { const updateModelMatrix = spyOn( import__723.ModelSceneGraph.prototype, "updateModelMatrix" ).and.callThrough(); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, upAxis: import__723.Axis.Z, forwardAxis: import__723.Axis.X, minimumPixelSize: 1, offset: new import__723.HeadingPitchRange(0, 0, 500) }, scene2 ).then(function(model) { const expectedRadius = 0.866; scene2.renderForSpecs(); expect(updateModelMatrix).toHaveBeenCalled(); expect(model.scale).toEqual(1); expect(model.boundingSphere.radius).toEqualEpsilon( expectedRadius, import__723.Math.EPSILON3 ); model.minimumPixelSize = 0; scene2.renderForSpecs(); expect(updateModelMatrix).toHaveBeenCalled(); expect(model.scale).toEqual(1); expect(model.boundingSphere.radius).toEqualEpsilon( expectedRadius, import__723.Math.EPSILON3 ); model.minimumPixelSize = 1; scene2.renderForSpecs(); expect(updateModelMatrix).toHaveBeenCalled(); expect(model.scale).toEqual(1); expect(model.boundingSphere.radius).toEqualEpsilon( expectedRadius, import__723.Math.EPSILON3 ); }); }); }); describe("maximumScale", function() { it("initializes with maximumScale", function() { const resource = import__723.Resource.createIfNeeded(boxTexturedGlbUrl); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { return loadAndZoomToModelAsync_default( { gltf: new Uint8Array(buffer), upAxis: import__723.Axis.Z, forwardAxis: import__723.Axis.X, maximumScale: 0 }, scene2 ).then(function(model) { scene2.renderForSpecs(); verifyRender(model, false); expect(model.boundingSphere.center).toEqual(import__723.Cartesian3.ZERO); expect(model.boundingSphere.radius).toEqual(0); }); }); }); it("changing maximumScale works", function() { const updateModelMatrix = spyOn( import__723.ModelSceneGraph.prototype, "updateModelMatrix" ).and.callThrough(); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, upAxis: import__723.Axis.Z, forwardAxis: import__723.Axis.X, scale: 2 }, scene2 ).then(function(model) { scene2.renderForSpecs(); verifyRender(model, true); model.maximumScale = 0; scene2.renderForSpecs(); expect(updateModelMatrix).toHaveBeenCalled(); verifyRender(model, false); model.maximumScale = 1; scene2.renderForSpecs(); expect(updateModelMatrix).toHaveBeenCalled(); verifyRender(model, true); }); }); it("changing maximumScale affects bounding sphere", function() { const resource = import__723.Resource.createIfNeeded(boxTexturedGlbUrl); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { return loadAndZoomToModelAsync_default( { gltf: new Uint8Array(buffer), scale: 20, maximumScale: 10 }, scene2 ).then(function(model) { scene2.renderForSpecs(); const expectedRadius = 0.866; const boundingSphere = model.boundingSphere; expect(boundingSphere.center).toEqual(import__723.Cartesian3.ZERO); expect(boundingSphere.radius).toEqualEpsilon( expectedRadius * 10, import__723.Math.EPSILON3 ); model.maximumScale = 0; scene2.renderForSpecs(); expect(boundingSphere.center).toEqual(import__723.Cartesian3.ZERO); expect(boundingSphere.radius).toEqual(0); model.maximumScale = 1; scene2.renderForSpecs(); expect(boundingSphere.center).toEqual(import__723.Cartesian3.ZERO); expect(boundingSphere.radius).toEqualEpsilon( expectedRadius, import__723.Math.EPSILON3 ); }); }); }); it("changing maximumScale affects minimumPixelSize", function() { const resource = import__723.Resource.createIfNeeded(boxTexturedGlbUrl); const loadPromise = resource.fetchArrayBuffer(); return loadPromise.then(function(buffer) { return loadAndZoomToModelAsync_default( { gltf: new Uint8Array(buffer), minimumPixelSize: 1, maximumScale: 10 }, scene2 ).then(function(model) { scene2.renderForSpecs(); const expectedRadius = 0.866; const boundingSphere = model.boundingSphere; expect(boundingSphere.center).toEqual(import__723.Cartesian3.ZERO); expect(boundingSphere.radius).toEqualEpsilon( expectedRadius, import__723.Math.EPSILON3 ); model.maximumScale = 0; scene2.renderForSpecs(); expect(boundingSphere.center).toEqual(import__723.Cartesian3.ZERO); expect(boundingSphere.radius).toEqual(0); model.maximumScale = 10; scene2.renderForSpecs(); expect(boundingSphere.center).toEqual(import__723.Cartesian3.ZERO); expect(boundingSphere.radius).toEqualEpsilon( expectedRadius, import__723.Math.EPSILON3 ); }); }); }); }); it("resets draw commands when vertical exaggeration changes", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl }, scene2 ).then(function(model) { const resetDrawCommands = spyOn( model, "resetDrawCommands" ).and.callThrough(); expect(model.ready).toBe(true); scene2.verticalExaggeration = 2; scene2.renderForSpecs(); expect(resetDrawCommands).toHaveBeenCalled(); scene2.verticalExaggeration = 1; }); }); it("does not issue draw commands when ignoreCommands is true", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl }, scene2 ).then(function(model) { expect(model.ready).toBe(true); model._ignoreCommands = true; scene2.renderForSpecs(); expect(scene2.frameState.commandList.length).toEqual(0); }); }); describe("frustum culling ", function() { it("enables frustum culling", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, cull: true }, scene2 ).then(function(model) { expect(model.cull).toEqual(true); scene2.renderForSpecs(); expect(scene2.frustumCommandsList.length).toBeGreaterThan(0); model.modelMatrix = import__723.Matrix4.fromTranslation( new import__723.Cartesian3(100, 0, 0) ); scene2.renderForSpecs(); expect(scene2.frustumCommandsList.length).toEqual(0); }); }); it("disables frustum culling", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, cull: false }, scene2 ).then(function(model) { expect(model.cull).toEqual(false); scene2.renderForSpecs(); const length2 = scene2.frustumCommandsList.length; expect(length2).toBeGreaterThan(0); model.modelMatrix = import__723.Matrix4.fromTranslation( new import__723.Cartesian3(0, 100, 0) ); scene2.renderForSpecs(); expect(scene2.frustumCommandsList.length).toEqual(length2); }); }); }); describe("back-face culling", function() { const boxBackFaceCullingUrl = "./Data/Models/glTF-2.0/BoxBackFaceCulling/glTF/BoxBackFaceCulling.gltf"; const boxBackFaceCullingOffset = new import__723.HeadingPitchRange( Math.PI / 2, 0, 2 ); it("enables back-face culling", function() { return loadAndZoomToModelAsync_default( { gltf: boxBackFaceCullingUrl, backFaceCulling: true, offset: boxBackFaceCullingOffset }, scene2 ).then(function(model) { verifyRender(model, false, { zoomToModel: false }); }); }); it("disables back-face culling", function() { return loadAndZoomToModelAsync_default( { gltf: boxBackFaceCullingUrl, backFaceCulling: false, offset: boxBackFaceCullingOffset }, scene2 ).then(function(model) { verifyRender(model, true, { zoomToModel: false }); }); }); it("ignores back-face culling when translucent", function() { return loadAndZoomToModelAsync_default( { gltf: boxBackFaceCullingUrl, backFaceCulling: true, offset: boxBackFaceCullingOffset }, scene2 ).then(function(model) { verifyRender(model, false, { zoomToModel: false }); model.color = new import__723.Color(0, 0, 1, 0.5); verifyRender(model, true, { zoomToModel: false }); }); }); it("toggles back-face culling at runtime", function() { return loadAndZoomToModelAsync_default( { gltf: boxBackFaceCullingUrl, backFaceCulling: false, offset: boxBackFaceCullingOffset }, scene2 ).then(function(model) { verifyRender(model, true, { zoomToModel: false }); model.backFaceCulling = true; verifyRender(model, false, { zoomToModel: false }); }); }); it("ignores back-face culling toggles when translucent", function() { return loadAndZoomToModelAsync_default( { gltf: boxBackFaceCullingUrl, backFaceCulling: false, offset: boxBackFaceCullingOffset, color: new import__723.Color(0, 0, 1, 0.5) }, scene2 ).then(function(model) { verifyRender(model, true, { zoomToModel: false }); model.backFaceCulling = true; verifyRender(model, true, { zoomToModel: false }); model.backFaceCulling = false; verifyRender(model, true, { zoomToModel: false }); }); }); }); it("reverses winding order for negatively scaled models", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, modelMatrix: import__723.Matrix4.fromUniformScale(-1) }, scene2 ).then(function(model) { const renderOptions = { scene: scene2, time: defaultDate }; let initialRgba; expect(renderOptions).toRenderAndCall(function(rgba) { initialRgba = rgba; }); model.modelMatrix = import__723.Matrix4.IDENTITY; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).toEqual(initialRgba); }); model.modelMatrix = import__723.Matrix4.fromUniformScale(-1); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).toEqual(initialRgba); }); }); }); describe("clipping planes", function() { it("throws when given clipping planes attached to another model", function() { const plane = new import__723.ClippingPlane(import__723.Cartesian3.UNIT_X, 0); const clippingPlanes = new import__723.ClippingPlaneCollection({ planes: [plane] }); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, clippingPlanes }, scene2 ).then(function(model) { return loadAndZoomToModelAsync_default({ gltf: boxTexturedGlbUrl }, scene2); }).then(function(model2) { expect(function() { model2.clippingPlanes = clippingPlanes; }).toThrowDeveloperError(); }); }); it("updates clipping planes when clipping planes are enabled", function() { const plane = new import__723.ClippingPlane(import__723.Cartesian3.UNIT_X, 0); const clippingPlanes = new import__723.ClippingPlaneCollection({ planes: [plane] }); return loadAndZoomToModelAsync_default({ gltf: boxTexturedGlbUrl }, scene2).then( function(model) { const gl = scene2.frameState.context._gl; spyOn(gl, "texImage2D").and.callThrough(); scene2.renderForSpecs(); const callsBeforeClipping = gl.texImage2D.calls.count(); model.clippingPlanes = clippingPlanes; scene2.renderForSpecs(); scene2.renderForSpecs(); expect(gl.texImage2D.calls.count() - callsBeforeClipping).toEqual( 2 ); } ); }); it("initializes and updates with clipping planes", function() { const plane = new import__723.ClippingPlane(import__723.Cartesian3.UNIT_X, -2.5); const clippingPlanes = new import__723.ClippingPlaneCollection({ planes: [plane] }); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, clippingPlanes }, scene2 ).then(function(model) { verifyRender(model, false); model.clippingPlanes = void 0; verifyRender(model, true); }); }); it("updating clipping planes properties works", function() { const direction = import__723.Cartesian3.multiplyByScalar( import__723.Cartesian3.UNIT_X, -1, new import__723.Cartesian3() ); const plane = new import__723.ClippingPlane(direction, 0); const clippingPlanes = new import__723.ClippingPlaneCollection({ planes: [plane] }); return loadAndZoomToModelAsync_default({ gltf: boxTexturedGlbUrl }, scene2).then( function(model) { let modelColor; verifyRender(model, true); expect(scene2).toRenderAndCall(function(rgba) { modelColor = rgba; }); model.clippingPlanes = clippingPlanes; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual(modelColor); }); plane.distance = 10; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).toEqual(modelColor); }); } ); }); it("removing clipping plane from collection works", function() { const plane = new import__723.ClippingPlane(import__723.Cartesian3.UNIT_X, -2.5); const clippingPlanes = new import__723.ClippingPlaneCollection({ planes: [plane] }); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, clippingPlanes }, scene2 ).then(function(model) { verifyRender(model, false); clippingPlanes.removeAll(); verifyRender(model, true); }); }); it("removing clipping planes collection works", function() { const plane = new import__723.ClippingPlane(import__723.Cartesian3.UNIT_X, -2.5); const clippingPlanes = new import__723.ClippingPlaneCollection({ planes: [plane] }); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, clippingPlanes }, scene2 ).then(function(model) { verifyRender(model, false); model.clippingPlanes = void 0; verifyRender(model, true); }); }); it("replacing clipping planes with another collection works", function() { const modelClippedPlane = new import__723.ClippingPlane(import__723.Cartesian3.UNIT_X, -2.5); const modelVisiblePlane = new import__723.ClippingPlane(import__723.Cartesian3.UNIT_X, 2.5); const clippingPlanes = new import__723.ClippingPlaneCollection({ planes: [modelClippedPlane] }); return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl, clippingPlanes }, scene2 ).then(function(model) { verifyRender(model, false); model.clippingPlanes = new import__723.ClippingPlaneCollection({ planes: [modelVisiblePlane] }); verifyRender(model, true); model.clippingPlanes = new import__723.ClippingPlaneCollection({ planes: [modelClippedPlane] }); verifyRender(model, false); }); }); it("clipping planes apply edge styling", function() { const plane = new import__723.ClippingPlane(import__723.Cartesian3.UNIT_X, 0); const clippingPlanes = new import__723.ClippingPlaneCollection({ planes: [plane], edgeWidth: 25, // make large enough to show up on the render edgeColor: import__723.Color.BLUE }); return loadAndZoomToModelAsync_default({ gltf: boxTexturedGlbUrl }, scene2).then( function(model) { let modelColor; verifyRender(model, true); expect(scene2).toRenderAndCall(function(rgba) { modelColor = rgba; }); model.clippingPlanes = clippingPlanes; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).toEqual([0, 0, 255, 255]); }); clippingPlanes.edgeWidth = 0; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).toEqual(modelColor); }); } ); }); it("clipping planes union regions", function() { const clippingPlanes = new import__723.ClippingPlaneCollection({ planes: [ new import__723.ClippingPlane(import__723.Cartesian3.UNIT_Z, 5), new import__723.ClippingPlane(import__723.Cartesian3.UNIT_X, -2) ], unionClippingRegions: true }); return loadAndZoomToModelAsync_default({ gltf: boxTexturedGlbUrl }, scene2).then( function(model) { verifyRender(model, true); model.clippingPlanes = clippingPlanes; verifyRender(model, false); model.clippingPlanes.unionClippingRegions = false; verifyRender(model, true); } ); }); it("destroys attached ClippingPlaneCollections", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl }, scene2 ).then(function(model) { const clippingPlanes = new import__723.ClippingPlaneCollection({ planes: [new import__723.ClippingPlane(import__723.Cartesian3.UNIT_X, 0)] }); model.clippingPlanes = clippingPlanes; expect(model.isDestroyed()).toEqual(false); expect(clippingPlanes.isDestroyed()).toEqual(false); scene2.primitives.remove(model); expect(model.isDestroyed()).toEqual(true); expect(clippingPlanes.isDestroyed()).toEqual(true); }); }); it("destroys ClippingPlaneCollections that are detached", function() { let clippingPlanes; return loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl }, scene2 ).then(function(model) { clippingPlanes = new import__723.ClippingPlaneCollection({ planes: [new import__723.ClippingPlane(import__723.Cartesian3.UNIT_X, 0)] }); model.clippingPlanes = clippingPlanes; expect(clippingPlanes.isDestroyed()).toBe(false); model.clippingPlanes = void 0; expect(clippingPlanes.isDestroyed()).toBe(true); }); }); }); describe("clipping polygons", () => { let polygon; beforeEach(() => { const positions = import__723.Cartesian3.fromRadiansArray([ -import__723.Math.PI_OVER_TWO, -import__723.Math.PI_OVER_TWO, import__723.Math.PI_OVER_TWO, -import__723.Math.PI_OVER_TWO, import__723.Math.PI_OVER_TWO, import__723.Math.PI_OVER_TWO, -import__723.Math.PI_OVER_TWO, import__723.Math.PI_OVER_TWO ]); polygon = new import__723.ClippingPolygon({ positions }); }); it("throws when given clipping planes attached to another model", async function() { if (!scene2.context.webgl2) { return; } const collection = new import__723.ClippingPolygonCollection({ polygons: [polygon] }); const modelA = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl }, scene2 ); modelA.clippingPolygons = collection; const modelB = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl }, scene2 ); expect(function() { modelB.clippingPolygons = collection; }).toThrowDeveloperError(); }); it("selectively hides model regions", async function() { if (!scene2.context.webgl2) { return; } const collection = new import__723.ClippingPolygonCollection({ polygons: [polygon] }); const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl }, scene2 ); model.clippingPolygons = collection; verifyRender(model, false); model.clippingPolygons = void 0; verifyRender(model, true); }); it("inverse works", async function() { if (!scene2.context.webgl2) { return; } const collection = new import__723.ClippingPolygonCollection({ polygons: [polygon] }); const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl }, scene2 ); let modelColor; verifyRender(model, true); expect(scene2).toRenderAndCall(function(rgba) { modelColor = rgba; }); model.clippingPolygons = collection; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual(modelColor); }); model.clippingPolygons.inverse = true; expect(scene2).toRenderAndCall(function(rgba) { expect(rgba).toEqual(modelColor); }); }); it("adding polygon to collection works", async function() { if (!scene2.context.webgl2) { return; } const collection = new import__723.ClippingPolygonCollection(); const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl }, scene2 ); model.clippingPolygons = collection; verifyRender(model, true); collection.add(polygon); verifyRender(model, false); }); it("removing polygon from collection works", async function() { if (!scene2.context.webgl2) { return; } const collection = new import__723.ClippingPolygonCollection({ polygons: [polygon] }); const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl }, scene2 ); model.clippingPolygons = collection; verifyRender(model, false); model.clippingPolygons.remove(polygon); verifyRender(model, true); }); it("destroys attached ClippingPolygonCollections", async function() { const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl }, scene2 ); const collection = new import__723.ClippingPolygonCollection({ polygons: [polygon] }); model.clippingPolygons = collection; expect(model.isDestroyed()).toEqual(false); expect(collection.isDestroyed()).toEqual(false); scene2.primitives.remove(model); expect(model.isDestroyed()).toEqual(true); expect(collection.isDestroyed()).toEqual(true); }); it("destroys ClippingPolygonCollections that are detached", async function() { const model = await loadAndZoomToModelAsync_default( { gltf: boxTexturedGlbUrl }, scene2 ); const collection = new import__723.ClippingPolygonCollection({ polygons: [polygon] }); model.clippingPolygons = collection; expect(collection.isDestroyed()).toBe(false); model.clippingPolygons = void 0; expect(collection.isDestroyed()).toBe(true); }); }); it("renders with classificationType", function() { return loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl, classificationType: import__723.ClassificationType.CESIUM_3D_TILE }, scene2 ).then(function(model) { expect(model.classificationType).toBe( import__723.ClassificationType.CESIUM_3D_TILE ); verifyRender(model, false); }); }); describe("statistics", function() { it("gets triangle count", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl }, scene2 ).then(function(model) { const statistics = model.statistics; expect(statistics.trianglesLength).toEqual(12); }); }); it("gets point count", function() { return loadAndZoomToModelAsync_default({ gltf: pointCloudUrl }, scene2).then( function(model) { const statistics = model.statistics; expect(statistics.pointsLength).toEqual(2500); } ); }); it("gets memory usage for geometry and textures", function() { return loadAndZoomToModelAsync_default( { gltf: boxTexturedGltfUrl, incrementallyLoadTextures: false }, scene2 ).then(function(model) { const expectedGeometryMemory = 840; const expectedTextureMemory = Math.floor(256 * 256 * 4 * (4 / 3)); const statistics = model.statistics; expect(statistics.geometryByteLength).toEqual(expectedGeometryMemory); expect(statistics.texturesByteLength).toEqual(expectedTextureMemory); }); }); it("gets memory usage for property tables", function() { return loadAndZoomToModelAsync_default({ gltf: buildingsMetadata }, scene2).then( function(model) { const expectedPropertyTableMemory = 110; const statistics = model.statistics; expect(statistics.propertyTablesByteLength).toEqual( expectedPropertyTableMemory ); } ); }); }); describe("AGI_articulations", function() { it("setArticulationStage throws when model is not ready", async function() { const model = await import__723.Model.fromGltfAsync({ url: boxArticulationsUrl }); expect(function() { model.setArticulationStage("SampleArticulation MoveX", 10); }).toThrowDeveloperError(); }); it("setArticulationStage throws with invalid value", function() { return loadAndZoomToModelAsync_default( { gltf: boxArticulationsUrl }, scene2 ).then(function(model) { expect(function() { model.setArticulationStage("SampleArticulation MoveX", "bad"); }).toThrowDeveloperError(); }); }); it("applyArticulations throws when model is not ready", async function() { const model = await import__723.Model.fromGltfAsync({ url: boxArticulationsUrl }); expect(function() { model.applyArticulations(); }).toThrowDeveloperError(); }); it("applies articulations", function() { return loadAndZoomToModelAsync_default( { gltf: boxArticulationsUrl }, scene2 ).then(function(model) { verifyRender(model, true); model.setArticulationStage("SampleArticulation MoveX", 10); model.applyArticulations(); verifyRender(model, false); model.setArticulationStage("SampleArticulation MoveX", 0); model.applyArticulations(); verifyRender(model, true); model.setArticulationStage("SampleArticulation Size", 0); model.applyArticulations(); verifyRender(model, false); model.setArticulationStage("SampleArticulation Size", 1); model.applyArticulations(); verifyRender(model, true); }); }); }); describe("getNode", function() { it("getNode throws when model is not ready", async function() { const model = await import__723.Model.fromGltfAsync({ url: boxArticulationsUrl }); expect(function() { model.getNode("Root"); }).toThrowDeveloperError(); }); it("getNode throws when name is undefined", function() { return loadAndZoomToModelAsync_default( { gltf: boxArticulationsUrl }, scene2 ).then(function(model) { expect(function() { model.getNode(); }).toThrowDeveloperError(); }); }); it("getNode returns undefined for nonexistent node", function() { return loadAndZoomToModelAsync_default( { gltf: boxArticulationsUrl }, scene2 ).then(function(model) { const node = model.getNode("I don't exist"); expect(node).toBeUndefined(); }); }); it("getNode returns a node", function() { return loadAndZoomToModelAsync_default( { gltf: boxArticulationsUrl }, scene2 ).then(function(model) { const node = model.getNode("Root"); expect(node).toBeDefined(); expect(node.name).toEqual("Root"); expect(node.id).toEqual(0); expect(node.show).toEqual(true); expect(node.matrix).toEqual(boxArticulationsMatrix); expect(node.originalMatrix).toEqual(boxArticulationsMatrix); }); }); it("changing node.show works", function() { return loadAndZoomToModelAsync_default( { gltf: boxArticulationsUrl }, scene2 ).then(function(model) { verifyRender(model, true); const node = model.getNode("Root"); expect(node.show).toEqual(true); node.show = false; verifyRender(model, false); }); }); it("changing node.matrix works", function() { return loadAndZoomToModelAsync_default( { gltf: boxArticulationsUrl }, scene2 ).then(function(model) { verifyRender(model, true); const node = model.getNode("Root"); expect(node.matrix).toEqual(boxArticulationsMatrix); expect(node.originalMatrix).toEqual(boxArticulationsMatrix); node.matrix = import__723.Matrix4.fromTranslation(new import__723.Cartesian3(10, 0, 0)); verifyRender(model, false); }); }); }); describe("fog", function() { const sunnyDate = import__723.JulianDate.fromIso8601("2024-01-11T15:00:00Z"); const darkDate = import__723.JulianDate.fromIso8601("2024-01-11T00:00:00Z"); afterEach(function() { scene2.atmosphere = new import__723.Atmosphere(); scene2.fog = new import__723.Fog(); scene2.light = new import__723.SunLight(); scene2.camera.switchToPerspectiveFrustum(); }); function viewFog(scene3, model) { const center = model.boundingSphere.center; scene3.camera.lookAt(center, new import__723.Cartesian3(1e3, 0, 0)); scene3.camera.switchToOrthographicFrustum(); scene3.camera.frustum.width = 1; } it("renders a model in fog", async function() { scene2.fog.density = 1; scene2.atmosphere.brightnessShift = 1; const model = await loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame( import__723.Cartesian3.fromDegrees(0, 0, 10) ) }, scene2 ); viewFog(scene2, model); const renderOptions = { scene: scene2, time: sunnyDate }; let originalColor; scene2.fog.enabled = false; expect(renderOptions).toRenderAndCall(function(rgba) { originalColor = rgba; expect(originalColor).not.toEqual([0, 0, 0, 255]); }); scene2.fog.enabled = true; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).not.toEqual(originalColor); const [r, g, b, a] = rgba; expect(b).toBeGreaterThan(r); expect(b).toBeGreaterThan(g); expect(a).toBe(255); }); }); it("renders a model in fog (sunlight)", async function() { scene2.fog.density = 1; scene2.atmosphere.brightnessShift = 1; const model = await loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame( import__723.Cartesian3.fromDegrees(0, 0, 10) ) }, scene2 ); const center = model.boundingSphere.center; scene2.camera.lookAt(center, new import__723.Cartesian3(1e3, 0, 0)); scene2.camera.switchToOrthographicFrustum(); scene2.camera.frustum.width = 1; scene2.atmosphere.dynamicLighting = import__723.DynamicAtmosphereLightingType.NONE; const renderOptions = { scene: scene2, time: sunnyDate }; let originalColor; expect(renderOptions).toRenderAndCall(function(rgba) { originalColor = rgba; expect(originalColor).not.toEqual([0, 0, 0, 255]); }); scene2.atmosphere.dynamicLighting = import__723.DynamicAtmosphereLightingType.SUNLIGHT; let sunnyColor; expect(renderOptions).toRenderAndCall(function(rgba) { sunnyColor = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).not.toEqual(originalColor); }); renderOptions.time = darkDate; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual(originalColor); expect(rgba).not.toEqual(sunnyColor); const [sunR, sunG, sunB, sunA] = sunnyColor; const [r, g, b, a] = rgba; expect(r).toBeLessThan(sunR); expect(g).toBeLessThan(sunG); expect(b).toBeLessThan(sunB); expect(a).toBe(sunA); }); }); it("renders a model in fog (scene light)", async function() { scene2.fog.density = 1; scene2.atmosphere.brightnessShift = 1; const model = await loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame( import__723.Cartesian3.fromDegrees(0, 0, 10) ) }, scene2 ); viewFog(scene2, model); scene2.atmosphere.dynamicLighting = import__723.DynamicAtmosphereLightingType.NONE; const renderOptions = { scene: scene2, time: sunnyDate }; let originalColor; expect(renderOptions).toRenderAndCall(function(rgba) { originalColor = rgba; expect(originalColor).not.toEqual([0, 0, 0, 255]); }); scene2.atmosphere.dynamicLighting = import__723.DynamicAtmosphereLightingType.SUNLIGHT; let sunnyColor; expect(renderOptions).toRenderAndCall(function(rgba) { sunnyColor = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).not.toEqual(originalColor); }); scene2.light = new import__723.DirectionalLight({ direction: new import__723.Cartesian3(0, 1, 0) }); expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).toEqual(sunnyColor); }); scene2.atmosphere.dynamicLighting = import__723.DynamicAtmosphereLightingType.SCENE_LIGHT; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).not.toEqual(originalColor); expect(rgba).not.toEqual(sunnyColor); }); }); it("adjusts atmosphere light intensity", async function() { scene2.fog.density = 1; scene2.atmosphere.brightnessShift = 1; const model = await loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame( import__723.Cartesian3.fromDegrees(0, 0, 10) ) }, scene2 ); viewFog(scene2, model); const renderOptions = { scene: scene2, time: sunnyDate }; let originalColor; expect(renderOptions).toRenderAndCall(function(rgba) { originalColor = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); const [r, g, b, a] = rgba; expect(b).toBeGreaterThan(r); expect(b).toBeGreaterThan(g); expect(a).toBe(255); }); scene2.atmosphere.lightIntensity = 5; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).not.toEqual(originalColor); const [oldR, oldG, oldB, oldA] = originalColor; const [r, g, b, a] = rgba; expect(r).toBeLessThan(oldR); expect(g).toBeLessThan(oldG); expect(b).toBeLessThan(oldB); expect(a).toBe(oldA); }); }); it("applies a hue shift", async function() { scene2.fog.density = 1; scene2.atmosphere.brightnessShift = 1; const model = await loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame( import__723.Cartesian3.fromDegrees(0, 0, 10) ) }, scene2 ); viewFog(scene2, model); const renderOptions = { scene: scene2, time: sunnyDate }; let originalColor; expect(renderOptions).toRenderAndCall(function(rgba) { originalColor = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); const [r, g, b, a] = rgba; expect(b).toBeGreaterThan(r); expect(b).toBeGreaterThan(g); expect(a).toBe(255); }); scene2.atmosphere.hueShift = 0.4; let redColor; expect(renderOptions).toRenderAndCall(function(rgba) { redColor = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); expect(redColor).not.toEqual(originalColor); const [r, g, b, a] = rgba; expect(r).toBeGreaterThan(g); expect(r).toBeGreaterThan(b); expect(a).toBe(255); }); scene2.atmosphere.hueShift = 0.7; let greenColor; expect(renderOptions).toRenderAndCall(function(rgba) { greenColor = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); expect(greenColor).not.toEqual(originalColor); expect(greenColor).not.toEqual(redColor); const [r, g, b, a] = rgba; expect(g).toBeGreaterThan(r); expect(g).toBeGreaterThan(b); expect(a).toBe(255); }); scene2.atmosphere.hueShift = 1; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).toEqual(originalColor); }); }); it("applies a brightness shift", async function() { scene2.fog.density = 1; const model = await loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame( import__723.Cartesian3.fromDegrees(0, 0, 10) ) }, scene2 ); viewFog(scene2, model); const renderOptions = { scene: scene2, time: sunnyDate }; let originalColor; scene2.atmosphere.brightnessShift = 1; expect(renderOptions).toRenderAndCall(function(rgba) { originalColor = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); const [r, g, b, a] = rgba; expect(b).toBeGreaterThan(r); expect(b).toBeGreaterThan(g); expect(a).toBe(255); }); scene2.atmosphere.brightnessShift = 0.5; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).not.toEqual(originalColor); const [oldR, oldG, oldB, oldA] = originalColor; const [r, g, b, a] = rgba; expect(r).toBeLessThan(oldR); expect(g).toBeLessThan(oldG); expect(b).toBeLessThan(oldB); expect(a).toBe(oldA); }); }); it("applies a saturation shift", async function() { scene2.fog.density = 1; const model = await loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl, modelMatrix: import__723.Transforms.eastNorthUpToFixedFrame( import__723.Cartesian3.fromDegrees(0, 0, 10) ) }, scene2 ); viewFog(scene2, model); const renderOptions = { scene: scene2, time: sunnyDate }; let originalColor; expect(renderOptions).toRenderAndCall(function(rgba) { originalColor = rgba; expect(rgba).not.toEqual([0, 0, 0, 255]); const [r, g, b, a] = rgba; expect(b).toBeGreaterThan(r); expect(b).toBeGreaterThan(g); expect(a).toBe(255); }); scene2.atmosphere.saturationShift = -1; expect(renderOptions).toRenderAndCall(function(rgba) { expect(rgba).not.toEqual([0, 0, 0, 255]); expect(rgba).not.toEqual(originalColor); const [r, g, b, a] = rgba; expect(g).toBe(r); expect(b).toBe(g); expect(a).toBe(255); }); }); }); it("pick returns position of intersection between ray and model surface", async function() { const model = await loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl, enablePick: !scene2.frameState.context.webgl2 }, scene2 ); const ray = scene2.camera.getPickRay( new import__723.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); const expected = new import__723.Cartesian3(0.5, 0, 0.5); expect(model.pick(ray, scene2.frameState)).toEqualEpsilon( expected, import__723.Math.EPSILON12 ); }); it("destroy works", function() { spyOn(import__723.ShaderProgram.prototype, "destroy").and.callThrough(); return loadAndZoomToModelAsync_default({ gltf: boxTexturedGlbUrl }, scene2).then( function(model) { const resources = model._pipelineResources; const loader = model._loader; let resource; let i; for (i = 0; i < resources.length; i++) { resource = resources[i]; if ((0, import__723.defined)(resource.isDestroyed)) { expect(resource.isDestroyed()).toEqual(false); } } expect(loader.isDestroyed()).toEqual(false); expect(model.isDestroyed()).toEqual(false); scene2.primitives.remove(model); if (!webglStub) { expect(import__723.ShaderProgram.prototype.destroy).toHaveBeenCalled(); } for (i = 0; i < resources.length - 1; i++) { resource = resources[i]; if ((0, import__723.defined)(resource.isDestroyed)) { expect(resource.isDestroyed()).toEqual(true); } } expect(loader.isDestroyed()).toEqual(true); expect(model.isDestroyed()).toEqual(true); } ); }); it("destroy doesn't destroy resources when they're in use", function() { return Promise.all([ loadAndZoomToModelAsync_default({ gltf: boxTexturedGlbUrl }, scene2), loadAndZoomToModelAsync_default({ gltf: boxTexturedGlbUrl }, scene2) ]).then(function(models) { const cacheEntries = import__723.ResourceCache.cacheEntries; let cacheKey; let cacheEntry; scene2.primitives.remove(models[0]); for (cacheKey in cacheEntries) { if (cacheEntries.hasOwnProperty(cacheKey)) { cacheEntry = cacheEntries[cacheKey]; expect(cacheEntry.referenceCount).toBeGreaterThan(0); } } scene2.primitives.remove(models[1]); for (cacheKey in cacheEntries) { if (cacheEntries.hasOwnProperty(cacheKey)) { cacheEntry = cacheEntries[cacheKey]; expect(cacheEntry.referenceCount).toBe(0); } } }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/ModelSplitterPipelineStageSpec.js var import__724 = __toESM(require_Cesium(), 1); describe("Scene/Model/ModelSplitterPipelineStage", function() { const mockFrameState = {}; function mockRenderResources() { return { uniformMap: {}, shaderBuilder: new import__724.ShaderBuilder() }; } it("Configures shader for model splitter", function() { const model = { splitDirection: import__724.SplitDirection.LEFT }; const renderResources = mockRenderResources(); import__724.ModelSplitterPipelineStage.process(renderResources, model, mockFrameState); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_MODEL_SPLITTER" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform float model_splitDirection;" ]); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, []); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__724._shadersModelSplitterStageFS ]); const uniformMap = renderResources.uniformMap; expect(uniformMap.model_splitDirection()).toBe(import__724.SplitDirection.LEFT); }); }); // packages/engine/Specs/Scene/Model/ModelStatisticsSpec.js var import__725 = __toESM(require_Cesium(), 1); describe("Scene/Model/ModelStatistics", function() { const emptyMap = new import__725.AssociativeArray(); it("constructs", function() { const statistics = new import__725.ModelStatistics(); expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(0); expect(statistics.geometryByteLength).toBe(0); expect(statistics.texturesByteLength).toBe(0); expect(statistics.propertyTablesByteLength).toBe(0); expect(statistics.batchTexturesByteLength).toBe(0); expect(statistics._bufferIdSet).toEqual({}); expect(statistics._textureIdSet).toEqual({}); expect(statistics._batchTextureIdMap).toEqual(emptyMap); }); it("clears", function() { const statistics = new import__725.ModelStatistics(); statistics.pointsLength = 10; statistics.trianglesLength = 10; statistics.geometryByteLength = 10; statistics.texturesByteLength = 10; statistics.propertyTablesByteLength = 10; statistics._bufferIdSet = { uuid1: true, uuid2: true }; statistics._textureIdSet = { uuid3: true }; const map = new import__725.AssociativeArray(); map.set("uuid", {}); statistics._batchTextureIdMap = map; statistics.clear(); expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(0); expect(statistics.geometryByteLength).toBe(0); expect(statistics.texturesByteLength).toBe(0); expect(statistics.propertyTablesByteLength).toBe(0); expect(statistics.batchTexturesByteLength).toBe(0); expect(statistics._bufferIdSet).toEqual({}); expect(statistics._textureIdSet).toEqual({}); expect(statistics._batchTextureIdMap).toEqual(emptyMap); }); it("addBuffer throws without buffer", function() { const statistics = new import__725.ModelStatistics(); expect(function() { return statistics.addBuffer(void 0, false); }).toThrowDeveloperError(); }); it("addBuffer throws without hasCpuCopy", function() { const statistics = new import__725.ModelStatistics(); expect(function() { return statistics.addBuffer({}, void 0); }).toThrowDeveloperError(); }); it("addBuffer counts GPU buffers", function() { const statistics = new import__725.ModelStatistics(); const buffer = { _id: "uuid", sizeInBytes: 10 }; statistics.addBuffer(buffer, false); expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(0); expect(statistics.geometryByteLength).toBe(10); expect(statistics.texturesByteLength).toBe(0); expect(statistics.propertyTablesByteLength).toBe(0); expect(statistics.batchTexturesByteLength).toBe(0); expect(statistics._bufferIdSet).toEqual({ uuid: true }); expect(statistics._textureIdSet).toEqual({}); expect(statistics._batchTextureIdMap).toEqual(emptyMap); }); it("addBuffer counts GPU buffers with CPU copy", function() { const statistics = new import__725.ModelStatistics(); const buffer = { _id: "uuid", sizeInBytes: 10 }; statistics.addBuffer(buffer, true); expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(0); expect(statistics.geometryByteLength).toBe(20); expect(statistics.texturesByteLength).toBe(0); expect(statistics.propertyTablesByteLength).toBe(0); expect(statistics.batchTexturesByteLength).toBe(0); expect(statistics._bufferIdSet).toEqual({ uuid: true }); expect(statistics._textureIdSet).toEqual({}); expect(statistics._batchTextureIdMap).toEqual(emptyMap); }); it("addBuffer de-duplicates buffers", function() { const statistics = new import__725.ModelStatistics(); const buffer = { _id: "uuid1", sizeInBytes: 2 }; const buffer2 = { _id: "uuid2", sizeInBytes: 3 }; statistics.addBuffer(buffer, false); statistics.addBuffer(buffer, false); statistics.addBuffer(buffer2, false); expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(0); expect(statistics.geometryByteLength).toBe(5); expect(statistics.texturesByteLength).toBe(0); expect(statistics.propertyTablesByteLength).toBe(0); expect(statistics.batchTexturesByteLength).toBe(0); expect(statistics._bufferIdSet).toEqual({ uuid1: true, uuid2: true }); expect(statistics._textureIdSet).toEqual({}); expect(statistics._batchTextureIdMap).toEqual(emptyMap); }); it("addTexture throws without texture", function() { const statistics = new import__725.ModelStatistics(); expect(function() { return statistics.addTexture(void 0); }).toThrowDeveloperError(); }); it("addTexture counts textures", function() { const statistics = new import__725.ModelStatistics(); const texture = { _id: "uuid", sizeInBytes: 10 }; statistics.addTexture(texture); expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(0); expect(statistics.geometryByteLength).toBe(0); expect(statistics.texturesByteLength).toBe(10); expect(statistics.propertyTablesByteLength).toBe(0); expect(statistics.batchTexturesByteLength).toBe(0); expect(statistics._bufferIdSet).toEqual({}); expect(statistics._textureIdSet).toEqual({ uuid: true }); expect(statistics._batchTextureIdMap).toEqual(emptyMap); }); it("addTexture de-duplicates textures", function() { const statistics = new import__725.ModelStatistics(); const texture = { _id: "uuid1", sizeInBytes: 2 }; const texture2 = { _id: "uuid2", sizeInBytes: 3 }; statistics.addTexture(texture); statistics.addTexture(texture); statistics.addTexture(texture2); expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(0); expect(statistics.geometryByteLength).toBe(0); expect(statistics.texturesByteLength).toBe(5); expect(statistics.propertyTablesByteLength).toBe(0); expect(statistics.batchTexturesByteLength).toBe(0); expect(statistics._bufferIdSet).toEqual({}); expect(statistics._textureIdSet).toEqual({ uuid1: true, uuid2: true }); expect(statistics._batchTextureIdMap).toEqual(emptyMap); }); it("addBatchTexture throws without batch texture", function() { const statistics = new import__725.ModelStatistics(); expect(function() { return statistics.addBatchTexture(void 0); }).toThrowDeveloperError(); }); it("addBatchTexture counts batch textures as they load", function() { const statistics = new import__725.ModelStatistics(); const batchTexture = new import__725.BatchTexture({ featuresLength: 10, owner: {} }); statistics.addBatchTexture(batchTexture); const expectedMap = new import__725.AssociativeArray(); expectedMap.set(batchTexture._id, batchTexture); expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(0); expect(statistics.geometryByteLength).toBe(0); expect(statistics.texturesByteLength).toBe(0); expect(statistics.propertyTablesByteLength).toBe(0); expect(statistics.batchTexturesByteLength).toBe(0); expect(statistics._bufferIdSet).toEqual({}); expect(statistics._textureIdSet).toEqual({}); expect(statistics._batchTextureIdMap).toEqual(expectedMap); batchTexture._batchTexture = { sizeInBytes: 10 }; expect(statistics.batchTexturesByteLength).toBe(10); batchTexture._pickTexture = { sizeInBytes: 15 }; expect(statistics.batchTexturesByteLength).toBe(25); }); it("addBatchTexture de-duplicates batch textures", function() { const statistics = new import__725.ModelStatistics(); const batchTexture = new import__725.BatchTexture({ featuresLength: 10, owner: {} }); const batchTexture2 = new import__725.BatchTexture({ featuresLength: 15, owner: {} }); statistics.addBatchTexture(batchTexture); statistics.addBatchTexture(batchTexture2); statistics.addBatchTexture(batchTexture); const expectedMap = new import__725.AssociativeArray(); expectedMap.set(batchTexture._id, batchTexture); expectedMap.set(batchTexture2._id, batchTexture2); expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(0); expect(statistics.geometryByteLength).toBe(0); expect(statistics.texturesByteLength).toBe(0); expect(statistics.propertyTablesByteLength).toBe(0); expect(statistics.batchTexturesByteLength).toBe(0); expect(statistics._bufferIdSet).toEqual({}); expect(statistics._textureIdSet).toEqual({}); expect(statistics._batchTextureIdMap).toEqual(expectedMap); batchTexture._batchTexture = { sizeInBytes: 10 }; batchTexture._pickTexture = { sizeInBytes: 20 }; expect(statistics.batchTexturesByteLength).toBe(30); batchTexture2._batchTexture = { sizeInBytes: 25 }; batchTexture2._pickTexture = { sizeInBytes: 45 }; expect(statistics.batchTexturesByteLength).toBe(100); }); }); // packages/engine/Specs/Scene/Model/ModelTypeSpec.js var import__726 = __toESM(require_Cesium(), 1); describe("Scene/Model/ModelType", function() { it("is3DTiles works", function() { expect(import__726.ModelType.is3DTiles(import__726.ModelType.GLTF)).toBe(false); expect(import__726.ModelType.is3DTiles(import__726.ModelType.TILE_GLTF)).toBe(true); expect(import__726.ModelType.is3DTiles(import__726.ModelType.TILE_B3DM)).toBe(true); expect(import__726.ModelType.is3DTiles(import__726.ModelType.TILE_I3DM)).toBe(true); expect(import__726.ModelType.is3DTiles(import__726.ModelType.TILE_PNTS)).toBe(true); expect(import__726.ModelType.is3DTiles(import__726.ModelType.TILE_GEOJSON)).toBe(true); }); it("is3DTiles throws for invalid value", function() { expect(function() { return import__726.ModelType.is3DTiles("4DTiles"); }).toThrowDeveloperError(); }); it("is3DTiles throws without modelType", function() { expect(function() { return import__726.ModelType.is3DTiles(); }).toThrowDeveloperError(); }); it("is3DTiles throws with invalid modelType", function() { expect(function() { return import__726.ModelType.is3DTiles(10); }).toThrowDeveloperError(); }); }); // packages/engine/Specs/Scene/Model/ModelUtilitySpec.js var import__727 = __toESM(require_Cesium(), 1); describe("Scene/Model/ModelUtility", function() { it("getNodeTransform works when node has a matrix", function() { const nodeWithMatrix = { matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] }; const computedTransform = import__727.ModelUtility.getNodeTransform(nodeWithMatrix); expect(import__727.Matrix4.equals(computedTransform, import__727.Matrix4.IDENTITY)).toEqual(true); }); it("getNodeTransform works when node has translation, rotation, scale", function() { const nodeWithTRS = { translation: new import__727.Cartesian3(0, 0, 0), rotation: new import__727.Quaternion(0, 0, 0, 1), scale: new import__727.Cartesian3(1, 1, 1) }; const computedTransform = import__727.ModelUtility.getNodeTransform(nodeWithTRS); expect(import__727.Matrix4.equals(computedTransform, import__727.Matrix4.IDENTITY)).toEqual(true); }); it("hasQuantizedAttributes returns false for undefined attributes", function() { expect(import__727.ModelUtility.hasQuantizedAttributes()).toBe(false); }); it("hasQuantizedAttributes detects quantized attributes", function() { const attributes = [ { semantic: "POSITION", max: new import__727.Cartesian3(0.5, 0.5, 0.5), min: new import__727.Cartesian3(-0.5, -0.5, -0.5) }, { semantic: "NORMAL" } ]; expect(import__727.ModelUtility.hasQuantizedAttributes(attributes)).toBe(false); attributes[1].quantization = {}; expect(import__727.ModelUtility.hasQuantizedAttributes(attributes)).toBe(true); }); it("getAttributeInfo works for built-in attributes", function() { const attribute = { semantic: "POSITION", type: import__727.AttributeType.VEC3, max: new import__727.Cartesian3(0.5, 0.5, 0.5), min: new import__727.Cartesian3(-0.5, -0.5, -0.5) }; expect(import__727.ModelUtility.getAttributeInfo(attribute)).toEqual({ attribute, isQuantized: false, variableName: "positionMC", hasSemantic: true, glslType: "vec3", quantizedGlslType: void 0 }); }); it("getAttributeInfo works for attributes with a set index", function() { const attribute = { semantic: "TEXCOORD", setIndex: 0, type: import__727.AttributeType.VEC2 }; expect(import__727.ModelUtility.getAttributeInfo(attribute)).toEqual({ attribute, isQuantized: false, variableName: "texCoord_0", hasSemantic: true, glslType: "vec2", quantizedGlslType: void 0 }); }); it("getAttributeInfo promotes vertex colors to vec4 for GLSL", function() { const attribute = { semantic: "COLOR", setIndex: 0, type: import__727.AttributeType.VEC3 }; expect(import__727.ModelUtility.getAttributeInfo(attribute)).toEqual({ attribute, isQuantized: false, variableName: "color_0", hasSemantic: true, glslType: "vec4", quantizedGlslType: void 0 }); }); it("getAttributeInfo works for custom attributes", function() { const attribute = { name: "_TEMPERATURE", type: import__727.AttributeType.SCALAR }; expect(import__727.ModelUtility.getAttributeInfo(attribute)).toEqual({ attribute, isQuantized: false, variableName: "temperature", hasSemantic: false, glslType: "float", quantizedGlslType: void 0 }); }); it("getAttributeInfo works for quantized attributes", function() { let attribute = { semantic: "POSITION", type: import__727.AttributeType.VEC3, max: new import__727.Cartesian3(0.5, 0.5, 0.5), min: new import__727.Cartesian3(-0.5, -0.5, -0.5), quantization: { type: import__727.AttributeType.VEC3 } }; expect(import__727.ModelUtility.getAttributeInfo(attribute)).toEqual({ attribute, isQuantized: true, variableName: "positionMC", hasSemantic: true, glslType: "vec3", quantizedGlslType: "vec3" }); attribute = { semantic: "NORMAL", type: import__727.AttributeType.VEC3, quantization: { type: import__727.AttributeType.VEC2 } }; expect(import__727.ModelUtility.getAttributeInfo(attribute)).toEqual({ attribute, isQuantized: true, variableName: "normalMC", hasSemantic: true, glslType: "vec3", quantizedGlslType: "vec2" }); }); it("getAttributeInfo handles quantized vertex colors correctly", function() { const attribute = { semantic: "COLOR", setIndex: 0, type: import__727.AttributeType.VEC3, quantization: { type: import__727.AttributeType.VEC3 } }; expect(import__727.ModelUtility.getAttributeInfo(attribute)).toEqual({ attribute, isQuantized: true, variableName: "color_0", hasSemantic: true, glslType: "vec4", quantizedGlslType: "vec4" }); }); it("getPositionMinMax works", function() { const attributes = [ { semantic: "POSITION", max: new import__727.Cartesian3(0.5, 0.5, 0.5), min: new import__727.Cartesian3(-0.5, -0.5, -0.5) } ]; const mockPrimitive = { attributes }; const minMax = import__727.ModelUtility.getPositionMinMax(mockPrimitive); expect(minMax.min).toEqual(attributes[0].min); expect(minMax.max).toEqual(attributes[0].max); }); it("getPositionMinMax works with instancing", function() { const attributes = [ { semantic: "POSITION", max: new import__727.Cartesian3(0.5, 0.5, 0.5), min: new import__727.Cartesian3(-0.5, -0.5, -0.5) } ]; const mockPrimitive = { attributes }; const minMax = import__727.ModelUtility.getPositionMinMax( mockPrimitive, new import__727.Cartesian3(-5, -5, -5), new import__727.Cartesian3(5, 5, 5) ); const expectedMin = new import__727.Cartesian3(-5.5, -5.5, -5.5); const expectedMax = new import__727.Cartesian3(5.5, 5.5, 5.5); expect(minMax.min).toEqual(expectedMin); expect(minMax.max).toEqual(expectedMax); }); it("getAxisCorrectionMatrix works", function() { const expectedYToZMatrix = import__727.Axis.Y_UP_TO_Z_UP; const expectedXToZMatrix = import__727.Axis.X_UP_TO_Z_UP; const expectedCombinedMatrix = import__727.Matrix4.multiplyTransformation( expectedYToZMatrix, import__727.Axis.Z_UP_TO_X_UP, new import__727.Matrix4() ); let resultMatrix = import__727.ModelUtility.getAxisCorrectionMatrix( import__727.Axis.Z, import__727.Axis.X, new import__727.Matrix4() ); expect(import__727.Matrix4.equals(resultMatrix, import__727.Matrix4.IDENTITY)).toBe(true); resultMatrix = import__727.ModelUtility.getAxisCorrectionMatrix( import__727.Axis.Y, import__727.Axis.Z, new import__727.Matrix4() ); expect(import__727.Matrix4.equals(resultMatrix, expectedCombinedMatrix)).toBe(true); resultMatrix = import__727.ModelUtility.getAxisCorrectionMatrix( import__727.Axis.Y, import__727.Axis.X, new import__727.Matrix4() ); expect(import__727.Matrix4.equals(resultMatrix, expectedYToZMatrix)).toBe(true); resultMatrix = import__727.ModelUtility.getAxisCorrectionMatrix( import__727.Axis.X, import__727.Axis.Y, new import__727.Matrix4() ); expect(import__727.Matrix4.equals(resultMatrix, expectedXToZMatrix)).toBe(true); }); it("getAttributeBySemantic works", function() { const nodeIntanceAttributes = { attributes: [ { semantic: import__727.InstanceAttributeSemantic.TRANSLATION }, { semantic: import__727.InstanceAttributeSemantic.ROTATION }, { semantic: import__727.InstanceAttributeSemantic.SCALE }, { semantic: import__727.InstanceAttributeSemantic.FEATURE_ID } ] }; expect( import__727.ModelUtility.getAttributeBySemantic( nodeIntanceAttributes, import__727.InstanceAttributeSemantic.TRANSLATION ) ).toBeDefined(); expect( import__727.ModelUtility.getAttributeBySemantic( nodeIntanceAttributes, import__727.InstanceAttributeSemantic.ROTATION ) ).toBeDefined(); expect( import__727.ModelUtility.getAttributeBySemantic( nodeIntanceAttributes, import__727.InstanceAttributeSemantic.SCALE ) ).toBeDefined(); expect( import__727.ModelUtility.getAttributeBySemantic( nodeIntanceAttributes, import__727.InstanceAttributeSemantic.FEATURE_ID ) ).toBeDefined(); expect( import__727.ModelUtility.getAttributeBySemantic(nodeIntanceAttributes, "UNKNOWN") ).toBeUndefined(); const primitiveAttributes = { attributes: [ { semantic: import__727.VertexAttributeSemantic.POSITION }, { semantic: import__727.VertexAttributeSemantic.NORMAL }, { semantic: import__727.VertexAttributeSemantic.TANGENT }, { semantic: import__727.VertexAttributeSemantic.TEXCOORD, setIndex: 0 }, { semantic: import__727.VertexAttributeSemantic.TEXCOORD, setIndex: 1 } ] }; expect( import__727.ModelUtility.getAttributeBySemantic( primitiveAttributes, import__727.VertexAttributeSemantic.POSITION ) ).toBeDefined(); expect( import__727.ModelUtility.getAttributeBySemantic( primitiveAttributes, import__727.VertexAttributeSemantic.NORMAL ) ).toBeDefined(); expect( import__727.ModelUtility.getAttributeBySemantic( primitiveAttributes, import__727.VertexAttributeSemantic.TANGENT ) ).toBeDefined(); expect( import__727.ModelUtility.getAttributeBySemantic( primitiveAttributes, import__727.VertexAttributeSemantic.TEXCOORD, 0 ) ).toBeDefined(); expect( import__727.ModelUtility.getAttributeBySemantic( primitiveAttributes, import__727.VertexAttributeSemantic.TEXCOORD, 1 ) ).toBeDefined(); expect( import__727.ModelUtility.getAttributeBySemantic(primitiveAttributes, "UNKNOWN") ).toBeUndefined(); }); it("getFeatureIdsByLabel gets feature ID sets by label", function() { const featureIds = [{ label: "perVertex" }, { label: "perFace" }]; expect(import__727.ModelUtility.getFeatureIdsByLabel(featureIds, "perVertex")).toBe( featureIds[0] ); expect(import__727.ModelUtility.getFeatureIdsByLabel(featureIds, "perFace")).toBe( featureIds[1] ); }); it("getFeatureIdsByLabel gets feature ID sets by positional label", function() { const featureIds = [ { positionalLabel: "featureId_0" }, { positionalLabel: "featureId_1" } ]; expect(import__727.ModelUtility.getFeatureIdsByLabel(featureIds, "featureId_0")).toBe( featureIds[0] ); expect(import__727.ModelUtility.getFeatureIdsByLabel(featureIds, "featureId_1")).toBe( featureIds[1] ); }); it("getFeatureIdsByLabel returns undefined for unknown label", function() { const featureIds = [{ label: "perVertex" }, { label: "perFace" }]; expect( import__727.ModelUtility.getFeatureIdsByLabel(featureIds, "other") ).not.toBeDefined(); }); function expectCullFace(matrix, primitiveType, cullFace) { expect(import__727.ModelUtility.getCullFace(matrix, primitiveType)).toBe(cullFace); } it("getCullFace returns CullFace.BACK when primitiveType is not triangles", function() { const matrix = import__727.Matrix4.fromUniformScale(-1); expectCullFace(matrix, import__727.PrimitiveType.POINTS, import__727.CullFace.BACK); expectCullFace(matrix, import__727.PrimitiveType.LINES, import__727.CullFace.BACK); expectCullFace(matrix, import__727.PrimitiveType.LINE_LOOP, import__727.CullFace.BACK); expectCullFace(matrix, import__727.PrimitiveType.LINE_STRIP, import__727.CullFace.BACK); }); it("getCullFace return CullFace.BACK when determinant is greater than zero", function() { const matrix = import__727.Matrix4.IDENTITY; expectCullFace(matrix, import__727.PrimitiveType.TRIANGLES, import__727.CullFace.BACK); expectCullFace(matrix, import__727.PrimitiveType.TRIANGLE_STRIP, import__727.CullFace.BACK); expectCullFace(matrix, import__727.PrimitiveType.TRIANGLE_FAN, import__727.CullFace.BACK); }); it("getCullFace return CullFace.FRONT when determinant is less than zero", function() { const matrix = import__727.Matrix4.fromUniformScale(-1); expectCullFace(matrix, import__727.PrimitiveType.TRIANGLES, import__727.CullFace.FRONT); expectCullFace(matrix, import__727.PrimitiveType.TRIANGLE_STRIP, import__727.CullFace.FRONT); expectCullFace(matrix, import__727.PrimitiveType.TRIANGLE_FAN, import__727.CullFace.FRONT); }); it("sanitizeGlslIdentifier removes non-alphanumeric characters", function() { const identifier = "temperature \u2103"; const result = import__727.ModelUtility.sanitizeGlslIdentifier(identifier); expect(result).toEqual("temperature_"); }); it("sanitizeGlslIdentifier removes consecutive underscores", function() { const identifier = "custom__property"; const result = import__727.ModelUtility.sanitizeGlslIdentifier(identifier); expect(result).toEqual("custom_property"); }); it("sanitizeGlslIdentifier removes gl_ prefix", function() { const identifier = "gl_customProperty"; const result = import__727.ModelUtility.sanitizeGlslIdentifier(identifier); expect(result).toEqual("customProperty"); }); it("sanitizeGlslIdentifier adds underscore to digit identifier", function() { const identifier = "1234"; const result = import__727.ModelUtility.sanitizeGlslIdentifier(identifier); expect(result).toEqual("_1234"); }); it("sanitizeGlslIdentifier handles all cases", function() { const identifier = "gl_1st__test\u2103_variable"; const result = import__727.ModelUtility.sanitizeGlslIdentifier(identifier); expect(result).toEqual("_1st_test_variable"); }); it("checkSupportedExtensions throws for unsupported extension", function() { const extensionsRequired = [ "AGI_articulations", "NOT_supported_extension", "CESIUM_primitive_outline" ]; expect(function() { import__727.ModelUtility.checkSupportedExtensions(extensionsRequired); }).toThrowError(); }); it("checkSupportedExtensions doesn't throw for supported extensions", function() { const extensionsRequired = [ "AGI_articulations", "CESIUM_primitive_outline" ]; expect(function() { import__727.ModelUtility.checkSupportedExtensions(extensionsRequired); }).not.toThrowError(); }); }); // packages/engine/Specs/Scene/Model/MorphTargetsPipelineStageSpec.js var import__728 = __toESM(require_Cesium(), 1); describe( "Scene/Model/MorphTargetsPipelineStage", function() { let scene2; const gltfLoaders = []; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { const gltfLoadersLength = gltfLoaders.length; for (let i = 0; i < gltfLoadersLength; ++i) { const gltfLoader = gltfLoaders[i]; if (!gltfLoader.isDestroyed()) { gltfLoader.destroy(); } } gltfLoaders.length = 0; import__728.ResourceCache.clearForSpecs(); }); function getOptions(gltfPath, options) { const resource = new import__728.Resource({ url: gltfPath }); return (0, import__728.combine)(options, { gltfResource: resource, incrementallyLoadTextures: false // Default to false if not supplied }); } async function loadGltf(gltfPath, options) { const gltfLoader = new import__728.GltfLoader(getOptions(gltfPath, options)); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, scene2); return gltfLoader; } function verifyMorphTargetAttribute(attribute, expectedIndex, expectedOffset, expectedStride) { expect(attribute.index).toEqual(expectedIndex); expect(attribute.vertexBuffer).toBeDefined(); expect(attribute.componentsPerAttribute).toEqual(3); expect(attribute.componentDatatype).toEqual(import__728.ComponentDatatype.FLOAT); expect(attribute.offsetInBytes).toBe(expectedOffset); expect(attribute.strideInBytes).toBe(expectedStride); } const morphPrimitivesTestUrl = "./Data/Models/glTF-2.0/MorphPrimitivesTest/glTF/MorphPrimitivesTest.gltf"; const animatedMorphCubeUrl = "./Data/Models/glTF-2.0/AnimatedMorphCube/glTF/AnimatedMorphCube.gltf"; it("processes morph target with POSITION", function() { const renderResources = { attributes: [], shaderBuilder: new import__728.ShaderBuilder(), attributeIndex: 1, model: { statistics: new import__728.ModelStatistics(), type: import__728.ModelType.TILE_GLTF }, runtimeNode: { morphWeights: void 0 } }; return loadGltf(morphPrimitivesTestUrl).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; renderResources.runtimeNode.morphWeights = [1]; import__728.MorphTargetsPipelineStage.process(renderResources, primitive); const shaderBuilder = renderResources.shaderBuilder; const attributes = renderResources.attributes; expect(attributes.length).toEqual(1); const positionAttribute = attributes[0]; const expectedIndex = 1; const expectedByteOffset = 0; const expectedStride = 12; verifyMorphTargetAttribute( positionAttribute, expectedIndex, expectedByteOffset, expectedStride ); ShaderBuilderTester_default.expectHasVertexFunction( shaderBuilder, import__728.MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_POSITION, import__728.MorphTargetsPipelineStage.FUNCTION_SIGNATURE_GET_MORPHED_POSITION, [ " vec3 morphedPosition = position;", " morphedPosition += u_morphWeights[0] * a_targetPosition_0;", " return morphedPosition;" ] ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_MORPH_TARGETS" ]); ShaderBuilderTester_default.expectHasAttributes(shaderBuilder, void 0, [ "in vec3 a_targetPosition_0;" ]); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__728._shadersMorphTargetsStageVS ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform float u_morphWeights[1];" ]); const uniformMap = renderResources.uniformMap; expect(uniformMap.u_morphWeights()).toBe( renderResources.runtimeNode.morphWeights ); }); }); it("processes morph target with POSITION, NORMAL, and TANGENT", function() { const renderResources = { attributes: [], shaderBuilder: new import__728.ShaderBuilder(), attributeIndex: 1, model: { statistics: new import__728.ModelStatistics(), type: import__728.ModelType.TILE_GLTF }, runtimeNode: { morphWeights: void 0 } }; return loadGltf(animatedMorphCubeUrl).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; renderResources.runtimeNode.morphWeights = [0.5, 0.5]; import__728.MorphTargetsPipelineStage.process(renderResources, primitive); const shaderBuilder = renderResources.shaderBuilder; const attributes = renderResources.attributes; const length2 = attributes.length; expect(length2).toEqual(6); const expectedByteOffset = 0; const expectedStride = 12; for (let i = 0; i < length2; i++) { const attribute = attributes[i]; verifyMorphTargetAttribute( attribute, i + 1, expectedByteOffset, expectedStride ); } ShaderBuilderTester_default.expectHasVertexFunction( shaderBuilder, import__728.MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_POSITION, import__728.MorphTargetsPipelineStage.FUNCTION_SIGNATURE_GET_MORPHED_POSITION, [ " vec3 morphedPosition = position;", " morphedPosition += u_morphWeights[0] * a_targetPosition_0;", " morphedPosition += u_morphWeights[1] * a_targetPosition_1;", " return morphedPosition;" ] ); ShaderBuilderTester_default.expectHasVertexFunction( shaderBuilder, import__728.MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_NORMAL, import__728.MorphTargetsPipelineStage.FUNCTION_SIGNATURE_GET_MORPHED_NORMAL, [ " vec3 morphedNormal = normal;", " morphedNormal += u_morphWeights[0] * a_targetNormal_0;", " morphedNormal += u_morphWeights[1] * a_targetNormal_1;", " return morphedNormal;" ] ); ShaderBuilderTester_default.expectHasVertexFunction( shaderBuilder, import__728.MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_TANGENT, import__728.MorphTargetsPipelineStage.FUNCTION_SIGNATURE_GET_MORPHED_TANGENT, [ " vec3 morphedTangent = tangent;", " morphedTangent += u_morphWeights[0] * a_targetTangent_0;", " morphedTangent += u_morphWeights[1] * a_targetTangent_1;", " return morphedTangent;" ] ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_MORPH_TARGETS" ]); ShaderBuilderTester_default.expectHasAttributes(shaderBuilder, void 0, [ "in vec3 a_targetPosition_0;", "in vec3 a_targetPosition_1;", "in vec3 a_targetNormal_0;", "in vec3 a_targetNormal_1;", "in vec3 a_targetTangent_0;", "in vec3 a_targetTangent_1;" ]); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__728._shadersMorphTargetsStageVS ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform float u_morphWeights[2];" ]); const uniformMap = renderResources.uniformMap; expect(uniformMap.u_morphWeights()).toBe( renderResources.runtimeNode.morphWeights ); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/NodeRenderResourcesSpec.js var import__729 = __toESM(require_Cesium(), 1); describe( "Scene/Model/NodeRenderResources", function() { const mockModel = {}; const mockNode = {}; const mockSceneGraph = { computedModelMatrix: import__729.Matrix4.IDENTITY, components: { upAxis: import__729.Axis.Y, forwardAxis: import__729.Axis.Z } }; const runtimeNode = new import__729.ModelRuntimeNode({ node: mockNode, transform: import__729.Matrix4.IDENTITY, transformToRoot: import__729.Matrix4.fromTranslation(new import__729.Cartesian3(1, 2, 3)), sceneGraph: mockSceneGraph, children: [] }); it("throws for undefined modelRenderResources", function() { expect(function() { return new import__729.NodeRenderResources(void 0, runtimeNode); }).toThrowDeveloperError(); }); it("throws for undefined runtimeNode", function() { expect(function() { const modelResources = new import__729.ModelRenderResources(mockModel); return new import__729.NodeRenderResources(modelResources, void 0); }).toThrowDeveloperError(); }); it("constructs", function() { const modelResources = new import__729.ModelRenderResources(mockModel); const nodeResources = new import__729.NodeRenderResources( modelResources, runtimeNode ); const defaultRenderState = import__729.RenderState.getState( import__729.RenderState.fromCache({ depthTest: { enabled: true, func: import__729.DepthFunction.LESS_OR_EQUAL } }) ); expect(nodeResources.runtimeNode).toBe(runtimeNode); expect(nodeResources.attributes).toEqual([]); expect(nodeResources.renderStateOptions).toEqual(defaultRenderState); expect(nodeResources.hasSilhouette).toBe(false); expect(nodeResources.hasSkipLevelOfDetail).toBe(false); }); it("inherits from model render resources", function() { const modelResources = new import__729.ModelRenderResources(mockModel); modelResources.shaderBuilder.addDefine("MODEL"); modelResources.renderStateOptions.cull = { enabled: true }; modelResources.hasSilhouette = true; modelResources.hasSkipLevelOfDetail = true; const nodeResources = new import__729.NodeRenderResources( modelResources, runtimeNode ); nodeResources.shaderBuilder.addDefine("NODE"); expect(nodeResources.model).toBe(mockModel); expect(nodeResources.renderStateOptions).not.toBe( modelResources.renderStateOptions ); expect(nodeResources.renderStateOptions.cull).toEqual({ enabled: true }); expect(nodeResources.hasSilhouette).toBe(true); expect(nodeResources.hasSkipLevelOfDetail).toBe(true); expect(nodeResources.shaderBuilder).not.toBe( modelResources.shaderBuilder ); ShaderBuilderTester_default.expectHasFragmentDefines( modelResources.shaderBuilder, ["MODEL"] ); ShaderBuilderTester_default.expectHasFragmentDefines( nodeResources.shaderBuilder, ["MODEL", "NODE"] ); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/NodeStatisticsPipelineStageSpec.js var import__730 = __toESM(require_Cesium(), 1); describe( "Scene/Model/NodeStatisticsPipelineStage", function() { const boxTextured = "./Data/Models/glTF-2.0/BoxTextured/glTF-Binary/BoxTextured.glb"; const boxInstanced = "./Data/Models/glTF-2.0/BoxInstanced/glTF/box-instanced.gltf"; const boxInstancedTranslationMinMax = "./Data/Models/glTF-2.0/BoxInstancedTranslationWithMinMax/glTF/box-instanced-translation-min-max.gltf"; let scene2; const gltfLoaders = []; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { const gltfLoadersLength = gltfLoaders.length; for (let i = 0; i < gltfLoadersLength; ++i) { const gltfLoader = gltfLoaders[i]; if (!gltfLoader.isDestroyed()) { gltfLoader.destroy(); } } gltfLoaders.length = 0; import__730.ResourceCache.clearForSpecs(); }); function getOptions(gltfPath, options) { const resource = new import__730.Resource({ url: gltfPath }); return (0, import__730.combine)(options, { gltfResource: resource, incrementallyLoadTextures: false // Default to false if not supplied }); } async function loadGltf(gltfPath, options) { const gltfLoader = new import__730.GltfLoader(getOptions(gltfPath, options)); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, scene2); return gltfLoader; } function mockRenderResources(components) { return { model: { sceneGraph: { components, computedModelMatrix: import__730.Matrix4.IDENTITY }, statistics: new import__730.ModelStatistics() }, runtimeNode: { computedTransform: import__730.Matrix4.IDENTITY } }; } it("does not update statistics for a non-instanced model", function() { return loadGltf(boxTextured).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[1]; const renderResources = mockRenderResources(components); import__730.NodeStatisticsPipelineStage.process(renderResources, node); const statistics = renderResources.model.statistics; expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(0); expect(statistics.geometryByteLength).toBe(0); expect(statistics.texturesByteLength).toBe(0); expect(statistics.propertyTablesByteLength).toBe(0); }); }); it("updates statistics for an instanced model", function() { return loadGltf(boxInstancedTranslationMinMax).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const renderResources = mockRenderResources(components); import__730.NodeStatisticsPipelineStage.process(renderResources, node); const statistics = renderResources.model.statistics; const expectedByteLength = 48; expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(0); expect(statistics.geometryByteLength).toBe(expectedByteLength); expect(statistics.texturesByteLength).toBe(0); expect(statistics.propertyTablesByteLength).toBe(0); }); }); it("_countInstancingAttributes counts attributes with buffers", function() { return loadGltf(boxInstancedTranslationMinMax).then(function(gltfLoader) { const statistics = new import__730.ModelStatistics(); const components = gltfLoader.components; const node = components.nodes[0]; import__730.NodeStatisticsPipelineStage._countInstancingAttributes( statistics, node.instances ); const expectedByteLength = 4 * 12; expect(statistics.geometryByteLength).toBe(expectedByteLength); }); }); it("_countInstancingAttributes does not count attributes without buffers", function() { return loadGltf(boxInstanced).then(function(gltfLoader) { const statistics = new import__730.ModelStatistics(); const components = gltfLoader.components; const node = components.nodes[0]; import__730.NodeStatisticsPipelineStage._countInstancingAttributes( statistics, node.instances ); const expectedByteLength = 16; expect(statistics.geometryByteLength).toBe(expectedByteLength); }); }); it("_countGeneratedBuffers counts instancing transform buffer", function() { return loadGltf(boxInstanced).then(function(gltfLoader) { const statistics = new import__730.ModelStatistics(); const mockRuntimeNode = { instancingTransformsBuffer: { // Matrices are stored as 3 vec4s, so this is // 4 matrices * 12 floats/matrix * 4 bytes/float = 192 sizeInBytes: 192 } }; import__730.NodeStatisticsPipelineStage._countGeneratedBuffers( statistics, mockRuntimeNode ); const transformsBuffer = mockRuntimeNode.instancingTransformsBuffer; expect(statistics.geometryByteLength).toBe( transformsBuffer.sizeInBytes ); }); }); it("_countGeneratedBuffers counts instancing transform buffer for 2D", function() { return loadGltf(boxInstanced).then(function(gltfLoader) { const statistics = new import__730.ModelStatistics(); const mockRuntimeNode = { instancingTransformsBuffer2D: { // Matrices are stored as 3 vec4s, so this is // 4 matrices * 12 floats/matrix * 4 bytes/float = 192 sizeInBytes: 192 } }; import__730.NodeStatisticsPipelineStage._countGeneratedBuffers( statistics, mockRuntimeNode ); const transformsBuffer2D = mockRuntimeNode.instancingTransformsBuffer2D; expect(statistics.geometryByteLength).toBe( transformsBuffer2D.sizeInBytes ); }); }); it("_countGeneratedBuffers counts instancing translation buffer for 2D", function() { return loadGltf(boxInstancedTranslationMinMax).then(function(gltfLoader) { const statistics = new import__730.ModelStatistics(); const mockRuntimeNode = { instancingTranslationBuffer2D: { // Model contains four translated instances: // 4 instances * 3 floats * 4 bytes per float sizeInBytes: 48 } }; import__730.NodeStatisticsPipelineStage._countGeneratedBuffers( statistics, mockRuntimeNode ); const translationBuffer2D = mockRuntimeNode.instancingTranslationBuffer2D; expect(statistics.geometryByteLength).toBe( translationBuffer2D.sizeInBytes ); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/PickingPipelineStageSpec.js var import__731 = __toESM(require_Cesium(), 1); describe( "Scene/Model/PickingPipelineStage", function() { const boxVertexColors = "./Data/Models/glTF-2.0/BoxVertexColors/glTF/BoxVertexColors.gltf"; const boxInstanced = "./Data/Models/glTF-2.0/BoxInstanced/glTF/box-instanced.gltf"; const microcosm = "./Data/Models/glTF-2.0/Microcosm/glTF/microcosm.gltf"; const mockIdObject = {}; let scene2; const gltfLoaders = []; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { const gltfLoadersLength = gltfLoaders.length; for (let i = 0; i < gltfLoadersLength; ++i) { const gltfLoader = gltfLoaders[i]; if (!gltfLoader.isDestroyed()) { gltfLoader.destroy(); } } gltfLoaders.length = 0; import__731.ResourceCache.clearForSpecs(); }); function getOptions(gltfPath, options) { const resource = new import__731.Resource({ url: gltfPath }); return (0, import__731.combine)(options, { gltfResource: resource, incrementallyLoadTexture: false }); } async function loadGltf(gltfPath, options) { const gltfLoader = new import__731.GltfLoader(getOptions(gltfPath, options)); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, scene2); return gltfLoader; } function mockRenderResources() { return { attributes: [], attributeIndex: 1, pickId: void 0, shaderBuilder: new import__731.ShaderBuilder(), model: { _pipelineResources: [], _pickIds: [], statistics: new import__731.ModelStatistics(), type: import__731.ModelType.GLTF }, runtimePrimitive: { primitive: {} }, runtimeNode: { node: {} }, uniformMap: {} }; } function expectUniformMap(uniformMap, expected) { for (const key in expected) { if (expected.hasOwnProperty(key)) { const expectedValue = expected[key]; const uniformFunction = uniformMap[key]; expect(uniformFunction).toBeDefined(); expect(uniformFunction()).toEqual(expectedValue); } } } function verifyPickObject(pickObject, renderResources, instanceId) { const model = renderResources.model; expect(pickObject).toBeDefined(); if (import__731.ModelType.is3DTiles(model.type)) { const content = model.content; expect(pickObject.primitive).toEqual(content.tileset); expect(pickObject.content).toEqual(content); } else { expect(pickObject.primitive).toEqual(model); } if ((0, import__731.defined)(instanceId)) { expect(pickObject.instanceId).toEqual(instanceId); } const detailPickObject = pickObject.detail; expect(detailPickObject).toBeDefined(); expect(detailPickObject.model).toEqual(model); expect(detailPickObject.node).toEqual(renderResources.runtimeNode); expect(detailPickObject.primitive).toEqual( renderResources.runtimePrimitive ); } it("returns model.pickObject if defined", function() { const renderResources = mockRenderResources(); const customPickObject = { primitive: { id: "custom" } }; renderResources.model.pickObject = customPickObject; return loadGltf(boxVertexColors).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const frameState2 = scene2.frameState; const context = frameState2.context; context._pickObjects = []; import__731.PickingPipelineStage.process(renderResources, primitive, frameState2); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform vec4 czm_pickColor;" ]); const pickObject = context._pickObjects[Object.keys(context._pickObjects)[0]]; expect(pickObject).toBe(customPickObject); const uniformMap = renderResources.uniformMap; expect(uniformMap.czm_pickColor).toBeDefined(); expect(uniformMap.czm_pickColor()).toBeDefined(); expect(renderResources.model._pipelineResources.length).toEqual(1); expect(renderResources.model._pickIds.length).toEqual(1); expect(renderResources.pickId).toEqual("czm_pickColor"); }); }); it("sets the picking variables in render resources for 3D Tiles", function() { const renderResources = mockRenderResources(); renderResources.model.type = import__731.ModelType.TILE_GLTF; renderResources.model.content = { tileset: {} }; return loadGltf(boxVertexColors).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const frameState2 = scene2.frameState; const context = frameState2.context; context._pickObjects = []; import__731.PickingPipelineStage.process(renderResources, primitive, frameState2); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform vec4 czm_pickColor;" ]); const pickObject = context._pickObjects[Object.keys(context._pickObjects)[0]]; verifyPickObject(pickObject, renderResources); const uniformMap = renderResources.uniformMap; expect(uniformMap.czm_pickColor).toBeDefined(); expect(uniformMap.czm_pickColor()).toBeDefined(); expect(renderResources.model._pipelineResources.length).toEqual(1); expect(renderResources.model._pickIds.length).toEqual(1); expect(renderResources.pickId).toEqual("czm_pickColor"); }); }); it("sets the picking variables in render resources for models", function() { const renderResources = mockRenderResources(); return loadGltf(boxVertexColors).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const frameState2 = scene2.frameState; const context = frameState2.context; context._pickObjects = []; import__731.PickingPipelineStage.process(renderResources, primitive, frameState2); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform vec4 czm_pickColor;" ]); const pickObject = context._pickObjects[Object.keys(context._pickObjects)[0]]; verifyPickObject(pickObject, renderResources); const uniformMap = renderResources.uniformMap; expect(uniformMap.czm_pickColor).toBeDefined(); expect(uniformMap.czm_pickColor()).toBeDefined(); expect(renderResources.model._pipelineResources.length).toEqual(1); expect(renderResources.model._pickIds.length).toEqual(1); expect(renderResources.pickId).toEqual("czm_pickColor"); }); }); it("sets value for pick object id if model has an id defined", function() { const renderResources = mockRenderResources(); renderResources.model.id = mockIdObject; return loadGltf(boxVertexColors).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const frameState2 = scene2.frameState; const context = frameState2.context; context._pickObjects = []; import__731.PickingPipelineStage.process(renderResources, primitive, frameState2); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform vec4 czm_pickColor;" ]); const pickObject = context._pickObjects[Object.keys(context._pickObjects)[0]]; verifyPickObject(pickObject, renderResources, void 0); expect(pickObject.id).toBe(mockIdObject); const uniformMap = renderResources.uniformMap; expect(uniformMap.czm_pickColor).toBeDefined(); expect(uniformMap.czm_pickColor()).toBeDefined(); expect(renderResources.model._pipelineResources.length).toEqual(1); expect(renderResources.model._pickIds.length).toEqual(1); expect(renderResources.pickId).toEqual("czm_pickColor"); }); }); it("sets the picking variables in render resources with instancing", function() { const renderResources = mockRenderResources(); renderResources.instanceCount = 4; renderResources.runtimeNode.node.instances = { featureIds: [{}, {}] }; return loadGltf(boxInstanced).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; renderResources.runtimeNode.node = components.nodes[0]; const frameState2 = scene2.frameState; const context = frameState2.context; context._pickObjects = []; import__731.PickingPipelineStage.process(renderResources, primitive, frameState2); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasAttributes(shaderBuilder, void 0, [ "in vec4 a_pickColor;" ]); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "vec4 v_pickColor;" ]); let i = 0; for (const key in context._pickObjects) { if (context._pickObjects.hasOwnProperty(key)) { const pickObject = context._pickObjects[key]; verifyPickObject(pickObject, renderResources, i++); } } const pickIdAttribute = renderResources.attributes[0]; expect(pickIdAttribute).toBeDefined(); expect(pickIdAttribute.index).toEqual(1); expect(renderResources.attributeIndex).toEqual(2); expect(pickIdAttribute.vertexBuffer).toBeDefined(); expect(pickIdAttribute.vertexBuffer.sizeInBytes).toEqual( renderResources.instanceCount * 4 ); expect(pickIdAttribute.instanceDivisor).toEqual(1); expect(renderResources.model._pipelineResources.length).toEqual(5); expect(renderResources.model._pickIds.length).toEqual(4); const statistics = renderResources.model.statistics; expect(statistics.geometryByteLength).toBe( renderResources.instanceCount * 4 ); expect(renderResources.pickId).toEqual("v_pickColor"); }); }); it("sets the picking variables in render resources with feature ID textures", function() { const mockModelFeatureTable = { batchTexture: { pickTexture: "mockPickTexture" } }; const renderResources = mockRenderResources(); renderResources.hasPropertyTable = true; renderResources.model.featureIdLabel = "featureId_0"; renderResources.model.featureTables = [mockModelFeatureTable]; return loadGltf(microcosm).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const frameState2 = scene2.frameState; const context = frameState2.context; context._pickObjects = []; import__731.PickingPipelineStage.process(renderResources, primitive, frameState2); const expectedUniforms = { model_pickTexture: mockModelFeatureTable.batchTexture.pickTexture }; expectUniformMap(renderResources.uniformMap, expectedUniforms); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform sampler2D model_pickTexture;" ]); expect(renderResources.pickId).toEqual( "((selectedFeature.id < int(model_featuresLength)) ? texture(model_pickTexture, selectedFeature.st) : vec4(0.0))" ); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/PntsLoaderSpec.js var import__732 = __toESM(require_Cesium(), 1); describe( "Scene/Model/PntsLoader", function() { const pointCloudRGBUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudRGB/pointCloudRGB.pnts"; const pointCloudRGBAUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudRGBA/pointCloudRGBA.pnts"; const pointCloudRGB565Url = "./Data/Cesium3DTiles/PointCloud/PointCloudRGB565/pointCloudRGB565.pnts"; const pointCloudNoColorUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudNoColor/pointCloudNoColor.pnts"; const pointCloudWithTransformUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudWithTransform/pointCloudWithTransform.pnts"; const pointCloudConstantColorUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudConstantColor/pointCloudConstantColor.pnts"; const pointCloudNormalsUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudNormals/pointCloudNormals.pnts"; const pointCloudNormalsOctEncodedUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudNormalsOctEncoded/pointCloudNormalsOctEncoded.pnts"; const pointCloudQuantizedUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudQuantized/pointCloudQuantized.pnts"; const pointCloudQuantizedOctEncodedUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudQuantizedOctEncoded/pointCloudQuantizedOctEncoded.pnts"; const pointCloudDracoUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudDraco/pointCloudDraco.pnts"; const pointCloudDracoPartialUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudDracoPartial/pointCloudDracoPartial.pnts"; const pointCloudDracoBatchedUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudDracoBatched/pointCloudDracoBatched.pnts"; const pointCloudWGS84Url = "./Data/Cesium3DTiles/PointCloud/PointCloudWGS84/pointCloudWGS84.pnts"; const pointCloudBatchedUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudBatched/pointCloudBatched.pnts"; const pointCloudWithPerPointPropertiesUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudWithPerPointProperties/pointCloudWithPerPointProperties.pnts"; const pointCloudWithUnicodePropertyIdsUrl = "./Data/Cesium3DTiles/PointCloud/PointCloudWithUnicodePropertyIds/pointCloudWithUnicodePropertyIds.pnts"; let scene2; const pntsLoaders = []; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { for (let i = 0; i < pntsLoaders.length; i++) { const loader = pntsLoaders[i]; if (!loader.isDestroyed()) { loader.destroy(); } } pntsLoaders.length = 0; import__732.ResourceCache.clearForSpecs(); }); async function loadPntsArrayBuffer(arrayBuffer, options) { options = (0, import__732.defaultValue)(options, import__732.defaultValue.EMPTY_OBJECT); const loader = new import__732.PntsLoader({ arrayBuffer, loadAttributesFor2D: options.loadAttributesFor2D }); pntsLoaders.push(loader); await loader.load(); await waitForLoaderProcess_default(loader, scene2); return loader; } function loadPnts(pntsPath, options) { return import__732.Resource.fetchArrayBuffer({ url: pntsPath }).then(function(arrayBuffer) { return loadPntsArrayBuffer(arrayBuffer, options); }); } async function expectLoadError(arrayBuffer) { await expectAsync(loadPntsArrayBuffer(arrayBuffer)).toBeRejectedWithError( import__732.RuntimeError ); } function expectEmptyMetadata(structuralMetadata) { expect(structuralMetadata).toBeDefined(); expect(structuralMetadata.schema).toEqual({}); expect(structuralMetadata.propertyTableCount).toBe(0); } function expectMetadata(structuralMetadata, expectedProperties, isBatched) { expect(structuralMetadata).toBeDefined(); const schema = structuralMetadata.schema; const batchClass = schema.classes[import__732.MetadataClass.BATCH_TABLE_CLASS_NAME]; const properties = batchClass.properties; const expectedPropertyTableCount = isBatched ? 1 : 0; expect(structuralMetadata.propertyTableCount).toEqual( expectedPropertyTableCount ); const propertyTable = structuralMetadata.getPropertyTable(0); const tablePropertyNames = []; const attributePropertyNames = []; for (const propertyName in expectedProperties) { if (expectedProperties.hasOwnProperty(propertyName)) { const expectedProperty = expectedProperties[propertyName]; const property = properties[propertyName]; if (expectedProperty.isJson) { expect(propertyTable.getProperty(0, propertyName)).toBeDefined(); tablePropertyNames.push(propertyName); } else { expect(property.type).toEqual(expectedProperty.type); expect(property.componentType).toEqual( expectedProperty.componentType ); const nameList = isBatched ? tablePropertyNames : attributePropertyNames; nameList.push(propertyName); } } } if (isBatched) { expect(propertyTable.getPropertyIds(0).sort()).toEqual( tablePropertyNames.sort() ); } else { const propertyAttribute = structuralMetadata.getPropertyAttribute(0); expect(Object.keys(propertyAttribute.properties).sort()).toEqual( attributePropertyNames.sort() ); } } function expectPosition(attribute) { expect(attribute.name).toBe("POSITION"); expect(attribute.semantic).toBe(import__732.VertexAttributeSemantic.POSITION); expect(attribute.componentDatatype).toBe(import__732.ComponentDatatype.FLOAT); expect(attribute.type).toBe(import__732.AttributeType.VEC3); expect(attribute.normalized).toBe(false); expect(attribute.quantization).not.toBeDefined(); expect(attribute.max).toBeDefined(); expect(attribute.min).toBeDefined(); } function expectPositionQuantized(attribute) { expect(attribute.name).toBe("POSITION"); expect(attribute.semantic).toBe(import__732.VertexAttributeSemantic.POSITION); expect(attribute.componentDatatype).toBe(import__732.ComponentDatatype.FLOAT); expect(attribute.type).toBe(import__732.AttributeType.VEC3); expect(attribute.normalized).toBe(false); expect(attribute.max).toBeDefined(); expect(attribute.min).toBeDefined(); const quantization = attribute.quantization; expect(quantization.componentDatatype).toBe( import__732.ComponentDatatype.UNSIGNED_SHORT ); expect(quantization.normalizationRange).toBeDefined(); expect(quantization.octEncoded).toBe(false); expect(quantization.quantizedVolumeDimensions).toBeDefined(); expect(quantization.quantizedVolumeOffset).toBeDefined(); expect(quantization.quantizedVolumeStepSize).toBeDefined(); expect(quantization.type).toBe(import__732.AttributeType.VEC3); } function expectColorRGB(attribute) { expect(attribute.name).toBe("COLOR"); expect(attribute.semantic).toBe(import__732.VertexAttributeSemantic.COLOR); expect(attribute.setIndex).toBe(0); expect(attribute.componentDatatype).toBe(import__732.ComponentDatatype.UNSIGNED_BYTE); expect(attribute.type).toBe(import__732.AttributeType.VEC3); expect(attribute.normalized).toBe(true); } function expectColorRGB565(attribute) { expect(attribute.name).toBe("COLOR"); expect(attribute.semantic).toBe(import__732.VertexAttributeSemantic.COLOR); expect(attribute.setIndex).toBe(0); expect(attribute.componentDatatype).toBe(import__732.ComponentDatatype.FLOAT); expect(attribute.type).toBe(import__732.AttributeType.VEC3); expect(attribute.normalized).toBe(false); } function expectColorRGBA(attribute) { expect(attribute.name).toBe("COLOR"); expect(attribute.semantic).toBe(import__732.VertexAttributeSemantic.COLOR); expect(attribute.setIndex).toBe(0); expect(attribute.componentDatatype).toBe(import__732.ComponentDatatype.UNSIGNED_BYTE); expect(attribute.type).toBe(import__732.AttributeType.VEC4); expect(attribute.normalized).toBe(true); } function expectConstantColor(attribute) { expect(attribute.name).toBe("COLOR"); expect(attribute.semantic).toBe(import__732.VertexAttributeSemantic.COLOR); expect(attribute.setIndex).toBe(0); expect(attribute.componentDatatype).toBe(import__732.ComponentDatatype.FLOAT); expect(attribute.type).toBe(import__732.AttributeType.VEC4); expect(attribute.normalized).toBe(false); expect(attribute.constant).toBeDefined(); } function expectDefaultColor(attribute) { expect(attribute.name).toBe("COLOR"); expect(attribute.semantic).toBe(import__732.VertexAttributeSemantic.COLOR); expect(attribute.setIndex).toBe(0); expect(attribute.componentDatatype).toBe(import__732.ComponentDatatype.FLOAT); expect(attribute.type).toBe(import__732.AttributeType.VEC4); expect(attribute.normalized).toBe(false); expect(attribute.constant).toEqual(import__732.Color.pack(import__732.Color.DARKGRAY, [])); } function expectNormal(attribute) { expect(attribute.name).toBe("NORMAL"); expect(attribute.semantic).toBe(import__732.VertexAttributeSemantic.NORMAL); expect(attribute.componentDatatype).toBe(import__732.ComponentDatatype.FLOAT); expect(attribute.type).toBe(import__732.AttributeType.VEC3); expect(attribute.normalized).toBe(false); expect(attribute.quantization).not.toBeDefined(); } function expectNormalOctEncoded(attribute, componentDatatype, isDraco) { expect(attribute.name).toBe("NORMAL"); expect(attribute.semantic).toBe(import__732.VertexAttributeSemantic.NORMAL); expect(attribute.componentDatatype).toBe(import__732.ComponentDatatype.FLOAT); expect(attribute.type).toBe(import__732.AttributeType.VEC3); expect(attribute.normalized).toBe(false); const quantization = attribute.quantization; expect(quantization.componentDatatype).toBe(componentDatatype); expect(quantization.normalizationRange).toBeDefined(); expect(quantization.octEncoded).toBe(true); const isZXY = isDraco; expect(quantization.octEncodedZXY).toBe(isZXY); expect(quantization.quantizedVolumeDimensions).not.toBeDefined(); expect(quantization.quantizedVolumeOffset).not.toBeDefined(); expect(quantization.quantizedVolumeStepSize).not.toBeDefined(); expect(quantization.type).toBe(import__732.AttributeType.VEC2); } function expectBatchId(attribute, componentDatatype) { expect(attribute.name).toBe("_FEATURE_ID"); expect(attribute.semantic).toBe(import__732.VertexAttributeSemantic.FEATURE_ID); expect(attribute.componentDatatype).toBe(componentDatatype); expect(attribute.type).toBe(import__732.AttributeType.SCALAR); expect(attribute.normalized).toBe(false); expect(attribute.quantization).not.toBeDefined(); } it("releases array buffer when finished", function() { return loadPnts(pointCloudRGBUrl).then(function(loader) { expect(loader.components).toBeDefined(); expect(loader._arrayBuffer).not.toBeDefined(); }); }); it("loads PointCloudRGB", function() { return loadPnts(pointCloudRGBUrl).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); expectEmptyMetadata(components.structuralMetadata); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(2); expectPosition(attributes[0]); expectColorRGB(attributes[1]); }); }); it("loads PointCloudRGBA", function() { return loadPnts(pointCloudRGBAUrl).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); expectEmptyMetadata(components.structuralMetadata); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(2); expectPosition(attributes[0]); expectColorRGBA(attributes[1]); }); }); it("loads PointCloudRGB565", function() { return loadPnts(pointCloudRGB565Url).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); expectEmptyMetadata(components.structuralMetadata); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(2); expectPosition(attributes[0]); expectColorRGB565(attributes[1]); }); }); it("loads PointCloudNoColor", function() { return loadPnts(pointCloudNoColorUrl).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); expectEmptyMetadata(components.structuralMetadata); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(2); expectPosition(attributes[0]); expectDefaultColor(attributes[1]); }); }); it("loads PointCloudConstantColor", function() { return loadPnts(pointCloudConstantColorUrl).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); expectEmptyMetadata(components.structuralMetadata); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(2); expectPosition(attributes[0]); expectConstantColor(attributes[1]); }); }); it("loads PointCloudNormals", function() { return loadPnts(pointCloudNormalsUrl).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); expectEmptyMetadata(components.structuralMetadata); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(3); expectPosition(attributes[0]); expectNormal(attributes[1]); expectColorRGB(attributes[2]); }); }); it("loads PointCloudNormalsOctEncoded", function() { return loadPnts(pointCloudNormalsOctEncodedUrl).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); expectEmptyMetadata(components.structuralMetadata); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(3); expectPosition(attributes[0]); expectNormalOctEncoded( attributes[1], import__732.ComponentDatatype.UNSIGNED_BYTE, false ); expectColorRGB(attributes[2]); }); }); it("loads PointCloudQuantized", function() { return loadPnts(pointCloudQuantizedUrl).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); expectEmptyMetadata(components.structuralMetadata); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(2); expectPositionQuantized(attributes[0], import__732.ComponentDatatype.UNSIGNED_BYTE); expectColorRGB(attributes[1]); }); }); it("loads PointCloudQuantizedOctEncoded", function() { return loadPnts(pointCloudQuantizedOctEncodedUrl).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); expectEmptyMetadata(components.structuralMetadata); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(3); expectPositionQuantized(attributes[0]); expectNormalOctEncoded( attributes[1], import__732.ComponentDatatype.UNSIGNED_BYTE, false ); expectColorRGB(attributes[2]); }); }); it("loads PointCloudDraco", function() { return loadPnts(pointCloudDracoUrl).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); const isBatched = false; expectMetadata( components.structuralMetadata, { secondaryColor: { type: import__732.MetadataType.VEC3, componentType: import__732.MetadataComponentType.FLOAT32 }, temperature: { type: import__732.MetadataType.SCALAR, componentType: import__732.MetadataComponentType.FLOAT32 }, id: { type: import__732.MetadataType.SCALAR, componentType: import__732.MetadataComponentType.UINT16 } }, isBatched ); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(6); expectPositionQuantized(attributes[0]); expectNormalOctEncoded( attributes[1], import__732.ComponentDatatype.UNSIGNED_BYTE, true ); expectColorRGB(attributes[2]); }); }); it("loads PointCloudDracoPartial", function() { return loadPnts(pointCloudDracoPartialUrl).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); const isBatched = false; expectMetadata( components.structuralMetadata, { secondaryColor: { type: import__732.MetadataType.VEC3, componentType: import__732.MetadataComponentType.FLOAT32 }, temperature: { type: import__732.MetadataType.SCALAR, componentType: import__732.MetadataComponentType.FLOAT32 }, id: { type: import__732.MetadataType.SCALAR, componentType: import__732.MetadataComponentType.UINT16 } }, isBatched ); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(6); expectPositionQuantized(attributes[0]); expectNormal(attributes[1]); expectColorRGB(attributes[2]); }); }); it("loads PointCloudDracoBatched", function() { return loadPnts(pointCloudDracoBatchedUrl).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); const isBatched = true; expectMetadata( components.structuralMetadata, { dimensions: { type: import__732.MetadataType.VEC3, componentType: import__732.MetadataComponentType.FLOAT32 }, name: { type: import__732.MetadataType.SCALAR, isJson: true }, id: { type: import__732.MetadataType.SCALAR, componentType: import__732.MetadataComponentType.UINT32 } }, isBatched ); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(4); expectPositionQuantized(attributes[0]); expectNormalOctEncoded( attributes[1], import__732.ComponentDatatype.UNSIGNED_BYTE, true ); expectColorRGB(attributes[2]); expectBatchId(attributes[3], import__732.ComponentDatatype.UNSIGNED_BYTE); }); }); it("loads PointCloudWGS84", function() { return loadPnts(pointCloudWGS84Url).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); expectEmptyMetadata(components.structuralMetadata); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(2); expectPosition(attributes[0]); expectColorRGB(attributes[1]); }); }); it("loads PointCloudBatched", function() { return loadPnts(pointCloudBatchedUrl).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); const isBatched = true; expectMetadata( components.structuralMetadata, { dimensions: { type: import__732.MetadataType.VEC3, componentType: import__732.MetadataComponentType.FLOAT32 }, name: { type: import__732.MetadataType.SCALAR, isJson: true }, id: { type: import__732.MetadataType.SCALAR, componentType: import__732.MetadataComponentType.UINT32 } }, isBatched ); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(4); expectPosition(attributes[0]); expectNormal(attributes[1]); expectDefaultColor(attributes[2]); expectBatchId(attributes[3], import__732.ComponentDatatype.UNSIGNED_BYTE); }); }); it("loads PointCloudWithTransform", function() { return loadPnts(pointCloudWithTransformUrl).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); expectEmptyMetadata(components.structuralMetadata); expect(components.transform).toEqual(import__732.Matrix4.IDENTITY); const node = components.nodes[0]; expect(node.matrix).not.toBeDefined(); expect(node.translation).not.toBeDefined(); expect(node.rotation).not.toBeDefined(); expect(node.scale).not.toBeDefined(); const primitive = node.primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(2); expectPosition(attributes[0]); expectColorRGB(attributes[1]); }); }); it("BATCH_ID semantic uses componentType of UNSIGNED_SHORT by default", function() { const arrayBuffer = Cesium3DTilesTester_default.generatePointCloudTileBuffer({ featureTableJson: { POINTS_LENGTH: 2, POSITION: [0, 0, 0, 1, 1, 1], BATCH_ID: [0, 1], BATCH_LENGTH: 2 } }); return loadPntsArrayBuffer(arrayBuffer).then(function(loader) { const components = loader.components; const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(3); expectPosition(attributes[0]); expectDefaultColor(attributes[1]); expectBatchId(attributes[2], import__732.ComponentDatatype.UNSIGNED_SHORT); }); }); it("loads PointCloudWithPerPointProperties", function() { return loadPnts(pointCloudWithPerPointPropertiesUrl).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); const isBatched = false; expectMetadata( components.structuralMetadata, { temperature: { type: import__732.MetadataType.SCALAR, componentType: import__732.MetadataComponentType.FLOAT32 }, secondaryColor: { type: import__732.MetadataType.VEC3, componentType: import__732.MetadataComponentType.FLOAT32 }, id: { type: import__732.MetadataType.SCALAR, componentType: import__732.MetadataComponentType.UINT16 } }, isBatched ); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(5); expectPosition(attributes[0]); expectColorRGB(attributes[1]); }); }); it("loads PointCloudWithUnicodePropertyIds", function() { return loadPnts(pointCloudWithUnicodePropertyIdsUrl).then(function(loader) { const components = loader.components; expect(components).toBeDefined(); const isBatched = false; expectMetadata( components.structuralMetadata, { // Originally "temperature ℃", but sanitized for GLSL temperature_: { type: import__732.MetadataType.SCALAR, componentType: import__732.MetadataComponentType.FLOAT32 }, secondaryColor: { type: import__732.MetadataType.VEC3, componentType: import__732.MetadataComponentType.FLOAT32 }, id: { type: import__732.MetadataType.SCALAR, componentType: import__732.MetadataComponentType.UINT16 } }, isBatched ); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(5); expectPosition(attributes[0]); expectColorRGB(attributes[1]); }); }); it("loads attributes for 2D", function() { return loadPnts(pointCloudRGBUrl, { loadAttributesFor2D: true }).then( function(loader) { const components = loader.components; expect(components).toBeDefined(); expectEmptyMetadata(components.structuralMetadata); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(2); const positionAttribute = attributes[0]; expectPosition(positionAttribute); expect(positionAttribute.typedArray).toBeDefined(); expectColorRGB(attributes[1]); } ); }); it("loads attributes for 2D with Draco", function() { return loadPnts(pointCloudDracoUrl, { loadAttributesFor2D: true }).then( function(loader) { const components = loader.components; expect(components).toBeDefined(); const isBatched = false; expectMetadata( components.structuralMetadata, { secondaryColor: { type: import__732.MetadataType.VEC3, componentType: import__732.MetadataComponentType.FLOAT32 }, temperature: { type: import__732.MetadataType.SCALAR, componentType: import__732.MetadataComponentType.FLOAT32 }, id: { type: import__732.MetadataType.SCALAR, componentType: import__732.MetadataComponentType.UINT16 } }, isBatched ); const primitive = components.nodes[0].primitives[0]; const attributes = primitive.attributes; expect(attributes.length).toBe(6); const positionAttribute = attributes[0]; expectPositionQuantized(positionAttribute); expect(positionAttribute.typedArray).toBeDefined(); expectNormalOctEncoded( attributes[1], import__732.ComponentDatatype.UNSIGNED_BYTE, true ); expectColorRGB(attributes[2]); } ); }); it("throws with invalid version", async function() { const arrayBuffer = Cesium3DTilesTester_default.generatePointCloudTileBuffer({ version: 2 }); await expectLoadError(arrayBuffer); }); it("throws if featureTableJsonByteLength is 0", async function() { const arrayBuffer = Cesium3DTilesTester_default.generatePointCloudTileBuffer({ featureTableJsonByteLength: 0 }); await expectLoadError(arrayBuffer); }); it("throws if the feature table does not contain POINTS_LENGTH", async function() { const arrayBuffer = Cesium3DTilesTester_default.generatePointCloudTileBuffer({ featureTableJson: { POSITION: { byteOffset: 0 } } }); await expectLoadError(arrayBuffer); }); it("throws if the feature table does not contain POSITION or POSITION_QUANTIZED", async function() { const arrayBuffer = Cesium3DTilesTester_default.generatePointCloudTileBuffer({ featureTableJson: { POINTS_LENGTH: 1 } }); await expectLoadError(arrayBuffer); }); it("throws if the positions are quantized and the feature table does not contain QUANTIZED_VOLUME_SCALE", async function() { const arrayBuffer = Cesium3DTilesTester_default.generatePointCloudTileBuffer({ featureTableJson: { POINTS_LENGTH: 1, POSITION_QUANTIZED: { byteOffset: 0 }, QUANTIZED_VOLUME_OFFSET: [0, 0, 0] } }); await expectLoadError(arrayBuffer); }); it("throws if the positions are quantized and the feature table does not contain QUANTIZED_VOLUME_OFFSET", async function() { const arrayBuffer = Cesium3DTilesTester_default.generatePointCloudTileBuffer({ featureTableJson: { POINTS_LENGTH: 1, POSITION_QUANTIZED: { byteOffset: 0 }, QUANTIZED_VOLUME_SCALE: [1, 1, 1] } }); await expectLoadError(arrayBuffer); }); it("throws if the BATCH_ID semantic is defined but BATCH_LENGTH is not", async function() { const arrayBuffer = Cesium3DTilesTester_default.generatePointCloudTileBuffer({ featureTableJson: { POINTS_LENGTH: 2, POSITION: [0, 0, 0, 1, 1, 1], BATCH_ID: [0, 1] } }); await expectLoadError(arrayBuffer); }); it("error decoding a draco point cloud causes loading to fail", async function() { const readyPromise = pollToPromise_default(function() { return import__732.DracoLoader._taskProcessorReady; }); import__732.DracoLoader._getDecoderTaskProcessor(); await readyPromise; const decoder = import__732.DracoLoader._getDecoderTaskProcessor(); spyOn(decoder, "scheduleTask").and.callFake(function() { return Promise.reject({ message: "my error" }); }); await expectAsync(loadPnts(pointCloudDracoUrl)).toBeRejectedWithError( import__732.RuntimeError, "Failed to load Draco pnts\nmy error" ); }); it("destroys pnts loader", function() { return loadPnts(pointCloudBatchedUrl).then(function(loader) { expect(loader.components).toBeDefined(); expect(loader.isDestroyed()).toBe(false); loader.destroy(); expect(loader.components).toBeUndefined(); expect(loader.isDestroyed()).toBe(true); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/PointCloudStylingPipelineStageSpec.js var import__733 = __toESM(require_Cesium(), 1); describe( "Scene/Model/PointCloudStylingPipelineStage", function() { let scene2; const mockPrimitive = { attributes: [ { semantic: import__733.VertexAttributeSemantic.POSITION, min: new import__733.Cartesian3(0, 0, 0), max: new import__733.Cartesian3(1, 1, 1), count: 64 } ] }; const mockPrimitiveWithNormals = { attributes: [ { semantic: import__733.VertexAttributeSemantic.POSITION, min: new import__733.Cartesian3(0, 0, 0), max: new import__733.Cartesian3(1, 1, 1), count: 64 }, { semantic: import__733.VertexAttributeSemantic.NORMAL, min: new import__733.Cartesian3(-1, -1, -1), max: new import__733.Cartesian3(1, 1, 1), count: 64 } ] }; const mockRuntimeNode = { // prettier-ignore transform: new import__733.Matrix4( 2, 0, 0, 1, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1 ) }; function mockGltfRenderResources(pointCloudShading) { const shaderBuilder = new import__733.ShaderBuilder(); const uniformMap = {}; const mockModel = { type: import__733.ModelType.GLTF, pointCloudShading }; return { shaderBuilder, uniformMap, runtimeNode: mockRuntimeNode, model: mockModel }; } function mockPntsRenderResources(options) { const pointCloudShading = (0, import__733.defaultValue)( options.pointCloudShading, new import__733.PointCloudShading() ); const shaderBuilder = new import__733.ShaderBuilder(); const uniformMap = {}; const mockModel = { type: import__733.ModelType.TILE_PNTS, content: options.content, style: options.style, pointCloudShading, structuralMetadata: options.structuralMetadata, featureTableId: options.featureTableId, featureTables: options.featureTables }; return { shaderBuilder, uniformMap, runtimeNode: mockRuntimeNode, model: mockModel, alphaOptions: {} }; } const functionParameterList = "(ProcessedAttributes attributes, Metadata metadata, float tiles3d_tileset_time)"; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { scene2.morphTo3D(0); scene2.camera = new import__733.Camera(scene2); scene2.renderForSpecs(); }); it("adds common uniform and code to the shader", function() { const pointCloudShading = new import__733.PointCloudShading(); const renderResources = mockGltfRenderResources(pointCloudShading); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, scene2.frameState ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform vec4 model_pointCloudParameters;" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); expect(uniformMap.model_pointCloudParameters).toBeDefined(); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__733._shadersPointCloudStylingStageVS ]); }); it("applies color style in shader", function() { const renderResources = mockPntsRenderResources({ style: new import__733.Cesium3DTileStyle({ color: 'color("red")' }), content: { tile: { refine: import__733.Cesium3DTileRefine.ADD }, tileset: { maximumScreenSpaceError: 16 } } }); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, scene2.frameState ); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "vec4 v_pointCloudColor;" ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_POINT_CLOUD_COLOR_STYLE", "COMPUTE_POSITION_WC_STYLE" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_POINT_CLOUD_COLOR_STYLE" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform vec4 model_pointCloudParameters;" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); expect(uniformMap.model_pointCloudParameters).toBeDefined(); ShaderBuilderTester_default.expectVertexLinesContains( shaderBuilder, `vec4 getColorFromStyle${functionParameterList}` ); }); it("adjusts render options for translucent color style", function() { const renderResources = mockPntsRenderResources({ style: new import__733.Cesium3DTileStyle({ color: "rgba(255, 0, 0, 0.005)" }), content: { tile: { refine: import__733.Cesium3DTileRefine.ADD }, tileset: { maximumScreenSpaceError: 16 } } }); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, scene2.frameState ); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "vec4 v_pointCloudColor;" ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_POINT_CLOUD_COLOR_STYLE", "COMPUTE_POSITION_WC_STYLE" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_POINT_CLOUD_COLOR_STYLE" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform vec4 model_pointCloudParameters;" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); expect(uniformMap.model_pointCloudParameters).toBeDefined(); ShaderBuilderTester_default.expectVertexLinesContains( shaderBuilder, `vec4 getColorFromStyle${functionParameterList}` ); expect(renderResources.alphaOptions.pass).toEqual(import__733.Pass.TRANSLUCENT); }); it("applies point size style in shader", function() { const renderResources = mockPntsRenderResources({ style: new import__733.Cesium3DTileStyle({ pointSize: 5 }), content: { tile: { refine: import__733.Cesium3DTileRefine.ADD }, tileset: { maximumScreenSpaceError: 16 } } }); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, scene2.frameState ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_POINT_CLOUD_POINT_SIZE_STYLE", "COMPUTE_POSITION_WC_STYLE" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform vec4 model_pointCloudParameters;" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); expect(uniformMap.model_pointCloudParameters).toBeDefined(); ShaderBuilderTester_default.expectVertexLinesContains( shaderBuilder, `float getPointSizeFromStyle${functionParameterList}` ); }); it("applies show style in shader", function() { const renderResources = mockPntsRenderResources({ style: new import__733.Cesium3DTileStyle({ show: false }), content: { tile: { refine: import__733.Cesium3DTileRefine.ADD }, tileset: { maximumScreenSpaceError: 16 } } }); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, scene2.frameState ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_POINT_CLOUD_SHOW_STYLE", "COMPUTE_POSITION_WC_STYLE" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform vec4 model_pointCloudParameters;" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); expect(uniformMap.model_pointCloudParameters).toBeDefined(); ShaderBuilderTester_default.expectVertexLinesContains( shaderBuilder, `bool getShowFromStyle${functionParameterList}` ); }); it("substitutes position name in shader", function() { const renderResources = mockPntsRenderResources({ style: new import__733.Cesium3DTileStyle({ show: "${POSITION}[0] > 0.5" }), content: { tile: { refine: import__733.Cesium3DTileRefine.ADD }, tileset: { maximumScreenSpaceError: 16 } } }); const shaderBuilder = renderResources.shaderBuilder; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, scene2.frameState ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_POINT_CLOUD_SHOW_STYLE", "COMPUTE_POSITION_WC_STYLE" ]); ShaderBuilderTester_default.expectVertexLinesContains( shaderBuilder, `bool getShowFromStyle${functionParameterList}` ); ShaderBuilderTester_default.expectVertexLinesContains( shaderBuilder, "attributes.positionMC" ); }); it("substitutes absolute position name in shader", function() { const renderResources = mockPntsRenderResources({ style: new import__733.Cesium3DTileStyle({ color: "vec4(${POSITION_ABSOLUTE} / 100000.0, 1.0)" }), content: { tile: { refine: import__733.Cesium3DTileRefine.ADD }, tileset: { maximumScreenSpaceError: 16 } } }); const shaderBuilder = renderResources.shaderBuilder; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, scene2.frameState ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_POINT_CLOUD_COLOR_STYLE", "COMPUTE_POSITION_WC_STYLE" ]); ShaderBuilderTester_default.expectVertexLinesContains( shaderBuilder, `vec4 getColorFromStyle${functionParameterList}` ); ShaderBuilderTester_default.expectVertexLinesContains( shaderBuilder, "v_positionWC" ); }); it("substitutes normal name in shader", function() { const renderResources = mockPntsRenderResources({ style: new import__733.Cesium3DTileStyle({ color: "vec4(${NORMAL}, 1.0)" }), content: { tile: { refine: import__733.Cesium3DTileRefine.ADD }, tileset: { maximumScreenSpaceError: 16 } } }); const shaderBuilder = renderResources.shaderBuilder; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitiveWithNormals, scene2.frameState ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_POINT_CLOUD_COLOR_STYLE", "COMPUTE_POSITION_WC_STYLE" ]); ShaderBuilderTester_default.expectVertexLinesContains( shaderBuilder, `vec4 getColorFromStyle${functionParameterList}` ); ShaderBuilderTester_default.expectVertexLinesContains( shaderBuilder, "attributes.normalMC" ); }); it("substitutes color name in shader", function() { const renderResources = mockPntsRenderResources({ style: new import__733.Cesium3DTileStyle({ color: "vec4(${COLOR}[0], 0.0, 1.0, 1.0)" }), content: { tile: { refine: import__733.Cesium3DTileRefine.ADD }, tileset: { maximumScreenSpaceError: 16 } } }); const shaderBuilder = renderResources.shaderBuilder; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, scene2.frameState ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_POINT_CLOUD_COLOR_STYLE", "COMPUTE_POSITION_WC_STYLE" ]); ShaderBuilderTester_default.expectVertexLinesContains( shaderBuilder, `vec4 getColorFromStyle${functionParameterList}` ); ShaderBuilderTester_default.expectVertexLinesContains( shaderBuilder, "attributes.color_0" ); }); it("throws if style uses normals but primitive has none", function() { const renderResources = mockPntsRenderResources({ style: new import__733.Cesium3DTileStyle({ color: "vec4(${NORMAL}, 1.0)" }), content: { tile: { refine: import__733.Cesium3DTileRefine.ADD }, tileset: { maximumScreenSpaceError: 16 } } }); expect(function() { import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, scene2.frameState ); }).toThrowError(import__733.RuntimeError); }); it("substitutes metadata name in shader", function() { const renderResources = mockPntsRenderResources({ style: new import__733.Cesium3DTileStyle({ color: "vec4(${temperature}, 0.0, 0.0, 1.0)", show: "${id} > 5" }), content: { tile: { refine: import__733.Cesium3DTileRefine.ADD }, tileset: { maximumScreenSpaceError: 16 } }, structuralMetadata: { propertyAttributes: [ { properties: { temperature: {}, id: {} } } ] } }); const shaderBuilder = renderResources.shaderBuilder; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, scene2.frameState ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_POINT_CLOUD_COLOR_STYLE", "HAS_POINT_CLOUD_SHOW_STYLE", "COMPUTE_POSITION_WC_STYLE" ]); ShaderBuilderTester_default.expectVertexLinesContains( shaderBuilder, `bool getShowFromStyle${functionParameterList}` ); ShaderBuilderTester_default.expectVertexLinesContains( shaderBuilder, `vec4 getColorFromStyle${functionParameterList}` ); ShaderBuilderTester_default.expectVertexLinesContains( shaderBuilder, "metadata.temperature" ); ShaderBuilderTester_default.expectVertexLinesContains( shaderBuilder, "metadata.id" ); }); it("propogates tileset time to the shader", function() { const renderResources = mockPntsRenderResources({ style: new import__733.Cesium3DTileStyle({ color: "vec4(fract(${tiles3d_tileset_time}), 0.0, 0.0, 1.0)", pointSize: 5 }), content: { tile: { refine: import__733.Cesium3DTileRefine.ADD }, tileset: { maximumScreenSpaceError: 16, timeSinceLoad: 5 } } }); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, scene2.frameState ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_POINT_CLOUD_COLOR_STYLE", "HAS_POINT_CLOUD_POINT_SIZE_STYLE", "COMPUTE_POSITION_WC_STYLE" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform vec4 model_pointCloudParameters;" ]); const parameters = uniformMap.model_pointCloudParameters(); expect(parameters.w).toBe(5); }); it("does not apply style if model has feature table", function() { const renderResources = mockPntsRenderResources({ style: new import__733.Cesium3DTileStyle({ show: false }), content: { tile: { refine: import__733.Cesium3DTileRefine.ADD }, tileset: { maximumScreenSpaceError: 16 } }, featureTableId: 0, featureTables: [ { featuresLength: 1 } ] }); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, scene2.frameState ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform vec4 model_pointCloudParameters;" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); expect(uniformMap.model_pointCloudParameters).toBeDefined(); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__733._shadersPointCloudStylingStageVS ]); }); it("adds point cloud back face culling define to the shader", function() { const pointCloudShading = new import__733.PointCloudShading({ backFaceCulling: true }); const renderResources = mockGltfRenderResources(pointCloudShading); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, scene2.frameState ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_POINT_CLOUD_BACK_FACE_CULLING" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform vec4 model_pointCloudParameters;" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); expect(uniformMap.model_pointCloudParameters).toBeDefined(); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__733._shadersPointCloudStylingStageVS ]); }); it("adds attenuation define to the shader", function() { const pointCloudShading = new import__733.PointCloudShading({ attenuation: true }); const renderResources = mockGltfRenderResources(pointCloudShading); const shaderBuilder = renderResources.shaderBuilder; const uniformMap = renderResources.uniformMap; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, scene2.frameState ); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_POINT_CLOUD_ATTENUATION" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform vec4 model_pointCloudParameters;" ]); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); expect(uniformMap.model_pointCloudParameters).toBeDefined(); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__733._shadersPointCloudStylingStageVS ]); }); it("point size is determined by maximumAttenuation", function() { const pointCloudShading = new import__733.PointCloudShading({ attenuation: true, maximumAttenuation: 4 }); const renderResources = mockGltfRenderResources(pointCloudShading); const uniformMap = renderResources.uniformMap; const frameState2 = scene2.frameState; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, frameState2 ); const attenuation = uniformMap.model_pointCloudParameters(); expect(attenuation.x).toEqual(4 * frameState2.pixelRatio); }); it("point size defaults to 5dp for 3D Tiles with additive refinement", function() { const pointCloudShading = new import__733.PointCloudShading({ attenuation: true, maximumAttenuation: void 0 }); const renderResources = mockPntsRenderResources({ pointCloudShading, content: { tile: { refine: import__733.Cesium3DTileRefine.ADD }, tileset: { maximumScreenSpaceError: 16 } } }); const uniformMap = renderResources.uniformMap; const frameState2 = scene2.frameState; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, frameState2 ); const attenuation = uniformMap.model_pointCloudParameters(); expect(attenuation.x).toEqual(5 * frameState2.pixelRatio); }); it("point size defaults to tileset.maximumScreenSpaceError for 3D Tiles with replace refinement", function() { const pointCloudShading = new import__733.PointCloudShading({ attenuation: true, maximumAttenuation: void 0 }); const renderResources = mockPntsRenderResources({ pointCloudShading, content: { tile: { refine: import__733.Cesium3DTileRefine.REPLACE }, tileset: { maximumScreenSpaceError: 16, memoryAdjustedScreenSpaceError: 16 } } }); const uniformMap = renderResources.uniformMap; const frameState2 = scene2.frameState; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, frameState2 ); const attenuation = uniformMap.model_pointCloudParameters(); expect(attenuation.x).toEqual(16 * frameState2.pixelRatio); }); it("point size defaults to 1dp when maximumAttenuation is not defined", function() { const pointCloudShading = new import__733.PointCloudShading({ attenuation: true, maximumAttenuation: void 0 }); const renderResources = mockGltfRenderResources(pointCloudShading); const uniformMap = renderResources.uniformMap; const frameState2 = scene2.frameState; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, frameState2 ); const attenuation = uniformMap.model_pointCloudParameters(); expect(attenuation.x).toEqual(frameState2.pixelRatio); }); it("scales geometricError", function() { const pointCloudShading = new import__733.PointCloudShading({ attenuation: true, geometricErrorScale: 2 }); const renderResources = mockPntsRenderResources({ pointCloudShading, content: { tile: { geometricError: 3, refine: import__733.Cesium3DTileRefine.ADD }, tileset: {} } }); const uniformMap = renderResources.uniformMap; const frameState2 = scene2.frameState; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, frameState2 ); const attenuation = uniformMap.model_pointCloudParameters(); expect(attenuation.y).toEqual(6); }); it("uses tile geometric error when available", function() { const pointCloudShading = new import__733.PointCloudShading({ attenuation: true, geometricErrorScale: 1 }); const renderResources = mockPntsRenderResources({ pointCloudShading, content: { tile: { geometricError: 3, refine: import__733.Cesium3DTileRefine.ADD }, tileset: {} } }); const uniformMap = renderResources.uniformMap; const frameState2 = scene2.frameState; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, frameState2 ); const attenuation = uniformMap.model_pointCloudParameters(); expect(attenuation.y).toEqual(3); }); it("uses baseResolution when tile geometric error is 0", function() { const pointCloudShading = new import__733.PointCloudShading({ attenuation: true, geometricErrorScale: 1, baseResolution: 4 }); const renderResources = mockPntsRenderResources({ pointCloudShading, content: { tile: { geometricError: 0, refine: import__733.Cesium3DTileRefine.ADD }, tileset: {} } }); const uniformMap = renderResources.uniformMap; const frameState2 = scene2.frameState; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, frameState2 ); const attenuation = uniformMap.model_pointCloudParameters(); expect(attenuation.y).toEqual(4); }); it("uses baseResolution for glTF models", function() { const pointCloudShading = new import__733.PointCloudShading({ attenuation: true, geometricErrorScale: 1, baseResolution: 4 }); const renderResources = mockGltfRenderResources(pointCloudShading); const uniformMap = renderResources.uniformMap; const frameState2 = scene2.frameState; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, frameState2 ); const attenuation = uniformMap.model_pointCloudParameters(); expect(attenuation.y).toEqual(4); }); it("estimates geometric error when baseResolution is not available", function() { const pointCloudShading = new import__733.PointCloudShading({ attenuation: true, geometricErrorScale: 1, baseResolution: void 0 }); const renderResources = mockGltfRenderResources(pointCloudShading); const uniformMap = renderResources.uniformMap; const frameState2 = scene2.frameState; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, frameState2 ); const attenuation = uniformMap.model_pointCloudParameters(); const volume = 8; const pointsLength = 64; const expected = import__733.Math.cbrt(volume / pointsLength); expect(attenuation.y).toEqual(expected); }); it("computes depth multiplier from drawing buffer and frustum", function() { const pointCloudShading = new import__733.PointCloudShading({ attenuation: true }); const renderResources = mockGltfRenderResources(pointCloudShading); const uniformMap = renderResources.uniformMap; const frameState2 = scene2.frameState; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, frameState2 ); const attenuation = uniformMap.model_pointCloudParameters(); const expected = scene2.context.drawingBufferHeight / scene2.camera.frustum.sseDenominator; expect(attenuation.z).toEqual(expected); }); it("depth multiplier is set to positive infinity when in 2D mode", function() { scene2.morphTo2D(0); scene2.renderForSpecs(); const pointCloudShading = new import__733.PointCloudShading({ attenuation: true }); const renderResources = mockGltfRenderResources(pointCloudShading); const uniformMap = renderResources.uniformMap; const frameState2 = scene2.frameState; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, frameState2 ); const attenuation = uniformMap.model_pointCloudParameters(); expect(attenuation.z).toEqual(Number.POSITIVE_INFINITY); }); it("depth multiplier is set to positive infinity when the camera uses orthographic projection", function() { const camera = scene2.camera; camera.frustum = new import__733.OrthographicFrustum(); camera.frustum.aspectRatio = scene2.drawingBufferWidth / scene2.drawingBufferHeight; camera.frustum.width = camera.positionCartographic.height; scene2.renderForSpecs(); const pointCloudShading = new import__733.PointCloudShading({ attenuation: true }); const renderResources = mockGltfRenderResources(pointCloudShading); const uniformMap = renderResources.uniformMap; const frameState2 = scene2.frameState; import__733.PointCloudStylingPipelineStage.process( renderResources, mockPrimitive, frameState2 ); const attenuation = uniformMap.model_pointCloudParameters(); expect(attenuation.z).toBe(Number.POSITIVE_INFINITY); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/PrimitiveLoadPlanSpec.js var import__734 = __toESM(require_Cesium(), 1); describe( "Scene/Model/PrimitiveLoadPlan", function() { function mockPrimitive() { const primitive = new import__734.ModelComponents.Primitive(); const position = new import__734.ModelComponents.Attribute(); position.count = 4; position.typedArray = new Float32Array([ 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0 ]); const indices = new import__734.ModelComponents.Indices(); indices.typedArray = new Uint8Array([ 0, 1, 2, 0, 2, 3 ]); primitive.attributes.push(position); primitive.indices = indices; return primitive; } function mockLoadPlan() { const primitive = mockPrimitive(); const loadPlan = new import__734.PrimitiveLoadPlan(primitive); loadPlan.indicesPlan = new import__734.PrimitiveLoadPlan.IndicesLoadPlan( primitive.indices ); const [positions] = primitive.attributes; loadPlan.attributePlans.push( new import__734.PrimitiveLoadPlan.AttributeLoadPlan(positions) ); return loadPlan; } const mockOutlineIndices = [ 0, 1, 1, 2, 2, 3 ]; const buffers = []; function expectOutlineCoordinates(primitive, outlineCoordinatesPlan) { expect(outlineCoordinatesPlan.loadBuffer).toBe(true); expect(outlineCoordinatesPlan.loadTypedArray).toBe(false); const attribute = outlineCoordinatesPlan.attribute; expect(attribute.name).toBe("_OUTLINE_COORDINATES"); expect(attribute.buffer).toBeDefined(); buffers.push(attribute.buffer); expect(attribute.typedArray).not.toBeDefined(); expect(attribute.type).toBe(import__734.AttributeType.VEC3); expect(attribute.normalized).toBe(false); expect(attribute.count).toBe(5); expect(primitive.outlineCoordinates).toBe(attribute); } let context; beforeAll(function() { context = createContext_default(); }); afterEach(function() { const length2 = buffers.length; for (let i = 0; i < length2; i++) { const buffer = buffers[i]; if (!buffer.isDestroyed()) { buffer.destroy(); } } buffers.length = 0; }); it("AttributeLoadPlan throws for undefined primitive", function() { expect(function() { return new import__734.PrimitiveLoadPlan.AttributeLoadPlan(void 0); }).toThrowDeveloperError(); }); it("AttributeLoadPlan constructs", function() { const attribute = new import__734.ModelComponents.Attribute(); const attributePlan = new import__734.PrimitiveLoadPlan.AttributeLoadPlan(attribute); expect(attributePlan.attribute).toBe(attribute); expect(attributePlan.loadBuffer).toBe(false); expect(attributePlan.loadTypedArray).toBe(false); }); it("IndicesLoadPlan throws for undefined indices", function() { expect(function() { return new import__734.PrimitiveLoadPlan.IndicesLoadPlan(void 0); }).toThrowDeveloperError(); }); it("IndicesLoadPlan constructs", function() { const indices = new import__734.ModelComponents.Indices(); const indicesPlan = new import__734.PrimitiveLoadPlan.IndicesLoadPlan(indices); expect(indicesPlan.indices).toBe(indices); expect(indicesPlan.loadBuffer).toBe(false); expect(indicesPlan.loadTypedArray).toBe(false); }); it("PrimitiveLoadPlan throws for undefined primitive", function() { expect(function() { return new import__734.PrimitiveLoadPlan(void 0); }).toThrowDeveloperError(); }); it("PrimitiveLoadPlan constructs", function() { const primitive = mockPrimitive(); const loadPlan = new import__734.PrimitiveLoadPlan(primitive); expect(loadPlan.primitive).toBe(primitive); expect(loadPlan.attributePlans).toEqual([]); expect(loadPlan.indicesPlan).not.toBeDefined(); }); it("postProcess does nothing if there are no outlines", function() { const loadPlan = mockLoadPlan(); const [positionPlan] = loadPlan.attributePlans; const indicesPlan = loadPlan.indicesPlan; positionPlan.loadBuffer = true; indicesPlan.loadBuffer = true; loadPlan.postProcess(context); expect(loadPlan.attributePlans.length).toBe(1); const [outputPositionPlan] = loadPlan.attributePlans; expect(outputPositionPlan).toBe(positionPlan); expect(positionPlan.attribute.buffer).not.toBeDefined(); expect(indicesPlan.indices.buffer).not.toBeDefined(); }); it("postProcess processes CESIUM_primitive_outline as a buffer", function() { const loadPlan = mockLoadPlan(); const [positionPlan] = loadPlan.attributePlans; const indicesPlan = loadPlan.indicesPlan; loadPlan.needsOutlines = true; loadPlan.outlineIndices = mockOutlineIndices; positionPlan.loadBuffer = true; indicesPlan.loadBuffer = true; loadPlan.postProcess(context); expect(loadPlan.attributePlans.length).toBe(2); const [ outputPositionPlan, outlineCoordinatesPlan ] = loadPlan.attributePlans; expect(outputPositionPlan).toBe(positionPlan); expectOutlineCoordinates(loadPlan.primitive, outlineCoordinatesPlan); const attribute = positionPlan.attribute; expect(attribute.buffer).toBeDefined(); buffers.push(attribute.buffer); expect(attribute.typedArray).not.toBeDefined(); const indices = indicesPlan.indices; expect(indices.buffer).toBeDefined(); buffers.push(indices.buffer); expect(indices.typedArray).not.toBeDefined(); }); it("postProcess processes CESIUM_primitive_outline as typed arrays", function() { const loadPlan = mockLoadPlan(); const [positionPlan] = loadPlan.attributePlans; const indicesPlan = loadPlan.indicesPlan; const originalPositions = positionPlan.attribute.typedArray.slice(); loadPlan.needsOutlines = true; loadPlan.outlineIndices = mockOutlineIndices; positionPlan.loadTypedArray = true; indicesPlan.loadTypedArray = true; loadPlan.postProcess(context); expect(loadPlan.attributePlans.length).toBe(2); const [ outputPositionPlan, outlineCoordinatesPlan ] = loadPlan.attributePlans; expect(outputPositionPlan).toBe(positionPlan); expectOutlineCoordinates(loadPlan.primitive, outlineCoordinatesPlan); const attribute = positionPlan.attribute; expect(attribute.buffer).not.toBeDefined(); const originalLength = originalPositions.length; const expectedPositions = new Float32Array(originalLength + 3); expectedPositions.set(originalPositions); expectedPositions[originalLength] = originalPositions[0]; expectedPositions[originalLength + 1] = originalPositions[1]; expectedPositions[originalLength + 2] = originalPositions[2]; expect(attribute.typedArray).toEqual(expectedPositions); const indices = indicesPlan.indices; expect(indices.buffer).not.toBeDefined(); const expectedIndices = new Uint8Array([ 0, 1, 2, 4, 2, 3 // 4 is a copy of vertex 0 ]); expect(indices.typedArray).toEqual(expectedIndices); }); it("postProcess processes CESIUM_primitive_outline as both a buffer and typed array", function() { const loadPlan = mockLoadPlan(); const [positionPlan] = loadPlan.attributePlans; const indicesPlan = loadPlan.indicesPlan; const originalPositions = positionPlan.attribute.typedArray.slice(); loadPlan.needsOutlines = true; loadPlan.outlineIndices = mockOutlineIndices; positionPlan.loadBuffer = true; positionPlan.loadTypedArray = true; indicesPlan.loadBuffer = true; indicesPlan.loadTypedArray = true; loadPlan.postProcess(context); expect(loadPlan.attributePlans.length).toBe(2); const [ outputPositionPlan, outlineCoordinatesPlan ] = loadPlan.attributePlans; expect(outputPositionPlan).toBe(positionPlan); expectOutlineCoordinates(loadPlan.primitive, outlineCoordinatesPlan); const attribute = positionPlan.attribute; expect(attribute.buffer).toBeDefined(); buffers.push(attribute.buffer); const originalLength = originalPositions.length; const expectedPositions = new Float32Array(originalLength + 3); expectedPositions.set(originalPositions); expectedPositions[originalLength] = originalPositions[0]; expectedPositions[originalLength + 1] = originalPositions[1]; expectedPositions[originalLength + 2] = originalPositions[2]; expect(attribute.typedArray).toEqual(expectedPositions); const indices = indicesPlan.indices; expect(indices.buffer).toBeDefined(); buffers.push(indices.buffer); const expectedIndices = new Uint8Array([ 0, 1, 2, 4, 2, 3 // 4 is a copy of vertex 0 ]); expect(indices.typedArray).toEqual(expectedIndices); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/PrimitiveOutlineGeneratorSpec.js var import__735 = __toESM(require_Cesium(), 1); describe( "Scene/Model/PrimitiveOutlineGenerator", function() { it("throws for undefined triangleIndices", function() { expect(function() { return new import__735.PrimitiveOutlineGenerator({ triangleIndices: void 0, outlineIndices: new Uint16Array(36), originalVertexCount: 6 }); }).toThrowDeveloperError(); }); it("throws for undefined outlineIndices", function() { expect(function() { return new import__735.PrimitiveOutlineGenerator({ triangleIndices: new Uint16Array(12), outlineIndices: void 0, originalVertexCount: 6 }); }).toThrowDeveloperError(); }); it("throws for undefined originalVertexCount", function() { expect(function() { return new import__735.PrimitiveOutlineGenerator({ triangleIndices: new Uint16Array(12), outlineIndices: new Uint16Array(36), originalVertexCount: void 0 }); }).toThrowDeveloperError(); }); function addVertex(vertices, position) { const index = vertices.length / 3; vertices.push(position.x, position.y, position.z); return index; } function createGeometry() { const p0 = new import__735.Cartesian3(-1, -1, 0); const p1 = new import__735.Cartesian3(0, -1, 0); const p2 = new import__735.Cartesian3(1, -1, 0); const p3 = new import__735.Cartesian3(-1, 0, 0); const p4 = new import__735.Cartesian3(0, 0, 0); const p5 = new import__735.Cartesian3(1, 0, 0); const p6 = new import__735.Cartesian3(-1, 1, 0); const p7 = new import__735.Cartesian3(0, 1, 0); const p8 = new import__735.Cartesian3(1, 1, 0); const vertices = []; const i0 = addVertex(vertices, p0); const i1 = addVertex(vertices, p1); const i2 = addVertex(vertices, p2); const i3 = addVertex(vertices, p3); const i4 = addVertex(vertices, p4); const i5 = addVertex(vertices, p5); const i6 = addVertex(vertices, p6); const i7 = addVertex(vertices, p7); const i8 = addVertex(vertices, p8); const verticesTypedArray = new Float32Array(vertices); const indices = []; indices.push(i0, i1, i4); indices.push(i0, i4, i3); indices.push(i1, i2, i4); indices.push(i4, i2, i5); indices.push(i3, i4, i6); indices.push(i6, i4, i7); indices.push(i4, i5, i8); indices.push(i4, i8, i7); const indicesTypedArray = new Uint8Array(indices); const edges = []; edges.push(i0, i1); edges.push(i1, i2); edges.push(i2, i5); edges.push(i5, i8); edges.push(i8, i7); edges.push(i7, i6); edges.push(i6, i3); const edgesTypedArray = new Uint8Array(edges); return { vertices: verticesTypedArray, edges: edgesTypedArray, indices: indicesTypedArray }; } function createTrickyGeometry() { const p0 = new import__735.Cartesian3(-1, 1, 0); const p1 = new import__735.Cartesian3(-2, 2, 0); const p2 = new import__735.Cartesian3(-1, 2, 0); const p3 = new import__735.Cartesian3(1, 1, 0); const p4 = new import__735.Cartesian3(2, 2, 0); const p5 = new import__735.Cartesian3(1, 2, 0); const p6 = new import__735.Cartesian3(0, 0, 0); const p7 = new import__735.Cartesian3(-1, -1, 0); const p8 = new import__735.Cartesian3(-1, 1, 0); const vertices = []; const i0 = addVertex(vertices, p0); const i1 = addVertex(vertices, p1); const i2 = addVertex(vertices, p2); const i3 = addVertex(vertices, p3); const i4 = addVertex(vertices, p4); const i5 = addVertex(vertices, p5); const i6 = addVertex(vertices, p6); const i7 = addVertex(vertices, p7); const i8 = addVertex(vertices, p8); const verticesTypedArray = new Float32Array(vertices); const indices = []; indices.push(i0, i2, i1); indices.push(i3, i4, i5); indices.push(i6, i7, i8); indices.push(i0, i6, i3); const indicesTypedArray = new Uint8Array(indices); const edges = []; edges.push(i0, i1); edges.push(i0, i2); edges.push(i3, i5); edges.push(i3, i4); edges.push(i6, i7); edges.push(i6, i8); edges.push(i0, i3); edges.push(i0, i6); edges.push(i3, i6); const edgesTypedArray = new Uint8Array(edges); return { vertices: verticesTypedArray, indices: indicesTypedArray, edges: edgesTypedArray }; } function createLargerGeometry(targetVertexCount) { const vertexCount = 9; const copies = Math.floor(targetVertexCount / vertexCount); const vertices = []; const indices = []; const edges = []; for (let i = 0; i < copies; i++) { const p0 = new import__735.Cartesian3(-1, -1, 0); const p1 = new import__735.Cartesian3(0, -1, 0); const p2 = new import__735.Cartesian3(1, -1, 0); const p3 = new import__735.Cartesian3(-1, 0, 0); const p4 = new import__735.Cartesian3(0, 0, 0); const p5 = new import__735.Cartesian3(1, 0, 0); const p6 = new import__735.Cartesian3(-1, 1, 0); const p7 = new import__735.Cartesian3(0, 1, 0); const p8 = new import__735.Cartesian3(1, 1, 0); const i0 = addVertex(vertices, p0); const i1 = addVertex(vertices, p1); const i2 = addVertex(vertices, p2); const i3 = addVertex(vertices, p3); const i4 = addVertex(vertices, p4); const i5 = addVertex(vertices, p5); const i6 = addVertex(vertices, p6); const i7 = addVertex(vertices, p7); const i8 = addVertex(vertices, p8); indices.push(i0, i1, i4); indices.push(i0, i4, i3); indices.push(i1, i2, i4); indices.push(i4, i2, i5); indices.push(i3, i4, i6); indices.push(i6, i4, i7); indices.push(i4, i5, i8); indices.push(i4, i8, i7); edges.push(i0, i1); edges.push(i1, i2); edges.push(i2, i5); edges.push(i5, i8); edges.push(i8, i7); edges.push(i7, i6); edges.push(i6, i3); } const verticesTypedArray = new Float32Array(vertices); let indicesTypedArray; let edgesTypedArray; if (targetVertexCount <= 255) { indicesTypedArray = new Uint8Array(indices); edgesTypedArray = new Uint8Array(edges); } else if (targetVertexCount <= 65535) { indicesTypedArray = new Uint16Array(indices); edgesTypedArray = new Uint16Array(edges); } else { indicesTypedArray = new Uint32Array(indices); edgesTypedArray = new Uint32Array(edges); } return { vertices: verticesTypedArray, edges: edgesTypedArray, indices: indicesTypedArray }; } it("duplicates vertices as needed and generates outline coordinates", function() { let geometry = createGeometry(); let vertices = geometry.vertices; let generator = new import__735.PrimitiveOutlineGenerator({ // slice because the value may be modified in place triangleIndices: geometry.indices.slice(), outlineIndices: geometry.edges, originalVertexCount: vertices.length / 3 }); let expectedIndices = new Uint8Array([ 0, 1, 4, 9, 4, 3, 1, 2, 4, 4, 2, 5, 10, 4, 6, 6, 4, 7, 4, 5, 8, 4, 8, 11 ]); let expectedOutlineCoordinates = new Float32Array([ 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0 ]); let expectedExtraVertices = [0, 3, 7]; expect(generator.updatedTriangleIndices).toEqual(expectedIndices); expect(generator.outlineCoordinates).toEqual(expectedOutlineCoordinates); expect(generator._extraVertices).toEqual(expectedExtraVertices); geometry = createTrickyGeometry(); vertices = geometry.vertices; generator = new import__735.PrimitiveOutlineGenerator({ triangleIndices: geometry.indices.slice(), outlineIndices: geometry.edges, originalVertexCount: vertices.length / 3 }); expectedIndices = new Uint8Array([ 0, 2, 1, 3, 4, 5, 6, 7, 8, 0, 10, 9 ]); expectedOutlineCoordinates = new Float32Array([ 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1 ]); expectedExtraVertices = [3, 6]; expect(generator.updatedTriangleIndices).toEqual(expectedIndices); expect(generator.outlineCoordinates).toEqual(expectedOutlineCoordinates); expect(generator._extraVertices).toEqual(expectedExtraVertices); }); it("switches to 16-bit indices if more than 255 vertices are required", function() { const geometry = createLargerGeometry(255); const vertices = geometry.vertices; expect(geometry.indices).toBeInstanceOf(Uint8Array); const generator = new import__735.PrimitiveOutlineGenerator({ // slice because the value may be modified in place triangleIndices: geometry.indices.slice(), outlineIndices: geometry.edges, originalVertexCount: vertices.length / 3 }); expect(generator.updatedTriangleIndices).toBeInstanceOf(Uint16Array); }); it("switches to 32-bit indices if more than 65535 vertices are required", function() { const geometry = createLargerGeometry(65535); const vertices = geometry.vertices; expect(geometry.indices).toBeInstanceOf(Uint16Array); const generator = new import__735.PrimitiveOutlineGenerator({ // slice because the value may be modified in place triangleIndices: geometry.indices.slice(), outlineIndices: geometry.edges, originalVertexCount: vertices.length / 3 }); expect(generator.updatedTriangleIndices).toBeInstanceOf(Uint32Array); }); it("updateAttribute copies vertex attributes", function() { let geometry = createGeometry(); let vertices = geometry.vertices; let generator = new import__735.PrimitiveOutlineGenerator({ // slice because the value may be modified in place triangleIndices: geometry.indices.slice(), outlineIndices: geometry.edges, originalVertexCount: vertices.length / 3 }); geometry = createTrickyGeometry(); vertices = geometry.vertices; let attribute = new Uint16Array([0, 1, 2, 3, 4, 5, 6, 7, 8]); let result = generator.updateAttribute(attribute); let expectedAttribute = new Uint16Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, // copy of vertex 0 3, // copy of vertex 3 7 // copy of vertex 7 ]); expect(result).toEqual(expectedAttribute); generator = new import__735.PrimitiveOutlineGenerator({ // slice because the value may be modified in place triangleIndices: geometry.indices.slice(), outlineIndices: geometry.edges, originalVertexCount: vertices.length / 3 }); attribute = new Float32Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]); result = generator.updateAttribute(attribute); expectedAttribute = new Float32Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 3, // copy of vertex 3 6 // copy of vertex 6 ]); expect(result).toEqual(expectedAttribute); }); it("updateAttribute copies vector attributes", function() { let geometry = createGeometry(); let vertices = geometry.vertices; let generator = new import__735.PrimitiveOutlineGenerator({ // slice because the value may be modified in place triangleIndices: geometry.indices.slice(), outlineIndices: geometry.edges, originalVertexCount: vertices.length / 3 }); let result = generator.updateAttribute(geometry.vertices); let expectedVertices = new Float32Array([ -1, -1, 0, 0, -1, 0, 1, -1, 0, -1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 1, 0, 0, 1, 0, 1, 1, 0, -1, -1, 0, // copy of vertex 0 -1, 0, 0, // copy of vertex 3 0, 1, 0 // copy of vertex 7 ]); expect(result).toEqual(expectedVertices); geometry = createTrickyGeometry(); vertices = geometry.vertices; generator = new import__735.PrimitiveOutlineGenerator({ // slice because the value may be modified in place triangleIndices: geometry.indices.slice(), outlineIndices: geometry.edges, originalVertexCount: vertices.length / 3 }); result = generator.updateAttribute(geometry.vertices); expectedVertices = new Float32Array([ -1, 1, 0, -2, 2, 0, -1, 2, 0, 1, 1, 0, 2, 2, 0, 1, 2, 0, 0, 0, 0, -1, -1, 0, -1, 1, 0, 1, 1, 0, // copy of vertex 3 0, 0, 0 // copy of vertex 6 ]); expect(result).toEqual(expectedVertices); }); describe("createTexture", function() { let context; beforeEach(function() { if ((0, import__735.defined)(context)) { context.destroyForSpecs(); } context = createContext_default(); }); it("createTexture creates texture on the first run", function() { const cache = context.cache; expect(cache.modelOutliningCache).not.toBeDefined(); const texture = import__735.PrimitiveOutlineGenerator.createTexture(context); expect(texture).toBeDefined(); expect(cache.modelOutliningCache.outlineTexture).toBe(texture); }); it("createTexture uses a cached texture on subsequent runs", function() { const cache = context.cache; expect(cache.modelOutliningCache).not.toBeDefined(); const texture = import__735.PrimitiveOutlineGenerator.createTexture(context); const texture2 = import__735.PrimitiveOutlineGenerator.createTexture(context); expect(texture2).toBe(texture); expect(texture).toBeDefined(); expect(cache.modelOutliningCache.outlineTexture).toBe(texture); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/PrimitiveOutlinePipelineStageSpec.js var import__736 = __toESM(require_Cesium(), 1); describe( "Scene/Model/PrimitiveOutlinePipelineStage", function() { const boxWithPrimitiveOutline = "./Data/Models/glTF-2.0/BoxWithPrimitiveOutline/glTF/BoxWithPrimitiveOutline.gltf"; let scene2; const gltfLoaders = []; const resources = []; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); function cleanup(resourcesArray) { for (let i = 0; i < resourcesArray.length; i++) { const resource = resourcesArray[i]; if (!resource.isDestroyed()) { resource.destroy(); } } resourcesArray.length = 0; } afterEach(function() { cleanup(resources); cleanup(gltfLoaders); import__736.ResourceCache.clearForSpecs(); }); function getOptions(gltfPath, options) { const resource = new import__736.Resource({ url: gltfPath }); return (0, import__736.combine)(options, { gltfResource: resource, incrementallyLoadTextures: false // Default to false if not supplied }); } async function loadGltf(gltfPath, options) { const gltfLoader = new import__736.GltfLoader(getOptions(gltfPath, options)); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, scene2); return gltfLoader; } function mockRenderResources() { return { model: { outlineColor: import__736.Color.RED, showOutline: false }, shaderBuilder: new import__736.ShaderBuilder(), uniformMap: {}, attributes: [], attributeIndex: 1 }; } it("Processes model with CESIUM_primitive_outline extension", function() { return loadGltf(boxWithPrimitiveOutline).then(function(gltfLoader) { const components = gltfLoader.components; const [node] = components.nodes; const [primitive] = node.primitives; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(); import__736.PrimitiveOutlinePipelineStage.process( renderResources, primitive, frameState2 ); const context = frameState2.context; const outlineTexture = context.cache.modelOutliningCache.outlineTexture; const uniformMap = renderResources.uniformMap; expect(uniformMap.model_outlineTexture()).toBe(outlineTexture); expect(uniformMap.model_outlineColor()).toBe(import__736.Color.RED); expect(uniformMap.model_showOutline()).toBe(false); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_PRIMITIVE_OUTLINE" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_PRIMITIVE_OUTLINE" ]); ShaderBuilderTester_default.expectHasAttributes(shaderBuilder, void 0, [ "in vec3 a_outlineCoordinates;" ]); ShaderBuilderTester_default.expectHasVaryings(shaderBuilder, [ "vec3 v_outlineCoordinates;" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, [ "uniform bool model_showOutline;", "uniform sampler2D model_outlineTexture;", "uniform vec4 model_outlineColor;" ]); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__736._shadersPrimitiveOutlineStageVS ]); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__736._shadersPrimitiveOutlineStageFS ]); const attributes = renderResources.attributes; expect(attributes.length).toBe(1); const [outlineCoordinates] = attributes; expect(outlineCoordinates.index).toBe(1); expect(outlineCoordinates.vertexBuffer).toBe( primitive.outlineCoordinates.buffer ); expect(outlineCoordinates.componentsPerAttribute).toBe(3); expect(outlineCoordinates.componentDatatype).toBe( import__736.ComponentDatatype.FLOAT ); expect(outlineCoordinates.offsetInBytes).toBe(0); expect(outlineCoordinates.strideInBytes).not.toBeDefined(); expect(outlineCoordinates.normalize).toBe(false); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/PrimitiveRenderResourcesSpec.js var import__737 = __toESM(require_Cesium(), 1); describe( "Scene/Model/PrimitiveRenderResources", function() { const mockModel = { modelMatrix: import__737.Matrix4.IDENTITY, type: import__737.ModelType.GLTF }; const mockNode = {}; const mockSceneGraph = { computedModelMatrix: import__737.Matrix4.IDENTITY, components: { upAxis: import__737.Axis.Y, forwardAxis: import__737.Axis.Z } }; const runtimeNode = new import__737.ModelRuntimeNode({ node: mockNode, transform: import__737.Matrix4.IDENTITY, transformToRoot: import__737.Matrix4.fromTranslation(new import__737.Cartesian3(1, 2, 3)), sceneGraph: mockSceneGraph, children: [] }); const primitive = { indices: { count: 6 }, primitiveType: import__737.PrimitiveType.TRIANGLES, featureIds: [], attributes: [ { semantic: import__737.VertexAttributeSemantic.POSITION, buffer: new Float32Array([0, 1, 2, 3, 4, 5]).buffer, type: import__737.AttributeType.VEC3, componentDatatype: import__737.ComponentDatatype.FLOAT, min: new import__737.Cartesian3(-1, -1, -1), max: new import__737.Cartesian3(1, 1, 1) } ] }; const primitiveWithoutIndices = { primitiveType: import__737.PrimitiveType.POINTS, featureIds: [], featureIdTextures: [], attributes: [ { semantic: import__737.VertexAttributeSemantic.POSITION, buffer: new Float32Array([0, 1, 2, 3, 4, 5, 6, 7, 8]).buffer, type: import__737.AttributeType.VEC3, componentDatatype: import__737.ComponentDatatype.FLOAT, count: 8, min: new import__737.Cartesian3(-2, -2, -2), max: new import__737.Cartesian3(2, 2, 2) } ] }; const defaultRenderState = import__737.RenderState.getState( import__737.RenderState.fromCache({ depthTest: { enabled: true, func: import__737.DepthFunction.LESS_OR_EQUAL } }) ); let runtimePrimitive; let runtimePrimitiveWithoutIndices; beforeAll(function() { runtimePrimitive = new import__737.ModelRuntimePrimitive({ primitive, node: mockNode, model: mockModel }); runtimePrimitiveWithoutIndices = new import__737.ModelRuntimePrimitive({ primitive: primitiveWithoutIndices, node: mockNode, model: mockModel }); }); it("throws for undefined nodeRenderResources", function() { expect(function() { return new import__737.PrimitiveRenderResources(void 0, runtimePrimitive); }).toThrowDeveloperError(); }); it("throws for undefined runtimePrimitive", function() { expect(function() { const modelResources = new import__737.ModelRenderResources(mockModel); const nodeResources = new import__737.NodeRenderResources( modelResources, runtimeNode ); return new import__737.PrimitiveRenderResources(nodeResources, void 0); }).toThrowDeveloperError(); }); it("constructs", function() { const modelResources = new import__737.ModelRenderResources(mockModel); const nodeResources = new import__737.NodeRenderResources( modelResources, runtimeNode ); const primitiveResources = new import__737.PrimitiveRenderResources( nodeResources, runtimePrimitive ); expect(primitiveResources.runtimePrimitive).toBe(runtimePrimitive); expect(primitiveResources.pickId).toBeUndefined(); expect(primitiveResources.count).toBe(6); expect(primitiveResources.indices).toBe(primitive.indices); expect(primitiveResources.primitiveType).toBe(import__737.PrimitiveType.TRIANGLES); expect(primitiveResources.positionMin).toEqual( new import__737.Cartesian3(-1, -1, -1) ); expect(primitiveResources.positionMax).toEqual(new import__737.Cartesian3(1, 1, 1)); expect(primitiveResources.boundingSphere.center).toEqualEpsilon( import__737.Cartesian3.ZERO, import__737.Math.EPSILON9 ); expect(primitiveResources.boundingSphere.radius).toEqualEpsilon( Math.sqrt(3), import__737.Math.EPSILON9 ); expect(primitiveResources.uniformMap).toEqual({}); expect(primitiveResources.lightingOptions.lightingModel).toEqual( import__737.LightingModel.UNLIT ); expect( import__737.RenderState.getState(primitiveResources.renderStateOptions) ).toEqual(defaultRenderState); expect(primitiveResources.hasSilhouette).toBe(false); expect(primitiveResources.hasSkipLevelOfDetail).toBe(false); }); it("constructs from primitive without indices", function() { const modelResources = new import__737.ModelRenderResources(mockModel); const nodeResources = new import__737.NodeRenderResources( modelResources, runtimeNode ); const primitiveResources = new import__737.PrimitiveRenderResources( nodeResources, runtimePrimitiveWithoutIndices ); expect(primitiveResources.count).toBe(8); expect(primitiveResources.indices).not.toBeDefined(); expect(primitiveResources.primitiveType).toBe(import__737.PrimitiveType.POINTS); expect(primitiveResources.positionMin).toEqual( new import__737.Cartesian3(-2, -2, -2) ); expect(primitiveResources.positionMax).toEqual(new import__737.Cartesian3(2, 2, 2)); expect(primitiveResources.boundingSphere.center).toEqualEpsilon( import__737.Cartesian3.ZERO, import__737.Math.EPSILON9 ); expect(primitiveResources.boundingSphere.radius).toEqualEpsilon( 2 * Math.sqrt(3), import__737.Math.EPSILON9 ); expect(primitiveResources.uniformMap).toEqual({}); expect(primitiveResources.lightingOptions.lightingModel).toEqual( import__737.LightingModel.UNLIT ); expect( import__737.RenderState.getState(primitiveResources.renderStateOptions) ).toEqual(defaultRenderState); }); it("inherits from model render resources", function() { const modelResources = new import__737.ModelRenderResources(mockModel); modelResources.shaderBuilder.addDefine("MODEL"); modelResources.renderStateOptions.cull = { enabled: true }; modelResources.hasSilhouette = true; modelResources.hasSkipLevelOfDetail = true; const nodeResources = new import__737.NodeRenderResources( modelResources, runtimeNode ); nodeResources.shaderBuilder.addDefine("NODE"); const primitiveResources = new import__737.PrimitiveRenderResources( nodeResources, runtimePrimitive ); primitiveResources.shaderBuilder.addDefine("PRIMITIVE"); expect(primitiveResources.model).toBe(mockModel); expect(primitiveResources.shaderBuilder).not.toBe( modelResources.shaderBuilder ); expect(primitiveResources.shaderBuilder).not.toBe( modelResources.shaderBuilder ); expect(primitiveResources.renderStateOptions.cull).toEqual({ enabled: true }); expect(primitiveResources.hasSilhouette).toBe(true); expect(primitiveResources.hasSkipLevelOfDetail).toBe(true); ShaderBuilderTester_default.expectHasFragmentDefines( modelResources.shaderBuilder, ["MODEL"] ); ShaderBuilderTester_default.expectHasFragmentDefines( nodeResources.shaderBuilder, ["MODEL", "NODE"] ); ShaderBuilderTester_default.expectHasFragmentDefines( primitiveResources.shaderBuilder, ["MODEL", "NODE", "PRIMITIVE"] ); }); it("inherits from node render resources", function() { const modelResources = new import__737.ModelRenderResources(mockModel); modelResources.shaderBuilder.addDefine("MODEL"); modelResources.renderStateOptions.cull = { enabled: true }; const nodeResources = new import__737.NodeRenderResources( modelResources, runtimeNode ); nodeResources.shaderBuilder.addDefine("NODE"); nodeResources.renderStateOptions.blending = import__737.BlendingState.ALPHA_BLEND; const primitiveResources = new import__737.PrimitiveRenderResources( nodeResources, runtimePrimitive ); expect(primitiveResources.runtimeNode).toBe(runtimeNode); expect(primitiveResources.attributes).toEqual([]); expect(primitiveResources.renderStateOptions.cull).toEqual({ enabled: true }); expect(primitiveResources.renderStateOptions.blending).toEqual( import__737.BlendingState.ALPHA_BLEND ); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/PrimitiveStatisticsPipelineStageSpec.js var import__738 = __toESM(require_Cesium(), 1); describe( "Scene/Model/PrimitiveStatisticsPipelineStage", function() { const animatedMorphCube = "./Data/Models/glTF-2.0/AnimatedMorphCube/glTF/AnimatedMorphCube.gltf"; const boomBox = "./Data/Models/glTF-2.0/BoomBox/glTF/BoomBox.gltf"; const boomBoxSpecularGlossiness = "./Data/Models/glTF-2.0/BoomBox/glTF-pbrSpecularGlossiness/BoomBox.gltf"; const boxTextured = "./Data/Models/glTF-2.0/BoxTextured/glTF-Binary/BoxTextured.glb"; const boxTexturedBinary = "./Data/Models/glTF-2.0/BoxTextured/glTF-Binary/BoxTextured.glb"; const boxWithPrimitiveOutline = "./Data/Models/glTF-2.0/BoxWithPrimitiveOutline/glTF/BoxWithPrimitiveOutline.gltf"; const buildingsMetadata = "./Data/Models/glTF-2.0/BuildingsMetadata/glTF/buildings-metadata.gltf"; const microcosm = "./Data/Models/glTF-2.0/Microcosm/glTF/microcosm.gltf"; const pointCloudRGB = "./Data/Models/glTF-2.0/PointCloudWithRGBColors/glTF-Binary/PointCloudWithRGBColors.glb"; const pointCloudWithPropertyAttributes = "./Data/Models/glTF-2.0/PointCloudWithPropertyAttributes/glTF/PointCloudWithPropertyAttributes.gltf"; const simplePropertyTexture = "./Data/Models/glTF-2.0/SimplePropertyTexture/glTF/SimplePropertyTexture.gltf"; const triangle = "./Data/Models/glTF-2.0/Triangle/glTF/Triangle.gltf"; const triangleWithoutIndices = "./Data/Models/glTF-2.0/TriangleWithoutIndices/glTF/TriangleWithoutIndices.gltf"; const triangleStrip = "./Data/Models/glTF-2.0/TriangleStrip/glTF/TriangleStrip.gltf"; const triangleFan = "./Data/Models/glTF-2.0/TriangleFan/glTF/TriangleFan.gltf"; let scene2; const gltfLoaders = []; beforeAll(function() { scene2 = createScene_default({ contextOptions: { requestWebgl1: true } }); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { const gltfLoadersLength = gltfLoaders.length; for (let i = 0; i < gltfLoadersLength; ++i) { const gltfLoader = gltfLoaders[i]; if (!gltfLoader.isDestroyed()) { gltfLoader.destroy(); } } gltfLoaders.length = 0; import__738.ResourceCache.clearForSpecs(); }); function getOptions(gltfPath, options) { const resource = new import__738.Resource({ url: gltfPath }); return (0, import__738.combine)(options, { gltfResource: resource, incrementallyLoadTextures: false // Default to false if not supplied }); } async function loadGltf(gltfPath, options) { const gltfLoader = new import__738.GltfLoader(getOptions(gltfPath, options)); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, scene2); return gltfLoader; } function mockModel(components) { return { structuralMetadata: components.structuralMetadata }; } function mockRenderResources(components) { return { model: { statistics: new import__738.ModelStatistics(), structuralMetadata: components.structuralMetadata }, runtimePrimitive: {} }; } it("counts memory for a model", function() { return loadGltf(boxTextured).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; const renderResources = mockRenderResources(components); import__738.PrimitiveStatisticsPipelineStage.process(renderResources, primitive); const statistics = renderResources.model.statistics; const attributes = primitive.attributes; let expectedGeometryLength = 0; expectedGeometryLength += attributes[0].buffer.sizeInBytes; expectedGeometryLength += attributes[2].buffer.sizeInBytes; expectedGeometryLength += primitive.indices.buffer.sizeInBytes; const material = primitive.material; const metallicRoughness = material.metallicRoughness; const expectedTexturesLength = metallicRoughness.baseColorTexture.texture.sizeInBytes; expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(12); expect(statistics.geometryByteLength).toBe(expectedGeometryLength); expect(statistics.texturesByteLength).toBe(expectedTexturesLength); expect(statistics.propertyTablesByteLength).toBe(0); }); }); it("_countGeometry computes memory usage for a triangle mesh", function() { return loadGltf(boxTextured).then(function(gltfLoader) { const statistics = new import__738.ModelStatistics(); const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; import__738.PrimitiveStatisticsPipelineStage._countGeometry(statistics, primitive); expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(12); const attributes = primitive.attributes; let expectedLength = 0; expectedLength += attributes[0].buffer.sizeInBytes; expectedLength += attributes[2].buffer.sizeInBytes; expectedLength += primitive.indices.buffer.sizeInBytes; expect(statistics.geometryByteLength).toBe(expectedLength); }); }); it("_countGeometry computes memory usage for triangle mesh without indices", function() { return loadGltf(triangleWithoutIndices).then(function(gltfLoader) { const statistics = new import__738.ModelStatistics(); const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; import__738.PrimitiveStatisticsPipelineStage._countGeometry(statistics, primitive); expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(1); const attributes = primitive.attributes; let expectedLength = 0; expectedLength += attributes[0].buffer.sizeInBytes; expect(statistics.geometryByteLength).toBe(expectedLength); }); }); it("_countGeometry computes memory usage correctly for attributes with CPU copy", function() { const options = { loadAttributesFor2D: true, loadIndicesForWireframe: true }; return loadGltf(boxTextured, options).then(function(gltfLoader) { const statistics = new import__738.ModelStatistics(); const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; import__738.PrimitiveStatisticsPipelineStage._countGeometry(statistics, primitive); expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(12); const attributes = primitive.attributes; let expectedLength = 0; expectedLength += 2 * attributes[0].buffer.sizeInBytes; expectedLength += attributes[1].buffer.sizeInBytes; expectedLength += attributes[2].buffer.sizeInBytes; expectedLength += 2 * primitive.indices.buffer.sizeInBytes; expect(statistics.geometryByteLength).toBe(expectedLength); }); }); it("_countGeometry computes memory usage for point cloud", function() { return loadGltf(pointCloudRGB).then(function(gltfLoader) { const statistics = new import__738.ModelStatistics(); const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; import__738.PrimitiveStatisticsPipelineStage._countGeometry(statistics, primitive); expect(statistics.pointsLength).toBe(2500); expect(statistics.trianglesLength).toBe(0); const attributes = primitive.attributes; let expectedLength = 0; expectedLength += attributes[0].buffer.sizeInBytes; expect(statistics.geometryByteLength).toBe(expectedLength); }); }); it("_countGeometry computes memory usage for triangle strip", function() { return loadGltf(triangleStrip).then(function(gltfLoader) { const statistics = new import__738.ModelStatistics(); const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; import__738.PrimitiveStatisticsPipelineStage._countGeometry(statistics, primitive); expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(2); const attributes = primitive.attributes; let expectedLength = 0; expectedLength += attributes[0].buffer.sizeInBytes; expectedLength += primitive.indices.buffer.sizeInBytes; expect(statistics.geometryByteLength).toBe(expectedLength); }); }); it("_countGeometry computes memory usage for triangle fan", function() { return loadGltf(triangleFan).then(function(gltfLoader) { const statistics = new import__738.ModelStatistics(); const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; import__738.PrimitiveStatisticsPipelineStage._countGeometry(statistics, primitive); expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(2); const attributes = primitive.attributes; let expectedLength = 0; expectedLength += attributes[0].buffer.sizeInBytes; expectedLength += primitive.indices.buffer.sizeInBytes; expect(statistics.geometryByteLength).toBe(expectedLength); }); }); it("_countGeometry computes memory usage for CESIUM_primitive_outline", function() { return loadGltf(boxWithPrimitiveOutline).then(function(gltfLoader) { const statistics = new import__738.ModelStatistics(); const components = gltfLoader.components; const [node] = components.nodes; const [primitive] = node.primitives; import__738.PrimitiveStatisticsPipelineStage._countGeometry(statistics, primitive); expect(statistics.pointsLength).toBe(0); expect(statistics.trianglesLength).toBe(12); const attributes = primitive.attributes; let expectedLength = 0; const attributesLength = attributes.length; for (let i = 0; i < attributesLength; i++) { expectedLength += attributes[i].buffer.sizeInBytes; } expectedLength += primitive.outlineCoordinates.buffer.sizeInBytes; expectedLength += primitive.indices.buffer.sizeInBytes; expect(statistics.geometryByteLength).toBe(expectedLength); }); }); it("_countPositions2D does not update count if 2D positions were not computed", function() { const statistics = new import__738.ModelStatistics(); const mockRuntimePrimitive = { positionBuffer2D: void 0 }; import__738.PrimitiveStatisticsPipelineStage._count2DPositions( statistics, mockRuntimePrimitive ); expect(statistics.geometryByteLength).toBe(0); }); it("_countPositions2D updates count if 2D positions exist", function() { return loadGltf(boxTextured, { loadAttributesFor2D: true }).then(function(gltfLoader) { const statistics = new import__738.ModelStatistics(); const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; const positionAttribute = primitive.attributes[1]; const mockRuntimePrimitive = { positionBuffer2D: { sizeInBytes: positionAttribute.typedArray.byteLength } }; positionAttribute.typedArray = void 0; import__738.PrimitiveStatisticsPipelineStage._count2DPositions( statistics, mockRuntimePrimitive ); const positions2D = mockRuntimePrimitive.positionBuffer2D; expect(statistics.geometryByteLength).toBe(2 * positions2D.sizeInBytes); }); }); it("_countMorphTargetAttributes updates memory statistics", function() { return loadGltf(animatedMorphCube).then(function(gltfLoader) { const statistics = new import__738.ModelStatistics(); const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; import__738.PrimitiveStatisticsPipelineStage._countMorphTargetAttributes( statistics, primitive ); let totalSize = 0; const morphTargets = primitive.morphTargets; const morphTargetsLength = morphTargets.length; for (let i = 0; i < morphTargetsLength; i++) { const attributes = morphTargets[i].attributes; const attributesLength = attributes.length; for (let j = 0; j < attributesLength; j++) { totalSize += attributes[j].buffer.sizeInBytes; } } expect(statistics.geometryByteLength).toBe(totalSize); }); }); it("_countMaterialTextures does not update memory if there is no material", function() { return loadGltf(triangle).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const statistics = new import__738.ModelStatistics(); import__738.PrimitiveStatisticsPipelineStage._countMaterialTextures( statistics, primitive.material ); expect(statistics.texturesByteLength).toBe(0); }); }); it("_countMaterialTextures updates memory statistics for metallic roughness", function() { return loadGltf(boomBox).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const material = primitive.material; const metallicRoughness = material.metallicRoughness; const statistics = new import__738.ModelStatistics(); import__738.PrimitiveStatisticsPipelineStage._countMaterialTextures( statistics, primitive.material ); const totalTextureSize = material.emissiveTexture.texture.sizeInBytes + material.normalTexture.texture.sizeInBytes + material.occlusionTexture.texture.sizeInBytes + metallicRoughness.baseColorTexture.texture.sizeInBytes; expect(statistics.texturesByteLength).toBe(totalTextureSize); }); }); it("_countMaterialTextures updates memory statistics for specular glossiness", function() { return loadGltf(boomBoxSpecularGlossiness).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; const material = primitive.material; const specularGlossiness = material.specularGlossiness; const statistics = new import__738.ModelStatistics(); import__738.PrimitiveStatisticsPipelineStage._countMaterialTextures( statistics, primitive.material ); const totalTextureSize = material.emissiveTexture.texture.sizeInBytes + material.normalTexture.texture.sizeInBytes + material.occlusionTexture.texture.sizeInBytes + specularGlossiness.diffuseTexture.texture.sizeInBytes + specularGlossiness.specularGlossinessTexture.texture.sizeInBytes; expect(statistics.texturesByteLength).toBe(totalTextureSize); }); }); it("_countFeatureIdTextures counts feature ID textures", function() { return loadGltf(microcosm).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const primitive = node.primitives[0]; const statistics = new import__738.ModelStatistics(); import__738.PrimitiveStatisticsPipelineStage._countFeatureIdTextures( statistics, primitive.featureIds ); const featureIdTexture = primitive.featureIds[0]; expect(statistics.geometryByteLength).toBe(0); expect(statistics.texturesByteLength).toBe( featureIdTexture.textureReader.texture.sizeInBytes ); }); }); it("_countBinaryMetadata does not update statistics for primitive without metadata", function() { return loadGltf(boxTexturedBinary).then(function(gltfLoader) { const statistics = new import__738.ModelStatistics(); const components = gltfLoader.components; const model = mockModel(components); import__738.PrimitiveStatisticsPipelineStage._countBinaryMetadata( statistics, model ); expect(statistics.geometryByteLength).toBe(0); }); }); it("_countBinaryMetadata updates statistics for property tables", function() { return loadGltf(buildingsMetadata).then(function(gltfLoader) { const statistics = new import__738.ModelStatistics(); const components = gltfLoader.components; const model = mockModel(components); import__738.PrimitiveStatisticsPipelineStage._countBinaryMetadata( statistics, model ); const structuralMetadata = model.structuralMetadata; const propertyTable = structuralMetadata.getPropertyTable(0); expect(statistics.propertyTablesByteLength).toBe( propertyTable.byteLength ); }); }); it("_countBinaryMetadata does not update statistics for property attributes", function() { return loadGltf(pointCloudWithPropertyAttributes).then(function(gltfLoader) { const statistics = new import__738.ModelStatistics(); const components = gltfLoader.components; const model = mockModel(components); import__738.PrimitiveStatisticsPipelineStage._countBinaryMetadata( statistics, model ); expect(statistics.geometryByteLength).toBe(0); }); }); it("_countBinaryMetadata updates statistics for propertyTextures", function() { return loadGltf(simplePropertyTexture).then(function(gltfLoader) { const statistics = new import__738.ModelStatistics(); const components = gltfLoader.components; const model = mockModel(components); import__738.PrimitiveStatisticsPipelineStage._countBinaryMetadata( statistics, model ); const structuralMetadata = model.structuralMetadata; const propertyTexture1 = structuralMetadata.getPropertyTexture(0); const property = propertyTexture1.getProperty("insideTemperature"); const textureSize = property.textureReader.texture.sizeInBytes; expect(statistics.texturesByteLength).toBe(textureSize); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/SceneMode2DPipelineStageSpec.js var import__739 = __toESM(require_Cesium(), 1); describe( "Scene/Model/SceneMode2DPipelineStage", function() { const scratchMatrix = new import__739.Matrix4(); const boxTexturedUrl = "./Data/Models/glTF-2.0/BoxTextured/glTF-Binary/BoxTextured.glb"; const dracoBoxWithTangentsUrl = "./Data/Models/glTF-2.0/BoxWithTangents/glTF-Draco/BoxWithTangents.gltf"; const boxInstancedTranslationUrl = "./Data/Models/glTF-2.0/BoxInstancedTranslation/glTF/box-instanced-translation.gltf"; let scene2; const gltfLoaders = []; beforeAll(function() { scene2 = createScene_default(); scene2.morphTo2D(0); scene2.updateFrameState(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { const gltfLoadersLength = gltfLoaders.length; for (let i = 0; i < gltfLoadersLength; ++i) { const gltfLoader = gltfLoaders[i]; if (!gltfLoader.isDestroyed()) { gltfLoader.destroy(); } } gltfLoaders.length = 0; import__739.ResourceCache.clearForSpecs(); }); function getOptions(gltfPath, options) { const resource = new import__739.Resource({ url: gltfPath }); return (0, import__739.combine)(options, { gltfResource: resource, incrementallyLoadTextures: false // Default to false if not supplied }); } async function loadGltf(gltfPath, options) { const gltfLoader = new import__739.GltfLoader(getOptions(gltfPath, options)); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, scene2); return gltfLoader; } function mockRenderResources() { return { attributes: [], shaderBuilder: new import__739.ShaderBuilder(), attributeIndex: 1, model: { type: import__739.ModelType.TILE_GLTF, statistics: new import__739.ModelStatistics(), sceneGraph: { computedModelMatrix: import__739.Matrix4.IDENTITY }, _modelResources: [] }, runtimeNode: { computedTransform: import__739.Matrix4.IDENTITY }, runtimePrimitive: {}, positionMin: new import__739.Cartesian3(-0.5, -0.5, -0.5), positionMax: new import__739.Cartesian3(0.5, 0.5, 0.5) }; } it("processes resources for 2D for primitive", function() { const renderResources = mockRenderResources(); return loadGltf(boxTexturedUrl, { loadAttributesFor2D: true }).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[1]; renderResources.runtimeNode.node = node; const primitive = node.primitives[0]; import__739.SceneMode2DPipelineStage.process( renderResources, primitive, scene2.frameState ); const model = renderResources.model; const runtimePrimitive = renderResources.runtimePrimitive; expect(runtimePrimitive.boundingSphere2D).toBeDefined(); const positions2D = runtimePrimitive.positionBuffer2D; expect(positions2D).toBeDefined(); expect(model._modelResources).toEqual([positions2D]); const positionAttribute = import__739.ModelUtility.getAttributeBySemantic( primitive, import__739.VertexAttributeSemantic.POSITION ); expect(positionAttribute.typedArray).toBeUndefined(); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "USE_2D_POSITIONS" ]); const translationMatrix = import__739.Matrix4.fromTranslation( runtimePrimitive.boundingSphere2D.center, scratchMatrix ); const expected = import__739.Matrix4.multiplyTransformation( scene2.frameState.context.uniformState.view, translationMatrix, translationMatrix ); expect(renderResources.uniformMap.u_modelView2D()).toEqual(expected); }); }); it("processes resources for 2D for primitive with draco compression", function() { const renderResources = mockRenderResources(); return loadGltf(dracoBoxWithTangentsUrl, { loadAttributesFor2D: true }).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; renderResources.runtimeNode.node = node; const primitive = node.primitives[0]; import__739.SceneMode2DPipelineStage.process( renderResources, primitive, scene2.frameState ); const model = renderResources.model; const runtimePrimitive = renderResources.runtimePrimitive; expect(runtimePrimitive.boundingSphere2D).toBeDefined(); const positions2D = runtimePrimitive.positionBuffer2D; expect(positions2D).toBeDefined(); expect(model._modelResources).toEqual([positions2D]); const positionAttribute = import__739.ModelUtility.getAttributeBySemantic( primitive, import__739.VertexAttributeSemantic.POSITION ); expect(positionAttribute.typedArray).toBeUndefined(); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "USE_2D_POSITIONS" ]); const translationMatrix = import__739.Matrix4.fromTranslation( runtimePrimitive.boundingSphere2D.center, scratchMatrix ); const expected = import__739.Matrix4.multiplyTransformation( scene2.frameState.context.uniformState.view, translationMatrix, translationMatrix ); expect(renderResources.uniformMap.u_modelView2D()).toEqual(expected); }); }); it("processes resources for instanced model in 2D", function() { const renderResources = mockRenderResources(); return loadGltf(boxInstancedTranslationUrl, { loadAttributesFor2D: true }).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; renderResources.runtimeNode.node = node; const primitive = node.primitives[0]; import__739.SceneMode2DPipelineStage.process( renderResources, primitive, scene2.frameState ); const runtimePrimitive = renderResources.runtimePrimitive; expect(runtimePrimitive.boundingSphere2D).toBeDefined(); expect(runtimePrimitive.positionBuffer2D).toBeUndefined(); const positionAttribute = import__739.ModelUtility.getAttributeBySemantic( primitive, import__739.VertexAttributeSemantic.POSITION ); expect(positionAttribute.typedArray).toBeUndefined(); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); expect(renderResources.uniformMap).toBeUndefined(); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/SelectedFeatureIdPipelineStageSpec.js var import__740 = __toESM(require_Cesium(), 1); describe( "Scene/Model/SelectedFeatureIdPipelineStage", function() { const buildingsMetadata = "./Data/Models/glTF-2.0/BuildingsMetadata/glTF/buildings-metadata.gltf"; const microcosm = "./Data/Models/glTF-2.0/Microcosm/glTF/microcosm.gltf"; const boxInstanced = "./Data/Models/glTF-2.0/BoxInstanced/glTF/box-instanced.gltf"; const largeFeatureIdTexture = "./Data/Models/glTF-2.0/LargeFeatureIdTexture/glTF/LargeFeatureIdTexture.gltf"; let scene2; const gltfLoaders = []; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { const gltfLoadersLength = gltfLoaders.length; for (let i = 0; i < gltfLoadersLength; ++i) { const gltfLoader = gltfLoaders[i]; if (!gltfLoader.isDestroyed()) { gltfLoader.destroy(); } } gltfLoaders.length = 0; import__740.ResourceCache.clearForSpecs(); }); function createDefaultShaderBuilder() { const shaderBuilder = new import__740.ShaderBuilder(); shaderBuilder.addStruct( import__740.SelectedFeatureIdPipelineStage.STRUCT_ID_SELECTED_FEATURE, import__740.SelectedFeatureIdPipelineStage.STRUCT_NAME_SELECTED_FEATURE, import__740.ShaderDestination.BOTH ); return shaderBuilder; } function verifyFeatureStruct(shaderBuilder) { ShaderBuilderTester_default.expectHasVertexStruct( shaderBuilder, import__740.SelectedFeatureIdPipelineStage.STRUCT_ID_SELECTED_FEATURE, import__740.SelectedFeatureIdPipelineStage.STRUCT_NAME_SELECTED_FEATURE, [" int id;", " vec2 st;", " vec4 color;"] ); ShaderBuilderTester_default.expectHasFragmentStruct( shaderBuilder, import__740.SelectedFeatureIdPipelineStage.STRUCT_ID_SELECTED_FEATURE, import__740.SelectedFeatureIdPipelineStage.STRUCT_NAME_SELECTED_FEATURE, [" int id;", " vec2 st;", " vec4 color;"] ); } function getOptions(gltfPath, options) { const resource = new import__740.Resource({ url: gltfPath }); return (0, import__740.combine)(options, { gltfResource: resource, incrementallyLoadTextures: false }); } async function loadGltf(gltfPath, options) { const gltfLoader = new import__740.GltfLoader(getOptions(gltfPath, options)); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, scene2); return gltfLoader; } function mockRenderResources(node) { return { shaderBuilder: createDefaultShaderBuilder(), runtimeNode: { node }, model: { featureIdLabel: "featureId_0", instanceFeatureIdLabel: "instanceFeatureId_0" }, uniformMap: {}, hasPropertyTable: false }; } it("selects primitive feature IDs", function() { return loadGltf(buildingsMetadata).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[1]; const primitive = node.primitives[0]; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(node); renderResources.model.featureIdLabel = "featureId_1"; import__740.SelectedFeatureIdPipelineStage.process( renderResources, primitive, frameState2 ); expect(renderResources.hasPropertyTable).toBe(true); const shaderBuilder = renderResources.shaderBuilder; verifyFeatureStruct(shaderBuilder); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_SELECTED_FEATURE_ID", "HAS_SELECTED_FEATURE_ID_ATTRIBUTE", "SELECTED_FEATURE_ID defaultIdsTest" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_SELECTED_FEATURE_ID", "HAS_SELECTED_FEATURE_ID_ATTRIBUTE", "SELECTED_FEATURE_ID defaultIdsTest" ]); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__740._shadersSelectedFeatureIdStageCommon ]); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__740._shadersSelectedFeatureIdStageCommon ]); }); }); it("selects feature ID texture", function() { return loadGltf(microcosm).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const primitive = node.primitives[0]; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(node); renderResources.model.featureIdLabel = "landCover"; import__740.SelectedFeatureIdPipelineStage.process( renderResources, primitive, frameState2 ); expect(renderResources.hasPropertyTable).toBe(true); const shaderBuilder = renderResources.shaderBuilder; verifyFeatureStruct(shaderBuilder); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_SELECTED_FEATURE_ID", "HAS_SELECTED_FEATURE_ID_TEXTURE", "SELECTED_FEATURE_ID landCover" ]); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, []); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__740._shadersSelectedFeatureIdStageCommon ]); }); }); it("selects instance feature IDs", function() { return loadGltf(boxInstanced).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const primitive = node.primitives[0]; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(node); renderResources.model.instanceFeatureIdLabel = "section"; import__740.SelectedFeatureIdPipelineStage.process( renderResources, primitive, frameState2 ); expect(renderResources.hasPropertyTable).toBe(true); const shaderBuilder = renderResources.shaderBuilder; verifyFeatureStruct(shaderBuilder); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_SELECTED_FEATURE_ID", "HAS_SELECTED_FEATURE_ID_ATTRIBUTE", "SELECTED_FEATURE_ID section" ]); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_SELECTED_FEATURE_ID", "HAS_SELECTED_FEATURE_ID_ATTRIBUTE", "SELECTED_FEATURE_ID section" ]); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__740._shadersSelectedFeatureIdStageCommon ]); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__740._shadersSelectedFeatureIdStageCommon ]); }); }); it("handles null feature ID when present", function() { return loadGltf(largeFeatureIdTexture).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[0]; const primitive = node.primitives[0]; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(node); renderResources.model.featureIdLabel = "idsGWithNull"; import__740.SelectedFeatureIdPipelineStage.process( renderResources, primitive, frameState2 ); expect(renderResources.hasPropertyTable).toBe(true); const shaderBuilder = renderResources.shaderBuilder; verifyFeatureStruct(shaderBuilder); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_NULL_FEATURE_ID", "HAS_SELECTED_FEATURE_ID", "HAS_SELECTED_FEATURE_ID_TEXTURE", "SELECTED_FEATURE_ID idsGWithNull" ]); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, []); ShaderBuilderTester_default.expectFragmentLinesEqual(shaderBuilder, [ import__740._shadersSelectedFeatureIdStageCommon ]); const uniformMap = renderResources.uniformMap; expect(uniformMap.model_nullFeatureId()).toBe(10); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/SkinningPipelineStageSpec.js var import__741 = __toESM(require_Cesium(), 1); describe( "Scene/Model/SkinningPipelineStage", function() { let scene2; const gltfLoaders = []; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { const gltfLoadersLength = gltfLoaders.length; for (let i = 0; i < gltfLoadersLength; ++i) { const gltfLoader = gltfLoaders[i]; if (!gltfLoader.isDestroyed()) { gltfLoader.destroy(); } } gltfLoaders.length = 0; import__741.ResourceCache.clearForSpecs(); }); function getOptions(gltfPath, options) { const resource = new import__741.Resource({ url: gltfPath }); return (0, import__741.combine)(options, { gltfResource: resource, incrementallyLoadTextures: false // Default to false if not supplied }); } async function loadGltf(gltfPath, options) { const gltfLoader = new import__741.GltfLoader(getOptions(gltfPath, options)); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, scene2); return gltfLoader; } const simpleSkinUrl = "./Data/Models/glTF-2.0/SimpleSkin/glTF/SimpleSkin.gltf"; const cesiumManUrl = "./Data/Models/glTF-2.0/CesiumMan/glTF-Draco/CesiumMan.gltf"; it("processes skin with two joints", function() { const mockJointMatrices = [ new import__741.Matrix4(), import__741.Matrix4.clone(import__741.Matrix4.IDENTITY) ]; const renderResources = { attributes: [], shaderBuilder: new import__741.ShaderBuilder(), attributeIndex: 1, model: { type: import__741.ModelType.TILE_GLTF }, runtimeNode: { computedJointMatrices: mockJointMatrices } }; return loadGltf(simpleSkinUrl).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[0].primitives[0]; import__741.SkinningPipelineStage.process(renderResources, primitive); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_SKINNING" ]); ShaderBuilderTester_default.expectHasVertexFunction( shaderBuilder, import__741.SkinningPipelineStage.FUNCTION_ID_GET_SKINNING_MATRIX, import__741.SkinningPipelineStage.FUNCTION_SIGNATURE_GET_SKINNING_MATRIX, [ " mat4 skinnedMatrix = mat4(0);", " skinnedMatrix += a_weights_0.x * u_jointMatrices[int(a_joints_0.x)];", " skinnedMatrix += a_weights_0.y * u_jointMatrices[int(a_joints_0.y)];", " skinnedMatrix += a_weights_0.z * u_jointMatrices[int(a_joints_0.z)];", " skinnedMatrix += a_weights_0.w * u_jointMatrices[int(a_joints_0.w)];", " return skinnedMatrix;" ] ); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__741._shadersSkinningStageVS ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform mat4 u_jointMatrices[2];" ]); const runtimeNode = renderResources.runtimeNode; const uniformMap = renderResources.uniformMap; expect(uniformMap.u_jointMatrices()).toBe( runtimeNode.computedJointMatrices ); }); }); it("processes skin with many joints", function() { const jointCount = 19; const mockJointMatrices = new Array(jointCount); const renderResources = { attributes: [], shaderBuilder: new import__741.ShaderBuilder(), attributeIndex: 1, model: { type: import__741.ModelType.TILE_GLTF }, runtimeNode: { computedJointMatrices: mockJointMatrices } }; return loadGltf(cesiumManUrl).then(function(gltfLoader) { const components = gltfLoader.components; const primitive = components.nodes[1].primitives[0]; import__741.SkinningPipelineStage.process(renderResources, primitive); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_SKINNING" ]); ShaderBuilderTester_default.expectHasVertexFunction( shaderBuilder, import__741.SkinningPipelineStage.FUNCTION_ID_GET_SKINNING_MATRIX, import__741.SkinningPipelineStage.FUNCTION_SIGNATURE_GET_SKINNING_MATRIX, [ " mat4 skinnedMatrix = mat4(0);", " skinnedMatrix += a_weights_0.x * u_jointMatrices[int(a_joints_0.x)];", " skinnedMatrix += a_weights_0.y * u_jointMatrices[int(a_joints_0.y)];", " skinnedMatrix += a_weights_0.z * u_jointMatrices[int(a_joints_0.z)];", " skinnedMatrix += a_weights_0.w * u_jointMatrices[int(a_joints_0.w)];", " return skinnedMatrix;" ] ); ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__741._shadersSkinningStageVS ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ `uniform mat4 u_jointMatrices[${jointCount}];` ]); const runtimeNode = renderResources.runtimeNode; const uniformMap = renderResources.uniformMap; expect(uniformMap.u_jointMatrices()).toBe( runtimeNode.computedJointMatrices ); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/TextureManagerSpec.js var import__742 = __toESM(require_Cesium(), 1); // packages/engine/Source/Core/WebGLConstants.js var WebGLConstants9 = { 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 }; var WebGLConstants_default = Object.freeze(WebGLConstants9); // packages/engine/Source/Renderer/TextureMinificationFilter.js var TextureMinificationFilter11 = { /** * 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 <code>NEAREST</code> filtering. * * @type {number} * @constant */ LINEAR: WebGLConstants_default.LINEAR, /** * Selects the nearest mip level and applies nearest sampling within that level. * <p> * Requires that the texture has a mipmap. The mip level is chosen by the view angle and screen-space size of the texture. * </p> * * @type {number} * @constant */ NEAREST_MIPMAP_NEAREST: WebGLConstants_default.NEAREST_MIPMAP_NEAREST, /** * Selects the nearest mip level and applies linear sampling within that level. * <p> * Requires that the texture has a mipmap. The mip level is chosen by the view angle and screen-space size of the texture. * </p> * * @type {number} * @constant */ LINEAR_MIPMAP_NEAREST: WebGLConstants_default.LINEAR_MIPMAP_NEAREST, /** * Read texture values with nearest sampling from two adjacent mip levels and linearly interpolate the results. * <p> * This option provides a good balance of visual quality and speed when sampling from a mipmapped texture. * </p> * <p> * Requires that the texture has a mipmap. The mip level is chosen by the view angle and screen-space size of the texture. * </p> * * @type {number} * @constant */ NEAREST_MIPMAP_LINEAR: WebGLConstants_default.NEAREST_MIPMAP_LINEAR, /** * Read texture values with linear sampling from two adjacent mip levels and linearly interpolate the results. * <p> * This option provides a good balance of visual quality and speed when sampling from a mipmapped texture. * </p> * <p> * Requires that the texture has a mipmap. The mip level is chosen by the view angle and screen-space size of the texture. * </p> * @type {number} * @constant */ LINEAR_MIPMAP_LINEAR: WebGLConstants_default.LINEAR_MIPMAP_LINEAR }; TextureMinificationFilter11.validate = function(textureMinificationFilter) { return textureMinificationFilter === TextureMinificationFilter11.NEAREST || textureMinificationFilter === TextureMinificationFilter11.LINEAR || textureMinificationFilter === TextureMinificationFilter11.NEAREST_MIPMAP_NEAREST || textureMinificationFilter === TextureMinificationFilter11.LINEAR_MIPMAP_NEAREST || textureMinificationFilter === TextureMinificationFilter11.NEAREST_MIPMAP_LINEAR || textureMinificationFilter === TextureMinificationFilter11.LINEAR_MIPMAP_LINEAR; }; var TextureMinificationFilter_default = Object.freeze(TextureMinificationFilter11); // packages/engine/Specs/Scene/Model/TextureManagerSpec.js describe( "Scene/Model/TextureManager", function() { let sceneWithWebgl1; let sceneWithWebgl2; beforeAll(function() { sceneWithWebgl1 = createScene_default({ contextOptions: { requestWebgl1: true } }); sceneWithWebgl2 = createScene_default(); }); afterAll(function() { sceneWithWebgl1.destroyForSpecs(); sceneWithWebgl2.destroyForSpecs(); }); const textureManagers = []; afterEach(function() { for (let i = 0; i < textureManagers.length; i++) { const textureManager = textureManagers[i]; if (!textureManager.isDestroyed()) { textureManager.destroy(); } } textureManagers.length = 0; }); function waitForTextureLoad(textureManager, textureId, webgl2) { const scene2 = webgl2 ? sceneWithWebgl2 : sceneWithWebgl1; const oldValue = textureManager.getTexture(textureId); return pollToPromise_default(function() { scene2.renderForSpecs(); textureManager.update(scene2.frameState); return textureManager.getTexture(textureId) !== oldValue; }).then(function() { return textureManager.getTexture(textureId); }); } const blueUrl = "Data/Images/Blue2x2.png"; const greenUrl = "Data/Images/Green1x4.png"; const redUrl = "Data/Images/Red16x16.png"; const blue10x10Url = "Data/Images/Blue10x10.png"; it("constructs", function() { const textureManager = new import__742.TextureManager(); textureManagers.push(textureManager); expect(textureManager._textures).toEqual({}); expect(textureManager._loadedImages).toEqual([]); }); it("loads texture from a URL", function() { const textureManager = new import__742.TextureManager(); textureManagers.push(textureManager); const id = "testTexture"; textureManager.loadTexture2D( id, new import__742.TextureUniform({ url: blueUrl }) ); return waitForTextureLoad(textureManager, id).then(function(texture) { expect(texture.width).toBe(2); expect(texture.height).toBe(2); }); }); it("loads texture from a typed array", function() { const textureManager = new import__742.TextureManager(); textureManagers.push(textureManager); const id = "testTexture"; textureManager.loadTexture2D( id, new import__742.TextureUniform({ typedArray: new Uint8Array([255, 0, 0, 255, 0, 255, 0, 255]), width: 1, height: 2 }) ); return waitForTextureLoad(textureManager, id).then(function(texture) { expect(texture.width).toBe(1); expect(texture.height).toBe(2); }); }); it("generates mipmaps when sampler type requires them", function() { const textureManager = new import__742.TextureManager(); textureManagers.push(textureManager); const id = "testTexture"; textureManager.loadTexture2D( id, new import__742.TextureUniform({ url: redUrl, minificationFilter: TextureMinificationFilter_default.LINEAR_MIPMAP_LINEAR }) ); return waitForTextureLoad(textureManager, id, false).then(function(texture) { expect(texture._hasMipmap).toBe(true); }); }); it("resizes image to power-of-two dimensions if needed", function() { const textureManager = new import__742.TextureManager(); textureManagers.push(textureManager); const id = "testTexture"; textureManager.loadTexture2D( id, new import__742.TextureUniform({ url: blue10x10Url, minificationFilter: TextureMinificationFilter_default.LINEAR_MIPMAP_NEAREST }) ); return waitForTextureLoad(textureManager, id, false).then(function(texture) { expect(texture.width).toBe(16); expect(texture.height).toBe(16); expect(texture._hasMipmap).toBe(true); }); }); it("can resize a texture supplied as a Uint8Array", function() { const redPixels3x3 = Array(9).fill([255, 0, 0, 255]).flat(); const uint8array3x3 = new Uint8Array(redPixels3x3); const textureUniform = new import__742.TextureUniform({ typedArray: uint8array3x3, width: 3, height: 3, minificationFilter: TextureMinificationFilter_default.NEAREST_MIPMAP_LINEAR }); const textureManager = new import__742.TextureManager(); textureManagers.push(textureManager); const id = "testTexture"; textureManager.loadTexture2D(id, textureUniform); return waitForTextureLoad(textureManager, id).then(function(texture) { expect(texture.width).toBe(4); expect(texture.height).toBe(4); expect(texture._hasMipmap).toBe(true); }); }); it("generates mipmaps without resizing in WebGL2", function() { if (!sceneWithWebgl2.context.webgl2) { return; } const textureManager = new import__742.TextureManager(); textureManagers.push(textureManager); const id = "testTexture"; textureManager.loadTexture2D( id, new import__742.TextureUniform({ url: blue10x10Url, minificationFilter: TextureMinificationFilter_default.NEAREST_MIPMAP_NEAREST }) ); const webgl2 = true; return waitForTextureLoad(textureManager, id, webgl2).then(function(texture) { expect(texture.width).toBe(10); expect(texture.height).toBe(10); expect(texture._hasMipmap).toBe(true); }); }); it("destroys old texture before adding a new one", function() { const textureManager = new import__742.TextureManager(); textureManagers.push(textureManager); const id = "testTexture"; textureManager.loadTexture2D( id, new import__742.TextureUniform({ url: blueUrl }) ); return waitForTextureLoad(textureManager, id).then(function(blueTexture) { expect(blueTexture.width).toBe(2); expect(blueTexture.height).toBe(2); expect(blueTexture.isDestroyed()).toBe(false); textureManager.loadTexture2D( id, new import__742.TextureUniform({ url: greenUrl }) ); return waitForTextureLoad(textureManager, id).then(function(greenTexture) { expect(blueTexture.isDestroyed()).toBe(true); expect(greenTexture.width).toBe(1); expect(greenTexture.height).toBe(4); expect(greenTexture.isDestroyed()).toBe(false); }); }); }); it("getTexture returns undefined for unknown texture", function() { const textureManager = new import__742.TextureManager(); textureManagers.push(textureManager); const texture = textureManager.getTexture("notATexture"); expect(texture).not.toBeDefined(); }); it("sets a defaultTexture on error", function() { spyOn(import__742.Resource.prototype, "fetchImage").and.callFake(function() { return Promise.reject(); }); const textureManager = new import__742.TextureManager(); textureManagers.push(textureManager); const id = "testTexture"; textureManager.update(sceneWithWebgl1.frameState); textureManager.loadTexture2D( id, new import__742.TextureUniform({ url: "https://example.com/not-a-texture.jpg" }) ); return waitForTextureLoad(textureManager, id).then(function(texture) { const defaultTexture = sceneWithWebgl1.frameState.context.defaultTexture; expect(texture).toBe(defaultTexture); }).catch(console.error); }); it("destroys", function() { const textureManager = new import__742.TextureManager(); textureManagers.push(textureManager); const id = "testTexture"; textureManager.loadTexture2D( id, new import__742.TextureUniform({ url: blueUrl }) ); return waitForTextureLoad(textureManager, id).then(function(texture) { expect(textureManager.isDestroyed()).toBe(false); expect(texture.isDestroyed()).toBe(false); textureManager.destroy(); expect(textureManager.isDestroyed()).toBe(true); expect(texture.isDestroyed()).toBe(true); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/TextureUniformSpec.js var import__743 = __toESM(require_Cesium(), 1); describe("Scene/Model/TextureUniform", function() { const exampleUrl = "https://example.com/url"; const greenTexture = new Uint8Array([0, 255, 0, 255]); const defaultSampler = new import__743.Sampler({ wrapS: import__743.TextureWrap.REPEAT, wrapT: import__743.TextureWrap.REPEAT, minificationFilter: import__743.TextureMinificationFilter.LINEAR, magnificationFilter: import__743.TextureMagnificationFilter.LINEAR, maximumAnisotropy: 1 }); it("throws if no texture is specified", function() { expect(function() { return new import__743.TextureUniform(); }).toThrowDeveloperError(); }); it("throws if both url and typedArray are specified", function() { expect(function() { return new import__743.TextureUniform({ url: exampleUrl, typedArray: greenTexture, width: 1, height: 1 }); }).toThrowDeveloperError(); }); it("constructs with a URL", function() { const textureUniform = new import__743.TextureUniform({ url: exampleUrl }); expect(textureUniform.resource).toBeDefined(); expect(textureUniform.resource.url).toEqual(exampleUrl); expect(textureUniform.typedArray).not.toBeDefined(); expect(textureUniform.width).not.toBeDefined(); expect(textureUniform.height).not.toBeDefined(); expect(textureUniform.sampler).toEqual(defaultSampler); expect(textureUniform.pixelFormat).toEqual(import__743.PixelFormat.RGBA); expect(textureUniform.pixelDatatype).toEqual(import__743.PixelDatatype.UNSIGNED_BYTE); }); it("throws if width and height are not provided for a typed array", function() { expect(function() { return new import__743.TextureUniform({ typedArray: greenTexture }); }).toThrowDeveloperError(); }); it("constructs with a typed array", function() { const textureUniform = new import__743.TextureUniform({ typedArray: greenTexture, width: 1, height: 1 }); expect(textureUniform.resource).not.toBeDefined(); expect(textureUniform.typedArray).toBe(greenTexture); expect(textureUniform.width).toBe(1); expect(textureUniform.height).toBe(1); expect(textureUniform.sampler).toEqual(defaultSampler); expect(textureUniform.pixelFormat).toEqual(import__743.PixelFormat.RGBA); expect(textureUniform.pixelDatatype).toEqual(import__743.PixelDatatype.UNSIGNED_BYTE); }); it("constructs with a resource", function() { const resource = new import__743.Resource({ url: exampleUrl }); const textureUniform = new import__743.TextureUniform({ url: resource }); expect(textureUniform.resource).toBe(resource); expect(textureUniform.typedArray).not.toBeDefined(); expect(textureUniform.width).not.toBeDefined(); expect(textureUniform.height).not.toBeDefined(); expect(textureUniform.sampler).toEqual(defaultSampler); expect(textureUniform.pixelFormat).toEqual(import__743.PixelFormat.RGBA); expect(textureUniform.pixelDatatype).toEqual(import__743.PixelDatatype.UNSIGNED_BYTE); }); it("sets sampler settings", function() { const textureUniform = new import__743.TextureUniform({ url: exampleUrl, repeat: false, minificationFilter: import__743.TextureMinificationFilter.NEAREST, magnificationFilter: import__743.TextureMagnificationFilter.NEAREST, maximumAnisotropy: 2 }); expect(textureUniform.sampler).toEqual( new import__743.Sampler({ wrapS: import__743.TextureWrap.CLAMP_TO_EDGE, wrapT: import__743.TextureWrap.CLAMP_TO_EDGE, minificationFilter: import__743.TextureMinificationFilter.NEAREST, magnificationFilter: import__743.TextureMagnificationFilter.NEAREST, maximumAnisotropy: 2 }) ); }); it("sets texture settings for typed arrays", function() { const textureUniform = new import__743.TextureUniform({ typedArray: new Uint8Array([255, 0, 0, 0, 255, 0]), width: 1, height: 1, pixelFormat: import__743.PixelFormat.RGB, pixelDatatype: import__743.PixelDatatype.UNSIGNED_SHORT }); expect(textureUniform.pixelFormat).toEqual(import__743.PixelFormat.RGB); expect(textureUniform.pixelDatatype).toEqual(import__743.PixelDatatype.UNSIGNED_SHORT); }); }); // packages/engine/Specs/Scene/Model/TilesetPipelineStageSpec.js var import__744 = __toESM(require_Cesium(), 1); describe("Scene/Model/TilesetPipelineStage", function() { const mockFrameState = {}; function mockRenderResources() { return { shaderBuilder: new import__744.ShaderBuilder(), uniformMap: {}, model: { hasSkipLevelOfDetail: function() { return false; } }, renderStateOptions: {} }; } it("configures the render resources for skipping level of detail", function() { const renderResources = mockRenderResources(); const model = renderResources.model; model.hasSkipLevelOfDetail = function() { return true; }; import__744.TilesetPipelineStage.process(renderResources, model, mockFrameState); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "POLYGON_OFFSET" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, []); ShaderBuilderTester_default.expectHasFragmentUniforms(shaderBuilder, []); const uniformMap = renderResources.uniformMap; expect(uniformMap.u_polygonOffset()).toEqual(import__744.Cartesian2.ZERO); expect(renderResources.hasSkipLevelOfDetail).toBe(true); }); it("sets stencil test and mask", function() { const renderResources = mockRenderResources(); const model = renderResources.model; import__744.TilesetPipelineStage.process(renderResources, model, mockFrameState); const renderStateOptions = renderResources.renderStateOptions; expect(renderStateOptions.stencilTest).toEqual( import__744.StencilConstants.setCesium3DTileBit() ); expect(renderStateOptions.stencilMask).toEqual( import__744.StencilConstants.CESIUM_3D_TILE_MASK ); }); }); // packages/engine/Specs/Scene/Model/VerticalExaggerationPipelineStageSpec.js var import__745 = __toESM(require_Cesium(), 1); describe( "Scene/Model/VerticalExaggerationPipelineStage", function() { const mockModel = {}; const mockPrimitive = {}; const mockFrameState = { verticalExaggeration: 2, verticalExaggerationRelativeHeight: 100 }; function mockRenderResources() { return { model: mockModel, shaderBuilder: new import__745.ShaderBuilder(), uniformMap: {}, renderStateOptions: import__745.RenderState.getState(import__745.RenderState.fromCache()) }; } it("adds shader lines, defines, and uniforms", function() { const renderResources = mockRenderResources(); import__745.VerticalExaggerationPipelineStage.process( renderResources, mockPrimitive, mockFrameState ); const shaderBuilder = renderResources.shaderBuilder; ShaderBuilderTester_default.expectVertexLinesEqual(shaderBuilder, [ import__745._shadersVerticalExaggerationStageVS ]); ShaderBuilderTester_default.expectHasVertexDefines(shaderBuilder, [ "HAS_VERTICAL_EXAGGERATION" ]); ShaderBuilderTester_default.expectHasVertexUniforms(shaderBuilder, [ "uniform vec2 u_verticalExaggerationAndRelativeHeight;" ]); const expectedUniform = import__745.Cartesian2.fromElements( mockFrameState.verticalExaggeration, mockFrameState.verticalExaggerationRelativeHeight ); expect( renderResources.uniformMap.u_verticalExaggerationAndRelativeHeight() ).toEqual(expectedUniform); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/WireframePipelineStageSpec.js var import__746 = __toESM(require_Cesium(), 1); describe( "Scene/Model/WireframePipelineStage", function() { const boxTexturedBinary = "./Data/Models/glTF-2.0/BoxTextured/glTF-Binary/BoxTextured.glb"; const resources = []; const gltfLoaders = []; let scene2; let sceneWithWebgl2; beforeAll(function() { scene2 = createScene_default({ contextOptions: { sceneWithWebgl1: true } }); sceneWithWebgl2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); sceneWithWebgl2.destroyForSpecs(); }); function cleanup(resourcesArray) { for (let i = 0; i < resourcesArray.length; i++) { const resource = resourcesArray[i]; if (!resource.isDestroyed()) { resource.destroy(); } } resourcesArray.length = 0; } afterEach(function() { cleanup(resources); cleanup(gltfLoaders); import__746.ResourceCache.clearForSpecs(); }); function getOptions(gltfPath, options) { const resource = new import__746.Resource({ url: gltfPath }); return (0, import__746.combine)(options, { gltfResource: resource, incrementallyLoadTextures: false // Default to false if not supplied }); } async function loadGltf(gltfPath, scene3, options) { const gltfLoader = new import__746.GltfLoader(getOptions(gltfPath, options)); gltfLoaders.push(gltfLoader); await gltfLoader.load(); await waitForLoaderProcess_default(gltfLoader, scene3); return gltfLoader; } function mockRenderResources(primitive) { return { indices: primitive.indices, count: primitive.indices.count, primitiveType: primitive.primitiveType, wireframeIndexBuffer: void 0, model: { _pipelineResources: resources, statistics: new import__746.ModelStatistics() }, shaderBuilder: new import__746.ShaderBuilder() }; } it("adds define to shader", function() { return loadGltf(boxTexturedBinary, sceneWithWebgl2).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[1]; const primitive = node.primitives[0]; const frameState2 = sceneWithWebgl2.frameState; const renderResources = mockRenderResources(primitive); const shaderBuilder = renderResources.shaderBuilder; import__746.WireframePipelineStage.process(renderResources, primitive, frameState2); ShaderBuilderTester_default.expectHasFragmentDefines(shaderBuilder, [ "HAS_WIREFRAME" ]); }); }); it("Creates wireframe indices from buffer (WebGL 2)", function() { if (!sceneWithWebgl2.context.webgl2) { return; } return loadGltf(boxTexturedBinary, sceneWithWebgl2).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[1]; const primitive = node.primitives[0]; const frameState2 = sceneWithWebgl2.frameState; const renderResources = mockRenderResources(primitive); expect(renderResources.count).toBe(36); expect(renderResources.primitiveType).toBe(import__746.PrimitiveType.TRIANGLES); import__746.WireframePipelineStage.process(renderResources, primitive, frameState2); const wireframeIndexBuffer = renderResources.wireframeIndexBuffer; const model = renderResources.model; expect(wireframeIndexBuffer).toBeDefined(); expect(model._pipelineResources).toEqual([wireframeIndexBuffer]); expect(model.statistics.geometryByteLength).toBe( wireframeIndexBuffer.sizeInBytes ); expect(renderResources.primitiveType).toBe(import__746.PrimitiveType.LINES); expect(renderResources.count).toBe(72); }); }); it("Creates wireframe indices from typedArray (WebGL 1)", function() { const options = { loadIndicesForWireframe: true }; return loadGltf(boxTexturedBinary, scene2, options).then(function(gltfLoader) { const components = gltfLoader.components; const node = components.nodes[1]; const primitive = node.primitives[0]; const frameState2 = scene2.frameState; const renderResources = mockRenderResources(primitive); expect(renderResources.count).toBe(36); expect(renderResources.primitiveType).toBe(import__746.PrimitiveType.TRIANGLES); import__746.WireframePipelineStage.process(renderResources, primitive, frameState2); const wireframeIndexBuffer = renderResources.wireframeIndexBuffer; const model = renderResources.model; expect(wireframeIndexBuffer).toBeDefined(); expect(model._pipelineResources).toEqual([wireframeIndexBuffer]); expect(model.statistics.geometryByteLength).toBe( wireframeIndexBuffer.sizeInBytes ); expect(renderResources.primitiveType).toBe(import__746.PrimitiveType.LINES); expect(renderResources.count).toBe(72); }); }); }, "WebGL" ); // packages/engine/Specs/Scene/Model/pickModelSpec.js var import__747 = __toESM(require_Cesium(), 1); describe("Scene/Model/pickModel", function() { const boxTexturedGltfUrl = "./Data/Models/glTF-2.0/BoxTextured/glTF/BoxTextured.gltf"; const boxInstanced = "./Data/Models/glTF-2.0/BoxInstancedNoNormals/glTF/BoxInstancedNoNormals.gltf"; const boxWithOffsetUrl = "./Data/Models/glTF-2.0/BoxWithOffset/glTF/BoxWithOffset.gltf"; const pointCloudUrl = "./Data/Models/glTF-2.0/PointCloudWithRGBColors/glTF-Binary/PointCloudWithRGBColors.glb"; const boxWithMixedCompression = "./Data/Models/glTF-2.0/BoxMixedCompression/glTF/BoxMixedCompression.gltf"; const boxWithQuantizedAttributes = "./Data/Models/glTF-2.0/BoxWeb3dQuantizedAttributes/glTF/BoxWeb3dQuantizedAttributes.gltf"; const boxCesiumRtcUrl = "./Data/Models/glTF-2.0/BoxCesiumRtc/glTF/BoxCesiumRtc.gltf"; const boxBackFaceCullingUrl = "./Data/Models/glTF-2.0/BoxBackFaceCulling/glTF/BoxBackFaceCulling.gltf"; const boxInterleaved = "./Data/Models/glTF-2.0/BoxInterleaved/glTF/BoxInterleaved.gltf"; let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); afterEach(function() { scene2.frameState.mode = import__747.SceneMode.SCENE3D; scene2.primitives.removeAll(); }); it("throws without model", function() { expect(() => (0, import__747.pickModel)()).toThrowDeveloperError(); }); it("throws without ray", async function() { const model = await import__747.Model.fromGltfAsync({ url: boxTexturedGltfUrl }); expect(() => (0, import__747.pickModel)(model)).toThrowDeveloperError(); }); it("throws without frameState", async function() { const model = await import__747.Model.fromGltfAsync({ url: boxTexturedGltfUrl, enablePick: !scene2.frameState.context.webgl2 }); const ray = new import__747.Ray(); expect(() => (0, import__747.pickModel)(model, ray)).toThrowDeveloperError(); }); it("returns undefined if model is not ready", async function() { const model = await import__747.Model.fromGltfAsync({ url: boxTexturedGltfUrl, enablePick: !scene2.frameState.context.webgl2 }); const ray = new import__747.Ray(); expect((0, import__747.pickModel)(model, ray, scene2.frameState)).toBeUndefined(); }); it("returns undefined if ray does not intersect model surface", async function() { const model = await loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl, enablePick: !scene2.frameState.context.webgl2 }, scene2 ); const ray = new import__747.Ray(); expect((0, import__747.pickModel)(model, ray, scene2.frameState)).toBeUndefined(); }); it("returns position of intersection between ray and model surface", async function() { const model = await loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl, enablePick: !scene2.frameState.context.webgl2 }, scene2 ); const ray = scene2.camera.getPickRay( new import__747.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); const expected = new import__747.Cartesian3(0.5, 0, 0.5); expect((0, import__747.pickModel)(model, ray, scene2.frameState)).toEqualEpsilon( expected, import__747.Math.EPSILON12 ); }); it("returns position of intersection between ray and model surface with enablePick in WebGL 1", async function() { const sceneWithWebgl1 = createScene_default({ contextOptions: { requestWebgl1: true } }); const model = await loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl, enablePick: true }, scene2 ); const ray = scene2.camera.getPickRay( new import__747.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); const expected = new import__747.Cartesian3(0.5, 0, 0.5); expect((0, import__747.pickModel)(model, ray, scene2.frameState)).toEqualEpsilon( expected, import__747.Math.EPSILON12 ); sceneWithWebgl1.destroyForSpecs(); }); it("returns position of intersection accounting for node transforms", async function() { const model = await loadAndZoomToModelAsync_default( { url: boxWithOffsetUrl, enablePick: !scene2.frameState.context.webgl2 }, scene2 ); const ray = scene2.camera.getPickRay( new import__747.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); const expected = new import__747.Cartesian3(0, 5.5, -0.5); expect((0, import__747.pickModel)(model, ray, scene2.frameState)).toEqualEpsilon( expected, import__747.Math.EPSILON12 ); }); it("returns position of intersection with RTC model", async function() { const model = await loadAndZoomToModelAsync_default( { url: boxCesiumRtcUrl, enablePick: !scene2.frameState.context.webgl2 }, scene2 ); const ray = scene2.camera.getPickRay( new import__747.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); const expected = new import__747.Cartesian3(63781375e-1, 0, -0.499999996649); expect((0, import__747.pickModel)(model, ray, scene2.frameState)).toEqualEpsilon( expected, import__747.Math.EPSILON8 ); }); it("returns position of intersection with quantzed model", async function() { const model = await loadAndZoomToModelAsync_default( { url: boxWithQuantizedAttributes, enablePick: !scene2.frameState.context.webgl2 }, scene2 ); const ray = scene2.camera.getPickRay( new import__747.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); const expected = new import__747.Cartesian3(0.5, 0, 0.5); expect((0, import__747.pickModel)(model, ray, scene2.frameState)).toEqualEpsilon( expected, import__747.Math.EPSILON12 ); }); it("returns position of intersection with mixed compression model", async function() { const model = await loadAndZoomToModelAsync_default( { url: boxWithMixedCompression, enablePick: !scene2.frameState.context.webgl2 }, scene2 ); const ray = scene2.camera.getPickRay( new import__747.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); const expected = new import__747.Cartesian3(1, 0, 1); expect((0, import__747.pickModel)(model, ray, scene2.frameState)).toEqualEpsilon( expected, import__747.Math.EPSILON12 ); }); it("returns position of intersection with interleaved model", async function() { const model = await loadAndZoomToModelAsync_default( { url: boxInterleaved, enablePick: !scene2.frameState.context.webgl2 }, scene2 ); const ray = scene2.camera.getPickRay( new import__747.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); const expected = new import__747.Cartesian3(0.5, 0, 0.5); expect((0, import__747.pickModel)(model, ray, scene2.frameState)).toEqualEpsilon( expected, import__747.Math.EPSILON12 ); }); it("returns position of intersection with instanced model", async function() { const offset = new import__747.HeadingPitchRange( import__747.Math.PI_OVER_TWO, -import__747.Math.PI_OVER_FOUR, 1 ); const model = await loadAndZoomToModelAsync_default( { url: boxInstanced, enablePick: !scene2.frameState.context.webgl2, offset }, scene2 ); const ray = scene2.camera.getPickRay( new import__747.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); const expected = new import__747.Cartesian3(0, -0.5, 0.5); expect((0, import__747.pickModel)(model, ray, scene2.frameState)).toEqualEpsilon( expected, import__747.Math.EPSILON12 ); }); it("returns undefined for point cloud", async function() { const model = await loadAndZoomToModelAsync_default( { url: pointCloudUrl, enablePick: !scene2.frameState.context.webgl2 }, scene2 ); const ray = scene2.camera.getPickRay( new import__747.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); expect((0, import__747.pickModel)(model, ray, scene2.frameState)).toBeUndefined(); }); it("cullsBackFaces by default", async function() { const model = await loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl, enablePick: !scene2.frameState.context.webgl2 }, scene2 ); const ray = scene2.camera.getPickRay( new import__747.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); ray.origin = model.boundingSphere.center; expect((0, import__747.pickModel)(model, ray, scene2.frameState)).toBeUndefined(); }); it("includes back faces results when model disables backface culling", async function() { const model = await loadAndZoomToModelAsync_default( { url: boxBackFaceCullingUrl, enablePick: !scene2.frameState.context.webgl2, backFaceCulling: false }, scene2 ); const ray = scene2.camera.getPickRay( new import__747.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); ray.origin = model.boundingSphere.center; const expected = new import__747.Cartesian3( -0.9999998807907355, 0, -0.9999998807907104 ); expect((0, import__747.pickModel)(model, ray, scene2.frameState)).toEqualEpsilon( expected, import__747.Math.EPSILON12 ); }); it("uses result parameter if specified", async function() { const model = await loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl, enablePick: !scene2.frameState.context.webgl2 }, scene2 ); const ray = scene2.camera.getPickRay( new import__747.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); const result = new import__747.Cartesian3(); const expected = new import__747.Cartesian3(0.5, 0, 0.5); const returned = (0, import__747.pickModel)( model, ray, scene2.frameState, void 0, void 0, void 0, result ); expect(result).toEqualEpsilon(expected, import__747.Math.EPSILON12); expect(returned).toBe(result); }); it("returns undefined when morphing", async function() { const model = await loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl, enablePick: !scene2.frameState.context.webgl2 }, scene2 ); const ray = scene2.camera.getPickRay( new import__747.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); scene2.frameState.mode = import__747.SceneMode.MORPHING; expect((0, import__747.pickModel)(model, ray, scene2.frameState)).toBeUndefined(); }); it("returns position with vertical exaggeration", async function() { const model = await loadAndZoomToModelAsync_default( { url: boxTexturedGltfUrl, enablePick: !scene2.frameState.context.webgl2 }, scene2 ); const ray = scene2.camera.getPickRay( new import__747.Cartesian2( scene2.drawingBufferWidth / 2, scene2.drawingBufferHeight / 2 ) ); const expected = new import__747.Cartesian3(-65.51341504, 0, -65.51341504); expect( (0, import__747.pickModel)( model, ray, scene2.frameState, 2, -import__747.Ellipsoid.WGS84.minimumRadius ) ).toEqualEpsilon(expected, import__747.Math.EPSILON8); }); }); // packages/widgets/Specs/ClockViewModelSpec.js var import_engine31 = __toESM(require_Cesium(), 1); var import__748 = __toESM(require_Cesium(), 1); describe("Widgets/ClockViewModel", function() { it("default constructor creates a clock", function() { const clockViewModel = new import__748.ClockViewModel(); expect(clockViewModel.clock).toBeDefined(); }); it("constructor sets expected properties", function() { const clock = new import_engine31.Clock(); clock.startTime = import_engine31.JulianDate.fromIso8601("2012-01-01T00:00:00"); clock.stopTime = import_engine31.JulianDate.fromIso8601("2012-01-02T00:00:00"); clock.currentTime = import_engine31.JulianDate.fromIso8601("2012-01-01T12:00:00"); clock.multiplier = 1; clock.clockStep = import_engine31.ClockStep.TICK_DEPENDENT; clock.clockRange = import_engine31.ClockRange.UNBOUNDED; clock.shouldAnimate = false; const clockViewModel = new import__748.ClockViewModel(clock); expect(clockViewModel.clock).toBe(clock); expect(clockViewModel.startTime).toEqual(clock.startTime); expect(clockViewModel.stopTime).toEqual(clock.stopTime); expect(clockViewModel.currentTime).toEqual(clock.currentTime); expect(clockViewModel.multiplier).toEqual(clock.multiplier); expect(clockViewModel.clockStep).toEqual(clock.clockStep); expect(clockViewModel.clockRange).toEqual(clock.clockRange); expect(clockViewModel.systemTime).toBeDefined(); expect(clockViewModel.shouldAnimate).toEqual(false); }); it("observables are updated from the clock", function() { const clock = new import_engine31.Clock(); clock.startTime = import_engine31.JulianDate.fromIso8601("2012-01-01T00:00:00"); clock.stopTime = import_engine31.JulianDate.fromIso8601("2012-01-02T00:00:00"); clock.currentTime = import_engine31.JulianDate.fromIso8601("2012-01-01T12:00:00"); clock.multiplier = 1; clock.clockStep = import_engine31.ClockStep.TICK_DEPENDENT; clock.clockRange = import_engine31.ClockRange.UNBOUNDED; clock.shouldAnimate = false; const clockViewModel = new import__748.ClockViewModel(clock); expect(clockViewModel.clock).toBe(clock); expect(clockViewModel.startTime).toEqual(clock.startTime); expect(clockViewModel.stopTime).toEqual(clock.stopTime); expect(clockViewModel.currentTime).toEqual(clock.currentTime); expect(clockViewModel.multiplier).toEqual(clock.multiplier); expect(clockViewModel.clockStep).toEqual(clock.clockStep); expect(clockViewModel.clockRange).toEqual(clock.clockRange); expect(clockViewModel.shouldAnimate).toEqual(clock.shouldAnimate); expect(clockViewModel.systemTime).toBeDefined(); clock.startTime = import_engine31.JulianDate.fromIso8601("2013-01-01T00:00:00"); clock.stopTime = import_engine31.JulianDate.fromIso8601("2013-01-02T00:00:00"); clock.currentTime = import_engine31.JulianDate.fromIso8601("2013-01-01T12:00:00"); clock.multiplier = 2; clock.clockStep = import_engine31.ClockStep.SYSTEM_CLOCK_MULTIPLIER; clock.clockRange = import_engine31.ClockRange.CLAMPED; clock.shouldAnimate = true; expect(clockViewModel.startTime).not.toEqual(clock.startTime); expect(clockViewModel.stopTime).not.toEqual(clock.stopTime); expect(clockViewModel.currentTime).not.toEqual(clock.currentTime); expect(clockViewModel.multiplier).not.toEqual(clock.multiplier); expect(clockViewModel.clockStep).not.toEqual(clock.clockStep); expect(clockViewModel.clockRange).not.toEqual(clock.clockRange); expect(clockViewModel.shouldAnimate).not.toEqual(clock.shouldAnimate); clock.tick(); expect(clockViewModel.startTime).toEqual(clock.startTime); expect(clockViewModel.stopTime).toEqual(clock.stopTime); expect(clockViewModel.currentTime).toEqual(clock.currentTime); expect(clockViewModel.multiplier).toEqual(clock.multiplier); expect(clockViewModel.clockStep).toEqual(clock.clockStep); expect(clockViewModel.clockRange).toEqual(clock.clockRange); expect(clockViewModel.shouldAnimate).toEqual(clock.shouldAnimate); }); }); // packages/widgets/Specs/SvgPathBindingHandlerSpec.js var import__749 = __toESM(require_Cesium(), 1); describe("ThirdParty/knockout", function() { it("check binding with constants", function() { const div = document.createElement("div"); div.setAttribute( "data-bind", 'cesiumSvgPath: { path: "M 100 100 L 300 100 L 200 300 Z", width: 28, height: 40, css: "someClass" }' ); document.body.appendChild(div); import__749.knockout.applyBindings({}, div); const svg = div.querySelector("svg.cesium-svgPath-svg"); expect(svg).not.toBeNull(); expect(svg.getAttribute("width")).toEqual("28"); expect(svg.getAttribute("height")).toEqual("40"); expect(svg.getAttribute("class").split(/\s/)).toContain("someClass"); const path = div.querySelector("svg > path"); expect(path).not.toBeNull(); expect(path.getAttribute("d")).toEqual("M 100 100 L 300 100 L 200 300 Z"); import__749.knockout.cleanNode(div); document.body.removeChild(div); }); it("check binding with observables", function() { const div = document.createElement("div"); div.setAttribute( "data-bind", "cesiumSvgPath: { path: p, width: w, height: h, css: c }" ); document.body.appendChild(div); import__749.knockout.applyBindings( { p: import__749.knockout.observable("M 100 100 L 300 100 L 200 300 Z"), w: import__749.knockout.observable(28), h: import__749.knockout.observable(40), c: import__749.knockout.observable("someClass") }, div ); const svg = div.querySelector("svg.cesium-svgPath-svg"); expect(svg).not.toBeNull(); expect(svg.getAttribute("width")).toEqual("28"); expect(svg.getAttribute("height")).toEqual("40"); expect(svg.getAttribute("class").split(/\s/)).toContain("someClass"); const path = div.querySelector("svg > path"); expect(path).not.toBeNull(); expect(path.getAttribute("d")).toEqual("M 100 100 L 300 100 L 200 300 Z"); import__749.knockout.cleanNode(div); document.body.removeChild(div); }); it("check binding with observable parameter object", function() { const div = document.createElement("div"); div.setAttribute("data-bind", "cesiumSvgPath: svgPath"); document.body.appendChild(div); const viewModel = { svgPath: import__749.knockout.observable({ path: import__749.knockout.observable("M 100 100 L 300 100 L 200 300 Z"), width: import__749.knockout.observable(28), height: import__749.knockout.observable(40), css: import__749.knockout.observable("someClass") }) }; import__749.knockout.applyBindings(viewModel, div); const svg = div.querySelector("svg.cesium-svgPath-svg"); expect(svg).not.toBeNull(); expect(svg.getAttribute("width")).toEqual("28"); expect(svg.getAttribute("height")).toEqual("40"); expect(svg.getAttribute("class").split(/\s/)).toContain("someClass"); const path = div.querySelector("svg > path"); expect(path).not.toBeNull(); expect(path.getAttribute("d")).toEqual("M 100 100 L 300 100 L 200 300 Z"); import__749.knockout.cleanNode(div); document.body.removeChild(div); }); }); // packages/widgets/Specs/createCommandSpec.js var import__750 = __toESM(require_Cesium(), 1); // Specs/getArguments.js function getArguments() { return arguments; } var getArguments_default = getArguments; // packages/widgets/Specs/createCommandSpec.js describe("Widgets/createCommand", function() { let spyFunction; const spyFunctionReturnValue = 5; beforeEach(function() { spyFunction = jasmine.createSpy("spyFunction").and.returnValue(spyFunctionReturnValue); }); it("works with default value of canExecute", function() { const command = (0, import__750.createCommand)(spyFunction); expect(command.canExecute).toBe(true); expect(command()).toBe(spyFunctionReturnValue); expect(spyFunction).toHaveBeenCalled(); }); it("throws when canExecute value is false", function() { const command = (0, import__750.createCommand)(spyFunction, false); expect(function() { command(); }).toThrowDeveloperError(); expect(spyFunction).not.toHaveBeenCalled(); }); it("throws without a func parameter", function() { expect(function() { return (0, import__750.createCommand)(void 0); }).toThrowDeveloperError(); }); it("works with custom canExecute observable", function() { const canExecute = import__750.knockout.observable(false); const command = (0, import__750.createCommand)(spyFunction, canExecute); expect(command.canExecute).toBe(false); expect(function() { command(); }).toThrowDeveloperError(); expect(spyFunction).not.toHaveBeenCalled(); canExecute(true); expect(command.canExecute).toBe(true); expect(command()).toBe(spyFunctionReturnValue); expect(spyFunction).toHaveBeenCalled(); }); it("calls pre/post events", function() { const command = (0, import__750.createCommand)(spyFunction); const myArg = {}; const beforeExecuteSpy = jasmine.createSpy("beforeExecute"); command.beforeExecute.addEventListener(beforeExecuteSpy); const afterExecuteSpy = jasmine.createSpy("afterExecute"); command.afterExecute.addEventListener(afterExecuteSpy); expect(command(myArg)).toBe(spyFunctionReturnValue); expect(beforeExecuteSpy.calls.count()).toEqual(1); expect(beforeExecuteSpy).toHaveBeenCalledWith({ cancel: false, args: getArguments_default(myArg) }); expect(afterExecuteSpy.calls.count()).toEqual(1); expect(afterExecuteSpy).toHaveBeenCalledWith(spyFunctionReturnValue); }); it("cancels a command if beforeExecute sets cancel to true", function() { const command = (0, import__750.createCommand)(spyFunction); const myArg = {}; const beforeExecuteSpy = jasmine.createSpy("beforeExecute").and.callFake(function(info) { info.cancel = true; }); command.beforeExecute.addEventListener(beforeExecuteSpy); const afterExecuteSpy = jasmine.createSpy("afterExecute"); command.afterExecute.addEventListener(afterExecuteSpy); expect(command(myArg)).toBeUndefined(); expect(beforeExecuteSpy.calls.count()).toEqual(1); expect(afterExecuteSpy).not.toHaveBeenCalled(); }); }); // packages/widgets/Specs/Animation/AnimationSpec.js var import_engine32 = __toESM(require_Cesium(), 1); var import__751 = __toESM(require_Cesium(), 1); describe("Widgets/Animation/Animation", function() { let container; let animation; afterEach(function() { if ((0, import_engine32.defined)(animation)) { animation = animation.destroy(); } if ((0, import_engine32.defined)(container) && (0, import_engine32.defined)(container.parentNode)) { container.parentNode.removeChild(container); } }); it("Can create and destroy", function() { const clockViewModel = new import__751.ClockViewModel(); const animationViewModel = new import__751.AnimationViewModel(clockViewModel); animation = new import__751.Animation(document.body, animationViewModel); }); it("Can create with container not in the DOM", function() { container = document.createElement("div"); const clockViewModel = new import__751.ClockViewModel(); const animationViewModel = new import__751.AnimationViewModel(clockViewModel); const animation2 = new import__751.Animation(container, animationViewModel); spyOn(animation2, "applyThemeChanges").and.callThrough(); document.body.appendChild(container); return pollToPromise_default(function() { return animation2.applyThemeChanges.calls.count() === 1; }); }); it("Can destroy without container ever being in the DOM", function() { container = document.createElement("div"); const clockViewModel = new import__751.ClockViewModel(); const animationViewModel = new import__751.AnimationViewModel(clockViewModel); animation = new import__751.Animation(container, animationViewModel); }); }); // packages/widgets/Specs/Animation/AnimationViewModelSpec.js var import_engine33 = __toESM(require_Cesium(), 1); var import__752 = __toESM(require_Cesium(), 1); describe("Widgets/Animation/AnimationViewModel", function() { let clockViewModel; beforeEach(function() { clockViewModel = new import__752.ClockViewModel(); }); function verifyPausedState(viewModel) { expect(viewModel.pauseViewModel.toggled).toEqual(true); expect(viewModel.playReverseViewModel.toggled).toEqual(false); expect(viewModel.playForwardViewModel.toggled).toEqual(false); expect(viewModel.playRealtimeViewModel.toggled).toEqual(false); } function verifyForwardState(viewModel) { expect(viewModel.pauseViewModel.toggled).toEqual(false); expect(viewModel.playReverseViewModel.toggled).toEqual(false); expect(viewModel.playForwardViewModel.toggled).toEqual(true); expect(viewModel.playRealtimeViewModel.toggled).toEqual(false); } function verifyReverseState(viewModel) { expect(viewModel.pauseViewModel.toggled).toEqual(false); expect(viewModel.playReverseViewModel.toggled).toEqual(true); expect(viewModel.playForwardViewModel.toggled).toEqual(false); expect(viewModel.playRealtimeViewModel.toggled).toEqual(false); } function verifyRealtimeState(viewModel) { expect(viewModel.pauseViewModel.toggled).toEqual(false); expect(viewModel.playReverseViewModel.toggled).toEqual(false); expect(viewModel.playForwardViewModel.toggled).toEqual(false); expect(viewModel.playRealtimeViewModel.toggled).toEqual(true); expect(viewModel.shuttleRingAngle).toEqual( import__752.AnimationViewModel._realtimeShuttleRingAngle ); } it("constructor sets expected properties", function() { const animationViewModel = new import__752.AnimationViewModel(clockViewModel); expect(animationViewModel.clockViewModel).toBe(clockViewModel); }); it("setTimeFormatter overrides the default formatter", function() { const animationViewModel = new import__752.AnimationViewModel(clockViewModel); const expectedString = "My Time"; const myCustomFormatter = function(date) { expect(date).toEqual(clockViewModel.currentTime); return expectedString; }; animationViewModel.timeFormatter = myCustomFormatter; expect(animationViewModel.timeLabel).toEqual(expectedString); expect(animationViewModel.timeFormatter).toEqual(myCustomFormatter); }); it("defaultTimeFormatter produces expected result", function() { const animationViewModel = new import__752.AnimationViewModel(clockViewModel); const date = import_engine33.JulianDate.fromIso8601("2012-03-05T06:07:08.89Z"); clockViewModel.multiplier = 1; let expectedResult = "06:07:08 UTC"; let result = animationViewModel.timeFormatter(date, animationViewModel); expect(result).toEqual(expectedResult); clockViewModel.multiplier = -1; expectedResult = "06:07:08 UTC"; result = animationViewModel.timeFormatter(date, animationViewModel); expect(result).toEqual(expectedResult); clockViewModel.multiplier = -0.5; expectedResult = "06:07:08.890"; result = animationViewModel.timeFormatter(date, animationViewModel); expect(result).toEqual(expectedResult); clockViewModel.multiplier = 0.5; expectedResult = "06:07:08.890"; result = animationViewModel.timeFormatter(date, animationViewModel); expect(result).toEqual(expectedResult); }); it("setDateFormatter overrides the default formatter", function() { const animationViewModel = new import__752.AnimationViewModel(clockViewModel); const expectedString = "My Date"; const myCustomFormatter = function(date) { expect(date).toEqual(clockViewModel.currentTime); return expectedString; }; animationViewModel.dateFormatter = myCustomFormatter; expect(animationViewModel.dateLabel).toEqual(expectedString); expect(animationViewModel.dateFormatter).toEqual(myCustomFormatter); }); it("defaultDateFormatter produces expected result", function() { const animationViewModel = new import__752.AnimationViewModel(new import__752.ClockViewModel()); let date = import_engine33.JulianDate.fromIso8601("2012-01-05T06:07:08.89Z"); let expectedResult = "Jan 5 2012"; let result = animationViewModel.dateFormatter(date, animationViewModel); expect(result).toEqual(expectedResult); date = import_engine33.JulianDate.fromIso8601("2012-02-05T06:07:08.89Z"); expectedResult = "Feb 5 2012"; result = animationViewModel.dateFormatter(date, animationViewModel); expect(result).toEqual(expectedResult); date = import_engine33.JulianDate.fromIso8601("2012-03-05T06:07:08.89Z"); expectedResult = "Mar 5 2012"; result = animationViewModel.dateFormatter(date, animationViewModel); expect(result).toEqual(expectedResult); date = import_engine33.JulianDate.fromIso8601("2012-04-05T06:07:08.89Z"); expectedResult = "Apr 5 2012"; result = animationViewModel.dateFormatter(date, animationViewModel); expect(result).toEqual(expectedResult); date = import_engine33.JulianDate.fromIso8601("2012-05-05T06:07:08.89Z"); expectedResult = "May 5 2012"; result = animationViewModel.dateFormatter(date, animationViewModel); expect(result).toEqual(expectedResult); date = import_engine33.JulianDate.fromIso8601("2012-06-05T06:07:08.89Z"); expectedResult = "Jun 5 2012"; result = animationViewModel.dateFormatter(date, animationViewModel); expect(result).toEqual(expectedResult); date = import_engine33.JulianDate.fromIso8601("2012-07-05T06:07:08.89Z"); expectedResult = "Jul 5 2012"; result = animationViewModel.dateFormatter(date, animationViewModel); expect(result).toEqual(expectedResult); date = import_engine33.JulianDate.fromIso8601("2012-08-05T06:07:08.89Z"); expectedResult = "Aug 5 2012"; result = animationViewModel.dateFormatter(date, animationViewModel); expect(result).toEqual(expectedResult); date = import_engine33.JulianDate.fromIso8601("2012-09-05T06:07:08.89Z"); expectedResult = "Sep 5 2012"; result = animationViewModel.dateFormatter(date, animationViewModel); expect(result).toEqual(expectedResult); date = import_engine33.JulianDate.fromIso8601("2012-10-05T06:07:08.89Z"); expectedResult = "Oct 5 2012"; result = animationViewModel.dateFormatter(date, animationViewModel); expect(result).toEqual(expectedResult); date = import_engine33.JulianDate.fromIso8601("2012-11-05T06:07:08.89Z"); expectedResult = "Nov 5 2012"; result = animationViewModel.dateFormatter(date, animationViewModel); expect(result).toEqual(expectedResult); date = import_engine33.JulianDate.fromIso8601("2012-12-05T06:07:08.89Z"); expectedResult = "Dec 5 2012"; result = animationViewModel.dateFormatter(date, animationViewModel); expect(result).toEqual(expectedResult); }); it("correctly formats speed label", function() { const animationViewModel = new import__752.AnimationViewModel(clockViewModel); let expectedString; clockViewModel.clockStep = import_engine33.ClockStep.TICK_DEPENDENT; clockViewModel.multiplier = 123.1; expectedString = "123.1x"; expect(animationViewModel.multiplierLabel).toEqual(expectedString); clockViewModel.clockStep = import_engine33.ClockStep.TICK_DEPENDENT; clockViewModel.multiplier = 123.12; expectedString = "123.12x"; expect(animationViewModel.multiplierLabel).toEqual(expectedString); clockViewModel.clockStep = import_engine33.ClockStep.TICK_DEPENDENT; clockViewModel.multiplier = 123.123; expectedString = "123.123x"; expect(animationViewModel.multiplierLabel).toEqual(expectedString); clockViewModel.clockStep = import_engine33.ClockStep.TICK_DEPENDENT; clockViewModel.multiplier = 123.1236; expectedString = "123.124x"; expect(animationViewModel.multiplierLabel).toEqual(expectedString); clockViewModel.clockStep = import_engine33.ClockStep.SYSTEM_CLOCK; expectedString = "Today"; expect(animationViewModel.multiplierLabel).toEqual(expectedString); clockViewModel.clockStep = import_engine33.ClockStep.TICK_DEPENDENT; clockViewModel.multiplier = 15; expectedString = "15x"; expect(animationViewModel.multiplierLabel).toEqual(expectedString); }); it("pause button restores current state", function() { clockViewModel.startTime = import_engine33.JulianDate.fromIso8601("2012-01-01T00:00:00"); clockViewModel.stopTime = import_engine33.JulianDate.fromIso8601("2012-01-02T00:00:00"); clockViewModel.currentTime = import_engine33.JulianDate.fromIso8601("2012-01-01T12:00:00"); clockViewModel.multiplier = 1; clockViewModel.clockStep = import_engine33.ClockStep.TICK_DEPENDENT; clockViewModel.clockRange = import_engine33.ClockRange.UNBOUNDED; clockViewModel.shouldAnimate = false; const viewModel = new import__752.AnimationViewModel(clockViewModel); verifyPausedState(viewModel); viewModel.pauseViewModel.command(); verifyForwardState(viewModel); viewModel.pauseViewModel.command(); verifyPausedState(viewModel); clockViewModel.multiplier = -1; viewModel.pauseViewModel.command(); verifyReverseState(viewModel); }); it("animating forwards negates the multiplier if it is negative", function() { const viewModel = new import__752.AnimationViewModel(clockViewModel); const multiplier = -100; clockViewModel.multiplier = multiplier; viewModel.playForwardViewModel.command(); expect(clockViewModel.multiplier).toEqual(-multiplier); }); it("animating backwards negates the multiplier if it is positive", function() { const viewModel = new import__752.AnimationViewModel(clockViewModel); const multiplier = 100; clockViewModel.multiplier = multiplier; viewModel.playReverseViewModel.command(); expect(clockViewModel.multiplier).toEqual(-multiplier); }); it("animating backwards pauses with a bounded startTime", function() { const centerTime = import_engine33.JulianDate.fromIso8601("2012-01-01T12:00:00"); clockViewModel.startTime = import_engine33.JulianDate.fromIso8601("2012-01-01T00:00:00"); clockViewModel.stopTime = import_engine33.JulianDate.fromIso8601("2012-01-02T00:00:00"); clockViewModel.clockStep = import_engine33.ClockStep.TICK_DEPENDENT; clockViewModel.currentTime = centerTime; clockViewModel.shouldAnimate = false; const viewModel = new import__752.AnimationViewModel(clockViewModel); verifyPausedState(viewModel); clockViewModel.multiplier = -1; clockViewModel.clockRange = import_engine33.ClockRange.CLAMPED; viewModel.playReverseViewModel.command(); verifyReverseState(viewModel); clockViewModel.currentTime = clockViewModel.startTime; verifyPausedState(viewModel); clockViewModel.currentTime = centerTime; clockViewModel.clockRange = import_engine33.ClockRange.LOOP_STOP; viewModel.playReverseViewModel.command(); verifyReverseState(viewModel); clockViewModel.currentTime = clockViewModel.startTime; verifyPausedState(viewModel); viewModel.playReverseViewModel.command(); verifyPausedState(viewModel); clockViewModel.clockRange = import_engine33.ClockRange.UNBOUNDED; viewModel.playReverseViewModel.command(); verifyReverseState(viewModel); }); it("dragging shuttle ring does not pause with bounded start or stop Time", function() { const centerTime = import_engine33.JulianDate.fromIso8601("2012-01-01T12:00:00"); clockViewModel.startTime = import_engine33.JulianDate.fromIso8601("2012-01-01T00:00:00"); clockViewModel.stopTime = import_engine33.JulianDate.fromIso8601("2012-01-02T00:00:00"); clockViewModel.clockStep = import_engine33.ClockStep.TICK_DEPENDENT; clockViewModel.clockRange = import_engine33.ClockRange.CLAMPED; clockViewModel.multiplier = 1; const viewModel = new import__752.AnimationViewModel(clockViewModel); verifyPausedState(viewModel); clockViewModel.currentTime = centerTime; viewModel.playForwardViewModel.command(); verifyForwardState(viewModel); viewModel.shuttleRingDragging = true; clockViewModel.currentTime = clockViewModel.stopTime; verifyForwardState(viewModel); viewModel.shuttleRingDragging = false; verifyPausedState(viewModel); clockViewModel.currentTime = centerTime; viewModel.playReverseViewModel.command(); verifyReverseState(viewModel); viewModel.shuttleRingDragging = true; clockViewModel.currentTime = clockViewModel.startTime; verifyReverseState(viewModel); viewModel.shuttleRingDragging = false; verifyPausedState(viewModel); }); it("animating forward pauses with a bounded stopTime", function() { const centerTime = import_engine33.JulianDate.fromIso8601("2012-01-01T12:00:00"); clockViewModel.startTime = import_engine33.JulianDate.fromIso8601("2012-01-01T00:00:00"); clockViewModel.stopTime = import_engine33.JulianDate.fromIso8601("2012-01-02T00:00:00"); clockViewModel.clockStep = import_engine33.ClockStep.TICK_DEPENDENT; clockViewModel.currentTime = centerTime; clockViewModel.shouldAnimate = false; const viewModel = new import__752.AnimationViewModel(clockViewModel); verifyPausedState(viewModel); clockViewModel.multiplier = 1; clockViewModel.clockRange = import_engine33.ClockRange.CLAMPED; viewModel.playForwardViewModel.command(); verifyForwardState(viewModel); clockViewModel.currentTime = clockViewModel.stopTime; verifyPausedState(viewModel); viewModel.playForwardViewModel.command(); verifyPausedState(viewModel); clockViewModel.clockRange = import_engine33.ClockRange.UNBOUNDED; viewModel.playForwardViewModel.command(); verifyForwardState(viewModel); }); it("slower has no effect if at the slowest speed", function() { const viewModel = new import__752.AnimationViewModel(clockViewModel); viewModel.setShuttleRingTicks([0, 1, 2]); const slowestMultiplier = -2; clockViewModel.multiplier = slowestMultiplier; viewModel.slower(); expect(clockViewModel.multiplier).toEqual(slowestMultiplier); }); it("faster has no effect if at the faster speed", function() { const viewModel = new import__752.AnimationViewModel(clockViewModel); viewModel.setShuttleRingTicks([0, 1, 2]); const fastestMultiplier = 2; clockViewModel.multiplier = fastestMultiplier; viewModel.faster(); expect(clockViewModel.multiplier).toEqual(fastestMultiplier); }); it("slower and faster cycle through defined multipliers", function() { const viewModel = new import__752.AnimationViewModel(clockViewModel); let i = 0; const multipliers = viewModel.getShuttleRingTicks(); const length2 = multipliers.length; clockViewModel.multiplier = multipliers[0]; for (i = 1; i < length2; i++) { viewModel.faster(); expect(clockViewModel.multiplier).toEqual(multipliers[i]); } expect(clockViewModel.multiplier).toEqual(multipliers[length2 - 1]); for (i = length2 - 2; i >= 0; i--) { viewModel.slower(); expect(clockViewModel.multiplier).toEqual(multipliers[i]); } expect(clockViewModel.multiplier).toEqual(multipliers[0]); }); it("Realtime canExecute and tooltip depends on clock settings", function() { const viewModel = new import__752.AnimationViewModel(clockViewModel); clockViewModel.systemTime = import_engine33.JulianDate.now(); clockViewModel.clockRange = import_engine33.ClockRange.UNBOUNDED; clockViewModel.startTime = import_engine33.JulianDate.addSeconds( clockViewModel.systemTime, -60, new import_engine33.JulianDate() ); clockViewModel.stopTime = import_engine33.JulianDate.addSeconds( clockViewModel.systemTime, -30, new import_engine33.JulianDate() ); expect(viewModel.playRealtimeViewModel.command.canExecute).toEqual(true); expect(viewModel.playRealtimeViewModel.tooltip).toEqual( "Today (real-time)" ); clockViewModel.clockRange = import_engine33.ClockRange.CLAMPED; clockViewModel.startTime = import_engine33.JulianDate.addSeconds( clockViewModel.systemTime, -60, new import_engine33.JulianDate() ); clockViewModel.stopTime = import_engine33.JulianDate.addSeconds( clockViewModel.systemTime, -30, new import_engine33.JulianDate() ); expect(viewModel.playRealtimeViewModel.command.canExecute).toEqual(false); expect(viewModel.playRealtimeViewModel.tooltip).toEqual( "Current time not in range" ); clockViewModel.clockRange = import_engine33.ClockRange.CLAMPED; clockViewModel.startTime = import_engine33.JulianDate.addSeconds( clockViewModel.systemTime, -60, new import_engine33.JulianDate() ); clockViewModel.stopTime = import_engine33.JulianDate.addSeconds( clockViewModel.systemTime, 60, new import_engine33.JulianDate() ); expect(viewModel.playRealtimeViewModel.command.canExecute).toEqual(true); expect(viewModel.playRealtimeViewModel.tooltip).toEqual( "Today (real-time)" ); clockViewModel.clockRange = import_engine33.ClockRange.LOOP_STOP; clockViewModel.startTime = import_engine33.JulianDate.addSeconds( clockViewModel.systemTime, -60, new import_engine33.JulianDate() ); clockViewModel.stopTime = import_engine33.JulianDate.addSeconds( clockViewModel.systemTime, -30, new import_engine33.JulianDate() ); expect(viewModel.playRealtimeViewModel.command.canExecute).toEqual(false); expect(viewModel.playRealtimeViewModel.tooltip).toEqual( "Current time not in range" ); clockViewModel.clockRange = import_engine33.ClockRange.LOOP_STOP; clockViewModel.startTime = import_engine33.JulianDate.addSeconds( clockViewModel.systemTime, -60, new import_engine33.JulianDate() ); clockViewModel.stopTime = import_engine33.JulianDate.addSeconds( clockViewModel.systemTime, 60, new import_engine33.JulianDate() ); expect(viewModel.playRealtimeViewModel.command.canExecute).toEqual(true); expect(viewModel.playRealtimeViewModel.tooltip).toEqual( "Today (real-time)" ); }); it("User action breaks out of realtime mode", function() { const viewModel = new import__752.AnimationViewModel(clockViewModel); clockViewModel.clockStep = import_engine33.ClockStep.TICK_DEPENDENT; clockViewModel.clockRange = import_engine33.ClockRange.UNBOUNDED; viewModel.playRealtimeViewModel.command(); verifyRealtimeState(viewModel); expect(clockViewModel.multiplier).toEqual(1); viewModel.pauseViewModel.command(); verifyPausedState(viewModel); expect(clockViewModel.multiplier).toEqual(1); viewModel.playRealtimeViewModel.command(); verifyRealtimeState(viewModel); viewModel.playReverseViewModel.command(); verifyReverseState(viewModel); expect(clockViewModel.multiplier).toEqual(-1); viewModel.playRealtimeViewModel.command(); verifyRealtimeState(viewModel); viewModel.playForwardViewModel.command(); verifyRealtimeState(viewModel); expect(clockViewModel.multiplier).toEqual(1); viewModel.playRealtimeViewModel.command(); verifyRealtimeState(viewModel); viewModel.shuttleRingAngle = viewModel.shuttleRingAngle + 1; verifyForwardState(viewModel); }); it("real time mode toggles off but not back on when shouldAnimate changes", function() { const viewModel = new import__752.AnimationViewModel(clockViewModel); viewModel.playRealtimeViewModel.command(); verifyRealtimeState(viewModel); clockViewModel.shouldAnimate = false; expect(viewModel.playRealtimeViewModel.toggled).toEqual(false); clockViewModel.shouldAnimate = true; expect(viewModel.playRealtimeViewModel.toggled).toEqual(false); }); it("Shuttle ring angles set expected multipliers", function() { const viewModel = new import__752.AnimationViewModel(clockViewModel); const shuttleRingTicks = viewModel.getShuttleRingTicks(); const maxMultiplier = shuttleRingTicks[shuttleRingTicks.length - 1]; const minMultiplier = -maxMultiplier; viewModel.shuttleRingAngle = import__752.AnimationViewModel._maxShuttleRingAngle; expect(clockViewModel.multiplier).toEqual(maxMultiplier); viewModel.shuttleRingAngle = -import__752.AnimationViewModel._maxShuttleRingAngle; expect(clockViewModel.multiplier).toEqual(minMultiplier); viewModel.shuttleRingAngle = import__752.AnimationViewModel._realtimeShuttleRingAngle; expect(clockViewModel.multiplier).toEqual(1); viewModel.shuttleRingAngle = -import__752.AnimationViewModel._realtimeShuttleRingAngle; expect(clockViewModel.multiplier).toEqual(-1); viewModel.shuttleRingAngle = 45; expect(clockViewModel.multiplier).toEqual(85); viewModel.shuttleRingAngle = -90; expect(clockViewModel.multiplier).toEqual(-66e3); viewModel.shuttleRingAngle = 0; expect(clockViewModel.multiplier).toEqual(0); }); it("Shuttle ring angles set expected multipliers when snapping to ticks", function() { const viewModel = new import__752.AnimationViewModel(clockViewModel); viewModel.snapToTicks = true; const shuttleRingTicks = viewModel.getShuttleRingTicks(); const maxMultiplier = shuttleRingTicks[shuttleRingTicks.length - 1]; const minMultiplier = -maxMultiplier; viewModel.shuttleRingAngle = import__752.AnimationViewModel._maxShuttleRingAngle; expect(clockViewModel.multiplier).toEqual(maxMultiplier); viewModel.shuttleRingAngle = -import__752.AnimationViewModel._maxShuttleRingAngle; expect(clockViewModel.multiplier).toEqual(minMultiplier); viewModel.shuttleRingAngle = import__752.AnimationViewModel._realtimeShuttleRingAngle; expect(clockViewModel.multiplier).toEqual(1); viewModel.shuttleRingAngle = -import__752.AnimationViewModel._realtimeShuttleRingAngle; expect(clockViewModel.multiplier).toEqual(-1); viewModel.shuttleRingAngle = 45; expect(clockViewModel.multiplier).toEqual(120); viewModel.shuttleRingAngle = -90; expect(clockViewModel.multiplier).toEqual(-43200); viewModel.shuttleRingAngle = 0; expect(clockViewModel.multiplier).toEqual( import__752.AnimationViewModel.defaultTicks[0] ); }); it("throws when constructed without arguments", function() { expect(function() { return new import__752.AnimationViewModel(); }).toThrowDeveloperError(); }); it("setting timeFormatter throws with non-function", function() { const animationViewModel = new import__752.AnimationViewModel(clockViewModel); expect(function() { animationViewModel.timeFormatter = {}; }).toThrowDeveloperError(); }); it("setting dateFormatter throws with non-function", function() { const animationViewModel = new import__752.AnimationViewModel(clockViewModel); expect(function() { animationViewModel.dateFormatter = {}; }).toThrowDeveloperError(); }); it("setting shuttleRingTicks throws with undefined", function() { const animationViewModel = new import__752.AnimationViewModel(clockViewModel); expect(function() { animationViewModel.setShuttleRingTicks(void 0); }).toThrowDeveloperError(); }); it("returns a copy of shuttleRingTicks when getting", function() { const animationViewModel = new import__752.AnimationViewModel(clockViewModel); const originalTicks = [0, 1, 2]; animationViewModel.setShuttleRingTicks(originalTicks); const ticks = animationViewModel.getShuttleRingTicks(); ticks.push(99); ticks[0] = -99; expect(animationViewModel.getShuttleRingTicks()).toEqual(originalTicks); }); it("sorts shuttleRingTicks when setting", function() { const animationViewModel = new import__752.AnimationViewModel(clockViewModel); const ticks = [4, 0, 8, 2]; animationViewModel.setShuttleRingTicks(ticks); expect(animationViewModel.getShuttleRingTicks()).toEqual([ 0, 2, 4, 8 ]); }); }); // packages/widgets/Specs/BaseLayerPicker/BaseLayerPickerSpec.js var import_engine34 = __toESM(require_Cesium(), 1); var import__753 = __toESM(require_Cesium(), 1); describe("Widgets/BaseLayerPicker/BaseLayerPicker", function() { function MockGlobe() { this.imageryLayers = new import_engine34.ImageryLayerCollection(); this.terrainProvider = new import_engine34.EllipsoidTerrainProvider(); } it("can create and destroy", function() { const container = document.createElement("div"); container.id = "testContainer"; document.body.appendChild(container); const globe2 = new MockGlobe(); const widget = new import__753.BaseLayerPicker("testContainer", { globe: globe2 }); expect(widget.container).toBe(container); expect(widget.viewModel.globe).toBe(globe2); expect(widget.isDestroyed()).toEqual(false); widget.destroy(); expect(widget.isDestroyed()).toEqual(true); document.body.removeChild(container); }); function addCloseOnInputSpec(name, func) { it(`${name} event closes dropdown if target is not inside container`, function() { const container = document.createElement("div"); container.id = "testContainer"; document.body.appendChild(container); const widget = new import__753.BaseLayerPicker("testContainer", { globe: new MockGlobe() }); widget.viewModel.dropDownVisible = true; func(document.body); expect(widget.viewModel.dropDownVisible).toEqual(false); widget.viewModel.dropDownVisible = true; func(container.firstChild); expect(widget.viewModel.dropDownVisible).toEqual(true); widget.destroy(); document.body.removeChild(container); }); } if (import_engine34.FeatureDetection.supportsPointerEvents()) { addCloseOnInputSpec("pointerDown", DomEventSimulator_default.firePointerDown); } else { addCloseOnInputSpec("mousedown", DomEventSimulator_default.fireMouseDown); addCloseOnInputSpec("touchstart", DomEventSimulator_default.fireTouchStart); } it("constructor throws with no layer collection", function() { expect(function() { return new import__753.BaseLayerPicker(document.body, void 0); }).toThrowDeveloperError(); }); it("constructor throws with no element", function() { expect(function() { return new import__753.BaseLayerPicker(void 0, { globe: new MockGlobe() }); }).toThrowDeveloperError(); }); it("constructor throws with string element that does not exist", function() { expect(function() { return new import__753.BaseLayerPicker("does not exist", { globe: new MockGlobe() }); }).toThrowDeveloperError(); }); }); // packages/widgets/Specs/BaseLayerPicker/BaseLayerPickerViewModelSpec.js var import_engine35 = __toESM(require_Cesium(), 1); var import__754 = __toESM(require_Cesium(), 1); describe("Widgets/BaseLayerPicker/BaseLayerPickerViewModel", function() { function MockGlobe() { this.imageryLayers = new import_engine35.ImageryLayerCollection(); this.terrainProvider = new import_engine35.EllipsoidTerrainProvider(); this.terrainProviderChanged = new import_engine35.Event(); this.depthTestAgainstTerrain = false; } MockGlobe.prototype.isDestroyed = () => false; const testProvider = { tilingScheme: new import_engine35.GeographicTilingScheme() }; const testProvider2 = { tilingScheme: new import_engine35.GeographicTilingScheme() }; const testProvider3 = { tilingScheme: new import_engine35.GeographicTilingScheme() }; const testEllipsoidProviderViewModel = new import__754.ProviderViewModel({ name: "name", tooltip: "tooltip", iconUrl: "url", creationFunction: function() { return new import_engine35.EllipsoidTerrainProvider(); } }); const testProviderViewModel = new import__754.ProviderViewModel({ name: "name", tooltip: "tooltip", iconUrl: "url", creationFunction: function() { return testProvider; } }); const testProviderViewModel2 = new import__754.ProviderViewModel({ name: "name2", tooltip: "tooltip2", iconUrl: "url2", creationFunction: function() { return [testProvider, testProvider2]; } }); const testProviderViewModel3 = new import__754.ProviderViewModel({ name: "name3", tooltip: "tooltip3", iconUrl: "url3", creationFunction: function() { return testProvider3; } }); const testProviderViewModelAsync = new import__754.ProviderViewModel({ name: "name3", tooltip: "tooltip3", iconUrl: "url3", creationFunction: async function() { return testProvider; } }); it("constructor sets expected values", function() { const imageryViewModels = []; const terrainViewModels = []; const globe2 = new MockGlobe(); const viewModel = new import__754.BaseLayerPickerViewModel({ globe: globe2, imageryProviderViewModels: imageryViewModels, terrainProviderViewModels: terrainViewModels }); expect(viewModel.globe).toBe(globe2); expect(viewModel.imageryProviderViewModels.length).toBe(0); expect(viewModel.terrainProviderViewModels.length).toBe(0); }); it("separates providers into categories", function() { const imageryProviders = [ new import__754.ProviderViewModel({ name: "name", tooltip: "tooltip", iconUrl: "url", category: "cat1", creationFunction: function() { return testProvider; } }), new import__754.ProviderViewModel({ name: "name", tooltip: "tooltip", iconUrl: "url", category: "cat1", creationFunction: function() { return testProvider; } }), new import__754.ProviderViewModel({ name: "name", tooltip: "tooltip", iconUrl: "url", category: "cat2", creationFunction: function() { return testProvider; } }) ]; const terrainProviders = [ new import__754.ProviderViewModel({ name: "name", tooltip: "tooltip", iconUrl: "url", category: "cat1", creationFunction: function() { return testProvider; } }), new import__754.ProviderViewModel({ name: "name", tooltip: "tooltip", iconUrl: "url", category: "cat2", creationFunction: function() { return testProvider; } }), new import__754.ProviderViewModel({ name: "name", tooltip: "tooltip", iconUrl: "url", category: "cat2", creationFunction: function() { return testProvider; } }) ]; const viewModel = new import__754.BaseLayerPickerViewModel({ globe: new MockGlobe(), imageryProviderViewModels: imageryProviders, terrainProviderViewModels: terrainProviders }); expect(viewModel._imageryProviders).toBeDefined(); expect(viewModel._imageryProviders().length).toBe(2); expect(viewModel._imageryProviders()[0].providers.length).toBe(2); expect(viewModel._imageryProviders()[0].name).toBe("cat1"); expect(viewModel._imageryProviders()[1].providers.length).toBe(1); expect(viewModel._imageryProviders()[1].name).toBe("cat2"); expect(viewModel._terrainProviders).toBeDefined(); expect(viewModel._terrainProviders().length).toBe(2); expect(viewModel._terrainProviders()[0].providers.length).toBe(1); expect(viewModel._terrainProviders()[0].name).toBe("cat1"); expect(viewModel._terrainProviders()[1].providers.length).toBe(2); expect(viewModel._terrainProviders()[1].name).toBe("cat2"); }); it("selecting imagery closes the dropDown", function() { const imageryViewModels = [testProviderViewModel]; const globe2 = new MockGlobe(); const viewModel = new import__754.BaseLayerPickerViewModel({ globe: globe2, imageryProviderViewModels: imageryViewModels }); viewModel.dropDownVisible = true; viewModel.selectedImagery = testProviderViewModel; expect(viewModel.dropDownVisible).toEqual(false); }); it("selecting terrain closes the dropDown", async function() { const imageryViewModels = [testProviderViewModel]; const globe2 = new MockGlobe(); const viewModel = new import__754.BaseLayerPickerViewModel({ globe: globe2, imageryProviderViewModels: imageryViewModels }); viewModel.dropDownVisible = true; viewModel.selectedTerrain = testProviderViewModel; await testProviderViewModel.creationCommand(); expect(viewModel.dropDownVisible).toEqual(false); }); it("tooltip, buttonImageUrl, and selectedImagery all return expected values", async function() { const imageryViewModels = [testProviderViewModel]; const terrainViewModels = [testProviderViewModel3]; const globe2 = new MockGlobe(); const viewModel = new import__754.BaseLayerPickerViewModel({ globe: globe2, imageryProviderViewModels: imageryViewModels, terrainProviderViewModels: terrainViewModels }); viewModel.selectedImagery = testProviderViewModel; await testProviderViewModel.creationCommand(); expect(viewModel.buttonTooltip).toEqual( `${testProviderViewModel.name} ${testProviderViewModel3.name}` ); viewModel.selectedImagery = void 0; expect(viewModel.buttonTooltip).toEqual(testProviderViewModel3.name); viewModel.selectedImagery = testProviderViewModel; await testProviderViewModel.creationCommand(); viewModel.selectedTerrain = void 0; expect(viewModel.buttonTooltip).toEqual(testProviderViewModel.name); expect(viewModel.buttonImageUrl).toEqual(testProviderViewModel.iconUrl); }); it("selectedImagery actually sets base layer", async function() { const imageryViewModels = [testProviderViewModel]; const globe2 = new MockGlobe(); const imageryLayers = globe2.imageryLayers; const viewModel = new import__754.BaseLayerPickerViewModel({ globe: globe2, imageryProviderViewModels: imageryViewModels }); expect(imageryLayers.length).toEqual(1); viewModel.selectedImagery = testProviderViewModel; expect(imageryLayers.length).toEqual(1); await pollToPromise_default(() => imageryLayers.get(0).ready); expect(imageryLayers.get(0).imageryProvider).toBe(testProvider); viewModel.selectedImagery = testProviderViewModel2; expect(imageryLayers.length).toEqual(2); await pollToPromise_default(() => imageryLayers.get(0).ready); expect(imageryLayers.get(0).imageryProvider).toBe(testProvider); await pollToPromise_default(() => imageryLayers.get(1).ready); expect(imageryLayers.get(1).imageryProvider).toBe(testProvider2); }); it("selectedTerrain actually sets terrainProvider", async function() { const terrainProviderViewModels = [ testProviderViewModel, testProviderViewModel3 ]; const globe2 = new MockGlobe(); const viewModel = new import__754.BaseLayerPickerViewModel({ globe: globe2, terrainProviderViewModels }); viewModel.selectedTerrain = testProviderViewModel3; await testProviderViewModel3.creationCommand(); expect(globe2.terrainProvider).toBe(testProvider3); }); it("selectedTerrain actually sets async terrainProvider", async function() { const terrainProviderViewModels = [ testProviderViewModel, testProviderViewModelAsync ]; const globe2 = new MockGlobe(); const viewModel = new import__754.BaseLayerPickerViewModel({ globe: globe2, terrainProviderViewModels }); viewModel.selectedTerrain = testProviderViewModelAsync; await testProviderViewModelAsync.creationCommand(); expect(globe2.terrainProvider).toBe(testProvider); expect(globe2.depthTestAgainstTerrain).toBeTrue(); }); it("selectedTerrain sets ellipsoid terrain provider", async function() { const terrainProviderViewModels = [testEllipsoidProviderViewModel]; const globe2 = new MockGlobe(); const viewModel = new import__754.BaseLayerPickerViewModel({ globe: globe2, terrainProviderViewModels }); viewModel.selectedTerrain = testEllipsoidProviderViewModel; await testProviderViewModelAsync.creationCommand(); expect(globe2.terrainProvider).toBeInstanceOf(import_engine35.EllipsoidTerrainProvider); expect(globe2.depthTestAgainstTerrain).toBeFalse(); }); it("default does not override default value of depthTestAgainstTerrain", async function() { const terrainProviderViewModels = [testEllipsoidProviderViewModel]; const globe2 = new MockGlobe(); const viewModel = new import__754.BaseLayerPickerViewModel({ globe: globe2, terrainProviderViewModels }); globe2.depthTestAgainstTerrain = true; await testEllipsoidProviderViewModel.creationCommand(); expect(globe2.terrainProvider).toBeInstanceOf(import_engine35.EllipsoidTerrainProvider); expect(globe2.depthTestAgainstTerrain).toBeTrue(); }); it("selectedTerrain cancels update if terrainProvider is set externally", async function() { const terrainProviderViewModels = [testProviderViewModel3]; const globe2 = new MockGlobe(); const viewModel = new import__754.BaseLayerPickerViewModel({ globe: globe2, terrainProviderViewModels }); viewModel.selectedTerrain = testProviderViewModelAsync; globe2.terrainProviderChanged.raiseEvent(); await testProviderViewModelAsync.creationCommand(); expect(globe2.terrainProvider).not.toBe(testProvider); }); it("settings selectedImagery only removes layers added by view model", async function() { const imageryViewModels = [testProviderViewModel]; const globe2 = new MockGlobe(); const imageryLayers = globe2.imageryLayers; const viewModel = new import__754.BaseLayerPickerViewModel({ globe: globe2, imageryProviderViewModels: imageryViewModels }); expect(imageryLayers.length).toEqual(1); viewModel.selectedImagery = testProviderViewModel2; expect(imageryLayers.length).toEqual(2); await pollToPromise_default(() => imageryLayers.get(0).ready); expect(imageryLayers.get(0).imageryProvider).toBe(testProvider); await pollToPromise_default(() => imageryLayers.get(1).ready); expect(imageryLayers.get(1).imageryProvider).toBe(testProvider2); imageryLayers.addImageryProvider(testProvider3, 1); imageryLayers.remove(imageryLayers.get(0)); viewModel.selectedImagery = void 0; expect(imageryLayers.length).toEqual(1); await pollToPromise_default(() => imageryLayers.get(0).ready); expect(imageryLayers.get(0).imageryProvider).toBe(testProvider3); }); it("dropDownVisible and toggleDropDown work", function() { const viewModel = new import__754.BaseLayerPickerViewModel({ globe: new MockGlobe() }); expect(viewModel.dropDownVisible).toEqual(false); viewModel.toggleDropDown(); expect(viewModel.dropDownVisible).toEqual(true); viewModel.dropDownVisible = false; expect(viewModel.dropDownVisible).toEqual(false); }); it("constructor throws with no globe", function() { expect(function() { return new import__754.BaseLayerPickerViewModel({}); }).toThrowDeveloperError(); }); }); // packages/widgets/Specs/BaseLayerPicker/ProviderViewModelSpec.js var import__755 = __toESM(require_Cesium(), 1); describe("Widgets/BaseLayerPicker/ProviderViewModel", function() { let spyCreationFunction; beforeEach(function() { spyCreationFunction = jasmine.createSpy("creationFunction"); }); describe("with observables", function() { it("constructor sets expected parameters", function() { const options = { name: import__755.knockout.observable("name"), tooltip: import__755.knockout.observable("tooltip"), iconUrl: import__755.knockout.observable("iconUrl"), category: "mycategory", creationFunction: (0, import__755.createCommand)(spyCreationFunction) }; const viewModel = new import__755.ProviderViewModel(options); expect(viewModel.name).toBe(options.name()); expect(viewModel.tooltip).toBe(options.tooltip()); expect(viewModel.iconUrl).toBe(options.iconUrl()); expect(viewModel.category).toBe(options.category); expect(viewModel.creationCommand).toBeDefined(); viewModel.creationCommand(); expect(spyCreationFunction).toHaveBeenCalled(); }); it("constructor throws with no name", function() { const options = { tooltip: import__755.knockout.observable("tooltip"), iconUrl: import__755.knockout.observable("iconUrl"), creationFunction: (0, import__755.createCommand)(spyCreationFunction) }; expect(function() { return new import__755.ProviderViewModel(options); }).toThrowDeveloperError(); }); it("constructor throws with no tooltip", function() { const options = { name: import__755.knockout.observable("name"), iconUrl: import__755.knockout.observable("iconUrl"), creationFunction: (0, import__755.createCommand)(spyCreationFunction) }; expect(function() { return new import__755.ProviderViewModel(options); }).toThrowDeveloperError(); }); it("constructor throws with no iconUrl", function() { const options = { name: import__755.knockout.observable("name"), tooltip: import__755.knockout.observable("tooltip"), creationFunction: (0, import__755.createCommand)(spyCreationFunction) }; expect(function() { return new import__755.ProviderViewModel(options); }).toThrowDeveloperError(); }); it("constructor throws with no creationFunction", function() { const options = { name: import__755.knockout.observable("name"), tooltip: import__755.knockout.observable("tooltip"), iconUrl: import__755.knockout.observable("iconUrl") }; expect(function() { return new import__755.ProviderViewModel(options); }).toThrowDeveloperError(); }); }); describe("with values", function() { it("constructor sets expected parameters", function() { const options = { name: "name", tooltip: "tooltip", iconUrl: "iconUrl", creationFunction: spyCreationFunction }; const viewModel = new import__755.ProviderViewModel(options); expect(viewModel.name).toEqual(options.name); expect(viewModel.tooltip).toEqual(options.tooltip); expect(viewModel.iconUrl).toEqual(options.iconUrl); expect(viewModel.creationCommand).toBeDefined(); viewModel.creationCommand(); expect(spyCreationFunction).toHaveBeenCalled(); }); it("constructor throws with no name", function() { const options = { tooltip: "tooltip", iconUrl: "iconUrl", creationFunction: spyCreationFunction }; expect(function() { return new import__755.ProviderViewModel(options); }).toThrowDeveloperError(); }); it("constructor throws with no tooltip", function() { const options = { name: "name", iconUrl: "iconUrl", creationFunction: spyCreationFunction }; expect(function() { return new import__755.ProviderViewModel(options); }).toThrowDeveloperError(); }); it("constructor throws with no iconUrl", function() { const options = { name: "name", tooltip: "tooltip", creationFunction: spyCreationFunction }; expect(function() { return new import__755.ProviderViewModel(options); }).toThrowDeveloperError(); }); it("constructor throws with no creationFunction", function() { const options = { name: "name", tooltip: "tooltip", iconUrl: "iconUrl" }; expect(function() { return new import__755.ProviderViewModel(options); }).toThrowDeveloperError(); }); }); }); // packages/widgets/Specs/Cesium3DTilesInspector/Cesium3DTilesInspectorSpec.js var import_engine36 = __toESM(require_Cesium(), 1); var import__756 = __toESM(require_Cesium(), 1); describe( "Widgets/Cesium3DTilesInspector/Cesium3DTilesInspector", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); const ellipsoid = import_engine36.Ellipsoid.UNIT_SPHERE; scene2.globe = new import_engine36.Globe(ellipsoid); }); afterAll(function() { scene2.destroyForSpecs(); }); it("can create and destroy", function() { const container = document.createElement("div"); container.id = "testContainer"; document.body.appendChild(container); const widget = new import__756.Cesium3DTilesInspector("testContainer", scene2); expect(widget.container).toBe(container); expect(widget.viewModel._scene).toBe(scene2); expect(widget.isDestroyed()).toEqual(false); widget.destroy(); expect(widget.isDestroyed()).toEqual(true); document.body.removeChild(container); }); it("constructor throws with no element", function() { expect(function() { return new import__756.Cesium3DTilesInspector(); }).toThrowDeveloperError(); }); it("constructor throws with string element that does not exist", function() { expect(function() { return new import__756.Cesium3DTilesInspector("does not exist", scene2); }).toThrowDeveloperError(); }); it("constructor throws with no scene", function() { expect(function() { return new import__756.Cesium3DTilesInspector(document.body); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/widgets/Specs/Cesium3DTilesInspector/Cesium3DTilesInspectorViewModelSpec.js var import_engine37 = __toESM(require_Cesium(), 1); var import__757 = __toESM(require_Cesium(), 1); describe( "Widgets/Cesium3DTilesInspector/Cesium3DTilesInspectorViewModel", function() { const tilesetUrl = "./Data/Cesium3DTiles/Tilesets/Tileset/tileset.json"; let scene2; let viewModel; const performanceContainer = document.createElement("div"); beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { scene2.globe = new import_engine37.Globe(); scene2.initializeFrame(); }); afterEach(function() { scene2.primitives.removeAll(); }); it("can create and destroy", function() { const viewModel2 = new import__757.Cesium3DTilesInspectorViewModel( scene2, performanceContainer ); expect(viewModel2._scene).toBe(scene2); expect(viewModel2.isDestroyed()).toEqual(false); viewModel2.destroy(); expect(viewModel2.isDestroyed()).toEqual(true); }); it("throws if scene is undefined", function() { expect(function() { return new import__757.Cesium3DTilesInspectorViewModel(); }).toThrowDeveloperError(); }); it("throws if performanceContainer is undefined", function() { expect(function() { return new import__757.Cesium3DTilesInspectorViewModel(scene2); }).toThrowDeveloperError(); }); describe("tileset options", function() { it("show properties", async function() { viewModel = new import__757.Cesium3DTilesInspectorViewModel( scene2, performanceContainer ); const tileset = await import_engine37.Cesium3DTileset.fromUrl(tilesetUrl); viewModel.tileset = tileset; expect(viewModel.properties.indexOf("id") !== -1).toBe(true); expect(viewModel.properties.indexOf("Longitude") !== -1).toBe(true); expect(viewModel.properties.indexOf("Latitude") !== -1).toBe(true); expect(viewModel.properties.indexOf("Height") !== -1).toBe(true); viewModel.destroy(); }); }); describe("display options", function() { beforeAll(async function() { viewModel = new import__757.Cesium3DTilesInspectorViewModel( scene2, performanceContainer ); const tileset = await import_engine37.Cesium3DTileset.fromUrl(tilesetUrl); viewModel.tileset = tileset; }); afterAll(function() { viewModel.destroy(); }); it("colorize", function() { viewModel.colorize = true; expect(viewModel.tileset.debugColorizeTiles).toBe(true); viewModel.colorize = false; expect(viewModel.tileset.debugColorizeTiles).toBe(false); }); it("wireframe", function() { viewModel.wireframe = true; expect(viewModel.tileset.debugWireframe).toBe(true); viewModel.wireframe = false; expect(viewModel.tileset.debugWireframe).toBe(false); }); it("showBoundingVolumes", function() { viewModel.showBoundingVolumes = true; expect(viewModel.tileset.debugShowBoundingVolume).toBe(true); viewModel.showBoundingVolumes = false; expect(viewModel.tileset.debugShowBoundingVolume).toBe(false); }); it("showContentVolumes", function() { viewModel.showContentBoundingVolumes = true; expect(viewModel.tileset.debugShowContentBoundingVolume).toBe(true); viewModel.showContentBoundingVolumes = false; expect(viewModel.tileset.debugShowContentBoundingVolume).toBe(false); }); it("showRequestVolumes", function() { viewModel.showRequestVolumes = true; expect(viewModel.tileset.debugShowViewerRequestVolume).toBe(true); viewModel.showRequestVolumes = false; expect(viewModel.tileset.debugShowViewerRequestVolume).toBe(false); }); it("showOnlyPickedTileDebugLabel", function() { viewModel.showOnlyPickedTileDebugLabel = true; expect(viewModel.tileset.debugPickedTileLabelOnly).toBe(true); viewModel.showOnlyPickedTileDebugLabel = false; expect(viewModel.tileset.debugPickedTileLabelOnly).toBe(false); }); it("showGeometricError", function() { viewModel.showGeometricError = true; expect(viewModel.tileset.debugShowGeometricError).toBe(true); viewModel.showGeometricError = false; expect(viewModel.tileset.debugShowGeometricError).toBe(false); }); it("showRenderingStatistics", function() { viewModel.showRenderingStatistics = true; expect(viewModel.tileset.debugShowRenderingStatistics).toBe(true); viewModel.showRenderingStatistics = false; expect(viewModel.tileset.debugShowRenderingStatistics).toBe(false); }); it("showMemoryUsage", function() { viewModel.showMemoryUsage = true; expect(viewModel.tileset.debugShowMemoryUsage).toBe(true); viewModel.showMemoryUsage = false; expect(viewModel.tileset.debugShowMemoryUsage).toBe(false); }); it("showUrl", function() { viewModel.showUrl = true; expect(viewModel.tileset.debugShowUrl).toBe(true); viewModel.showUrl = false; expect(viewModel.tileset.debugShowUrl).toBe(false); }); it("pointCloudShading", function() { viewModel.pointCloudShading = true; expect(viewModel.tileset.pointCloudShading.attenuation).toBe(true); viewModel.pointCloudShading = false; expect(viewModel.tileset.pointCloudShading.attenuation).toBe(false); }); it("geometricErrorScale", function() { viewModel.geometricErrorScale = 1; expect(viewModel.tileset.pointCloudShading.geometricErrorScale).toBe( 1 ); viewModel.geometricErrorScale = 0; expect(viewModel.tileset.pointCloudShading.geometricErrorScale).toBe( 0 ); }); it("maximumAttenuation", function() { viewModel.maximumAttenuation = 1; expect(viewModel.tileset.pointCloudShading.maximumAttenuation).toBe( 1 ); viewModel.maximumAttenuation = 0; expect( viewModel.tileset.pointCloudShading.maximumAttenuation ).not.toBeDefined(); }); it("baseResolution", function() { viewModel.baseResolution = 1; expect(viewModel.tileset.pointCloudShading.baseResolution).toBe(1); viewModel.baseResolution = 0; expect( viewModel.tileset.pointCloudShading.baseResolution ).not.toBeDefined(); }); it("eyeDomeLighting", function() { viewModel.eyeDomeLighting = true; expect(viewModel.tileset.pointCloudShading.eyeDomeLighting).toBe(true); viewModel.eyeDomeLighting = false; expect(viewModel.tileset.pointCloudShading.eyeDomeLighting).toBe(false); }); it("eyeDomeLightingStrength", function() { viewModel.eyeDomeLightingStrength = 1; expect( viewModel.tileset.pointCloudShading.eyeDomeLightingStrength ).toBe(1); viewModel.eyeDomeLightingStrength = 0; expect( viewModel.tileset.pointCloudShading.eyeDomeLightingStrength ).toBe(0); }); it("eyeDomeLightingRadius", function() { viewModel.eyeDomeLightingRadius = 1; expect(viewModel.tileset.pointCloudShading.eyeDomeLightingRadius).toBe( 1 ); viewModel.eyeDomeLightingRadius = 0; expect(viewModel.tileset.pointCloudShading.eyeDomeLightingRadius).toBe( 0 ); }); }); describe("update options", function() { beforeAll(async function() { viewModel = new import__757.Cesium3DTilesInspectorViewModel( scene2, performanceContainer ); viewModel.tileset = await import_engine37.Cesium3DTileset.fromUrl(tilesetUrl); }); afterAll(function() { viewModel.destroy(); }); it("freeze frame", function() { viewModel.freezeFrame = false; expect(viewModel.tileset.debugFreezeFrame).toBe(false); viewModel.freezeFrame = true; expect(viewModel.tileset.debugFreezeFrame).toBe(true); }); it("maximum screen space error", function() { viewModel.dynamicScreenSpaceError = false; viewModel.maximumScreenSpaceError = 10; expect(viewModel.tileset.dynamicScreenSpaceError).toBe(false); expect(viewModel.tileset.maximumScreenSpaceError).toBe(10); }); it("dynamic screen space error", function() { viewModel.dynamicScreenSpaceError = true; viewModel.dynamicScreenSpaceErrorFactor = 2; viewModel.dynamicScreenSpaceErrorDensity = 0.1; expect(viewModel.tileset.dynamicScreenSpaceError).toBe(true); expect(viewModel.tileset.dynamicScreenSpaceErrorFactor).toBe(2); expect(viewModel.tileset.dynamicScreenSpaceErrorDensity).toBe(0.1); }); it("dynamicScreenSpaceErrorDensity slider uses an exponential scale", function() { const rawSliderValue = 0.2; const scaledValue = Math.pow(rawSliderValue, 6); viewModel.dynamicScreenSpaceErrorDensitySliderValue = rawSliderValue; expect( viewModel.dynamicScreenSpaceErrorDensitySliderValue ).toEqualEpsilon(rawSliderValue, import_engine37.Math.EPSILON8); expect(viewModel.tileset.dynamicScreenSpaceErrorDensity).toEqualEpsilon( scaledValue, import_engine37.Math.EPSILON8 ); }); }); describe("style options", function() { let style; beforeAll(async function() { style = new import_engine37.Cesium3DTileStyle({ color: { conditions: [ ["${Height} >= 83", "color('purple', 0.5)"], ["${Height} >= 80", "color('red')"], ["${Height} >= 70", "color('orange')"], ["${Height} >= 12", "color('yellow')"], ["${Height} >= 7", "color('lime')"], ["${Height} >= 1", "color('cyan')"], ["true", "color('blue')"] ] }, meta: { description: "'Building id ${id} has height ${Height}.'" } }); viewModel = new import__757.Cesium3DTilesInspectorViewModel( scene2, performanceContainer ); viewModel.tileset = await import_engine37.Cesium3DTileset.fromUrl(tilesetUrl); }); afterAll(function() { viewModel.destroy(); }); it("loads tileset style", function() { viewModel.tileset.style = style; viewModel._update(); expect(JSON.stringify(style.style)).toBe( JSON.stringify(JSON.parse(viewModel.styleString)) ); }); it("does not throw on invalid syntax", function() { expect(function() { viewModel.styleString = "invalid"; }).not.toThrowError(); }); it("recompiles style", function() { viewModel._style = void 0; viewModel.tileset.style = style; viewModel._update(); const s = JSON.parse(viewModel.styleString); s.color = "color('red')"; viewModel.styleString = JSON.stringify(s); viewModel.compileStyle(); viewModel._update(); expect(viewModel.tileset.style.style.color).toBe("color('red')"); expect(viewModel.tileset.style.style.meta.description).toBe( "'Building id ${id} has height ${Height}.'" ); }); it("does not throw on invalid value", function() { expect(function() { viewModel.styleString = '{ "color": "color(1)" }'; }).not.toThrowError(); }); }); }, "WebGL" ); // packages/widgets/Specs/CesiumInspector/CesiumInspectorSpec.js var import_engine38 = __toESM(require_Cesium(), 1); var import__758 = __toESM(require_Cesium(), 1); describe( "Widgets/CesiumInspector/CesiumInspector", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); const ellipsoid = import_engine38.Ellipsoid.UNIT_SPHERE; const globe2 = new import_engine38.Globe(ellipsoid); scene2.globe = globe2; }); afterAll(function() { scene2.destroyForSpecs(); }); it("can create and destroy", function() { const container = document.createElement("div"); container.id = "testContainer"; document.body.appendChild(container); const widget = new import__758.CesiumInspector("testContainer", scene2); expect(widget.container).toBe(container); expect(widget.viewModel.scene).toBe(scene2); expect(widget.isDestroyed()).toEqual(false); widget.destroy(); expect(widget.isDestroyed()).toEqual(true); document.body.removeChild(container); }); it("constructor throws with no element", function() { expect(function() { return new import__758.CesiumInspector(); }).toThrowDeveloperError(); }); it("constructor throws with string element that does not exist", function() { expect(function() { return new import__758.CesiumInspector("does not exist", scene2); }).toThrowDeveloperError(); }); it("constructor throws with no scene", function() { expect(function() { return new import__758.CesiumInspector(document.body); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/widgets/Specs/CesiumInspector/CesiumInspectorViewModelSpec.js var import_engine39 = __toESM(require_Cesium(), 1); var import__759 = __toESM(require_Cesium(), 1); describe( "Widgets/CesiumInspector/CesiumInspectorViewModel", function() { let scene2; let performanceContainer; function createRectangle(rectangle, rotation) { return new import_engine39.Primitive({ geometryInstances: new import_engine39.GeometryInstance({ geometry: new import_engine39.RectangleGeometry({ rectangle, vertexFormat: import_engine39.EllipsoidSurfaceAppearance.VERTEX_FORMAT, rotation }) }), appearance: new import_engine39.EllipsoidSurfaceAppearance({ aboveGround: false }) }); } beforeAll(function() { scene2 = createScene_default(); performanceContainer = document.createElement("div"); }); afterAll(function() { scene2.destroyForSpecs(); }); beforeEach(function() { scene2.globe = new import_engine39.Globe(); scene2.initializeFrame(); }); afterEach(function() { scene2.primitives.removeAll(); }); it("can create and destroy", function() { const viewModel = new import__759.CesiumInspectorViewModel( scene2, performanceContainer ); expect(viewModel.scene).toBe(scene2); expect(viewModel.performanceContainer).toBe(performanceContainer); expect(viewModel.isDestroyed()).toEqual(false); viewModel.destroy(); expect(viewModel.isDestroyed()).toEqual(true); }); it("throws if scene is undefined", function() { expect(function() { return new import__759.CesiumInspectorViewModel(); }).toThrowDeveloperError(); }); it("throws if performanceContainer is undefined", function() { expect(function() { return new import__759.CesiumInspectorViewModel(scene2); }).toThrowDeveloperError(); }); it("show frustums", function() { const viewModel = new import__759.CesiumInspectorViewModel( scene2, performanceContainer ); viewModel.frustums = true; expect(viewModel.scene.debugShowFrustums).toBe(true); scene2.render(); viewModel.frustums = false; expect(viewModel.scene.debugShowFrustums).toBe(false); }); it("show performance", function() { const viewModel = new import__759.CesiumInspectorViewModel( scene2, performanceContainer ); viewModel.performance = true; scene2.render(); expect(performanceContainer.innerHTML).not.toEqual(""); viewModel.performance = false; scene2.render(); expect(performanceContainer.innerHTML).toEqual(""); }); it("primitive bounding sphere", function() { const p = scene2.primitives.add( createRectangle( new import_engine39.Rectangle( import_engine39.Math.toRadians(-110), import_engine39.Math.toRadians(0), import_engine39.Math.toRadians(-90), import_engine39.Math.toRadians(20) ), import_engine39.Math.toRadians(45) ) ); const viewModel = new import__759.CesiumInspectorViewModel( scene2, performanceContainer ); scene2.render(); viewModel.primitive = p; viewModel.primitiveBoundingSphere = true; expect(p.debugShowBoundingVolume).toEqual(true); viewModel.primitiveBoundingSphere = false; scene2.render(); expect(p.debugShowBoundingVolume).toEqual(false); }); it("primitive filter", function() { const p = scene2.primitives.add( createRectangle( new import_engine39.Rectangle( import_engine39.Math.toRadians(-110), import_engine39.Math.toRadians(0), import_engine39.Math.toRadians(-90), import_engine39.Math.toRadians(20) ), import_engine39.Math.toRadians(45) ) ); const q = scene2.primitives.add( createRectangle( new import_engine39.Rectangle( import_engine39.Math.toRadians(-10), import_engine39.Math.toRadians(0), import_engine39.Math.toRadians(-9), import_engine39.Math.toRadians(20) ) ) ); const viewModel = new import__759.CesiumInspectorViewModel( scene2, performanceContainer ); scene2.render(); viewModel.primitive = p; viewModel.filterPrimitive = true; expect((0, import_engine39.defined)(scene2.debugCommandFilter)).toEqual(true); expect(scene2.debugCommandFilter({ owner: p })).toEqual(true); expect(scene2.debugCommandFilter({ owner: q })).toEqual(false); viewModel.filterPrimitive = false; expect((0, import_engine39.defined)(scene2.debugCommandFilter)).toEqual(false); }); it("primitive reference frame", function() { const p = scene2.primitives.add( createRectangle( new import_engine39.Rectangle( import_engine39.Math.toRadians(-110), import_engine39.Math.toRadians(0), import_engine39.Math.toRadians(-90), import_engine39.Math.toRadians(20) ), import_engine39.Math.toRadians(45) ) ); const viewModel = new import__759.CesiumInspectorViewModel( scene2, performanceContainer ); scene2.render(); viewModel.primitive = p; viewModel.primitiveReferenceFrame = true; expect(scene2.primitives.length).toEqual(2); viewModel.primitiveReferenceFrame = false; scene2.render(); expect(scene2.primitives.length).toEqual(1); }); it("show wireframe", function() { const viewModel = new import__759.CesiumInspectorViewModel( scene2, performanceContainer ); viewModel.wireframe = true; expect(viewModel.scene.globe._surface.tileProvider._debug.wireframe).toBe( true ); viewModel.wireframe = false; expect(viewModel.scene.globe._surface.tileProvider._debug.wireframe).toBe( false ); }); it("suspend updates", function() { const viewModel = new import__759.CesiumInspectorViewModel( scene2, performanceContainer ); viewModel.suspendUpdates = true; expect(viewModel.scene.globe._surface._debug.suspendLodUpdate).toBe(true); viewModel.suspendUpdates = false; expect(viewModel.scene.globe._surface._debug.suspendLodUpdate).toBe( false ); }); it("show tile coords", function() { const viewModel = new import__759.CesiumInspectorViewModel( scene2, performanceContainer ); expect(viewModel.scene.imageryLayers.length).toBe(0); viewModel.tileCoordinates = true; expect(viewModel.scene.imageryLayers.length).toBe(1); viewModel.tileCoordinates = false; expect(viewModel.scene.imageryLayers.length).toBe(0); }); it("show tile bounding sphere", function() { const viewModel = new import__759.CesiumInspectorViewModel( scene2, performanceContainer ); const tile = new import_engine39.QuadtreeTile({ tilingScheme: new import_engine39.WebMercatorTilingScheme(), x: 0, y: 0, level: 0 }); tile.data = new import_engine39.GlobeSurfaceTile(); viewModel.tile = tile; viewModel.tileBoundingSphere = true; expect( viewModel.scene.globe._surface.tileProvider._debug.boundingSphereTile ).toBe(tile); viewModel.tileBoundingSphere = false; expect( viewModel.scene.globe._surface.tileProvider._debug.boundingSphereTile ).toBe(void 0); }); it("filter tile", function() { const viewModel = new import__759.CesiumInspectorViewModel( scene2, performanceContainer ); const tile = new import_engine39.QuadtreeTile({ tilingScheme: new import_engine39.WebMercatorTilingScheme(), x: 0, y: 0, level: 0 }); tile.data = new import_engine39.GlobeSurfaceTile(); tile.renderable = true; viewModel.tile = tile; viewModel.filterTile = true; expect(viewModel.scene.globe._surface._tilesToRender[0]).toBe(tile); expect(viewModel.suspendUpdates).toBe(true); viewModel.filterTile = false; expect(viewModel.suspendUpdates).toBe(false); }); it("does not try to render a non-renderable tile", function() { const viewModel = new import__759.CesiumInspectorViewModel( scene2, performanceContainer ); const tile = new import_engine39.QuadtreeTile({ tilingScheme: new import_engine39.WebMercatorTilingScheme(), x: 0, y: 0, level: 0 }); tile.data = new import_engine39.GlobeSurfaceTile(); viewModel.tile = tile; viewModel.filterTile = true; expect(viewModel.scene.globe._surface._tilesToRender.length).toBe(0); expect(viewModel.suspendUpdates).toBe(true); viewModel.filterTile = false; expect(viewModel.suspendUpdates).toBe(false); }); }, "WebGL" ); // packages/widgets/Specs/FullscreenButton/FullscreenButtonSpec.js var import__760 = __toESM(require_Cesium(), 1); describe("Widgets/FullscreenButton/FullscreenButton", function() { it("constructor sets default values", function() { const fullscreenButton = new import__760.FullscreenButton(document.body); expect(fullscreenButton.container).toBe(document.body); expect(fullscreenButton.viewModel.fullscreenElement).toBe(document.body); expect(fullscreenButton.isDestroyed()).toEqual(false); fullscreenButton.destroy(); expect(fullscreenButton.isDestroyed()).toEqual(true); }); it("constructor sets expected values", function() { const testElement = document.createElement("span"); const fullscreenButton = new import__760.FullscreenButton(document.body, testElement); expect(fullscreenButton.container).toBe(document.body); expect(fullscreenButton.viewModel.fullscreenElement).toBe(testElement); fullscreenButton.destroy(); }); it("constructor works with string id container", function() { const testElement = document.createElement("span"); testElement.id = "testElement"; document.body.appendChild(testElement); const fullscreenButton = new import__760.FullscreenButton("testElement"); expect(fullscreenButton.container).toBe(testElement); document.body.removeChild(testElement); fullscreenButton.destroy(); }); it("throws if container is undefined", function() { expect(function() { return new import__760.FullscreenButton(void 0); }).toThrowDeveloperError(); }); it("throws if container string is undefined", function() { expect(function() { return new import__760.FullscreenButton("testElement"); }).toThrowDeveloperError(); }); }); // packages/widgets/Specs/FullscreenButton/FullscreenButtonViewModelSpec.js var import_engine40 = __toESM(require_Cesium(), 1); var import__761 = __toESM(require_Cesium(), 1); describe("Widgets/FullscreenButton/FullscreenButtonViewModel", function() { it("constructor sets default values", function() { const viewModel = new import__761.FullscreenButtonViewModel(); expect(viewModel.fullscreenElement).toBe(document.body); expect(viewModel.isDestroyed()).toEqual(false); viewModel.destroy(); expect(viewModel.isDestroyed()).toEqual(true); }); it("constructor sets expected values", function() { const testElement = document.createElement("span"); const viewModel = new import__761.FullscreenButtonViewModel(testElement); expect(viewModel.fullscreenElement).toBe(testElement); viewModel.destroy(); }); it("constructor can take an element id", function() { const testElement = document.createElement("span"); testElement.id = "testElement"; document.body.appendChild(testElement); const viewModel = new import__761.FullscreenButtonViewModel("testElement"); expect(viewModel.fullscreenElement).toBe(testElement); viewModel.destroy(); document.body.removeChild(testElement); }); it("isFullscreenEnabled work as expected", function() { const viewModel = new import__761.FullscreenButtonViewModel(); expect(viewModel.isFullscreenEnabled).toEqual(import_engine40.Fullscreen.enabled); viewModel.isFullscreenEnabled = false; expect(viewModel.isFullscreenEnabled).toEqual(false); viewModel.destroy(); }); it("can get and set fullscreenElement", function() { const testElement = document.createElement("span"); const viewModel = new import__761.FullscreenButtonViewModel(); expect(viewModel.fullscreenElement).not.toBe(testElement); viewModel.fullscreenElement = testElement; expect(viewModel.fullscreenElement).toBe(testElement); }); it("throws is setting fullscreenElement is not an Element", function() { const viewModel = new import__761.FullscreenButtonViewModel(); expect(function() { viewModel.fullscreenElement = {}; }).toThrowDeveloperError(); }); }); // packages/widgets/Specs/HomeButton/HomeButtonSpec.js var import__762 = __toESM(require_Cesium(), 1); describe( "Widgets/HomeButton/HomeButton", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); it("constructor sets default values", function() { const homeButton = new import__762.HomeButton(document.body, scene2); expect(homeButton.container).toBe(document.body); expect(homeButton.viewModel.scene).toBe(scene2); expect(homeButton.isDestroyed()).toEqual(false); homeButton.destroy(); expect(homeButton.isDestroyed()).toEqual(true); }); it("constructor sets expected values", function() { const homeButton = new import__762.HomeButton(document.body, scene2); expect(homeButton.container).toBe(document.body); expect(homeButton.viewModel.scene).toBe(scene2); homeButton.destroy(); }); it("constructor works with string id container", function() { const testElement = document.createElement("span"); testElement.id = "testElement"; document.body.appendChild(testElement); const homeButton = new import__762.HomeButton("testElement", scene2); expect(homeButton.container).toBe(testElement); document.body.removeChild(testElement); homeButton.destroy(); }); it("throws if container is undefined", function() { expect(function() { return new import__762.HomeButton(void 0, scene2); }).toThrowDeveloperError(); }); it("throws if container string is undefined", function() { expect(function() { return new import__762.HomeButton("testElement", scene2); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/widgets/Specs/HomeButton/HomeButtonViewModelSpec.js var import_engine41 = __toESM(require_Cesium(), 1); var import__763 = __toESM(require_Cesium(), 1); describe( "Widgets/HomeButton/HomeButtonViewModel", function() { let scene2; const ellipsoid = import_engine41.Ellipsoid.WGS84; const globe2 = new import_engine41.Globe(ellipsoid); beforeAll(function() { scene2 = createScene_default(); scene2.globe = globe2; }); afterAll(function() { scene2.destroyForSpecs(); }); it("constructor sets default values", function() { const viewModel = new import__763.HomeButtonViewModel(scene2); expect(viewModel.scene).toBe(scene2); }); it("throws if scene is undefined", function() { expect(function() { return new import__763.HomeButtonViewModel(void 0); }).toThrowDeveloperError(); }); it("works in 3D", function() { scene2.render(); const viewModel = new import__763.HomeButtonViewModel(scene2); viewModel.command(); }); it("works in 2D", function() { scene2.render(); const viewModel = new import__763.HomeButtonViewModel(scene2); scene2.morphTo2D(); viewModel.command(); }); it("works in Columbus View", function() { scene2.render(); const viewModel = new import__763.HomeButtonViewModel(scene2); scene2.morphToColumbusView(); viewModel.command(); }); it("works while morphing", function() { scene2.render(); const viewModel = new import__763.HomeButtonViewModel(scene2); scene2.morphToColumbusView(2e3); viewModel.command(); }); }, "WebGL" ); // packages/widgets/Specs/Geocoder/GeocoderSpec.js var import__764 = __toESM(require_Cesium(), 1); describe( "Widgets/Geocoder/Geocoder", function() { let scene2; beforeEach(function() { scene2 = createScene_default(); }); afterEach(function() { scene2.destroyForSpecs(); }); it("constructor sets expected properties", function() { const flightDuration = 1234; const destinationFound = jasmine.createSpy(); const geocoder = new import__764.Geocoder({ container: document.body, scene: scene2, flightDuration, destinationFound }); const viewModel = geocoder.viewModel; expect(viewModel.scene).toBe(scene2); expect(viewModel.flightDuration).toBe(flightDuration); expect(viewModel.destinationFound).toBe(destinationFound); geocoder.destroy(); }); it("can create and destroy", function() { const container = document.createElement("div"); container.id = "testContainer"; document.body.appendChild(container); const widget = new import__764.Geocoder({ container: "testContainer", scene: scene2 }); expect(widget.container).toBe(container); expect(widget.isDestroyed()).toEqual(false); expect(container.children.length).not.toEqual(0); widget.destroy(); expect(container.children.length).toEqual(0); expect(widget.isDestroyed()).toEqual(true); document.body.removeChild(container); }); it("constructor throws with no scene", function() { expect(function() { return new import__764.Geocoder({ container: document.body }); }).toThrowDeveloperError(); }); it("constructor throws with no element", function() { expect(function() { return new import__764.Geocoder({ scene: scene2 }); }).toThrowDeveloperError(); }); it("constructor throws with string element that does not exist", function() { expect(function() { return new import__764.Geocoder({ container: "does not exist", scene: scene2 }); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/widgets/Specs/Geocoder/GeocoderViewModelSpec.js var import_engine42 = __toESM(require_Cesium(), 1); var import__765 = __toESM(require_Cesium(), 1); describe( "Widgets/Geocoder/GeocoderViewModel", function() { let scene2; const mockDestination = new import_engine42.Cartesian3(1, 2, 3); const geocoderResults1 = [ { displayName: "a", destination: mockDestination }, { displayName: "b", destination: mockDestination }, { displayName: "c", destination: mockDestination } ]; const customGeocoderOptions = { autoComplete: true, geocode: function(input) { return Promise.resolve(geocoderResults1); } }; const geocoderResults2 = [ { displayName: "1", destination: mockDestination }, { displayName: "2", destination: mockDestination } ]; const customGeocoderOptions2 = { autoComplete: true, geocode: function(input) { return Promise.resolve(geocoderResults2); } }; const noResultsGeocoder = { autoComplete: true, geocode: function(input) { return Promise.resolve([]); } }; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); let geocoderViewModel; afterEach(function() { geocoderViewModel = geocoderViewModel && geocoderViewModel.destroy(); }); it("constructor sets expected properties", function() { const flightDuration = 1234; geocoderViewModel = new import__765.GeocoderViewModel({ scene: scene2, flightDuration }); expect(geocoderViewModel.scene).toBe(scene2); expect(geocoderViewModel.flightDuration).toBe(flightDuration); expect(geocoderViewModel.keepExpanded).toBe(false); }); it("can get and set flight duration", function() { geocoderViewModel = new import__765.GeocoderViewModel({ scene: scene2 }); geocoderViewModel.flightDuration = 324; expect(geocoderViewModel.flightDuration).toEqual(324); expect(function() { geocoderViewModel.flightDuration = -123; }).toThrowDeveloperError(); }); it("throws if searchText is not a string", function() { geocoderViewModel = new import__765.GeocoderViewModel({ scene: scene2, geocoderServices: [customGeocoderOptions] }); expect(function() { geocoderViewModel.searchText = void 0; }).toThrowDeveloperError(); }); it("moves camera when search command invoked", async function() { let destinationFoundCallback; const promise = new Promise((resolve) => { destinationFoundCallback = async function(viewModel, destination) { await import__765.GeocoderViewModel.flyToDestination(viewModel, destination); resolve(); }; }); geocoderViewModel = new import__765.GeocoderViewModel({ scene: scene2, geocoderServices: [customGeocoderOptions], destinationFound: destinationFoundCallback }); const cameraPosition = import_engine42.Cartesian3.clone(scene2.camera.position); geocoderViewModel.searchText = "220 Valley Creek Blvd, Exton, PA"; await geocoderViewModel.search(); await pollToPromise_default(function() { scene2.tweens.update(); return !import_engine42.Cartesian3.equals(cameraPosition, scene2.camera.position); }); await expectAsync(promise).toBeResolved(); }); it("constructor throws without scene", function() { expect(function() { return new import__765.GeocoderViewModel(); }).toThrowDeveloperError(); }); it("raises the complete event camera finished", async function() { let destinationFoundCallback; const promise = new Promise((resolve) => { destinationFoundCallback = function(viewModel, destination) { import__765.GeocoderViewModel.flyToDestination(viewModel, destination).then( resolve ); }; }); geocoderViewModel = new import__765.GeocoderViewModel({ scene: scene2, flightDuration: 0, geocoderServices: [customGeocoderOptions], destinationFound: destinationFoundCallback }); const spyListener = jasmine.createSpy("listener"); geocoderViewModel.complete.addEventListener(spyListener); geocoderViewModel.searchText = "-1.0, -2.0"; await geocoderViewModel.search(); await promise; expect(spyListener.calls.count()).toBe(1); }); it("can be created with a custom geocoder", function() { expect(function() { geocoderViewModel = new import__765.GeocoderViewModel({ scene: scene2, geocoderServices: [customGeocoderOptions] }); }).not.toThrowDeveloperError(); }); it("automatic suggestions can be retrieved", async function() { const destinationFoundCallback = jasmine.createSpy(); geocoderViewModel = new import__765.GeocoderViewModel({ scene: scene2, geocoderServices: [customGeocoderOptions], destinationFound: destinationFoundCallback // Don't move the camera after a successful geocode }); geocoderViewModel._searchText = "some_text"; await import__765.GeocoderViewModel._updateSearchSuggestions(geocoderViewModel); expect(geocoderViewModel._suggestions.length).toEqual(3); expect(destinationFoundCallback).not.toHaveBeenCalled(); }); it("update search suggestions results in empty list if the query is empty", async function() { const destinationFoundCallback = jasmine.createSpy(); geocoderViewModel = new import__765.GeocoderViewModel({ scene: scene2, geocoderServices: [customGeocoderOptions], destinationFound: destinationFoundCallback // Don't move the camera after a successful geocode }); geocoderViewModel._searchText = ""; await import__765.GeocoderViewModel._updateSearchSuggestions(geocoderViewModel); expect(geocoderViewModel._suggestions.length).toEqual(0); expect(destinationFoundCallback).not.toHaveBeenCalled(); }); it("can activate selected search suggestion", function() { const destinationFoundCallback = jasmine.createSpy(); const destination = new import_engine42.Rectangle(0, -0.1, 0.1, 0.1); geocoderViewModel = new import__765.GeocoderViewModel({ scene: scene2, geocoderServices: [customGeocoderOptions], destinationFound: destinationFoundCallback // Don't move the camera after a successful geocode }); const suggestion = { displayName: "a", destination }; geocoderViewModel._selectedSuggestion = suggestion; geocoderViewModel.activateSuggestion(suggestion); expect(geocoderViewModel._searchText).toEqual("a"); expect(destinationFoundCallback).toHaveBeenCalledWith( geocoderViewModel, destination ); }); it("if more than one geocoder service is provided, use first result from first geocode in array order", async function() { const destinationFoundCallback = jasmine.createSpy(); geocoderViewModel = new import__765.GeocoderViewModel({ scene: scene2, geocoderServices: [noResultsGeocoder, customGeocoderOptions2], destinationFound: destinationFoundCallback // Don't move the camera after a successful geocode }); geocoderViewModel._searchText = "sthsnth"; await geocoderViewModel.search(); expect(geocoderViewModel._searchText).toEqual( geocoderResults2[0].displayName ); expect(destinationFoundCallback).toHaveBeenCalledWith( geocoderViewModel, mockDestination ); }); it("can update autoComplete suggestions list using multiple geocoders", async function() { const destinationFoundCallback = jasmine.createSpy(); geocoderViewModel = new import__765.GeocoderViewModel({ scene: scene2, geocoderServices: [customGeocoderOptions, customGeocoderOptions2], destinationFound: destinationFoundCallback // Don't move the camera after a successful geocode }); geocoderViewModel._searchText = "sthsnth"; await import__765.GeocoderViewModel._updateSearchSuggestions(geocoderViewModel); expect(geocoderViewModel._suggestions.length).toEqual( geocoderResults1.length + geocoderResults2.length ); expect(destinationFoundCallback).not.toHaveBeenCalled(); }); it("uses custom destination found callback", async function() { spyOn(import__765.GeocoderViewModel, "flyToDestination"); const destinationFoundCallback = jasmine.createSpy(); geocoderViewModel = new import__765.GeocoderViewModel({ scene: scene2, geocoderServices: [noResultsGeocoder, customGeocoderOptions2], destinationFound: destinationFoundCallback }); geocoderViewModel._searchText = "sthsnth"; await geocoderViewModel.search(); expect(geocoderViewModel._searchText).toEqual( geocoderResults2[0].displayName ); expect(import__765.GeocoderViewModel.flyToDestination).not.toHaveBeenCalled(); expect(destinationFoundCallback).toHaveBeenCalledWith( geocoderViewModel, mockDestination ); }); it("automatic suggestions can be navigated by arrow up/down keys", function() { spyOn(import__765.GeocoderViewModel, "_adjustSuggestionsScroll"); const destinationFoundCallback = jasmine.createSpy(); geocoderViewModel = new import__765.GeocoderViewModel({ scene: scene2, geocoderServices: [customGeocoderOptions], destinationFound: destinationFoundCallback // Don't move the camera after a successful geocode }); geocoderViewModel._searchText = "some_text"; return import__765.GeocoderViewModel._updateSearchSuggestions(geocoderViewModel).then( function() { expect(geocoderViewModel._selectedSuggestion).toEqual(void 0); geocoderViewModel._handleArrowDown(geocoderViewModel); expect(geocoderViewModel._selectedSuggestion.displayName).toEqual( "a" ); geocoderViewModel._handleArrowDown(geocoderViewModel); geocoderViewModel._handleArrowDown(geocoderViewModel); expect(geocoderViewModel._selectedSuggestion.displayName).toEqual( "c" ); geocoderViewModel._handleArrowDown(geocoderViewModel); expect(geocoderViewModel._selectedSuggestion.displayName).toEqual( "a" ); geocoderViewModel._handleArrowDown(geocoderViewModel); geocoderViewModel._handleArrowUp(geocoderViewModel); expect(geocoderViewModel._selectedSuggestion.displayName).toEqual( "a" ); geocoderViewModel._handleArrowUp(geocoderViewModel); expect(geocoderViewModel._selectedSuggestion).toBeUndefined(); expect(destinationFoundCallback).not.toHaveBeenCalled(); } ); }); it("updates credits based on returned results", async function() { const geocoderResults = [ { displayName: "a", destination: mockDestination, attributions: [ { html: "attribution" } ] }, { displayName: "b", destination: mockDestination }, { displayName: "c", destination: mockDestination } ]; const geocoderOptions = { autoComplete: true, geocode: function(input) { return Promise.resolve(geocoderResults); }, credit: new import_engine42.Credit("custom credit", false) }; const destinationFoundCallback = jasmine.createSpy(); geocoderViewModel = new import__765.GeocoderViewModel({ scene: scene2, geocoderServices: [geocoderOptions], destinationFound: destinationFoundCallback // Don't move the camera after a successful geocode }); geocoderViewModel._searchText = "sthsnth"; await geocoderViewModel.search(); scene2.frameState.creditDisplay.beginFrame(); scene2.frameState.creditDisplay.endFrame(); const credits = scene2.frameState.creditDisplay._staticCredits; expect(credits.length).toBe(2); expect(credits[1]).toBeInstanceOf(import_engine42.Credit); expect(credits[1].html).toEqual("attribution"); expect(credits[1].showOnScreen).toBeFalse(); expect(destinationFoundCallback).toHaveBeenCalled(); }); it("uses default geocoder service credit if not present in results", async function() { const geocoderOptions = { autoComplete: true, geocode: function(input) { return Promise.resolve(geocoderResults1); }, credit: new import_engine42.Credit("custom credit", false) }; const destinationFoundCallback = jasmine.createSpy(); geocoderViewModel = new import__765.GeocoderViewModel({ scene: scene2, geocoderServices: [geocoderOptions], destinationFound: destinationFoundCallback // Don't move the camera after a successful geocode }); geocoderViewModel._searchText = "sthsnth"; await geocoderViewModel.search(); scene2.frameState.creditDisplay.beginFrame(); scene2.frameState.creditDisplay.endFrame(); const credits = scene2.frameState.creditDisplay._staticCredits; expect(credits.length).toBe(2); expect(credits[1]).toBeInstanceOf(import_engine42.Credit); expect(credits[1].html).toEqual("custom credit"); expect(credits[1].showOnScreen).toBeFalse(); expect(destinationFoundCallback).toHaveBeenCalled(); }); }, "WebGL" ); // packages/widgets/Specs/I3SBSLExplorer/I3SBSLExplorerSpec.js var import__766 = __toESM(require_Cesium(), 1); describe("Widgets/I3SBuildingSceneLayerExplorer/I3SBuildingSceneLayerExplorer", function() { const i3sProvider = { sublayers: [ { name: "Overview", modelName: "Overview", visibility: true, sublayers: [] }, { name: "Full Model", modelName: "FullModel", visibility: true, sublayers: [ { name: "Cat1", visibility: false, sublayers: [ { name: "SubCat1", visibility: true, sublayers: [] }, { name: "SubCat2", visibility: false, sublayers: [] } ] } ] } ], getAttributeNames: function() { return ["BldgLevel", "testAttr"]; }, getAttributeValues: function() { return [1, 0]; } }; it("can create bsl explorer ui", function() { const container = document.createElement("div"); container.id = "testContainer"; document.body.appendChild(container); const widget = new import__766.I3SBuildingSceneLayerExplorer("testContainer", { sublayers: [] }); expect(widget).toBeInstanceOf(import__766.I3SBuildingSceneLayerExplorer); expect(container.childElementCount).toEqual(1); expect(container.children[0].childElementCount).toEqual(3); expect(container.children[0].children[0].localName).toEqual("h3"); expect(container.children[0].children[0].textContent).toEqual( "Building explorer" ); expect(container.children[0].children[1].localName).toEqual("select"); expect(container.children[0].children[1].textContent).toEqual( "Building layers not found" ); expect(container.children[0].children[2].localName).toEqual("div"); expect(container.children[0].children[2].id).toEqual("bsl-wrapper"); document.body.removeChild(container); }); it("throws dev error with no container", function() { expect(function() { return new import__766.I3SBuildingSceneLayerExplorer(); }).toThrowDeveloperError(); }); it("throws dev error with no i3sdataprovider", function() { const container = document.createElement("div"); container.id = "testContainer"; document.body.appendChild(container); expect(function() { return new import__766.I3SBuildingSceneLayerExplorer("testContainer"); }).toThrowDeveloperError(); document.body.removeChild(container); }); it("can expand/collapse bsl tree", function() { const container = document.createElement("div"); container.id = "testContainer"; document.body.appendChild(container); i3sProvider.filterByAttributes = jasmine.createSpy(); const widget = new import__766.I3SBuildingSceneLayerExplorer( "testContainer", i3sProvider ); expect(widget).toBeInstanceOf(import__766.I3SBuildingSceneLayerExplorer); const expander = document.querySelector(".expandItem"); const nestedList = expander.parentElement.parentElement.querySelector( "#Cat1-expander" ); expect(expander.textContent).toEqual("+"); expect(nestedList.className).toEqual("nested"); DomEventSimulator_default.fireClick(expander); expect(expander.textContent).toEqual("-"); expect(nestedList.className).toEqual("nested active"); DomEventSimulator_default.fireClick(expander); expect(expander.textContent).toEqual("+"); expect(nestedList.className).toEqual("nested"); document.body.removeChild(container); }); }); // packages/widgets/Specs/I3SBSLExplorer/I3SBSLExplorerViewModelSpec.js var import__767 = __toESM(require_Cesium(), 1); var import__768 = __toESM(require_Cesium(), 1); describe("Widgets/I3SBuildingSceneLayerExplorer/I3SBuildingSceneLayerExplorerViewModel", function() { const i3sProvider = { sublayers: [ { name: "Full Model", modelName: "FullModel", visibility: true, sublayers: [ { name: "Cat1", visibility: false, sublayers: [ { name: "SubCat1", visibility: true, sublayers: [] }, { name: "SubCat2", visibility: false, sublayers: [] } ] } ] }, { name: "Overview", modelName: "Overview", visibility: true, sublayers: [] } ], getAttributeNames: function() { return ["BldgLevel", "testAttr"]; }, getAttributeValues: function() { return [1, 0]; } }; const i3sProviderWithoutOverview = { sublayers: [ { name: "Cat1", visibility: false, sublayers: [ { name: "SubCat1", visibility: true, sublayers: [] }, { name: "SubCat2", visibility: false, sublayers: [] } ] } ] }; it("can create bsl explorer ViewModel", function() { const viewModel = new import__767.I3SBuildingSceneLayerExplorerViewModel(i3sProvider); expect(viewModel.levels).toEqual(["All", 0, 1]); expect(viewModel.selectedLevel).toEqual("All"); expect(viewModel.sublayers.length).toEqual(2); expect(viewModel.sublayers[1].name).toEqual("Overview"); expect(viewModel.sublayers[1].modelName).toEqual("Overview"); expect(viewModel.sublayers[1].visibility).toEqual(false); expect(viewModel.sublayers[1].sublayers.length).toEqual(0); expect(viewModel.sublayers[0].name).toEqual("Full Model"); expect(viewModel.sublayers[0].modelName).toEqual("FullModel"); expect(viewModel.sublayers[0].visibility).toEqual(false); expect(viewModel.sublayers[0].sublayers.length).toEqual(1); expect(viewModel.sublayers[0].sublayers[0].name).toEqual("Cat1"); expect(viewModel.sublayers[0].sublayers[0].visibility).toEqual(true); expect(viewModel.sublayers[0].sublayers[0].sublayers.length).toEqual(2); expect(viewModel.sublayers[0].sublayers[0].sublayers[0].name).toEqual( "SubCat1" ); expect(viewModel.sublayers[0].sublayers[0].sublayers[0].visibility).toEqual( true ); expect( viewModel.sublayers[0].sublayers[0].sublayers[0].sublayers.length ).toEqual(0); expect(viewModel.sublayers[0].sublayers[0].sublayers[1].name).toEqual( "SubCat2" ); expect(viewModel.sublayers[0].sublayers[0].sublayers[1].visibility).toEqual( false ); expect( viewModel.sublayers[0].sublayers[0].sublayers[1].sublayers.length ).toEqual(0); expect(viewModel.topLayers.length).toEqual(3); expect(viewModel.defaultLayer.modelName).toEqual("Overview"); }); it("can create bsl explorer ViewModel if no Overview", function() { const viewModel = new import__767.I3SBuildingSceneLayerExplorerViewModel( i3sProviderWithoutOverview ); expect(viewModel.sublayers.length).toEqual(1); expect(viewModel.sublayers[0].name).toEqual("Full Model"); expect(viewModel.sublayers[0].modelName).toEqual("FullModel"); expect(viewModel.sublayers[0].visibility).toEqual(false); expect(viewModel.sublayers[0].sublayers.length).toEqual(1); expect(viewModel.sublayers[0].sublayers[0].name).toEqual("Cat1"); expect(viewModel.sublayers[0].sublayers[0].visibility).toEqual(true); expect(viewModel.sublayers[0].sublayers[0].sublayers.length).toEqual(2); expect(viewModel.sublayers[0].sublayers[0].sublayers[0].name).toEqual( "SubCat1" ); expect(viewModel.sublayers[0].sublayers[0].sublayers[0].visibility).toEqual( true ); expect( viewModel.sublayers[0].sublayers[0].sublayers[0].sublayers.length ).toEqual(0); expect(viewModel.sublayers[0].sublayers[0].sublayers[1].name).toEqual( "SubCat2" ); expect(viewModel.sublayers[0].sublayers[0].sublayers[1].visibility).toEqual( false ); expect( viewModel.sublayers[0].sublayers[0].sublayers[1].sublayers.length ).toEqual(0); expect(viewModel.topLayers.length).toEqual(2); expect(viewModel.defaultLayer.modelName).toEqual("FullModel"); }); it("can handle filtering by level", function() { i3sProvider.filterByAttributes = jasmine.createSpy(); const viewModel = new import__767.I3SBuildingSceneLayerExplorerViewModel(i3sProvider); import__768.knockout.track(viewModel); viewModel.currentLevel = 1; expect(i3sProvider.filterByAttributes).toHaveBeenCalledWith([ { name: "BldgLevel", values: [1] } ]); viewModel.currentLevel = "All"; expect(i3sProvider.filterByAttributes).toHaveBeenCalledWith(); }); it("can handle top layer selection", function() { const bslWrapper = document.createElement("div"); bslWrapper.id = "bsl-wrapper"; document.body.appendChild(bslWrapper); i3sProvider.filterByAttributes = jasmine.createSpy(); const viewModel = new import__767.I3SBuildingSceneLayerExplorerViewModel(i3sProvider); import__768.knockout.track(viewModel); viewModel.currentLayer = { name: "Full Model", modelName: "FullModel", index: 1 }; viewModel.currentLevel = 1; viewModel.currentLayer = { name: "Overview", modelName: "Overview", index: 0 }; expect(viewModel.sublayers[0].visibility).toEqual(true); expect(viewModel.sublayers[1].visibility).toEqual(false); expect(viewModel.selectedLevel).toEqual(1); expect(viewModel.currentLevel).toEqual("All"); expect(bslWrapper.style.display).toEqual("none"); viewModel.currentLayer = { name: "Full Model", modelName: "FullModel", index: 1 }; expect(viewModel.sublayers[0].visibility).toEqual(false); expect(viewModel.sublayers[1].visibility).toEqual(true); expect(viewModel.currentLevel).toEqual(1); expect(bslWrapper.style.display).toEqual("block"); document.body.removeChild(bslWrapper); }); it("can handle top layer selection if no Overview", function() { const bslWrapper = document.createElement("div"); bslWrapper.id = "bsl-wrapper"; document.body.appendChild(bslWrapper); i3sProviderWithoutOverview.filterByAttributes = jasmine.createSpy(); const viewModel = new import__767.I3SBuildingSceneLayerExplorerViewModel( i3sProviderWithoutOverview ); import__768.knockout.track(viewModel); viewModel.currentLayer = { name: "Full Model", modelName: "FullModel", index: 0 }; expect(viewModel.sublayers[0].visibility).toEqual(true); expect(bslWrapper.style.display).toEqual("block"); document.body.removeChild(bslWrapper); }); }); // packages/widgets/Specs/InfoBox/InfoBoxSpec.js var import_engine43 = __toESM(require_Cesium(), 1); var import__769 = __toESM(require_Cesium(), 1); describe("Widgets/InfoBox/InfoBox", function() { let testContainer; let infoBox; beforeEach(function() { testContainer = document.createElement("span"); testContainer.id = "testContainer"; document.body.appendChild(testContainer); }); afterEach(function() { if ((0, import_engine43.defined)(infoBox) && !infoBox.isDestroyed()) { infoBox = infoBox.destroy(); } document.body.removeChild(testContainer); }); it("constructor sets expected values", function() { infoBox = new import__769.InfoBox(testContainer); expect(infoBox.container).toBe(testContainer); expect(infoBox.viewModel).toBeDefined(); expect(infoBox.isDestroyed()).toEqual(false); infoBox.destroy(); expect(infoBox.isDestroyed()).toEqual(true); }); it("can set description body", function() { const infoBox2 = new import__769.InfoBox(testContainer); let node; const infoElement = testContainer.firstChild; infoBox2.viewModel.description = "Please do not crash"; return pollToPromise_default(function() { node = infoBox2.frame.contentDocument.body.firstChild; return node !== null; }).then(function() { expect(infoElement.style["background-color"]).toEqual(""); return pollToPromise_default(function() { return node.innerHTML === infoBox2.viewModel.description; }); }).then(function() { infoBox2.viewModel.description = '<div style="background-color: rgb(255, 255, 255);">Please do not crash</div>'; expect(infoElement.style["background-color"]).toEqual( "rgb(255, 255, 255)" ); return pollToPromise_default(function() { return node.innerHTML === infoBox2.viewModel.description; }); }).then(function() { expect(infoElement["background-color"]).toBeUndefined(); }); }); it("constructor works with string id container", function() { infoBox = new import__769.InfoBox("testContainer"); expect(infoBox.container.id).toBe(testContainer.id); }); it("throws if container is undefined", function() { expect(function() { return new import__769.InfoBox(void 0); }).toThrowDeveloperError(); }); it("throws if container string is undefined", function() { expect(function() { return new import__769.InfoBox("foo"); }).toThrowDeveloperError(); }); }); // packages/widgets/Specs/InfoBox/InfoBoxViewModelSpec.js var import__770 = __toESM(require_Cesium(), 1); describe("Widgets/InfoBox/InfoBoxViewModel", function() { it("constructor sets expected values", function() { const viewModel = new import__770.InfoBoxViewModel(); expect(viewModel.enableCamera).toBe(false); expect(viewModel.isCameraTracking).toBe(false); expect(viewModel.showInfo).toBe(false); expect(viewModel.cameraClicked).toBeDefined(); expect(viewModel.closeClicked).toBeDefined(); expect(viewModel.maxHeightOffset(0)).toBeDefined(); }); it("sets description", function() { const safeString = "<p>This is a test.</p>"; const viewModel = new import__770.InfoBoxViewModel(); viewModel.description = safeString; expect(viewModel.description).toBe(safeString); }); it("indicates missing description", function() { const viewModel = new import__770.InfoBoxViewModel(); expect(viewModel._bodyless).toBe(true); viewModel.description = "Testing"; expect(viewModel._bodyless).toBe(false); }); it("camera icon changes when tracking is not available, unless due to active tracking", function() { const viewModel = new import__770.InfoBoxViewModel(); viewModel.enableCamera = true; viewModel.isCameraTracking = false; const enabledTrackingPath = viewModel.cameraIconPath; viewModel.enableCamera = false; viewModel.isCameraTracking = false; expect(viewModel.cameraIconPath).not.toBe(enabledTrackingPath); const disableTrackingPath = viewModel.cameraIconPath; viewModel.enableCamera = true; viewModel.isCameraTracking = true; expect(viewModel.cameraIconPath).toBe(disableTrackingPath); viewModel.enableCamera = false; viewModel.isCameraTracking = true; expect(viewModel.cameraIconPath).toBe(disableTrackingPath); }); }); // packages/widgets/Specs/NavigationHelpButton/NavigationHelpButtonSpec.js var import_engine44 = __toESM(require_Cesium(), 1); var import__771 = __toESM(require_Cesium(), 1); describe("Widgets/NavigationHelpButton/NavigationHelpButton", function() { it("can create and destroy", function() { const container = document.createElement("span"); container.id = "testContainer"; document.body.appendChild(container); const widget = new import__771.NavigationHelpButton({ container: "testContainer" }); expect(widget.container.id).toBe(container.id); expect(widget.isDestroyed()).toEqual(false); widget.destroy(); expect(widget.isDestroyed()).toEqual(true); document.body.removeChild(container); }); it("does not show instructions by default", function() { const widget = new import__771.NavigationHelpButton({ container: document.body }); expect(widget.viewModel.showInstructions).toBe(false); widget.destroy(); }); it("shows instructions by default if told to do so in the constructor", function() { const widget = new import__771.NavigationHelpButton({ container: document.body, instructionsInitiallyVisible: true }); expect(widget.viewModel.showInstructions).toBe(true); widget.destroy(); }); function addCloseOnInputSpec(name, func) { it(`${name} event closes dropdown if target is not inside container`, function() { const container = document.createElement("span"); container.id = "testContainer"; document.body.appendChild(container); const widget = new import__771.NavigationHelpButton({ container: "testContainer" }); widget.viewModel.showInstructions = true; func(document.body); expect(widget.viewModel.showInstructions).toEqual(false); widget.viewModel.showInstructions = true; func(container.firstChild); expect(widget.viewModel.showInstructions).toEqual(true); widget.destroy(); document.body.removeChild(container); }); } if (import_engine44.FeatureDetection.supportsPointerEvents()) { addCloseOnInputSpec("pointerDown", DomEventSimulator_default.firePointerDown); } else { addCloseOnInputSpec("mousedown", DomEventSimulator_default.fireMouseDown); addCloseOnInputSpec("touchstart", DomEventSimulator_default.fireTouchStart); } it("throws if container is undefined", function() { expect(function() { return new import__771.NavigationHelpButton({ container: void 0 }); }).toThrowDeveloperError(); }); it("throws if options is undefined", function() { expect(function() { return new import__771.NavigationHelpButton(void 0); }).toThrowDeveloperError(); }); it("throws if options.container is undefined", function() { expect(function() { return new import__771.NavigationHelpButton({ container: void 0 }); }).toThrowDeveloperError(); }); it("constructor throws with string element that does not exist", function() { expect(function() { return new import__771.NavigationHelpButton({ container: "does not exist" }); }).toThrowDeveloperError(); }); }); // packages/widgets/Specs/NavigationHelpButton/NavigationHelpButtonViewModelSpec.js var import__772 = __toESM(require_Cesium(), 1); describe("Widgets/NavigationHelpButton/NavigationHelpButtonViewModel", function() { it("Can construct", function() { const viewModel = new import__772.NavigationHelpButtonViewModel(); expect(viewModel.showInstructions).toBe(false); }); it("invoking command toggles showing", function() { const viewModel = new import__772.NavigationHelpButtonViewModel(); expect(viewModel.showInstructions).toBe(false); viewModel.command(); expect(viewModel.showInstructions).toBe(true); viewModel.command(); expect(viewModel.showInstructions).toBe(false); }); }); // packages/widgets/Specs/PerformanceWatchdog/PerformanceWatchdogSpec.js var import__773 = __toESM(require_Cesium(), 1); describe( "Widgets/PerformanceWatchdog/PerformanceWatchdog", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); it("can create and destroy", function() { const container = document.createElement("span"); container.id = "testContainer"; document.body.appendChild(container); const widget = new import__773.PerformanceWatchdog({ container: "testContainer", scene: scene2 }); expect(widget.container.id).toEqual(container.id); expect(widget.isDestroyed()).toEqual(false); widget.destroy(); expect(widget.isDestroyed()).toEqual(true); document.body.removeChild(container); }); it("throws if options is undefined", function() { expect(function() { return new import__773.PerformanceWatchdog(void 0); }).toThrowDeveloperError(); }); it("throws if options.container is undefined", function() { expect(function() { return new import__773.PerformanceWatchdog({ container: void 0, scene: scene2 }); }).toThrowDeveloperError(); }); it("throws if options.scene is undefined", function() { const container = document.createElement("span"); container.id = "testContainer"; document.body.appendChild(container); expect(function() { return new import__773.PerformanceWatchdog({ container, scene: void 0 }); }).toThrowDeveloperError(); document.body.removeChild(container); }); it("constructor throws with string element that does not exist", function() { expect(function() { return new import__773.PerformanceWatchdog({ container: "does not exist", scene: scene2 }); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/widgets/Specs/PerformanceWatchdog/PerformanceWatchdogViewModelSpec.js var import_engine45 = __toESM(require_Cesium(), 1); var import__774 = __toESM(require_Cesium(), 1); describe( "Widgets/PerformanceWatchdog/PerformanceWatchdogViewModel", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); let viewModel; afterEach(function() { if ((0, import_engine45.defined)(viewModel)) { viewModel.destroy(); viewModel = void 0; } import_engine45.FrameRateMonitor.fromScene(scene2).destroy(); }); function spinWait(milliseconds) { const endTime = (0, import_engine45.getTimestamp)() + milliseconds; while ((0, import_engine45.getTimestamp)() < endTime) { } } it("throws when constructed without a scene", function() { expect(function() { viewModel = new import__774.PerformanceWatchdogViewModel(); }).toThrowDeveloperError(); expect(function() { viewModel = new import__774.PerformanceWatchdogViewModel({}); }).toThrowDeveloperError(); }); it("can be constructed with just a scene", function() { viewModel = new import__774.PerformanceWatchdogViewModel({ scene: scene2 }); expect(viewModel.lowFrameRateMessage).toBeDefined(); expect(viewModel.lowFrameRateMessageDismissed).toBe(false); expect(viewModel.showingLowFrameRateMessage).toBe(false); expect(viewModel.scene).toBe(scene2); }); it("honors parameters to the constructor", function() { const options = { scene: scene2, lowFrameRateMessage: "why so slow?" }; viewModel = new import__774.PerformanceWatchdogViewModel(options); expect(viewModel.lowFrameRateMessage).toBe("why so slow?"); expect(viewModel.scene).toBe(scene2); }); it("shows a message on low frame rate", function() { const monitor = import_engine45.FrameRateMonitor.fromScene(scene2); monitor.quietPeriod = 1e-3; monitor.warmupPeriod = 1e-3; monitor.samplingWindow = 1e-3; monitor.minimumFrameRateDuringWarmup = 1e3; monitor.minimumFrameRateAfterWarmup = 1e3; viewModel = new import__774.PerformanceWatchdogViewModel({ scene: scene2 }); expect(viewModel.showingLowFrameRateMessage).toBe(false); scene2.render(); spinWait(2); scene2.render(); spinWait(2); scene2.render(); expect(viewModel.showingLowFrameRateMessage).toBe(true); }); it("does not report a low frame rate during the queit period", function() { const monitor = import_engine45.FrameRateMonitor.fromScene(scene2); monitor.quietPeriod = 1; monitor.warmupPeriod = 1e-3; monitor.samplingWindow = 1e-3; monitor.minimumFrameRateDuringWarmup = 1e3; monitor.minimumFrameRateAfterWarmup = 1e3; viewModel = new import__774.PerformanceWatchdogViewModel({ scene: scene2 }); scene2.render(); spinWait(2); scene2.render(); expect(viewModel.showingLowFrameRateMessage).toBe(false); }); it("the low frame rate message goes away after the warmup period if the frame rate returns to nominal", function() { const monitor = import_engine45.FrameRateMonitor.fromScene(scene2); monitor.quietPeriod = 1e-3; monitor.warmupPeriod = 1e-3; monitor.samplingWindow = 1e-3; monitor.minimumFrameRateDuringWarmup = 10; monitor.minimumFrameRateAfterWarmup = 10; viewModel = new import__774.PerformanceWatchdogViewModel({ scene: scene2 }); expect(viewModel.showingLowFrameRateMessage).toBe(false); scene2.render(); spinWait(2); scene2.render(); spinWait(120); scene2.render(); expect(viewModel.showingLowFrameRateMessage).toBe(true); const endTime = (0, import_engine45.getTimestamp)() + 50; while ((0, import_engine45.getTimestamp)() < endTime) { scene2.render(); } expect(viewModel.showingLowFrameRateMessage).toBe(false); }); it("does not show the low frame rate message again once it is dismissed", function() { const monitor = import_engine45.FrameRateMonitor.fromScene(scene2); monitor.quietPeriod = 1e-3; monitor.warmupPeriod = 1e-3; monitor.samplingWindow = 1e-3; monitor.minimumFrameRateDuringWarmup = 1e3; monitor.minimumFrameRateAfterWarmup = 1e3; viewModel = new import__774.PerformanceWatchdogViewModel({ scene: scene2 }); expect(viewModel.showingLowFrameRateMessage).toBe(false); scene2.render(); spinWait(2); scene2.render(); spinWait(2); scene2.render(); expect(viewModel.showingLowFrameRateMessage).toBe(true); viewModel.dismissMessage(); scene2.render(); spinWait(2); scene2.render(); expect(viewModel.showingLowFrameRateMessage).toBe(false); }); }, "WebGL" ); // packages/widgets/Specs/ProjectionPicker/ProjectionPickerSpec.js var import_engine46 = __toESM(require_Cesium(), 1); var import__775 = __toESM(require_Cesium(), 1); describe( "Widgets/ProjectionPicker/ProjectionPicker", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); it("can create and destroy", function() { const container = document.createElement("span"); container.id = "testContainer"; document.body.appendChild(container); const widget = new import__775.ProjectionPicker("testContainer", scene2); expect(widget.container.id).toBe(container.id); expect(widget.isDestroyed()).toEqual(false); widget.destroy(); expect(widget.isDestroyed()).toEqual(true); document.body.removeChild(container); }); function addCloseOnInputSpec(name, func) { it(`${name} event closes dropdown if target is not inside container`, function() { const container = document.createElement("span"); container.id = "testContainer"; document.body.appendChild(container); const widget = new import__775.ProjectionPicker("testContainer", scene2); widget.viewModel.dropDownVisible = true; func(document.body); expect(widget.viewModel.dropDownVisible).toEqual(false); widget.viewModel.dropDownVisible = true; func(container.firstChild); expect(widget.viewModel.dropDownVisible).toEqual(true); widget.destroy(); document.body.removeChild(container); }); } function addDisabledDuringFlightSpec(name, func) { it(`${name} event does nothing during camera flight`, function() { const container = document.createElement("span"); container.id = "testContainer"; document.body.appendChild(container); const widget = new import__775.ProjectionPicker("testContainer", scene2); scene2.camera.flyHome(100); func(container.firstChild); expect(widget.viewModel.dropDownVisible).toEqual(false); scene2.camera.cancelFlight(); widget.destroy(); document.body.removeChild(container); }); } function addDisabledIn2DSpec(name, func) { it(`${name} event does nothing in 2D`, function() { const container = document.createElement("span"); container.id = "testContainer"; document.body.appendChild(container); const widget = new import__775.ProjectionPicker("testContainer", scene2); scene2.morphTo2D(0); func(container.firstChild); expect(widget.viewModel.dropDownVisible).toEqual(false); widget.destroy(); document.body.removeChild(container); }); } if (import_engine46.FeatureDetection.supportsPointerEvents()) { addCloseOnInputSpec("pointerDown", DomEventSimulator_default.firePointerDown); addDisabledDuringFlightSpec( "pointerDown", DomEventSimulator_default.firePointerDown ); addDisabledIn2DSpec("pointerDown", DomEventSimulator_default.firePointerDown); } else { addCloseOnInputSpec("mousedown", DomEventSimulator_default.fireMouseDown); addCloseOnInputSpec("touchstart", DomEventSimulator_default.fireTouchStart); addDisabledDuringFlightSpec("mousedown", DomEventSimulator_default.fireMouseDown); addDisabledDuringFlightSpec( "touchstart", DomEventSimulator_default.fireTouchStart ); addDisabledIn2DSpec("mousedown", DomEventSimulator_default.fireMouseDown); addDisabledIn2DSpec("touchstart", DomEventSimulator_default.fireTouchStart); } it("constructor throws with no scene", function() { expect(function() { return new import__775.ProjectionPicker(document.body, void 0); }).toThrowDeveloperError(); }); it("constructor throws with no element", function() { expect(function() { return new import__775.ProjectionPicker(void 0, scene2); }).toThrowDeveloperError(); }); it("constructor throws with string element that does not exist", function() { expect(function() { return new import__775.ProjectionPicker("does not exist", scene2); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/widgets/Specs/ProjectionPicker/ProjectionPickerViewModelSpec.js var import_engine47 = __toESM(require_Cesium(), 1); var import__776 = __toESM(require_Cesium(), 1); describe( "Widgets/ProjectionPicker/ProjectionPickerViewModel", function() { let scene2; beforeEach(function() { scene2 = createScene_default(); }); afterEach(function() { scene2.destroyForSpecs(); }); it("Can construct and destroy", function() { const viewModel = new import__776.ProjectionPickerViewModel(scene2); expect(viewModel.scene).toBe(scene2); expect(scene2.morphComplete.numberOfListeners).toEqual(1); expect(scene2.preRender.numberOfListeners).toEqual(1); expect(viewModel.isDestroyed()).toEqual(false); viewModel.destroy(); expect(viewModel.isDestroyed()).toEqual(true); expect(scene2.morphComplete.numberOfListeners).toEqual(0); expect(scene2.preRender.numberOfListeners).toEqual(0); }); it("dropDownVisible and toggleDropDown work", function() { const viewModel = new import__776.ProjectionPickerViewModel(scene2); expect(viewModel.dropDownVisible).toEqual(false); viewModel.toggleDropDown(); expect(viewModel.dropDownVisible).toEqual(true); viewModel.dropDownVisible = false; expect(viewModel.dropDownVisible).toEqual(false); viewModel.destroy(); }); it("morphing to 2D calls correct transition", function() { const viewModel = new import__776.ProjectionPickerViewModel(scene2); expect(scene2.mode).toEqual(import_engine47.SceneMode.SCENE3D); expect(viewModel.isOrthographicProjection).toEqual(false); scene2.morphTo2D(0); expect(scene2.mode).toEqual(import_engine47.SceneMode.SCENE2D); expect(viewModel.isOrthographicProjection).toEqual(true); viewModel.destroy(); }); it("switching projection calls correct transition", function() { const viewModel = new import__776.ProjectionPickerViewModel(scene2); expect(scene2.mode).toEqual(import_engine47.SceneMode.SCENE3D); expect(viewModel.isOrthographicProjection).toEqual(false); expect(scene2.camera.frustum).toBeInstanceOf(import_engine47.PerspectiveFrustum); viewModel.switchToOrthographic(); expect(viewModel.isOrthographicProjection).toEqual(true); expect(scene2.camera.frustum).toBeInstanceOf(import_engine47.OrthographicFrustum); viewModel.switchToPerspective(); expect(viewModel.isOrthographicProjection).toEqual(false); expect(scene2.camera.frustum).toBeInstanceOf(import_engine47.PerspectiveFrustum); viewModel.destroy(); }); it("selectedTooltip changes on transition", function() { const viewModel = new import__776.ProjectionPickerViewModel(scene2); viewModel.switchToOrthographic(); expect(viewModel.selectedTooltip).toEqual(viewModel.tooltipOrthographic); viewModel.switchToPerspective(); expect(viewModel.selectedTooltip).toEqual(viewModel.tooltipPerspective); viewModel.destroy(); }); it("create throws with undefined scene", function() { expect(function() { return new import__776.ProjectionPickerViewModel(); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/widgets/Specs/SceneModePicker/SceneModePickerSpec.js var import_engine48 = __toESM(require_Cesium(), 1); var import__777 = __toESM(require_Cesium(), 1); describe( "Widgets/SceneModePicker/SceneModePicker", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); it("can create and destroy", function() { const container = document.createElement("span"); container.id = "testContainer"; document.body.appendChild(container); const widget = new import__777.SceneModePicker("testContainer", scene2); expect(widget.container.id).toBe(container.id); expect(widget.isDestroyed()).toEqual(false); widget.destroy(); expect(widget.isDestroyed()).toEqual(true); document.body.removeChild(container); }); function addCloseOnInputSpec(name, func) { it(`${name} event closes dropdown if target is not inside container`, function() { const container = document.createElement("span"); container.id = "testContainer"; document.body.appendChild(container); const widget = new import__777.SceneModePicker("testContainer", scene2); widget.viewModel.dropDownVisible = true; func(document.body); expect(widget.viewModel.dropDownVisible).toEqual(false); widget.viewModel.dropDownVisible = true; func(container.firstChild); expect(widget.viewModel.dropDownVisible).toEqual(true); widget.destroy(); document.body.removeChild(container); }); } if (import_engine48.FeatureDetection.supportsPointerEvents()) { addCloseOnInputSpec("pointerDown", DomEventSimulator_default.firePointerDown); } else { addCloseOnInputSpec("mousedown", DomEventSimulator_default.fireMouseDown); addCloseOnInputSpec("touchstart", DomEventSimulator_default.fireTouchStart); } it("constructor throws with no transitioner", function() { expect(function() { return new import__777.SceneModePicker(document.body, void 0); }).toThrowDeveloperError(); }); it("constructor throws with no element", function() { expect(function() { return new import__777.SceneModePicker(void 0, scene2); }).toThrowDeveloperError(); }); it("constructor throws with string element that does not exist", function() { expect(function() { return new import__777.SceneModePicker("does not exist", scene2); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/widgets/Specs/SceneModePicker/SceneModePickerViewModelSpec.js var import_engine49 = __toESM(require_Cesium(), 1); var import__778 = __toESM(require_Cesium(), 1); describe( "Widgets/SceneModePicker/SceneModePickerViewModel", function() { let scene2; const ellipsoid = import_engine49.Ellipsoid.WGS84; beforeEach(function() { scene2 = createScene_default(); const globe2 = new import_engine49.Globe(ellipsoid); scene2.globe = globe2; }); afterEach(function() { scene2.destroyForSpecs(); }); it("Can construct and destroy", function() { const viewModel = new import__778.SceneModePickerViewModel(scene2, 1); expect(viewModel.scene).toBe(scene2); expect(viewModel.duration).toEqual(1); expect(scene2.morphStart.numberOfListeners).toEqual(1); expect(viewModel.isDestroyed()).toEqual(false); viewModel.destroy(); expect(viewModel.isDestroyed()).toEqual(true); expect(scene2.morphStart.numberOfListeners).toEqual(0); }); it("dropDownVisible and toggleDropDown work", function() { const viewModel = new import__778.SceneModePickerViewModel(scene2); expect(viewModel.dropDownVisible).toEqual(false); viewModel.toggleDropDown(); expect(viewModel.dropDownVisible).toEqual(true); viewModel.dropDownVisible = false; expect(viewModel.dropDownVisible).toEqual(false); viewModel.destroy(); }); it("morphing closes the dropDown", function() { const viewModel = new import__778.SceneModePickerViewModel(scene2); viewModel.dropDownVisible = true; viewModel.morphToColumbusView(); expect(viewModel.dropDownVisible).toEqual(false); viewModel.dropDownVisible = true; viewModel.morphTo3D(); expect(viewModel.dropDownVisible).toEqual(false); viewModel.dropDownVisible = true; viewModel.morphTo2D(); expect(viewModel.dropDownVisible).toEqual(false); viewModel.destroy(); }); it("morphing calls correct transition", function() { const viewModel = new import__778.SceneModePickerViewModel(scene2); expect(scene2.mode).toEqual(import_engine49.SceneMode.SCENE3D); viewModel.morphToColumbusView(); scene2.completeMorph(); expect(scene2.mode).toEqual(import_engine49.SceneMode.COLUMBUS_VIEW); viewModel.morphTo3D(); scene2.completeMorph(); expect(scene2.mode).toEqual(import_engine49.SceneMode.SCENE3D); viewModel.morphTo2D(); scene2.completeMorph(); expect(scene2.mode).toEqual(import_engine49.SceneMode.SCENE2D); viewModel.destroy(); }); it("selectedTooltip changes on transition", function() { const viewModel = new import__778.SceneModePickerViewModel(scene2); viewModel.morphToColumbusView(); expect(viewModel.selectedTooltip).toEqual(viewModel.tooltipColumbusView); viewModel.morphTo3D(); expect(viewModel.selectedTooltip).toEqual(viewModel.tooltip3D); viewModel.morphTo2D(); expect(viewModel.selectedTooltip).toEqual(viewModel.tooltip2D); viewModel.destroy(); }); it("create throws with undefined scene", function() { expect(function() { return new import__778.SceneModePickerViewModel(); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/widgets/Specs/SelectionIndicator/SelectionIndicatorSpec.js var import__779 = __toESM(require_Cesium(), 1); describe( "Widgets/SelectionIndicator/SelectionIndicator", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); it("constructor sets expected values", function() { const selectionIndicator = new import__779.SelectionIndicator(document.body, scene2); expect(selectionIndicator.container).toBe(document.body); expect(selectionIndicator.viewModel.scene).toBe(scene2); expect(selectionIndicator.isDestroyed()).toEqual(false); selectionIndicator.destroy(); expect(selectionIndicator.isDestroyed()).toEqual(true); }); it("constructor works with string id container", function() { const testElement = document.createElement("span"); testElement.id = "testElement"; document.body.appendChild(testElement); const selectionIndicator = new import__779.SelectionIndicator("testElement", scene2); expect(selectionIndicator.container).toBe(testElement); document.body.removeChild(testElement); selectionIndicator.destroy(); }); it("throws if container is undefined", function() { expect(function() { return new import__779.SelectionIndicator(void 0, scene2); }).toThrowDeveloperError(); }); it("throws if container string is undefined", function() { expect(function() { return new import__779.SelectionIndicator("testElement", scene2); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/widgets/Specs/SelectionIndicator/SelectionIndicatorViewModelSpec.js var import_engine50 = __toESM(require_Cesium(), 1); var import__780 = __toESM(require_Cesium(), 1); describe( "Widgets/SelectionIndicator/SelectionIndicatorViewModel", function() { let scene2; const selectionIndicatorElement = document.createElement("div"); selectionIndicatorElement.style.width = "20px"; selectionIndicatorElement.style.height = "20px"; const container = document.createElement("div"); container.appendChild(selectionIndicatorElement); beforeAll(function() { scene2 = createScene_default(); }); afterAll(function() { scene2.destroyForSpecs(); }); it("constructor sets expected values", function() { const viewModel = new import__780.SelectionIndicatorViewModel( scene2, selectionIndicatorElement, container ); expect(viewModel.scene).toBe(scene2); expect(viewModel.selectionIndicatorElement).toBe( selectionIndicatorElement ); expect(viewModel.container).toBe(container); expect(viewModel.computeScreenSpacePosition).toBeDefined(); }); it("throws if scene is undefined", function() { expect(function() { return new import__780.SelectionIndicatorViewModel(void 0); }).toThrowDeveloperError(); }); it("throws if selectionIndicatorElement is undefined", function() { expect(function() { return new import__780.SelectionIndicatorViewModel(scene2); }).toThrowDeveloperError(); }); it("throws if container is undefined", function() { expect(function() { return new import__780.SelectionIndicatorViewModel( scene2, selectionIndicatorElement ); }).toThrowDeveloperError(); }); it("can animate selection element", function() { const viewModel = new import__780.SelectionIndicatorViewModel( scene2, selectionIndicatorElement, container ); viewModel.animateAppear(); viewModel.animateDepart(); }); it("can use custom screen space positions", function() { document.body.appendChild(container); const viewModel = new import__780.SelectionIndicatorViewModel( scene2, selectionIndicatorElement, container ); viewModel.showSelection = true; viewModel.position = new import_engine50.Cartesian3(1, 2, 3); viewModel.computeScreenSpacePosition = function(position, result) { return import_engine50.Cartesian2.clone(position, result); }; viewModel.update(); expect(viewModel._screenPositionX).toBe("-9px"); expect(viewModel._screenPositionY).toBe("-8px"); document.body.removeChild(container); }); it("hides the indicator when position is unknown", function() { const viewModel = new import__780.SelectionIndicatorViewModel( scene2, selectionIndicatorElement, container ); expect(viewModel.isVisible).toBe(false); viewModel.showSelection = true; expect(viewModel.isVisible).toBe(false); viewModel.position = new import_engine50.Cartesian3(1, 2, 3); expect(viewModel.isVisible).toBe(true); viewModel.showSelection = false; expect(viewModel.isVisible).toBe(false); }); it("can move the indicator off screen", function() { document.body.appendChild(container); const viewModel = new import__780.SelectionIndicatorViewModel( scene2, selectionIndicatorElement, container ); viewModel.showSelection = true; viewModel.position = new import_engine50.Cartesian3(1, 2, 3); viewModel.computeScreenSpacePosition = function(position, result) { return void 0; }; viewModel.update(); expect(viewModel._screenPositionX).toBe("-1000px"); expect(viewModel._screenPositionY).toBe("-1000px"); document.body.removeChild(container); }); }, "WebGL" ); // packages/widgets/Specs/ThirdParty/knockoutSpec.js var import__781 = __toESM(require_Cesium(), 1); describe("ThirdParty/knockout", function() { it("can track all properties", function() { const obj = { one: 1, two: void 0, three: import__781.knockout.observable() }; expect(import__781.knockout.getObservable(obj, "one")).toBeNull(); expect(import__781.knockout.getObservable(obj, "two")).toBeNull(); expect(import__781.knockout.getObservable(obj, "three")).toBeNull(); import__781.knockout.track(obj); expect(import__781.knockout.getObservable(obj, "one")).not.toBeNull(); expect(import__781.knockout.getObservable(obj, "two")).not.toBeNull(); expect(import__781.knockout.getObservable(obj, "three")).not.toBeNull(); }); }); // packages/widgets/Specs/Timeline/TimelineSpec.js var import_engine51 = __toESM(require_Cesium(), 1); var import__782 = __toESM(require_Cesium(), 1); describe("Widgets/Timeline/Timeline", function() { let container; beforeEach(function() { container = document.createElement("span"); container.id = "container"; container.style.width = "1px"; container.style.height = "1px"; document.body.appendChild(container); }); afterEach(function() { document.body.removeChild(container); }); it("sanity check", function() { const timeline = new import__782.Timeline(container, new import_engine51.Clock()); timeline.resize(); expect(timeline.isDestroyed()).toEqual(false); timeline.destroy(); expect(timeline.isDestroyed()).toEqual(true); }); }); // packages/widgets/Specs/VRButton/VRButtonSpec.js var import__783 = __toESM(require_Cesium(), 1); describe("Widgets/VRButton/VRButton", function() { let scene2; beforeEach(function() { scene2 = createScene_default(); }); afterEach(function() { scene2.destroyForSpecs(); }); it("constructor sets default values", function() { const vrButton = new import__783.VRButton(document.body, scene2); expect(vrButton.container).toBe(document.body); expect(vrButton.viewModel.vrElement).toBe(document.body); expect(vrButton.isDestroyed()).toEqual(false); vrButton.destroy(); expect(vrButton.isDestroyed()).toEqual(true); }); it("constructor sets expected values", function() { const testElement = document.createElement("span"); const vrButton = new import__783.VRButton(document.body, scene2, testElement); expect(vrButton.container).toBe(document.body); expect(vrButton.viewModel.vrElement).toBe(testElement); vrButton.destroy(); }); it("constructor works with string id container", function() { const testElement = document.createElement("span"); testElement.id = "testElement"; document.body.appendChild(testElement); const vrButton = new import__783.VRButton("testElement", scene2); expect(vrButton.container).toBe(testElement); document.body.removeChild(testElement); vrButton.destroy(); }); it("throws if container is undefined", function() { expect(function() { return new import__783.VRButton(void 0, scene2); }).toThrowDeveloperError(); }); it("throws if container string is undefined", function() { expect(function() { return new import__783.VRButton("testElement", scene2); }).toThrowDeveloperError(); }); it("throws if scene is undefined", function() { expect(function() { return new import__783.VRButton(document.body, void 0); }).toThrowDeveloperError(); }); }); // packages/widgets/Specs/VRButton/VRButtonViewModelSpec.js var import_engine52 = __toESM(require_Cesium(), 1); var import__784 = __toESM(require_Cesium(), 1); describe("Widgets/VRButton/VRButtonViewModel", function() { let scene2; beforeEach(function() { scene2 = createScene_default(); }); afterEach(function() { scene2.destroyForSpecs(); }); it("constructor sets default values", function() { const viewModel = new import__784.VRButtonViewModel(scene2); expect(viewModel.vrElement).toBe(document.body); expect(viewModel.isDestroyed()).toEqual(false); viewModel.destroy(); expect(viewModel.isDestroyed()).toEqual(true); }); it("constructor sets expected values", function() { const testElement = document.createElement("span"); const viewModel = new import__784.VRButtonViewModel(scene2, testElement); expect(viewModel.vrElement).toBe(testElement); viewModel.destroy(); }); it("constructor can take an element id", function() { const testElement = document.createElement("span"); testElement.id = "testElement"; document.body.appendChild(testElement); const viewModel = new import__784.VRButtonViewModel(scene2, "testElement"); expect(viewModel.vrElement).toBe(testElement); viewModel.destroy(); document.body.removeChild(testElement); }); it("isVREnabled work as expected", function() { const viewModel = new import__784.VRButtonViewModel(scene2); expect(viewModel.isVREnabled).toEqual(import_engine52.Fullscreen.enabled); viewModel.isVREnabled = false; expect(viewModel.isVREnabled).toEqual(false); viewModel.destroy(); }); it("can get and set vrElement", function() { const testElement = document.createElement("span"); const viewModel = new import__784.VRButtonViewModel(scene2); expect(viewModel.vrElement).not.toBe(testElement); viewModel.vrElement = testElement; expect(viewModel.vrElement).toBe(testElement); }); it("throws when constructed without a scene", function() { expect(function() { return new import__784.VRButtonViewModel(); }).toThrowDeveloperError(); }); it("throws is setting vrElement is not an Element", function() { const viewModel = new import__784.VRButtonViewModel(scene2); expect(function() { viewModel.vrElement = {}; }).toThrowDeveloperError(); }); }); // packages/widgets/Specs/Viewer/ViewerSpec.js var import_engine54 = __toESM(require_Cesium(), 1); var import__786 = __toESM(require_Cesium(), 1); // packages/widgets/Specs/createViewer.js var import_engine53 = __toESM(require_Cesium(), 1); var import__785 = __toESM(require_Cesium(), 1); function createViewer(container, options) { options = (0, import_engine53.defaultValue)(options, {}); options.contextOptions = (0, import_engine53.defaultValue)(options.contextOptions, {}); options.contextOptions.webgl = (0, import_engine53.defaultValue)(options.contextOptions.webgl, {}); if (!!window.webglStub) { options.contextOptions.getWebGLStub = getWebGLStub_default; } return new import__785.Viewer(container, options); } var createViewer_default = createViewer; // packages/widgets/Specs/Viewer/ViewerSpec.js describe( "Widgets/Viewer/Viewer", function() { const testProvider = { tilingScheme: { tileXYToRectangle: function() { return new import_engine54.Rectangle(); } }, rectangle: import_engine54.Rectangle.MAX_VALUE }; const testProviderViewModel = new import__786.ProviderViewModel({ name: "name", tooltip: "tooltip", iconUrl: "url", creationFunction: function() { return testProvider; } }); let container; let viewer; beforeEach(function() { container = document.createElement("div"); container.id = "container"; container.style.width = "1px"; container.style.height = "1px"; container.style.overflow = "hidden"; container.style.position = "relative"; document.body.appendChild(container); }); afterEach(function() { if (viewer && !viewer.isDestroyed()) { viewer = viewer.destroy(); } document.body.removeChild(container); }); it("constructor sets default values", function() { viewer = createViewer_default(container); expect(viewer.container).toBe(container); expect(viewer.cesiumWidget).toBeInstanceOf(import_engine54.CesiumWidget); expect(viewer.geocoder).toBeInstanceOf(import__786.Geocoder); expect(viewer.homeButton).toBeInstanceOf(import__786.HomeButton); expect(viewer.sceneModePicker).toBeInstanceOf(import__786.SceneModePicker); expect(viewer.baseLayerPicker).toBeInstanceOf(import__786.BaseLayerPicker); expect(viewer.navigationHelpButton).toBeInstanceOf(import__786.NavigationHelpButton); expect(viewer.animation).toBeInstanceOf(import__786.Animation); expect(viewer.clockViewModel).toBeInstanceOf(import__786.ClockViewModel); expect(viewer.animation.viewModel.clockViewModel).toBe( viewer.clockViewModel ); expect(viewer.timeline).toBeInstanceOf(import__786.Timeline); expect(viewer.fullscreenButton).toBeInstanceOf(import__786.FullscreenButton); expect(viewer.selectionIndicator).toBeInstanceOf(import__786.SelectionIndicator); expect(viewer.imageryLayers).toBeInstanceOf(import_engine54.ImageryLayerCollection); expect(viewer.terrainProvider).toBeInstanceOf(import_engine54.EllipsoidTerrainProvider); expect(viewer.creditDisplay).toBeInstanceOf(import_engine54.CreditDisplay); expect(viewer.camera).toBeInstanceOf(import_engine54.Camera); expect(viewer.dataSourceDisplay).toBeInstanceOf(import_engine54.DataSourceDisplay); expect(viewer.dataSources).toBeInstanceOf(import_engine54.DataSourceCollection); expect(viewer.canvas).toBe(viewer.cesiumWidget.canvas); expect(viewer.cesiumLogo).toBe(viewer.cesiumWidget.cesiumLogo); expect(viewer.screenSpaceEventHandler).toBe( viewer.cesiumWidget.screenSpaceEventHandler ); expect(viewer.useBrowserRecommendedResolution).toBe(true); expect(viewer.isDestroyed()).toEqual(false); viewer.destroy(); expect(viewer.isDestroyed()).toEqual(true); }); it("can specify custom clockViewModel", function() { const clockViewModel = new import__786.ClockViewModel(); viewer = createViewer_default(container, { clockViewModel }); expect(viewer.clockViewModel).toBe(clockViewModel); expect(viewer.animation.viewModel.clockViewModel).toBe( viewer.clockViewModel ); viewer.destroy(); expect(clockViewModel.isDestroyed()).toBe(false); clockViewModel.destroy(); }); it("can set shouldAnimate", function() { viewer = createViewer_default(container, { shouldAnimate: true }); expect(viewer.clock.shouldAnimate).toBe(true); }); it("setting shouldAnimate in options overrides clock shouldAnimate", function() { const clockViewModel = new import__786.ClockViewModel( new import_engine54.Clock({ shouldAnimate: false }) ); viewer = createViewer_default(container, { clockViewModel, shouldAnimate: true }); expect(viewer.clock.shouldAnimate).toBe(true); }); it("renders without errors", function() { viewer = createViewer_default(container); spyOn(viewer.scene.renderError, "raiseEvent"); viewer.render(); expect(viewer.scene.renderError.raiseEvent).not.toHaveBeenCalled(); }); it("constructor works with container id string", function() { viewer = createViewer_default("container"); expect(viewer.container).toBe(container); }); it("can shut off HomeButton", function() { viewer = createViewer_default(container, { homeButton: false }); expect(viewer.container).toBe(container); expect(viewer.cesiumWidget).toBeInstanceOf(import_engine54.CesiumWidget); expect(viewer.geocoder).toBeInstanceOf(import__786.Geocoder); expect(viewer.homeButton).toBeUndefined(); expect(viewer.sceneModePicker).toBeInstanceOf(import__786.SceneModePicker); expect(viewer.baseLayerPicker).toBeInstanceOf(import__786.BaseLayerPicker); expect(viewer.navigationHelpButton).toBeInstanceOf(import__786.NavigationHelpButton); expect(viewer.animation).toBeInstanceOf(import__786.Animation); expect(viewer.timeline).toBeInstanceOf(import__786.Timeline); expect(viewer.fullscreenButton).toBeInstanceOf(import__786.FullscreenButton); expect(viewer.selectionIndicator).toBeInstanceOf(import__786.SelectionIndicator); viewer.resize(); viewer.render(); }); it("can shut off SceneModePicker", function() { viewer = createViewer_default(container, { sceneModePicker: false }); expect(viewer.container).toBe(container); expect(viewer.cesiumWidget).toBeInstanceOf(import_engine54.CesiumWidget); expect(viewer.geocoder).toBeInstanceOf(import__786.Geocoder); expect(viewer.homeButton).toBeInstanceOf(import__786.HomeButton); expect(viewer.sceneModePicker).toBeUndefined(); expect(viewer.baseLayerPicker).toBeInstanceOf(import__786.BaseLayerPicker); expect(viewer.navigationHelpButton).toBeInstanceOf(import__786.NavigationHelpButton); expect(viewer.animation).toBeInstanceOf(import__786.Animation); expect(viewer.timeline).toBeInstanceOf(import__786.Timeline); expect(viewer.fullscreenButton).toBeInstanceOf(import__786.FullscreenButton); expect(viewer.selectionIndicator).toBeInstanceOf(import__786.SelectionIndicator); viewer.resize(); viewer.render(); }); it("can shut off BaseLayerPicker", function() { viewer = createViewer_default(container, { baseLayerPicker: false }); expect(viewer.container).toBe(container); expect(viewer.cesiumWidget).toBeInstanceOf(import_engine54.CesiumWidget); expect(viewer.geocoder).toBeInstanceOf(import__786.Geocoder); expect(viewer.homeButton).toBeInstanceOf(import__786.HomeButton); expect(viewer.sceneModePicker).toBeInstanceOf(import__786.SceneModePicker); expect(viewer.baseLayerPicker).toBeUndefined(); expect(viewer.navigationHelpButton).toBeInstanceOf(import__786.NavigationHelpButton); expect(viewer.animation).toBeInstanceOf(import__786.Animation); expect(viewer.timeline).toBeInstanceOf(import__786.Timeline); expect(viewer.fullscreenButton).toBeInstanceOf(import__786.FullscreenButton); expect(viewer.selectionIndicator).toBeInstanceOf(import__786.SelectionIndicator); viewer.resize(); viewer.render(); }); it("can shut off NavigationHelpButton", function() { viewer = createViewer_default(container, { navigationHelpButton: false }); expect(viewer.container).toBe(container); expect(viewer.cesiumWidget).toBeInstanceOf(import_engine54.CesiumWidget); expect(viewer.geocoder).toBeInstanceOf(import__786.Geocoder); expect(viewer.homeButton).toBeInstanceOf(import__786.HomeButton); expect(viewer.sceneModePicker).toBeInstanceOf(import__786.SceneModePicker); expect(viewer.baseLayerPicker).toBeInstanceOf(import__786.BaseLayerPicker); expect(viewer.navigationHelpButton).toBeUndefined(); expect(viewer.animation).toBeInstanceOf(import__786.Animation); expect(viewer.timeline).toBeInstanceOf(import__786.Timeline); expect(viewer.fullscreenButton).toBeInstanceOf(import__786.FullscreenButton); expect(viewer.selectionIndicator).toBeInstanceOf(import__786.SelectionIndicator); viewer.resize(); viewer.render(); }); it("can shut off Animation", function() { viewer = createViewer_default(container, { animation: false }); expect(viewer.container).toBe(container); expect(viewer.cesiumWidget).toBeInstanceOf(import_engine54.CesiumWidget); expect(viewer.geocoder).toBeInstanceOf(import__786.Geocoder); expect(viewer.homeButton).toBeInstanceOf(import__786.HomeButton); expect(viewer.sceneModePicker).toBeInstanceOf(import__786.SceneModePicker); expect(viewer.baseLayerPicker).toBeInstanceOf(import__786.BaseLayerPicker); expect(viewer.navigationHelpButton).toBeInstanceOf(import__786.NavigationHelpButton); expect(viewer.animation).toBeUndefined(); expect(viewer.timeline).toBeInstanceOf(import__786.Timeline); expect(viewer.fullscreenButton).toBeInstanceOf(import__786.FullscreenButton); expect(viewer.selectionIndicator).toBeInstanceOf(import__786.SelectionIndicator); viewer.resize(); viewer.render(); }); it("can shut off Timeline", function() { viewer = createViewer_default(container, { timeline: false }); expect(viewer.container).toBe(container); expect(viewer.cesiumWidget).toBeInstanceOf(import_engine54.CesiumWidget); expect(viewer.geocoder).toBeInstanceOf(import__786.Geocoder); expect(viewer.homeButton).toBeInstanceOf(import__786.HomeButton); expect(viewer.sceneModePicker).toBeInstanceOf(import__786.SceneModePicker); expect(viewer.baseLayerPicker).toBeInstanceOf(import__786.BaseLayerPicker); expect(viewer.navigationHelpButton).toBeInstanceOf(import__786.NavigationHelpButton); expect(viewer.animation).toBeInstanceOf(import__786.Animation); expect(viewer.timeline).toBeUndefined(); expect(viewer.fullscreenButton).toBeInstanceOf(import__786.FullscreenButton); expect(viewer.selectionIndicator).toBeInstanceOf(import__786.SelectionIndicator); viewer.resize(); viewer.render(); }); it("can shut off FullscreenButton", function() { viewer = createViewer_default(container, { fullscreenButton: false }); expect(viewer.container).toBe(container); expect(viewer.cesiumWidget).toBeInstanceOf(import_engine54.CesiumWidget); expect(viewer.geocoder).toBeInstanceOf(import__786.Geocoder); expect(viewer.homeButton).toBeInstanceOf(import__786.HomeButton); expect(viewer.sceneModePicker).toBeInstanceOf(import__786.SceneModePicker); expect(viewer.baseLayerPicker).toBeInstanceOf(import__786.BaseLayerPicker); expect(viewer.navigationHelpButton).toBeInstanceOf(import__786.NavigationHelpButton); expect(viewer.animation).toBeInstanceOf(import__786.Animation); expect(viewer.timeline).toBeInstanceOf(import__786.Timeline); expect(viewer.fullscreenButton).toBeUndefined(); expect(viewer.selectionIndicator).toBeInstanceOf(import__786.SelectionIndicator); viewer.resize(); viewer.render(); }); it("can shut off FullscreenButton and Timeline", function() { viewer = createViewer_default(container, { timeline: false, fullscreenButton: false }); expect(viewer.container).toBe(container); expect(viewer.cesiumWidget).toBeInstanceOf(import_engine54.CesiumWidget); expect(viewer.geocoder).toBeInstanceOf(import__786.Geocoder); expect(viewer.homeButton).toBeInstanceOf(import__786.HomeButton); expect(viewer.sceneModePicker).toBeInstanceOf(import__786.SceneModePicker); expect(viewer.baseLayerPicker).toBeInstanceOf(import__786.BaseLayerPicker); expect(viewer.navigationHelpButton).toBeInstanceOf(import__786.NavigationHelpButton); expect(viewer.animation).toBeInstanceOf(import__786.Animation); expect(viewer.timeline).toBeUndefined(); expect(viewer.fullscreenButton).toBeUndefined(); expect(viewer.selectionIndicator).toBeInstanceOf(import__786.SelectionIndicator); viewer.resize(); viewer.render(); }); it("can shut off FullscreenButton, Timeline, and Animation", function() { viewer = createViewer_default(container, { timeline: false, fullscreenButton: false, animation: false }); expect(viewer.container).toBe(container); expect(viewer.cesiumWidget).toBeInstanceOf(import_engine54.CesiumWidget); expect(viewer.geocoder).toBeInstanceOf(import__786.Geocoder); expect(viewer.homeButton).toBeInstanceOf(import__786.HomeButton); expect(viewer.sceneModePicker).toBeInstanceOf(import__786.SceneModePicker); expect(viewer.baseLayerPicker).toBeInstanceOf(import__786.BaseLayerPicker); expect(viewer.navigationHelpButton).toBeInstanceOf(import__786.NavigationHelpButton); expect(viewer.animation).toBeUndefined(import__786.Animation); expect(viewer.timeline).toBeUndefined(); expect(viewer.fullscreenButton).toBeUndefined(); expect(viewer.selectionIndicator).toBeInstanceOf(import__786.SelectionIndicator); viewer.resize(); viewer.render(); }); it("can shut off Geocoder", function() { viewer = createViewer_default(container, { geocoder: false }); expect(viewer.container).toBe(container); expect(viewer.cesiumWidget).toBeInstanceOf(import_engine54.CesiumWidget); expect(viewer.geocoder).toBeUndefined(); expect(viewer.homeButton).toBeInstanceOf(import__786.HomeButton); expect(viewer.sceneModePicker).toBeInstanceOf(import__786.SceneModePicker); expect(viewer.baseLayerPicker).toBeInstanceOf(import__786.BaseLayerPicker); expect(viewer.navigationHelpButton).toBeInstanceOf(import__786.NavigationHelpButton); expect(viewer.animation).toBeInstanceOf(import__786.Animation); expect(viewer.timeline).toBeInstanceOf(import__786.Timeline); expect(viewer.fullscreenButton).toBeInstanceOf(import__786.FullscreenButton); expect(viewer.selectionIndicator).toBeInstanceOf(import__786.SelectionIndicator); viewer.resize(); viewer.render(); }); it("constructs geocoder", function() { viewer = createViewer_default(container, { geocoder: true }); expect(viewer.geocoder).toBeDefined(); expect(viewer.geocoder.viewModel._geocoderServices.length).toBe(1); }); it("constructs geocoder with geocoder service option", function() { const service = new import_engine54.CartographicGeocoderService(); viewer = createViewer_default(container, { geocoder: service }); expect(viewer.geocoder).toBeDefined(); expect(viewer.geocoder.viewModel._geocoderServices.length).toBe(1); expect(viewer.geocoder.viewModel._geocoderServices[0]).toBe(service); }); it("constructs geocoder with geocoder service options", function() { const service = new import_engine54.CartographicGeocoderService(); viewer = createViewer_default(container, { geocoder: [service] }); expect(viewer.geocoder).toBeDefined(); expect(viewer.geocoder.viewModel._geocoderServices.length).toBe(1); expect(viewer.geocoder.viewModel._geocoderServices[0]).toBe(service); }); it("can shut off SelectionIndicator", function() { viewer = createViewer_default(container, { selectionIndicator: false }); expect(viewer.container).toBe(container); expect(viewer.cesiumWidget).toBeInstanceOf(import_engine54.CesiumWidget); expect(viewer.geocoder).toBeInstanceOf(import__786.Geocoder); expect(viewer.homeButton).toBeInstanceOf(import__786.HomeButton); expect(viewer.sceneModePicker).toBeInstanceOf(import__786.SceneModePicker); expect(viewer.baseLayerPicker).toBeInstanceOf(import__786.BaseLayerPicker); expect(viewer.navigationHelpButton).toBeInstanceOf(import__786.NavigationHelpButton); expect(viewer.animation).toBeInstanceOf(import__786.Animation); expect(viewer.timeline).toBeInstanceOf(import__786.Timeline); expect(viewer.fullscreenButton).toBeInstanceOf(import__786.FullscreenButton); expect(viewer.selectionIndicator).toBeUndefined(); viewer.resize(); viewer.render(); }); it("can set shadows", function() { viewer = createViewer_default(container, { shadows: true }); expect(viewer.shadows).toBe(true); }); it("can set terrain shadows", function() { viewer = createViewer_default(container, { terrainShadows: import_engine54.ShadowMode.ENABLED }); expect(viewer.terrainShadows).toBe(import_engine54.ShadowMode.ENABLED); }); it("can set terrainProvider", function() { const provider = new import_engine54.EllipsoidTerrainProvider(); viewer = createViewer_default(container, { baseLayerPicker: false, terrainProvider: provider }); expect(viewer.scene.terrainProvider).toBe(provider); const anotherProvider = new import_engine54.EllipsoidTerrainProvider(); viewer.terrainProvider = anotherProvider; expect(viewer.terrainProvider).toBe(anotherProvider); }); it("can set fullScreenElement", function() { const testElement = document.createElement("span"); viewer = createViewer_default(container, { fullscreenElement: testElement }); expect(viewer.fullscreenButton.viewModel.fullscreenElement).toBe( testElement ); }); it("can set contextOptions", function() { const webglOptions = { alpha: true, depth: true, //TODO Change to false when https://bugzilla.mozilla.org/show_bug.cgi?id=745912 is fixed. stencil: true, antialias: false, powerPreference: "low-power", premultipliedAlpha: true, // Workaround IE 11.0.8, which does not honor false. preserveDrawingBuffer: true }; const contextOptions = { allowTextureFilterAnisotropic: false, webgl: webglOptions }; viewer = createViewer_default(container, { contextOptions }); const context = viewer.scene.context; const contextAttributes = context._gl.getContextAttributes(); expect(context.options.allowTextureFilterAnisotropic).toEqual(false); expect(contextAttributes.alpha).toEqual(webglOptions.alpha); expect(contextAttributes.depth).toEqual(webglOptions.depth); expect(contextAttributes.stencil).toEqual(webglOptions.stencil); expect(contextAttributes.antialias).toEqual(webglOptions.antialias); expect(contextAttributes.powerPreference).toEqual( webglOptions.powerPreference ); expect(contextAttributes.premultipliedAlpha).toEqual( webglOptions.premultipliedAlpha ); expect(contextAttributes.preserveDrawingBuffer).toEqual( webglOptions.preserveDrawingBuffer ); }); it("can disable Order Independent Translucency", function() { viewer = createViewer_default(container, { orderIndependentTranslucency: false }); expect(viewer.scene.orderIndependentTranslucency).toBe(false); }); it("can set scene mode", function() { viewer = createViewer_default(container, { sceneMode: import_engine54.SceneMode.SCENE2D }); viewer.scene.completeMorph(); expect(viewer.scene.mode).toBe(import_engine54.SceneMode.SCENE2D); }); it("can set map projection", function() { const mapProjection = new import_engine54.WebMercatorProjection(); viewer = createViewer_default(container, { mapProjection }); expect(viewer.scene.mapProjection).toEqual(mapProjection); }); it("can set selectedImageryProviderViewModel", async function() { viewer = createViewer_default(container, { selectedImageryProviderViewModel: testProviderViewModel }); await pollToPromise_default(() => viewer.scene.imageryLayers.get(0).ready); expect(viewer.scene.imageryLayers.length).toEqual(1); expect(viewer.scene.imageryLayers.get(0).imageryProvider).toBe( testProvider ); expect(viewer.baseLayerPicker.viewModel.selectedImagery).toBe( testProviderViewModel ); }); it("can set imageryProviderViewModels", async function() { const models = [testProviderViewModel]; viewer = createViewer_default(container, { imageryProviderViewModels: models }); await pollToPromise_default(() => viewer.scene.imageryLayers.get(0).ready); expect(viewer.scene.imageryLayers.length).toEqual(1); expect(viewer.scene.imageryLayers.get(0).imageryProvider).toBe( testProvider ); expect(viewer.baseLayerPicker.viewModel.selectedImagery).toBe( testProviderViewModel ); expect( viewer.baseLayerPicker.viewModel.imageryProviderViewModels.length ).toBe(models.length); expect( viewer.baseLayerPicker.viewModel.imageryProviderViewModels[0] ).toEqual(models[0]); }); it("can set baseLayer when BaseLayerPicker is disabled", function() { viewer = createViewer_default(container, { baseLayerPicker: false, baseLayer: new import_engine54.ImageryLayer(testProvider) }); expect(viewer.scene.imageryLayers.length).toEqual(1); expect(viewer.scene.imageryLayers.get(0).imageryProvider).toBe( testProvider ); }); it("can set baseLayer to false when BaseLayerPicker is disabled", function() { viewer = createViewer_default(container, { baseLayerPicker: false, baseLayer: false }); expect(viewer.scene.imageryLayers.length).toEqual(0); }); it("can disable render loop", function() { viewer = createViewer_default(container, { useDefaultRenderLoop: false }); expect(viewer.useDefaultRenderLoop).toBe(false); }); it("can set target frame rate", function() { viewer = createViewer_default(container, { targetFrameRate: 23 }); expect(viewer.targetFrameRate).toBe(23); }); it("does not create a globe if option is false", function() { viewer = createViewer_default(container, { globe: false }); expect(viewer.scene.globe).not.toBeDefined(); }); it("does not create a skyBox if option is false", function() { viewer = createViewer_default(container, { skyBox: false }); expect(viewer.scene.skyBox).not.toBeDefined(); }); it("does not create a skyAtmosphere if option is false", function() { viewer = createViewer_default(container, { skyAtmosphere: false }); expect(viewer.scene.skyAtmosphere).not.toBeDefined(); }); it("can set dataSources at construction", function() { const collection = new import_engine54.DataSourceCollection(); viewer = createViewer_default(container, { dataSources: collection }); expect(viewer.dataSources).toBe(collection); }); it("default DataSourceCollection is destroyed when Viewer is destroyed", function() { viewer = createViewer_default(container); const dataSources = viewer.dataSources; viewer.destroy(); expect(dataSources.isDestroyed()).toBe(true); }); it("specified DataSourceCollection is not destroyed when Viewer is destroyed", function() { const collection = new import_engine54.DataSourceCollection(); viewer = createViewer_default(container, { dataSources: collection }); viewer.destroy(); expect(collection.isDestroyed()).toBe(false); }); it("throws if targetFrameRate less than 0", function() { viewer = createViewer_default(container); expect(function() { viewer.targetFrameRate = -1; }).toThrowDeveloperError(); }); it("can set resolutionScale", function() { viewer = createViewer_default(container); viewer.resolutionScale = 0.5; expect(viewer.resolutionScale).toBe(0.5); }); it("throws if resolutionScale is less than 0", function() { viewer = createViewer_default(container); expect(function() { viewer.resolutionScale = -1; }).toThrowDeveloperError(); }); it("can enable useBrowserRecommendedResolution", function() { viewer = createViewer_default(container, { useBrowserRecommendedResolution: true }); expect(viewer.useBrowserRecommendedResolution).toBe(true); }); it("useBrowserRecommendedResolution ignores devicePixelRatio", function() { const oldDevicePixelRatio = window.devicePixelRatio; window.devicePixelRatio = 2; viewer = createViewer_default(container, { useDefaultRenderLoop: false }); viewer.resolutionScale = 0.5; viewer.useBrowserRecommendedResolution = true; viewer.resize(); expect(viewer.scene.pixelRatio).toEqual(0.5); viewer.useBrowserRecommendedResolution = false; viewer.resize(); expect(viewer.scene.pixelRatio).toEqual(1); window.devicePixelRatio = oldDevicePixelRatio; }); it("constructor throws with undefined container", function() { expect(function() { return createViewer_default(void 0); }).toThrowDeveloperError(); }); it("constructor throws with non-existant string container", function() { expect(function() { return createViewer_default("doesNotExist"); }).toThrowDeveloperError(); }); it("constructor throws if using selectedImageryProviderViewModel with BaseLayerPicker disabled", function() { expect(function() { return createViewer_default(container, { baseLayerPicker: false, selectedImageryProviderViewModel: testProviderViewModel }); }).toThrowDeveloperError(); }); it("extend throws with undefined mixin", function() { viewer = createViewer_default(container); expect(function() { return viewer.extend(void 0); }).toThrowDeveloperError(); }); it("stops the render loop when render throws", function() { viewer = createViewer_default(container); expect(viewer.useDefaultRenderLoop).toEqual(true); const error = "foo"; viewer.scene.primitives.update = function() { throw error; }; return pollToPromise_default(function() { return !viewer.useDefaultRenderLoop; }, "render loop to be disabled."); }); it("sets the clock and timeline based on the first data source", function() { const dataSource = new MockDataSource_default(); dataSource.clock = new import_engine54.DataSourceClock(); dataSource.clock.startTime = import_engine54.JulianDate.fromIso8601("2013-08-01T18:00Z"); dataSource.clock.stopTime = import_engine54.JulianDate.fromIso8601("2013-08-21T02:00Z"); dataSource.clock.currentTime = import_engine54.JulianDate.fromIso8601( "2013-08-02T00:00Z" ); dataSource.clock.clockRange = import_engine54.ClockRange.CLAMPED; dataSource.clock.clockStep = import_engine54.ClockStep.TICK_DEPENDENT; dataSource.clock.multiplier = 20; viewer = createViewer_default(container); return viewer.dataSources.add(dataSource).then(function() { expect(viewer.clock.startTime).toEqual(dataSource.clock.startTime); expect(viewer.clock.stopTime).toEqual(dataSource.clock.stopTime); expect(viewer.clock.currentTime).toEqual(dataSource.clock.currentTime); expect(viewer.clock.clockRange).toEqual(dataSource.clock.clockRange); expect(viewer.clock.clockStep).toEqual(dataSource.clock.clockStep); expect(viewer.clock.multiplier).toEqual(dataSource.clock.multiplier); }); }); it("sets the clock for multiple data sources", function() { const dataSource1 = new MockDataSource_default(); dataSource1.clock = new import_engine54.DataSourceClock(); dataSource1.clock.startTime = import_engine54.JulianDate.fromIso8601("2013-08-01T18:00Z"); dataSource1.clock.stopTime = import_engine54.JulianDate.fromIso8601("2013-08-21T02:00Z"); dataSource1.clock.currentTime = import_engine54.JulianDate.fromIso8601( "2013-08-02T00:00Z" ); let dataSource2, dataSource3; viewer = createViewer_default(container); return viewer.dataSources.add(dataSource1).then(function() { expect(viewer.clockTrackedDataSource).toBe(dataSource1); expect(viewer.clock.startTime).toEqual(dataSource1.clock.startTime); dataSource2 = new MockDataSource_default(); dataSource2.clock = new import_engine54.DataSourceClock(); dataSource2.clock.startTime = import_engine54.JulianDate.fromIso8601( "2014-08-01T18:00Z" ); dataSource2.clock.stopTime = import_engine54.JulianDate.fromIso8601( "2014-08-21T02:00Z" ); dataSource2.clock.currentTime = import_engine54.JulianDate.fromIso8601( "2014-08-02T00:00Z" ); viewer.dataSources.add(dataSource2); }).then(function() { expect(viewer.clockTrackedDataSource).toBe(dataSource2); expect(viewer.clock.startTime).toEqual(dataSource2.clock.startTime); dataSource3 = new MockDataSource_default(); dataSource3.clock = new import_engine54.DataSourceClock(); dataSource3.clock.startTime = import_engine54.JulianDate.fromIso8601( "2015-08-01T18:00Z" ); dataSource3.clock.stopTime = import_engine54.JulianDate.fromIso8601( "2015-08-21T02:00Z" ); dataSource3.clock.currentTime = import_engine54.JulianDate.fromIso8601( "2015-08-02T00:00Z" ); viewer.dataSources.add(dataSource3); }).then(function() { expect(viewer.clockTrackedDataSource).toBe(dataSource3); expect(viewer.clock.startTime).toEqual(dataSource3.clock.startTime); viewer.dataSources.remove(dataSource3); expect(viewer.clockTrackedDataSource).toBe(dataSource2); expect(viewer.clock.startTime).toEqual(dataSource2.clock.startTime); viewer.dataSources.remove(dataSource1); expect(viewer.clockTrackedDataSource).toBe(dataSource2); expect(viewer.clock.startTime).toEqual(dataSource2.clock.startTime); }); }); it("updates the clock when the data source changes", function() { const dataSource = new MockDataSource_default(); dataSource.clock = new import_engine54.DataSourceClock(); dataSource.clock.startTime = import_engine54.JulianDate.fromIso8601("2013-08-01T18:00Z"); dataSource.clock.stopTime = import_engine54.JulianDate.fromIso8601("2013-08-21T02:00Z"); dataSource.clock.currentTime = import_engine54.JulianDate.fromIso8601( "2013-08-02T00:00Z" ); dataSource.clock.clockRange = import_engine54.ClockRange.CLAMPED; dataSource.clock.clockStep = import_engine54.ClockStep.TICK_DEPENDENT; dataSource.clock.multiplier = 20; viewer = createViewer_default(container); return viewer.dataSources.add(dataSource).then(function() { dataSource.clock.startTime = import_engine54.JulianDate.fromIso8601( "2014-08-01T18:00Z" ); dataSource.clock.stopTime = import_engine54.JulianDate.fromIso8601("2014-08-21T02:00Z"); dataSource.clock.currentTime = import_engine54.JulianDate.fromIso8601( "2014-08-02T00:00Z" ); dataSource.clock.clockRange = import_engine54.ClockRange.UNBOUNDED; dataSource.clock.clockStep = import_engine54.ClockStep.SYSTEM_CLOCK_MULTIPLIER; dataSource.clock.multiplier = 10; dataSource.changedEvent.raiseEvent(dataSource); expect(viewer.clock.startTime).toEqual(dataSource.clock.startTime); expect(viewer.clock.stopTime).toEqual(dataSource.clock.stopTime); expect(viewer.clock.currentTime).toEqual(dataSource.clock.currentTime); expect(viewer.clock.clockRange).toEqual(dataSource.clock.clockRange); expect(viewer.clock.clockStep).toEqual(dataSource.clock.clockStep); expect(viewer.clock.multiplier).toEqual(dataSource.clock.multiplier); dataSource.clock.clockStep = import_engine54.ClockStep.SYSTEM_CLOCK; dataSource.clock.multiplier = 1; dataSource.changedEvent.raiseEvent(dataSource); expect(viewer.clock.clockStep).toEqual(dataSource.clock.clockStep); }); }); it("can manually control the clock tracking", function() { const dataSource1 = new MockDataSource_default(); dataSource1.clock = new import_engine54.DataSourceClock(); dataSource1.clock.startTime = import_engine54.JulianDate.fromIso8601("2013-08-01T18:00Z"); dataSource1.clock.stopTime = import_engine54.JulianDate.fromIso8601("2013-08-21T02:00Z"); dataSource1.clock.currentTime = import_engine54.JulianDate.fromIso8601( "2013-08-02T00:00Z" ); viewer = createViewer_default(container, { automaticallyTrackDataSourceClocks: false }); let dataSource2; return viewer.dataSources.add(dataSource1).then(function() { expect(viewer.clockTrackedDataSource).not.toBeDefined(); expect(viewer.clock.startTime).not.toEqual( dataSource1.clock.startTime ); viewer.clockTrackedDataSource = dataSource1; expect(viewer.clockTrackedDataSource).toBe(dataSource1); expect(viewer.clock.startTime).toEqual(dataSource1.clock.startTime); dataSource2 = new MockDataSource_default(); dataSource2.clock = new import_engine54.DataSourceClock(); dataSource2.clock.startTime = import_engine54.JulianDate.fromIso8601( "2014-08-01T18:00Z" ); dataSource2.clock.stopTime = import_engine54.JulianDate.fromIso8601( "2014-08-21T02:00Z" ); dataSource2.clock.currentTime = import_engine54.JulianDate.fromIso8601( "2014-08-02T00:00Z" ); viewer.dataSources.add(dataSource2); }).then(function() { expect(viewer.clockTrackedDataSource).toBe(dataSource1); expect(viewer.clock.startTime).toEqual(dataSource1.clock.startTime); viewer.dataSources.remove(dataSource1); expect(viewer.clockTrackedDataSource).not.toBeDefined(); }); }); it("shows the error panel when render throws", function() { viewer = createViewer_default(container); const error = "foo"; viewer.scene.primitives.update = function() { throw error; }; return pollToPromise_default(function() { return !viewer.useDefaultRenderLoop; }).catch(function() { expect( viewer._element.querySelector(".cesium-widget-errorPanel") ).not.toBeNull(); const messages = viewer._element.querySelectorAll( ".cesium-widget-errorPanel-message" ); let found = false; for (let i = 0; i < messages.length; ++i) { if (messages[i].textContent.indexOf(error) !== -1) { found = true; } } expect(found).toBe(true); DomEventSimulator_default.fireClick( viewer._element.querySelector(".cesium-button") ); expect( viewer._element.querySelector(".cesium-widget-errorPanel") ).toBeNull(); }); }); it("does not show the error panel if disabled", function() { viewer = createViewer_default(container, { showRenderLoopErrors: false }); const error = "foo"; viewer.scene.primitives.update = function() { throw error; }; return pollToPromise_default(function() { return !viewer.useDefaultRenderLoop; }).catch(function() { expect( viewer._element.querySelector(".cesium-widget-errorPanel") ).toBeNull(); }); }); it("can enable requestRender mode", function() { viewer = createViewer_default(container, { requestRenderMode: true }); expect(viewer.scene.requestRenderMode).toBe(true); }); it("can set maximumRenderTimeChange", function() { viewer = createViewer_default(container, { maximumRenderTimeChange: Number.POSITIVE_INFINITY }); expect(viewer.scene.maximumRenderTimeChange).toBe( Number.POSITIVE_INFINITY ); }); it("can set depthPlaneEllipsoidOffset", function() { viewer = createViewer_default(container, { depthPlaneEllipsoidOffset: Number.POSITIVE_INFINITY }); expect(viewer.scene._depthPlane._ellipsoidOffset).toBe( Number.POSITIVE_INFINITY ); }); it("can get and set trackedEntity", function() { viewer = createViewer_default(container); const entity = new import_engine54.Entity(); entity.position = new import_engine54.ConstantProperty( new import_engine54.Cartesian3(123456, 123456, 123456) ); viewer.trackedEntity = entity; expect(viewer.trackedEntity).toBe(entity); viewer.trackedEntity = void 0; expect(viewer.trackedEntity).toBeUndefined(); }); it("can get and set selectedEntity", function() { const viewer2 = createViewer_default(container); const dataSource = new MockDataSource_default(); viewer2.dataSources.add(dataSource); const entity = new import_engine54.Entity(); entity.position = new import_engine54.ConstantPositionProperty( new import_engine54.Cartesian3(123456, 123456, 123456) ); dataSource.entities.add(entity); viewer2.selectedEntity = entity; expect(viewer2.selectedEntity).toBe(entity); viewer2.selectedEntity = void 0; expect(viewer2.selectedEntity).toBeUndefined(); viewer2.destroy(); }); it("raises an event when the selected entity changes", function() { const viewer2 = createViewer_default(container); const dataSource = new MockDataSource_default(); viewer2.dataSources.add(dataSource); const entity = new import_engine54.Entity(); entity.position = new import_engine54.ConstantPositionProperty( new import_engine54.Cartesian3(123456, 123456, 123456) ); dataSource.entities.add(entity); let myEntity; viewer2.selectedEntityChanged.addEventListener(function(newSelection) { myEntity = newSelection; }); viewer2.selectedEntity = entity; expect(myEntity).toBe(entity); viewer2.selectedEntity = void 0; expect(myEntity).toBeUndefined(); viewer2.destroy(); }); it("raises an event when the tracked entity changes", function() { const viewer2 = createViewer_default(container); const dataSource = new MockDataSource_default(); viewer2.dataSources.add(dataSource); const entity = new import_engine54.Entity(); entity.position = new import_engine54.ConstantPositionProperty( new import_engine54.Cartesian3(123456, 123456, 123456) ); dataSource.entities.add(entity); let myEntity; viewer2.trackedEntityChanged.addEventListener(function(newValue) { myEntity = newValue; }); viewer2.trackedEntity = entity; expect(myEntity).toBe(entity); viewer2.trackedEntity = void 0; expect(myEntity).toBeUndefined(); viewer2.destroy(); }); it("selectedEntity sets InfoBox properties", function() { const viewer2 = createViewer_default(container); const entity = new import_engine54.Entity(); const viewModel = viewer2.infoBox.viewModel; expect(viewModel.showInfo).toBe(false); viewer2.selectedEntity = entity; viewer2.clock.tick(); expect(viewModel.showInfo).toBe(true); expect(viewModel.titleText).toEqual(entity.id); expect(viewModel.description).toEqual(""); entity.name = "Yes, this is name."; entity.description = "tubelcane"; viewer2.clock.tick(); expect(viewModel.showInfo).toBe(true); expect(viewModel.titleText).toEqual(entity.name); expect(viewModel.description).toEqual(entity.description.getValue()); viewer2.selectedEntity = void 0; viewer2.clock.tick(); expect(viewModel.showInfo).toBe(false); expect(viewModel.titleText).toEqual(""); expect(viewModel.description).toEqual(""); viewer2.destroy(); }); it("home button resets tracked object", function() { viewer = createViewer_default(container); const entity = new import_engine54.Entity(); entity.position = new import_engine54.ConstantProperty( new import_engine54.Cartesian3(123456, 123456, 123456) ); viewer.trackedEntity = entity; expect(viewer.trackedEntity).toBe(entity); spyOn(import_engine54.CameraFlightPath, "createTween").and.returnValue({ startObject: {}, stopObject: {}, duration: 0 }); viewer.homeButton.viewModel.command(); expect(viewer.trackedEntity).toBeUndefined(); }); it("stops tracking when tracked object is removed", function() { viewer = createViewer_default(container); const entity = new import_engine54.Entity(); entity.position = new import_engine54.ConstantProperty( new import_engine54.Cartesian3(123456, 123456, 123456) ); const dataSource = new MockDataSource_default(); dataSource.entities.add(entity); viewer.dataSources.add(dataSource); viewer.trackedEntity = entity; expect(viewer.trackedEntity).toBe(entity); return pollToPromise_default(function() { viewer.render(); return import_engine54.Cartesian3.equals( import_engine54.Matrix4.getTranslation( viewer.scene.camera.transform, new import_engine54.Cartesian3() ), entity.position.getValue() ); }).then(function() { dataSource.entities.remove(entity); expect(viewer.trackedEntity).toBeUndefined(); expect(viewer.scene.camera.transform).toEqual(import_engine54.Matrix4.IDENTITY); dataSource.entities.add(entity); viewer.trackedEntity = entity; expect(viewer.trackedEntity).toBe(entity); return pollToPromise_default(function() { viewer.render(); viewer.render(); return import_engine54.Cartesian3.equals( import_engine54.Matrix4.getTranslation( viewer.scene.camera.transform, new import_engine54.Cartesian3() ), entity.position.getValue() ); }).then(function() { viewer.dataSources.remove(dataSource); expect(viewer.trackedEntity).toBeUndefined(); expect(viewer.scene.camera.transform).toEqual(import_engine54.Matrix4.IDENTITY); }); }); }); it("does not crash when tracking an object with a position property whose value is undefined.", function() { viewer = createViewer_default(container); const entity = new import_engine54.Entity(); entity.position = new import_engine54.ConstantProperty(void 0); entity.polyline = { positions: [ import_engine54.Cartesian3.fromDegrees(0, 0, 0), import_engine54.Cartesian3.fromDegrees(0, 0, 1) ] }; viewer.entities.add(entity); viewer.trackedEntity = entity; spyOn(viewer.scene.renderError, "raiseEvent"); return pollToPromise_default(function() { viewer.render(); return viewer.dataSourceDisplay.update(viewer.clock.currentTime); }).then(function() { expect(viewer.scene.renderError.raiseEvent).not.toHaveBeenCalled(); }); }); it("zoomTo throws if target is not defined", function() { viewer = createViewer_default(container); expect(function() { viewer.zoomTo(); }).toThrowDeveloperError(); }); it("zoomTo zooms to Cesium3DTileset with default offset when offset not defined", async function() { viewer = createViewer_default(container); const path = "./Data/Cesium3DTiles/Tilesets/TilesetOfTilesets/tileset.json"; const tileset = await import_engine54.Cesium3DTileset.fromUrl(path); const expectedBoundingSphere = tileset.boundingSphere; const expectedOffset = new import_engine54.HeadingPitchRange( 0, -0.5, expectedBoundingSphere.radius ); let wasCompleted = false; spyOn(viewer.camera, "viewBoundingSphere").and.callFake(function(boundingSphere, offset) { expect(boundingSphere).toEqual(expectedBoundingSphere); expect(offset).toEqual(expectedOffset); wasCompleted = true; }); const promise = viewer.zoomTo(tileset); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); it("zoomTo zooms to Cesium3DTileset with offset", async function() { viewer = createViewer_default(container); const path = "./Data/Cesium3DTiles/Tilesets/TilesetOfTilesets/tileset.json"; const tileset = await import_engine54.Cesium3DTileset.fromUrl(path); const expectedBoundingSphere = tileset.boundingSphere; const expectedOffset = new import_engine54.HeadingPitchRange( 0.4, 1.2, 4 * expectedBoundingSphere.radius ); const promise = viewer.zoomTo(tileset, expectedOffset); let wasCompleted = false; spyOn(viewer.camera, "viewBoundingSphere").and.callFake(function(boundingSphere, offset) { expect(boundingSphere).toEqual(expectedBoundingSphere); expect(offset).toEqual(expectedOffset); wasCompleted = true; }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); async function loadTimeDynamicPointCloud(viewer2) { const scene2 = viewer2.scene; const clock = viewer2.clock; const uri = "./Data/Cesium3DTiles/PointCloud/PointCloudTimeDynamic/0.pnts"; const dates = ["2018-07-19T15:18:00Z", "2018-07-19T15:18:00.5Z"]; function dataCallback() { return { uri }; } const timeIntervalCollection = import_engine54.TimeIntervalCollection.fromIso8601DateArray( { iso8601Dates: dates, dataCallback } ); const pointCloud = new import_engine54.TimeDynamicPointCloud({ intervals: timeIntervalCollection, clock }); const start = import_engine54.JulianDate.fromIso8601(dates[0]); clock.startTime = start; clock.currentTime = start; clock.multiplier = 0; scene2.primitives.add(pointCloud); await pollToPromise_default(function() { scene2.render(); return (0, import_engine54.defined)(pointCloud.boundingSphere); }); return pointCloud; } it("zoomTo zooms to TimeDynamicPointCloud with default offset when offset not defined", function() { viewer = createViewer_default(container); return loadTimeDynamicPointCloud(viewer).then(function(pointCloud) { const expectedBoundingSphere = pointCloud.boundingSphere; const expectedOffset = new import_engine54.HeadingPitchRange( 0, -0.5, expectedBoundingSphere.radius ); const promise = viewer.zoomTo(pointCloud); let wasCompleted = false; spyOn(viewer.camera, "viewBoundingSphere").and.callFake(function(boundingSphere, offset) { expect(boundingSphere).toEqual(expectedBoundingSphere); expect(offset).toEqual(expectedOffset); wasCompleted = true; }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); viewer.scene.primitives.remove(pointCloud); }); }); }); it("zoomTo zooms to TimeDynamicPointCloud with offset", function() { viewer = createViewer_default(container); return loadTimeDynamicPointCloud(viewer).then(function(pointCloud) { const expectedBoundingSphere = pointCloud.boundingSphere; const expectedOffset = new import_engine54.HeadingPitchRange( 0.4, 1.2, 4 * expectedBoundingSphere.radius ); const promise = viewer.zoomTo(pointCloud, expectedOffset); let wasCompleted = false; spyOn(viewer.camera, "viewBoundingSphere").and.callFake(function(boundingSphere, offset) { expect(boundingSphere).toEqual(expectedBoundingSphere); expect(offset).toEqual(expectedOffset); wasCompleted = true; }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); viewer.scene.primitives.remove(pointCloud); }); }); }); async function loadVoxelPrimitive(viewer2) { const voxelPrimitive = new import_engine54.VoxelPrimitive({ provider: await import_engine54.Cesium3DTilesVoxelProvider.fromUrl( "./Data/Cesium3DTiles/Voxel/VoxelEllipsoid3DTiles/tileset.json" ) }); viewer2.scene.primitives.add(voxelPrimitive); return voxelPrimitive; } it("zoomTo zooms to VoxelPrimitive with default offset when offset not defined", function() { viewer = createViewer_default(container); return loadVoxelPrimitive(viewer).then(function(voxelPrimitive) { const expectedBoundingSphere = voxelPrimitive.boundingSphere; const expectedOffset = new import_engine54.HeadingPitchRange( 0, -0.5, expectedBoundingSphere.radius ); const promise = viewer.zoomTo(voxelPrimitive); let wasCompleted = false; spyOn(viewer.camera, "viewBoundingSphere").and.callFake(function(boundingSphere, offset) { expect(boundingSphere).toEqual(expectedBoundingSphere); expect(offset).toEqual(expectedOffset); wasCompleted = true; }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); }); it("zoomTo zooms to VoxelPrimitive with offset", function() { viewer = createViewer_default(container); return loadVoxelPrimitive(viewer).then(function(voxelPrimitive) { const expectedBoundingSphere = voxelPrimitive.boundingSphere; const expectedOffset = new import_engine54.HeadingPitchRange( 0.4, 1.2, 4 * expectedBoundingSphere.radius ); const promise = viewer.zoomTo(voxelPrimitive, expectedOffset); let wasCompleted = false; spyOn(viewer.camera, "viewBoundingSphere").and.callFake(function(boundingSphere, offset) { expect(boundingSphere).toEqual(expectedBoundingSphere); expect(offset).toEqual(expectedOffset); wasCompleted = true; }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); }); it("zoomTo zooms to entity with undefined offset when offset not defined", function() { viewer = createViewer_default(container); viewer.entities.add({ name: "Blue box", position: import_engine54.Cartesian3.fromDegrees(-114, 40, 3e5), box: { dimensions: new import_engine54.Cartesian3(4e5, 3e5, 5e5), material: import_engine54.Color.BLUE } }); const entities = viewer.entities; const promise = viewer.zoomTo(entities); let wasCompleted = false; spyOn(viewer._dataSourceDisplay, "getBoundingSphere").and.callFake( function() { return new import_engine54.BoundingSphere(); } ); spyOn(viewer.camera, "viewBoundingSphere").and.callFake(function(boundingSphere, offset) { expect(boundingSphere).toBeDefined(); expect(offset).toBeUndefined(); wasCompleted = true; }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); it("zoomTo zooms to entity with offset", function() { viewer = createViewer_default(container); viewer.entities.add({ name: "Blue box", position: import_engine54.Cartesian3.fromDegrees(-114, 40, 3e5), box: { dimensions: new import_engine54.Cartesian3(4e5, 3e5, 5e5), material: import_engine54.Color.BLUE } }); const entities = viewer.entities; const expectedOffset = new import_engine54.HeadingPitchRange(3, 0.2, 2.3); const promise = viewer.zoomTo(entities, expectedOffset); let wasCompleted = false; spyOn(viewer._dataSourceDisplay, "getBoundingSphere").and.callFake( function() { return new import_engine54.BoundingSphere(); } ); spyOn(viewer.camera, "viewBoundingSphere").and.callFake(function(boundingSphere, offset) { expect(expectedOffset).toEqual(offset); wasCompleted = true; }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); it("zoomTo zooms to entity when globe is disabled", async function() { const viewer2 = createViewer_default(container, { globe: false, infoBox: false, selectionIndicator: false, shadows: true, shouldAnimate: true }); const position = import_engine54.Cartesian3.fromDegrees(-123.0744619, 44.0503706, 1e3); const entity = viewer2.entities.add({ position, model: { uri: "../SampleData/models/CesiumAir/Cesium_Air.glb" } }); await viewer2.zoomTo(entity); expect(viewer2.scene).toBeDefined(); expect(viewer2.scene.errorEvent).toBeUndefined(); }); it("flyTo throws if target is not defined", function() { viewer = createViewer_default(container); expect(function() { viewer.flyTo(); }).toThrowDeveloperError(); }); it("flyTo flies to Cesium3DTileset with default offset when options not defined", async function() { viewer = createViewer_default(container); const path = "./Data/Cesium3DTiles/Tilesets/TilesetOfTilesets/tileset.json"; const tileset = await import_engine54.Cesium3DTileset.fromUrl(path); const promise = viewer.flyTo(tileset); let wasCompleted = false; spyOn(viewer.camera, "flyToBoundingSphere").and.callFake(function(target, options) { expect(options.offset).toBeDefined(); expect(options.duration).toBeUndefined(); expect(options.maximumHeight).toBeUndefined(); wasCompleted = true; options.complete(); }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); it("flyTo flies to Cesium3DTileset with default offset when offset not defined", async function() { viewer = createViewer_default(container); const path = "./Data/Cesium3DTiles/Tilesets/TilesetOfTilesets/tileset.json"; const tileset = await import_engine54.Cesium3DTileset.fromUrl(path); const options = {}; const promise = viewer.flyTo(tileset, options); let wasCompleted = false; spyOn(viewer.camera, "flyToBoundingSphere").and.callFake(function(target, options2) { expect(options2.offset).toBeDefined(); expect(options2.duration).toBeUndefined(); expect(options2.maximumHeight).toBeUndefined(); wasCompleted = true; options2.complete(); }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); it("flyTo flies to Cesium3DTileset when options are defined", async function() { viewer = createViewer_default(container); const path = "./Data/Cesium3DTiles/Tilesets/TilesetOfTilesets/tileset.json"; const tileset = await import_engine54.Cesium3DTileset.fromUrl(path); const offsetVal = new import_engine54.HeadingPitchRange(3, 0.2, 2.3); const options = { offset: offsetVal, duration: 3, maximumHeight: 5 }; const promise = viewer.flyTo(tileset, options); let wasCompleted = false; spyOn(viewer.camera, "flyToBoundingSphere").and.callFake(function(target, options2) { expect(options2.duration).toBeDefined(); expect(options2.maximumHeight).toBeDefined(); wasCompleted = true; options2.complete(); }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); it("flyTo flies to TimeDynamicPointCloud with default offset when options not defined", function() { viewer = createViewer_default(container); return loadTimeDynamicPointCloud(viewer).then(function(pointCloud) { const promise = viewer.flyTo(pointCloud); let wasCompleted = false; spyOn(viewer.camera, "flyToBoundingSphere").and.callFake(function(target, options) { expect(options.offset).toBeDefined(); expect(options.duration).toBeUndefined(); expect(options.maximumHeight).toBeUndefined(); wasCompleted = true; options.complete(); }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); viewer.scene.primitives.remove(pointCloud); }); }); }); it("flyTo flies to TimeDynamicPointCloud with default offset when offset not defined", function() { viewer = createViewer_default(container); return loadTimeDynamicPointCloud(viewer).then(function(pointCloud) { const options = {}; const promise = viewer.flyTo(pointCloud, options); let wasCompleted = false; spyOn(viewer.camera, "flyToBoundingSphere").and.callFake(function(target, options2) { expect(options2.offset).toBeDefined(); expect(options2.duration).toBeUndefined(); expect(options2.maximumHeight).toBeUndefined(); wasCompleted = true; options2.complete(); }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); viewer.scene.primitives.remove(pointCloud); }); }); }); it("flyTo flies to TimeDynamicPointCloud when options are defined", function() { viewer = createViewer_default(container); return loadTimeDynamicPointCloud(viewer).then(function(pointCloud) { const offsetVal = new import_engine54.HeadingPitchRange(3, 0.2, 2.3); const options = { offset: offsetVal, duration: 3, maximumHeight: 5 }; const promise = viewer.flyTo(pointCloud, options); let wasCompleted = false; spyOn(viewer.camera, "flyToBoundingSphere").and.callFake(function(target, options2) { expect(options2.duration).toBeDefined(); expect(options2.maximumHeight).toBeDefined(); wasCompleted = true; options2.complete(); }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); viewer.scene.primitives.remove(pointCloud); }); }); }); it("flyTo flies to VoxelPrimitive with default offset when options not defined", function() { viewer = createViewer_default(container); return loadVoxelPrimitive(viewer).then(function(voxelPrimitive) { const promise = viewer.flyTo(voxelPrimitive); let wasCompleted = false; spyOn(viewer.camera, "flyToBoundingSphere").and.callFake(function(target, options) { expect(options.offset).toBeDefined(); expect(options.duration).toBeUndefined(); expect(options.maximumHeight).toBeUndefined(); wasCompleted = true; options.complete(); }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); }); it("flyTo flies to VoxelPrimitive with default offset when offset not defined", function() { viewer = createViewer_default(container); const options = {}; return loadVoxelPrimitive(viewer).then(function(voxelPrimitive) { const promise = viewer.flyTo(voxelPrimitive, options); let wasCompleted = false; spyOn(viewer.camera, "flyToBoundingSphere").and.callFake(function(target, options2) { expect(options2.offset).toBeDefined(); expect(options2.duration).toBeUndefined(); expect(options2.maximumHeight).toBeUndefined(); wasCompleted = true; options2.complete(); }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); }); it("flyTo flies to VoxelPrimitive when options are defined", function() { viewer = createViewer_default(container); return loadVoxelPrimitive(viewer).then(function(voxelPrimitive) { const offsetVal = new import_engine54.HeadingPitchRange(3, 0.2, 2.3); const options = { offset: offsetVal, duration: 3, maximumHeight: 5 }; const promise = viewer.flyTo(voxelPrimitive, options); let wasCompleted = false; spyOn(viewer.camera, "flyToBoundingSphere").and.callFake(function(target, options2) { expect(options2.duration).toBeDefined(); expect(options2.maximumHeight).toBeDefined(); wasCompleted = true; options2.complete(); }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); }); it("flyTo flies to entity with default offset when options not defined", function() { viewer = createViewer_default(container); viewer.entities.add({ name: "Blue box", position: import_engine54.Cartesian3.fromDegrees(-114, 40, 3e5), box: { dimensions: new import_engine54.Cartesian3(4e5, 3e5, 5e5), material: import_engine54.Color.BLUE } }); const entities = viewer.entities; const promise = viewer.flyTo(entities); let wasCompleted = false; spyOn(viewer._dataSourceDisplay, "getBoundingSphere").and.callFake( function() { return new import_engine54.BoundingSphere(); } ); spyOn(viewer.camera, "flyToBoundingSphere").and.callFake(function(target, options) { expect(options.duration).toBeUndefined(); expect(options.maximumHeight).toBeUndefined(); wasCompleted = true; options.complete(); }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); it("flyTo flies to imagery layer with default offset when options are not defined", async function() { viewer = createViewer_default(container); const imageryLayer = new import_engine54.ImageryLayer(testProvider); const promise = viewer.flyTo(imageryLayer, { duration: 0 }); viewer._postRender(); await expectAsync(promise).toBeResolved(); }); it("flyTo flies to VoxelPrimitive with default offset when options not defined", function() { viewer = createViewer_default(container); return loadVoxelPrimitive(viewer).then(function(voxelPrimitive) { const promise = viewer.flyTo(voxelPrimitive); let wasCompleted = false; spyOn(viewer.camera, "flyToBoundingSphere").and.callFake(function(target, options) { expect(options.offset).toBeDefined(); expect(options.duration).toBeUndefined(); expect(options.maximumHeight).toBeUndefined(); wasCompleted = true; options.complete(); }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); }); it("flyTo flies to VoxelPrimitive with default offset when offset not defined", function() { viewer = createViewer_default(container); const options = {}; return loadVoxelPrimitive(viewer).then(function(voxelPrimitive) { const promise = viewer.flyTo(voxelPrimitive, options); let wasCompleted = false; spyOn(viewer.camera, "flyToBoundingSphere").and.callFake(function(target, options2) { expect(options2.offset).toBeDefined(); expect(options2.duration).toBeUndefined(); expect(options2.maximumHeight).toBeUndefined(); wasCompleted = true; options2.complete(); }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); }); it("flyTo flies to VoxelPrimitive when options are defined", function() { viewer = createViewer_default(container); return loadVoxelPrimitive(viewer).then(function(voxelPrimitive) { const offsetVal = new import_engine54.HeadingPitchRange(3, 0.2, 2.3); const options = { offset: offsetVal, duration: 3, maximumHeight: 5 }; const promise = viewer.flyTo(voxelPrimitive, options); let wasCompleted = false; spyOn(viewer.camera, "flyToBoundingSphere").and.callFake(function(target, options2) { expect(options2.duration).toBeDefined(); expect(options2.maximumHeight).toBeDefined(); wasCompleted = true; options2.complete(); }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); }); it("flyTo flys to entity with default offset when offset not defined", function() { viewer = createViewer_default(container); viewer.entities.add({ name: "Blue box", position: import_engine54.Cartesian3.fromDegrees(-114, 40, 3e5), box: { dimensions: new import_engine54.Cartesian3(4e5, 3e5, 5e5), material: import_engine54.Color.BLUE } }); const entities = viewer.entities; const options = {}; const promise = viewer.flyTo(entities, options); let wasCompleted = false; spyOn(viewer._dataSourceDisplay, "getBoundingSphere").and.callFake( function() { return new import_engine54.BoundingSphere(); } ); spyOn(viewer.camera, "flyToBoundingSphere").and.callFake(function(target, options2) { expect(options2.duration).toBeUndefined(); expect(options2.maximumHeight).toBeUndefined(); wasCompleted = true; options2.complete(); }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); it("flyTo flies to entity when options are defined", function() { viewer = createViewer_default(container); viewer.entities.add({ name: "Blue box", position: import_engine54.Cartesian3.fromDegrees(-114, 40, 3e5), box: { dimensions: new import_engine54.Cartesian3(4e5, 3e5, 5e5), material: import_engine54.Color.BLUE } }); const entities = viewer.entities; const offsetVal = new import_engine54.HeadingPitchRange(3, 0.2, 2.3); const options = { offset: offsetVal, duration: 3, maximumHeight: 5 }; const promise = viewer.flyTo(entities, options); let wasCompleted = false; spyOn(viewer._dataSourceDisplay, "getBoundingSphere").and.callFake( function() { return new import_engine54.BoundingSphere(); } ); spyOn(viewer.camera, "flyToBoundingSphere").and.callFake(function(target, options2) { expect(options2.duration).toBeDefined(); expect(options2.maximumHeight).toBeDefined(); wasCompleted = true; options2.complete(); }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); it("flyTo flies to entity when offset is defined but other options for flyTo are not", function() { viewer = createViewer_default(container); viewer.entities.add({ name: "Blue box", position: import_engine54.Cartesian3.fromDegrees(-114, 40, 3e5), box: { dimensions: new import_engine54.Cartesian3(4e5, 3e5, 5e5), material: import_engine54.Color.BLUE } }); const entities = viewer.entities; const offsetVal = new import_engine54.HeadingPitchRange(3, 0.2, 2.3); const options = { offset: offsetVal }; const promise = viewer.flyTo(entities, options); let wasCompleted = false; spyOn(viewer._dataSourceDisplay, "getBoundingSphere").and.callFake( function() { return new import_engine54.BoundingSphere(); } ); spyOn(viewer.camera, "flyToBoundingSphere").and.callFake(function(target, options2) { expect(options2.duration).toBeUndefined(); expect(options2.maximumHeight).toBeUndefined(); wasCompleted = true; options2.complete(); }); viewer._postRender(); return promise.then(function() { expect(wasCompleted).toEqual(true); }); }); it("removes data source listeners when destroyed", function() { viewer = createViewer_default(container); const preMixinDataSource = new MockDataSource_default(); const postMixinDataSource = new MockDataSource_default(); return viewer.dataSources.add(preMixinDataSource).then(function() { viewer.dataSources.add(postMixinDataSource); }).then(function() { const preMixinListenerCount = preMixinDataSource.entities.collectionChanged._listeners.length; const postMixinListenerCount = postMixinDataSource.entities.collectionChanged._listeners.length; viewer = viewer.destroy(); expect( preMixinDataSource.entities.collectionChanged._listeners.length ).not.toEqual(preMixinListenerCount); expect( postMixinDataSource.entities.collectionChanged._listeners.length ).not.toEqual(postMixinListenerCount); }); }); }, "WebGL" ); // packages/widgets/Specs/Viewer/viewerDragDropMixinSpec.js var import_engine55 = __toESM(require_Cesium(), 1); var import__787 = __toESM(require_Cesium(), 1); describe( "Widgets/Viewer/viewerDragDropMixin", function() { let container; let viewer; beforeEach(function() { container = document.createElement("div"); container.id = "container"; container.style.display = "none"; document.body.appendChild(container); const fakeFileReader = jasmine.createSpyObj("FileReader", ["readAsText"]); fakeFileReader.readAsText = function(file) { if ((0, import_engine55.defined)(file.czmlString)) { this.onload({ target: { result: file.czmlString } }); } else { this.onerror({ target: { error: file.errorMessage } }); } }; spyOn(window, "FileReader").and.returnValue(fakeFileReader); }); afterEach(function() { if (viewer && !viewer.isDestroyed()) { viewer = viewer.destroy(); } document.body.removeChild(container); }); it("mixin sets default values", function() { viewer = createViewer_default(container); viewer.extend(import__787.viewerDragDropMixin); expect(viewer.dropTarget).toBe(viewer.container); expect(viewer.dropEnabled).toEqual(true); expect(viewer.clearOnDrop).toEqual(true); expect(viewer.clampToGround).toEqual(true); expect(viewer.flyToOnDrop).toEqual(true); }); it("clearOnDrop defaults to true when dataSourceBrowser is not used", function() { viewer = createViewer_default(container, { dataSourceBrowser: false }); viewer.extend(import__787.viewerDragDropMixin); expect(viewer.clearOnDrop).toEqual(true); }); it("mixin sets option values", function() { viewer = createViewer_default(container); viewer.extend(import__787.viewerDragDropMixin, { dropTarget: document.body, clearOnDrop: false, clampToGround: false, flyToOnDrop: false }); expect(viewer.dropTarget).toBe(document.body); expect(viewer.dropEnabled).toEqual(true); expect(viewer.clearOnDrop).toEqual(false); expect(viewer.clampToGround).toEqual(false); expect(viewer.flyToOnDrop).toEqual(false); }); it("mixin works with dropTarget id string", function() { viewer = createViewer_default(container); viewer.extend(import__787.viewerDragDropMixin, { dropTarget: "container" }); expect(viewer.dropTarget).toBe(container); }); const czml1 = [ { id: "document", version: "1.0", clock: { interval: "2000-01-01/2001-01-01" } }, { id: "test" } ]; const czml2 = [ { id: "document", version: "1.0", clock: { interval: "2000-01-02/2001-01-02" } }, { id: "test2" } ]; it("handleDrop processes drop event", function() { const mockEvent = { dataTransfer: { files: [ { name: "czml1.czml", czmlString: JSON.stringify(czml1) } ] }, stopPropagation: function() { }, preventDefault: function() { } }; viewer = createViewer_default(container); viewer.extend(import__787.viewerDragDropMixin); DomEventSimulator_default.fireMockEvent(viewer._handleDrop, mockEvent); return pollToPromise_default(function() { return viewer.dataSources.length === 1; }).then(function() { const dataSource = viewer.dataSources.get(0); const interval = import_engine55.TimeInterval.fromIso8601({ iso8601: czml1[0].clock.interval }); expect(dataSource.entities.getById("test")).toBeDefined(); expect(dataSource.clock.startTime).toEqual(interval.start); expect(dataSource.clock.stopTime).toEqual(interval.stop); }); }); it("handleDrop processes drop event with multiple files", function() { const mockEvent = { dataTransfer: { files: [ { name: "czml1.czml", czmlString: JSON.stringify(czml1) }, { name: "czml2.czml", czmlString: JSON.stringify(czml2) } ] }, stopPropagation: function() { }, preventDefault: function() { } }; viewer = createViewer_default(container); viewer.extend(import__787.viewerDragDropMixin); DomEventSimulator_default.fireMockEvent(viewer._handleDrop, mockEvent); return pollToPromise_default(function() { return viewer.dataSources.length === 2; }).then(function() { const source1 = viewer.dataSources.get(0); const source2 = viewer.dataSources.get(1); expect(source1.entities.getById("test")).toBeDefined(); expect(source2.entities.getById("test2")).toBeDefined(); const interval = import_engine55.TimeInterval.fromIso8601({ iso8601: czml1[0].clock.interval }); expect(source1.clock.startTime).toEqual(interval.start); expect(source1.clock.stopTime).toEqual(interval.stop); }); }); it("handleDrop obeys clearOnDrop", function() { const mockEvent = { dataTransfer: { files: [ { name: "czml1.czml", czmlString: JSON.stringify(czml1) }, { name: "czml2.czml", czmlString: JSON.stringify(czml2) } ] }, stopPropagation: function() { }, preventDefault: function() { } }; viewer = createViewer_default(container); viewer.extend(import__787.viewerDragDropMixin); DomEventSimulator_default.fireMockEvent(viewer._handleDrop, mockEvent); return pollToPromise_default(function() { return viewer.dataSources.length === 2; }).then(function() { const source1 = viewer.dataSources.get(0); const source2 = viewer.dataSources.get(1); expect(source1.entities.getById("test")).toBeDefined(); expect(source2.entities.getById("test2")).toBeDefined(); const interval = import_engine55.TimeInterval.fromIso8601({ iso8601: czml1[0].clock.interval }); expect(source1.clock.startTime).toEqual(interval.start); expect(source1.clock.stopTime).toEqual(interval.stop); viewer.clearOnDrop = false; DomEventSimulator_default.fireMockEvent(viewer._handleDrop, mockEvent); return pollToPromise_default(function() { return viewer.dataSources.length === 4; }).then(function() { const source12 = viewer.dataSources.get(0); const source22 = viewer.dataSources.get(1); const source3 = viewer.dataSources.get(2); const source4 = viewer.dataSources.get(3); expect(source12.entities.getById("test")).toBeDefined(); expect(source22.entities.getById("test2")).toBeDefined(); expect(source3.entities.getById("test")).toBeDefined(); expect(source4.entities.getById("test2")).toBeDefined(); viewer.clearOnDrop = true; DomEventSimulator_default.fireMockEvent(viewer._handleDrop, mockEvent); return pollToPromise_default(function() { return viewer.dataSources.length === 2; }).then(function() { const source13 = viewer.dataSources.get(0); const source23 = viewer.dataSources.get(1); expect(source13.entities.getById("test")).toBeDefined(); expect(source23.entities.getById("test2")).toBeDefined(); const interval2 = import_engine55.TimeInterval.fromIso8601({ iso8601: czml1[0].clock.interval }); expect(source13.clock.startTime).toEqual(interval2.start); expect(source13.clock.stopTime).toEqual(interval2.stop); }); }); }); }); it("dropError is raised on exception", function() { const mockEvent = { dataTransfer: { files: [ { name: "czml1.czml", czmlString: "bad JSON" } ] }, stopPropagation: function() { }, preventDefault: function() { } }; viewer = createViewer_default(container); viewer.extend(import__787.viewerDragDropMixin); const spyListener = jasmine.createSpy("listener"); viewer.dropError.addEventListener(spyListener); DomEventSimulator_default.fireMockEvent(viewer._handleDrop, mockEvent); return pollToPromise_default(function() { return spyListener.calls.any(); }).then(function() { expect(spyListener).toHaveBeenCalledWith( viewer, "czml1.czml", jasmine.any(SyntaxError) ); viewer.dropError.removeEventListener(spyListener); }); }); it("dropError is raised FileReader error", function() { const mockEvent = { dataTransfer: { files: [ { name: "czml1.czml", errorMessage: "bad JSON" } ] }, stopPropagation: function() { }, preventDefault: function() { } }; viewer = createViewer_default(container); viewer.extend(import__787.viewerDragDropMixin); const spyListener = jasmine.createSpy("listener"); viewer.dropError.addEventListener(spyListener); DomEventSimulator_default.fireMockEvent(viewer._handleDrop, mockEvent); return pollToPromise_default(function() { return spyListener.calls.any(); }).then(function() { expect(spyListener).toHaveBeenCalledWith( viewer, mockEvent.dataTransfer.files[0].name, mockEvent.dataTransfer.files[0].errorMessage ); viewer.dropError.removeEventListener(spyListener); }); }); function MockContainer() { const events = {}; this.events = events; this.addEventListener = function(name, func, bubble) { events[name] = { func, bubble }; }; this.removeEventListener = function(name, func, bubble) { const subscribed = events[name]; expect(subscribed.func).toBe(func); expect(subscribed.bubble).toEqual(bubble); delete events[name]; }; } it("enable/disable subscribes to provided dropTarget.", function() { const dropTarget = new MockContainer(); viewer = createViewer_default(container); viewer.extend(import__787.viewerDragDropMixin, { dropTarget }); expect(dropTarget.events.drop).toBeDefined(); expect(dropTarget.events.dragenter).toBeDefined(); expect(dropTarget.events.dragover).toBeDefined(); expect(dropTarget.events.dragexit).toBeDefined(); viewer.dropEnabled = false; expect(dropTarget.events.drop).toBeUndefined(); expect(dropTarget.events.dragenter).toBeUndefined(); expect(dropTarget.events.dragover).toBeUndefined(); expect(dropTarget.events.dragexit).toBeUndefined(); viewer.dropEnabled = true; expect(dropTarget.events.drop).toBeDefined(); expect(dropTarget.events.dragenter).toBeDefined(); expect(dropTarget.events.dragover).toBeDefined(); expect(dropTarget.events.dragexit).toBeDefined(); }); it("can set new dropTarget.", function() { const dropTarget1 = new MockContainer(); const dropTarget2 = new MockContainer(); viewer = createViewer_default(container); viewer.extend(import__787.viewerDragDropMixin, { dropTarget: dropTarget1 }); expect(dropTarget1.events.drop).toBeDefined(); expect(dropTarget1.events.dragenter).toBeDefined(); expect(dropTarget1.events.dragover).toBeDefined(); expect(dropTarget1.events.dragexit).toBeDefined(); viewer.dropTarget = dropTarget2; expect(dropTarget1.events.drop).toBeUndefined(); expect(dropTarget1.events.dragenter).toBeUndefined(); expect(dropTarget1.events.dragover).toBeUndefined(); expect(dropTarget1.events.dragexit).toBeUndefined(); expect(dropTarget2.events.drop).toBeDefined(); expect(dropTarget2.events.dragenter).toBeDefined(); expect(dropTarget2.events.dragover).toBeDefined(); expect(dropTarget2.events.dragexit).toBeDefined(); }); it("can set proxy.", function() { const proxy = {}; viewer = createViewer_default(container); viewer.extend(import__787.viewerDragDropMixin, { proxy }); expect(viewer.proxy).toBe(proxy); }); it("throws with undefined viewer", function() { expect(function() { (0, import__787.viewerDragDropMixin)(void 0); }).toThrowDeveloperError(); }); it("throws with non-existant string container", function() { viewer = createViewer_default(container); expect(function() { viewer.extend(import__787.viewerDragDropMixin, { dropTarget: "doesNotExist" }); }).toThrowDeveloperError(); }); it("throws if dropTarget property already added by another mixin.", function() { viewer = createViewer_default(container); viewer.dropTarget = true; expect(function() { viewer.extend(import__787.viewerDragDropMixin); }).toThrowDeveloperError(); }); it("throws if dropEnabled property already added by another mixin.", function() { viewer = createViewer_default(container); viewer.dropEnabled = true; expect(function() { viewer.extend(import__787.viewerDragDropMixin); }).toThrowDeveloperError(); }); it("throws if dropError property already added by another mixin.", function() { viewer = createViewer_default(container); viewer.dropError = true; expect(function() { viewer.extend(import__787.viewerDragDropMixin); }).toThrowDeveloperError(); }); it("throws if clearOnDrop property already added by another mixin.", function() { viewer = createViewer_default(container); viewer.clearOnDrop = true; expect(function() { viewer.extend(import__787.viewerDragDropMixin); }).toThrowDeveloperError(); }); it("throws if flyToOnDrop property already added by another mixin.", function() { viewer = createViewer_default(container); viewer.flyToOnDrop = true; expect(function() { viewer.extend(import__787.viewerDragDropMixin); }).toThrowDeveloperError(); }); it("setting dropTarget to undefined throws exception", function() { viewer = createViewer_default(container); viewer.extend(import__787.viewerDragDropMixin); expect(function() { viewer.dropTarget = void 0; }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/widgets/Specs/Viewer/viewerPerformanceWatchdogMixinSpec.js var import__788 = __toESM(require_Cesium(), 1); describe( "Widgets/Viewer/viewerPerformanceWatchdogMixin", function() { let container; let viewer; beforeEach(function() { container = document.createElement("div"); container.id = "container"; container.style.display = "none"; document.body.appendChild(container); }); afterEach(function() { if (viewer && !viewer.isDestroyed()) { viewer = viewer.destroy(); } document.body.removeChild(container); }); it("mixin sets default values", function() { viewer = createViewer_default(container); viewer.extend(import__788.viewerPerformanceWatchdogMixin); expect(viewer.performanceWatchdog).toBeInstanceOf(import__788.PerformanceWatchdog); }); it("mixin sets option values", function() { viewer = createViewer_default(container); viewer.extend(import__788.viewerPerformanceWatchdogMixin, { lowFrameRateMessage: "Foo" }); expect(viewer.performanceWatchdog.viewModel.lowFrameRateMessage).toBe( "Foo" ); }); it("throws if not given a viewer", function() { expect(function() { (0, import__788.viewerPerformanceWatchdogMixin)(); }).toThrowDeveloperError(); }); }, "WebGL" ); // packages/widgets/Specs/VoxelInspector/VoxelInspectorSpec.js var import_engine56 = __toESM(require_Cesium(), 1); var import__789 = __toESM(require_Cesium(), 1); describe( "Widgets/VoxelInspector/VoxelInspector", function() { let scene2; beforeAll(function() { scene2 = createScene_default(); const ellipsoid = import_engine56.Ellipsoid.UNIT_SPHERE; const globe2 = new import_engine56.Globe(ellipsoid); scene2.globe = globe2; }); afterAll(function() { scene2.destroyForSpecs(); }); it("can create and destroy", function() { const container = document.createElement("div"); container.id = "testContainer"; document.body.appendChild(container); const widget = new import__789.VoxelInspector("testContainer", scene2); expect(widget.container).toBe(container); expect(widget.viewModel.scene).toBe(scene2); expect(widget.isDestroyed()).toEqual(false); widget.destroy(); expect(widget.isDestroyed()).toEqual(true); document.body.removeChild(container); }); it("constructor throws with no element", function() { expect(function() { return new import__789.VoxelInspector(); }).toThrowDeveloperError(); }); it("constructor throws with string element that does not exist", function() { expect(function() { return new import__789.VoxelInspector("does not exist", scene2); }).toThrowDeveloperError(); }); it("constructor throws with no scene", function() { expect(function() { return new import__789.VoxelInspector(document.body); }).toThrowDeveloperError(); }); }, "WebGL" ); // Specs/SpecList.js var VERSION = "1.117"; export { VERSION }; /*! Bundled license information: urijs/src/punycode.js: (*! https://mths.be/punycode v1.4.0 by @mathias *) urijs/src/IPv6.js: (*! * URI.js - Mutating URLs * IPv6 Support * * Version: 1.19.11 * * Author: Rodney Rehm * Web: http://medialize.github.io/URI.js/ * * Licensed under * MIT License http://www.opensource.org/licenses/mit-license * *) urijs/src/SecondLevelDomains.js: (*! * URI.js - Mutating URLs * Second Level Domain (SLD) Support * * Version: 1.19.11 * * Author: Rodney Rehm * Web: http://medialize.github.io/URI.js/ * * Licensed under * MIT License http://www.opensource.org/licenses/mit-license * *) urijs/src/URI.js: (*! * URI.js - Mutating URLs * * Version: 1.19.11 * * Author: Rodney Rehm * Web: http://medialize.github.io/URI.js/ * * Licensed under * MIT License http://www.opensource.org/licenses/mit-license * *) */ //# sourceMappingURL=SpecList.js.map